For your case, add the following code to vscode's settings.json
.
"python.linting.pylintArgs": [
"--init-hook='import sys; sys.path.append(\"~/google-cloud-sdk/platform/google_appengine/lib\")'"
]
For the other who got troubles with pip packages, you can go with
"python.linting.pylintArgs": [
"--init-hook='import sys; sys.path.append(\"/usr/local/lib/python3.7/dist-packages\")'"
]
You should replace python3.7
above with your python version.
In case you are using node.js (with express)
If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:
app.use(express.static("public"));
Where app is:
const express = require("express");
const app = express();
Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)
Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.
After you add them change the stylesheet accordingly. For example if it was:
href="cssFileName.css"
and
src="imgName.png"
Make them:
href="css/cssFileName.css"
src="css/images/imgName.png"
That should work
I found some issue about that kind of error
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
Nothing wrong with your method, it's a G-mail security issue.
Login g-mail account settings.
Enable 2-step verification.
Use new-generated password in place of your real g-mail password.
Don't forget to clear cache.
php artisan config:cache.
php artisan config:clear.
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=generatedAppPassword
MAIL_ENCRYPTION=tls
I experienced this exception, and it was also related to ServicePointManager.SecurityProtocol
.
For me, this was because ServicePointManager.SecurityProtocol
had been set to Tls | Tls11
(because of certain websites the application visits with broken TLS 1.2) and upon visiting a TLS 1.2-only website (tested with SSLLabs' SSL Report), it failed.
An option for .NET 4.5 and higher is to enable all TLS versions:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
What helped me... changing sendmail parameters from -bs to -t.
'sendmail' => '/your/sendmail/path -t',
From Apple documentation
If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible. In addition, your communication through higher-level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. If you try to make a connection that doesn't follow this requirement, an error is thrown. If your app needs to make a request to an insecure domain, you have to specify this domain in your app's Info.plist file.
To Bypass App Transport Security:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourserver.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
To allow all insecure domains
<key>NSAppTransportSecurity</key>
<dict>
<!--Include to allow all connections (DANGER)-->
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Read More: Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11
If you are using email password then you should replace it with app password.for setting APP password you need to enable the 2 step authentication before setting password which can be disabled later.
Also make sure that you have allowed less secure app in setting section.For additional info you can follow how to here
Using NSExceptionDomains
may not apply an effect simultaneously due to target site may load resources (e.g. js
files) from external domains over http
. It can be resolved by adding these external domains to NSExceptionDomains
as well.
To inspect which resources cannot be loaded try to use Remote debugging. Here is a tutorial: http://geeklearning.io/apache-cordova-and-remote-debugging-on-ios/
Update Answer (after wwdc 2016):
IOS apps will require secure HTTPS connections by the end of 2016
App Transport Security, or ATS, is a feature that Apple introduced in iOS 9. When ATS is enabled, it forces an app to connect to web services over an HTTPS connection rather than non secure HTTP.
However, developers can still switch ATS off and allow their apps to send data over an HTTP connection as mentioned in above answers. At the end of 2016, Apple will make ATS mandatory for all developers who hope to submit their apps to the App Store. link
It seems that you need to pass a flag "-l, --log-file"
https://github.com/elastic/kibana/issues/3407
Usage: kibana [options]
Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for Elasticsearch.
Options:
-h, --help output usage information
-V, --version output the version number
-e, --elasticsearch <uri> Elasticsearch instance
-c, --config <path> Path to the config file
-p, --port <port> The port to bind to
-q, --quiet Turns off logging
-H, --host <host> The host to bind to
-l, --log-file <path> The file to log to
--plugins <path> Path to scan for plugins
If you use the init script to run as a service, maybe you will need to customize it.
Look up: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html
From AuthenticationManagerConfiguration.java looking at code, I see below. Also the in-memory configuration is a fallback if no authentication manager is provided as per Javadoc. Your earlier attempt of Injecting the Authentication Manager would work because you will no longer be using the In-memory authentication and this class will be out of picture.
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
if (auth.isConfigured()) {
return;
}
User user = this.securityProperties.getUser();
if (user.isDefaultPassword()) {
logger.info("\n\nUsing default security password: " + user.getPassword()
+ "\n");
}
Set<String> roles = new LinkedHashSet<String>(user.getRole());
withUser(user.getName()).password(user.getPassword()).roles(
roles.toArray(new String[roles.size()]));
setField(auth, "defaultUserDetailsService", getUserDetailsService());
super.configure(auth);
}
If you use inmemory authentication which is default, customize your logger configuration for org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration and remove this message.
I have solved as plist file.
This happened to me when an web request endpoint was switched to another server that accepted TLS1.2 requests only. Tried so many attempts mostly found on Stackoverflow like
The exception received did no make justice to the actual problem I was facing and found no help from the service operator.
To solve this I have to add a new Cipher Suite TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 I have used IIS Crypto 2.0 Tool from here as shown below.
write direct password into config>database.php
'password' => env('DB_PASSWORD', '')
Change to
'password' => 'your password',
My problem was with TIMEZONE
in emulator genymotion. Change TIMEZONE ANDROID EMULATOR
equal TIMEZONE SERVER
, solved problem.
It might be that you are forgetting to specify the settings which was the case with me.
Try:
mvn clean install -s settings_file.xml
It happens to me also.
It is because when we edit the
.env
file we need to restart the server. Just stop the currentphp artisan serve
and start it once again. This will work for sure.
If still not worked try doing php artisan config:cache
HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.
The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.
Had the same problem, it turned out it was the WindowsFirewall blocking connections. Try to disable WindowsFirewall for a while to see if helps and if it is the problem open ports as needed.
Even the latest jQuery has that line, so you have these options:
I think number 2 is the most sensible course of action in this case.
By the way if you haven't already tried, try this out: $.ajaxSetup({async:true});
, but I don't think it will work.
As of Socket.IO 1.0 (May 2014), all connections begin with an HTTP polling request (more info here). That means that in addition to forwarding WebSocket traffic, you need to forward any transport=polling
HTTP requests.
The solution below should redirect all socket traffic correctly, without redirecting any other traffic.
Enable the following Apache2 mods:
sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
Use these settings in your *.conf file (e.g. /etc/apache2/sites-available/mysite.com.conf
). I've included comments to explain each piece:
<VirtualHost *:80>
ServerName www.mydomain.com
# Enable the rewrite engine
# Requires: sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
# In the rules/conds, [NC] means case-insensitve, [P] means proxy
RewriteEngine On
# socket.io 1.0+ starts all connections with an HTTP polling request
RewriteCond %{QUERY_STRING} transport=polling [NC]
RewriteRule /(.*) http://localhost:3001/$1 [P]
# When socket.io wants to initiate a WebSocket connection, it sends an
# "upgrade: websocket" request that should be transferred to ws://
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /(.*) ws://localhost:3001/$1 [P]
# OPTIONAL: Route all HTTP traffic at /node to port 3001
ProxyRequests Off
ProxyPass /node http://localhost:3001
ProxyPassReverse /node http://localhost:3001
</VirtualHost>
I've included an extra section for routing /node
traffic that I find handy, see here for more info.
If you're curious which protocols .NET supports, you can try HttpClient out on https://www.howsmyssl.com/
// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");
File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);
// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");
The result is damning:
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
As Eddie explains above, you can enable better protocols manually:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?
In my case, the application context is not loaded because I add @DataJpaTest
annotation. When I change it to @SpringBootTest
it works.
@DataJpaTest
only loads the JPA part of a Spring Boot application. In the JavaDoc:
Annotation that can be used in combination with
@RunWith(SpringRunner.class)
for a typical JPA test. Can be used when a test focuses only on JPA components. Using this annotation will disable full auto-configuration and instead apply only configuration relevant to JPA tests.By default, tests annotated with
@DataJpaTest
will use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource). The@AutoConfigureTestDatabase
annotation can be used to override these settings. If you are looking to load your full application configuration, but use an embedded database, you should consider@SpringBootTest
combined with@AutoConfigureTestDatabase
rather than this annotation.
Check your elasticsearch.yml, "transport.host" property must be "0.0.0.0" not "127.0.0.1" or "localhost"
I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:
"Cannot install at this time".
Finally Zillan's link helped me to get apple documentation. So, check:
ax.init.itunes.apple.com
is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load). As soon as I changed the proxy it installed completely. Hope it will help someone.
Your json contains an array, but you're trying to parse it as an object.
This error occurs because objects must start with {
.
You have 2 options:
You can get rid of the ShopContainer
class and use Shop[]
instead
ShopContainer response = restTemplate.getForObject(
url, ShopContainer.class);
replace with
Shop[] response = restTemplate.getForObject(url, Shop[].class);
and then make your desired object from it.
You can change your server to return an object instead of a list
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
replace with
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
new ShopContainer(list));
I had this problem when using X2Go. The problem happened in a folder that was shared between the remote computer and my local PC.
Solution: cd out of that folder and in again. That fixed it.
I used version 2.4.0 of socket.io in easyRTC and used the following code in server_ssl.js which worked for me
io = require("socket.io")(webServer, {
handlePreflightRequest: (req, res) => {
res.writeHead(200, {
"Access-Control-Allow-Origin": req.headers.origin,
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Host, Authorization",
"Access-Control-Allow-Credentials": true,
"Access-Control-Max-Age":86400
});
res.end();
}
});
It could be because of the property pageable -> pageSizes: true
.
Remove this and check again.
This happened to me when using ng-include, and the included page had controllers defined. Apparently that's not supported.
You could use python JayDeBeApi package to create DB-API connection from Hive or Impala JDBC driver and then pass the connection to pandas.read_sql function to return data in pandas dataframe.
import jaydebeapi
# Apparently need to load the jar files for the first time for impala jdbc driver to work
conn = jaydebeapi.connect('com.cloudera.hive.jdbc41.HS2Driver',
['jdbc:hive2://host:10000/db;AuthMech=1;KrbHostFQDN=xxx.com;KrbServiceName=hive;KrbRealm=xxx.COM', "",""],
jars=['/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/HiveJDBC41.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/TCLIServiceClient.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-codec-1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_metastore.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_service.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/log4j-1.2.14.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/ql.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/zookeeper-3.4.6.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/ImpalaJDBC41.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/TCLIServiceClient.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/commons-codec-1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/hive_metastore.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/hive_service.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/log4j-1.2.14.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/ql.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/zookeeper-3.4.6.jar'
])
# the previous call have initialized the jar files, technically this call needs not include the required jar files
impala_conn = jaydebeapi.connect('com.cloudera.impala.jdbc41.Driver',
['jdbc:impala://host:21050/db;AuthMech=1;KrbHostFQDN=xxx.com;KrbServiceName=impala;KrbRealm=xxx.COM',"",""],
jars=['/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/HiveJDBC41.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/TCLIServiceClient.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-codec-1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_metastore.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/hive_service.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/log4j-1.2.14.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/ql.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/hive_jdbc_2.5.18.1050/2.5.18.1050 GA/Cloudera_HiveJDBC41_2.5.18.1050/zookeeper-3.4.6.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/ImpalaJDBC41.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/TCLIServiceClient.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/commons-codec-1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/commons-logging-1.1.1.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/hive_metastore.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/hive_service.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/httpclient-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/httpcore-4.1.3.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/libfb303-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/libthrift-0.9.0.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/log4j-1.2.14.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/ql.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-api-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/slf4j-log4j12-1.5.11.jar',
'/hadp/opt/jdbc/impala_jdbc_2.5.35/2.5.35.1055 GA/Cloudera_ImpalaJDBC41_2.5.35/zookeeper-3.4.6.jar'
])
import pandas as pd
df1 = pd.read_sql("SELECT * FROM tablename", conn)
df2 = pd.read_sql("SELECT * FROM tablename", impala_conn)
conn.close()
impala_conn.close()
Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.
Here is the code - The code is in asp.net core 2.0 but should work in above versions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
namespace UnityAssets.Website.Services
{
public class EmailSender : IEmailSender
{
public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
{
var email = new MimeMessage();
email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
email.Subject = subject;
var body = new BodyBuilder
{
HtmlBody = htmlMessage
};
email.Body = body.ToMessageBody();
using (var client = new SmtpClient())
{
//provider specific settings
await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);
await client.SendAsync(email).ConfigureAwait(false);
await client.DisconnectAsync(true).ConfigureAwait(false);
}
}
}
}
My best guess as to the answer: Consider these 3 options for how to get the CSRF token down from the server to the browser.
I think the 1st one, request body (while demonstrated by the Express tutorial I linked in the question), is not as portable to a wide variety of situations; not everyone is generating every HTTP response dynamically; where you end up needing to put the token in the generated response might vary widely (in a hidden form input; in a fragment of JS code or a variable accessible by other JS code; maybe even in a URL though that seems generally a bad place to put CSRF tokens). So while workable with some customization, #1 is a hard place to do a one-size-fits-all approach.
The second one, custom header, is attractive but doesn't actually work, because while JS can get the headers for an XHR it invoked, it can't get the headers for the page it loaded from.
That leaves the third one, a cookie carried by a Set-Cookie header, as an approach that is easy to use in all situations (anyone's server will be able to set per-request cookie headers, and it doesn't matter what kind of data is in the request body). So despite its downsides, it was the easiest method for frameworks to implement widely.
We can not bind this to setTimeout()
, as it always execute with global object (Window), if you want to access this
context in the callback function then by using bind()
to the callback function we can achieve as:
setTimeout(function(){
this.methodName();
}.bind(this), 2000);
I've tried all the answers above but still get this error with Office 365 account. The code seems to work fine with Google account and smtp.gmail.com when allowing less secure apps.
Any other suggestions that I could try?
Here is the code that I'm using
int port = 587;
string host = "smtp.office365.com";
string username = "[email protected]";
string password = "password";
string mailFrom = "[email protected]";
string mailTo = "[email protected]";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
using (SmtpClient client = new SmtpClient())
{
MailAddress from = new MailAddress(mailFrom);
MailMessage message = new MailMessage
{
From = from
};
message.To.Add(mailTo);
message.Subject = mailTitle;
message.Body = mailMessage;
message.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = host;
client.Port = port;
client.EnableSsl = true;
client.Credentials = new NetworkCredential
{
UserName = username,
Password = password
};
client.Send(message);
}
UPDATE AND HOW I SOLVED IT:
Solved problem by changing Smtp Client to Mailkit. The System.Net.Mail Smtp Client is now not recommended to use by Microsoft because of security issues and you should instead be using MailKit. Using Mailkit gave me clearer error messages that I could understand finding the root cause of the problem (license issue). You can get Mailkit by downloading it as a Nuget Package.
Read documentation about Smtp Client for more information: https://docs.microsoft.com/es-es/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.7.2
Here is how I implemented SmtpClient with MailKit
int port = 587;
string host = "smtp.office365.com";
string username = "[email protected]";
string password = "password";
string mailFrom = "[email protected]";
string mailTo = "[email protected]";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(mailFrom));
message.To.Add(new MailboxAddress(mailTo));
message.Subject = mailTitle;
message.Body = new TextPart("plain") { Text = mailMessage };
using (var client = new SmtpClient())
{
client.Connect(host , port, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(message);
client.Disconnect(true);
}
My issue was also caused by missing https binding in IIS: Selected default website > On the far right pane selected Bindings > add > https
Choose 'IIS Express Development Certificate' and set port to 443
I found the simplest method, described in this article mentioned in Greg T's answer, was to create an App Password which is available after turning on 2FA for the account.
myaccount.google.com > Sign-in & security > Signing in to Google > App Passwords
This gives you an alternative password for the account, then you just configure nodemailer as a normal SMTP service.
var smtpTransport = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: "[email protected]",
pass: "app password"
}
});
While Google recommend Oauth2 as the best option, this method is easy and hasn't been mentioned in this question yet.
Extra tip: I also found you can add your app name to the "from" address and GMail does not replace it with just the account email like it does if you try to use another address. ie.
from: 'My Pro App Name <[email protected]>'
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
I was also facing the same error. The reason for this is that there is no smtp server on your environment. For creating a fake smtp server I used this fake-smtp.jar file for creating a virtual server and listening to all the requests. If you are facing the same error, I recommend you to use this jar and run it after extracting and then try to run your application.
If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :
{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}
@JsonProperty("data")
private JsonNode data;
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
I had this issue when working on a Java Project in Debian 10 with Tomcat as the application server.
The issue was that the application already had https defined as it's default protocol while I was using http to call the application in the browser. So when I try running the application I get this error in my log file:
org.apache.coyote.http11.AbstractHttp11Processor process
INFO: Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
I however tried using the https protocol in the browser but it didn't connect throwing the error:
Here's how I solved it:
You need a certificate to setup the https protocol for the application. I first had to create a keystore file for the application, more like a self-signed certificate for the https protocol:
sudo keytool -genkey -keyalg RSA -alias tomcat -keystore /usr/share/tomcat.keystore
Note: You need to have Java installed on the server to be able to do this. Java can be installed using sudo apt install default-jdk
.
Next, I added a https Tomcat server connector for the application in the Tomcat server configuration file (/opt/tomcat/conf/server.xml
):
sudo nano /opt/tomcat/conf/server.xml
Add the following to the configuration of the application. Notice that the keystore file location and password are specified. Also a port for the https protocol is defined, which is different from the port for the http protocol:
<Connector protocol="org.apache.coyote.http11.Http11Protocol"
port="8443" maxThreads="200" scheme="https"
secure="true" SSLEnabled="true"
keystoreFile="/usr/share/tomcat.keystore"
keystorePass="my-password"
clientAuth="false" sslProtocol="TLS"
URIEncoding="UTF-8"
compression="force"
compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>
So the full server configuration for the application looked liked this in the Tomcat server configuration file (/opt/tomcat/conf/server.xml
):
<Service name="my-application">
<Connector protocol="org.apache.coyote.http11.Http11Protocol"
port="8443" maxThreads="200" scheme="https"
secure="true" SSLEnabled="true"
keystoreFile="/usr/share/tomcat.keystore"
keystorePass="my-password"
clientAuth="false" sslProtocol="TLS"
URIEncoding="UTF-8"
compression="force"
compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>
<Connector port="8009" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Engine name="my-application" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.LockOutRealm">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
</Engine>
</Service>
This time when I tried accessing the application from the browser using:
https://my-server-ip-address:https-port
In my case it was:
https:35.123.45.6:8443
it worked fine. Although, I had to accept a warning which added a security exception for the website since the certificate used is a self-signed one.
That's all.
I hope this helps
I had this issue as well but the solution had nothing to do with coding. Make sure you are able to connect to gmail. Ping smtp.gmail.com. If you don't get a reply check your firewall settings. It could also be a proxy setting issue.
You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding
, and the default value for securityMode\transport
for that binding is Message
.
Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration
attribute:
<bindings>
<wsHttpBinding>
<binding name="ota2010AEndpoint"
.......>
<readerQuotas maxDepth="32" ... />
<reliableSession ordered="true" .... />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
(Snipped parts of the config to save space in the answer).
<service name="Synxis" behaviorConfiguration="SynxisWCF">
<endpoint address="" name="wsHttpEndpoint"
binding="wsHttpBinding"
bindingConfiguration="ota2010AEndpoint"
contract="Synxis" />
This will then assign your defined binding (with Transport security) to the endpoint.
Try to add the path to tnsnames.ora to the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<oracle.manageddataaccess.client>
<version number="4.112.3.60">
<settings>
<setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
</settings>
</version>
</oracle.manageddataaccess.client>
</configuration>
I was facing the same issue but I mitigated it by placing:
server.timeout = 0;
before server.listen
. server
is an HTTP server here. The default timeout is 2 minutes as per the API documentation.
Ok, so this might not fix your issue but it definitely worked for me.
So you've created your Mysql user I take it? Go to user privileges on PhpMyAdmin and click edit next to the user your using for Symfony. Scroll down to near the bottom and where it says which host you want to use make sure you've selected LocalHost not % Any.
Then in your config file swap 127.0.0.1 for localhost. Hopefully that will work for you. Just worked for me as I was having the same issue.
I got the same issue. To solve the issue you need to update your PHP version.
Try using the smtpsend program that comes with JavaMail, as described here. If that fails in the same way, there's something wrong with your JDK configuration or your network configuration.
I found many of the Q&A on this topic, not nothing was helping me - that's because my issue was more basic ( what can I say I am not a networking guru :) ). My ip address in /etc/hosts was incorrect. What I had tried included the following for CATALINA_OPTS:
CATALINA_OPTS="$CATALINA_OPTS -Djava.awt.headless=true -Xmx128M -server
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=7091
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=A.B.C.D" #howeverI put the wrong ip here!
export CATALINA_OPTS
My problem was that I had changed my ip address many months ago, but never updated my /etc/hosts file. it seems that by default the jconsole uses the hostname -i ip address in some fashion even though I was viewing local processes. The best solution was to simply change the /etc/hosts file.
The other solution which can work is to get your correct ip address from /sbin/ifconfig and use that ip address when specifying the ip address in, for example, a catalina.sh script:
-Djava.rmi.server.hostname=A.B.C.D
In my case it was simply an error in the web.config.
I had:
<endpoint address="http://localhost/WebService/WebOnlineService.asmx"
It should have been:
<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"
The port number (:10593) was missing from the address.
In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".
Here is how you can fix it:
/var/lib/jenkins/config.xml
<useSecurity>true</useSecurity>
to false sudo service jenkins restart
allow anyone to do anything
, and allow user signup.www.yoursite.com/securityRealm/addUser
and create a userallow anyone to do anything
to whatever you actually want users to be able to do. In my case, it is allow logged in users to do anything
.If you're able to successfully load a page from Eclipses internal web browser (by going to "Window"=>"Show View"=>"Other"=>"Internal Web Browser" and trying to open a page) BUT installing software from the eclipse marketplace and the "Help"=>"Install New Software" window are not working then this fix may help you (worked for me on a Windows 7 machine):
In v 5.8.38, I set the env file as the following:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=difficultCombination
MAIL_ENCRYPTION=ssl
MAIL_FROM_NAME=myWebappName
After doing php artisan config:clear
, it worked well on a shard server.
Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.
You can review permissions using the following command.
Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell
Found this tip here (updated link, thanks "unbob"):
https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/
It fixed it for me.
Apparently anonymous functions cannot be serialized.
Example
$function = function () {
return "ABC";
};
serialize($function); // would throw error
From your code you are using Closure:
$callback = function () // <---------------------- Issue
{
return 'ZendMail_' . microtime(true) . '.tmp';
};
Solution 1 : Replace with a normal function
Example
function emailCallback() {
return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;
Solution 2 : Indirect method call by array variable
If you look at http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html
public function __construct($options = null)
63 {
64 if ($options instanceof Zend_Config) {
65 $options = $options->toArray();
66 } elseif (!is_array($options)) {
67 $options = array();
68 }
69
70 // Making sure we have some defaults to work with
71 if (!isset($options['path'])) {
72 $options['path'] = sys_get_temp_dir();
73 }
74 if (!isset($options['callback'])) {
75 $options['callback'] = array($this, 'defaultCallback'); <- here
76 }
77
78 $this->setOptions($options);
79 }
You can use the same approach to send the callback
$callback = array($this,"aMethodInYourClass");
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
There's no fixed time for retransmission. Simple implementations estimate the RTT (round-trip-time) and if no ACK to send data has been received in 2x that time then they re-send.
They then double the wait-time and re-send once more if again there is no reply. Rinse. Repeat.
More sophisticated systems make better estimates of how long it should take for the ACK as well as guesses about exactly which data has been lost.
The bottom-line is that there is no hard-and-fast rule about exactly when to retransmit. It's up to the implementation. All retransmissions are triggered solely by the sender based on lack of response from the receiver.
TCP never drops data so no, there is no way to indicate a server should forget about some segment.
The problem may lie in you don't have enabled openssl extention in your php.ini file
go to your php.ini file end remove ;
in line where extension=openssl
is
Of course in question code there is a part of code responsible for checking whether extension is loaded or not but maybe some uncautious forget about it
For me, the problem was that catalina.sh didnt have execute permissions. The "Unable to open debugger port in intellij" message appeared in Intellij, but it sort of masked the 'could not execute catalina.sh' error that appeared in the logs immediately prior.
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
Another option is if windows updates are turned totally off on your PC. In this case even if you download the USB driver & try update it manually as described above it will not work. The only way in this case is enabling windows updating drivers automatically. Once you enabled this, remove the non-working driver from device manager & connect you tablet to the PC via USB cable. The drivers will be automatically downloaded & installed by Windows. This way worked on my Windows 7 PC.
Try this code :
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.prot", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("PUT THE MAIL SENDER HERE !", "PUT THE PASSWORD OF THE MAIL SENDER HERE !");
}
}
);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("PUT THE MAIL SENDER HERE !"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("PUT THE MAIL RECEIVER HERE !"));
message.setSubject("MAIL SUBJECT !");
message.setText("MAIL BODY !");
Transport.send(message);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
You have to less secure the security of the mail sender. if the problem persist I think It can be caused by the antivirus, try to disable it ..
Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.
But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
// ip address of the service URL(like.23.28.244.244)
if (hostname.equals("23.28.244.244"))
return true;
return false;
}
});
}
If you happen to be using Java 8, there is a much slicker way of achieving the same result:
static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}
In the endpoint tag you need to include the property address=""
<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />
In my project I had the same error, I restarted Tomcat and it worked, withtout killing the java process.
If you're like me and you use this method of passing variables a lot, here's a write-less-code solution.
In your node.js route, pass the variables in an object called window
, like this:
router.get('/', function (req, res, next) {
res.render('index', {
window: {
instance: instance
}
});
});
Then in your pug/jade layout file (just before the block content
), you get them out like this:
if window
each object, key in window
script.
window.!{key} = !{JSON.stringify(object)};
As my layout.pug file gets loaded with each pug file, I don't need to 'import' my variables over and over.
This way all variables/objects passed to window
'magically' end up in the real window
object of your browser where you can use them in Reactjs, Angular, ... or vanilla javascript.
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
To create a valid DSA format private key supported by Paramiko in Puttygen.
Click on Conversions then Export OpenSSH Key
Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.
Parsed data from jquery success handler for text/html response:
var parsed = JSON.parse(data);
Parsed data from jquery success handler for application/json response:
var parsed = data;
This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site. Good Luck.
On Server side
io.on('connection', socket => {
console.log(socket.id)
})
On Client side
import io from 'socket.io-client';
socket = io.connect('http://localhost:5000');
socket.on('connect', () => {
console.log(socket.id, socket.io.engine.id, socket.json.id)
})
If socket.id
, doesn't work, make sure you call it in on('connect')
or after the connection.
I've solved this issue adding user and password in Transport.send
call:
Transport.send(msg, "user", "password");
According to this signature of the send
function in javax.mail (from version 1.5):
public static void send(Message msg, String user, String password)
Also, if you use this signature it's not necessary to set up any Authenticator
, and to set user and password in the Properties
(only the host is needed). So your code could be:
private void sendMail(){
try{
Properties prop = System.getProperties();
prop.put("mail.smtp.host", "yourHost");
Session session = Session.getInstance(prop);
Message msg = #createYourMsg(session, from, to, subject, mailer, yatta yatta...)#;
Transport.send(msg, "user", "password");
}catch(Exception exc) {
// Deal with it! :)
}
}
You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator
public class FooImpl implements Foo {
private static final Logger LOGGER = Logger.getLogger(FooBar.class);
public Object createObject() {
BasicConfigurator.configure();
LOGGER.info("something");
return new Object();
}
}
So under the table, configure do:
configure() {
Logger root = Logger.getRootLogger();
root.addAppender(new ConsoleAppender(
new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
}
The guys have given the simple solution, which will do be you should have a look at the help - it's good, looks like a lot in one go but it's actually quick to read:
get-help about_Remote_Troubleshooting | more
Put the things like /src/main/resources/foo/bar.properties
and then reference them as classpath:/foo/bar.properties
.
It may be related to Java JRE version.
In my case I need Tomcat 6.0.26 which presented same error with JRE 1.8.0_91. A downgrade to JRE 1.7.49 solved it.
You might find more information in: http://www.howopensource.com/2015/07/unable-to-compile-class-for-jsp-the-type-java-util-mapentry-cannot-be-resolved/
This might not be relevant to your specific problem, but the error message you mentioned has many causes, one of them is using a return type for an [OperationContract] that is either abstract, interface, or not known to the WCF client code.
Check the post (and solution) below
I got this after i copied the svc file and renamed it. Although the file name and the svc.cs file were correctly renamed, the markup still referenced the original file.
To fix this, right click on the copied svc file and choose View Markup and change the service reference.
You also need to increase maxBufferSize. Also note that you might need to increase the readerQuotas.
I received this error when calling a web-service. The issue was also related to transport level security. I could call the web-service through a website project, but when reusing the same code in a test project I would get a WebException that contained this message. Adding the following line before making the call resolved the issue:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Edit
System.Net.ServicePointManager.SecurityProtocol - This property selects the version of the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocol to use for new connections that use the Secure Hypertext Transfer Protocol (HTTPS) scheme only; existing connections are not changed.
I believe the SecurityProtocol
configuration is important during the TLS handshake when selecting the protocol version.
TLS handshake - This protocol is used to exchange all the information required by both sides for the exchange of the actual application data by TLS.
ClientHello - A client sends a ClientHello message specifying the highest TLS protocol version it supports ...
ServerHello - The server responds with a ServerHello message, containing the chosen protocol version ... The chosen protocol version should be the highest that both the client and server support. For example, if the client supports TLS version 1.1 and the server supports version 1.2, version 1.1 should be selected; version 1.2 should not be selected.
X++
binding = endPoint.get_Binding();
binding.set_UseDefaultWebProxy(false);
If your jQuery page isn't being loaded from http://localhost:54473
then this issue is probably because you're trying to make cross-domain request.
Update 1 Take a look at this blog post.
Update 2 If this is indeed the problem (and I suspect it is), you might want to check out JSONP as a solution. Here are a few links that might help you get started:
changing the Binding Type from wsHttpbinding to basichttp binding in the endpoint tag and from wsHttpbinding to mexhttpbinginding in metadata endpoint tag helped to overcome the error. Thank you...
The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).
Typical symptoms:
[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100
[root@host /]# netstat -plant | grep 25
tcp 0 0 :::25 :::* LISTEN 1082/exim
If this happens, make sure that you don't have two entries for localhost
in /etc/hosts
with different IP addresses, like this (bad) example:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
To avoid confusion, make sure you only have one entry for localhost
, preferably an IPv4 address, like this:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4.localdomain4 localhost4
::1 localhost6 localhost6.localdomain6
The "loginVo.htmlBody(messageBodyPart);" will contain the html formatted designed information, but in mail does not receive it.
JAVA - STRUTS2
package com.action;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.opensymphony.xwork2.Action;
import com.bo.LoginBo;
import com.manager.AttendanceManager;
import com.manager.LoginManager;
import com.manager.SSLEmail;
import com.vo.AttendanceManagementVo;
import com.vo.LeaveManagementVo;
import com.vo.LoginVo;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeBodyPart;
public class InsertApplyLeaveAction implements Action {
private AttendanceManagementVo attendanceManagementVo;
public AttendanceManagementVo getAttendanceManagementVo() {
return attendanceManagementVo;
}
public void setAttendanceManagementVo(
AttendanceManagementVo attendanceManagementVo) {
this.attendanceManagementVo = attendanceManagementVo;
}
@Override
public String execute() throws Exception {
String empId=attendanceManagementVo.getEmpId();
String leaveType=attendanceManagementVo.getLeaveType();
String leaveStartDate=attendanceManagementVo.getLeaveStartDate();
String leaveEndDate=attendanceManagementVo.getLeaveEndDate();
String reason=attendanceManagementVo.getReason();
String employeeName=attendanceManagementVo.getEmployeeName();
String manageEmployeeId=empId;
float totalLeave=attendanceManagementVo.getTotalLeave();
String leaveStatus=attendanceManagementVo.getLeaveStatus();
// String approverId=attendanceManagementVo.getApproverId();
attendanceManagementVo.setEmpId(empId);
attendanceManagementVo.setLeaveType(leaveType);
attendanceManagementVo.setLeaveStartDate(leaveStartDate);
attendanceManagementVo.setLeaveEndDate(leaveEndDate);
attendanceManagementVo.setReason(reason);
attendanceManagementVo.setManageEmployeeId(manageEmployeeId);
attendanceManagementVo.setTotalLeave(totalLeave);
attendanceManagementVo.setLeaveStatus(leaveStatus);
attendanceManagementVo.setEmployeeName(employeeName);
AttendanceManagementVo attendanceManagementVo1=new AttendanceManagementVo();
AttendanceManager attendanceManager=new AttendanceManager();
attendanceManagementVo1=attendanceManager.insertLeaveData(attendanceManagementVo);
attendanceManagementVo1=attendanceManager.getApproverId(attendanceManagementVo);
String approverId=attendanceManagementVo1.getApproverId();
String approverEmployeeName=attendanceManagementVo1.getApproverEmployeeName();
LoginVo loginVo=new LoginVo();
LoginManager loginManager=new LoginManager();
loginVo.setEmpId(approverId);
loginVo=loginManager.getEmailAddress(loginVo);
String emailAddress=loginVo.getEmailAddress();
String subject="LEAVE IS SUBMITTED FOR AN APPROVAL BY THE - " +employeeName;
// String body = "Hi "+approverEmployeeName+" ," + "\n" + "\n" +
// leaveType+" is Applied for "+totalLeave+" days by the " +employeeName+ "\n" + "\n" +
// " Employee Name: " + employeeName +"\n" +
// " Applied Leave Type: " + leaveType +"\n" +
// " Total Days: " + totalLeave +"\n" + "\n" +
// " To view Leave History, Please visit the employee poratal or copy and paste the below link in your browser: " + "\n" +
// " NOTE : This is an automated message. Please do not reply."+ "\n" + "\n" +
Session session = null;
MimeBodyPart messageBodyPart = new MimeBodyPart();
MimeMessage message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
String htmlText = ("<div style=\"color:red;\">BRIDGEYE</div>");
messageBodyPart.setContent(htmlText, "text/html");
loginVo.setHtmlBody(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
loginVo.setSubject(subject);
// loginVo.setBody(body);
loginVo.setEmailAddress(emailAddress);
SSLEmail sSSEmail=new SSLEmail();
sSSEmail.sendEmail(loginVo);
return "success";
}
}
I had to move domain, username, password from
client.ClientCredentials.UserName.UserName = domain + "\\" + username; client.ClientCredentials.UserName.Password = password
to
client.ClientCredentials.Windows.ClientCredential.UserName = username; client.ClientCredentials.Windows.ClientCredential.Password = password; client.ClientCredentials.Windows.ClientCredential.Domain = domain;
Inspired by many other FFmpeg on Android implementations out there (mainly the guadianproject), I found a solution (with Lame support also).
(lame and FFmpeg: https://github.com/intervigilium/liblame and http://bambuser.com/opensource)
to call FFmpeg:
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
FfmpegController ffmpeg = null;
try {
ffmpeg = new FfmpegController(context);
} catch (IOException ioe) {
Log.e(DEBUG_TAG, "Error loading ffmpeg. " + ioe.getMessage());
}
ShellDummy shell = new ShellDummy();
String mp3BitRate = "192";
try {
ffmpeg.extractAudio(in, out, audio, mp3BitRate, shell);
} catch (IOException e) {
Log.e(DEBUG_TAG, "IOException running ffmpeg" + e.getMessage());
} catch (InterruptedException e) {
Log.e(DEBUG_TAG, "InterruptedException running ffmpeg" + e.getMessage());
}
Looper.loop();
}
}).start();
and to handle the console output:
private class ShellDummy implements ShellCallback {
@Override
public void shellOut(String shellLine) {
if (someCondition) {
doSomething(shellLine);
}
Utils.logger("d", shellLine, DEBUG_TAG);
}
@Override
public void processComplete(int exitValue) {
if (exitValue == 0) {
// Audio job OK, do your stuff:
// i.e.
// write id3 tags,
// calls the media scanner,
// etc.
}
}
@Override
public void processNotStartedCheck(boolean started) {
if (!started) {
// Audio job error, as above.
}
}
}
Modify catalina.bat to add
set JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
and
CATALINA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
Optional: Add below line to run the debug mode by default when you run startup.bat
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
Eclipse or STS select debug configuration right click -> new
connection type -> Standard socket Attach
Port -> 8000 (as given in the CATALINA_OPTS)
Host -> localhost or IP address
on windows open a cmd.exe window with administrator permissions and use netstat -a -b -o
you will get the id of the proccess that holds your port and be able to kill it using task manager.
Following code worked for me.
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
final String username = "[email protected]";
final String password = "yourpassword";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
Strange enough sending emails works again. We did not change anything and the host say they did not either. We think a server restarts or so. It is strange :S
Your first mistake is thinking that ASCII encoding and Base64 encoding are interchangeable. They are not. They are used for different purposes.
To understand why Base64 was necessary in the first place we need a little history of computing.
Computers communicate in binary - 0s and 1s - but people typically want to communicate with more rich forms data such as text or images. In order to transfer this data between computers it first has to be encoded into 0s and 1s, sent, then decoded again. To take text as an example - there are many different ways to perform this encoding. It would be much simpler if we could all agree on a single encoding, but sadly this is not the case.
Originally a lot of different encodings were created (e.g. Baudot code) which used a different number of bits per character until eventually ASCII became a standard with 7 bits per character. However most computers store binary data in bytes consisting of 8 bits each so ASCII is unsuitable for tranferring this type of data. Some systems would even wipe the most significant bit. Furthermore the difference in line ending encodings across systems mean that the ASCII character 10 and 13 were also sometimes modified.
To solve these problems Base64 encoding was introduced. This allows you to encode arbitrary bytes to bytes which are known to be safe to send without getting corrupted (ASCII alphanumeric characters and a couple of symbols). The disadvantage is that encoding the message using Base64 increases its length - every 3 bytes of data is encoded to 4 ASCII characters.
To send text reliably you can first encode to bytes using a text encoding of your choice (for example UTF-8) and then afterwards Base64 encode the resulting binary data into a text string that is safe to send encoded as ASCII. The receiver will have to reverse this process to recover the original message. This of course requires that the receiver knows which encodings were used, and this information often needs to be sent separately.
Historically it has been used to encode binary data in email messages where the email server might modify line-endings. A more modern example is the use of Base64 encoding to embed image data directly in HTML source code. Here it is necessary to encode the data to avoid characters like '<' and '>' being interpreted as tags.
Here is a working example:
I wish to send a text message with two lines:
Hello world!
If I send it as ASCII (or UTF-8) it will look like this:
72 101 108 108 111 10 119 111 114 108 100 33
The byte 10 is corrupted in some systems so we can base 64 encode these bytes as a Base64 string:
SGVsbG8Kd29ybGQh
Which when encoded using ASCII looks like this:
83 71 86 115 98 71 56 75 100 50 57 121 98 71 81 104
All the bytes here are known safe bytes, so there is very little chance that any system will corrupt this message. I can send this instead of my original message and let the receiver reverse the process to recover the original message.
Even I faced the same problem in my XMPP notification application, receivers message needs to be added back to list view (implemented with ArrayList
). When I tried to add the receiver content through MessageListener
(separate thread), application quits with above error. I solved this by adding the content to my arraylist
& setListviewadapater
through runOnUiThread
method which is part of Activity class. This solved my problem.
All you need is to Stop the ASP.NET Development Server and run the project again
After many answers that did not work, I finally found a solution when Anonymous access is Disabled on the IIS server. Our server is using Windows authentication, not Kerberos. This is thanks to this blog posting.
No changes were made to web.config.
On the server side, the .SVC file in the ISAPI folder uses MultipleBaseAddressBasicHttpBindingServiceHostFactory
The class attributes of the service are:
[BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class InvoiceServices : IInvoiceServices
{
...
}
On the client side, the key that made it work was the http binding security attributes:
EndpointAddress endpoint =
new EndpointAddress(new Uri("http://SharePointserver/_vti_bin/InvoiceServices.svc"));
BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
InvoiceServicesClient myClient = new InvoiceServicesClient(httpBinding, endpoint);
myClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
(call service)
I hope this works for you!
wsHttpBinding is a problem because silverlight doesn't support it!
Well, the "failure sending e-mail" should hopefully have a bit more detail. But there are a few things that could cause this.
Regardless if it is one of these or another error, you will want to look at the exception and inner exception to get a bit more detail.
You need to implement a custom Authenticator
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
class GMailAuthenticator extends Authenticator {
String user;
String pw;
public GMailAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
Now use it in the Session
Session session = Session.getInstance(props, new GMailAuthenticator(username, password));
Also check out the JavaMail FAQ
Just recently experienced this:
System.ServiceModel.CommunicationException:
An error occurred while making the HTTP request to http://example.com/WebServices/SomeService.svc. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.
---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
I found out from an administrator that the IIS application pool that was hosting the web service recycled automatically after running out of memory. The error on the client occurred when the application pool recycled.
Increasing the memory available to the application pool resolved the immediate issue.
You can setup _JAVA_OPTIONS
instead of JAVA_OPTS
. This should work without $_JAVA_OPTIONS
.
For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:
import javax.mail.*
import javax.mail.internet.*
private class SMTPAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication('[email protected]', 'test1234');
}
}
def d_email = "[email protected]",
d_uname = "email",
d_password = "password",
d_host = "smtp.gmail.com",
d_port = "465", //465,587
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email."
def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);
def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))
Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
As explained in this thread on the cxf-user mailing list, rather than having the CXFServlet load its own spring context from user-webservice-servlet.xml
, you can just load the whole lot into the root context. Rename your existing user-webservice-servlet.xml
to some other name (e.g. user-webservice-beans.xml
) then change your contextConfigLocation
parameter to something like:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/user-webservice-beans.xml
</param-value>
</context-param>
<servlet>
<servlet-name>user-webservice</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user-webservice</servlet-name>
<url-pattern>/UserService/*</url-pattern>
</servlet-mapping>
One difference we can note in Windows is:
If you use Runtime.getRuntime().exec("rmiregistry 1024");
you can see rmiregistry.exe process will run in your Task Manager
whereas if you use Registry registry = LocateRegistry.createRegistry(1024);
you can not see the process running in Task Manager,
I think Java handles it in a different way.
and this is my server.policy file
Before running the the application, make sure that you killed all your existing javaw.exe and rmiregistry.exe corresponds to your rmi programs which are already running.
The following code works for me by using Registry.LocateRegistry()
or
Runtime.getRuntime.exec("");
// Standard extensions get all permissions by default
grant {
permission java.security.AllPermission;
};
VM argument
-Djava.rmi.server.codebase=file:\C:\Users\Durai\workspace\RMI2\src\
Code:
package server;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class HelloServer
{
public static void main (String[] argv)
{
try {
if(System.getSecurityManager()==null){
System.setProperty("java.security.policy","C:\\Users\\Durai\\workspace\\RMI\\src\\server\\server.policy");
System.setSecurityManager(new RMISecurityManager());
}
Runtime.getRuntime().exec("rmiregistry 1024");
// Registry registry = LocateRegistry.createRegistry(1024);
// registry.rebind ("Hello", new Hello ("Hello,From Roseindia.net pvt ltd!"));
//Process process = Runtime.getRuntime().exec("C:\\Users\\Durai\\workspace\\RMI\\src\\server\\rmi_registry_start.bat");
Naming.rebind ("//localhost:1024/Hello",new Hello ("Hello,From Roseindia.net pvt ltd!"));
System.out.println ("Server is connected and ready for operation.");
}
catch (Exception e) {
System.out.println ("Server not connected: " + e);
e.printStackTrace();
}
}
}
I was having problem in Windows 7 with PHP 5.4.0 in command line, using Xampp 1.8.1 server. This is what i did:
php.ini-production
to php.ini
(in C:\xampp\php\ folder)php.ini
and uncomment extension_dir=ext
.extension=php_openssl.dll
.After that it worked fine.
While it's possible that this is due to a jar file missing from your classpath, it may not be.
It is important to keep two or three different exceptions strait in our head in this case:
java.lang.ClassNotFoundException
This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError
This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying again, but we're not even going to try to load it, because we failed loading it earlier. The earlier failure could be a ClassNotFoundException
or an ExceptionInInitializerError
(indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError
is not necessarily a classpath problem.
I would look at the source for javax.mail.Authenticator
, and see what it is doing in it's static initializer. (Look at static variable initialization and the static block, if there is one.) If you aren't getting a ClassNotFoundException
prior to the NoClassDefFoundError
, you're almost guaranteed that it's a static initialization problem.
I have seen similar errors quite frequently when the hosts file incorrectly defines the localhost address, and the static initialization block relies on InetAddress.getLocalHost()
. 127.0.0.1 should point to 'localhost' (and probably also localhost.localdomain). It should NOT point to the actual host name of the machine (although for some reason, many older RedHat Linux installers liked to set it incorrectly).
Here's another way of attaching the event based on W3C DOM Level 2 Events Specification:
transport_select.addEventListener(
'change',
function() { toggleSelect(this.id); },
false
);
The timeout configuration needs to be set at the client level, so the configuration I was setting in the web.config had no effect, the WCF test tool has its own configuration and there is where you need to set the timeout.
Make sure your SendTimeout
hasn't elapsed after opening the client.
Use strace
is more suitable for this situation.
strace -f -e trace=network -s 10000 -p <PID>;
options -f
to also trace all forked processes, -e trace=netwrok
to only filter network system-call and -s
to display string length up to 10000 char.
You can also only trace certain calls like send,recv, read operations.
strace -f -e trace=send,recv,read -s 10000 -p <PID>;
This happened to me as well. For me, Postfix was located at the same server as the PHP script, and the error was happening when I would be using SMTP authentication and smtp.domain.com instead of localhost.
So when I commented out these lines:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
and set the host to
$mail->Host = "localhost";
instead
$mail->Host = 'smtp.mydomainiuse.com'
and it worked :)
If more than one result is expected, then the getResponse()
method will return a Vector
containing the various responses.
In which case the offending code becomes:
Object result = envelope.getResponse();
// treat result as a vector
String resultText = null;
if (result instanceof Vector)
{
SoapPrimitive element0 = (SoapPrimitive)((Vector) result).elementAt(0);
resultText = element0.toString();
}
tv.setText(resultText);
Answer based on the ksoap2-android (mosabua fork)
I have a similar issue, have you tried:
proxy.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
I'm late to this party but I'll offer my approach for any passersby that might be interested in an alternative.
As noted in previous answers, the System.Net.Mail
SmtpClient
class does not support Implicit SSL. It does support Explicit SSL, which requires an insecure connection to the SMTP server over port 25 in order to negotiate the transport level security (TLS). I blogged about my travails with this subtlety here.
In short, SMTP over Implict SSL port 465 requires TLS to be negotiated before connecting to the SMTP server. Rather than write a .Net SMTPS implementation I turned to a utility named Stunnel. It's a small service that will let you redirect traffic on a local port to a remote port via SSL.
DISCLAIMER: Stunnel uses portions of the OpenSSL library, which recently had a high-profile exploit published in all major tech news media. I believe the latest version uses the patched OpenSSL but please use at your own risk.
Once the utility is installed a small addition to the configuration file:
; Example SSL client mode services
[my-smtps]
client = yes
accept = 127.0.0.1:465
connect = mymailserver.com:465
...instructs the Stunnel service to reroute local requests to port 465 to my mail server on port 465. This happens over TLS, which satisfies the SMTP server on the other end.
Using this utility, the following code will successfully transmit over port 465:
using System;
using System.Net;
using System.Net.Mail;
namespace RSS.SmtpTest
{
class Program
{
static void Main( string[] args )
{
try {
using( SmtpClient smtpClient = new SmtpClient( "localhost", 465 ) ) { // <-- note the use of localhost
NetworkCredential creds = new NetworkCredential( "username", "password" );
smtpClient.Credentials = creds;
MailMessage msg = new MailMessage( "[email protected]", "[email protected]", "Test", "This is a test" );
smtpClient.Send( msg );
}
}
catch( Exception ex ) {
Console.WriteLine( ex.Message );
}
}
}
}
So the advantage here is that you can use Implict SSL and port 465 as the security protocol while still using the send mail methods built into the framework. The disadvantage is that it requires the use of a third party service that may not be useful for anything but this specific function.
Steps:
See Step by Step guide on Java remote debugging for full details.
in a case of Elliptic Curve and answer the question import an existing x509 certificate and private key in Java keystore, you may want to have a look also to this thread How to read EC Private key in java which is in .pem file format
Please check your Windows system event log for any errors specifically for the "Event Source: Dhcp". It's very likely a networking error related to DHCP. Address lease time expired or so. It shouldn't be a problem related to the SQL Server or the query itself.
Just search the internet for "The semaphore timeout period has expired" and you'll get plenty of suggestions what might be a solution for your problem. Unfortunately there doesn't seem to be the solution for this problem.
Just want to point out
Apart from MaxRecivedMessageSize, there are also attributes under ReaderQuotas, you might hit number of items limit instead of size limit. MSDN link is here
use my function as diagnostic certificates issues - see screen
System.Net.ServicePointManager.ServerCertificateValidationCallback = Function(s As Object,
cert As System.Security.Cryptography.X509Certificates.X509Certificate,
chain As System.Security.Cryptography.X509Certificates.X509Chain,
err As System.Net.Security.SslPolicyErrors)
Return True
End Function
This error occurs on the server side when the client closed the socket connection before the response could be returned over the socket. In a web app scenario not all of these are dangerous, since they can be created manually. For example, by quitting the browser before the reponse was retrieved.
If you want easy and simple, you might also want to look at Fabric. It's an automated deployment tool like Ruby's Capistrano, but simpler and of course for Python. It's build on top of Paramiko.
You might not want to do 'automated deployment' but Fabric would suit your use case perfectly none the less. To show you how simple Fabric is: the fab file and command for your script would look like this (not tested, but 99% sure it will work):
fab_putfile.py:
from fabric.api import *
env.hosts = ['THEHOST.com']
env.user = 'THEUSER'
env.password = 'THEPASSWORD'
def put_file(file):
put(file, './THETARGETDIRECTORY/') # it's copied into the target directory
Then run the file with the fab command:
fab -f fab_putfile.py put_file:file=./path/to/my/file
And you're done! :)
In my case i am setting security mode to "TransportCredentialOnly" instead of "Transport" in binding. Changing it resolved the issue
<bindings>
<webHttpBinding>
<binding name="webHttpSecure">
<security mode="Transport">
<transport clientCredentialType="Windows" ></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
Of course, it doesn't necessarily have to be transmitted over TCP. I implemented HTTP on top of UDP, for use in the Satellite TV Broadcasting industry.
I found this MSDN forum post which suggests two solutions to your problem.
First solution (not recommended):
Find the .Net Framework 3.5 and 2.0 folder
Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder
Add the reference to these two assemblies
Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work
Second solution (Use a different class / library):
The user who had posted the question claimed that Uri.EscapeUriString
and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer
.
You could also try to use Json.Net. It's a third party library and pretty powerful.
Check if the Console is telling you something. Usually this happen when the project could not be install in the device, and just show the previous one. The most common case I has seen this is when there are different signatures in the project, and is not running at all. Please, read all red letter you see. If the LogCat does not show anything, take for sure that the Console will do.
In addition to your CORS issue, the server you are trying to access has HTTP basic authentication enabled. You can include credentials in your cross-domain request by specifying the credentials in the URL you pass to the XHR:
url = 'http://username:[email protected]/testpage'
There are ways to change the default delimiter, as shown by other answers.
There are also ways to convert the raw output to csv with some bash scripting. There are 3 delimiters to consider though, not just \001. Things get a bit more complicated when your hive table has maps.
I wrote a bash script that can handle all 3 default delimiters (\001 \002 and \003) from hive and output a csv. The script and some more info are here:
Hive Default Delimiters to CSV
Hive's default delimiters are
Row Delimiter => Control-A ('\001') Collection Item Delimiter => Control-B ('\002') Map Key Delimiter => Control-C ('\003')
There are ways to change these delimiters when exporting tables but sometimes you might still get stuck needing to convert this to csv.
Here's a quick bash script that can handle a DB export that's segmented in multiple files and has the default delimiters. It will output a single CSV file.
It is assumed that the segments all have the naming convention 000*_0
INDIRECTORY="path/to/input/directory" for f in $INDIRECTORY/000*_0; do echo "Processing $f file.."; cat -v $f | LC_ALL=C sed -e "s/^/\"/g" | LC_ALL=C sed -e "s/\^A/\",\"/g" | LC_ALL=C sed -e "s/\^C\^B/\"\":\"\"\"\",\"\"/g" | LC_ALL=C sed -e "s/\^B/\"\",\"\"/g" | LC_ALL=C sed -e "s/\^C/\"\":\"\"/g" | LC_ALL=C sed -e "s/$/\"/g" > $f-temp done echo "you,can,echo,your,header,here,if,you,like" > $INDIRECTORY/final_output.csv cat $INDIRECTORY/*-temp >> $INDIRECTORY/final_output.csv rm $INDIRECTORY/*-temp
More explanation on the gist
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
Your code is way more cluttered than necessary.
Replace (Not (X Is Nothing))
with X IsNot Nothing
and omit the outer parentheses:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For i As Integer = 0 To comp.Container.Components.Count() - 1
fixUIIn(comp.Container.Components(i), style)
Next
End If
Much more readable. … Also notice that I’ve removed the redundant Step 1
and the probably redundant .Item
.
But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each
instead:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For Each component In comp.Container.Components
fixUIIn(component, style)
Next
End If
Adding to Winnie's great answer,
If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.
SHOW config_file;
For me changing the max_connections alone made the trick.
Try this:
TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
txt = txt.Trim();
All of todays browsers use at least version 1.5
:
http://en.wikipedia.org/wiki/ECMAScript#Dialect
Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide
You may still want to watch out for features which require version 1.6
or above, as this might give Internet Explorer some troubles.
Per Microsoft's KB, try allowing programmatic access to the Visual Basic project:
- Click the Microsoft Office Button, and then click Excel Options.
- Click Trust Center.
- Click Trust Center Settings.
- Click Macro Settings.
- Click to select the Trust access to the VBA project object model check box.
- Click OK to close the Excel Options dialog box.
- You may need to close and re-open excel.
Run: psql -E
, and then \ds
Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary>
and <detail>
tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.
I've made an example here:
<details>
<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>
</details>
Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
In my situation, in order to include color.sh
from the same directory in init.sh
, I had to do something as follows.
. ./color.sh
Not sure why the ./
and not color.sh
directly. The content of color.sh
is as follows.
RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`
Making use of File color.sh
does not error but, the color do not display. I have tested this in Ubuntu 18.04
and the Bash
version is:
GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)
Kotlin Code to read SMS :
1- Add this permission to AndroidManifest.xml :
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
2-Create a BroadCastreceiver Class :
package utils.broadcastreceivers
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import android.util.Log
class MySMSBroadCastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var body = ""
val bundle = intent?.extras
val pdusArr = bundle!!.get("pdus") as Array<Any>
var messages: Array<SmsMessage?> = arrayOfNulls(pdusArr.size)
// if SMSis Long and contain more than 1 Message we'll read all of them
for (i in pdusArr.indices) {
messages[i] = SmsMessage.createFromPdu(pdusArr[i] as ByteArray)
}
var MobileNumber: String? = messages[0]?.originatingAddress
Log.i(TAG, "MobileNumber =$MobileNumber")
val bodyText = StringBuilder()
for (i in messages.indices) {
bodyText.append(messages[i]?.messageBody)
}
body = bodyText.toString()
if (body.isNotEmpty()){
// Do something, save SMS in DB or variable , static object or ....
Log.i("Inside Receiver :" , "body =$body")
}
}
}
3-Get SMS Permission if Android 6 and above:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ActivityCompat.checkSelfPermission(context!!,
Manifest.permission.RECEIVE_SMS
) != PackageManager.PERMISSION_GRANTED
) { // Needs permission
requestPermissions(arrayOf(Manifest.permission.RECEIVE_SMS),
PERMISSIONS_REQUEST_READ_SMS
)
} else { // Permission has already been granted
}
4- Add this request code to Activity or fragment :
companion object {
const val PERMISSIONS_REQUEST_READ_SMS = 100
}
5- Override Check permisstion Request result fun :
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSIONS_REQUEST_READ_SMS -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("BroadCastReceiver", "PERMISSIONS_REQUEST_READ_SMS Granted")
} else {
// toast("Permission must be granted ")
}
}
}
}
Provide the data frame and a string of comma separated names to remove:
remove_features <- function(df, features) {
rem_vec <- unlist(strsplit(features, ', '))
res <- df[,!(names(df) %in% rem_vec)]
return(res)
}
Usage:
remove_features(iris, "Sepal.Length, Petal.Width")
You could dispatching events like
el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
Update your cordova to the latest version and the issue should be resolved. In case the issue not resolved please set the path in the environment variable (in case of Windows). Example: System Variable Value name GRADLE_HOME Value D:\Android\Android Studio\gradle\gradle-4.3.1 (please replace with your path)
Workaround:
Window -> Preferences -> Java -> Installed JREs, select a different JRE
maybe this JDK edition is not suitable:
So try this one instead:
Problem solved!
Create a macro and use the following code to grab the data and put it in a new sheet (Sheet2):
Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1
For i = 1 To 700 Step 7
strCellNum = "A" & i
strValue = Worksheets("Sheet1").Range(strCellNum).Value
Debug.Print strValue
Worksheets("Sheet2").Range("A" & x).Value = strValue
x = x + 1
Next
Let me know if this helps! JFV
while (<@INC>)
This joins the paths in @INC together in a string, separated by spaces, then calls glob() on the string, which then iterates through the space-separated components (unless there are file-globbing meta-characters.)
This doesn't work so well if there are paths in @INC containing spaces, \, [], {}, *, ?, or ~, and there seems to be no reason to avoid the safe alternative:
for (@INC)
for ( int i=0 ; i<=list.size() ; i++){
....}
By executing this for loop , the loop will execute with a thrown exception as IndexOutOfBoundException
cause, suppose list size is 10 , so when index i will get to 10 i.e when i=10 the exception will be thrown cause index=size
, i.e. i=size
and as known that Java considers index starting from 0,1,2...etc the expression which Java agrees upon is index < size
. So the solution for such exception is to make the statement in loop as i<list.size()
for ( int i=0 ; i<list.size() ; i++){
...}
i have encountered that same problem. found out the case was the class name. i dealt with it by changing the name. hence resolving the problem.
For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.
After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope
if there is no $scope
for that element)
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.
Hope it will help.
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
A reference is semantically the following:
T& <=> *(T * const)
const T& <=> *(T const * const)
T&& <=> [no C equivalent]
(C++11)
As with other answers, the following from the C++ FAQ is the one-line answer: references when possible, pointers when needed.
An advantage over pointers is that you need explicit casting in order to pass NULL. It's still possible, though. Of the compilers I've tested, none emit a warning for the following:
int* p() {
return 0;
}
void x(int& y) {
y = 1;
}
int main() {
x(*p());
}
A non-open source approach is: PDF Creator Pilot which provides more language options including C++, C#, Delphi, ASP, ASP.NET, VB, VB.NET, VBScript, PHP and Python
Consider the alternative:
<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
It should be the same thing of maven.compiler.source/maven.compiler.target
but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)
Of course you can write "something" a bit better to keep maintenance:
#include <iostream>
#include <cstdlib>
using namespace std;
class Something
{
public:
Something(int x, int y, int z) : a(x), b(y), c(z) { }
int a;
int b;
int c;
friend ostream& operator<<(ostream&, const Something&);
void print() const { printf("%i, %i, %i\n", a, b, c); }
};
ostream& operator<<(ostream& o, const Something& s)
{
o << s.a << ", " << s.b << ", " << s.c;
return o;
}
int main(void)
{
Something s(3, 2, 1);
// Output with printf
s.print(); // Simple as well, isn't it?
// Output with cout
cout << s << endl;
return 0;
}
And a bit extended test of cout vs. printf, added a test of 'double', if anyone wants to do more testing (Visual Studio 2008, release version of the executable):
#include <stdio.h>
#include <iostream>
#include <ctime>
class TimedSection {
char const *d_name;
//timespec d_start;
clock_t d_start;
public:
TimedSection(char const *name) :
d_name(name)
{
//clock_gettime(CLOCK_REALTIME, &d_start);
d_start = clock();
}
~TimedSection() {
clock_t end;
//clock_gettime(CLOCK_REALTIME, &end);
end = clock();
double duration = /*1e3 * (end.tv_sec - d_start.tv_sec) +
1e-6 * (end.tv_nsec - d_start.tv_nsec);
*/
(double) (end - d_start) / CLOCKS_PER_SEC;
std::cerr << d_name << '\t' << std::fixed << duration * 1000.0 << " ms\n";
}
};
int main() {
const int iters = 1000000;
char const *text = "01234567890123456789";
{
TimedSection s("cout with only endl");
for (int i = 0; i < iters; ++i)
std::cout << std::endl;
}
{
TimedSection s("cout with only '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << '\n';
}
{
TimedSection s("printf with only '\\n'");
for (int i = 0; i < iters; ++i)
printf("\n");
}
{
TimedSection s("cout with string constant and endl");
for (int i = 0; i < iters; ++i)
std::cout << "01234567890123456789" << std::endl;
}
{
TimedSection s("cout with string constant and '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << "01234567890123456789\n";
}
{
TimedSection s("printf with string constant and '\\n'");
for (int i = 0; i < iters; ++i)
printf("01234567890123456789\n");
}
{
TimedSection s("cout with some stuff and endl");
for (int i = 0; i < iters; ++i)
std::cout << text << "01234567890123456789" << i << std::endl;
}
{
TimedSection s("cout with some stuff and '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << text << "01234567890123456789" << i << '\n';
}
{
TimedSection s("printf with some stuff and '\\n'");
for (int i = 0; i < iters; ++i)
printf("%s01234567890123456789%i\n", text, i);
}
{
TimedSection s("cout with formatted double (width & precision once)");
std::cout << std::fixed << std::scientific << std::right << std::showpoint;
std::cout.width(8);
for (int i = 0; i < iters; ++i)
std::cout << text << 8.315 << i << '\n';
}
{
TimedSection s("cout with formatted double (width & precision on each call)");
std::cout << std::fixed << std::scientific << std::right << std::showpoint;
for (int i = 0; i < iters; ++i)
{ std::cout.width(8);
std::cout.precision(3);
std::cout << text << 8.315 << i << '\n';
}
}
{
TimedSection s("printf with formatted double");
for (int i = 0; i < iters; ++i)
printf("%8.3f%i\n", 8.315, i);
}
}
The result is:
cout with only endl 6453.000000 ms
cout with only '\n' 125.000000 ms
printf with only '\n' 156.000000 ms
cout with string constant and endl 6937.000000 ms
cout with string constant and '\n' 1391.000000 ms
printf with string constant and '\n' 3391.000000 ms
cout with some stuff and endl 9672.000000 ms
cout with some stuff and '\n' 7296.000000 ms
printf with some stuff and '\n' 12235.000000 ms
cout with formatted double (width & precision once) 7906.000000 ms
cout with formatted double (width & precision on each call) 9141.000000 ms
printf with formatted double 3312.000000 ms
This helped me understand / streamline, only what I needed to animate:
// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}
.base {
max-width: 0vw;
opacity: 0;
transition-property: max-width, opacity; // relative order
transition-duration: 2s, 4s; // effects relatively ordered animation properties
transition-delay: 6s; // effects delay of all animation properties
animation-timing-function: ease;
&:hover {
max-width: 100vw;
opacity: 1;
transition-duration: 5s; // effects duration of all aniomation properties
transition-delay: 2s, 7s; // effects relatively ordered animation properties
}
}
~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class
As of Chrome 52, the UI has changed. When the Developer Tools dialog is open, you select the vertical ellipsis and can then choose the docking position:
Select the icon on the left to open the Chrome Developer Tools in a new window:
Click and hold the button next to the close button of the Developer Tool in order to reveal the "Undock into separate window" option.
Note: A "press" is not enough in that state.
It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id
was given, and assign it to req.user
.
Below, you could have a route like:
app.get('/users', function(req, res) {
// check for and maybe do something with req.user
});
Since /users/123 will match the route in your example first, that will first check and find user 123
; then /users
can do something with the result of that.
Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users
model with an async findOne()
:
function loadUser(req, res, next) {
if (req.params.userId) {
Users.findOne({ id: req.params.userId }, function(err, user) {
if (err) {
next(new Error("Couldn't find user: " + err));
return;
}
req.user = user;
next();
});
} else {
next();
}
}
// ...
app.get('/user/:userId', loadUser, function(req, res) {
// do something with req.user
});
app.get('/users/:userId?', loadUser, function(req, res) {
// if req.user was set, it's because userId was specified (and we found the user).
});
// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {
req.user.items.append(req.item.name);
});
Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:
/**
* Only allows the page to be accessed if the user is an admin.
* Requires use of `loadUser` middleware.
*/
function requireAdmin(req, res, next) {
if (!req.user || !req.user.admin) {
next(new Error("Permission denied."));
return;
}
next();
}
app.get('/top/secret', loadUser, requireAdmin, function(req, res) {
res.send('blahblahblah');
});
Hope this gave you some inspiration!
if you know what unknown is,
you can do something like
myArray = zeros(2,2);
for i: 1:unknown
myArray(:,i) = zeros(x,y);
end
However it has been a while since I last used matlab. so this page might shed some light on the matter :
You can use killall command as well .
-o, --older-than Match only processes that are older (started before) the time specified. The time is specified as a float then a unit. The units are s,m,h,d,w,M,y for seconds, minutes, hours, days,
-e, --exact Require an exact match for very long names.
-r, --regexp Interpret process name pattern as an extended regular expression.
This worked like a charm.
There is a problem with objects such as PACKAGE_BODY:
SELECT DBMS_METADATA.get_ddl(object_Type, object_name, owner) FROM ALL_OBJECTS WHERE OWNER = 'WEBSERVICE';
ORA-31600 invalid input value PACKAGE BODY parameter OBJECT_TYPE in function GET_DDL
ORA-06512: ?? "SYS.DBMS_METADATA", line 4018
ORA-06512: ?? "SYS.DBMS_METADATA", line 5843
ORA-06512: ?? line 1
31600. 00000 - "invalid input value %s for parameter %s in function %s"
*Cause: A NULL or invalid value was supplied for the parameter.
*Action: Correct the input value and try the call again.
SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type,' ','_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1');
Perhaps the easiest one compare to several others.
\(?\d+\)?[-.\s]?\d+[-.\s]?\d+
It matches the following:
(555) 444-6789
555-444-6789
555.444.6789
555 444 6789
Use the children funcion of jQuery.
$("#text-field").keydown(function(event) {
if($('#popup').children('p.filled-text').length > 0) {
console.log("Found");
}
});
$.children('').length
will return the count of child elements which match the selector.
In Global.asax.cs, Application_Start() method add:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));
I used line-height:0
and it works fine for me.
This worked for me!
Resolving EACCES permissions errors when installing packages globally
no need to that, tomcat naturally extract the war file into a folder of the same name. you simply modify the desired file inside that folder (including .xml configuration files), that's all. technically no need to restart tomcat after applying the modifications
There are quite significant differences when it comes to working with branches (especially short-term ones).
It is explained in this article (BranchingExplained) which compares Mercurial with Git.
You could also use:
nvidia-smi | grep "CUDA Version:"
To retrieve the explicit line.
Simple way is to use:
echo '<script>window.location.href = "the-target-page.php";</script>';
BlogPost.find_each(&:destroy)
This code should work:
>>> iter = (i for i in range(50))
>>> sum(1 for _ in iter)
50
Although it does iterate through each item and count them, it is the fastest way to do so.
It also works for when the iterator has no item:
>>> sum(1 for _ in range(0))
0
Of course, it runs forever for an infinite input, so remember that iterators can be infinite:
>>> sum(1 for _ in itertools.count())
[nothing happens, forever]
Also, be aware that the iterator will be exhausted by doing this, and further attempts to use it will see no elements. That's an unavoidable consequence of the Python iterator design. If you want to keep the elements, you'll have to store them in a list or something.
This issue vexed me for some time. I was using reactive forms and I fixed it using this method. PS. Using Angular 9 and Material 9.
In the "ngOnInit" lifecycle hook
1) Get the object you want to set as the default from your array or object literal
const countryDefault = this.countries.find(c => c.number === '826');
Here I am grabbing the United Kingdom object from my countries array.
2) Then set the formsbuilder object (the mat-select) with the default value.
this.addressForm.get('country').setValue(countryDefault.name);
3) Lastly...set the bound value property. In my case I want the name value.
<mat-select formControlName="country">
<mat-option *ngFor="let country of countries" [value]="country.name" >
{{country.name}}
</mat-option>
</mat-select>
Works like a charm. I hope it helps
I advise you to go with Scanner
instead of DataInputStream
. Scanner
is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner
.
Example
Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
Call c_str()
to get a const char *
(LPCSTR
) from a std::string
.
It's all in the name:
LPSTR
- (long) pointer to string - char *
LPCSTR
- (long) pointer to constant string - const char *
LPWSTR
- (long) pointer to Unicode (wide) string - wchar_t *
LPCWSTR
- (long) pointer to constant Unicode (wide) string - const wchar_t *
LPTSTR
- (long) pointer to TCHAR (Unicode if UNICODE is defined, ANSI if not) string - TCHAR *
LPCTSTR
- (long) pointer to constant TCHAR string - const TCHAR *
You can ignore the L (long) part of the names -- it's a holdover from 16-bit Windows.
public class PlaindromeNumbers {
int func1(int n)
{
if(n==1)
return 1;
return n*func1(n-1);
}
static boolean check=false;
int func(int no)
{
String a=""+no;
String reverse = new StringBuffer(a).reverse().toString();
if(a.equals(reverse))
{
if(!a.contains("0"))
{
System.out.println("hey");
check=true;
return Integer.parseInt(a);
}
}
// else
// {
func(no++);
if(check==true)
{
return 0;
}
return 0;
}
public static void main(String[] args) {
// TODO code application logic here
Scanner in=new Scanner(System.in);
System.out.println("Enter testcase");
int testcase=in.nextInt();
while(testcase>0)
{
int a=in.nextInt();
PlaindromeNumbers obj=new PlaindromeNumbers();
System.out.println(obj.func(a));
testcase--;
}
}
}
I put above-mentioned methods together using ax
instead of plt
import numpy as np
import matplotlib.pyplot as plt
x = range(100)
y = x
fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.plot(x, y);
# method 1
print(ax.get_xlim())
print(ax.get_xlim())
# method 2
print(ax.axis())
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
If you define your array like this:
string[][] table = new string[][] {
new string[] { "aa", "aaa" },
new string[]{ "bb", "bbb" }
};
Then you can use a foreach loop on it.
Yup, this is possible of course. Here are several examples.
-- one way to do this
DECLARE @Cnt int
SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn
-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)
-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double
SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable
string startTime = "7:00 AM";
string endTime = "2:00 PM";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Will output: 07:00:00.
It also works if the user input military time:
string startTime = "7:00";
string endTime = "14:00";
TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));
Console.WriteLine(duration);
Console.ReadKey();
Outputs: 07:00:00.
To change the format: duration.ToString(@"hh\:mm")
More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Addendum:
Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".
Works fine for me, the code needed around the getResource() thing is as follows:
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> spinner, View v,
int arg2, long arg3) {
String selectedVal = getResources().getStringArray(R.array.compass_rate_values)[spinner.getSelectedItemPosition()];
//Do something with the value
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Just need to make sure (by yourself) the values in the two arrays are aligned properly!
Since the verification is based on package's name, you can change the package name inside your config.xml or manifest file for another name you want.
When publishing your app don't forget to change back the name!
window.print();
unless you mean a custom looking popup.
I messed around with a lot of the suggestions on this post.
I had the following but still could not land on a break point. Throwing an exception proved the code was being entered.
<appSettings>
...
<add key="owin:AutomaticAppStartup" value="true" />
<add key="owin:appStartup" value="SSOResource.Startup, SSOResource" />
...
</appSettings>
Finally out of desperation I looked at project->properties, and then under the WEB section I also checked the NATIVE CODE checkbox (ASP.NET should be already checked).
That finally fixed it for me.
Note : I am using Visual Studio 2017 Professional.
Try this:
SELECT *
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'YourTable';
This should deliver you which Tables have references to the table you want to drop, once you drop these references, or the datasets which reference datasets in this table you will be able to drop the table
Since you have the manual user input loop, after the scanner has read your first input it will pass the carriage/return into the next line which will also be read; of course, that is not what you wanted.
You can try this
try {
// ...
} catch (InputMismatchException e) {
reader.next();
}
or alternatively, you can consume that carriage return before reading your next double input by calling
reader.next()
Cluster differs from Cloud and Grid in that a cluster is a group of computers connected by a local area network (LAN), whereas cloud and grid are more wide scale and can be geographically distributed. Another way to put it is to say that a cluster is tightly coupled, whereas a Grid or a cloud is loosely coupled. Also, clusters are made up of machines with similar hardware, whereas clouds and grids are made up of machines with possibly very different hardware configurations.
To know more about cloud computing, I recommend reading this paper: «Above the Clouds: A Berkeley View of Cloud Computing», Michael Armbrust, Armando Fox, Rean Griffith, Anthony D. Joseph, Randy H. Katz, Andrew Konwinski, Gunho Lee, David A. Patterson, Ariel Rabkin, Ion Stoica and Matei Zaharia. The following is an abstract from the above paper:
Cloud Computing refers to both the applications delivered as services over the Internet and the hardware and systems software in the datacenters that provide those services. The services themselves have long been referred to as Software as a Service (SaaS). The datacenter hardware and software is what we call a Cloud. When a Cloud is made available in a pay-as-you-go manner to the general public, we call it a Public Cloud; the service being sold is Utility Computing. We use the term Private Cloud to refer to internal datacenters of a business or other organization, not made available to the general public. Thus, Cloud Computing is the sum of SaaS and Utility Computing, but does not include Private Clouds. People can be users or providers of SaaS, or users or providers of Utility Computing.
The difference between a cloud and a grid can be expressed as below:
Resource distribution: Cloud computing is a centralized model whereas grid computing is a decentralized model where the computation could occur over many administrative domains.
Ownership: A grid is a collection of computers which is owned by multiple parties in multiple locations and connected together so that users can share the combined power of resources. Whereas a cloud is a collection of computers usually owned by a single party.
Examples of Clouds: Amazon Web Services (AWS), Google App Engine.
Examples of Grids: FutureGrid.
Examples of cloud computing services: Dropbox, Gmail, Facebook, Youtube, RapidShare.
Maybe this answer is so late, but it's useful.
to do it,we have 3 steps:
1- Create a modal structure in HTML.
2- Create a button to call a function in java script, to open modal and set display:none
in CSS .
3- Call this button by function in code behind .
you can see these steps in below snippet :
HTML modal:
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">
Registration done Successfully</h4>
</div>
<div class="modal-body">
<asp:Label ID="lblMessage" runat="server" />
</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>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Hidden Button:
<button type="button" style="display: none;" id="btnShowPopup" class="btn btn-primary btn-lg"
data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
Script Code:
<script type="text/javascript">
function ShowPopup() {
$("#btnShowPopup").click();
}
</script>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup();", true);
this.lblMessage.Text = "Your Registration is done successfully. Our team will contact you shotly";
}
this solution is one of any solutions that I used it .
in XAMPP the default root is "htdocs" inside the XAMPP folder, if you followed the instructions on the xampp homepage it would be "/opt/lampp/htdocs"
Please check: http://man7.org/linux/man-pages/man5/proc.5.html
address perms offset dev inode pathname
00400000-00452000 r-xp 00000000 08:02 173521 /usr/bin/dbus-daemon
The address field is the address space in the process that the mapping occupies.
The perms field is a set of permissions:
r = read
w = write
x = execute
s = shared
p = private (copy on write)
The offset field is the offset into the file/whatever;
dev is the device (major:minor);
inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).
The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).
Under Linux 2.0, there is no field giving pathname.
As an alternative to bc, you can use awk within your script.
For example:
echo "$IMG_WIDTH $IMG2_WIDTH" | awk '{printf "%.2f \n", $1/$2}'
In the above, " %.2f " tells the printf function to return a floating point number with two digits after the decimal place. I used echo to pipe in the variables as fields since awk operates properly on them. " $1 " and " $2 " refer to the first and second fields input into awk.
And you can store the result as some other variable using:
RESULT = `echo ...`
Using pandas:
import pandas as pd
xls = pd.ExcelFile(r"yourfilename.xls") #use r before absolute file path
sheetX = xls.parse(2) #2 is the sheet number+1 thus if the file has only 1 sheet write 0 in paranthesis
var1 = sheetX['ColumnName']
print(var1[1]) #1 is the row number...
For me,
Even after upgrading to appcompat-v7:22.1.0
, in which AppCompatActivty
is added,
the problem was not resolved for me, Android Studio was giving same problem
Cannot resolve symbol 'AppCompatActivity'
Sometimes clearing the android studio caches help.
In android studio I just cleared the caches and restarted with the following option--
File->Invalidate Caches/Restart
Leave off the quotes
$cmd &
$othercmd &
eg:
nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash
cmd="ls -la"
$cmd &
nicholas@nick-win7 /tmp
$ ./test
nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root 0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx 1 nicholas None 35 2010-09-10 20:44 test
-rwxr-xr-x 1 nicholas None 41 2010-09-10 20:43 test~
The real easy way to do that it is
word = str(raw_input(""))
is_palindrome = word.find(word[::-1])
if is_palindrome == 0:
print True
else:
print False
And if/else here just for fancy looks. The question about palindrome was on Amazon's interview for QA
I have met the same problem and after long investigation of my XML file I found the problem: there was few unescaped characters like «
»
.
After installing Anaconda3 on your system you need to add Anaconda to the PATH environment variable. This will allow you to access Anaconda with the 'conda' command from cmd.exe or PowerShell.
The link I provided below go through the three major issues with not recognized error. Which are:
My issue was resolved following the steps for issue #2 Environment PATH is incorrectly added. I did not have all three file paths in my variable environment.
Try browse the WCF in IIS see if it's alive and works normally,
In my case it's because the physical path of the WCF is misdirected.
imo the best approach is using GraphicsMagick Image Processing System with im4java as a comand-line interface for Java.
There are a lot of advantages of GraphicsMagick, but one for all:
Based on the previous answer,
from urllib.request import Request, urlopen
#specify url
url = 'https://xyz/xyz'
req = Request(url, headers={'User-Agent': 'XYZ/3.0'})
response = urlopen(req, timeout=20).read()
This worked for me by extending the timeout.
please try with below query
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
convert(datetime, convert(varchar(10), created_date, 102)) <= convert(datetime,'2013-04-12')
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
This code will open and read lines of complete text file That variable "ReadedData" Holds the text line in memory
Open "C:\satheesh\myfile\Hello.txt" For Input As #1
do until EOF(1)
Input #1, ReadedData
loop**
What I found worked was checking the "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions => Web Projects section under the Tools=>Options menu.
With anonymous classes, you are actually declaring a "nameless" nested class. For nested classes, the compiler generates a new standalone public class with a constructor that will take all the variables it uses as arguments (for "named" nested classes, this is always an instance of the original/enclosing class). This is done because the runtime environment has no notion of nested classes, so there needs to be a (automatic) conversion from a nested to a standalone class.
Take this code for example:
public class EnclosingClass {
public void someMethod() {
String shared = "hello";
new Thread() {
public void run() {
// this is not valid, won't compile
System.out.println(shared); // this instance expects shared to point to the reference where the String object "hello" lives in heap
}
}.start();
// change the reference 'shared' points to, with a new value
shared = "other hello";
System.out.println(shared);
}
}
That won't work, because this is what the compiler does under the hood:
public void someMethod() {
String shared = "hello";
new EnclosingClass$1(shared).start();
// change the reference 'shared' points to, with a new value
shared = "other hello";
System.out.println(shared);
}
The original anonymous class is replaced by some standalone class that the compiler generates (code is not exact, but should give you a good idea):
public class EnclosingClass$1 extends Thread {
String shared;
public EnclosingClass$1(String shared) {
this.shared = shared;
}
public void run() {
System.out.println(shared);
}
}
As you can see, the standalone class holds a reference to the shared object, remember that everything in java is pass-by-value, so even if the reference variable 'shared' in EnclosingClass gets changed, the instance it points to is not modified, and all other reference variables pointing to it (like the one in the anonymous class: Enclosing$1), will not be aware of this. This is the main reason the compiler forces you to declare this 'shared' variables as final, so that this type of behavior won't make it into your already running code.
Now, this is what happens when you use an instance variable inside an anonymous class (this is what you should do to solve your problem, move your logic to an "instance" method or a constructor of a class):
public class EnclosingClass {
String shared = "hello";
public void someMethod() {
new Thread() {
public void run() {
System.out.println(shared); // this is perfectly valid
}
}.start();
// change the reference 'shared' points to, with a new value
shared = "other hello";
System.out.println(shared);
}
}
This compiles fine, because the compiler will modify the code, so that the new generated class Enclosing$1 will hold a reference to the instance of EnclosingClass where it was instantiated (this is only a representation, but should get you going):
public void someMethod() {
new EnclosingClass$1(this).start();
// change the reference 'shared' points to, with a new value
shared = "other hello";
System.out.println(shared);
}
public class EnclosingClass$1 extends Thread {
EnclosingClass enclosing;
public EnclosingClass$1(EnclosingClass enclosing) {
this.enclosing = enclosing;
}
public void run() {
System.out.println(enclosing.shared);
}
}
Like this, when the reference variable 'shared' in EnclosingClass gets reassigned, and this happens before the call to Thread#run(), you'll see "other hello" printed twice, because now EnclosingClass$1#enclosing variable will keep a reference to the object of the class where it was declared, so changes to any attribute on that object will be visible to instances of EnclosingClass$1.
For more information on the subject, you can see this excelent blog post (not written by me): http://kevinboone.net/java_inner.html
The default port for SQL Server Database Engine is 1433.
And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.
Bascailly, "a b" selects all b's inside a, while "a>b" selects b's what are only children to the a, it will not select b what is child of b what is child of a.
This example illustrates the difference:
div span{background:red}
div>span{background:green}
<div><span>abc</span><span>def<span>ghi</span></span></div>
Background color of abc and def will be green, but ghi will have red background color.
IMPORTANT: If you change order of the rules to:
div>span{background:green}
div span{background:red}
All letters will have red background, because descendant selector selects child's too.
As a refinement of simplest solution, and if you can’t or don’t want to install Powershell, just run:
dir /s /b | sort /r /+261 > out.txt
or (faster):
dir /s /b | sort /r /+261 /o out.txt
And lines longer than 260 will get to the top of listing. Note that you must add 1 to SORT column parameter (/+n).
You can do this concisely using the toolbelt vg. It's a light layer on top of numpy and it supports single values and stacked vectors.
import numpy as np
import vg
x = np.array([1, 2, 3, 4, 5])
mag1 = np.linalg.norm(x)
mag2 = vg.magnitude(x)
print mag1 == mag2
# True
I created the library at my last startup, where it was motivated by uses like this: simple ideas which are far too verbose in NumPy.
I use the QPython app. It's free and includes a code editor, an interactive interpreter and a package manager, allowing you to create and execute Python programs directly on your device.
Note: This code is untested
Define a record for your refCursor return type, call it rec. For example:
TYPE MyRec IS RECORD (col1 VARCHAR2(10), col2 VARCHAR2(20), ...); --define the record
rec MyRec; -- instantiate the record
Once you have the refcursor returned from your procedure, you can add the following code where your comments are now:
LOOP
FETCH refCursor INTO rec;
EXIT WHEN refCursor%NOTFOUND;
dbms_output.put_line(rec.col1||','||rec.col2||','||...);
END LOOP;
I struggled with this issue for a long time... My solution was to modify the php.ini file, in the folder that contained the php script. This was important, as modifying the php.ini at the root did not resolve the problem (I have a php.ini in each folder for granular control). The relevant entries in my php.ini looked like this.... (the output_buffering is not likely needed for this issue)
output_buffering = On
upload_max_filesize = 20M
post_max_size = 21M
Based on the correct answer, but taking into account ASCII control characters as well, the solution that worked for me is this:
SELECT * FROM `table` WHERE NOT `field` REGEXP "[\\x00-\\xFF]|^$";
It does the same thing: searches for violations of the ASCII range in a column, but lets you search for control characters too, since it uses hexadecimal notation for code points. Since there is no comparison or conversion (unlike @Ollie's answer), this should be significantly faster, too. (Especially if MySQL does early-termination on the regex query, which it definitely should.)
It also avoids returning fields that are zero-length. If you want a slightly-longer version that might perform better, you can use this instead:
SELECT * FROM `table` WHERE `field` <> "" AND NOT `field` REGEXP "[\\x00-\\xFF]";
It does a separate check for length to avoid zero-length results, without considering them for a regex pass. Depending on the number of zero-length entries you have, this could be significantly faster.
Note that if your default character set is something bizarre where 0x00-0xFF don't map to the same values as ASCII (is there such a character set in existence anywhere?), this would return a false positive. Otherwise, enjoy!
I recommend a generic solution so you don't have to add the code for every form. Use the jquery form plugin (http://jquery.malsup.com/form/) and add this code.
$(function(){
$('form.ajax_submit').submit(function() {
$(this).ajaxSubmit();
//validation and other stuff
return false;
});
});
If you need to change the value of another field, you can use this:
<input type="hidden" id="mainvalue" name="mainvalue" value="0">
<select onChange="document.getElementById('mainvalue').value = this.value;">
<option value="0">option 1</option>
<option value="1">option 2</option>
</select>
Git doesn't store file permissions other than executable scripts. Consider using something like git-cache-meta to save file ownership and permissions.
Git can only store two types of modes: 755 (executable) and 644 (not executable). If your file was 444 git would store it has 644.
Within the code of my app I can get the running device IP andress easily like beolow:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
One time I had a problem while using Off
instead of off
. And also check the pads one more time... The path has to be exact. Also add the following line to your environmental variable.
C:\your-apache-path\bin; C:\your-php-path\bin;C:\your-mysql-path\bin
If you are in Windows, right click My Computer, select properties, and navigate to the Advanced tab... (is Windows 7). Click on Advanced system settings first then select the Advanced tab and then Environmental variables. Select PATH and click on Edit. Make a copy of the string in a .txt file for back up (it might be empty)--- set your environmental variables... Log out and log back in.
S3_REGION="eu-central-1"
bucket="mybucket1"
name="objectname"
import boto3
from botocore.client import Config
client = boto3.client('s3',region_name=S3_REGION,config=Config(signature_version='s3v4'))
list = client.list_objects_v2(Bucket=bucket,Prefix=name)
for obj in list.get('Contents', []):
if obj['Key'] == name: return True
return False
This probably should be a comment under the cmdow.exe
answer, but here is a simple batch file I wrote to allow for fairly sophisticated and simple control over all windows that you can see in the taskbar.
First step is to run cmdow /t
to display a list of those windows. Look at what the image name is in the column Image
, then command line:
mycmdowscript.cmd imagename
Here are the contents of the batch file:
:: mycmdowscript.cmd
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET IMAGE=%1
SET ACTION=/%2
SET REST=1
SET PARAMS=
:: GET ANY ADDITIONAL PARAMS AND STORE THEM IN A VARIABLE
FOR %%I in (%*) DO (
IF !REST! geq 3 (
SET PARAMS=!PARAMS! %%I
)
SET /A REST+=1
)
FOR /F "USEBACKQ tokens=1,8" %%I IN (`CMDOW /t`) DO (
IF %IMAGE%==%%J (
:: you now have access to the handle in %%I
cmdow %%I %ACTION% !PARAMS!
)
)
ENDLOCAL
@echo on
EXIT /b
example usage
:: will set notepad to 500 500
mycmdowscript.cmd notepad siz 500 500
You could probably rewrite this to allow for multiple actions on a single command, but I haven't tried yet.
For this to work, cmdow.exe must be located in your path. Beware that when you download this, your AV program might yell at you. This tool has (I guess) in the past been used by malware authors to manipulate windows. It is not harmful by itself.
In PHP 5.3 or greater, you can get it like this:
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
This command:
git ls-tree --full-tree -r --name-only HEAD
lists all of the already committed files being tracked by your git repo.
Place dependency in pubspec.yaml
flutter_responsive_screen: ^1.0.0
Function hp = Screen(MediaQuery.of(context).size).hp;
Function wp = Screen(MediaQuery.of(context).size).wp;
Example :
return Container(height: hp(27),weight: wp(27));
Just thought I would help somebody with this.
Typically, you can just paste this in console.
$("body").css({"overflow":"visible"});
Or, the javascript only version:
document.body.style.overflow = "visible";
2014 While
is back
Just think logical.
Look at this
for( var index = 0 , length = array.length ; index < length ; index++ ) {
//do stuff
}
for
loop has 3 parametersNow tell me why this should be faster than:
var length = array.length;
while( --length ) { //or length--
//do stuff
}
while
has only one parameterI was totally confused when Chrome 28 showed that the for loop is faster than the while. This must have ben some sort of
"Uh, everyone is using the for loop, let's focus on that when developing for chrome."
But now, in 2014 the while loop is back on chrome. it's 2 times faster , on other/older browsers it was always faster.
Lately i made some new tests. Now in real world envoirement those short codes are worth nothing and jsperf can't actually execute properly the while loop, because it needs to recreate the array.length which also takes time.
you CAN'T get the actual speed of a while loop on jsperf.
you need to create your own custom function and check that with window.performance.now()
And yeah... there is no way the while loop is simply faster.
The real problem is actually the dom manipulation / rendering time / drawing time or however you wanna call it.
For example i have a canvas scene where i need to calculate the coordinates and collisions... this is done between 10-200 MicroSeconds (not milliseconds). it actually takes various milliseconds to render everything.Same as in DOM.
BUT
There is another super performant way using the for loop
in some cases... for example to copy/clone an array
for(
var i = array.length ;
i > 0 ;
arrayCopy[ --i ] = array[ i ] // doing stuff
);
Notice the setup of the parameters:
Said that, this confirms that machines like the --
writing that i was thinking to make it a little shorter and remove some useless stuff and wrote this one using the same style:
for(
var i = array.length ;
i-- ;
arrayCopy[ i ] = array[ i ] // doing stuff
);
Even if it's shorter it looks like using i
one more time slows down everything.
It's 1/5 slower than the previous for
loop and the while
one.
Note: the ;
is very important after the for looo without {}
Even if i just told you that jsperf is not the best way to test scripts .. i added this 2 loops here
http://jsperf.com/caching-array-length/40
And here is another answer about performance in javascript
https://stackoverflow.com/a/21353032/2450730
This answer is to show performant ways of writing javascript. So if you can't read that, ask and you will get an answer or read a book about javascript http://www.ecma-international.org/ecma-262/5.1/
I sometimes encounter the same issue. I can only answer your second bullet, because I am not as expert in R as I am with other languages. I have found that the standard for
loop has some unexpected results. Say x = 0
for (i in 1:x) {
print(i)
}
The output is
[1] 1
[1] 0
Whereas with python, for example
for i in range(x):
print i
does nothing. The loop is not entered.
I expected that if x = 0
that in R, the loop would not be entered. However, 1:0
is a valid range of numbers. I have not yet found a good workaround besides having an if
statement wrapping the for
loop
I had this problem too. I used the disableSelection()
method of jQuery UI on a parent DIV which contained my input fields. In Chrome the input fields were not affected but in Firefox the inputs (and textareas as well) did not get focused on clicking. The strange thing here was, that the click event on these inputs worked.
The solution was to remove the disableSelection()
method for the parent DIV.
Adding to what @sateesh said, when you just want to mock a void method in order to prevent the test from calling it, you could use a Spy
this way:
World world = new World();
World spy = Mockito.spy(world);
Mockito.doNothing().when(spy).methodToMock();
When you want to run your test, make sure you call the method in test on the spy
object and not on the world
object. For example:
assertEquals(0, spy.methodToTestThatShouldReturnZero());
Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.
1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
2. $ git branch <new_branch> (creates new branch)
3. $ git checkout new_branch
4. $ git add . (After making changes in the current branch)
5. $ git commit -m "type commit msg here"
6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
7. $ git merge new_branch (starts merging)
8. $ git push origin master (push to the remote server)
I referred this blog and I found it to be a cleaner approach.
If you want to use your dataframe object only once, use:
df['BoolCol'].loc[lambda x: x==True].index
To demonstrate how the USING and ON clauses work, let's assume we have the following post
and post_comment
database tables, which form a one-to-many table relationship via the post_id
Foreign Key column in the post_comment
table referencing the post_id
Primary Key column in the post
table:
The parent post
table has 3 rows:
| post_id | title |
|---------|-----------|
| 1 | Java |
| 2 | Hibernate |
| 3 | JPA |
and the post_comment
child table has the 3 records:
| post_comment_id | review | post_id |
|-----------------|-----------|---------|
| 1 | Good | 1 |
| 2 | Excellent | 1 |
| 3 | Awesome | 2 |
Traditionally, when writing an INNER JOIN
or LEFT JOIN
query, we happen to use the ON clause to define the join condition.
For example, to get the comments along with their associated post title and identifier, we can use the following SQL projection query:
SELECT
post.post_id,
title,
review
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id
And, we get back the following result set:
| post_id | title | review |
|---------|-----------|-----------|
| 1 | Java | Good |
| 1 | Java | Excellent |
| 2 | Hibernate | Awesome |
When the Foreign Key column and the column it references have the same name, we can use the USING clause, like in the following example:
SELECT
post_id,
title,
review
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id
And, the result set for this particular query is identical to the previous SQL query that used the ON clause:
| post_id | title | review |
|---------|-----------|-----------|
| 1 | Java | Good |
| 1 | Java | Excellent |
| 2 | Hibernate | Awesome |
The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn't support the USING clause, so you need to use the ON clause instead.
The USING clause can be used with INNER, LEFT, RIGHT, and FULL JOIN statements.
SELECT *
Now, if we change the previous ON clause query to select all columns using SELECT *
:
SELECT *
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id
We are going to get the following result set:
| post_id | title | post_comment_id | review | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1 | Java | 1 | Good | 1 |
| 1 | Java | 2 | Excellent | 1 |
| 2 | Hibernate | 3 | Awesome | 2 |
As you can see, the
post_id
is duplicated because both thepost
andpost_comment
tables contain apost_id
column.
SELECT *
On the other hand, if we run a SELECT *
query that features the USING clause for the JOIN condition:
SELECT *
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id
We will get the following result set:
| post_id | title | post_comment_id | review |
|---------|-----------|-----------------|-----------|
| 1 | Java | 1 | Good |
| 1 | Java | 2 | Excellent |
| 2 | Hibernate | 3 | Awesome |
You can see that this time, the
post_id
column is deduplicated, so there is a singlepost_id
column being included in the result set.
If the database schema is designed so that Foreign Key column names match the columns they reference, and the JOIN conditions only check if the Foreign Key column value is equal to the value of its mirroring column in the other table, then you can employ the USING clause.
Otherwise, if the Foreign Key column name differs from the referencing column or you want to include a more complex join condition, then you should use the ON clause instead.
Try like this format and use "width" attribute to manage the image size, it is simple. JavaScript can be implemented in element too.
<button><img src=""></button>
_x000D_
For Angular 9+ You can add headers and params directly without the key-value notion:
const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params});
If you are only concerned with getting an integer value out of a whole floating point number (i.e. 12347.9999 or 54321.0001), this approach (borrowed and modified from above) will do the trick:
my $rounded = floor($float + 0.1);
The WITH syntax appears to be valid in an inline view, e.g.
UPDATE (WITH comp AS ...
SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
SET SomeColumn=ComputedValue;
But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view
, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.
You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:
MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;
But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING
clause arbitrarily complex, incorporating multiple WITH
clauses.
As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.
To answer your specific questions:
Here is a functional ES6 way of iterating over a NodeList
. This method uses the Array
's forEach
like so:
Array.prototype.forEach.call(element.childNodes, f)
Where f
is the iterator function that receives a child nodes as it's first parameter and the index as the second.
If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:
const forEach = f => x => Array.prototype.forEach.call(x, f);
// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)
// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)
(You can do the same trick for map()
and other Array functions.)
Try obuildfactory.
There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.
Until then enjoy, sir :)
You may use Upsert with $setOnInsert operator.
db.Table.update({noExist: true}, {"$setOnInsert": {xxxYourDocumentxxx}}, {upsert: true})
To find the names of all files modified since your last commit:
git diff --name-only
Or (for a bit more information, including untracked files):
git status
If you are running multiple extensions that perform ad or script blocking you will need to
individually update each one to your whitelist
Taking from this source, here are some of the extensions that may cause the case and how to deal with them.
Adblock Plus
Firefox Tracking Protection
In Firefox “Tracking Protection” may activate our adblock notice. It can be temporarily disabled for a browsing session by clicking the “shield” icon in the url bar if visible and following the instructions.
For further details on Tracking Protection please review Mozilla’s support.
Adblock
Ghostery
uBlock / uBlock Origin
Click the uBlock / uBlock Origin icon.
Click the “power” button in the menu that appears to whitelist the current web site.
Click the reload icon to reload the page you were viewing.
Disconnect
Kaspersky Ant-Banner
Please review How to configure Anti-Banner in Kaspersky Total Security for information on how to whitelist with Kaspersky Total Security.
echo.|set /p=>file
echo.
suppress the "Command ECHO activated"
|set /p=
prevent newline (and file is now 0 byte)
This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,
function pingAddress($ip) {
$pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);
if ($status==0) {
$status = "alive";
} else {
$status = "dead";
}
$message .= '<div id="dialog-block-left">';
$message .= '<div id="ip-status">The IP address, '.$ip.', is '.$status.'</div><div style="clear:both"></div>';
return $message;
}
// Some IP Address
pingAddress("192.168.1.1");
This worked perfectly for me, finally. I referred this from http://www.phpscriptsdaily.com/php/php-ping/ Hope this will help
Well I want to modify this as it is working fine on my localhost but not on my live server For live server, I got another thing which now works for both local as well as live.
$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }
Then I show the Server is up for 0 and down for 1.
This works perfectly for me. I got this from Ping site and return result in PHP Thanks @karim79
line 2 should be
for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**
For line 3, I'm having to do
JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
I came across a similar situation while trying to fetch a List
of Project
s, rather than the default Iterable<T> findAll()
declared in CrudRepository
interface. So, in my ProjectRepository
interface (which extends from CrudRepository
), I simply declared the findAll()
method to return a List<Project>
instead of Iterable<Project>
.
package com.example.projectmanagement.dao;
import com.example.projectmanagement.entities.Project;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface ProjectRepository extends CrudRepository<Project, Long> {
@Override
List<Project> findAll();
}
This is the simplest solution, I think, without requiring conversion logic or usage of external libraries.
That is a pretty standard use case for apply()
:
R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
start end newcol
1 1 2 1.5
2 3 6 4.5
3 5 7 6.0
4 7 9 8.0
R>
You can also use plyr
if you prefer but here is no real need to go beyond functions from base R.
shell request failed on channel 0
mean you don't have shell or remote commands access, fix your user permission on server to have shell access or if you just want tunneling use -N
and -T
options
If you don't have the option to delete the already existing file in the new location, but still need to move and delete from the original location, this renaming trick might work:
string newFileLocation = @"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);
This assumes the only '.' in the file name is before the extension. It splits the file in two before the extension, attaches "_copy." in between. This lets you move the file, but creates a copy if the file already exists or a copy of the copy already exists, or a copy of the copy of the copy exists... ;)
It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.
It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.
Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146
Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml
@Path("/customer")
public class CustomerService {
private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();
@POST
@Path("save")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public SaveResult save(Customer c) {
customers.put(c.getId(), c);
SaveResult sr = new SaveResult();
sr.sucess = true;
return sr;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Customer getCustomer(@PathParam("id") int id) {
Customer c = customers.get(id);
if (c == null) {
c = new Customer();
c.setId(id * 3);
c.setName("unknow " + id);
}
return c;
}
}
And in the pom.xml
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
If you happen to be using Visual Studio 2017+
This will do it all for you.
$(window).scroll(function () {
var Bottom = $(window).height() + $(window).scrollTop() >= $(document).height();
if(Bottom )
{
$('#div').hide();
}
});
Use the FileSystemObject
object, namely, its CreateFolder
and CopyFile
methods. Basically, this is what your script will look like:
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
' Create a new folder
oFSO.CreateFolder "C:\MyFolder"
' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"
You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder
raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:
Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FolderExists(strFolder) Then
oFSO.CreateFolder strFolder
End If
oFSO.CopyFile strFile, strFolder, Overwrite
I didn't like the slide effect either. To fix this all you have to do is make the the top
attribute the same for both .modal.fade and modal.fade.in. You can take off the top 0.3s ease-out
in the transitions too, but it doesn't hurt to leave it in. I like this approach because the fade in/out works, it just kills the slide.
.modal.fade {
top: 20%;
-webkit-transition: opacity 0.3s linear;
-moz-transition: opacity 0.3s linear;
-o-transition: opacity 0.3s linear;
transition: opacity 0.3s linear;
}
.modal.fade.in {
top: 20%;
}
If you're looking for a bootstrap 3 answer, look here
exit
is a helper for the interactive shell - sys.exit
is intended for use in programs.
The
site
module (which is imported automatically during startup, except if the-S
command-line option is given) adds several constants to the built-in namespace (e.g.exit
). They are useful for the interactive interpreter shell and should not be used in programs.
Technically, they do mostly the same: raising SystemExit
. sys.exit
does so in sysmodule.c:
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
PyObject *exit_code = 0;
if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
return NULL;
/* Raise SystemExit so callers may catch it or clean up. */
PyErr_SetObject(PyExc_SystemExit, exit_code);
return NULL;
}
While exit
is defined in site.py and _sitebuiltins.py, respectively.
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()
).
There is the semicolon missing (;) after the "50%"
but you should also notice that the percentage of your div is connected to the div that contains it.
for instance:
<div id="wrapper">
<div class="container">
adsf
</div>
</div>
#wrapper {
height:100px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.
if you have:
adsf
#wrapper {
height:400px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
then you .container will be 200px. 50% of the wrapper.
So you may want to look at the divs "wrapping" your ".container"...
you can use this code
if (DecimalVariable.Equals(null))
{
//something statements
}
require_once('db/connect.php');
//rand(1000000 , 9999999);
$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];
do
{
array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));
/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);
for ($i=0; $i < $row_counter; $i++)
{
$current_row = $ids_array[$i];
$rand = rand(1000000 , 9999999);
mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}
Singleton scope in spring means single instance in a Spring context ..
Spring container merely returns the same instance again and again for subsequent calls to get the bean.
And spring doesn't bother if the class of the bean is coded as singleton or not , in fact if the class is coded as singleton whose constructor as private, Spring use BeanUtils.instantiateClass (javadoc here) to set the constructor to accessible and invoke it.
Alternatively, we can use a factory-method attribute in bean definition like this
<bean id="exampleBean" class="example.Singleton" factory-method="getInstance"/>
You can switch between windows as below:
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// Perform the actions on new window
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
// Continue with original browser (first window)
Apart from above information, there is still an interesting history of LF (\n) and CR (\r). [Original author : ??? Source : http://www.ruanyifeng.com/blog/2006/04/post_213.html] Before computer came out, there was a type of teleprinter called Teletype Model 33. It can print 10 characters each second. But there is one problem with this, after finishing printing each line, it will take 0.2 second to move to next line, which is time of printing 2 characters. If a new characters is transferred during this 0.2 second, then this new character will be lost.
So scientists found a way to solve this problem, they add two ending characters after each line, one is 'Carriage return', which is to tell the printer to bring the print head to the left.; the other one is 'Line feed', it tells the printer to move the paper up 1 line.
Later, computer became popular, these two concepts are used on computers. At that time, the storage device was very expensive, so some scientists said that it was expensive to add two characters at the end of each line, one is enough, so there are some arguments about which one to use.
In UNIX/Mac and Linux, '\n' is put at the end of each line, in Windows, '\r\n' is put at the end of each line. The consequence of this use is that files in UNIX/Mac will be displayed in one line if opened in Windows. While file in Windows will have one ^M at the end of each line if opened in UNIX or Mac.
No 3rd-party frameworks; Allows query string; Adds trailing slash; Handles 404
Create a public_html
subfolder and place all of your content in it.
Gist: https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3
var fs = require('fs');
require('http').createServer(function(request, response) {
var path = 'public_html'+ request.url.slice(0,
(request.url.indexOf('?')+1 || request.url.length+1) - 1);
fs.stat(path, function(bad_path, path_stat) {
if (bad_path) respond(404);
else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
response.setHeader('Location', path.slice(11)+'/');
respond(301);
} else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
function(bad_file, file_content) {
if (bad_file) respond(404);
else respond(200, file_content);
});
});
function respond(status, content) {
response.statusCode = status;
response.end(content);
}
}).listen(80, function(){console.log('Server running on port 80...')});
Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.
Best way to swap images with javascript with left vertical clickable thumbnails
SCRIPT FILE: function swapImages() {
window.onload = function () {
var img = document.getElementById("img_wrap");
var imgall = img.getElementsByTagName("img");
var firstimg = imgall[0]; //first image
for (var a = 0; a <= imgall.length; a++) {
setInterval(function () {
var rand = Math.floor(Math.random() * imgall.length);
firstimg.src = imgall[rand].src;
}, 3000);
imgall[1].onmouseover = function () {
//alert("what");
clearInterval();
firstimg.src = imgall[1].src;
}
imgall[2].onmouseover = function () {
clearInterval();
firstimg.src = imgall[2].src;
}
imgall[3].onmouseover = function () {
clearInterval();
firstimg.src = imgall[3].src;
}
imgall[4].onmouseover = function () {
clearInterval();
firstimg.src = imgall[4].src;
}
imgall[5].onmouseover = function () {
clearInterval();
firstimg.src = imgall[5].src;
}
}
}
}
Remember, if you are inside of private red with some proxy, you must be logout and relogin with an external WIFI for example.
Short code example:
.slider ul {
overflow: hidden;
-webkit-transition: max-height 3.3s ease;
}
.slider.hide ul {
max-height: 0px;
}
.slider.show ul {
max-height: 1000px;
}
Java Heap Memory is part of memory allocated to JVM by Operating System.
Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.
You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:
Young , Tenured and Perm generation
PermGen has been replaced with Metaspace since Java 8 release.
Regarding your queries:
Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.
If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write
{% for athlete in athlete_list %}
...
{% empty %}
No athletes
{% endfor %}
Useful when the something that you want to do involves special treatment for lists that might be empty.
I defined an OnClickListener for ImageView as an OnClickListener for a button and it seems to be working fine. Here's what I had. Please try and let us know if it doesn't work.
final ImageView imageview1 = (ImageView) findViewById(R.id.imageView1);
imageview1.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
try {
Log.i("MyTag","Image button is pressed, visible in LogCat");;
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});
From Wikipedia (you can read which is correct for your OS at that article):
Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, '\r\n', 0x0D0A).
Just wrap all that inside a ScrollView
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ruatech.sanikamal.justjava.MainActivity">
<!-- Here you put the rest of your current view-->
</ScrollView>
Try my way :
robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR
Had to put /XD
before /MIR
while including the full Destination Source directly after /XD
.
Line magics are only supported by the IPython command line. They cannot simply be used inside a script, because %something
is not correct Python syntax.
If you want to do this from a script you have to get access to the IPython API and then call the run_line_magic
function.
Instead of %matplotlib inline
, you will have to do something like this in your script:
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
A similar approach is described in this answer, but it uses the deprecated magic
function.
Note that the script still needs to run in IPython. Under vanilla Python the get_ipython
function returns None
and get_ipython().run_line_magic
will raise an AttributeError
.
Sorry for answering again on that question... I needed to embed the image.
I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds.
Sourcecode of the screenshot:
@Override
protected void onDraw( Canvas canvas ) {
for( int i = 0; i < 20; i++ ) {
int startSize = 10;
int curSize = i + startSize;
paint.setTextSize( curSize );
String text = i + startSize + " - " + TEXT_SNIPPET;
Rect bounds = new Rect();
paint.getTextBounds( text, 0, text.length(), bounds );
float top = STEP_DISTANCE * i + curSize;
bounds.top += top;
bounds.bottom += top;
canvas.drawRect( bounds, bgPaint );
canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
}
}
I've been thinking about this too. From a C background, you can simulate function return code types, as well as, parameter types, using something like the following:
function top_function() {
var rc;
console.log("1st call");
rc = Number(test_function("number", 1, "string", "my string"));
console.log("typeof rc: " + typeof rc + " rc: " + rc);
console.log("2nd call");
rc = Number(test_function("number", "a", "string", "my string"));
console.log("typeof rc: " + typeof rc + " rc: " + rc);
}
function test_function(parm_type_1, parm_val_1, parm_type_2, parm_val_2) {
if (typeof parm_val_1 !== parm_type_1) console.log("Parm 1 not correct type");
if (typeof parm_val_2 !== parm_type_2) console.log("Parm 2 not correct type");
return parm_val_1;
}
The Number before the calling function returns a Number type regardless of the type of the actual value returned, as seen in the 2nd call where typeof rc = number but the value is NaN
the console.log for the above is:
1st call
typeof rc: number rc: 1
2nd call
Parm 1 not correct type
typeof rc: number rc: NaN
I was trying a hello world program, and this line:
#include <stdio.h>
was underlined green. I tried:
fixed the error warning. i don't know if it fixed the actual problem. But then i'm compiling via a linux VM on Windows 10
Do I need Class elements in persistence.xml?
No, you don't necessarily. Here is how you do it in Eclipse (Kepler tested):
Right click on the project, click Properties, select JPA, in the Persistence class management tick Discover annotated classes automatically.
function focusNextElement(){
var focusable = [].slice.call(document.querySelectorAll("a, button, input, select, textarea, [tabindex], [contenteditable]")).filter(function($e){
if($e.disabled || ($e.getAttribute("tabindex") && parseInt($e.getAttribute("tabindex"))<0)) return false;
return true;
}).sort(function($a, $b){
return (parseFloat($a.getAttribute("tabindex") || 99999) || 99999) - (parseFloat($b.getAttribute("tabindex") || 99999) || 99999);
});
var focusIndex = focusable.indexOf(document.activeElement);
if(focusable[focusIndex+1]) focusable[focusIndex+1].focus();
};
String dir="/Attendancesystem";
public void displaypdf() {
File file = null;
file = new File(Environment.getExternalStorageDirectory()+dir+ "/sample.pdf");
Toast.makeText(getApplicationContext(), file.toString() , Toast.LENGTH_LONG).show();
if(file.exists()) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
else
Toast.makeText(getApplicationContext(), "File path is incorrect." , Toast.LENGTH_LONG).show();
}
The C99 stdint.h
defines these:
int8_t
int16_t
int32_t
uint8_t
uint16_t
uint32_t
And, if the architecture supports them:
int64_t
uint64_t
There are various other integer typedefs in stdint.h
as well.
If you're stuck without a C99 environment then you should probably supply your own typedefs and use the C99 ones anyway.
The uint32
and uint64
(i.e. without the _t
suffix) are probably application specific.
For example: conda install -c conda-forge spacy
Your class might implement the Comparable interface to achieve the same functionality. Your class should implement the compareTo() method declared in the interface.
public class MyClass implements Comparable<MyClass>{
String a;
public MyClass(String ab){
a = ab;
}
// returns an int not a boolean
public int compareTo(MyClass someMyClass){
/* The String class implements a compareTo method, returning a 0
if the two strings are identical, instead of a boolean.
Since 'a' is a string, it has the compareTo method which we call
in MyClass's compareTo method.
*/
return this.a.compareTo(someMyClass.a);
}
public static void main(String[] args){
MyClass object1 = new MyClass("test");
MyClass object2 = new MyClass("test");
if(object1.compareTo(object2) == 0){
System.out.println("true");
}
else{
System.out.println("false");
}
}
}
db.adminCommand( { getLog: "*" } )
Then
db.adminCommand( { getLog : "global" } )
To remove the variable from the current environment (not permanently):
set FOOBAR=
To permanently remove the variable from the user environment (which is the default place setx
puts it):
REG delete HKCU\Environment /F /V FOOBAR
If the variable is set in the system environment (e.g. if you originally set it with setx /M
), as an administrator run:
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
Note: The REG
commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.
>= Angular 4.3
for the introduced HttpClientModule
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
FormsModule, // if used
HttpClientModule,
JsonpModule // if used
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Angular2 >= RC.5
Import HttpModule
to the module where you use it (here for example the AppModule
:
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
BrowserModule,
FormsModule, // if used
HttpModule,
JsonpModule // if used
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Importing the HttpModule
is quite similar to adding HTTP_PROVIDERS
in previous version.
Edit: Answer updated to reflect changes in recent versions of NAudio
It's possible using the NAudio open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the MP3Frame
and AcmMp3FrameDecompressor
classes in NAudio to decompress streamed MP3 on the fly.
I have posted an article on my blog explaining how to play back an MP3 stream using NAudio. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a BufferedWaveProvider
. Another thread then plays back using the BufferedWaveProvider
as an input.
Here's a function that can include an optional offset for those fixed headers. No external libraries needed.
function scrollIntoView(selector, offset = 0) {
window.scroll(0, document.querySelector(selector).offsetTop - offset);
}
You can grab the height of an element using JQuery and scroll to it.
var headerHeight = $('.navbar-fixed-top').height();
scrollIntoView('#some-element', headerHeight)
Update March 2018
Scroll to this answer without using JQuery
scrollIntoView('#answer-44786637', document.querySelector('.top-bar').offsetHeight)
I came up with 4 methods to achieve the results. Here is demo
Method 1:
#a {
margin-right: auto;
}
Method 2:
#a {
flex-grow: 1;
}
Method 3:
#b {
margin-left: auto;
}
Method 4:
#container {
justify-content: space-between;
}
The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). Most of the time, the array module is used to interface with C code. To give you a more direct answer to your question about performance:
Arrays are more efficient than lists for some uses. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory. GvR has an optimization anecdote in which the array module comes out to be the winner (long read, but worth it).
On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.
TL;DR I'd only use an array if you had an exceptional optimization need or you need to interface with C code (and can't use pyrex).
Because when you call $( "#form_id" ).submit();
it triggers the external submit handler which prevents the default action, instead use
$( "#form_id" )[0].submit();
or
$form.submit();//declare `$form as a local variable by using var $form = this;
When you call the dom element's submit method programatically, it won't trigger the submit handlers attached to the element
You could try using unidecode
, which is available as a ruby gem and as a perl module on cpan. Essentially, it works as a huge lookup table, where each unicode code point relates to an ascii character or string.
There is one more way to achieve it:-
Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
.Top = 30
.Left = 30
.Width = 200
.Height = 340
.ColumnHeads = True
.ColumnCount = 2
.ColumnWidths = "100;100"
.MultiSelect = fmMultiSelectExtended
.RowSource = "Sheet1!C4:D25"
End With End Sub
Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.
The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.
Naïve datetime
versus aware datetime
Default datetime
objects are said to be "naïve": they keep time information without the time zone information. Think about naïve datetime
as a relative number (ie: +4
) without a clear origin (in fact your origin will be common throughout your system boundary).
In contrast, think about aware datetime
as absolute numbers (ie: 8
) with a common origin for the whole world.
Without timezone information you cannot convert the "naive" datetime towards any non-naive time representation (where does +4
targets if we don't know from where to start ?). This is why you can't have a datetime.datetime.toutctimestamp()
method. (cf: http://bugs.python.org/issue1457227)
To check if your datetime
dt
is naïve, check dt.tzinfo
, if None
, then it's naïve:
datetime.now() ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1) ## returns naïve datetime pointing on user given time
I have naïve datetimes, what can I do ?
You must make an assumption depending on your particular context:
The question you must ask yourself is: was your datetime
on UTC ? or was it local time ?
If you were using UTC (you are out of trouble):
import calendar
def dt2ts(dt):
"""Converts a datetime object to UTC timestamp
naive datetime will be considered UTC.
"""
return calendar.timegm(dt.utctimetuple())
If you were NOT using UTC, welcome to hell.
You have to make your datetime
non-naïve prior to using the former
function, by giving them back their intended timezone.
You'll need the name of the timezone and the information about if DST was in effect when producing the target naïve datetime (the last info about DST is required for cornercases):
import pytz ## pip install pytz
mytz = pytz.timezone('Europe/Amsterdam') ## Set your timezone
dt = mytz.normalize(mytz.localize(dt, is_dst=True)) ## Set is_dst accordingly
Consequences of not providing is_dst
:
Not using is_dst
will generate incorrect time (and UTC timestamp)
if target datetime was produced while a backward DST was put in place
(for instance changing DST time by removing one hour).
Providing incorrect is_dst
will of course generate incorrect
time (and UTC timestamp) only on DST overlap or holes. And, when
providing
also incorrect time, occuring in "holes" (time that never existed due
to forward shifting DST), is_dst
will give an interpretation of
how to consider this bogus time, and this is the only case where
.normalize(..)
will actually do something here, as it'll then
translate it as an actual valid time (changing the datetime AND the
DST object if required). Note that .normalize()
is not required
for having a correct UTC timestamp at the end, but is probably
recommended if you dislike the idea of having bogus times in your
variables, especially if you re-use this variable elsewhere.
and AVOID USING THE FOLLOWING: (cf: Datetime Timezone conversion using pytz)
dt = dt.replace(tzinfo=timezone('Europe/Amsterdam')) ## BAD !!
Why? because .replace()
replaces blindly the tzinfo
without
taking into account the target time and will choose a bad DST object.
Whereas .localize()
uses the target time and your is_dst
hint
to select the right DST object.
OLD incorrect answer (thanks @J.F.Sebastien for bringing this up):
Hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive datetime
object as it is related to the system configuration that you would hopefully NOT change between the naive datetime object creation and the moment when you want to get the UTC timestamp. This trick can be used to give an imperfect question.
By using time.mktime
we can create an utc_mktime
:
def utc_mktime(utc_tuple):
"""Returns number of seconds elapsed since epoch
Note that no timezone are taken into consideration.
utc tuple must be: (year, month, day, hour, minute, second)
"""
if len(utc_tuple) == 6:
utc_tuple += (0, 0, 0)
return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))
def datetime_to_timestamp(dt):
"""Converts a datetime object to UTC timestamp"""
return int(utc_mktime(dt.timetuple()))
You must make sure that your datetime
object is created on the same timezone than the one that has created your datetime
.
This last solution is incorrect because it makes the assumption that the UTC offset from now is the same than the UTC offset from EPOCH. Which is not the case for a lot of timezones (in specific moment of the year for the Daylight Saving Time (DST) offsets).
The best way is to use:
$("#yourid option:selected").text();
Depending on the requirement, you could also use this way:
var v = $("#yourid").val();
$("#yourid option[value="+v+"]").text()
There are also the following options:
docker container ls
docker container ls -a
# --all, -a
# Show all containers (default shows just running)
since: 1.13.0 (2017-01-18):
Restructure CLI commands by adding
docker image
anddocker container
commands for more consistency #26025
and as stated here: Introducing Docker 1.13, users are encouraged to adopt the new syntax:
CLI restructured
In Docker 1.13, we regrouped every command to sit under the logical object it’s interacting with. For example
list
andstart
of containers are now subcommands ofdocker container
andhistory
is a subcommand ofdocker image
.These changes let us clean up the Docker CLI syntax, improve help text and make Docker simpler to use. The old command syntax is still supported, but we encourage everybody to adopt the new syntax.
For Python, I haven't found an OpenCV function that provides contrast. As others have suggested, there are some techniques to automatically increase contrast using a very simple formula.
In the official OpenCV docs, it is suggested that this equation can be used to apply both contrast and brightness at the same time:
new_img = alpha*old_img + beta
where alpha corresponds to a contrast and beta is brightness. Different cases
alpha 1 beta 0 --> no change
0 < alpha < 1 --> lower contrast
alpha > 1 --> higher contrast
-127 < beta < +127 --> good range for brightness values
In C/C++, you can implement this equation using cv::Mat::convertTo, but we don't have access to that part of the library from Python. To do it in Python, I would recommend using the cv::addWeighted function, because it is quick and it automatically forces the output to be in the range 0 to 255 (e.g. for a 24 bit color image, 8 bits per channel). You could also use convertScaleAbs
as suggested by @nathancy.
import cv2
img = cv2.imread('input.png')
# call addWeighted function. use beta = 0 to effectively only operate one one image
out = cv2.addWeighted( img, contrast, img, 0, brightness)
output = cv2.addWeighted
The above formula and code is quick to write and will make changes to brightness and contrast. But they yield results that are significantly different than photo editing programs. The rest of this answer will yield a result that will reproduce the behavior in the GIMP and also LibreOffice brightness and contrast. It's more lines of code, but it gives a nice result.
In the GIMP, contrast levels go from -127 to +127. I adapted the formulas from here to fit in that range.
f = 131*(contrast + 127)/(127*(131-contrast))
new_image = f*(old_image - 127) + 127 = f*(old_image) + 127*(1-f)
To figure out brightness, I figured out the relationship between brightness and levels and used information in this levels post to arrive at a solution.
#pseudo code
if brightness > 0
shadow = brightness
highlight = 255
else:
shadow = 0
highlight = 255 + brightness
new_img = ((highlight - shadow)/255)*old_img + shadow
Putting it all together and adding using the reference "mandrill" image from USC SIPI:
import cv2
import numpy as np
# Open a typical 24 bit color image. For this kind of image there are
# 8 bits (0 to 255) per color channel
img = cv2.imread('mandrill.png') # mandrill reference image from USC SIPI
s = 128
img = cv2.resize(img, (s,s), 0, 0, cv2.INTER_AREA)
def apply_brightness_contrast(input_img, brightness = 0, contrast = 0):
if brightness != 0:
if brightness > 0:
shadow = brightness
highlight = 255
else:
shadow = 0
highlight = 255 + brightness
alpha_b = (highlight - shadow)/255
gamma_b = shadow
buf = cv2.addWeighted(input_img, alpha_b, input_img, 0, gamma_b)
else:
buf = input_img.copy()
if contrast != 0:
f = 131*(contrast + 127)/(127*(131-contrast))
alpha_c = f
gamma_c = 127*(1-f)
buf = cv2.addWeighted(buf, alpha_c, buf, 0, gamma_c)
return buf
font = cv2.FONT_HERSHEY_SIMPLEX
fcolor = (0,0,0)
blist = [0, -127, 127, 0, 0, 64] # list of brightness values
clist = [0, 0, 0, -64, 64, 64] # list of contrast values
out = np.zeros((s*2, s*3, 3), dtype = np.uint8)
for i, b in enumerate(blist):
c = clist[i]
print('b, c: ', b,', ',c)
row = s*int(i/3)
col = s*(i%3)
print('row, col: ', row, ', ', col)
out[row:row+s, col:col+s] = apply_brightness_contrast(img, b, c)
msg = 'b %d' % b
cv2.putText(out,msg,(col,row+s-22), font, .7, fcolor,1,cv2.LINE_AA)
msg = 'c %d' % c
cv2.putText(out,msg,(col,row+s-4), font, .7, fcolor,1,cv2.LINE_AA)
cv2.putText(out, 'OpenCV',(260,30), font, 1.0, fcolor,2,cv2.LINE_AA)
cv2.imwrite('out.png', out)
I manually processed the images in the GIMP and added text tags in Python/OpenCV:
Note: @UtkarshBhardwaj has suggested that Python 2.x users must cast the contrast correction calculation code into float for getting floating result, like so:
...
if contrast != 0:
f = float(131*(contrast + 127))/(127*(131-contrast))
...
From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a +=
or a -=
. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is null
- if so, then no event handler has been added. If not, then maybe and you can loop through the values in
Delegate.GetInvocationList. If one is equal to the delegate that you want to add as event handler, then you know it's there.
public bool IsEventHandlerRegistered(Delegate prospectiveHandler)
{
if ( this.EventHandler != null )
{
foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
if ( existingHandler == prospectiveHandler )
{
return true;
}
}
}
return false;
}
And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore -=
and +=
, as suggested by @Lou Franco.
However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.
I just discovered that tabulate has a HTML option and is rather simple to use.
Quite similar to Wayne Werner's answer:
from IPython.display import HTML, display
import tabulate
table = [["Sun",696000,1989100000],
["Earth",6371,5973.6],
["Moon",1737,73.5],
["Mars",3390,641.85]]
display(HTML(tabulate.tabulate(table, tablefmt='html')))
Still looking for something simple to use to create more complex table layouts like with latex syntax and formatting to merge cells and do variable substitution in a notebook:
Allow references to Python variables in Markdown cells #2958
void FindMax()
{
int lessonNum;
System.out.print("Enter your lesson numbers : ");
lessonNum = input.nextInt();
int[] numbers = new int[lessonNum];
for (int i = 0; i < numbers.length; i++)
{
System.out.print("Please enter " + (i + 1) + " number : ");
numbers[i] = input.nextInt();
}
double max = numbers[0];
for (int i = 1; i < numbers.length; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
System.out.println("Maximum number is : " + max);
}
Before answering, I would like to give you some data from Wiki
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.
When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}sSampleStruct;
sizeof(sSampleStruct)
will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:
typedef struct
{
char Data1;
//3-Bytes Added here.
int Data2;
unsigned short Data3;
char Data4;
//1-byte Added here.
}sSampleStruct;
We can use __attribute__((packed, aligned(X)))
to insist particular(X) sized padding. X should be powers of two. Refer here
typedef struct
{
char Data1;
int Data2;
unsigned short Data3;
char Data4;
}__attribute__((packed, aligned(1))) sSampleStruct;
so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.
If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma
#pragma pack(push, 1)
//Structure 1
......
//Structure 2
......
#pragma pack(pop)
With the "classic" method, if the cast fails, an InvalidCastException
is thrown. With the as
method, it results in null
, which can be checked for, and avoid an exception being thrown.
Also, you can only use as
with reference types, so if you are typecasting to a value type, you must still use the "classic" method.
Note:
The as
method can only be used for types that can be assigned a null
value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null
value, they are valid to use with the as
operator.
Do it like so
all: program1 program2
program1: program1.c
gcc -o program1 program1.c
program2: program2.c
gcc -o program2 program2.c
You said you don't want advanced stuff, but you could also shorten it like this based on some default rules.
all: program1 program2
program1: program1.c
program2: program2.c
You can use JavaScripts Fetch API (available in your browser) to make network requests.
If using node, you will need to install the node-fetch package.
const url = "https://api.wit.ai/message?v=20140826&q=";
const options = {
headers: {
Authorization: "Bearer 6Q************"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );
Two's complement subtracts off (1<<bits)
if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.
A function for two's complement of an int...
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is
Going from a binary string is particularly easy...
binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))
A bit more useful to me is going from hex values (32 bits in this example)...
hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)
You can use the statement
- name: webfolder - Creates web folder
file: path=/srv/www state=directory owner=www-data group=www-data mode=0775`
Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:
A new config setting core.eol
is being added/evolved:
This is a replacement for the 'Add "
core.eol
" config variable' commit that's currently inpu
(the last one in my series).
Instead of implying that "core.autocrlf=true
" is a replacement for "* text=auto
", it makes explicit the fact thatautocrlf
is only for users who want to work with CRLFs in their working directory on a repository that doesn't have text file normalization.
When it is enabled, "core.eol" is ignored.Introduce a new configuration variable, "
core.eol
", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native
", which means CRLF on Windows and LF everywhere else. Note that "core.autocrlf
" overridescore.eol
.
This means that:[core] autocrlf = true
puts CRLFs in the working directory even if
core.eol
is set to "lf
".core.eol:
Sets the line ending type to use in the working directory for files that have the
text
property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value isnative
.
Other evolutions are being considered:
For 1.8, I would consider making
core.autocrlf
just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.
git 2.8 (March 2016) improves the way core.autocrlf
influences the eol:
See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit c6b94eb, 26 Feb 2016)
convert.c
: refactorcrlf_action
Refactor the determination and usage of
crlf_action
.
Today, when no "crlf
" attribute are set on a file,crlf_action
is set toCRLF_GUESS
. UseCRLF_UNDEFINED
instead, and search for "text
" or "eol
" as before.Replace the old
CRLF_GUESS
usage:
CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT
Make more clear, what is what, by defining:
- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
and core.eol is evaluated and one of CRLF_BINARY,
CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY : No processing of line endings.
- CRLF_TEXT : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true (no attributes)
As torek adds in the comments:
all these translations (any EOL conversion from
eol=
orautocrlf
settings, and "clean
" filters) are run when files move from work-tree to index, i.e., duringgit add
rather than atgit commit
time.
(Note thatgit commit -a
or--only
or--include
do add files to the index at that time, though.)
For more on that, see "What is difference between autocrlf and eol".
yes, %c
will print a single char:
printf("%c", 'h');
also, putchar
/putc
will work too. From "man putchar":
#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).
EDIT:
Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
Nope. You can't do that.
The reason is that a UIImageView
instance does not store an image file. It stores a displays a UIImage
instance. When you make an image from a file, you do something like this:
UIImage *picture = [UIImage imageNamed:@"myFile.png"];
Once this is done, there is no longer any reference to the filename. The UIImage
instance contains the data, regardless of where it got it. Thus, the UIImageView
couldn't possibly know the filename.
Also, even if you could, you would never get filename info from a view. That breaks MVC.
The @Inject
annotation is one of the JSR-330 annotations collection. This has Match by Type,Match by Qualifier, Match by Name execution paths.
These execution paths are valid for both setter and field injection.The behavior of @Autowired
annotation is same as the @Inject
annotation. The only difference is the @Autowired
annotation is a part of the Spring framework. @Autowired
annotation also has the above execution paths. So I recommend the @Autowired
for your answer.
Similar to answers above, but for python3, arguably readable and arguably extensible:
from pathlib import Path
class DisplayablePath(object):
display_filename_prefix_middle = '+--'
display_filename_prefix_last = '+--'
display_parent_prefix_middle = ' '
display_parent_prefix_last = '¦ '
def __init__(self, path, parent_path, is_last):
self.path = Path(str(path))
self.parent = parent_path
self.is_last = is_last
if self.parent:
self.depth = self.parent.depth + 1
else:
self.depth = 0
@property
def displayname(self):
if self.path.is_dir():
return self.path.name + '/'
return self.path.name
@classmethod
def make_tree(cls, root, parent=None, is_last=False, criteria=None):
root = Path(str(root))
criteria = criteria or cls._default_criteria
displayable_root = cls(root, parent, is_last)
yield displayable_root
children = sorted(list(path
for path in root.iterdir()
if criteria(path)),
key=lambda s: str(s).lower())
count = 1
for path in children:
is_last = count == len(children)
if path.is_dir():
yield from cls.make_tree(path,
parent=displayable_root,
is_last=is_last,
criteria=criteria)
else:
yield cls(path, displayable_root, is_last)
count += 1
@classmethod
def _default_criteria(cls, path):
return True
@property
def displayname(self):
if self.path.is_dir():
return self.path.name + '/'
return self.path.name
def displayable(self):
if self.parent is None:
return self.displayname
_filename_prefix = (self.display_filename_prefix_last
if self.is_last
else self.display_filename_prefix_middle)
parts = ['{!s} {!s}'.format(_filename_prefix,
self.displayname)]
parent = self.parent
while parent and parent.parent is not None:
parts.append(self.display_parent_prefix_middle
if parent.is_last
else self.display_parent_prefix_last)
parent = parent.parent
return ''.join(reversed(parts))
Example usage:
paths = DisplayablePath.make_tree(Path('doc'))
for path in paths:
print(path.displayable())
Example output:
doc/
+-- _static/
¦ +-- embedded/
¦ ¦ +-- deep_file
¦ ¦ +-- very/
¦ ¦ +-- deep/
¦ ¦ +-- folder/
¦ ¦ +-- very_deep_file
¦ +-- less_deep_file
+-- about.rst
+-- conf.py
+-- index.rst
A thread isn't a method - you don't normally "return" a value.
However, if you're trying to fetch a value back from the results of some processing, you have many options, the two main ones being:
It really depends on how you're creating the thread, and how you want to use it, as well as the language/framework/tools you're using.
I'll leave the discussion of the difference between Build Tools, Platform Tools, and Tools to others. From a practical standpoint, you only need to know the answer to your second question:
Answer: Use the most recent version.
For those using Android Studio with Gradle, the buildToolsVersion
has to be set in the build.gradle
(Module: app) file.
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
...
}
Open the Android SDK Manager.
The last item will show the most recent version.
Make sure it is installed and then write that number as the buildToolsVersion
in build.gradle
(Module: app).
Directly from the command line:
for /L %n in (1,1,100) do @echo %n
Using a batch file:
@echo off
for /L %%n in (1,1,100) do echo %%n
Displays:
1
2
3
...
100
This can be done in 2 ways:
if (str.match(/abc|def/)) {
...
}
if (/abc|def/.test(str)) {
....
}
You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...
num=(0, 0)
for item in tuplelist:
if item[1]>num[1]:
num=item #num has the whole tuple with the highest y value and its x value
gradle-wrapper.properties
Change this line:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
with
distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
build.gradle
(Project: your_app_name)Change this line
classpath 'com.android.tools.build:gradle:XXX'
to this
classpath 'com.android.tools.build:gradle:2.0.0-alpha3'
or
classpath 'com.android.tools.build:gradle:1.5.0'
Sync Now
File -> Invalidate Caches/Restart...
Invalidate and Restart
Android Studio would restart. After this, it should work normally
Hope it help
using System.Linq;
...
double total = myList.Sum(item => item.Amount);
You can use the Background Panel class. It does the custom painting as explained above but gives you options to display the image scaled, tiled or normal size. It also explains how you can use a JLabel with an image as the content pane for the frame.
The simple answer is that you can't. box-shadow applies to the whole element only. You could use a different approach and use ::before in CSS to insert an 1-pixel high element into header nav and set the box-shadow on that instead.
Might help some else - I came here because I missed putting two // after http:. This is what I had:
http:/abc.my.domain.com:55555/update
Let's make a Go 1-compatible list of all the ways to read and write files in Go.
Because file API has changed recently and most other answers don't work with Go 1. They also miss bufio
which is important IMHO.
In the following examples I copy a file by reading from it and writing to the destination file.
Start with the basics
package main
import (
"io"
"os"
)
func main() {
// open input file
fi, err := os.Open("input.txt")
if err != nil {
panic(err)
}
// close fi on exit and check for its returned error
defer func() {
if err := fi.Close(); err != nil {
panic(err)
}
}()
// open output file
fo, err := os.Create("output.txt")
if err != nil {
panic(err)
}
// close fo on exit and check for its returned error
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
// make a buffer to keep chunks that are read
buf := make([]byte, 1024)
for {
// read a chunk
n, err := fi.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
// write a chunk
if _, err := fo.Write(buf[:n]); err != nil {
panic(err)
}
}
}
Here I used os.Open
and os.Create
which are convenient wrappers around os.OpenFile
. We usually don't need to call OpenFile
directly.
Notice treating EOF. Read
tries to fill buf
on each call, and returns io.EOF
as error if it reaches end of file in doing so. In this case buf
will still hold data. Consequent calls to Read
returns zero as the number of bytes read and same io.EOF
as error. Any other error will lead to a panic.
Using bufio
package main
import (
"bufio"
"io"
"os"
)
func main() {
// open input file
fi, err := os.Open("input.txt")
if err != nil {
panic(err)
}
// close fi on exit and check for its returned error
defer func() {
if err := fi.Close(); err != nil {
panic(err)
}
}()
// make a read buffer
r := bufio.NewReader(fi)
// open output file
fo, err := os.Create("output.txt")
if err != nil {
panic(err)
}
// close fo on exit and check for its returned error
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
// make a write buffer
w := bufio.NewWriter(fo)
// make a buffer to keep chunks that are read
buf := make([]byte, 1024)
for {
// read a chunk
n, err := r.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
// write a chunk
if _, err := w.Write(buf[:n]); err != nil {
panic(err)
}
}
if err = w.Flush(); err != nil {
panic(err)
}
}
bufio
is just acting as a buffer here, because we don't have much to do with data. In most other situations (specially with text files) bufio
is very useful by giving us a nice API for reading and writing easily and flexibly, while it handles buffering behind the scenes.
Note: The following code is for older Go versions (Go 1.15 and before). Things have changed. For the new way, take a look at this answer.
Using ioutil
package main
import (
"io/ioutil"
)
func main() {
// read the whole file at once
b, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
// write the whole body at once
err = ioutil.WriteFile("output.txt", b, 0644)
if err != nil {
panic(err)
}
}
Easy as pie! But use it only if you're sure you're not dealing with big files.