The answer is to place the root dir to the location directives:
root /srv/www/ducklington.org/public_html;
I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).
Yes, LINQ can do this. It's simply:
MyList.Select(x => x.Name).ToArray();
Most likely the issue is that you either don't have a reference to System.Core
, or you are missing an using
directive for System.Linq
.
__FILE__
is the filename with extension of the file containing the code being executed.
In foo.rb
, __FILE__
would be "foo.rb".
If foo.rb
were in the dir /home/josh
then File.dirname(__FILE__)
would return /home/josh
.
In Windows 10, Windows Defender has a feature of core isolation which uses virtualisation technology that will also interupt in working of HAXM. Disable it and try again. In my case disabling it solved my issue.
Despite the existence of =begin
and =end
, the normal and a more correct way to comment is to use #
's on each line. If you read the source of any ruby library, you will see that this is the way multi-line comments are done in almost all cases.
If somebody experiences problems with ExifInterface
on Android 4.4 (KitKat) for getting the orientation, it might be because of wrong path got from the URI. See a solution for propoer getPath
in Stack Overflow question Get real path from URI, Android KitKat new storage access framework
Basing above suggestions from all, I was using xampp for running cgi scripts. Windows 8 it worked with out any changes, but Cent7.0 it was throwing errors like this as said above
AH01215: (2)No such file or directory: exec of '/opt/lampp/cgi-bin/pbsa_config.cgi' failed: /opt/lampp/cgi-bin/pbsa_config.cgi, referer: http://<>/MCB_HTML/TestBed.html
[Wed Aug 30 09:11:03.796584 2017] [cgi:error] [pid 32051] [client XX:60624] End of script output before headers: pbsa_config.cgi, referer: http://xx/MCB_HTML/TestBed.html
Try:
Disabled selinux
Given full permissions for script, but 755 will be ok
I finaly added like -w like below
#!/usr/bin/perl -w*
use CGI ':standard';
{
print header(),
...
end_html();
}
**-w** indictes enable all warnings.It started working, No idea why -w here.
Here is the SOLUTION
If you get Response:
bash: python: command not found
ORbash: conda: command not found
To the following Commands:
when you execute python
or python -V
conda
or conda --version
in your Git/Terminal window
Background: This is because you either
Solution:
At the command prompt, paste this command export PATH="$PATH:/c/Python36"
. That will tell Windows where to find Python. (This assumes that you installed it in C:\Python36)
If you installed python on your D drive, paste this command export PATH="$PATH:/d/Python36"
.
Then at the command prompt, paste python
or python -V
and you will see the version of Python installed and now you should not get Python 3.6.5
Assuming that it worked correctly you will want to set up git bash so that it always knows where to find python. To do that, enter the following command: echo 'export PATH="$PATH:/d/Python36"' > .bashrc
Permanent Solution
Go to BASH RC Source File (located on C: / C Drive in “C:\Users\myname”)
Make sure your BASH RC Source File is receiving direction from your Bash Profile Source File, you can do this by making sure that your BASH RC Source File contains this line of code: source ~/.bash_profile
Go to BASH Profile Source File (located on C: / C Drive in “C:\Users\myname”)
Enter line: export PATH="$PATH:/D/PROGRAMMING/Applications/PYTHON/Python365" (assuming this is the location where Python version 3.6.5 is installed)
This should take care of the problem permanently. Now whenever you open your Git Bash Terminal Prompt and enter “python
” or “python -V
” it should return the python version
Here is the solutions that worked for me:
index.php
from the htdocs
folderdashboard
with your database name.This should resolve the issue :-)
Panel with opacity:
public class GlassyPanel : Panel
{
const int WS_EX_TRANSPARENT = 0x20;
int opacity = 50;
public int Opacity
{
get
{
return opacity;
}
set
{
if (value < 0 || value > 100) throw new ArgumentException("Value must be between 0 and 100");
opacity = value;
}
}
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
using (var b = new SolidBrush(Color.FromArgb(opacity * 255 / 100, BackColor)))
{
e.Graphics.FillRectangle(b, ClientRectangle);
}
base.OnPaint(e);
}
}
The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.
Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as...
-> JUnit tests
.
Different use case, but set your session as the default session did the trick for me:
with sess.as_default():
result = compute_fn([seed_input,1])
This is one of these mistakes that is so obvious, once you have solved it.
My use-case is the following:
1) store keras VGG16 as tensorflow graph
2) load kers VGG16 as a graph
3) run tf function on the graph and get:
FailedPreconditionError: Attempting to use uninitialized value block1_conv2/bias
[[Node: block1_conv2/bias/read = Identity[T=DT_FLOAT, _class=["loc:@block1_conv2/bias"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](block1_conv2/bias)]]
[[Node: predictions/Softmax/_7 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_168_predictions/Softmax", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
>>> txt = '<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a> '
>>> fragment = bs4.BeautifulSoup(txt)
>>> fragment
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a>
>>> fragment.find('a', {'class': 'title'})
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a>
>>> fragment.find('a', {'class': 'title'}).string
u'Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)'
I found new Solution without any required certification to call curl only add two line code.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
In Start Menu, search for "mysql". Among the results, you should see the "MySQL Installer - Community". Run it.
MySQL Installer window will show up as shown below. Find "MySQL Server" under Product and click on "Reconfigure" link.
The MySQL Installer will show up (same one you used for the first MySQL Server installation). Go through all the steps.
After the MySQL Installer was finished, I started the MySQL service again. This time, the "Startup Message Log" on The MySQL Notifier was showing that the server started successfully:
https://www.howtosolutions.net/2017/08/fixing-mysql-10061-error-after-migration-of-database-files/
Try
mainScrollView.fullScroll(ScrollView.FOCUS_UP);
it should work.
Abstraction
and Encapsulation
by using a single generalized example------------------------------------------------------------------------------------------------------------------------------------
We all use calculator for calculation of complex problems !
Step over the next function(F10)
button beside Resume(F8)
in the upper top center of the chrome until you freeze the popup you want to see. The most portable regex would be ^[ \t\n]*$
to match an empty string (note that you would need to replace \t
and \n
with tab and newline accordingly) and [^ \n\t]
to match a non-whitespace string.
basename
does remove the directory prefix of a path:
$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example
Modules Preconditions:
The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (
precondition="managedHandler"
) only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />
If you remove the attribute
precondition="managedHandler"
, Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "
managedHandler
" precondition.To enable all managed modules to run for all requests without configuring each module entry to remove the "
managedHandler
" precondition, use therunAllManagedModulesForAllRequests
property in the<modules>
section:<modules runAllManagedModulesForAllRequests="true" />
When you use this property, the "
managedHandler
" precondition has no effect and all managed modules run for all requests.
Copied from IIS Modules Overview: Preconditions
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
This should do it:
<style>
body {
background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>
Git is probably already tracking the file.
From the gitignore docs:
To stop tracking a file that is currently tracked, use git rm --cached.
Use this, replacing [project]
and [username]
with your info:
git rm --cached [project].xcodeproj/project.xcworkspace/xcuserdata/[username].xcuserdatad/UserInterfaceState.xcuserstate
git commit -m "Removed file that shouldn't be tracked"
Alternatively you can use the -a
option to git commit
that will add all files that have been modified or deleted.
Once you've removed the file from git, it will respect your .gitignore
.
Generally speaking, jQuery plugins are namespaces on the jQuery scope. You could run a simple check to see if the namespace exists:
if(jQuery().pluginName) {
//run plugin dependent code
}
dateJs however is not a jQuery plugin. It modifies/extends the javascript date object, and is not added as a jQuery namespace. You could check if the method you need exists, for example:
if(Date.today) {
//Use the dateJS today() method
}
But you might run into problems where the API overlaps the native Date API.
This might be redundant but the above most voted answer says .then(function (success)
and that didn't work for me as of Angular version 1.5.8
. Instead use response
then inside the block response.data
got me my json data I was looking for.
$http({
method: 'get',
url: 'data/data.json'
}).then(function (response) {
console.log(response, 'res');
data = response.data;
},function (error){
console.log(error, 'can not get data.');
});
If you do a lot of set theoretic operations - you can also use Set::Scalar or similar module. Then $s = Set::Scalar->new( @array )
will build the Set for you - and you can query it with: $s->contains($m)
.
But I have declared that var in the top of the other files.
That's the problem. After all, this makes multiple declarations for the same name in the same (global) scope - which will throw an error with const
.
Instead, use var
, use only one declaration in your main file, or only assign to window.APP
exclusively.
Or use ES6 modules right away, and let your module bundler/loader deal with exposing them as expected.
I have approximately these problem. I need debug AngularJs application from Visual Studio 2013.
By default IIS Express restricted access to local files (like json).
But, first: JSON have JavaScript syntax.
Second: javascript files is allowed.
So:
rename JSON to JS (data.json->data.js
).
correct load command ($http.get('App/data.js').success(function (data) {...
load script data.js to page (<script src="App/data.js"></script>
)
Next use loaded data an usual manner. It is just workaround, of course.
You can use:
if not exist "C:\VTS\" mkdir "C:\VTS"
You can also expand the code to replace any missing expected files.
if not exist "C:\VTS\important.file" echo. > "C:\VTS\important.file"
UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.
If your project uses Maven you can simply include UCanAccess via the following coordinates:
groupId: net.sf.ucanaccess
artifactId: ucanaccess
The following is an excerpt from pom.xml
, you may need to update the <version>
to get the most recent release:
<dependencies>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies>
As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:
UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)
Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like
ucanaccess-4.0.1.jar
/lib/
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.6.jar
All you need to do is add all five (5) JARs to your project.
NOTE: Do not add
loader/ucanload.jar
to your build path if you are adding the other five (5) JAR files. TheUcanloadDriver
class is only used in special circumstances and requires a different setup. See the related answer here for details.
Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path...
. Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this
NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
After adding all five (5) JAR files the "Libraries" folder should look something like this:
IntelliJ IDEA: Choose File > Project Structure...
from the main menu. In the "Libraries" pane click the "Add" (+
) button and add the five (5) JAR files. Once that is done the project should look something like this:
Now "U Can Access" data in .accdb and .mdb files using code like this
// assumes...
// import java.sql.*;
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
System.out.println(rs.getString(1));
}
At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
If performance matters to you make sure you time:
import sys
import timeit
import pandas as pd
print('Python %s on %s' % (sys.version, sys.platform))
print('Pandas version %s' % pd.__version__)
repeat = 3
numbers = 100
def time(statement, _setup=None):
print (min(
timeit.Timer(statement, setup=_setup or setup).repeat(
repeat, numbers)))
print("Format %m/%d/%y")
setup = """import pandas as pd
import io
data = io.StringIO('''\
ProductCode,Date
''' + '''\
x1,07/29/15
x2,07/29/15
x3,07/29/15
x4,07/30/15
x5,07/29/15
x6,07/29/15
x7,07/29/15
y7,08/05/15
x8,08/05/15
z3,08/05/15
''' * 100)"""
time('pd.read_csv(data); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"]); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'infer_datetime_format=True); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'date_parser=lambda x: pd.datetime.strptime(x, "%m/%d/%y")); data.seek(0)')
print("Format %Y-%m-%d %H:%M:%S")
setup = """import pandas as pd
import io
data = io.StringIO('''\
ProductCode,Date
''' + '''\
x1,2016-10-15 00:00:43
x2,2016-10-15 00:00:56
x3,2016-10-15 00:00:56
x4,2016-10-15 00:00:12
x5,2016-10-15 00:00:34
x6,2016-10-15 00:00:55
x7,2016-10-15 00:00:06
y7,2016-10-15 00:00:01
x8,2016-10-15 00:00:00
z3,2016-10-15 00:00:02
''' * 1000)"""
time('pd.read_csv(data); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"]); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'infer_datetime_format=True); data.seek(0)')
time('pd.read_csv(data, parse_dates=["Date"],'
'date_parser=lambda x: pd.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")); data.seek(0)')
prints:
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28)
[Clang 6.0 (clang-600.0.57)] on darwin
Pandas version 0.23.4
Format %m/%d/%y
0.19123052499999993
8.20691274
8.143124389
1.2384357139999977
Format %Y-%m-%d %H:%M:%S
0.5238807110000039
0.9202787830000005
0.9832778819999959
12.002349824999996
So with iso8601-formatted date (%Y-%m-%d %H:%M:%S
is apparently an iso8601-formatted date, I guess the T can be dropped and replaced by a space) you should not specify infer_datetime_format
(which does not make a difference with more common ones either apparently) and passing your own parser in just cripples performance. On the other hand, date_parser
does make a difference with not so standard day formats. Be sure to time before you optimize, as usual.
this worked for me:
1.make a standards compliant link:
<a href="tel:1500100900">
2.replace it when mobile browser is not detected, for skype:
$("a.phone")
.each(function()
{
this.href = this.href.replace(/^tel/,
"callto");
});
Selecting link to replace via class seems more efficient.
Of course it works only on anchors with .phone
class.
I have put it in function if( !isMobile() ) { ...
so it triggers only when detects desktop browser. But this one is problably obsolete...
function isMobile() {
return (
( navigator.userAgent.indexOf( "iPhone" ) > -1 ) ||
( navigator.userAgent.indexOf( "iPod" ) > -1 ) ||
( navigator.userAgent.indexOf( "iPad" ) > -1 ) ||
( navigator.userAgent.indexOf( "Android" ) > -1 ) ||
( navigator.userAgent.indexOf( "webOS" ) > -1 )
);
}
A very simple method is to use apkanalyzer.
apkanalyzer manifest application-id "${_path_to_apk}"
You can specify multiple patterns in an array.
select-string VendorEnquiry,Failed C:\Logs
This works with -notmatch as well:
select-string -notmatch VendorEnquiry,Failed C:\Logs
I believe you need quotes around the model
:
JSON.stringify({ "model": source })
I know this question has been answered but the answers i found here didn't work for my scenario ( or for Windows ).
I am using windows 10 laptop with PHP 7.2 in Xampp v3.2.4.
$command = 'php Cron.php send_email "'. $id .'"';
if ( substr(php_uname(), 0, 7) == "Windows" )
{
//windows
pclose(popen("start /B " . $command . " 1> temp/update_log 2>&1 &", "r"));
}
else
{
//linux
shell_exec( $command . " > /dev/null 2>&1 &" );
}
This worked perfectly for me.
I hope it will help someone with windows. Cheers.
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>
For my fellow Googlers out there, here's a very simple plug-and-play solution that worked for me after struggling with the more complex solutions for a while:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ CONVERT(VARCHAR(10), projID )
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
Notice that I had to convert the ID into a VARCHAR in order to concatenate it as a string. If you don't have to do that, here's an even simpler version:
SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ projID
FROM returns
WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM
returns t
All credit for this goes to here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9508abc2-46e7-4186-b57f-7f368374e084/replicating-groupconcat-function-of-mysql-in-sql-server?forum=transactsql
How about:
<table>
<tr ng-repeat="(key, value) in data">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
</table>
This method is listed in the docs: https://docs.angularjs.org/api/ng/directive/ngRepeat
There are three major types of cloud services: IaaS, PaaS, and SaaS. You’ve probably seen these abbreviations on the websites of cloud providers. Before going into details, let’s compare IaaS, PaaS, and SaaS to transportation:
On-premises IT infrastructure is like owning a car. When you buy a car, you’re responsible for its maintenance, and upgrading means buying a new car.
IaaS is like leasing a car. When you lease a car, you choose the car you want and drive it wherever you wish, but the car isn’t yours. Want an upgrade? Just lease a different car!
PaaS is like taking a taxi. You don’t drive a taxi yourself, but simply tell the driver where you need to go and relax in the back seat.
SaaS is like going by bus. Buses have assigned routes, and you share the ride with other passengers.
<?php echo date('M j Y g:i A', strtotime('2013-11-15 13:01:02')); ?>
I wasn't able to get some of the other answers to work on Chrome, Firefox, IE11, and Edge with the same code. I came up with the below and it appears to work for those browsers listed above. I also wanted to see what OS the user was on. I haven't tested this against a browser with user overridden User-Agent settings, so mileage may vary. The order of the IFs is important for this to work correctly.
let os, osStore, bStore, appVersion, browser;
// Chrome
if(navigator.vendor === "Google Inc."){
appVersion = navigator.appVersion.split(" ");
os = [appVersion[1],appVersion[2],appVersion[3],appVersion[4],appVersion[5]].join(" ");
os = os.split("(")[1].split(")")[0]
browser = appVersion[appVersion.length-2].split("/").join(" ");
console.log("Browser:",browser,"- OS:",os);
}
// Safari
else if(navigator.vendor === "Apple Computer, Inc."){
appVersion = navigator.appVersion.split(" ");
os = [appVersion[1],appVersion[2],appVersion[3],appVersion[4],appVersion[5]].join(" ");
os = os.split("(")[1].split(")")[0];
browser = appVersion[appVersion.length-1].split("/").join(" ");
console.log("Browser:",browser,"- OS:",os);
}
// Firefox is seems the only browser with oscpu
else if(navigator.oscpu){
bStore = navigator.userAgent.split("; ").join("-").split(" ");
browser = bStore[bStore.length-1].replace("/"," ");
osStore = [bStore[1],bStore[2],bStore[3]].join(" ");
osStore = osStore.split("-");
osStore.pop(osStore.lastIndexOf)
osStore = osStore.join(" ").split("(");
os = osStore[1];
console.log("Browser:",browser,"- OS:",os);
}
// IE is seems the only browser with cpuClass
// MSIE 11:10 Mode
else if(navigator.appName === "Microsoft Internet Explorer"){
bStore = navigator.appVersion.split("; ");
browser = bStore[1]+" / "+bStore[4].replace("/"," ");
os = [bStore[2],bStore[3]].join(" ");
console.log("Browser:",browser,"- OS:",os);
}
// MSIE 11
else if(navigator.cpuClass){
bStore = navigator.appVersion.split("; ");
osStore = [bStore[0],bStore[1]].join(" ");
os = osStore.split("(")[1];
browser = "MSIE 11 "+bStore[2].split("/").join(" ");
console.log("Browser:",browser,"- OS:",os);
}
// Edge
else if(navigator.appVersion){
browser = navigator.appVersion.split(" ");
browser = browser[browser.length -1].split("/").join(" ");
os = navigator.appVersion.split(")")[0].split("(")[1];
console.log("Browser:",browser,"- OS:",os);
}
// Other browser
else {
console.log(JSON.stringify(navigator));
}
Here is a complete example showing how to use the **
operator to pass values from a dictionary as keyword arguments.
>>> def f(x=2):
... print(x)
...
>>> new_x = {'x': 4}
>>> f() # default value x=2
2
>>> f(x=3) # explicit value x=3
3
>>> f(**new_x) # dictionary value x=4
4
The options for popen
can be used in call
args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0
So...
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=myoutput)
Then you can do what you want with myoutput
(which would need to be a file btw).
Also, you can do something closer to a piped output like this.
dmesg | grep hda
would be:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
There's plenty of lovely, useful info on the python manual page.
Add this filter:
app.filter('unique', function () {
return function ( collection, keyname) {
var output = [],
keys = []
found = [];
if (!keyname) {
angular.forEach(collection, function (row) {
var is_found = false;
angular.forEach(found, function (foundRow) {
if (foundRow == row) {
is_found = true;
}
});
if (is_found) { return; }
found.push(row);
output.push(row);
});
}
else {
angular.forEach(collection, function (row) {
var item = row[keyname];
if (item === null || item === undefined) return;
if (keys.indexOf(item) === -1) {
keys.push(item);
output.push(row);
}
});
}
return output;
};
});
Update your markup:
<select ng-model="orderProp" >
<option ng-repeat="place in places | unique" value="{{place.category}}">{{place.category}}</option>
</select>
If you don't want to send the full modal structure you can replicate the old behaviour doing something like this:
// this is just an example, remember to adapt the selectors to your code!
$('.modal-link').click(function(e) {
var modal = $('#modal'), modalBody = $('#modal .modal-body');
modal
.on('show.bs.modal', function () {
modalBody.load(e.currentTarget.href)
})
.modal();
e.preventDefault();
});
I solved with these:
.card-img-top {
max-height: 20vh; /*not want to take all vertical space*/
object-fit: contain;/*show all image, autosized, no cut, in available space*/
}
JS provides the tools to do this the right way. Try the demo snippet.
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
this.classList.remove('mouse-down');_x000D_
alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling. It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px';
_x000D_
button{_x000D_
text-transform: uppercase;_x000D_
background-color:rgba(66, 66, 66,0.3);_x000D_
border:none;_x000D_
font-size:4em;_x000D_
color:white;_x000D_
-webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
-moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
-webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
-moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52); _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
display: flex;_x000D_
flex-flow: row nowrap ;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items: center;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
order:1;_x000D_
flex: 0 1 auto;_x000D_
align-self: auto;_x000D_
min-width: 0;_x000D_
min-height: auto;_x000D_
} _x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<meta name="description" content="3d Button Configuration" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<section id="box">_x000D_
<button>_x000D_
Submit_x000D_
</button>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
The answer is right, but it will add a listener that will be triggered every time a click occurs on your page. To avoid that, you can add the listener for just one time :
$('a#menu-link').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
$('#menu').toggleClass('open');
$(document).one('click', function closeMenu (e){
if($('#menu').has(e.target).length === 0){
$('#menu').removeClass('open');
} else {
$(document).one('click', closeMenu);
}
});
});
Edit: if you want to avoid the stopPropagation()
on the initial button you can use this
var $menu = $('#menu');
$('a#menu-link').on('click', function(e) {
e.preventDefault();
if (!$menu.hasClass('active')) {
$menu.addClass('active');
$(document).one('click', function closeTooltip(e) {
if ($menu.has(e.target).length === 0 && $('a#menu-link').has(e.target).length === 0) {
$menu.removeClass('active');
} else if ($menu.hasClass('active')) {
$(document).one('click', closeTooltip);
}
});
} else {
$menu.removeClass('active');
}
});
We can use the below npm module for this purpose:
You can update two tables in one query.
UPDATE Table1, Table2
SET Table1.LastName="DR. XXXXXX", Table2.WAprrs="start,stop"
WHERE Table1.id=Table2.id AND Table1.id="010008";
If you throw an exception without a variable (the second example) the StackTrace will include the original method that threw the exception.
In the first example the StackTrace will be changed to reflect the current method.
Example:
static string ReadAFile(string fileName) {
string result = string.Empty;
try {
result = File.ReadAllLines(fileName);
} catch(Exception ex) {
throw ex; // This will show ReadAFile in the StackTrace
throw; // This will show ReadAllLines in the StackTrace
}
Here is a version that expects a pathlib.Path
as input.
# Recusively copies the content of the directory src to the directory dst.
# If dst doesn't exist, it is created, together with all missing parent directories.
# If a file from src already exists in dst, the file in dst is overwritten.
# Files already existing in dst which don't exist in src are preserved.
# Symlinks inside src are copied as symlinks, they are not resolved before copying.
#
def copy_dir(src, dst):
dst.mkdir(parents=True, exist_ok=True)
for item in os.listdir(src):
s = src / item
d = dst / item
if s.is_dir():
copy_dir(s, d)
else:
shutil.copy2(str(s), str(d))
Note that this function requires Python 3.6, which is the first version of Python where os.listdir()
supports path-like objects as input. If you need to support earlier versions of Python, you can replace listdir(src)
by listdir(str(src))
.
In Firefox and Chrome (and possibly more) we can insert the string ‘( .... )’ into the alt text of an image that hasn’t loaded.
img {_x000D_
font-style: italic;_x000D_
color: #c00;_x000D_
}_x000D_
_x000D_
img:after {_x000D_
content: " (Image - Right click to reload if not loaded)";_x000D_
}_x000D_
_x000D_
img::after {_x000D_
content: " (Image - Right click to reload if not loaded)";_x000D_
}
_x000D_
<img alt="Alt text - " />
_x000D_
If you are here to just convert Timestamp into DateTime,
Timestamp timestamp = widget.firebaseDocument[timeStampfield];
DateTime date = Timestamp.fromMillisecondsSinceEpoch(
timestamp.millisecondsSinceEpoch).toDate();
Your deleted branches are not lost, they were copied into origin/contact_page and origin/new_pictures “remote tracking branches” by the fetch you showed (they were also pushed back out by the push you showed, but they were pushed into refs/remotes/origin/ instead of refs/heads/). Check git log origin/contact_page
and git log origin/new_pictures
to see if your local copies are “up to date” with whatever you think should be there. If any new commits were pushed onto those branches (from some other repo) between the fetch and push that you showed, you may have “lost” those (but probably you could probably find them in the other repo that most recently pushed those branches).
It looks like you are fetching in a normal, ‘remote mode’ (remote refs/heads/ are stored locally in refs/remotes/origin/), but pushing in ‘mirror mode’ (local refs/ are pushed onto remote refs/). Check your .git/config and reconcile the remote.origin.fetch
and remote.origin.push
settings.
Before trying any changes, make a simple tar or zip archive or your whole local repo. That way, if you do not like what happens, you can try again from a restored repo.
If you intend to use your remote repo as a mirror of your local one, do this:
git branch contact_page origin/contact_page &&
git branch new_pictures origin/new_pictures &&
git config remote.origin.fetch '+refs/*:refs/*' &&
git config --unset remote.origin.push &&
git config remote.origin.mirror true
You might also eventually want to do delete all your refs/remotes/origin/ refs, since they are not useful if you are operating in mirror mode (your normal branches take the place of the usual remote tracking branches).
But since it seems that you are using this remote repo with multiple “work” repos, you probably do not want to use mirror mode. You might try this:
git config push.default tracking &&
git config --unset remote.origin.push
git config --unset remote.origin.mirror
Then, you will eventually want to delete the bogus refs/remotes/origin refs in your remote repo: git push origin :refs/remotes/origin/contact_page :refs/remotes/origin/new_pictures …
.
Try git push --dry-run
to see what it git push
would do without having it make any changes on the remote repo. If you do not like what it says it is going to do, recover from your backup (tar/zip) and try the other option.
I found using css opacity is better for a simple show/hide hover, and you can add css3 transitions to make a nice finished hover effect. The transitions will just be dropped by older IE browsers, so it degrades gracefully to.
#stuff {
opacity: 0.0;
-webkit-transition: all 500ms ease-in-out;
-moz-transition: all 500ms ease-in-out;
-ms-transition: all 500ms ease-in-out;
-o-transition: all 500ms ease-in-out;
transition: all 500ms ease-in-out;
}
#hover {
width:80px;
height:20px;
background-color:green;
margin-bottom:15px;
}
#hover:hover + #stuff {
opacity: 1.0;
}
<div id="hover">Hover</div>
<div id="stuff">stuff</div>
Using underscore.js:
var foundObject = _.findWhere(jsObjects, {b: 6});
http://www.rtuin.nl/2013/02/how-to-make-git-ignore-different-line-endings/
echo "* -crlf" > .gitattributes
Do this on a separate commit or git might still see whole files as modified when you make a single change (depending on if you have changed autocrlf option)
This one really works. Git will respect the line endings in mixed line ending projects and not warning you about them.
The URI "file:///android_asset/"
points to YourProject/app/src/main/assets/
.
Note: android_asset/
uses the singular (asset) and src/main/assets
uses the plural (assets).
Suppose you have a file YourProject/app/src/main/assets/web_thing.html
that you would like to display in a WebView. You can refer to it like this:
WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/web_thing.html");
The snippet above could be located in your Activity class, possibly in the onCreate
method.
Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.
When a float
is passed to printf
, it is automatically converted to a double
. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...
), largely for historical reasons. Therefore, the “natural” specifier for a float
, %f
, must work with a double
argument. So the %f
and %lf
specifiers for printf
are the same; they both take a double
value.
When scanf
is called, pointers are passed, not direct values. A pointer to float
is not converted to a pointer to double
(this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf
, the argument for %f
must be a pointer to float
, and the argument for %lf
must be a pointer to double
.
You could alter the figsize
by passing a tuple
showing the width, height
parameters you would like to keep.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
EDIT
I remember answering a similar question of yours where you had to set the index as TIMESTAMP
. So, you could then do something like below:
df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)
For the head
of the dataframe you posted, the plot would look like:
You could concat the 2 variables together into a sortkey and use that for your comparison.
list.sort(function(a,b){
var aCat = a.var1 + a.var2;
var bCat = b.var1 + b.var2;
return (aCat > bCat ? 1 : aCat < bCat ? -1 : 0);
});
Looking onto this issue Github - Request/Upload progress handling via @angular/http, angular2 http does not support file upload yet.
For very basic file upload I created such service function as a workaround (using ???????'s answer):
uploadFile(file:File):Promise<MyEntity> {
return new Promise((resolve, reject) => {
let xhr:XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(<MyEntity>JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
xhr.open('POST', this.getServiceUrl(), true);
let formData = new FormData();
formData.append("file", file, file.name);
xhr.send(formData);
});
}
You have 2 options here:
Assign a default value to each primary constructor parameter:
data class Activity(
var updated_on: String = "",
var tags: List<String> = emptyList(),
var description: String = "",
var user_id: List<Int> = emptyList(),
var status_id: Int = -1,
var title: String = "",
var created_at: String = "",
var data: HashMap<*, *> = hashMapOf<Any, Any>(),
var id: Int = -1,
var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
)
Declare a secondary constructor that has no parameters:
data class Activity(
var updated_on: String,
var tags: List<String>,
var description: String,
var user_id: List<Int>,
var status_id: Int,
var title: String,
var created_at: String,
var data: HashMap<*, *>,
var id: Int,
var counts: LinkedTreeMap<*, *>
) {
constructor() : this("", emptyList(),
"", emptyList(), -1,
"", "", hashMapOf<Any, Any>(),
-1, LinkedTreeMap<Any, Any>()
)
}
If you don't rely on copy
or equals
of the Activity
class or don't use the autogenerated data class
methods at all you could use regular class like so:
class ActivityDto {
var updated_on: String = "",
var tags: List<String> = emptyList(),
var description: String = "",
var user_id: List<Int> = emptyList(),
var status_id: Int = -1,
var title: String = "",
var created_at: String = "",
var data: HashMap<*, *> = hashMapOf<Any, Any>(),
var id: Int = -1,
var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
}
Not every DTO needs to be a data class
and vice versa. In fact in my experience I find data classes to be particularly useful in areas that involve some complex business logic.
df.write.mode('overwrite').parquet("/output/folder/path")
works if you want to overwrite a parquet file using python. This is in spark 1.6.2. API may be different in later versions
The simplest and safest way to split a string using new lines, regardless of format (CRLF, LFCR or LF), is to remove all carriage return characters and then split on the new line characters. "text".replace(/\r/g, "").split(/\n/);
This ensures that when you have continuous new lines (i.e. \r\n\r\n
, \n\r\n\r
, or \n\n
) the result will always be the same.
In your case the code would look like:
(function ($) {
$(document).ready(function () {
$('#data').submit(function (e) {
var ks = $('#keywords').val().replace(/\r/g, "").split(/\n/);
e.preventDefault();
alert(ks[0]);
$.each(ks, function (k) {
alert(k);
});
});
});
})(jQuery);
Here are some examples that display the importance of this method:
var examples = ["Foo\r\nBar", "Foo\r\n\r\nBar", "Foo\n\r\n\rBar", "Foo\nBar\nFooBar"];_x000D_
_x000D_
examples.forEach(function(example) {_x000D_
output(`Example "${example}":`);_x000D_
output(`Split using "\n": "${example.split("\n")}"`);_x000D_
output(`Split using /\r?\n/: "${example.split(/\r?\n/)}"`);_x000D_
output(`Split using /\r\n|\n|\r/: "${example.split(/\r\n|\n|\r/)}"`);_x000D_
output(`Current method: ${example.replace(/\r/g, "").split("\n")}`);_x000D_
output("________");_x000D_
});_x000D_
_x000D_
function output(txt) {_x000D_
console.log(txt.replace(/\n/g, "\\n").replace(/\r/g, "\\r"));_x000D_
}
_x000D_
This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:
using System.Text.RegularExpressions;
/*
00123 => 123
00000 => 0
00000a => 0a
00001a => 1a
00001a => 1a
0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
*/
Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
var strs = new string[]
{
"00123",
"00000",
"00000a",
"00001a",
"00001a",
"0000132423423424565443546546356546454654633333a",
};
foreach (string str in strs)
{
Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
}
And this regex will remove leading zeroes anywhere inside string:
new Regex(@"(?<!\d)0+(?=\d)");
// "0000123432 d=0 p=002 3?0574 m=600"
// => "123432 d=0 p=2 3?574 m=600"
To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:
history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is
This will add an entry in the browser history. You could also consider replaceState
if you don't wan't to add a new entry and just want to replace the old entry.
WHERE MyColumn = COALESCE(@value,MyColumn)
If @value
is NULL
, it will compare MyColumn
to itself, ignoring
@value = no where
clause.
IF @value
has a value (NOT NULL
) it will compare MyColumn
to
@value
.
Reference: COALESCE (Transact-SQL).
I think flatMap()
is what you're looking for.
For example:
List<AClass> allTheObjects = map.values()
.stream()
.flatMap(listContainer -> listContainer.lst.stream())
.collect(Collectors.toList());
While I was able to solve this problem in one computer following the other users solutions, the command netsh
didn't solve the issue in one of my machines and even though the current user had administrator rights I was still getting the "HTTP could not register URL.... Your process does not have access rights to this namespace". So I'm sharing my solution in case you still don't get it to work with the other solutions too.
After also trying to give write permissions to the user in the physical directory of my website and getting no success, I finally decided trying to change IIS settings.
As the images below show, I configured the Physical Path Credentials of my website to connect as an specifc user, which was an admin account with DOMAIN\username and password, and this was enough to make the error disapear.
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Set<String> a = this;
Set<String> b = o;
Set<String> thedifference_a_b = new HashSet<String>(a);
thedifference_a_b.removeAll(b);
if(thedifference_a_b.isEmpty() == false) return false;
Set<String> thedifference_b_a = new HashSet<String>(b);
thedifference_b_a.removeAll(a);
if(thedifference_b_a.isEmpty() == false) return false;
return true;
}
Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId
I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.
Most of the above solutions are not mobile friendly.
The solution I am proposing detects if its not touch device and that the navbar-toggle
(hamburger menu) is not visible and makes the parent menu item revealing submenu on hover and and follow its link on click
Also makes tne margin-top 0 because the gap between the navbar and the menu in some browser will not let you hover to the subitems
$(function(){_x000D_
function is_touch_device() {_x000D_
return 'ontouchstart' in window // works on most browsers _x000D_
|| navigator.maxTouchPoints; // works on IE10/11 and Surface_x000D_
};_x000D_
_x000D_
if(!is_touch_device() && $('.navbar-toggle:hidden')){_x000D_
$('.dropdown-menu', this).css('margin-top',0);_x000D_
$('.dropdown').hover(function(){ _x000D_
$('.dropdown-toggle', this).trigger('click').toggleClass("disabled"); _x000D_
}); _x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="nav" class="nav nav-pills clearfix right" role="tablist">_x000D_
<li><a href="#">menuA</a></li>_x000D_
<li><a href="#">menuB</a></li>_x000D_
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>_x000D_
<ul id="products-menu" class="dropdown-menu clearfix" role="menu">_x000D_
<li><a href="">A</a></li>_x000D_
<li><a href="">B</a></li>_x000D_
<li><a href="">C</a></li>_x000D_
<li><a href="">D</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">menuD</a></li>_x000D_
<li><a href="#">menuE</a></li>_x000D_
</ul>
_x000D_
$(function(){_x000D_
$("#nav .dropdown").hover(_x000D_
function() {_x000D_
$('#products-menu.dropdown-menu', this).stop( true, true ).fadeIn("fast");_x000D_
$(this).toggleClass('open');_x000D_
},_x000D_
function() {_x000D_
$('#products-menu.dropdown-menu', this).stop( true, true ).fadeOut("fast");_x000D_
$(this).toggleClass('open');_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="nav" class="nav nav-pills clearfix right" role="tablist">_x000D_
<li><a href="#">menuA</a></li>_x000D_
<li><a href="#">menuB</a></li>_x000D_
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">menuC</a>_x000D_
<ul id="products-menu" class="dropdown-menu clearfix" role="menu">_x000D_
<li><a href="">A</a></li>_x000D_
<li><a href="">B</a></li>_x000D_
<li><a href="">C</a></li>_x000D_
<li><a href="">D</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a href="#">menuD</a></li>_x000D_
<li><a href="#">menuE</a></li>_x000D_
</ul>
_x000D_
As per Apple's documentation:
(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;
Description:
Tells a child controller its appearance is about to change.
If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke viewWillAppear:
, viewWillDisappear:
, viewDidAppear:
, or viewDidDisappear:
directly.
(void)endAppearanceTransition;
Description:
Tells a child controller its appearance has changed. If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.
Sample code:
(void)applicationDidEnterBackground:(UIApplication *)application
{
[self.window.rootViewController beginAppearanceTransition: NO animated: NO]; // I commented this line
[self.window.rootViewController endAppearanceTransition]; // I commented this line
}
Question: How I fixed?
Ans: I found this piece of lines in application. This lines made my app not recieving any ViewWillAppear notification's. When I commented these lines it's working fine.
setnames
from the data.table
package will work on data.frame
s or data.table
s
library(data.table)
d <- data.frame(a=1:2,b=2:3,d=4:5)
setnames(d, old = c('a','d'), new = c('anew','dnew'))
d
# anew b dnew
# 1 1 2 4
# 2 2 3 5
Note that changes are made by reference, so no copying (even for data.frames!)
If you can live with 01 for January instead of 1, then try...
d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")
You can check the docs for other formatting directives.
This button post to the current page while at the same time opens OtherPage.aspx
in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />
Unfortunately the switch option to mount a volume is only found in the run
command.
docker run --help
-v, --volume list Bind mount a volume (default [])
There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.
docker container export -o ./myimage.docker mycontainer
docker import ./myimage.docker myimage
docker run -i -t -v /somedir --name mycontainer myimage /bin/bash
Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)
Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.
Read The official Docs of collection
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
Oneline compilation example http://ideone.com/MJJwtc
If you tried the above options and no success, also you're using IIS (iisnode) to host your node app, putting this code on web.config resolved the problem for me:
Here is the reference: https://www.inflectra.com/support/knowledgebase/kb306.aspx
Also, you can chagne the length allowed because now I think its 2GB. Modify it by your needs.
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...
string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
//You have it ...
}
select top(3) min(Name),TotalSalary,ROW_NUMBER() OVER (Order by TotalSalary desc) AS RowNumber FROM tbl_EmployeeProfile group by TotalSalary
If you're using ctx.drawImage()
function, you can do the following:
var img = loadImage('../yourimage.png', callback);
function loadImage(src, callback) {
var img = new Image();
img.onload = callback;
img.setAttribute('crossorigin', 'anonymous'); // works for me
img.src = src;
return img;
}
And in your callback you can now use ctx.drawImage
and export it using toDataURL
This works to zoom into an area more then drop a pin: https://www.google.com/maps/@30.2,17.9820525,9z
And the params are:
@lat,lng,zoom
Uninstall the app, and re-install and it should work!
<!--Customize button -->
<LinearGradientBrush x:Key="Buttongradient" StartPoint="0.500023,0.999996" EndPoint="0.500023,4.37507e-006">
<GradientStop Color="#5e5e5e" Offset="1" />
<GradientStop Color="#0b0b0b" Offset="0" />
</LinearGradientBrush>
<Style x:Key="hhh" TargetType="{x:Type Button}">
<Setter Property="Background" Value="{DynamicResource Buttongradient}"/>
<Setter Property="Foreground" Value="White" />
<Setter Property="FontSize" Value="15" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0.5">
<Border.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="2"></DropShadowEffect>
</Border.Effect>
<Grid>
<Path Width="9" Height="16.5" Stretch="Fill" Fill="#000" HorizontalAlignment="Left" Margin="16.5,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z " Opacity="0.2">
</Path>
<Path x:Name="PathIcon" Width="8" Height="15" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z ">
<Path.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="5"></DropShadowEffect>
</Path.Effect>
</Path>
<Line HorizontalAlignment="Left" Margin="40,0,0,0" Name="line4" Stroke="Black" VerticalAlignment="Top" Width="2" Y1="0" Y2="640" Opacity="0.5" />
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#E59400" />
<Setter Property="Foreground" Value="White" />
<Setter TargetName="PathIcon" Property="Fill" Value="Black" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="OrangeRed" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
For someone who had the same problem I solved by pressing CTRL + SHIFT + DELETE to delete just the entire browser cache. Now I can access my localhost website on HTTP protocol.
Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.
I was looking for this:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
EDIT: As others have pointed out, use slice(-5)
instead of substr
. However, see the .split().pop()
solution at the bottom of this answer for another approach.
Original answer:
You'll want to use the Javascript string method .substr()
combined with the .length
property.
var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // => "1"
This gets the characters starting at id.length - 5 and, since the second argument for .substr() is omitted, continues to the end of the string.
You can also use the .slice()
method as others have pointed out below.
If you're simply looking to find the characters after the underscore, you could use this:
var tabId = id.split("_").pop(); // => "Tabs1"
This splits the string into an array on the underscore and then "pops" the last element off the array (which is the string you want).
Okay here some more complex sample for the use of For /F
:: Main
@prompt -$G
call :REGQUERY "Software\Classes\CLSID\{3E6AE265-3382-A429-56D1-BB2B4D1D}"
@goto :EOF
:REGQUERY
:: Checks HKEY_LOCAL_MACHINE\ and HKEY_CURRENT_USER\
:: for the key and lists its content
@call :EXEC "REG QUERY HKCU\%~1"
@call :EXEC "REG QUERY "HKLM\%~1""
@goto :EOF
:EXEC
@set output=
@for /F "delims=" %%i in ('%~1 2^>nul') do @(
set output=%%i
)
@if not "%output%"=="" (
echo %1 -^> %output%
)
@goto :EOF
I packed it into the sub function :EXEC so all of its nasty details of implementation doesn't litters the main script. So it got some kinda some batch tutorial. Notes 'bout the code:
echo %1 -^>...
so there ^ makes it possible the output a '>' via echo what else wouldn't have been possible.@if not "%output%"==""
looks like in most common programming languages - it's maybe different that you expected (if you're not used to MS-batch). Well remove the '@' at the beginning. Study the output. Change it tonot %output%==""
-rerun and consider why this doesn't work. ;)I got away with simply using two if tags, thought I'd add an answer in case it's of use to anyone else:
<c:if test="${condition}">
...
</c:if>
<c:if test="${!condition}">
...
</c:if>
whilst technically not an if-else
per se, the behaviour is the same and avoids the clunky approach of using the choose
tag, so depending on how complex your requirement is this might be preferable.
1.press esc to enter the command mode 2.perss l(it L in lowcase) to show the line number
To change the Modal position in the viewport you can target the Modal div id, in this example this id is myModal3
<div id="modal3" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
#myModal3 {
top:5%;
right:50%;
outline: none;
overflow:hidden;
}
If you are familiar with Maven there also rpm-maven-plugin
which simplifies making RPMs: you have to write only pom.xml
which will be then used to build RPM. RPM build environment is created implicitly by the plugin.
You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)
Simplified ES6 version of @joshcomley's answer with an example.
No JQuery, No library, No eval, No DOM change, Just pure Javascript.
http://plnkr.co/edit/MMegiu?p=preview
var setInnerHTML = function(elm, html) {
elm.innerHTML = html;
Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
const newScript = document.createElement("script");
Array.from(oldScript.attributes)
.forEach( attr => newScript.setAttribute(attr.name, attr.value) );
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
oldScript.parentNode.replaceChild(newScript, oldScript);
});
}
Usage
$0.innerHTML = HTML; // does *NOT* run <script> tags in HTML
setInnerHTML($0, HTML); // does run <script> tags in HTML
When I encountered this exception, I solved this by using Run Configurations... panel as picture shows below.Especially, at JRE tab, the VM Arguments are the critical
( "-Xmx1024m -Xms512m -XX:MaxPermSize=1024m -XX:PermSize=512m" ).
The "evil" answer did not work for me. Instead, I used what was recommended on the JSHints docs page. If you know the warning that is thrown, you can turn it off for a block of code. For example, I am using some third party code that does not use camel case functions, yet my JSHint rules require it, which led to a warning. To silence it, I wrote:
/*jshint -W106 */
save_state(id);
/*jshint +W106 */
You need to define operator <
for the Class1.
Map needs to compare the values using operator < and hence you need to provide the same when user defined class are used as key.
class Class1
{
public:
Class1(int id);
bool operator <(const Class1& rhs) const
{
return id < rhs.id;
}
private:
int id;
};
I'd recommend using a regular expressions instead of string operations for this:
Set fso = CreateObject("Scripting.FileSystemObject")
filename = "C:\VBS\filediprova.txt"
newtext = vbLf & "<tr><td><a href=""..."">Beginning_of_DD_TC5</a></td></tr>"
Set re = New RegExp
re.Pattern = "(\n.*?Test Case \d)"
re.Global = False
re.IgnoreCase = True
text = f.OpenTextFile(filename).ReadAll
f.OpenTextFile(filename, 2).Write re.Replace(text, newText & "$1")
The regular expression will match a line feed (\n
) followed by a line containing the string Test Case
followed by a number (\d
), and the replacement will prepend that with the text you want to insert (variable newtext
). Setting re.Global = False
makes the replacement stop after the first match.
If the line breaks in your text file are encoded as CR-LF
(carriage return + line feed) you'll have to change \n
into \r\n
and vbLf
into vbCrLf
.
If you have to modify several text files, you could do it in a loop like this:
For Each f In fso.GetFolder("C:\VBS").Files
If LCase(fso.GetExtensionName(f.Name)) = "txt" Then
text = f.OpenAsTextStream.ReadAll
f.OpenAsTextStream(2).Write re.Replace(text, newText & "$1")
End If
Next
This is what worked for me for IE 11+, Firefox and Chrome. In safari it downloads a file but as unknown and the filename is not set.
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([csvDataString]); //csv data string as an array.
// IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, fileName);
} else {
var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document for FireFox
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(csvDataString),
target: '_blank',
download: fileName
})[0].click();
anchor.remove();
}
sub.data<-data[ data[,1] != "b" & data[,1] != "d" & data[,1] != "e" , ]
Larger but simple to understand (I guess) and can be used with multiple columns, even with !is.na( data[,1])
.
You would first make a variable: for example: D = 1. Then Do This but replace the string with whatever you want:
D = 1
print("Here is a number!:",D)
No you can not do that, MyClass *myclass
will define a pointer (memory for the pointer is allocated on stack) which is pointing at a random memory location. Trying to use this pointer will cause undefined behavior.
In C++, you can create objects either on stack or heap like this:
MyClass myClass;
myClass.DoSomething();
Above will allocate myClass on stack (the term is not there in the standard I think but I am using for clarity). The memory allocated for the object is automatically released when myClass
variable goes out of scope.
Other way of allocating memory is to do a new
. In that case, you have to take care of releasing the memory by doing delete
yourself.
MyClass* p = new MyClass();
p->DoSomething();
delete p;
Remeber the delete
part, else there will be memory leak.
I always prefer to use the stack allocated objects whenever possible as I don't have to be bothered about the memory management.
If you don't want the overhead of WindowManagers, Points, or Displays, you can grab the height and width attributes of the topmost View item in your XML, provided its height and width are set to match_parent. (This is true so long as your layout takes up the entire screen.)
For example, if your XML starts with something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/entireLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
Then findViewById(R.id.entireLayout).getWidth()
will return the screen's width and findViewById(R.id.entireLayout).getHeight()
will return the screen's height.
OS X tends to prefix the system account names with "_"; you don't say what version of OS X you're using, but at least in 10.8 and 10.9 the _postgres user exists in a default install. Note that you won't be able to su
to this account (except as root), since it doesn't have a password. sudo -u _postgres
, on the other hand, should work fine.
replace() does not operate in-place, you need to assign its result to something. Also, for a more concise syntax, you could supplant your for loop with a one-liner: hello_no_spaces = map(lambda x: x.replace(' ', ''), hello)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "USER_ID")
Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> receiver;
}
public class Notification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "NOTIFICATION_ID")
Long notificationId;
@Column(name = "TEXT")
String text;
@Column(name = "ALERT_STATUS")
@Enumerated(EnumType.STRING)
AlertStatus alertStatus = AlertStatus.NEW;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SENDER_ID")
@JsonIgnore
User sender;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "RECEIVER_ID")
@JsonIgnore
User receiver;
}
What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..
User model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
List<Notification> sender;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
List<Notification> receiver;
Notification model:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
List<Notification> **sender**;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
List<Notification> **receiver**;
I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.
Put file inside while True
like so
while True:
f = open('torecv.png','wb')
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print "Receiving..."
l = c.recv(1024)
while (l):
print "Receiving..."
f.write(l)
l = c.recv(1024)
f.close()
print "Done Receiving"
c.send('Thank you for connecting')
c.close()
Taken from Burhan Khalid's answer and his comment about migrations: what worked for me was removing the content of the "migrations" folder along with the database, and then running manage.py migrate. Removing the database is not enough because of the saved information about table structure in the migrations folder.
You mean like this?
void foo ( int i ) {
if ( i < 0 ) return; // do nothing
// do something
}
I believe you are having the same problem here.
The sheet must be active before you can select a range on it.
Also, don't omit the sheet name qualifier:
Sheets("BxWsn Simulation").Select
Sheets("BxWsn Simulation").Range("Result").Select
Or,
With Sheets("BxWsn Simulation")
.Select
.Range("Result").Select
End WIth
which is the same.
Will it not be much better if we make one step further. Assuming every 3200 year as no leap year, the length of the year will come
364.999696 + 1/3200 = 364.999696 + .0003125 = 365.0000085
and after this the adjustment will be required after around 120000 years.
Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath
method . E.g.
File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block
Be careful on:
Header add Access-Control-Allow-Origin "*"
This is not judicious at all to grant access to everybody. It's preferable to allow a list of know trusted host only...
Header add Access-Control-Allow-Origin "http://aaa.example"
Header add Access-Control-Allow-Origin "http://bbb.example"
Header add Access-Control-Allow-Origin "http://ccc.example"
Regards,
Another solution is to use this library:
https://github.com/3846masa/axios-cookiejar-support
which integrates "Tough Cookie" support in to Axios. Note that this approach still requires the withCredentials
flag.
A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;
@Entity
public class Purchase {
private Date date;
@Column
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
// force java.sql.Timestamp to be set as a java.util.Date
this.date = new Date(date.getTime());
}
}
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Sometimes this can also happen when you have a stored procedure being called with parameters. For example, if you type something like:
set @runProc = 'dbo.StoredProcedure'
exec @runProc
This will work, However:
set @runProc = 'dbo.StoredProcedure ''foods'''
exec @runProc
This will throw the error "could not find stored procedure dbo.StoredProcedure 'foods'", however this can easily be overcome with parantheses like so:
set @runProc = 'exec dbo.StoredProcedure ''foods'''
exec (@runProc)
There can be an even simpler representation assuming that one has to only test graph algorithms not use them(graph) else where. This can be as a map from vertices to their adjacency lists as shown below :-
#include<bits/stdc++.h>
using namespace std;
/* implement the graph as a map from the integer index as a key to the adjacency list
* of the graph implemented as a vector being the value of each individual key. The
* program will be given a matrix of numbers, the first element of each row will
* represent the head of the adjacency list and the rest of the elements will be the
* list of that element in the graph.
*/
typedef map<int, vector<int> > graphType;
int main(){
graphType graph;
int vertices = 0;
cout << "Please enter the number of vertices in the graph :- " << endl;
cin >> vertices;
if(vertices <= 0){
cout << "The number of vertices in the graph can't be less than or equal to 0." << endl;
exit(0);
}
cout << "Please enter the elements of the graph, as an adjacency list, one row after another. " << endl;
for(int i = 0; i <= vertices; i++){
vector<int> adjList; //the vector corresponding to the adjacency list of each vertex
int key = -1, listValue = -1;
string listString;
getline(cin, listString);
if(i != 0){
istringstream iss(listString);
iss >> key;
iss >> listValue;
if(listValue != -1){
adjList.push_back(listValue);
for(; iss >> listValue; ){
adjList.push_back(listValue);
}
graph.insert(graphType::value_type(key, adjList));
}
else
graph.insert(graphType::value_type(key, adjList));
}
}
//print the elements of the graph
cout << "The graph that you entered :- " << endl;
for(graphType::const_iterator iterator = graph.begin(); iterator != graph.end(); ++iterator){
cout << "Key : " << iterator->first << ", values : ";
vector<int>::const_iterator vectBegIter = iterator->second.begin();
vector<int>::const_iterator vectEndIter = iterator->second.end();
for(; vectBegIter != vectEndIter; ++vectBegIter){
cout << *(vectBegIter) << ", ";
}
cout << endl;
}
}
In a separate terminal, connect your device to the computer and run the following commands:
react-native start
cd user/Library/Android/sdk/platform-tools/
./adb reverse tcp:8081 tcp:8081
Application terminal:
react-native run-android
install apk on your device from this location android/app/build/outputs/apk/app-debug.apk
If you are using localhost
and PHP set to this to solve the issue:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
From your front-end use:
{headers: {"Content-Type": "application/json"}}
and boom no more issues from localhost
!
This is expected.
Refer to Javadocs for split
.
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Maybe what you want is just plain old predefined variables.
Consider trying
$_SERVER['REQUEST_URI'']
Or read more here.
from types import MethodType
def method(self):
print 'hi!'
setattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )
With this, you can use the self pointer
In handlebar version 3.0 onwards,
{{#each users as |user userId|}}
Id: {{userId}} Name: {{user.name}}
{{/each}}
In this particular example, user will have the same value as the current context and userId will have the index value for the iteration. Refer - http://handlebarsjs.com/block_helpers.html in block helpers section
I came into the same situation. As a workaround, I just created a view
(If you have privileges) and described it and dropped it later. :)
If you have a string variable, you must convert it to a regex, so MongoDb will use a like statement on it.
const name = req.query.title; //John
db.users.find({ "name": new Regex(name) });
Is the same result as:
db.users.find({"name": /John/})
A hard reset will also resolve the problem
git reset --hard origin/master
First make sure that DataTable is not null and than check for the row count
if(dt!=null)
{
if(dt.Rows.Count>0)
{
//do your code
}
}
If you want to use C++ streams rather than C functions, you can do the following:
int ar[] = { 20, 30, 40, 50, 60, 70, 80, 90 };
const int siz_ar = sizeof(ar) / sizeof(int);
for (int i = 0; i < siz_ar; ++i)
cout << ar[i] << " ";
cout << endl;
for (int i = 0; i < siz_ar; ++i)
cout << hex << setfill('0') << setw(2) << ar[i] << " ";
cout << endl;
Very simple.
Output:
20 30 40 50 60 70 80 90
14 1e 28 32 3c 46 50 5a
To extrapolate on Felix Kling's comment, you can use .filter()
like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() === "json") { // if extension is .json
return null; // skip
} else {
return img.src;
}
}).filter(Boolean);
That will remove falsey values from the array that is returned by .map()
You could simplify it further like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() !== "json") { // if extension is .json
return img.src;
}
}).filter(Boolean);
Or even as a one-liner using an arrow function, object destructuring and the &&
operator:
var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);
Setting cookie in the express is easy
npm install cookie parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
console.dir(req.cookies.cookieName)
element.GetAttribute("value");
Eventhough if you don't see the "value" attribute in html dom, you will get the field value displayed on the GUI.
Git will not store the password when you use URLs like that. Instead, it will just store the username, so it only needs to prompt you for the password the next time. As explained in the manual, to store the password, you should use an external credential helper. For Windows, you can use the Windows Credential Store for Git. This helper is also included by default in GitHub for Windows.
When using it, your password will automatically be remembered, so you only need to enter it once. So when you clone, you will be asked for your password, and then every further communication with the remote will not prompt you for your password again. Instead, the credential helper will provide Git with the authentication.
This of course only works for authentication via https; for ssh access ([email protected]/repository.git
) you use SSH keys and those you can remember using ssh-agent
(or PuTTY’s pageant if you’re using plink).
lookup = 'the dog barked'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
print 'found at line:', num
I tried changing the padding
and margin
and well as the width
and height
, and then finally found that if you just increase the scale it'll work:
input[type=checkbox] {
transform: scale(1.5);
}
To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).
You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:
On the machine with Mosquitto Server running,
On the outside-word machine with mqtt-spy running,
I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really.
And also to my knowledge to run the mosquitto_sub
and mosquitto_pub
you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,
sudo apt-get install mosquitto-clients
You could use a couple approaches. First would be to use the strong tag
Here is an <strong>example of that tag</strong>.
Another approach would be to use the font-weight property. You can achieve inline, or via a class or id. Let's say you're using a class.
.className {
font-weight: bold;
}
Alternatively, you can also use a hard value for font-weight and most fonts support a value between 300 and 700, incremented by 100. For example, the following would be bold:
.className {
font-weight: 700;
}
SELECT DOB AS Birthdate ,
YEAR(GETDATE()) AS ThisYear,
YEAR(getdate()) - YEAR(DOB) AS Age
FROM tableprincejain
One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?
Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...
<div id="checkboxes">
<input type="checkbox" /> Some label<br />
<input type="checkbox" /> Some other label<br />
</div>
<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>
Based on this markup your jquery could bind to the click
event of the button and manipulate the DOM.
$('#addCheckbox').click(function() {
var text = $('#newCheckText').val();
$('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});
In my case,
but still I was getting the error as lombok is incompatible and getter and setters was not recognized. with further checking I found that recently my intelliJ version got upgraded and the old Lombok plugin is not compatible.
Go to Preference -> Plugins -> Search lombok and update
OR
Go to Preference -> Plugins -> Search lombok-> Uninstall restart IDE and install again from MarketPlace
This saved my life--->
set this line
ListView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
Then in your manifest in activity tag type this-->
<activity android:windowSoftInputMode="adjustPan">
Your usual intent
The difference between "" and () is:
With "" you are not calling anything.
With () you are calling a sub.
Example with sub:
Sub = MsgBox("Msg",vbYesNo,vbCritical,"Title")
Select Case Sub
Case = vbYes
MsgBox"You said yes"
Case = vbNo
MsgBox"You said no"
End Select
vs Normal:
MsgBox"This is normal"
Looking at the requirement you have, the below command shall help:
service nginx status
You might want to use grep "$(echo -e '\t')"
Only requirement is echo
to be capable of interpretation of backslash escapes.
Found the solution:
UltraPictureBox1.Image = _
My.Resources.ResourceManager.GetObject(object_name_as_string)
Make sure that your sas.png
is marked as Build Action: Content
and Copy To Output Directory: Copy Always
in its Visual Studio Properties
...
I think the C# source code goes like this...
Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;
and XAML should be
<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="image1" Stretch="Fill" VerticalAlignment="Top"
Source="../Bilder/sas.png"
Width="350" />
EDIT
Dynamically I think XAML would provide best way to load Images ...
<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
x:Name="MyImage"/>
where image.DataContext
is string
path.
MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";
public class MyImageSourceConverter : IValueConverter
{
public object Convert(object value_, Type targetType_,
object parameter_, System.Globalization.CultureInfo culture_)
{
return (new ImageSourceConverter()).ConvertFromString (value.ToString());
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now as you set a different data context, Image
would be automatically loaded at runtime.
for whom wants to do this in kotlin:
val timer = fixedRateTimer(period = 1000L) {
val currentTime: Date = Calendar.getInstance().time
runOnUiThread {
tvFOO.text = currentTime.toString()
}
}
for stopping the timer you can use this:
timer.cancel()
this function has many other options, give it a try
This can be done. For example with Firefox
CSS
#hlinks {
-moz-binding: url(stackexchange.xml#hlinks);
}
stackexchange.xml
<bindings xmlns="http://www.mozilla.org/xbl"
xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="hlinks">
<content>
<children/>
<html:a href="/privileges">privileges</html:a>
<html:span class="lsep"> | </html:span>
<html:a href="/users/logout">log out</html:a>
</content>
</binding>
</bindings>
I found a simple way to convert multilevel array into one. I use the function "http_build_query" which converts the array into a url string. Then, split the string with explode and decode the value.
Here is a sample.
$converted = http_build_query($data);
$rows = explode('&', $converted);
$output = array();
foreach($rows AS $k => $v){
list($kk, $vv) = explode('=', $v);
$output[ urldecode($kk) ] = urldecode($vv);
}
return $output;
If you need to get that in a program with Python on a Linux system for reproducibility:
with open('/proc/driver/nvidia/version') as f:
version = f.read().strip()
print(version)
gives:
NVRM version: NVIDIA UNIX x86_64 Kernel Module 384.90 Tue Sep 19 19:17:35 PDT 2017
GCC version: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)
Use java-google-translate-text-to-speech instead of Google Translate API v2 Java.
Api unofficial with the main features of Google Translate in Java.
It also provide text to speech api. If you want to translate the text "Hello!" in Romanian just write:
Translator translate = Translator.getInstance();
String text = translate.translate("Hello!", Language.ENGLISH, Language.ROMANIAN);
System.out.println(text); // "Buna ziua!"
As @r0ast3d correctly said:
Important: Google Translate API v2 is now available as a paid service. The courtesy limit for existing Translate API v2 projects created prior to August 24, 2011 will be reduced to zero on December 1, 2011. In addition, the number of requests your application can make per day will be limited.
This is correct: just see the official page:
Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.
BUT, java-google-translate-text-to-speech is FREE!
I've created a sample application that demonstrates that this works. Try it here: https://github.com/IonicaBizau/text-to-speech
In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.
You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.
if (a === undefined || a === null || a==='') {
console.log("Nothing");
} else {
console.log("Something");
}
Also I want to point out one more thing.
What will be the result of Boolean(0)?
Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.
If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this
devServer: {
contentBase: path.join(__dirname, './dist'),
compress: true,
host: 'localhost',
// host: '0.0.0.0',
port: 8080,
disableHostCheck: true //for ngrok
},
I'm creating html5 mobile apps and I noticed that the idle
, bounds_changed
and tilesloaded
events fire when the map object is created and rendered (even if it is not visible).
To make my map run code when it is shown for the first time I did the following:
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject is created and rendered
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
//this part runs when the mapobject shown for the first time
});
});
Press Ctrl-a then : and then type
scrollback 10000
to get a 10000 line buffer, for example.
You can also set the default number of scrollback lines by adding
defscrollback 10000
to your ~/.screenrc
file.
To scroll (if your terminal doesn't allow you to by default), press Ctrl-a ESC and then scroll (with the usual Ctrl-f for next page or Ctrl-a for previous page, or just with your mouse wheel / two-fingers). To exit the scrolling mode, just press ESC.
Another tip: Ctrl-a i shows your current buffer setting.
Maybe it's the comma in your if
condition.
function answers() {
var answer=document.getElementById("mySelect");
if(answer[answer.selectedIndex].value == "To measure time.") {
alert("That's correct!");
}
}
You can also write it like this.
function answers(){
document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}
Based on Ray Nicholus's answer :
inputElement.onchange = function(event) {
var fileList = inputElement.files;
//TODO do something with fileList.
}
using this will also work :
inputElement.onchange = function(event) {
var fileList = event.target.files;
//TODO do something with fileList.
}
I'd say yes - because virtually all existing (at least all non-trivial) javascript code would break if a browser's javascript engine were to run it asynchronously.
Add to that the fact that HTML5 already specifies Web Workers (an explicit, standardized API for multi-threading javascript code) introducing multi-threading into the basic Javascript would be mostly pointless.
(Note to others commenters: Even though setTimeout/setInterval
, HTTP-request onload events (XHR), and UI events (click, focus, etc.) provide a crude impression of multi-threadedness - they are still all executed along a single timeline - one at a time - so even if we don't know their execution order beforehand, there's no need to worry about external conditions changing during the execution of an event handler, timed function or XHR callback.)
One additional thought on some of the comments above that talks about ordered delivery.... It must be clarified that the destination computer may receive packets out of order on the wire, but the TCP at the destination is responsible for "rearranging out-of-order data" before passing it on to the upper layers of the stack. When you say TCP guarantees ordered packet delivery, what that means is it will deliver packets in correct order to the upper layers of the stack.
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];
///// called event
-(IBAction)Back_btn:(id)sender
{
//Your code here
}
SWIFT:
var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)
var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true
var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton
func back_btn(_ sender: Any) {
//Your code here
}
For a search routine you should look to use Find
, AutoFilter
or variant array approaches. Range loops are nomally too slow, worse again if they use Select
The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2
which you can then further process
Option Explicit
Const strText As String = "%"
Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
With Application
lAppCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
If Not cel1 Is Nothing Then
Set rng2 = cel1
strFirstAddress = cel1.Address
Do
Set cel1 = rng1.FindNext(cel1)
Set rng2 = Union(rng2, cel1)
Loop While strFirstAddress <> cel1.Address
End If
If Not rng2 Is Nothing Then
For Each cel2 In rng2
Debug.Print cel2.Address & " contained " & strText
Next
Else
MsgBox "No " & strText
End If
With Application
.ScreenUpdating = True
.Calculation = lAppCalc
End With
End Sub
var str = "This is a single quote: ' and so is this: '";
console.log(str);
var replaced = str.replace(/'/g, "\\'");
console.log(replaced);
Gives you:
This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'
Following @Erfan's good answer, most of the times in an analysis of aggregate values you want the unique possible combinations of these existing character values:
unique_chars = lambda x: ', '.join(x.unique())
(df
.groupby(['A'])
.agg({'C': unique_chars}))
Maybe someone will be interested in my solution:
class Version private constructor(private val versionString: String) : Comparable<Version> {
private val major: Int by lazy { versionString.split(".")[0].toInt() }
private val minor: Int by lazy { versionString.split(".")[1].toInt() }
private val patch: Int by lazy {
val splitArray = versionString.split(".")
if (splitArray.size == 3)
splitArray[2].toInt()
else
0
}
override fun compareTo(other: Version): Int {
return when {
major > other.major -> 1
major < other.major -> -1
minor > other.minor -> 1
minor < other.minor -> -1
patch > other.patch -> 1
patch < other.patch -> -1
else -> 0
}
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is Version) return false
return compareTo(other) == 0
}
override fun hashCode(): Int {
return major * minor * patch
}
companion object {
private fun doesContainsVersion(string: String): Boolean {
val versionArray = string.split(".")
return versionArray.size in 2..3
&& versionArray[0].toIntOrNull() != null
&& versionArray[1].toIntOrNull() != null
&& (versionArray.size == 2 || versionArray[2].toIntOrNull() != null)
}
fun from(string: String): Version? {
return if (doesContainsVersion(string)) {
Version(string)
} else {
null
}
}
}
}
Usage:
val version1 = Version.from("3.2")
val version2 = Version.from("3.2.1")
version1 <= version2
Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.
The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.
Pass a selector to the jQuery parents function:
d.parents('.a').attr('id')
EDIT Hmm, actually Slaks's answer is superior if you only want the closest ancestor that matches your selector.
For VS 2019, this should work without installing anything:
//#region MyRegion1
foo() {
}
//#endregion
//#region MyRegion2
bar() {
}
//#endregion
Just use an <a>
by itself, set it to display: block;
and set width
and height
. Get rid of the <span>
and <div>
. This is the semantic way to do it. There is no need to wrap things in <divs>
(or any element) for layout. That is what CSS is for.
Demo: http://jsfiddle.net/ThinkingStiff/89Enq/
HTML:
<a id="music" href="Music.html">Music I Like</a>
CSS:
#music {
background-color: black;
color: white;
display: block;
height: 40px;
line-height: 40px;
text-decoration: none;
width: 100px;
text-align: center;
}
Output:
Suppose you want to backup a database by executing a batch file from within a C# code. Here is a fully working solution that deals with blank spaces inside the path. This works in Windows. I have not tested it with mono though.
C# code:
public bool BackupDatabase()
{
bool res = true;
string file = "db.bat";
if (!File.Exists(file)) return false;
BackupPaths.ForEach(path =>
{
Directory.CreateDirectory(path);
string filePath = Path.Combine(path, string.Format("{0}_{1}.bak", Util.ConvertDateTimeToFileName(false), DatabaseName));
Process process = new Process();
process.StartInfo.FileName = file;
process.StartInfo.Arguments = string.Format(" {0} {1} \\\"{2}\\\""
, DBServerName
, DatabaseName
, filePath);
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
try
{
process.Start();
process.WaitForExit();
}
catch (Exception ee)
{
Logger.Log(ee);
res = false;
}
});
return res;
}
and here is the batch file:
@echo OFF
set DB_ServerName=%1
set Name_of_Database=%2
set PathToBackupLocation=%3
echo Server Name = '%DB_ServerName%'
echo Name of Database = '%Name_of_Database%'
echo Path To Backup Location = '%PathToBackupLocation%'
osql -S %DB_ServerName% -E -Q "BACKUP DATABASE %Name_of_Database% TO DISK=%PathToBackupLocation%"
This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment.
public class PostData
{
private List<PostDataParam> m_Params;
public List<PostDataParam> Params
{
get { return m_Params; }
set { m_Params = value; }
}
public PostData()
{
m_Params = new List<PostDataParam>();
// Add sample param
m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));
}
/// <summary>
/// Returns the parameters array formatted for multi-part/form data
/// </summary>
/// <returns></returns>
public string GetPostData()
{
// Get boundary, default is --AaB03x
string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();
StringBuilder sb = new StringBuilder();
foreach (PostDataParam p in m_Params)
{
sb.AppendLine(boundary);
if (p.Type == PostDataParamType.File)
{
sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
sb.AppendLine("Content-Type: text/plain");
sb.AppendLine();
sb.AppendLine(p.Value);
}
else
{
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
sb.AppendLine();
sb.AppendLine(p.Value);
}
}
sb.AppendLine(boundary);
return sb.ToString();
}
}
public enum PostDataParamType
{
Field,
File
}
public class PostDataParam
{
public PostDataParam(string name, string value, PostDataParamType type)
{
Name = name;
Value = value;
Type = type;
}
public string Name;
public string FileName;
public string Value;
public PostDataParamType Type;
}
To send the data you then need to:
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";
PostData pData = new PostData();
byte[] buffer = encoding.GetBytes(pData.GetPostData());
// Set content length of our data
oRequest.ContentLength = buffer.Length;
// Dump our buffered postdata to the stream, booyah
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();
// get the response
oResponse = (HttpWebResponse)oRequest.GetResponse();
Hope thats clear, i've cut and pasted from a few sources to get that tidier.
.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.
What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.
<input type="radio" name="gender" value="male"<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>: "checked='checked'" %> >Male
<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>
Adding on to Kalyoyan's answer, this subscription is tied to the router and will live until the page is fully refreshed. When subscribing to router events in a component, be sure to unsubscribe in ngOnDestroy:
import { OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from "rxjs/Rx";
class MyAppComponent implements OnDestroy {
private subscription: Subscription;
constructor(router: Router) {
this.subscription = router.events.subscribe(s => {
if (s instanceof NavigationEnd) {
const tree = router.parseUrl(router.url);
if (tree.fragment) {
const element = document.querySelector("#" + tree.fragment);
if (element) { element.scrollIntoView(element); }
}
}
});
}
public ngOnDestroy() {
this.subscription.unsubscribe();
}
}
I think simplest would be use numpy
here. For example you can read a file as bytes and then expand it to bits easily like this:
Bytes = numpy.fromfile(filename, dtype = "uint8")
Bits = numpy.unpackbits(Bytes)
Please be carefull with the usage of autoSizeColumn()
. It can be used without problems on small files but please take care that the method is called only once (at the end) for each column and not called inside a loop which would make no sense.
Please avoid using autoSizeColumn()
on large Excel files. The method generates a performance problem.
We used it on a 110k rows/11 columns file. The method took ~6m to autosize all columns.
For more details have a look at: How to speed up autosizing columns in apache POI?
You could use JavaScript and trigger the hidden file input when the button input has been clicked.
http://jsfiddle.net/gregorypratt/dhyzV/ - simple
http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery
Or, you could style a div directly over the file input and set pointer-events
in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events
A few snippets from the HTML5 spec: http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async
The defer and async attributes must not be specified if the src attribute is not present.
There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.
If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:
The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.
To count zeroes:
df[df == 0].count(axis=0)
To count NaN:
df.isnull().sum()
or
df.isna().sum()
Just wanted to add to an old thread to hopefully aid other people. I needed programmatically add a cert to the firefox database using a GPO, this was how I did it for Windows
1, First download and unzip the precompiled firefox NSS nss-3.13.5-nspr-4.9.1-compiled-x86.zip
2, Add the cert manually to firefox Options-->Advanced--Certificates-->Authorities-->Import
3, from the downloaded NSS package, run
certutil -L -d c:\users\[username]\appdata\roaming\mozilla\firefox\[profile].default
4, The above query will show you the certificate name and Trust Attributes e.g.
my company Ltd CT,C,C
5, Delete the certificate in step 2. Options-->Advanced--Certificates-->Authorities-->Delete
6, Create a powershell script using the information from step 4 as follows. This script will get the users profile path and add the certificate. This only works if the user has one firefox profile (need somehow to retrieve the users firefox folder profile name)
#Script adds Radius Certificate to independent Firefox certificate store since the browser does not use the Windows built in certificate store
#Get Firefox profile cert8.db file from users windows profile path
$ProfilePath = "C:\Users\" + $env:username + "\AppData\Roaming\Mozilla\Firefox\Profiles\"
$ProfilePath = $ProfilePath + (Get-ChildItem $ProfilePath | ForEach-Object { $_.Name }).ToString()
#Update firefox cert8.db file with Radius Certificate
certutil -A -n "UK my company" -t "CT,C,C" -i CertNameToAdd.crt -d $ProfilePath
7, Create GPO as a User Configuration to run the PowerShell script
Hope that helps save someone time
You can also use HeapWalker from the Netbeans Profiler or the Visual VM stand-alone tool. Visual VM is a good alternative to JHAT as it is stand alone, but is much easier to use than JHAT.
You need Java 6+ to fully use Visual VM.
Evidently, Eclipse does not automatically know where the source code for the dependent jars are. It is not clear why debugger could not inspect variables once the source was attached. One possibility is incorrect/incompatible source.
Assuming you have a maven project and the sources of the dependencies are downloaded and available in the local repository, you may want to install m2eclipse, the maven eclipse plugin and see if that helps in addressing your issue.
This way is easiest one in my opinion.
var nameList = new Array('item1','item2','item3','item4');
// Using for loop to loop through each item to check if item exist.
for (var i = 0; i < nameList.length; i++) {
if (nameList[i] === 'item1')
{
alert('Value exist');
}else{
alert('Value doesn\'t exist');
}
And Maybe Another way to do it is.
nameList.forEach(function(ItemList)
{
if(ItemList.name == 'item1')
{
alert('Item Exist');
}
}
Possible Suggestions to make it work:
Some modifications (U forgot to include a semicolon in the statement this.getName=function(){...}
it should be this.getName=function(){...};
)
function Customer(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}
(This might be one of the problem.)
and
Make sure U Link the JS files in the correct order
<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>
You can use this function:
UIImageWriteToSavedPhotosAlbum(UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo);
You only need completionTarget, completionSelector and contextInfo if you want to be notified when the UIImage
is done saving, otherwise you can pass in nil
.
See the official documentation for UIImageWriteToSavedPhotosAlbum()
.
File > Settings > Editor > Code Style > Java > Tabs and Indents > Use tab character
Substitute weapon of choice for Java as required.
Use subprocess.Popen()
with the close_fds=True
parameter, which will allow the spawned subprocess to be detached from the Python process itself and continue running even after Python exits.
https://gist.github.com/yinjimmy/d6ad0742d03d54518e9f
import os, time, sys, subprocess
if len(sys.argv) == 2:
time.sleep(5)
print 'track end'
if sys.platform == 'darwin':
subprocess.Popen(['say', 'hello'])
else:
print 'main begin'
subprocess.Popen(['python', os.path.realpath(__file__), '0'], close_fds=True)
print 'main end'
$('#test').click(function() {_x000D_
var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
check your build directory gracefully all the files will be available in the build folder.
asset-manifest.json
favicon.ico
manifest.json
robots.txt
static assets
index.html
precache-manifest.ddafca92870314adfea99542e1331500.js service-worker.js
4.copy the build folder to your apache server i.e /var/www/html
sudo cp -rf build /var/www/html
go to sites-available directory
cd /etc/apache2/sites-available/
open 000-default.conf file
sudo vi 000-default.conf and rechange the DocumentRoot path
Now goto apache conf.
cd /etc/aapche2
sudo vi apache2.conf
add the given snippet
<Directory /var/www/html>_x000D_
_x000D_
Options Indexes FollowSymLinks_x000D_
_x000D_
AllowOverride All_x000D_
_x000D_
Require all granted_x000D_
_x000D_
</Directory>
_x000D_
make a file inside /var/www/html/build
sudo vi .htaccess
Options -MultiViews_x000D_
_x000D_
RewriteEngine On_x000D_
_x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
_x000D_
RewriteRule ^ index.html [QSA,L]
_x000D_
9.sudo a2enmod rewrite
10.sudo systemctl restart apache2
restart apache server
sudo service apache2 restart
thanks, enjoy your day