You probably do not have any de_DE
locale available.
You can view a list of available locales with the locale -a
command.
For example, on my machine:
$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
it_CH.utf8
it_IT.utf8
POSIX
Note that if you want to set the locale to it_IT
you must also specify the .utf8
:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'it_IT') # error!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/locale.py", line 539, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, 'it_IT.utf8')
'it_IT.utf8'
To install a new locale use:
sudo apt-get install language-pack-id
where id
is the language code (taken from here)
After you have installed the locale you should follow Julien Palard advice and reconfigure the locales with:
sudo dpkg-reconfigure locales
It means to group by the first column regardless of what it's called. You can do the same with ORDER BY
.
Take a look at the documentation for HttpServletRequest
.
In order to build the URL in your example you will need to use:
getScheme()
getServerName()
getServerPort()
getContextPath()
Here is a method that will return your example:
public static String getURLWithContextPath(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
$_SERVER["PHP_SELF"];
will give you the current filename and its path, but basename(__FILE__)
should give you the filename that it is called from.
So
if(basename(__FILE__) == 'file_name.php') {
//Hide
} else {
//show
}
should do it.
While Niemeyer's answer is a more correct answer to the question, you could also do the following:
<div>
<input data-bind="value: VMA.name" />
</div>
<div>
<input data-bind="value: VMB.name" />
</div>
<script type="text/javascript">
var viewModels = {
VMA: {name: ko.observable("Bob")},
VMB: {name: ko.observable("Ted")}
};
ko.applyBindings(viewModels);
</script>
This means you don't have to specify the DOM element, and you can even bind multiple models to the same element, like this:
<div>
<input data-bind="value: VMA.name() + ' and ' + VMB.name()" />
</div>
Late answer but I'll add some additional insight to what has been shared, namely that there are several types of "parameters" to a request, and you should take this into account.
Now let's look at the different places where these parameters could go.
Generally you want State to be set in headers or cookies, depending on what type of state information it is. I think we can all agree on this. Use custom http headers (X-My-Header) if you need to.
Similarly, Content only has one place to belong, which is in the request body, either as query strings or as http multipart and/or JSON content. This is consistent with what you receive from the server when it sends you content. So you shouldn't be rude and do it differently.
Locators such as "id=5" or "action=refresh" or "page=2" would make sense to have as a URL path, such as mysite.com/article/5/page=2
where partly you know what each part is supposed to mean (the basics such as article and 5 obviously mean get me the data of type article with id 5) and additional parameters are specified as part of the URI. They can be in the form of page=2
, or page/2
if you know that after a certain point in the URI the "folders" are paired key-values.
Filters always go in the query string, because while they are a part of finding the right data, they are only there to return a subset or modification of what the Locators return alone. The search in mysite.com/article/?query=Obama
(subset) is a filter, and so is /article/5?order=backwards
(modification). Think about what it does, not just what it's called!
If "view" determines output format, then it is a filter (mysite.com/article/5?view=pdf
) because it returns a modification of the found resource rather than homing in on which resource we want. If it instead decides which specific part of the article we get to see (mysite.com/article/5/view=summary
) then it is a locator.
Remember, narrowing down a set of resources is filtering. Locating something specific within a resource is locating... duh. Subset filtering may return any number of results (even 0). Locating will always find that specific instance of something (if it exists). Modification filtering will return the same data as the locator, except modified (if such a modification is allowed).
Hope this helped give people some eureka moments if they've been lost about where to put stuff!
To access the tomcat manager from different machine you have to follow bellow steps:
1. Update conf/tomcat-users.xml file with user and some roles:
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".
Here tomcat user and password is : admin
2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):
Default configuration:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
<Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>
Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .
2.a : Allow specefic IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />
Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address
2.b : Allow all IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow=".*" />
Here using allow=".*" you are allowing all IP.
Thanks :)
There are two branches lets say
Being in branch A you can type
git diff --color B
then this will give you a output of
The important point about this is
Text in green is inside present in Branch A
Text in red is present in Branch B
use a css3 class "spinner". It's more beautiful and you don't need .gif
.spinner {
position: absolute;
left: 50%;
top: 50%;
height:60px;
width:60px;
margin:0px auto;
-webkit-animation: rotation .6s infinite linear;
-moz-animation: rotation .6s infinite linear;
-o-animation: rotation .6s infinite linear;
animation: rotation .6s infinite linear;
border-left:6px solid rgba(0,174,239,.15);
border-right:6px solid rgba(0,174,239,.15);
border-bottom:6px solid rgba(0,174,239,.15);
border-top:6px solid rgba(0,174,239,.8);
border-radius:100%;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(359deg);}
}
Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit
You can find a lot of css spinners like this here : http://cssload.net/en/spinners/
Instead of getopt()
, you may also consider using argp_parse()
(an alternative interface to the same library).
From libc manual:
getopt
is more standard (the short-option only version of it is a part of the POSIX standard), but usingargp_parse
is often easier, both for very simple and very complex option structures, because it does more of the dirty work for you.
But I was always happy with the standard getopt
.
N.B. GNU getopt
with getopt_long
is GNU LGPL.
I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).
The easiest solution that I have found is to do the following:
In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.
Example:
'use strict';
//my data variable that I need access to.
var data = null;
angular.module('sample', [])
Then in your controller:
.controller('SampleApp', function ($scope, $location) {
$scope.availableList = [];
$scope.init = function () {
$scope.availableList = data;
}
Finally, you have to init everything (order matters):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="/path/to/your/angular/js/sample.js"></script>
<script type="text/javascript">
data = <?= json_encode($cproducts); ?>
</script>
Finally initialize your controller and init function.
<div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">
By doing this you will now have access to whatever data you stuffed into the global variable.
I would strongly recommend not to use synchronous (blocking) functions, as they hold other concurrent operations. Instead, use asynchronous fs.promises:
const fs = require('fs').promises
const setValue = (fn, value) =>
fs.readFile(fn)
.then(body => JSON.parse(body))
.then(json => {
// manipulate your data here
json.value = value
return json
})
.then(json => JSON.stringify(json))
.then(body => fs.writeFile(fn, body))
.catch(error => console.warn(error))
Remeber that setValue
returns a pending promise, you'll need to use .then function or, within async functions, the await operator.
// await operator
await setValue('temp.json', 1) // save "value": 1
await setValue('temp.json', 2) // then "value": 2
await setValue('temp.json', 3) // then "value": 3
// then-sequence
setValue('temp.json', 1) // save "value": 1
.then(() => setValue('temp.json', 2)) // then save "value": 2
.then(() => setValue('temp.json', 3)) // then save "value": 3
If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers
parameter.
Here is an example with a non-empty body and headers:
import requests
import json
url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(body), headers=headers)
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object item in row.ItemArray)
{
// read item
}
}
}
Or, if you need the column info:
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
object item = row[column];
// read column and item
}
}
}
There can be several things which cause this.
targetSdkVersion
and compileSdkVersion
.targetSdkVersion
and compileSdkVersion
are same.Other solutions can be:
File
? Invalidate Caches / Restarts...
Build
? Clean Project
Build
? Rebuild Project
Build
? Make Project
[this process may take some time]Top answers have several disadvantages: you have to add new layout paths, AS places new resources to res\layouts
folder instead of res\values
.
Combining several answers I wrote similar:
sourceSets {
main {
res.srcDirs =
[
'src/main/res',
file("src/main/res/layouts/").listFiles(),
'src/main/res/layouts'
]
}
}
I made folders with this article: http://alexzh.com/tutorials/how-to-store-layouts-in-different-folders-in-android-project/. In order to create subfolders you should use this menu: New > Folder > Res Folder.
UPDATE
After a couple of weeks I found that changes in resources are not noticed by Android Studio. So, some weird bugs appear. For instance, layouts continue to show old sizes, margins. Sometimes AS doesn't find new XML-files (especially during run-time). Sometimes it mixes view id
s (references to another XML-file). It's often required to press Build > Clean Project
or Build > Rebuild Project
. Read Rebuild required after changing xml layout files in Android Studio.
There is also one ugly but working way. Decompile FirebaseMessagingService.class and modify it's behavior. Then just put the class to the right package in yout app and dex use it instead of the class in the messaging lib itself. It is quite easy and working.
There is method:
private void zzo(Intent intent) {
Bundle bundle = intent.getExtras();
bundle.remove("android.support.content.wakelockid");
if (zza.zzac(bundle)) { // true if msg is notification sent from FirebaseConsole
if (!zza.zzdc((Context)this)) { // true if app is on foreground
zza.zzer((Context)this).zzas(bundle); // create notification
return;
}
// parse notification data to allow use it in onMessageReceived whe app is on foreground
if (FirebaseMessagingService.zzav(bundle)) {
zzb.zzo((Context)this, intent);
}
}
this.onMessageReceived(new RemoteMessage(bundle));
}
This code is from version 9.4.0, method will have different names in different version because of obfuscation.
UPDATE t1
LEFT JOIN
t2
ON t2.id = t1.id
SET t1.col1 = newvalue
WHERE t2.id IS NULL
Note that for a SELECT
it would be more efficient to use NOT IN
/ NOT EXISTS
syntax:
SELECT t1.*
FROM t1
WHERE t1.id NOT IN
(
SELECT id
FROM t2
)
See the article in my blog for performance details:
LEFT JOIN
compared to NOT IN
Unfortunately, MySQL
does not allow using the target table in a subquery in an UPDATE
statement, that's why you'll need to stick to less efficient LEFT JOIN
syntax.
It might be safer to exit the trigger when there is nothing to do. Checking the nested level or altering the database by switching off RECURSIVE can be prone to issues.
Ms sql provides a simple way, in a trigger, to see if specific columns have been updated. Use the UPDATE() method to see if certain columns have been updated such as UPDATE(part_description_upper).
IF UPDATE(part_description_upper)
return
you can simply use JSON.stringify(options) convert JSON object to string before submit, then warning dismiss and works fine
Mobile number Validation using Java Script, This link will provide demo and more information.
function isNumber(evt) {_x000D_
evt = (evt) ? evt : window.event;_x000D_
var charCode = (evt.which) ? evt.which : evt.keyCode;_x000D_
if (charCode > 31 && (charCode < 48 || charCode > 57)) {_x000D_
alert("Please enter only Numbers.");_x000D_
return false;_x000D_
}_x000D_
_x000D_
return true;_x000D_
}_x000D_
_x000D_
function ValidateNo() {_x000D_
var phoneNo = document.getElementById('txtPhoneNo');_x000D_
_x000D_
if (phoneNo.value == "" || phoneNo.value == null) {_x000D_
alert("Please enter your Mobile No.");_x000D_
return false;_x000D_
}_x000D_
if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {_x000D_
alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");_x000D_
return false;_x000D_
}_x000D_
_x000D_
alert("Success ");_x000D_
return true;_x000D_
}
_x000D_
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />_x000D_
<input type="button" value="Submit" onclick="ValidateNo();">
_x000D_
LinearLayout is a subclass of ViewGroup, which has a method called addView. The addView method should be what you are after.
Keep in mind that gdb is a powerful command -capable of low level instructions- so is tied to assembly concepts.
What you are looking for is called de instruction pointer, i.e:
The instruction pointer register points to the memory address which the processor will next attempt to execute. The instruction pointer is called ip in 16-bit mode, eip in 32-bit mode,and rip in 64-bit mode.
more detail here
all registers available on gdb execution can be shown with:
(gdb) info registers
with it you can find which mode your program is running (looking which of these registers exist)
then (here using most common register rip nowadays, replace with eip or very rarely ip if needed):
(gdb)info line *$rip
will show you line number and file source
(gdb) list *$rip
will show you that line with a few before and after
but probably
(gdb) frame
should be enough in many cases.
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
If X inherits from Y, that has two somewhat orthogonal effects:
Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).
To list all the process running on port 8080 do the following.
netstat -ano | find "8080"
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 10612
TCP [::]:8080 [::]:0 LISTENING 10612
Then to kill the process run the following command
taskkill /F /PID 10612
its even simpler than that. Using HTML you can just add this metatag to your page (first thing on the page):
<meta http-equiv="X-UA-Compatible" content="IE=7" />
If you wanted to do it using.net, you just have to send your http request with that meta information in the header. This would require a page refresh to work though.
Also, you can look at a similar question here: Compatibility Mode in IE8 using VBScript
Threaded:
/// <summary>
/// Usage: var timer = SetIntervalThread(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be disposed.</returns>
public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
{
TimerStateManager state = new TimerStateManager();
System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
state.TimerObject = tmr;
return tmr;
}
Regular
/// <summary>
/// Usage: var timer = SetInterval(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be stopped and disposed.</returns>
public static System.Timers.Timer SetInterval(Action Act, int Interval)
{
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Elapsed += (sender, args) => Act();
tmr.AutoReset = true;
tmr.Interval = Interval;
tmr.Start();
return tmr;
}
Here's my PowerShell Send-MailMessage sample for Gmail...
Tested and working solution:
$EmailFrom = "[email protected]"
$EmailTo = "[email protected]"
$Subject = "Notification from XYZ"
$Body = "this is a notification from XYZ Notifications.."
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
Just change $EmailTo, and username/password in $SMTPClient.Credentials... Do not include @gmail.com in your username...
In VB.Net it would be
Dim maxAge As Integer = context.Persons.Max(Function(p) p.Age)
I had to encounter a situation as such, and simply, the
str_replace("\/","/",$variable)
did work for me.
For windows, you need to download the latest version of the open SSL binaries at this time is:
openssl-1.0.2k-x64_86-win64.zip
this problem happened to me when I tried to run MongoDB bin in windows 10
source to download: https://indy.fulgan.com/SSL/
You can try as follows:
//------ js/functions.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import completely:
//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Normally we use ./fileName.js
for importing own js file/module
and fileName.js
is used for importing package/library
module
When you will include the main.js file to your webpage you must set the type="module" attribute as follows:
<script type="module" src="js/main.js"></script>
For more details please check ES6 modules
We are currently recommending AS 3.3 for exercises.
These settings will work in the current 3.3 beta version with two small changes to your project:
In build.gradle (Project), change gradle version to 3.3.0-rc02
In menu go to File -> Project Structure. There you can change the gradle version to 4.10.0
Use:
php -i
command or add:
phpinfo();
to get the location of configuration file.
Update these variables according to your need and server
max_input_time = 24000
max_execution_time = 24000
upload_max_filesize = 12000M
post_max_size = 24000M
memory_limit = 12000M
On Linux you will need to restart nginx / apache and phpfpm service so the new ini settings are loaded. On xampp, ammps you can restart these from control panel that comes with such applications.
Set the JAVA_HOME variable as noted above, but also set the JRE_HOME variable to the Java Runtime Environment folder (example: C:\Program Files (x86)\Java\jdk1.6.0_23\jre )
To set the windows environment variable, right click on My Computer and select "Properties" and choose the "Advanced" tab on older windows versions, or click the "Advanced system settings" link on new versions of windows. Click the "Environment Variables" button and, in the System Variables section, click the "New" button and add the above variable names and enter the appropriate filesystem paths as the values.
After you've installed Netbeans, check the following:
Open C:\Program Files (x86)\NetBeans 6.0.1\etc\netbeans.conf
Change this value to the location of your JDK folder if it isn't set correctly already:
netbeans_jdkhome="C:\Program Files (x86)\Java\jdk1.6.0_23"
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
Instead of using JTextArea.setText(String text)
, use JTextArea.append(String text)
.
Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.
This will add text on to the end of your JTextArea
.
Another option would be to use getText()
to get the text from the JTextArea
, then manipulate the String (add or remove or change the String), then use setText(String text)
to set the text of the JTextArea
to be the new String.
If you use eclipse, you can generate equals()
and hashCode()
using:
Source -> Generate hashCode() and equals().
Using this function you can decide which fields you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.
In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date
. It is basically backed by the Epoch time in flavor of a long
, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.
In SQL side, there are several standard date and time types, DATE
, TIME
and TIMESTAMP
(at some DB's also called DATETIME
), which are represented in JDBC as java.sql.Date
, java.sql.Time
and java.sql.Timestamp
, all subclasses of java.util.Date
. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.
In contrary to java.util.Date
, the java.sql.Date
contains only information about the date part (year, month, day). The Time
contains only information about the time part (hours, minutes, seconds) and the Timestamp
contains information about the both parts, like as java.util.Date
does.
The normal practice to store a timestamp in the DB (thus, java.util.Date
in Java side and java.sql.Timestamp
in JDBC side) is to use PreparedStatement#setTimestamp()
.
java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);
The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp()
.
Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.
I had a similar issue while doing AOT angular build. Following commands helped me.
npm install -g increase-memory-limit
increase-memory-limit
Source: https://geeklearning.io/angular-aot-webpack-memory-trick/
The problem is that you set the first image through 'src' attribute and on hover added to the image a background-image. try this:
in html use:
<img id="Library">
then in css:
#Library {
height: 70px;
width: 120px;
background-image: url('LibraryTransparent.png');
}
#Library:hover {
background-image: url('LibraryHoverTrans.png');
}
You can also define a variable without the EnvInject Plugin within your Groovy System Script:
import hudson.model.*
def build = Thread.currentThread().executable
def pa = new ParametersAction([
new StringParameterValue("FOO", "BAR")
])
build.addAction(pa)
Then you can access this variable in the next build step which (for example) is an windows batch command:
@echo off
Setlocal EnableDelayedExpansion
echo FOO=!FOO!
This echo will show you "FOO=BAR".
Regards
The google play services requires all its dependencies to have the same version. But if you look at your dependencies:
compile 'com.google.firebase:firebase-messaging:10.0.1'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'
There is one that has a different version.
It can be solved by changing the version to (in this case) 11.0.4
.
This applies to both Firebase and Google Play Services - both have to have matching versions that also correspond with each other. If a Firebase dependency is 10.0.1
and a Google Play Services dependency is 11.0.4
, the same error will occur.
Note that in some cases, there can be a library that has a different version of a library (e.g. library x
uses play-services-games:10.0.1
while you use 11.0.4
for the dependencies in your app)
This answer does NOT cover the newer versions where versions are individual. Update com.google.gms:google-services:4.1.0
and check mvnrepository (or some other maven/gradle artifact search tool) to find the newest versions.
Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.
var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"
Here's a DEMO on how this regex works with test() and match().
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
You could do below:
select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20,
iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30,
iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40,
50 ) ) ) as commission
from table
You should use BFG Repo-Cleaner.
According to the website:
The BFG is a simpler, faster alternative to git-filter-branch for cleansing bad data out of your Git repository history:
- Removing Crazy Big Files
- Removing Passwords, Credentials & other Private data
The classic procedure for reducing the size of a repository would be:
git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --strip-biggest-blobs 500 some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
Just pass the object as is. Note you can create the object as follows
var data0 = {numberId: "1", companyId : "531"};
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: dataO,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('In Ajax');
}
});
UPDATE seems an odd issue with the serializer, maybe it is expecting a string, out of interest can you try the following.
data: "{'numberId':'1', 'companyId ':'531'}",
You can set the SelectedValue
to the value you want to select. If you already have selected item then you should clear the selection otherwise you would get "Cannot have multiple items selected in a DropDownList" error.
dropdownlist.ClearSelection();
dropdownlist.SelectedValue = value;
You can also use ListItemCollection.FindByText or ListItemCollection.FindByValue
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Use the FindByValue method to search the collection for a ListItem with a Value property that contains value specified by the value parameter. This method performs a case-sensitive and culture-insensitive comparison. This method does not do partial searches or wildcard searches. If an item is not found in the collection using this criteria, null is returned, MSDN.
If you expect that you may be looking for text/value that wont be present in DropDownList
ListItem collection then you must check if you get the ListItem
object or null
from FindByText
or FindByValue
before you access Selected property. If you try to access Selected when null is returned then you will get NullReferenceException.
ListItem listItem = dropdownlist.Items.FindByValue(value);
if(listItem != null)
{
dropdownlist.ClearSelection();
listItem.Selected = true;
}
For an Omnibus install, it is a little different.
The correct place in an Omnibus install is:
/etc/gitlab/gitlab.rb
external_url 'http://gitlab.example.com'
Finally, you'll need to execute sudo gitlab-ctl reconfigure
and sudo gitlab-ctl restart
so the changes apply.
I was making changes in the wrong places and they were getting blown away.
The incorrect paths are:
/opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
/var/opt/gitlab/.gitconfig
/var/opt/gitlab/nginx/conf/gitlab-http.conf
Pay attention to those warnings that read:
# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.
I couldn't get it to accept my Gradle JVM selection until I deleted a broken JDK
Th window below is from File -> Other Settings -> Structure For New Projects...
I had a red 1.8 JDK SDK entry here, once I deleted that Gradle JVM error below disappeared and I could move on to the next step
Steps to debug:-
In case you face any issue in kubernetes, first step is to check if kubernetes self applications are running fine or not.
Command to check:- kubectl get pods -n kube-system
If you see any pod is crashing, check it's logs
if getting NotReady
state error, verify network pod logs.
if not able to resolve with above, follow below steps:-
kubectl get nodes
# Check which node is not in ready state
kubectl describe node nodename
#nodename which is not in readystate
ssh to that node
execute systemctl status kubelet
# Make sure kubelet is running
systemctl status docker
# Make sure docker service is running
journalctl -u kubelet
# To Check logs in depth
Most probably you will get to know about error here, After fixing it reset kubelet with below commands:-
systemctl daemon-reload
systemctl restart kubelet
In case you still didn't get the root cause, check below things:-
Make sure your node has enough space and memory. Check for /var
directory space especially.
command to check: -df
-kh
, free -m
Verify cpu utilization with top command. and make sure any process is not taking an unexpected memory.
How we get right real dimensions without a blink real image:
(function( $ ){
$.fn.getDimensions=function(){
alert("First example:This works only for HTML code without CSS width/height definition.");
w=$(this, 'img')[0].width;
h=$(this, 'img')[0].height;
alert("This is a width/height on your monitor: " + $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
//This is bad practice - it shows on your monitor
$(this, 'img')[0].removeAttribute( "width" );
$(this, 'img')[0].removeAttribute( "height" );
alert("This is a bad effect of view after attributes removing, but we get right dimensions: "+ $(this, 'img')[0].width+"/"+$(this, 'img')[0].height);
//I'am going to repare it
$(this, 'img')[0].width=w;
$(this, 'img')[0].height=h;
//This is a good practice - it doesn't show on your monitor
ku=$(this, 'img').clone(); //We will work with a clone
ku.attr( "id","mnbv1lk87jhy0utrd" );//Markup clone for a final removing
ku[0].removeAttribute( "width" );
ku[0].removeAttribute( "height" );
//Now we still get 0
alert("There are still 0 before a clone appending to document: "+ $(ku)[0].width+"/"+$(ku)[0].height);
//Hide a clone
ku.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});
//A clone appending
$(document.body).append (ku[0]);
alert("We get right dimensions: "+ $(ku)[0].width+"/"+$(ku)[0].height);
//Remove a clone
$("#mnbv1lk87jhy0utrd").remove();
//But a next resolution is the best of all. It works in case of CSS definition of dimensions as well.
alert("But if you want to read real dimensions for image with CSS class definition outside of img element, you can't do it with a clone of image. Clone method is working with CSS dimensions, a clone has dimensions as well as in CSS class. That's why you have to work with a new img element.");
imgcopy=$('<img src="'+ $(this, 'img').attr('src') +'" />');//new object
imgcopy.attr( "id","mnbv1lk87jhy0aaa" );//Markup for a final removing
imgcopy.css({"visibility" : "hidden",'position':'absolute','left':'-9999px'});//hide copy
$(document.body).append (imgcopy);//append to document
alert("We get right dimensions: "+ imgcopy.width()+"/"+imgcopy.height());
$("#mnbv1lk87jhy0aaa").remove();
}
})( jQuery );
$(document).ready(function(){
$("img.toreaddimensions").click(function(){$(this).getDimensions();});
});
It works with <img class="toreaddimensions"...
SOLVED HOW TO USE A COMPONENT DECLARED IN A MODULE IN OTHER MODULE.
Based on Royi Namir explanation (Thank you so much). There is a missing part to reuse a component declared in a Module in any other module while lazy loading is used.
1st: Export the component in the module which contains it:
@NgModule({
declarations: [TaskCardComponent],
imports: [MdCardModule],
exports: [TaskCardComponent] <== this line
})
export class TaskModule{}
2nd: In the module where you want to use TaskCardComponent:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MdCardModule } from '@angular2-material/card';
@NgModule({
imports: [
CommonModule,
MdCardModule
],
providers: [],
exports:[ MdCardModule ] <== this line
})
export class TaskModule{}
Like this the second module imports the first module which imports and exports the component.
When we import the module in the second module we need to export it again. Now we can use the first component in the second module.
A better way to add the multiple classes separated by spaces in a string is using the Spread_syntax with the split:
element.classList.add(...classesStr.split(" "));
It's quite easy. Just write this, for example:
npm install -g [email protected]
Or:
npm install -g npm@latest // For the last stable version
npm install -g npm@next // For the most recent release
Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.
span
is an inline element that doesn't support vertical margins. Put the margin on the outer div
instead.
You can't close an alert box with Javascript.
You could, however, use a window instead:
var w = window.open('','','width=100,height=100')
w.document.write('Message')
w.focus()
setTimeout(function() {w.close();}, 5000)
Here is another simple answer, but without using classes.
from tkinter import *
def raise_frame(frame):
frame.tkraise()
root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
frame.grid(row=0, column=0, sticky='news')
Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()
Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')
Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()
Using TSQL/MSSQL
This query will get you: table name, column name, data type, data type length, and allowable nulls
SELECT TABLE_NAME,COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'your_table_name'
The only thing that needs to be changed is your_table_name.
Some options:
You can use the Execute Package Utility to change your datasource, before running the package.
You can run your package using DTEXEC, and change your connection by passing in a /CONNECTION parameter. Probably save it as a batch so next time you don't need to type the whole thing and just change the datasource as required.
You can use the SSIS XML package configuration file. Here is a walk through.
You can save your configrations in a database table.
SI
= Source Index
DI
= Destination Index
As others have indicated, they have special uses with the string instructions. For real mode programming, the ES
segment register must be used with DI
and DS
with SI
as in
movsb es:di, ds:si
SI and DI can also be used as general purpose index registers. For example, the C
source code
srcp [srcidx++] = argv [j];
compiles into
8B550C mov edx,[ebp+0C]
8B0C9A mov ecx,[edx+4*ebx]
894CBDAC mov [ebp+4*edi-54],ecx
47 inc edi
where ebp+12
contains argv
, ebx
is j
, and edi
has srcidx
. Notice the third instruction uses edi
mulitplied by 4 and adds ebp
offset by 0x54 (the location of srcp
); brackets around the address indicate indirection.
AX
= accumulator
DX
= double word accumulator
CX
= counter
BX
= base register
They look like general purpose registers, but there are a number of instructions which (unexpectedly?) use one of them—but which one?—implicitly.
-Download iPhone configuration utility tool
-open it-> In Library section:- select provisioning profile(Left side of tool)
-select provisioning profile(which you want to delete) using back space delete it.
You should wrap your elements inside a container, then use new CSS3 features like css grid, free course, and then use grid-gap:value
that was created for your specific problem
span{_x000D_
border:1px solid red;_x000D_
}_x000D_
.inRow{_x000D_
display:grid;_x000D_
grid-template-columns:repeat(auto-fill,auto);_x000D_
grid-gap:10px /*This add space between elements, only works on grid items*/_x000D_
}_x000D_
.inColumn{_x000D_
display:grid;_x000D_
grid-template-rows:repeat(auto-fill,auto);_x000D_
grid-gap:15px;_x000D_
}
_x000D_
<div class="inrow">_x000D_
<span>1</span>_x000D_
<span>2</span>_x000D_
<span>3</span>_x000D_
</div>_x000D_
<div class="inColumn">_x000D_
<span>4</span>_x000D_
<span>5</span>_x000D_
<span>6</span>_x000D_
</div>
_x000D_
Kinda late.But it just takes a bit of math.
.content {
margin-top: 50px;
background: #777;
padding: 30px;
padding-bottom: 0;
font-size: 11px;
border: 1px dotted #222;
}
.bottom-content {
background: #999;
width: 100%; /* you need this for it to work */
margin-left: -30px; /* will touch very left side */
padding-right: 60px; /* will touch very right side */
}
<div class='content'>
<p>A paragraph</p>
<p>Another paragraph.</p>
<p>No more content</p>
<div class='bottom-content'>
I want this div to ignore padding.
</div>
I don't have Windows so I didn't test this in IE.
fiddle: fiddle example..
You have an extra -c
you need to get rid of:
psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"
The various provided answers are wrong for numerous reasons, primarily from misunderstanding what a palindrome is. The majority only properly identify a subset of palindromes.
From Merriam-Webster
A word, verse, or sentence (such as "Able was I ere I saw Elba")
And from Wordnik
A word, phrase, verse, or sentence that reads the same backward or forward. For example: A man, a plan, a canal, Panama!
Consider non-trivial palindromes such as "Malayalam" (it's a proper language, so naming rules apply, and it should be capitalized), or palindromic sentences such as "Was it a car or a cat I saw?" or "No 'X' in Nixon".
These are recognized palindromes in any literature.
I'm lifting the thorough solution from a library providing this kind of stuff that I'm the primary author of, so the solution works for both String
and ReadOnlySpan<Char>
because that's a requirement I've imposed on the library. The solution for purely String
will be easy to determine from this, however.
public static Boolean IsPalindrome(this String @string) =>
!(@string is null) && @string.AsSpan().IsPalindrome();
public static Boolean IsPalindrome(this ReadOnlySpan<Char> span) {
// First we need to build the string without any punctuation or whitespace or any other
// unrelated-to-reading characters.
StringBuilder builder = new StringBuilder(span.Length);
foreach (Char s in span) {
if (!(s.IsControl()
|| s.IsPunctuation()
|| s.IsSeparator()
|| s.IsWhiteSpace()) {
_ = builder.Append(s);
}
}
String prepped = builder.ToString();
String reversed = prepped.Reverse().Join();
// Now actually check it's a palindrome
return String.Equals(prepped, reversed, StringComparison.CurrentCultureIgnoreCase);
}
You're going to want variants of this that accept a CultureInfo
parameter as well, when you're testing a specific language rather than your own language, by instead calling .ToUpper(cultureInfo)
on prepped
.
And here's proof from the projects unit tests that it works.
Find the row, then
var row = $('#yourTable');
the value you want to select
var theValue = "5";
row.find("select:eq(2)").find("option[value="+theValue+']').attr('selected','selected');
Change detection is not triggered when you change a property of an object (including nested object). One solution would be to reassign a new object reference using 'lodash' clone() function.
import * as _ from 'lodash';
this.foo = _.clone(this.foo);
You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:
#!/bin/bash
sudo -u username command1
command2
sudo -u username command3
command4
When running as root, sudo doesn't ask for a password.
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
The basic difference, is that provider allows to set primitive (non-objects), array, or callback function values into the factory declared variable, and thus if returning an object it has to be explicitly declared and returned.
On the other hand a service can only be used to set the service declared variable to an object, thus we can avoid the explicit creation and returning of the objects, while on the other hand it allows usage of the this keyword.
Or in short words "provider is a more generic form while service is limited to objects only".
In case you are uploading an sql file on cpanel, then try and replace root with your cpanel username in your sql file.
in the case above you could write
CREATE DEFINER = control_panel_username
@localhost
FUNCTION fnc_calcWalkedDistance
then upload the file. Hope it helps
You need to change the seed.
int main() {
srand(time(NULL));
cout << (rand() % 101);
return 0;
}
the srand
seeding thing is true also for a c
language code.
See also: http://xkcd.com/221/
Dictionary is a key value pair. Catch Key by
dic["cat"]
and assign its value like
dic["cat"] = 5
In Bootstrap 3
All textual < input >, < textarea >, and < select > elements with .form-control are set to width: 100%; by default.
http://getbootstrap.com/css/#forms-example
It seems, in some cases, we have to set manually the max width we want for the inputs.
Anyway, your example works. Just check it with a large screen, so you can see the name and email fields are getting the 2/12 of the with (col-lg-1 + col-lg-1 and you have 12 columns). But if you have a smaller screen (just resize your browser), the inputs will expand until the end of the row.
yum install python34-pip
pip3.4 install foo
You will likely need the EPEL repositories installed:
yum install -y epel-release
Add up to Dmitry's answer, if you don't want to handle unique key IDs manually, you can use React.Children.toArray
as proposed in the React documentation
React.Children.toArray
Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
Note:
React.Children.toArray()
changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.
<div>
<ul>
{
React.Children.toArray(
this.state.data.map((item, i) => <li>Test</li>)
)
}
</ul>
</div>
You can use JsonWriteNullProperties
for older versions of Jackson.
For Jackson 1.9+, use JsonSerialize.include
.
E = exponent expression, simply means power(10, n) or 10 ^ n
F = fraction expression, default 6 digits precision
G = gerneral expression, somehow smart to show the number in a concise way (but really?)
See the below example,
The code
void main(int argc, char* argv[])
{
double a = 4.5;
printf("=>>>> below is the example for printf 4.5\n");
printf("%%e %e\n",a);
printf("%%f %f\n",a);
printf("%%g %g\n",a);
printf("%%E %E\n",a);
printf("%%F %F\n",a);
printf("%%G %G\n",a);
double b = 1.79e308;
printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
printf("%%e %e\n",b);
printf("%%f %f\n",b);
printf("%%g %g\n",b);
printf("%%E %E\n",b);
printf("%%F %F\n",b);
printf("%%G %G\n",b);
double d = 2.25074e-308;
printf("=>>>> below is the example for printf 2.25074*10^-308\n");
printf("%%e %e\n",d);
printf("%%f %f\n",d);
printf("%%g %g\n",d);
printf("%%E %E\n",d);
printf("%%F %F\n",d);
printf("%%G %G\n",d);
}
The output
=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the exbmple for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308
I ran into this problem when trying to pull a third party package which was apparently including windows.h somewhere in it's mess of headers. Defining _WINSOCKAPI_
at the project level was much easier (not to mention more maintainable) than wading through their soup and fixing the problematic include.
The Mozilla.org FAQ on debugging Mozilla on Windows is of interest here.
In short, the Visual Studio debugger can be invoked on a program from the command line, allowing one to specify the command line arguments when invoking a command line program, directly on the command line.
This looks like the following for Visual Studio 8 or 9 (Visual Studio 2005 or Visual Studio 2008, respectively)
devenv /debugexe 'program name' 'program arguments'
It is also possible to have an explorer action to start a program in the Visual Studio debugger.
I've fixed the typescript version. For javascript, just remove type definitions.
_getFormDataKey(key0: any, key1: any): string {
return !key0 ? key1 : `${key0}[${key1}]`;
}
_convertModelToFormData(model: any, key: string, frmData?: FormData): FormData {
let formData = frmData || new FormData();
if (!model) return formData;
if (model instanceof Date) {
formData.append(key, model.toISOString());
} else if (model instanceof Array) {
model.forEach((element: any, i: number) => {
this._convertModelToFormData(element, this._getFormDataKey(key, i), formData);
});
} else if (typeof model === 'object' && !(model instanceof File)) {
for (let propertyName in model) {
if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
this._convertModelToFormData(model[propertyName], this._getFormDataKey(key, propertyName), formData);
}
} else {
formData.append(key, model);
}
return formData;
}
XPath has a contains-token function, specifically designed for this situation:
//div[contains-token(@class, 'Test')]
It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.
Within the inner class itself, you can use OuterClass.this
. This expression, which allows to refer to any lexically enclosing instance, is described in the JLS as Qualified this
.
I don't think there's a way to get the instance from outside the code of the inner class though. Of course, you can always introduce your own property:
public OuterClass getOuter() {
return OuterClass.this;
}
EDIT: By experimentation, it looks like the field holding the reference to the outer class has package level access - at least with the JDK I'm using.
EDIT: The name used (this$0
) is actually valid in Java, although the JLS discourages its use:
The
$
character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.
It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries) . So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.
Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.
For example:
static const struct x EmptyStruct;
Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.
Then, each time round the loop you can write:
myStructVariable = EmptyStruct;
I have found a solution to my problems that it's pretty same as yours.
First of all, I only have a LinearLayout with 2 elements, an ImageView and a LinearLayout wich contains 2 EditText and one Button, so I needed to keep them separate in full screen without keyboard, and when the keyboard appears they should look closer.
So I added the view between them with the height attribute in 0dp and weight 1, that let me keep my views separate one form each other. and when the keyboard appers, as they don't have a fix height, they just resize and keep the aspect.
Voila! The layout resize and the distance between my views is the same when the keyboard is or not present.
Had the same problem after merging some new code into a vs2019 project.
Restarted VS, unloaded and reloaded projects, ensured all projects in solution had same ToolsVersion=
and TargetFrameworkVersion
. None of this helped.
I had a case of project Substrate, failing to find namespace Skin (in project Skin).
Finally I opened up Substrate.csproj and checked all the ProjectReference Include
entries. The others were there, but no reference to Skin, even though Skin did show up in the check box of the little project dependencies dialog. So the project dependencies dialog took the check box for Skin (and saved it somewhere) but did not alter Substrate.csproj. I then added the ProjectReference Include
manually, ensuring I had the correct path and GUID for the skin project.
<ProjectReference Include="..\Skin\Skin.csproj"> <Project>{1ad4b5d7-5014-4f5f-983e-2c59ac0e0028}</Project> <Name>Skin</Name> </ProjectReference>
I then saved the Substrate.csproj and the problem was solved. So as others have said this is a problem with VS tooling
None of the answers include the overhead size and the metadata sizes of tables.
Here is a more accurate estimation of the "disk space" allocated by a database.
SELECT ROUND((SUM(data_length+index_length+data_free) + (COUNT(*) * 300 * 1024))/1048576+150, 2) AS MegaBytes FROM information_schema.TABLES WHERE table_schema = 'DATABASE-NAME'
To stage all manually deleted files you can use:
git rm $(git ls-files --deleted)
To add an alias to this command as git rm-deleted
, run:
git config --global alias.rm-deleted '!git rm $(git ls-files --deleted)'
Note many third-party clients have own timezone settings overlapping any Postgres server and\or session settings.
E.g. if you're using 'IntelliJ IDEA 2017.3' (or DataGrips), you should define timezone as:
'DB source properties' -> 'Advanced' tab -> 'VM Options': -Duser.timezone=UTC+06:00
otherwise you will see 'UTC' despite of whatever you have set anywhere else.
You want to run:
php -m
on the command line,
or if you have access to the server configuration file open
/etc/php5/apache2/php.ini
and look at all the the extensions,
you can even enable or disable them by switching between On and Off like this
<Extension_name> = <[On | Off]>
You probably want to edit the .bashrc
file in your home directory.
None of the answers here helped. I needed to have "apply plugin: 'com.google.gms.google-services'" in my gradle. What helped was updating Android Studio to the latest version. I was then able to add the plugin and connect to Firebase Messaging Service.
you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt()
in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();
Having reviewed a few different large scale React/Redux projects in my experience Sagas provide developers a more structured way of writing code that is much easier to test and harder to get wrong.
Yes it is a little wierd to start with, but most devs get enough of an understanding of it in a day. I always tell people to not worry about what yield
does to start with and that once you write a couple of test it will come to you.
I have seen a couple of projects where thunks have been treated as if they are controllers from the MVC patten and this quickly becomes an unmaintable mess.
My advice is to use Sagas where you need A triggers B type stuff relating to a single event. For anything that could cut across a number of actions, I find it is simpler to write customer middleware and use the meta property of an FSA action to trigger it.
Other than caching every hour, or every week, you may cache according to file data.
Example (in PHP):
<script src="js/my_script.js?v=<?=md5_file('js/my_script.js')?>"></script>
or even use file modification time:
<script src="js/my_script.js?v=<?=filemtime('js/my_script.js')?>"></script>
If tomcat is installed locally, type the following url in a browser window: { localhost:8080 }
This will display Tomcat home page with the following message.
If you're seeing this, you've successfully installed Tomcat. Congratulations!
If tomcat is installed on a separate server, you can type replace localhost by a valid hostname or Iess where tomcat is installed.
The above applies for a standard installation wherein tomcat uses the default port 8080
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
java.lang.String.split(String regex)
is what you are looking for.
I had this problem. I solved it with downloading 64x of the Java. Here is the link: http://javadl.sun.com/webapps/download/AutoDL?BundleId=87443
This is how I think of it (and have seen rationalized by others):
A library is something contained within your code. And a framework is a container for your application.
Note the guidelines for performing work on a UI thread, collected on my blog:
There are two techniques you should use:
1) Use ConfigureAwait(false)
when you can.
E.g., await MyAsync().ConfigureAwait(false);
instead of await MyAsync();
.
ConfigureAwait(false)
tells the await
that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async
method (after the ConfigureAwait
), you cannot do anything that assumes you're in the current context (e.g., update UI elements).
For more information, see my MSDN article Best Practices in Asynchronous Programming.
2) Use Task.Run
to call CPU-bound methods.
You should use Task.Run
, but not within any code you want to be reusable (i.e., library code). So you use Task.Run
to call the method, not as part of the implementation of the method.
So purely CPU-bound work would look like this:
// Documentation: This method is CPU-bound.
void DoWork();
Which you would call using Task.Run
:
await Task.Run(() => DoWork());
Methods that are a mixture of CPU-bound and I/O-bound should have an Async
signature with documentation pointing out their CPU-bound nature:
// Documentation: This method is CPU-bound.
Task DoWorkAsync();
Which you would also call using Task.Run
(since it is partially CPU-bound):
await Task.Run(() => DoWorkAsync());
Tilde (~)
major version is fixed, minor version is fixed, matches any build number
"express": "~4.13.3"
~4.13.3
means it will check for 4.13.x where x is anything and 4.14.0
Caret (^)
major version is fixed, matches any minor version, matches any build number
"supertest": "^3.0.0"
^3.0.0
means it will check for 3.x.x where x is anything
queryParams
queryParams
is another input of routerLink
where they can be passed like
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>
fragment
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>
routerLinkActiveOptions
To also get routes active class set on parent routes:
[routerLinkActiveOptions]="{ exact: false }"
To pass query parameters to this.router.navigate(...)
use
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
See also https://angular.io/guide/router#query-parameters-and-fragments
I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:
BufferedImage img = null;
try {
img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));
Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.
Keyboard shortcuts to that are:
For copy: Place cursor on starting of block and press md and then goto end of block and press y'd. This will select the block to paste it press p
For cut: Place cursor on starting of block and press ma and then goto end of block and press d'a. This will select the block to paste it press p
I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.
See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.
As soon as there is only method Long.valueOf(long)
, cast from int
to long
will be done implicitly in case of using Long.valueOf(intValue)
.
The more clear way to do this is
Integer.valueOf(intValue).longValue()
I had same issue but with express and apollo-server. The solution from here:
The only special consideration that needs to be made is to allow heroku to choose the port that the server is deployed to. Otherwise, there may be errors, such as a request timeout.
To configure apollo-server to use a port defined by Heroku at runtime, the listen function in your setup file can be called with a port defined by the PORT environment variable:
> server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
> console.log(`Server ready at ${url}`); });
There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.
Thus, try the following:
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except ValueError: # includes simplejson.decoder.JSONDecodeError
print 'Decoding JSON has failed'
EDIT: Since simplejson.decoder.JSONDecodeError
actually inherits from ValueError
(proof here), I simplified the catch statement by just using ValueError
.
There is not only 1 %SystemRoot%\System32
on Windows x64. There are 2 such directories.
The real %SystemRoot%\System32
directory is for 64-bit applications. This directory contains a 64-bit cmd.exe
.
But there is also %SystemRoot%\SysWOW64
for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32
. It contains a 32-bit cmd.exe
.
32-bit applications can access %SystemRoot%\System32
for 64-bit applications by using the alias %SystemRoot%\Sysnative
in path.
For more details see the Microsoft documentation about File System Redirector.
So the subdirectory run
was created either in %SystemRoot%\System32
for 64-bit applications and 32-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\SysWOW64
which is %SystemRoot%\System32
for 32-bit cmd.exe
or the subdirectory run
was created in %SystemRoot%\System32
for 32-bit applications and 64-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\System32
as this subdirectory exists only in %SystemRoot%\SysWOW64
.
The following code could be used at top of the batch file in case of subdirectory run
is in %SystemRoot%\System32
for 64-bit applications:
@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
Every console application in System32\run
directory must be executed with %SystemPath%
in the batch file, for example %SystemPath%\run\YourApp.exe
.
How it works?
There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32
as defined at top.
But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative
. In this case the batch file is processed currently by 32-bit cmd.exe
and only in this case %SystemRoot%\Sysnative
needs to be used at all. Otherwise %SystemRoot%\System32
can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe
, this is the directory containing the 64-bit console applications (and the subdirectory run
).
Note: %SystemRoot%\Sysnative
is not a directory! It is not possible to cd
to %SystemRoot%\Sysnative
or use if exist %SystemRoot%\Sysnative
or if exist %SystemRoot%\Sysnative\
. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe
or more general if exist %SystemRoot%\Sysnative\*
.
Unexpected token errors in ESLint parsing occur due to incompatibility between your development environment and ESLint's current parsing capabilities with the ongoing changes with JavaScripts ES6~7.
Adding the "parserOptions" property to your .eslintrc is no longer enough for particular situations, such as using
static contextTypes = { ... } /* react */
in ES6 classes as ESLint is currently unable to parse it on its own. This particular situation will throw an error of:
error Parsing error: Unexpected token =
The solution is to have ESLint parsed by a compatible parser. babel-eslint is a package that saved me recently after reading this page and i decided to add this as an alternative solution for anyone coming later.
just add:
"parser": "babel-eslint"
to your .eslintrc
file and run npm install babel-eslint --save-dev
or yarn add -D babel-eslint
.
Please note that as the new Context API starting from React ^16.3
has some important changes, please refer to the official guide.
The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.
Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).
Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.
Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.
So the relationships are:
There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.
Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.
One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.
I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.
Sass supports @if
statements. (See the documentation.)
You could write your mixin like this:
@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
@if $inset != "" {
-webkit-box-shadow:$top $left $blur $color $inset;
-moz-box-shadow:$top $left $blur $color $inset;
box-shadow:$top $left $blur $color $inset;
}
}
For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.
After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope
if there is no $scope
for that element)
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.
Hope it will help.
You can use numpy's polyfit. I use the following (you can safely remove the bit about coefficient of determination and error bounds, I just think it looks nice):
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import csv
with open("example.csv", "r") as f:
data = [row for row in csv.reader(f)]
xd = [float(row[0]) for row in data]
yd = [float(row[1]) for row in data]
# sort the data
reorder = sorted(range(len(xd)), key = lambda ii: xd[ii])
xd = [xd[ii] for ii in reorder]
yd = [yd[ii] for ii in reorder]
# make the scatter plot
plt.scatter(xd, yd, s=30, alpha=0.15, marker='o')
# determine best fit line
par = np.polyfit(xd, yd, 1, full=True)
slope=par[0][0]
intercept=par[0][1]
xl = [min(xd), max(xd)]
yl = [slope*xx + intercept for xx in xl]
# coefficient of determination, plot text
variance = np.var(yd)
residuals = np.var([(slope*xx + intercept - yy) for xx,yy in zip(xd,yd)])
Rsqr = np.round(1-residuals/variance, decimals=2)
plt.text(.9*max(xd)+.1*min(xd),.9*max(yd)+.1*min(yd),'$R^2 = %0.2f$'% Rsqr, fontsize=30)
plt.xlabel("X Description")
plt.ylabel("Y Description")
# error bounds
yerr = [abs(slope*xx + intercept - yy) for xx,yy in zip(xd,yd)]
par = np.polyfit(xd, yerr, 2, full=True)
yerrUpper = [(xx*slope+intercept)+(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]
yerrLower = [(xx*slope+intercept)-(par[0][0]*xx**2 + par[0][1]*xx + par[0][2]) for xx,yy in zip(xd,yd)]
plt.plot(xl, yl, '-r')
plt.plot(xd, yerrLower, '--r')
plt.plot(xd, yerrUpper, '--r')
plt.show()
This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.
For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.
I have left the read method unimplemented to keep the example small in size.
The realloc
function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.
For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.
Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.
var Buffer_A1 = function (chunk_size) {
this.buffer_list = [];
this.total_size = 0;
this.cur_size = 0;
this.cur_buffer = [];
this.chunk_size = chunk_size || 4096;
this.buffer_list.push(new Buffer(this.chunk_size));
};
Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;
var lastbuf = this.buffer_list.length - 1;
for (var x = 0; x < can_write; ++x) {
this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
}
this.cur_size += can_write;
this.total_size += can_write;
if (this.cur_size == this.chunk_size) {
this.buffer_list.push(new Buffer(this.chunk_size));
this.cur_size = 0;
}
return can_write;
};
/*
The `data` parameter can be anything that is array like. It just must
support indexing and a length and produce an acceptable value to be
used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
offset = offset == undefined ? 0 : offset;
length = length == undefined ? data.length : length;
var rem = length;
while (rem > 0) {
rem -= this.writeByteArrayLimited(data, length - rem, rem);
}
};
Buffer_A1.prototype.readByteArray = function (data, offset, length) {
/*
If you really wanted to implement some read functionality
then you would have to deal with unaligned reads which could
span two buffers.
*/
};
Buffer_A1.prototype.getSingleBuffer = function () {
var obuf = new Buffer(this.total_size);
var cur_off = 0;
var x;
for (x = 0; x < this.buffer_list.length - 1; ++x) {
this.buffer_list[x].copy(obuf, cur_off);
cur_off += this.buffer_list[x].length;
}
this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);
return obuf;
};
If you try it in Anaconda on Windows, PyPDF2 might not handle some of the PDFs with non-standard structure or unicode characters. I recommend using the following code if you need to open and read a lot of pdf files - the text of all pdf files in folder with relative path .//pdfs//
will be stored in list pdf_text_list
.
from tika import parser
import glob
def read_pdf(filename):
text = parser.from_file(filename)
return(text)
all_files = glob.glob(".\\pdfs\\*.pdf")
pdf_text_list=[]
for i,file in enumerate(all_files):
text=read_pdf(file)
pdf_text_list.append(text['content'])
print(pdf_text_list)
The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:
Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);
I too was wondering why you can't just start microsoftedge.exe, like you do "old-style" applications in windows 10. Searching the web, I found the answer -- it has to do with how Microsoft implemented "Universal Apps".
Below is a brief summary taken from that answer, but I recommend reading the entire entry, because it gives a great explanation of how these "Universal Apps" are being dealt with. Microsoft Edge is not the only app like this we'll be dealing with.
Here's the link: http://www.itworld.com/article/2943955/windows/how-to-script-microsofts-edge-browser.html
Here's the summary from that page:
"Microsoft Edge is a "Modern" Universal app. This means it can't be opened from the command line in the traditional Windows manner: Executable name followed by command switches/parameter values. But where there's a will, there's a way. In this case, the "way" is known as protocol activation."
Kudos to the author of the article, Stephen Glasskeys.
Span does not have 'change' event by default. But you can add this event manually.
Listen to the change event of span.
$("#span1").on('change',function(){
//Do calculation and change value of other span2,span3 here
$("#span2").text('calculated value');
});
And wherever you change the text in span1. Trigger the change event manually.
$("#span1").text('test').trigger('change');
protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
#region Dynamically Show gridView header From data base
getAllheaderName();/*To get all Allowences master headerName*/
TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
txt_Days.Text = hidMonthsDays.Value;
#endregion
}
}
you could use ts-node-dev
It restarts target node process when any of required files changes (as standard node-dev) but shares Typescript compilation process between restarts.
Install
yarn add ts-node-dev --dev
and your package.json could be like this
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"dev": "ts-node-dev --respawn --transpileOnly ./src/index.ts",
"prod": "tsc && node ./build/index.js"
}
If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character
This is not an answer but a feedback with few compilers of 2021. On Intel CoffeeLake 9900k.
With Microsoft compiler (VS2019), toolset v142:
unsigned 209695540000 1.8322 sec 28.6152 GB/s uint64_t 209695540000 3.08764 sec 16.9802 GB/s
With Intel compiler 2021:
unsigned 209695540000 1.70845 sec 30.688 GB/s uint64_t 209695540000 1.57956 sec 33.1921 GB/s
According to Mysticial's answer, Intel compiler is aware of False Data Dependency, but not Microsoft compiler.
For intel compiler, I used /QxHost
(optimize of CPU's architecture which is that of the host) /Oi
(enable intrinsic functions) and #include <nmmintrin.h>
instead of #include <immintrin.h>
.
Full compile command: /GS /W3 /QxHost /Gy /Zi /O2 /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" //fprofile-instr-use "x64\Release\" /Fp"x64\Release\Benchmark.pch"
.
The decompiled (by IDA 7.5) assembly from ICC:
int __cdecl main(int argc, const char **argv, const char **envp)
{
int v6; // er13
_BYTE *v8; // rsi
unsigned int v9; // edi
unsigned __int64 i; // rbx
unsigned __int64 v11; // rdi
int v12; // ebp
__int64 v13; // r14
__int64 v14; // rbx
unsigned int v15; // eax
unsigned __int64 v16; // rcx
unsigned int v17; // eax
unsigned __int64 v18; // rcx
__int64 v19; // rdx
unsigned int v20; // eax
int result; // eax
std::ostream *v23; // rbx
char v24; // dl
std::ostream *v33; // rbx
std::ostream *v41; // rbx
__int64 v42; // rdx
unsigned int v43; // eax
int v44; // ebp
__int64 v45; // r14
__int64 v46; // rbx
unsigned __int64 v47; // rax
unsigned __int64 v48; // rax
std::ostream *v50; // rdi
char v51; // dl
std::ostream *v58; // rdi
std::ostream *v60; // rdi
__int64 v61; // rdx
unsigned int v62; // eax
__asm
{
vmovdqa [rsp+98h+var_58], xmm8
vmovapd [rsp+98h+var_68], xmm7
vmovapd [rsp+98h+var_78], xmm6
}
if ( argc == 2 )
{
v6 = atol(argv[1]) << 20;
_R15 = v6;
v8 = operator new[](v6);
if ( v6 )
{
v9 = 1;
for ( i = 0i64; i < v6; i = v9++ )
v8[i] = rand();
}
v11 = (unsigned __int64)v6 >> 3;
v12 = 0;
v13 = Xtime_get_ticks_0();
v14 = 0i64;
do
{
if ( v6 )
{
v15 = 4;
v16 = 0i64;
do
{
v14 += __popcnt(*(_QWORD *)&v8[8 * v16])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 24])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 16])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 8]);
v16 = v15;
v15 += 4;
}
while ( v11 > v16 );
v17 = 4;
v18 = 0i64;
do
{
v14 += __popcnt(*(_QWORD *)&v8[8 * v18])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 24])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 16])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 8]);
v18 = v17;
v17 += 4;
}
while ( v11 > v18 );
}
v12 += 2;
}
while ( v12 != 10000 );
_RBP = 100 * (Xtime_get_ticks_0() - v13);
std::operator___std::char_traits_char___(std::cout, "unsigned\t");
v23 = (std::ostream *)std::ostream::operator<<(std::cout, v14);
std::operator___std::char_traits_char____0(v23, v24);
__asm
{
vmovq xmm0, rbp
vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
vpunpckldq xmm0, xmm0, xmm8
vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
vsubpd xmm0, xmm0, xmm7
vpermilpd xmm1, xmm0, 1
vaddsd xmm6, xmm1, xmm0
vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
}
v33 = (std::ostream *)std::ostream::operator<<(v23);
std::operator___std::char_traits_char___(v33, " sec \t");
__asm
{
vmovq xmm0, r15
vpunpckldq xmm0, xmm0, xmm8
vsubpd xmm0, xmm0, xmm7
vpermilpd xmm1, xmm0, 1
vaddsd xmm0, xmm1, xmm0
vmulsd xmm7, xmm0, cs:__real@40c3880000000000
vdivsd xmm1, xmm7, xmm6
}
v41 = (std::ostream *)std::ostream::operator<<(v33);
std::operator___std::char_traits_char___(v41, " GB/s");
LOBYTE(v42) = 10;
v43 = std::ios::widen((char *)v41 + *(int *)(*(_QWORD *)v41 + 4i64), v42);
std::ostream::put(v41, v43);
std::ostream::flush(v41);
v44 = 0;
v45 = Xtime_get_ticks_0();
v46 = 0i64;
do
{
if ( v6 )
{
v47 = 0i64;
do
{
v46 += __popcnt(*(_QWORD *)&v8[8 * v47])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 8])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 16])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 24]);
v47 += 4i64;
}
while ( v47 < v11 );
v48 = 0i64;
do
{
v46 += __popcnt(*(_QWORD *)&v8[8 * v48])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 8])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 16])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 24]);
v48 += 4i64;
}
while ( v48 < v11 );
}
v44 += 2;
}
while ( v44 != 10000 );
_RBP = 100 * (Xtime_get_ticks_0() - v45);
std::operator___std::char_traits_char___(std::cout, "uint64_t\t");
v50 = (std::ostream *)std::ostream::operator<<(std::cout, v46);
std::operator___std::char_traits_char____0(v50, v51);
__asm
{
vmovq xmm0, rbp
vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
vsubpd xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
vpermilpd xmm1, xmm0, 1
vaddsd xmm6, xmm1, xmm0
vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
}
v58 = (std::ostream *)std::ostream::operator<<(v50);
std::operator___std::char_traits_char___(v58, " sec \t");
__asm { vdivsd xmm1, xmm7, xmm6 }
v60 = (std::ostream *)std::ostream::operator<<(v58);
std::operator___std::char_traits_char___(v60, " GB/s");
LOBYTE(v61) = 10;
v62 = std::ios::widen((char *)v60 + *(int *)(*(_QWORD *)v60 + 4i64), v61);
std::ostream::put(v60, v62);
std::ostream::flush(v60);
free(v8);
result = 0;
}
else
{
std::operator___std::char_traits_char___(std::cerr, "usage: array_size in MB");
LOBYTE(v19) = 10;
v20 = std::ios::widen((char *)&std::cerr + *((int *)std::cerr + 1), v19);
std::ostream::put(std::cerr, v20);
std::ostream::flush(std::cerr);
result = -1;
}
__asm
{
vmovaps xmm6, [rsp+98h+var_78]
vmovaps xmm7, [rsp+98h+var_68]
vmovaps xmm8, [rsp+98h+var_58]
}
return result;
}
and disassembly of main:
.text:0140001000 .686p
.text:0140001000 .mmx
.text:0140001000 .model flat
.text:0140001000
.text:0140001000 ; ===========================================================================
.text:0140001000
.text:0140001000 ; Segment type: Pure code
.text:0140001000 ; Segment permissions: Read/Execute
.text:0140001000 _text segment para public 'CODE' use64
.text:0140001000 assume cs:_text
.text:0140001000 ;org 140001000h
.text:0140001000 assume es:nothing, ss:nothing, ds:_data, fs:nothing, gs:nothing
.text:0140001000
.text:0140001000 ; =============== S U B R O U T I N E =======================================
.text:0140001000
.text:0140001000
.text:0140001000 ; int __cdecl main(int argc, const char **argv, const char **envp)
.text:0140001000 main proc near ; CODE XREF: __scrt_common_main_seh+107?p
.text:0140001000 ; DATA XREF: .pdata:ExceptionDir?o
.text:0140001000
.text:0140001000 var_78 = xmmword ptr -78h
.text:0140001000 var_68 = xmmword ptr -68h
.text:0140001000 var_58 = xmmword ptr -58h
.text:0140001000
.text:0140001000 push r15
.text:0140001002 push r14
.text:0140001004 push r13
.text:0140001006 push r12
.text:0140001008 push rsi
.text:0140001009 push rdi
.text:014000100A push rbp
.text:014000100B push rbx
.text:014000100C sub rsp, 58h
.text:0140001010 vmovdqa [rsp+98h+var_58], xmm8
.text:0140001016 vmovapd [rsp+98h+var_68], xmm7
.text:014000101C vmovapd [rsp+98h+var_78], xmm6
.text:0140001022 cmp ecx, 2
.text:0140001025 jnz loc_14000113E
.text:014000102B mov rcx, [rdx+8] ; String
.text:014000102F call cs:__imp_atol
.text:0140001035 mov r13d, eax
.text:0140001038 shl r13d, 14h
.text:014000103C movsxd r15, r13d
.text:014000103F mov rcx, r15 ; size
.text:0140001042 call ??_U@YAPEAX_K@Z ; operator new[](unsigned __int64)
.text:0140001047 mov rsi, rax
.text:014000104A test r15d, r15d
.text:014000104D jz short loc_14000106E
.text:014000104F mov edi, 1
.text:0140001054 xor ebx, ebx
.text:0140001056 mov rbp, cs:__imp_rand
.text:014000105D nop dword ptr [rax]
.text:0140001060
.text:0140001060 loc_140001060: ; CODE XREF: main+6C?j
.text:0140001060 call rbp ; __imp_rand
.text:0140001062 mov [rsi+rbx], al
.text:0140001065 mov ebx, edi
.text:0140001067 inc edi
.text:0140001069 cmp rbx, r15
.text:014000106C jb short loc_140001060
.text:014000106E
.text:014000106E loc_14000106E: ; CODE XREF: main+4D?j
.text:014000106E mov rdi, r15
.text:0140001071 shr rdi, 3
.text:0140001075 xor ebp, ebp
.text:0140001077 call _Xtime_get_ticks_0
.text:014000107C mov r14, rax
.text:014000107F xor ebx, ebx
.text:0140001081 jmp short loc_14000109F
.text:0140001081 ; ---------------------------------------------------------------------------
.text:0140001083 align 10h
.text:0140001090
.text:0140001090 loc_140001090: ; CODE XREF: main+A2?j
.text:0140001090 ; main+EC?j ...
.text:0140001090 add ebp, 2
.text:0140001093 cmp ebp, 2710h
.text:0140001099 jz loc_140001184
.text:014000109F
.text:014000109F loc_14000109F: ; CODE XREF: main+81?j
.text:014000109F test r13d, r13d
.text:01400010A2 jz short loc_140001090
.text:01400010A4 mov eax, 4
.text:01400010A9 xor ecx, ecx
.text:01400010AB nop dword ptr [rax+rax+00h]
.text:01400010B0
.text:01400010B0 loc_1400010B0: ; CODE XREF: main+E7?j
.text:01400010B0 popcnt rcx, qword ptr [rsi+rcx*8]
.text:01400010B6 add rcx, rbx
.text:01400010B9 lea edx, [rax-3]
.text:01400010BC popcnt rdx, qword ptr [rsi+rdx*8]
.text:01400010C2 add rdx, rcx
.text:01400010C5 lea ecx, [rax-2]
.text:01400010C8 popcnt rcx, qword ptr [rsi+rcx*8]
.text:01400010CE add rcx, rdx
.text:01400010D1 lea edx, [rax-1]
.text:01400010D4 xor ebx, ebx
.text:01400010D6 popcnt rbx, qword ptr [rsi+rdx*8]
.text:01400010DC add rbx, rcx
.text:01400010DF mov ecx, eax
.text:01400010E1 add eax, 4
.text:01400010E4 cmp rdi, rcx
.text:01400010E7 ja short loc_1400010B0
.text:01400010E9 test r13d, r13d
.text:01400010EC jz short loc_140001090
.text:01400010EE mov eax, 4
.text:01400010F3 xor ecx, ecx
.text:01400010F5 db 2Eh
.text:01400010F5 nop word ptr [rax+rax+00000000h]
.text:01400010FF nop
.text:0140001100
.text:0140001100 loc_140001100: ; CODE XREF: main+137?j
.text:0140001100 popcnt rcx, qword ptr [rsi+rcx*8]
.text:0140001106 add rcx, rbx
.text:0140001109 lea edx, [rax-3]
.text:014000110C popcnt rdx, qword ptr [rsi+rdx*8]
.text:0140001112 add rdx, rcx
.text:0140001115 lea ecx, [rax-2]
.text:0140001118 popcnt rcx, qword ptr [rsi+rcx*8]
.text:014000111E add rcx, rdx
.text:0140001121 lea edx, [rax-1]
.text:0140001124 xor ebx, ebx
.text:0140001126 popcnt rbx, qword ptr [rsi+rdx*8]
.text:014000112C add rbx, rcx
.text:014000112F mov ecx, eax
.text:0140001131 add eax, 4
.text:0140001134 cmp rdi, rcx
.text:0140001137 ja short loc_140001100
.text:0140001139 jmp loc_140001090
.text:014000113E ; ---------------------------------------------------------------------------
.text:014000113E
.text:014000113E loc_14000113E: ; CODE XREF: main+25?j
.text:014000113E mov rsi, cs:__imp_?cerr@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cerr
.text:0140001145 lea rdx, aUsageArraySize ; "usage: array_size in MB"
.text:014000114C mov rcx, rsi ; std::ostream *
.text:014000114F call std__operator___std__char_traits_char___
.text:0140001154 mov rax, [rsi]
.text:0140001157 movsxd rcx, dword ptr [rax+4]
.text:014000115B add rcx, rsi
.text:014000115E mov dl, 0Ah
.text:0140001160 call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:0140001166 mov rcx, rsi
.text:0140001169 mov edx, eax
.text:014000116B call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001171 mov rcx, rsi
.text:0140001174 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000117A mov eax, 0FFFFFFFFh
.text:014000117F jmp loc_1400013E2
.text:0140001184 ; ---------------------------------------------------------------------------
.text:0140001184
.text:0140001184 loc_140001184: ; CODE XREF: main+99?j
.text:0140001184 call _Xtime_get_ticks_0
.text:0140001189 sub rax, r14
.text:014000118C imul rbp, rax, 64h ; 'd'
.text:0140001190 mov r14, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001197 lea rdx, aUnsigned ; "unsigned\t"
.text:014000119E mov rcx, r14 ; std::ostream *
.text:01400011A1 call std__operator___std__char_traits_char___
.text:01400011A6 mov rcx, r14
.text:01400011A9 mov rdx, rbx
.text:01400011AC call cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:01400011B2 mov rbx, rax
.text:01400011B5 mov rcx, rax ; std::ostream *
.text:01400011B8 call std__operator___std__char_traits_char____0
.text:01400011BD vmovq xmm0, rbp
.text:01400011C2 vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
.text:01400011CA vpunpckldq xmm0, xmm0, xmm8
.text:01400011CF vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
.text:01400011D7 vsubpd xmm0, xmm0, xmm7
.text:01400011DB vpermilpd xmm1, xmm0, 1
.text:01400011E1 vaddsd xmm6, xmm1, xmm0
.text:01400011E5 vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
.text:01400011ED mov r12, cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z ; std::ostream::operator<<(double)
.text:01400011F4 mov rcx, rbx
.text:01400011F7 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:01400011FA mov rbx, rax
.text:01400011FD lea rdx, aSec ; " sec \t"
.text:0140001204 mov rcx, rax ; std::ostream *
.text:0140001207 call std__operator___std__char_traits_char___
.text:014000120C vmovq xmm0, r15
.text:0140001211 vpunpckldq xmm0, xmm0, xmm8
.text:0140001216 vsubpd xmm0, xmm0, xmm7
.text:014000121A vpermilpd xmm1, xmm0, 1
.text:0140001220 vaddsd xmm0, xmm1, xmm0
.text:0140001224 vmulsd xmm7, xmm0, cs:__real@40c3880000000000
.text:014000122C vdivsd xmm1, xmm7, xmm6
.text:0140001230 mov rcx, rbx
.text:0140001233 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001236 mov rbx, rax
.text:0140001239 lea rdx, aGbS ; " GB/s"
.text:0140001240 mov rcx, rax ; std::ostream *
.text:0140001243 call std__operator___std__char_traits_char___
.text:0140001248 mov rax, [rbx]
.text:014000124B movsxd rcx, dword ptr [rax+4]
.text:014000124F add rcx, rbx
.text:0140001252 mov dl, 0Ah
.text:0140001254 call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:014000125A mov rcx, rbx
.text:014000125D mov edx, eax
.text:014000125F call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001265 mov rcx, rbx
.text:0140001268 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000126E xor ebp, ebp
.text:0140001270 call _Xtime_get_ticks_0
.text:0140001275 mov r14, rax
.text:0140001278 xor ebx, ebx
.text:014000127A jmp short loc_14000128F
.text:014000127A ; ---------------------------------------------------------------------------
.text:014000127C align 20h
.text:0140001280
.text:0140001280 loc_140001280: ; CODE XREF: main+292?j
.text:0140001280 ; main+2DB?j ...
.text:0140001280 add ebp, 2
.text:0140001283 cmp ebp, 2710h
.text:0140001289 jz loc_14000131D
.text:014000128F
.text:014000128F loc_14000128F: ; CODE XREF: main+27A?j
.text:014000128F test r13d, r13d
.text:0140001292 jz short loc_140001280
.text:0140001294 xor eax, eax
.text:0140001296 db 2Eh
.text:0140001296 nop word ptr [rax+rax+00000000h]
.text:01400012A0
.text:01400012A0 loc_1400012A0: ; CODE XREF: main+2D6?j
.text:01400012A0 xor ecx, ecx
.text:01400012A2 popcnt rcx, qword ptr [rsi+rax*8]
.text:01400012A8 add rcx, rbx
.text:01400012AB xor edx, edx
.text:01400012AD popcnt rdx, qword ptr [rsi+rax*8+8]
.text:01400012B4 add rdx, rcx
.text:01400012B7 xor ecx, ecx
.text:01400012B9 popcnt rcx, qword ptr [rsi+rax*8+10h]
.text:01400012C0 add rcx, rdx
.text:01400012C3 xor ebx, ebx
.text:01400012C5 popcnt rbx, qword ptr [rsi+rax*8+18h]
.text:01400012CC add rbx, rcx
.text:01400012CF add rax, 4
.text:01400012D3 cmp rax, rdi
.text:01400012D6 jb short loc_1400012A0
.text:01400012D8 test r13d, r13d
.text:01400012DB jz short loc_140001280
.text:01400012DD xor eax, eax
.text:01400012DF nop
.text:01400012E0
.text:01400012E0 loc_1400012E0: ; CODE XREF: main+316?j
.text:01400012E0 xor ecx, ecx
.text:01400012E2 popcnt rcx, qword ptr [rsi+rax*8]
.text:01400012E8 add rcx, rbx
.text:01400012EB xor edx, edx
.text:01400012ED popcnt rdx, qword ptr [rsi+rax*8+8]
.text:01400012F4 add rdx, rcx
.text:01400012F7 xor ecx, ecx
.text:01400012F9 popcnt rcx, qword ptr [rsi+rax*8+10h]
.text:0140001300 add rcx, rdx
.text:0140001303 xor ebx, ebx
.text:0140001305 popcnt rbx, qword ptr [rsi+rax*8+18h]
.text:014000130C add rbx, rcx
.text:014000130F add rax, 4
.text:0140001313 cmp rax, rdi
.text:0140001316 jb short loc_1400012E0
.text:0140001318 jmp loc_140001280
.text:014000131D ; ---------------------------------------------------------------------------
.text:014000131D
.text:014000131D loc_14000131D: ; CODE XREF: main+289?j
.text:014000131D call _Xtime_get_ticks_0
.text:0140001322 sub rax, r14
.text:0140001325 imul rbp, rax, 64h ; 'd'
.text:0140001329 mov rdi, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001330 lea rdx, aUint64T ; "uint64_t\t"
.text:0140001337 mov rcx, rdi ; std::ostream *
.text:014000133A call std__operator___std__char_traits_char___
.text:014000133F mov rcx, rdi
.text:0140001342 mov rdx, rbx
.text:0140001345 call cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:014000134B mov rdi, rax
.text:014000134E mov rcx, rax ; std::ostream *
.text:0140001351 call std__operator___std__char_traits_char____0
.text:0140001356 vmovq xmm0, rbp
.text:014000135B vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
.text:0140001363 vsubpd xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
.text:014000136B vpermilpd xmm1, xmm0, 1
.text:0140001371 vaddsd xmm6, xmm1, xmm0
.text:0140001375 vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
.text:014000137D mov rcx, rdi
.text:0140001380 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001383 mov rdi, rax
.text:0140001386 lea rdx, aSec ; " sec \t"
.text:014000138D mov rcx, rax ; std::ostream *
.text:0140001390 call std__operator___std__char_traits_char___
.text:0140001395 vdivsd xmm1, xmm7, xmm6
.text:0140001399 mov rcx, rdi
.text:014000139C call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:014000139F mov rdi, rax
.text:01400013A2 lea rdx, aGbS ; " GB/s"
.text:01400013A9 mov rcx, rax ; std::ostream *
.text:01400013AC call std__operator___std__char_traits_char___
.text:01400013B1 mov rax, [rdi]
.text:01400013B4 movsxd rcx, dword ptr [rax+4]
.text:01400013B8 add rcx, rdi
.text:01400013BB mov dl, 0Ah
.text:01400013BD call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:01400013C3 mov rcx, rdi
.text:01400013C6 mov edx, eax
.text:01400013C8 call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:01400013CE mov rcx, rdi
.text:01400013D1 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:01400013D7 mov rcx, rsi ; Block
.text:01400013DA call cs:__imp_free
.text:01400013E0 xor eax, eax
.text:01400013E2
.text:01400013E2 loc_1400013E2: ; CODE XREF: main+17F?j
.text:01400013E2 vmovaps xmm6, [rsp+98h+var_78]
.text:01400013E8 vmovaps xmm7, [rsp+98h+var_68]
.text:01400013EE vmovaps xmm8, [rsp+98h+var_58]
.text:01400013F4 add rsp, 58h
.text:01400013F8 pop rbx
.text:01400013F9 pop rbp
.text:01400013FA pop rdi
.text:01400013FB pop rsi
.text:01400013FC pop r12
.text:01400013FE pop r13
.text:0140001400 pop r14
.text:0140001402 pop r15
.text:0140001404 retn
.text:0140001404 main endp
Coffee lake specification update "POPCNT instruction may take longer to execute than expected".
center-block
is bad idea as it covers a portion on your screen and you cannot click on your fields or buttons.
col-md-offset-?
is better option.
Use col-md-offset-3
is better option if class is col-sm-6
. Just change the number to center your block.
An other regex
-based solution:
>>> strs = "foo\tbar\t\tspam"
>>> r = re.compile(r'([^\t]*)\t*')
>>> r.findall(strs)[:-1]
['foo', 'bar', 'spam']
As for adding a dependency, I'm afraid the java.util.Date & .Calendar really are so bad that the first thing I do to any new project is add the Joda-Time library. In Java 8 you can use the new java.time package, inspired by Joda-Time.
The core of Joda-Time is the DateTime
class. Unlike java.util.Date, it understands its assigned time zone (DateTimeZone
). When converting from j.u.Date, assign a zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeQuébec = new DateTime( date , zone );
LocalDate
One way to verify if two date-times land on the same date is to convert to LocalDate
objects.
That conversion depends on the assigned time zone. To compare LocalDate
objects, they must have been converted with the same zone.
Here is a little utility method.
static public Boolean sameDate ( DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1 );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( dt1.getZone() ) );
Boolean match = ld1.equals( ld2 );
return match;
}
Better would be another argument, specifying the time zone rather than assuming the first DateTime object’s time zone should be used.
static public Boolean sameDate ( DateTimeZone zone , DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1.withZone( zone ) );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( zone ) );
return ld1.equals( ld2 );
}
Another approach is to create a string representation of the date portion of each date-time, then compare strings.
Again, the assigned time zone is crucial.
DateTimeFormatter formatter = ISODateTimeFormat.date(); // Static method.
String s1 = formatter.print( dateTime1 );
String s2 = formatter.print( dateTime2.withZone( dt1.getZone() ) );
Boolean match = s1.equals( s2 );
return match;
The generalized solution is to define a span of time, then ask if the span contains your target. This example code is in Joda-Time 2.4. Note that the "midnight"-related classes are deprecated. Instead use the withTimeAtStartOfDay
method. Joda-Time offers three classes to represent a span of time in various ways: Interval, Period, and Duration.
Using the "Half-Open" approach where the beginning of the span is inclusive and the ending exclusive.
The time zone of the target can be different than the time zone of the interval.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime target = new DateTime( 2012, 3, 4, 5, 6, 7, timeZone );
DateTime start = DateTime.now( timeZone ).withTimeAtStartOfDay();
DateTime stop = start.plusDays( 1 ).withTimeAtStartOfDay();
Interval interval = new Interval( start, stop );
boolean containsTarget = interval.contains( target );
Java 8 and later comes with the java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See Tutorial.
The makers of Joda-Time have instructed us all to move to java.time as soon as is convenient. In the meantime Joda-Time continues as an actively maintained project. But expect future work to occur only in java.time and ThreeTen-Extra rather than Joda-Time.
To summarize java.time in a nutshell… An Instant
is a moment on the timeline in UTC. Apply a time zone (ZoneId
) to get a ZonedDateTime
object. To move off the timeline, to get the vague indefinite idea of a date-time, use the "local" classes: LocalDateTime
, LocalDate
, LocalTime
.
The logic discussed in the Joda-Time section of this Answer applies to java.time.
The old java.util.Date class has a new toInstant
method for conversion to java.time.
Instant instant = yourJavaUtilDate.toInstant(); // Convert into java.time type.
Determining a date requires a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
We apply that time zone object to the Instant
to obtain a ZonedDateTime
. From that we extract a date-only value (a LocalDate
) as our goal is to compare dates (not hours, minutes, etc.).
ZonedDateTime zdt1 = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate1 = LocalDate.from( zdt1 );
Do the same to the second java.util.Date
object we need for comparison. I’ll just use the current moment instead.
ZonedDateTime zdt2 = ZonedDateTime.now( zoneId );
LocalDate localDate2 = LocalDate.from( zdt2 );
Use the special isEqual
method to test for the same date value.
Boolean sameDate = localDate1.isEqual( localDate2 );
Using the type="image"
is problematic because the ability to pass a value is disabled. Although it's not as customizable and thus as pretty, you can still use your images ao long as they are part of a type="button"
.
<button type="submit" name="someName" value="someValue"><img src="someImage.png" alt="SomeAlternateText"></button>
Oracle has a different syntax for parameters than Sql-Server. So use :
instead of @
using(var con=new OracleConnection(connectionString))
{
con.open();
var sql = "insert into users values (:id,:name,:surname,:username)";
using(var cmd = new OracleCommand(sql,con)
{
OracleParameter[] parameters = new OracleParameter[] {
new OracleParameter("id",1234),
new OracleParameter("name","John"),
new OracleParameter("surname","Doe"),
new OracleParameter("username","johnd")
};
cmd.Parameters.AddRange(parameters);
cmd.ExecuteNonQuery();
}
}
When using named parameters in an OracleCommand you must precede the parameter name with a colon (:).
http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters.aspx
noticed its a very old question but people seem still having trouble using a formula for extracting unique items. here's a solution that returns the values them selfs.
Lets say you have "red", "blue", "red", "green", "blue", "black" in column A2:A7
then put this in B2 as an array formula and copy down =IFERROR(INDEX(A$2:A$7;SMALL(IF(FREQUENCY(MATCH(A$2:A$7;A$2:A$7;0);ROW(INDIRECT("1:"&COUNTA(A$2:A$7))));ROW(INDIRECT("1:"&COUNTA(A$2:A$7)));"");ROW(A1)));"")
then it should look something like this;
This is the Different Solution, Check if your Services are running correctly, if WAMP icon showing orange color, and 2 out of 3 services are running it's showing, then this solution will work . Root cause:
If in your system mysql was there, later you installed WAMP then again one MYSQL will install as WAMP package, default port for MYSQL is 3306 , So in both mysql the port will be 3306, which is a port conflict, So just change the port it will work fine. Steps to change the Port.
The problem comes from your Java application (or a library you are using).
First, you should read the entire outputs (Google for StreamGobbler), and pronto!
Javadoc says:
The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
Secondly, waitFor()
your process to terminate.
You then should close the input, output and error streams.
Finally destroy()
your Process.
My sources:
To concatenate multiple strings into a single string, separated by another character, there are a couple of ways.
The nicest I have seen is using the join
method on an array:
fn main() {
let a = "Hello";
let b = "world";
let result = [a, b].join("\n");
print!("{}", result);
}
Depending on your use case you might also prefer more control:
fn main() {
let a = "Hello";
let b = "world";
let result = format!("{}\n{}", a, b);
print!("{}", result);
}
There are some more manual ways I have seen, some avoiding one or two allocations here and there. For readability purposes I find the above two to be sufficient.
the mime type might not be text/csv
some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel
) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.
$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
// do something
} else {
die("Sorry, mime type not allowed");
}
if you wished you could add a further check if mime is returned as text/plain you could run a preg_match
to make sure it has enough commas in it to be a csv.
In the Blade Template : define a variable like this
@extends('app',['title' => 'Your Title Goes Here'])
@section('content')
And in the app.blade.php or any other of your choice ( I'm just following default Laravel 5 setup )
<title>{{ $title or 'Default title Information if not set explicitly' }}</title>
This is my first answer here. Hope it works.Good luck!
Your chunk of code does not create a new one, it only checks if its already there and nothing else.
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
If your looking for something a little more native, you can use getGnuWin32 to install all of the unix command line tools that have been ported. That plus winBash gives you most of a working unix environment. Add console2 for a better terminal emulator and you almost can't tell your on windows!
Cygwin is a better toolkit overall, but I have found myself running into suprise problems because of the divide between it and windows. None of these solutions are as good as a native linux system though.
You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.
Try json_dto. It is header-only and easy to use.
Simple example:
struct message_t
{
std::string m_from;
std::string m_text;
// Entry point for json_dto.
template < typename JSON_IO >
void
json_io( JSON_IO & io )
{
io
& json_dto::mandatory( "from", m_from )
& json_dto::mandatory( "text", m_text );
}
};
This will be convertable to and from JSON:
{ "from" : "json_dto", "text" : "Hello world!" }
Select the text of all items under produce:
//produce/item/text()
Select all the manager nodes in all departments:
//department/*
You can override the hover effect for devices that don't support hover. Like:
.my-thing {
color: #BADA55;
}
.my-thing:hover {
color: hotpink;
}
@media (hover: none) {
.my-thing {
color: #BADA55;
}
}
Tested and verified on iOS 12
Hat tip to https://stackoverflow.com/a/50285058/178959 for pointing this out.
On some servers and web hosts, it's possible to disable ModSecurity via .htaccess
, but be aware that you can only switch it on or off, you can't disable individual rules.
But a good practice that still keeps your site secure is to disable it only on specific URLs, rather than your entire site. You can specify which URLs to match via the regex in the <If>
statement below...
### DISABLE mod_security firewall
### Some rules are currently too strict and are blocking legitimate users
### We only disable it for URLs that contain the regex below
### The regex below should be placed between "m#" and "#"
### (this syntax is required when the string contains forward slashes)
<IfModule mod_security.c>
<If "%{REQUEST_URI} =~ m#/admin/#">
SecFilterEngine Off
SecFilterScanPOST Off
</If>
</IfModule>
If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!
If you know that you want the values to the thousandths, place, it's
SELECT (num - FLOOR(num)) * 1000 FROM table...;
Alexander's answer is great, but lacks the handling of proxies that sometimes return multiple IP's in the HTTP_X_FORWARDED_FOR header.
The real IP is usually at the end of the list, as explained here: http://en.wikipedia.org/wiki/X-Forwarded-For
The solution is a simple modification of Alexander's code:
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
Adding libxml2 is a big, fat, finicky pain in the ass. If you're going to do it, do it before you get too far in building your project.
You need to add it in two ways:
Click on your target (not your project) and select Build Phases
.
Click on the reveal triangle titled Link Binary With Libraries
. Click on the +
to add a library.
Scroll to the bottom of the list and select libxml2.dylib
. That adds the libxml2 library to your project.
Now you have to tell your project where to look for it three more times.
Select the Build Settings tab
.
Scroll down to the Linking
section.
Under your projects columns double click on the Other Linker Flags
row.
Click the +
and add -lxml2
to the list.
Still more.
In the same tab, scroll down to the Search Paths
section.
Under your projects column in the Framework Search Paths
row add /usr/lib/libxml2.dylib
.
In the Header Search Paths
and the User Header Search Paths
row add $(SDKROOT)/usr/include/libxml2
.
In those last two cases make sure that path is entered in Debug and Release.
Under the Product
Menu select Clean
.
Then, if I were you (and lets face it, I probably am) I'd quit Xcode and walk away. When you come back and launch you should be good to go.
Slight modification on @JRodd version to support objects coming from Json (JObject)
public static dynamic ToDynamic(this object value)
{
IDictionary<string, object> expando = new ExpandoObject();
//Get the type of object
Type t = value.GetType();
//If is Dynamic Expando object
if (t.Equals(typeof(ExpandoObject)))
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
}
//If coming from Json object
else if (t.Equals(typeof(JObject)))
{
foreach (JProperty property in (JToken)value)
expando.Add(property.Name, property.Value);
}
else //Try converting a regular object
{
string str = JsonConvert.SerializeObject(value);
ExpandoObject obj = JsonConvert.DeserializeObject<ExpandoObject>(str);
return obj;
}
return expando as ExpandoObject;
}
jquery will execute both handler since it allows multiple event handlers. I have created sample code. You can try it
sed "s/^[ \t]*//" -i youfile
Warning: this will overwrite the original file.
Try this;
@media print{ @page { margin-top: 30px; margin-bottom: 30px;}}
In Java 8:
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
michael's suggestions works like a charm for me :) If you replace $http.post with $http.get, remember that the .get method accepts 2 parameters instead of 3... this is where is wasted my time... ;)
controller:
$http.get('/getdoc/' + $stateParams.id,
{responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([(response)], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
view:
<object ng-show="content" data="{{content}}" type="application/pdf" style="width: 100%; height: 400px;"></object>
I stumbled upon this problem when I was making a pet project. I've read some of the answers here and I've probably adopted on or two of them in my code.
BAD NEWS: I managed to do this by using a very dirty way (you'll see why). There are still some bugs that I haven't bothered to address (I was writing this at like 2 am), like if the min
value is 10, you won't be able to input a number to begin with.
GOOD NEWS: I've managed to get rid of the leading zeros bug mentioned by @nnyerges using solely the InputFilter
down to only one 0, that is if the min
value is 0. However, the limit of my implementation of the InputFilter
comes when user deletes the first number(s) that's followed by zero(s), e.g. if at first user inputs 1000
but then deletes 1
, it will become 000
. That's ugly, and that's where my dirty ugly use of TextChangedListener
/ TextWatcher
comes in. (I know OP already said that he can do it using TextWatcher
, but whatever.)
Another limitation (or maybe MY limitation?) using the InputFilter
is when the inputType
is numberDecimal
, which means user can input a decimal separator. Example case: range is 0 - 100
, user inputs 99.99
, user then deletes the separator, we'd have 9999
. We don't want that, do we?
I've also made it to accommodate negative value.
Some features in my code, whether you like it or not, include trimming insignificant 0
s, e.g. if user deletes 1
from 10032
, as long as it's within the defined range, it will trim the leading 0
s, so the final result will be 32. Second, when user tries to delete the negative (-
) notation or the decimal separator (.
), it will check whether the resulting number after deletion is still in range. If not, then it will revert back to last value. In other words, user isn't allowed to do that kind of removal. But, if you prefer to set the new values to either min
or max
values when that happens, you can do it, too.
NOTE: I'm too lazy to even bother with localization, so people who use comma as decimal separator will have to manually change it themselves.
SECOND NOTE: The code is very messy and probably have some or a lot of redundant checks, so be aware. Also, if you have suggestion, feel free to comment, as I want to improve it, too. I may need to use it in the future. Who knows?
Anyway, here it goes.
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
public class InputFilterMinMax implements InputFilter {
private double min, max;
public InputFilterMinMax(double min, double max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Double.parseDouble(min);
this.max = Double.parseDouble(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
String lastVal = dest.toString();
String newVal = lastVal.substring(0, dstart) + source.toString() + lastVal.substring(dstart);
String strInput = source.toString();
double input;
if (strInput.equals("-") && (lastVal.length() == 0 || lastVal.equals("0"))) {
return null;
} else {
input = Double.parseDouble(newVal);
}
if (isInRange(min, max, input)) {
try {
if (lastVal.equals("0") && strInput.equals("0") && !strInput.equals(".")) {
Log.d("Checkpoint 1", "Can't put 0 again.");
return "";
} else if (strInput.equals("0")) {
if (dstart == 0) {
if (lastVal.substring(0, 1).equals("0")) {
Log.d("Checkpoint 2", "Can't put 0 again.");
return "";
} else if (!lastVal.substring(0, 1).equals(".")) {
Log.d("Checkpoint 3", "Can't put 0 in front of them.");
return "";
}
} else {
if (lastVal.substring(0, 1).equals("0") && dstart == 1) {
Log.d("Checkpoint 4", "Can't put 0 again.");
return "";
} else if (lastVal.substring(0, 1).equals("-")) {
if (Double.parseDouble(lastVal) == 0) {
if (!lastVal.contains(".")) {
Log.d("Checkpoint 5", "Can't put 0 here.");
return "";
} else {
if (dstart <= lastVal.indexOf(".")) {
Log.d("Checkpoint 6", "Can't put 0 here.");
return "";
}
}
} else {
if (lastVal.indexOf("0") == 1 && (dstart == 1 || dstart == 2)) {
Log.d("Checkpoint 7", "Can't put 0 here.");
return "";
} else if ((!lastVal.substring(1, 2).equals("0") && !lastVal.substring(1, 2).equals(".")) && dstart == 1) {
Log.d("Checkpoint 8", "Can't put 0 here.");
return "";
}
}
}
}
}
/**
* If last value is a negative that equals min value,
* and user tries to input a decimal separator at the
* very end, ignore it, because they won't be able to
* input anything except 0 after that anyway.
*/
if (strInput.equals(".") && lastVal.substring(0,1).equals("-")
&& Double.parseDouble(lastVal) == min && dstart == lastVal.length()) {
return "";
}
} catch (Exception e) {
}
return null;
}
} catch (Exception ignored) {
ignored.printStackTrace();
}
return "";
}
private boolean isInRange(double a, double b, double c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
Now, the really dirty part:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements TextWatcher {
private EditText editInput;
/**
* Var to store old value in case the new value is either
* out of range or invalid somehow. This was because I
* needed a double value for my app, which means I can
* enter a dot (.), and that could mean trouble if I decided
* to delete that dot, e.g. assume the range is 0 - 100.
* At first I enter 99.99, the InputFilter would allow that,
* but what if somewhere down the line I decided to delete
* the dot/decimal separator for "fun"?
* Wow, now I have 9999.
* Also, when I delete negative notation, it can produce
* the same problem.
*/
private String oldVal;
private int min, max;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editInput = findViewById(R.id.edt_input);
editInput.addTextChangedListener(this);
min = -1600;
max = 1500;
editInput.setFilters(new InputFilter[]{new InputFilterMinMax(min, max)});
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
oldVal = saveOldValue(s, start);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
validateChange(editInput, oldVal);
}
private String saveOldValue(CharSequence s, int start) {
String oldVal = s.toString();
if (oldVal.contains(".") && start == oldVal.indexOf(".") && start != oldVal.length() - 1) {
return oldVal;
} else if (oldVal.contains("-") && start == oldVal.indexOf("-") && start != oldVal.length() - 1) {
return oldVal;
}
return null;
}
private void validateChange(EditText editText, String oldVal) {
String strNewVal = editText.getText().toString().trim();
boolean isChanged = false;
if (strNewVal.indexOf("0") == 0 || (strNewVal.indexOf("-") == 0 && strNewVal.indexOf("0") == 1)) {
if (strNewVal.contains(".")) {
while ((strNewVal.indexOf("0") == 0 && strNewVal.indexOf(".") != 1 && strNewVal.length() > 2) ||
(strNewVal.indexOf("0") == 1 && strNewVal.indexOf(".") != 2 && strNewVal.length() > 3)) {
Log.d("Trimming 0", "");
strNewVal = strNewVal.replaceFirst("0", "");
isChanged = true;
}
} else if (!strNewVal.contains(".")) {
while (strNewVal.indexOf("0") == 0 && strNewVal.length() > 1) {
Log.d("Trimming 0", "");
strNewVal = strNewVal.replaceFirst("0", "");
isChanged = true;
}
if (Double.parseDouble(strNewVal) > max) {
editText.setText(oldVal); // Or, you can set it to max values here.
return;
}
}
}
if (strNewVal.indexOf(".") == 0) {
strNewVal = "0" + strNewVal;
isChanged = true;
}
try {
double newVal = Double.parseDouble(strNewVal);
Log.d("NewVal: ", String.valueOf(newVal));
if (newVal > max || newVal < min) {
Log.d("Over Limit", "Let's Reset");
editText.setText(oldVal); // Or, you can set it to min or max values here.
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (isChanged) {
editText.setText(strNewVal);
}
}
}
You can just use:
<input type="radio" checked />
Using just the attribute checked without stating a value is the same as checked="checked"
.
AWS RDS users if you are getting this it is because you are not a superuser and according to aws documentation you cannot be one. I have found I have to ignore these errors.
Decimal and Numeric are the same functionally but there is still data type precedence, which can be crucial in some cases.
SELECT SQL_VARIANT_PROPERTY(CAST(1 AS NUMERIC) + CAST(1 AS DECIMAL),'basetype')
The resulting data type is numeric because it takes data type precedence.
Exhaustive list of data types by precedence:
Example found on: http://www.orafaq.com/usenet/comp.databases.oracle.server/2006/12/20/0646.htm
SELECT REGEXP_REPLACE(SYS_GUID(), '(.{8})(.{4})(.{4})(.{4})(.{12})', '\1-\2-\3-\4-\5') MSSQL_GUID FROM DUAL
Result:
6C7C9A50-3514-4E77-E053-B30210AC1082
For me it worked using flexbox, which is in my opinion the cleanest solution.
Add a css class around the parent div / element with :
.parent {
display: flex;
}
and for the button use:
.button {
justify-content: center;
}
You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.
If this is not working, try :
#wrapper {
display:flex;
justify-content: center;
}
I suspect that the real issue here is that your test runner is copying your assembly to a different location. There's no way at runtime to tell where the assembly was copied from, but you can probably flip a switch to tell the test runner to run the assembly from where it is and not to copy it to a shadow directory.
Such a switch is likely to be different for each test runner, of course.
Have you considered embedding your XML data as resources inside your test assembly?
If you are in Javascript already, couldn't you just use Date.Parse() to validate a date instead of using regEx.
RegEx for date is actually unwieldy and hard to get right especially with leap years and all.
The functions getElementById
and getElementsByClassName
are very specific, while querySelector
and querySelectorAll
are more elaborate. My guess is that they will actually have a worse performance.
Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".
Place right_ax
before set_ylabel()
ax.right_ax.set_ylabel('AB scale')
Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.
For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:
For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.
In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.
in normal time, checkboxes return an on/off value.
you can verify it with this code:
<form action method="POST">
<input type="checkbox" name="hello"/>
</form>
<?php
if(isset($_POST['hello'])) echo('<p>'.$_POST['hello'].'</p>');
?>
this will return
<p>off</p>
or
<p>on</p>
Pros
%1
, %2
, ... %*
in tact/arg
and -arg
styleCons
setlocal
for local scoping or write an accompanying :CLEAR-ARGS
routine!--force
to -f
)""
argument supportHere is an example how the following arguments relate to .bat variables:
>> testargs.bat /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %* | /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %ARG_FOO% | c:\
echo %ARG_A% |
echo %ARG_B% | 3
echo %ARG_C% | 1
echo %ARG_D% | 1
@echo off
setlocal
CALL :ARG-PARSER %*
::Print examples
echo: ALL: %*
echo: FOO: %ARG_FOO%
echo: A: %ARG_A%
echo: B: %ARG_B%
echo: C: %ARG_C%
echo: D: %ARG_D%
::*********************************************************
:: Parse commandline arguments into sane variables
:: See the following scenario as usage example:
:: >> thisfile.bat /a /b "c:\" /c /foo 5
:: >> CALL :ARG-PARSER %*
:: ARG_a=1
:: ARG_b=c:\
:: ARG_c=1
:: ARG_foo=5
::*********************************************************
:ARG-PARSER
::Loop until two consecutive empty args
:loopargs
IF "%~1%~2" EQU "" GOTO :EOF
set "arg1=%~1"
set "arg2=%~2"
shift
::Allow either / or -
set "tst1=%arg1:-=/%"
if "%arg1%" NEQ "" (
set "tst1=%tst1:~0,1%"
) ELSE (
set "tst1="
)
set "tst2=%arg2:-=/%"
if "%arg2%" NEQ "" (
set "tst2=%tst2:~0,1%"
) ELSE (
set "tst2="
)
::Capture assignments (eg. /foo bar)
IF "%tst1%" EQU "/" IF "%tst2%" NEQ "/" IF "%tst2%" NEQ "" (
set "ARG_%arg1:~1%=%arg2%"
GOTO loopargs
)
::Capture flags (eg. /foo)
IF "%tst1%" EQU "/" (
set "ARG_%arg1:~1%=1"
GOTO loopargs
)
goto loopargs
GOTO :EOF
I assume you want to know the performance difference between the following:
WHERE foo IN ('a', 'b', 'c')
WHERE foo = 'a' OR foo = 'b' OR foo = 'c'
According to the manual for MySQL if the values are constant IN
sorts the list and then uses a binary search. I would imagine that OR
evaluates them one by one in no particular order. So IN
is faster in some circumstances.
The best way to know is to profile both on your database with your specific data to see which is faster.
I tried both on a MySQL with 1000000 rows. When the column is indexed there is no discernable difference in performance - both are nearly instant. When the column is not indexed I got these results:
SELECT COUNT(*) FROM t_inner WHERE val IN (1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000);
1 row fetched in 0.0032 (1.2679 seconds)
SELECT COUNT(*) FROM t_inner WHERE val = 1000 OR val = 2000 OR val = 3000 OR val = 4000 OR val = 5000 OR val = 6000 OR val = 7000 OR val = 8000 OR val = 9000;
1 row fetched in 0.0026 (1.7385 seconds)
So in this case the method using OR is about 30% slower. Adding more terms makes the difference larger. Results may vary on other databases and on other data.
You don't. strings.xml
is just here to define the raw text messages. You should (must) use styles.xml
to define reusable visual styles to apply to your widgets.
Think of it as a good practice to separate the concerns. You can work on the visual styles independently from the text messages.
I am using php 7.3.8 on a manjaro and I was working with Persian content. This solved my problem:
$html = 'hi</b><p>????<div>?????9 ?';
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
print $doc->saveHTML($doc->documentElement) . PHP_EOL . PHP_EOL;
Create a setenv.(sh|bat) file in the tomcat/bin directory with the environment variables that you want modified.
The catalina script checks if the setenv script exists and runs it to set the environment variables. This way you can change the parameters to only one instance of tomcat and is easier to copy it to another instance.
Probably your configuration app has created the setenv script and thats why tomcat is ignoring the environment variables.
Looks like the solution is to set the value of the properties inside the default constructor. So in this case the java class is:
class JavaObject {
public JavaObject() {
optionalMember = "Value";
}
@NotNull
public String notNullMember;
public String optionalMember;
}
After the mapping with Jackson, if the optionalMember
is missing from the JSON its value in the Java class is "Value"
.
However, I am still interested to know if there is a solution with annotations and without the default constructor.
I got stuck with this problem and found that it was the order of the call to
request.setCharacterEncoding("UTF-8");
that was causing the problem. It has to be called before any all call to request.getParameter(), so I made a special filter to use at the top of my filter chain.
https://rogerkeays.com/servletrequest-setcharactercoding-ignored
Try avoiding unnecessary loops and go for this if needed.
string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
//your logic goes here
}
else
{
//your logic goes here
}
If you want to search by specific ID then there should be a primary key in a table.
Did you set the bind option to allow remote access on the redis server?
Before (file /etc/redis/redis.conf
)
bind 127.0.0.1
After
bind 0.0.0.0
and run sudo service redis-server restart
to restart the server. If that's not the problem, you might want to check any firewalls that might block the access.
Important: If you don't use a firewall (iptables, ufw..) to control who connects to the port in use, ANYONE can connect to this Redis instance. Without using Redis' AUTH
that means anyone can access/change/delete your data. Be safe!
If you are not tweaking the curl command too much you can also go and call the curl command directly
import shlex
cmd = '''curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
You can do like this.
<input type="button" value="mybutton1" onclick="dosomething(this)">
function dosomething(element){
alert("value is "+element.value); //you can print any value like id,class,value,innerHTML etc.
};
In short, functools.wraps is just a regular function. Let's consider this official example. With the help of the source code, we can see more details about the implementation and the running steps as follows:
wrapper=O1.__call__(wrapper)
Checking the implementation of __call__, we see that after this step, (the left hand side )wrapper becomes the object resulted by self.func(*self.args, *args, **newkeywords) Checking the creation of O1 in __new__, we know self.func is the function update_wrapper. It uses the parameter *args, the right hand side wrapper, as its 1st parameter. Checking the last step of update_wrapper, one can see the right hand side wrapper is returned, with some of attributes modified as needed.
we can set the range of textfield like this..
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
int setrange = 20;
return !([textField.text length]>setrange && [string length] > range.length);
}
If you need something simple; once and done callback
//multiple ajax calls above
var callback = function () {
if ($.active !== 0) {
setTimeout(callback, '500');
return;
}
//whatever you need to do here
//...
};
callback();
In [18]: a
Out[18]:
x1 x2
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
In [19]: a['x2'] = a.x2.shift(1)
In [20]: a
Out[20]:
x1 x2
0 0 NaN
1 1 5
2 2 6
3 3 7
4 4 8
This should do the trick:
mapper.readValue(fileReader, MyClass.class);
I say should because I'm using that with a String
, not a BufferedReader
but it should still work.
Here's my code:
String inputString = // I grab my string here
MySessionClass sessionObject;
try {
ObjectMapper objectMapper = new ObjectMapper();
sessionObject = objectMapper.readValue(inputString, MySessionClass.class);
Here's the official documentation for that call: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(java.lang.String, java.lang.Class)
You can also define a custom deserializer when you instantiate the ObjectMapper
:
http://wiki.fasterxml.com/JacksonHowToCustomDeserializers
Edit:
I just remembered something else. If your object coming in has more properties than the POJO
has and you just want to ignore the extras you'll want to set this:
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Or you'll get an error that it can't find the property to set into.
I think returning 0 for succ/1 for fail (glenn jackman) and olibre's clear and explanatory answer says it all; just to mention a kind of "combo" approach for cases where results are not binary and you'd prefer to set a variable rather than "echoing out" a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)
# Syntax _w (wrapReturn)
# arg1 : method to wrap
# arg2 : variable to set
_w(){
eval $1
read $2 <<EOF
$?
EOF
eval $2=\$$2
}
as in (yep, the example is somewhat silly, it's just an.. example)
getDay(){
d=`date '+%d'`
[ $d -gt 255 ] && echo "Oh no a return value is 0-255!" && BAIL=0 # this will of course never happen, it's just to clarify the nature of returns
return $d
}
dayzToSalary(){
daysLeft=0
if [ $1 -lt 26 ]; then
daysLeft=`expr 25 - $1`
else
lastDayInMonth=`date -d "`date +%Y%m01` +1 month -1 day" +%d`
rest=`expr $lastDayInMonth - 25`
daysLeft=`expr 25 + $rest`
fi
echo "Mate, it's another $daysLeft days.."
}
# main
_w getDay DAY # call getDay, save the result in the DAY variable
dayzToSalary $DAY
Here is a more complete implementation of command line execution.
executeCommand("ls");
Output:
12/27/2017 11:18:11:732: ls
12/27/2017 11:18:11:820: build.gradle
12/27/2017 11:18:11:820: gradle
12/27/2017 11:18:11:820: gradlew
12/27/2017 11:18:11:820: gradlew.bat
12/27/2017 11:18:11:820: out
12/27/2017 11:18:11:820: settings.gradle
12/27/2017 11:18:11:820: src
private void executeCommand(String command) {
try {
log(command);
Process process = Runtime.getRuntime().exec(command);
logOutput(process.getInputStream(), "");
logOutput(process.getErrorStream(), "Error: ");
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private void logOutput(InputStream inputStream, String prefix) {
new Thread(() -> {
Scanner scanner = new Scanner(inputStream, "UTF-8");
while (scanner.hasNextLine()) {
synchronized (this) {
log(prefix + scanner.nextLine());
}
}
scanner.close();
}).start();
}
private static SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss:SSS");
private synchronized void log(String message) {
System.out.println(format.format(new Date()) + ": " + message);
}
In your CSS file, such as App.css in a create-react-app, add a fontface import. For example:
@fontface {
font-family: 'Bungee Inline', cursive;
src: url('https://fonts.googleapis.com/css?family=Bungee+Inline')
}
Then simply add the font to the DOM element within the same css file.
body {
font-family: 'Bungee Inline', cursive;
}
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
In a class derived from UITextField, override at least this two methods:
- (CGRect)textRectForBounds:(CGRect)bounds;
- (CGRect)editingRectForBounds:(CGRect)bounds;
It might be as simple as this if you have no additional content:
return CGRectInset(bounds , 10, 10);
UITextField provides several positioning methods you can override.
Your script should look like:
prog1 &
prog2 &
.
.
progn &
wait
progn+1 &
progn+2 &
.
.
Assuming your system can take n jobs at a time. use wait to run only n jobs at a time.
I found this solution a while back, can't remember where but it still seems to work well for me.
Create a copy of Eclipse.app for each workspace you want to work in (for this example ProjectB.app), then open ProjectB.app/Contents/MacOS/eclipse.ini and add these two lines at the beginning of the file:
-data
/Users/eric/Workspaces/projectb
... substituting where your workspace is located. When you launch ProjectB.app it will automatically start with that workspace instead of prompting for a location, and you should be able to run it at the same time as other Eclipse instances with no problem.
This will work:
smegma$ curl http://www.wolframalpha.com/input/?i=14+divided+by+3 2>/dev/null | gawk 'match($0, /link to /input/\?i=([0-9.+-]+)/, ary) { print substr( $0, ary[1, "start"], ary[1, "length"] )}' 4.6666666666666666666666666666666666666666666666666666
Just substitute '14' and '3' with your numbers.
Be advised that if you're using nodejs there's (at the time of writing) a dependency on libssl 1.0.* - so installing an alternative SSL library will break your nodejs installation.
An alternative solution to installing a different SSL library is that posted in this answer here: https://stackoverflow.com/a/59927568/13564342 to instead install libcurl4-gnutls-dev
sudo apt install libcurl4-gnutls-dev
Since 
(html) is 0D
(hex), this can be represented as '\u000d'
str = str.replace(/\n/g, '\u000d');
Sharing with you guys an AngularJS filter that replaces \n
with that character thanks to the references in the other answers
app.filter('titleLineBreaker', function () {
return function (str) {
if (!str) {
return str;
}
return str.replace(/\n/g, '\u000d');
};
});
usage
<div title="{{ message | titleLineBreaker }}"> </div>
Use this its work fine for me to reload the same page:
<button onClick="window.location.reload();">
For CMake 3.8 and newer you can use
target_compile_features(target PUBLIC cxx_std_11)
shouldComponentUpdate(nextProps, nextState)
The code below uses @bound
annotations from ES.Next babel-plugin-transform-decorators-legacy
of BabelJS 6 and class-properties (the annotation sets this value on member functions similar to bind):
/*
© 2017-present Harald Rudell <[email protected]> (http://www.haraldrudell.com)
All rights reserved.
*/
import React, {Component} from 'react'
import {bound} from 'class-bind'
const m = 'Form'
export default class Parent extends Component {
state = {one: 'One', two: 'Two'}
@bound submit(e) {
e.preventDefault()
const values = {...this.state}
console.log(`${m}.submit:`, values)
}
@bound fieldUpdate({name, value}) {
this.setState({[name]: value})
}
render() {
console.log(`${m}.render`)
const {state, fieldUpdate, submit} = this
const p = {fieldUpdate}
return (
<form onSubmit={submit}> {/* loop removed for clarity */}
<Child name='one' value={state.one} {...p} />
<Child name='two' value={state.two} {...p} />
<input type="submit" />
</form>
)
}
}
class Child extends Component {
value = this.props.value
@bound update(e) {
const {value} = e.target
const {name, fieldUpdate} = this.props
fieldUpdate({name, value})
}
shouldComponentUpdate(nextProps) {
const {value} = nextProps
const doRender = value !== this.value
if (doRender) this.value = value
return doRender
}
render() {
console.log(`Child${this.props.name}.render`)
const {value} = this.props
const p = {value}
return <input {...p} onChange={this.update} />
}
}