The Node Knockout competition wrapped up recently, and many of the submissions are available on github. The competition site doesn't appear to be working right now, but I'm sure you could Google up a few entries to check out.
If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet
constructor:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Fix it by adding the context as the constructor arg:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
You may be victim of a garbage collection problem.
When your application requires memory and it's getting low on what it's configured to use the garbage collector will run often which consume a lot of CPU cycles. If it can't collect anything your memory will stay low so it will be run again and again. When you redeploy your application the memory is cleared and the garbage collection won't happen more than required so the CPU utilization stays low until it's full again.
You should check that there is no possible memory leak in your application and that it's well configured for memory (check the -Xmx
parameter, see What does Java option -Xmx stand for?)
Also, what are you using as web framework? JSF relies a lot on sessions and consumes a lot of memory, consider being stateless at most!
Do you really need to load it from a file? If you place it along your classes (in WEB-INF/classes) you can get an InputStream to it using the class loader:
InputStream csv =
SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");
Read Cookie
in Web Api
var cookie = actionContext.Request.Headers.GetCookies("newhbsslv1");
Logger.Log("Cookie " + cookie, LoggerLevel.Info);
Logger.Log("Cookie count " + cookie.Count, LoggerLevel.Info);
if (cookie != null && cookie.Count > 0)
{
Logger.Log("Befor For " , LoggerLevel.Info);
foreach (var perCookie in cookie[0].Cookies)
{
Logger.Log("perCookie " + perCookie, LoggerLevel.Info);
if (perCookie.Name == "newhbsslv1")
{
strToken = perCookie.Value;
}
}
}
I got this error trying to test a solution using the following
string cn = "Data Source=[servername];Integrated Security=true;Initial Catalog=[dbname];";
The way I solved was: I had to open Visual Studio and run it under another account, because the account I was using to open was not my Admin account.
So if your problem is similar to mine: pin the VS to the task bar, then use Shift and Right Click to open the menu so you can open VS as another user.
If you're using a standard POSIX OS, you use cron.
If you're using Windows, you use at.
Write a Django management command to
Figure out what platform they're on.
Either execute the appropriate "AT" command for your users, or update the crontab for your users.
You can use this to figure out keyCodes easily:
$(document).keyup(function(e) {
// Displays the keycode of the last pressed key in the body
$(document.body).html(e.keyCode);
});
This only works after you save a bookmark to the app to the home screen. Not if you just browse to the site normally.
If you need to load a file that's relative to some directory where you already are (like in the current directory), here's an easy solution:
File f;
if (System.getProperty("sun.arch.data.model").equals("32")) {
// 32-bit JVM
f = new File("mylibfile32.so");
} else {
// 64-bit JVM
f = new File("mylibfile64.so");
}
System.load(f.getAbsolutePath());
There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.
I was having this problem too. For me, I couldn't start/stop openfire (it said it was stopped, but everything was still running)
sudo /etc/init.d/openfire stop
sudo /etc/init.d/openfire start
Also, restarting apache did not help either
sudo /etc/init.d/apache2 restart
The errors were inside:
/opt/openfire/logs/stderror.log
Error creating server listener on port 5269: Address already in use
Error creating server listener on port 5222: Address already in use
The way I fixed this, I had to actually turn off the server inside the admin area for my host.
Making this its own post because this had me going for hours.
I saw maybe a dozen of similar posts here and elsewhere about this problema and the aspnet_regiis fix. They weren't working for me, and aspnet_regiis was acting odd, just listing options etc.
As user ryan-anderson above indicated, you cannot enter .exe
For those less comfy with things outside IIS on the server, here's what you do in simple steps.
Find aspnet_regiis in a folder similar to this path. c:\Windows\Microsoft.NET\Framework\v4.0.30319\
Right-click command prompt in the start menu or wherever and tell it to run as administrator. Using the windows "Run" feature just won't work, or didn't for me.
Go back to the aspnet_regiis executable. Click-drag it right into the command prompt or copy-paste the address into the command prompt.
Remove, if it's there, the .exe at the end. This is key. Add the -i (space minus eye) at the end. Enter.
If you did this correctly, you will see that it starts to install asp.net, and then tells you it succeeded.
This worked for me:
mv xyz.war ./tmp
cd tmp
jar -xvf xyz.war
rm -rf WEB-INF/lib/zookeeper-3.4.10.jar
rm -rf xyz.war
jar -cvf xyz.war *
mv xyz.war ../
cd ..
The following method works in IE11+, Firefox 25+ and Chrome 30+:
<a id="export" class="myButton" download="" href="#">export</a>
<script>
function createDownloadLink(anchorSelector, str, fileName){
if(window.navigator.msSaveOrOpenBlob) {
var fileData = [str];
blobObject = new Blob(fileData);
$(anchorSelector).click(function(){
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
});
} else {
var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
$(anchorSelector).attr("download", fileName);
$(anchorSelector).attr("href", url);
}
}
$(function () {
var str = "hi,file";
createDownloadLink("#export",str,"file.txt");
});
</script>
See this in Action: http://jsfiddle.net/Kg7eA/
Firefox and Chrome support data URI for navigation, which allows us to create files by navigating to a data URI, while IE doesn't support it for security purposes.
On the other hand, IE has API for saving a blob, which can be used to create and download files.
I resolved this of following way:
here the code:
var deferred = $q.defer(),
self = this,
onConnect = function(status){
if (status === Strophe.Status.CONNECTING) {
deferred.notify({status: 'connecting'});
} else if (status === Strophe.Status.CONNFAIL) {
self.connected = false;
deferred.notify({status: 'fail'});
} else if (status === Strophe.Status.DISCONNECTING) {
deferred.notify({status: 'disconnecting'});
} else if (status === Strophe.Status.DISCONNECTED) {
self.connected = false;
deferred.notify({status: 'disconnected'});
} else if (status === Strophe.Status.CONNECTED) {
self.connection.send($pres().tree());
self.connected = true;
deferred.resolve({status: 'connected'});
} else if (status === Strophe.Status.ATTACHED) {
deferred.resolve({status: 'attached'});
self.connected = true;
}
},
output = function(data){
if (self.connected){
var rid = $(data).attr('rid'),
sid = $(data).attr('sid'),
storage = {};
if (localStorageService.cookie.get('day_bind')){
storage = localStorageService.cookie.get('day_bind');
}else{
storage = {};
}
storage[$window.name] = sid + '-' + rid;
localStorageService.cookie.set('day_bind', angular.toJson(storage));
}
};
if ($window.name){
var storage = localStorageService.cookie.get('day_bind'),
value = storage[$window.name].split('-')
sid = value[0],
rid = value[1];
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.attach('bosh@' + BoshDomain + '/' + $window.name, sid, parseInt(rid, 10) + 1, onConnect);
}else{
$window.name = 'web_' + (new Date()).getTime();
self.connection = new Strophe.Connection(BoshService);
self.connection.xmlOutput = output;
self.connection.connect('bosh@' + BoshDomain + '/' + $window.name, '123456', onConnect);
}
I hope help you
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
You can use the focusout event to detect keyboard dismissal. It's like blur, but bubbles. It will fire when the keyboard closes (but also in other cases, of course). In Safari and Chrome the event can only be registered with addEventListener, not with legacy methods. Here is an example I used to restore a Phonegap app after keyboard dismissal.
document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});
Without this snippet, the app container stayed in the up-scrolled position until page refresh.
There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:
ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource
methods.
ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");
or alternatively if you just want the input stream:
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");
The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.
EDIT:
The getContext() method is obviously something you would have to implement. JSP pages make it available as the context
field. In a servlet you get it from your ServletConfig
which is passed into the servlet's init()
method. If you store it at that time, you can get your ServletContext any time you want after that.
if you will include
System.Windows.forms
as namespace then it will conflict . Use
btn_click()
{
System.Windows.Forms.MessageBox.Show("Hello");
}
There is no definitive answer to this, as each browser has its own configuration for this, and this configuration may be changed. If you search on the internet you can find ways to change this limit (usually they're branded as "performance enhancement methods.") It might be worth advising your users to do so if it is required by your website.
I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I'm going to expand your question a bit and also include the compile function.
compile function - use for template DOM manipulation (i.e., manipulation of tElement = template element), hence manipulations that apply to all DOM clones of the template associated with the directive. (If you also need a link function (or pre and post link functions), and you defined a compile function, the compile function must return the link function(s) because the 'link'
attribute is ignored if the 'compile'
attribute is defined.)
link function - normally use for registering listener callbacks (i.e., $watch
expressions on the scope) as well as updating the DOM (i.e., manipulation of iElement = individual instance element). It is executed after the template has been cloned. E.g., inside an <li ng-repeat...>
, the link function is executed after the <li>
template (tElement) has been cloned (into an iElement) for that particular <li>
element. A $watch
allows a directive to be notified of scope property changes (a scope is associated with each instance), which allows the directive to render an updated instance value to the DOM.
controller function - must be used when another directive needs to interact with this directive. E.g., on the AngularJS home page, the pane directive needs to add itself to the scope maintained by the tabs directive, hence the tabs directive needs to define a controller method (think API) that the pane directive can access/call.
For a more in-depth explanation of the tabs and pane directives, and why the tabs directive creates a function on its controller using this
(rather than on $scope
), please see 'this' vs $scope in AngularJS controllers.
In general, you can put methods, $watches
, etc. into either the directive's controller or link function. The controller will run first, which sometimes matters (see this fiddle which logs when the ctrl and link functions run with two nested directives). As Josh mentioned in a comment, you may want to put scope-manipulation functions inside a controller just for consistency with the rest of the framework.
Right now i had this error and resolved it. Your url could match with created virtual directory.
You have to check virtual directories, in my example i found in applicationhost.config
next row:
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/admin/roles" physicalPath="C:\..." />
</application>
I tried to open page with an url (http://localhost/admin/roles
) of AdminController
and Roles
action and got this error.
@Alistair pointed out in this answer that sometimes users will return to the browser after opening the app. A commenter to that answer indicated that the times values used had to be changed depending on iOS version. When our team had to deal with this, we found that the time values for the initial timeout and telling whether we had returned to the browser had to be tuned, and often didn't work for all users and devices.
Rather than using an arbitrary time difference threshold to determine whether we had returned to the browser, it made sense to detect the "pagehide" and "pageshow" events.
I developed the following web page to help diagnose what was going on. It adds HTML diagnostics as the events unfold, mainly because using techniques like console logging, alerts, or Web Inspector, jsfiddle.net etc all had their drawbacks in this work flow. Rather than using a time threshold, the Javascript counts the number of "pagehide" and "pageshow" events to see whether they have occurred. And I found that the most robust strategy was to use an initial timeout of 1000 (rather than the 25, 50, or 100 reported/suggested by others).
This can be served on a local server, e.g. python -m SimpleHTTPServer
and viewed on iOS Safari.
To play with it, press either the "Open an installed app" or "App not installed" links. These links should cause respectively the Maps app or the App Store to open. You can then return to Safari to see the sequence and timing of the events.
(Note: this will work for Safari only. For other browsers (like Chrome) you'd have to install handlers for the pagehide/show-equivalent events).
Update: As @Mikko has pointed out in the comments, the pageshow/pagehide events we are using are apparently no longer supported in iOS8.
<html>
<head>
</head>
<body>
<a href="maps://" onclick="clickHandler()">Open an installed app</a>
<br/><br/>
<a href="xmapsx://" onclick="clickHandler()">App not installed</a>
<br/>
<script>
var hideShowCount = 0 ;
window.addEventListener("pagehide", function() {
hideShowCount++ ;
showEventTime('pagehide') ;
});
window.addEventListener("pageshow", function() {
hideShowCount++ ;
showEventTime('pageshow') ;
});
function clickHandler(){
var hideShowCountAtClick = hideShowCount ;
showEventTime('click') ;
setTimeout(function () {
showEventTime('timeout function '+(hideShowCount-hideShowCountAtClick)+' hide/show events') ;
if (hideShowCount == hideShowCountAtClick){
// app is not installed, go to App Store
window.location = 'http://itunes.apple.com/app' ;
}
}, 1000);
}
function currentTime()
{
return Date.now()/1000 ;
}
function showEventTime(event){
var time = currentTime() ;
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(time+' '+event));
}
</script>
</body>
</html>
As of spring boot 2 the server.contextPath
property is deprecated. Instead you should use server.servlet.contextPath
.
So in your application.properties file add:
server.servlet.contextPath=/myWebApp
For more details see: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#servlet-specific-server-properties
By far the easiest solution (at least in ubuntu/linux):
Works like a charm.
This error had me foxed for three days, the situation I faced produced the same error. Following all the advice I could find, I played with the configuration but to no avail.
Eventually I found it, the difference, the Service I was executing was contained in a common jar, the issue turned out to be AspectJ not treating the Service instantiation the same. In effect the proxy was simply calling the underlying method without all the normal Spring magic being executed before the method call.
In the end the @Scope annotation placed on the service as per the example solved the issue:
@Service
@Scope(proxyMode = ScopedProxyMode.INTERFACES)
@Transactional
public class CoreServiceImpl implements CoreService {
@PersistenceContext
protected EntityManager entityManager;
@Override
public final <T extends AbstractEntity> int deleteAll(Class<T> clazz) {
CriteriaDelete<T> criteriaDelete = entityManager.getCriteriaBuilder().createCriteriaDelete(clazz);
criteriaDelete.from(clazz);
return entityManager.createQuery(criteriaDelete).executeUpdate();
}
}
The method I have posted is a delete method but the annotations affect all persistence methods in the same way.
I hope this post helps someone else who has struggled with the same issue when loading a service from a jar
I've finally done it in this way.
Added a ServletContextListener that does the following:
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
System.setProperty("rootPath", context.getRealPath("/"));
}
Then in the log4j.properties file:
log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log
By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.
It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.
What do you think?
You can use curl
as is in this thread
For the lazy:
*/5 * * * * curl --request GET 'http://exemple.com/path/check.php?param1=1'
This will be executed every 5 minutes.
So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest
object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('${pageContext.request.contextPath}/myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern
of /myservlet
(you can change this to your taste) and have at least doGet()
implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World!
in the JavaScript alert.
You can of course also use doPost()
, but then you should use 'POST'
in xhr.open()
or use $.post()
instead of $.get()
in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data)
of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:
-DAPP_MASTER_PASSWORD=foo
and in your code, write
System.getProperty("APP_MASTER_PASSWORD");
You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.
A web application is a website in the same way that a square is a rectangle.
The application part is the model-controller combo. The web part (the view) is why it qualifies as a website.
Something that is only a website and not a web application is simply missing the dynamic aspect.
Of course, it can be difficult to decide on how much server-side processing is required to qualify it as a web application. Probably when it has a data store.
Thus, you have the primary role of webapps confused. A website's primary role is to inform. A web app's primary role is to inform using dynamic content (the do something part).
Drop root privileges after you bind to port 80 (or 443).
This allows port 80/443 to remain protected, while still preventing you from serving requests as root:
function drop_root() {
process.setgid('nobody');
process.setuid('nobody');
}
A full working example using the above function:
var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {
res.write("Success!");
res.end();
});
server.listen(80, null, null, function() {
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
drop_root();
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
});
See more details at this full reference.
This may or not be related....I started off with the same error mentioned above, started googling, making changes, getting new errors, endless loop.
The change that got me by that error was messing with the Feature Delegation in IIS Manager under the Management section of the server. I'm sorry I can't remember which one I changed, but googling might help.
That got me past the 1st error into a whole new stream of others, some totally nonsensical. (I would get one error when running under a virtual directory, converting it to an application yielded another error, etec etc). What finally solved this series of errors was: IIS manager, Application Pools, DefaultAppPool, Enable 32-Bit applications=True
I had started this app on a 32 bit windows xp box, and I am now running it on a 64Bit Windows 7 box.
So hopefully this helps someone else.
From your question, I think what you are trying to do is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To do this you don't need to set a paramater but an attribute using
void setAttribute(String name, Object o);
and then
Object getAttribute(String name);
Why do you need it to be of type GenericWebApplicationContext
?
I think you can probably work with any ApplicationContext type.
Usually you would use an init method (in addition to your setter method):
@PostConstruct
public void init(){
AutowireCapableBeanFactory bf = this.applicationContext
.getAutowireCapableBeanFactory();
// wire stuff here
}
And you would wire beans by using either
AutowireCapableBeanFactory.autowire(Class, int mode, boolean dependencyInject)
or
AutowireCapableBeanFactory.initializeBean(Object existingbean, String beanName)
webapps
folderhttp://host:port/manager
. You will have to setup some users beforehand.webapps/webappname
Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:
After you have it deployed (check the /logs
dir for any problems), it should be accessible via: http://host:port/yourwebappname/
. So in your case, one of those:
http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/
If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)
FYI Under certain network conditions your hostname may change or be incorrect. If you are on a mac the following will let you set your hostname fairly permanently:
sudo scutil --set HostName correct-name
They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.
Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.
Now... main (or little) differences you can see right now are:
SCAFFOLDING AND BOILERPLATE GENERATION
Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators
MODULARITY
Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...
BUILD SYSTEM
Mean.io has recently moved to gulp
Mean.js uses grunt
DEPLOYMENT
Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.
DOCUMENTATION
Mean.io has ok docs
Mean.js has AWESOME docs
COMMUNITY
Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth
On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.
MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:
You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..
Have fun!
Memcached is good at being a simple key/value store and is good at doing key => STRING. This makes it really good for session storage.
Redis is good at doing key => SOME_OBJECT.
It really depends on what you are going to be putting in there. My understanding is that in terms of performance they are pretty even.
Also good luck finding any objective benchmarks, if you do find some kindly send them my way.
I had this problem with a brand new web service. Solved it by adding read-only access for Everyone on Properties->Security for the folder that the service was in.
There are a lot of good tools mentioned here. I wonder if tools are an answer the question: "How do you stress test a web application?" The tools don't really provide a method to stress a Web app. Here's what I know:
Stress testing shows how a Web app fails while serving responses to an increasing population of users. Stress testing shows how the Web app functions while it fails. Most Web apps today - especially the Social/Mobile Web apps - are integrations of services. For example, when Facebook had its outage in May 2011 you could not log onto Pepsi.com's Web app. The app didn't fail entirely, just a big portion of its normal function become unavailable to users.
Performance testing shows a Web app's ability to maintain response times independent of how many users are concurrently using the app. For example, an app that handles 10 transactions per second with 10 concurrent users should handle 20 transactions per second at 20 users. If the app handles less than 20 transactions per second the response times are growing longer and the app is not able to achieve linear scalability.
Also, in the above example the transaction-per-second count should be of only successful operations of a test use case/workflow. Failures typically happen in shorter timespans and will make the TPS measurement overly optimistic. Failures are important to a stress and performance test since they generate load on the app too.
I wrote up the PushToTest methodology in the TestMaker User Guide at http://www.pushtotest.com/pushtotest-testmaker-6-methodology. TestMaker comes in two flavors: Open Source (GPL) Community version and TestMaker Enterprise (commercial with great professional support.)
-Frank
It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.
<input id="myFileInput" type="file" accept="image/*;capture=camera">
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
}
myInput.addEventListener('change', sendPic, false);
You can use HTML5 Websockets to introduce your own push messages. From Wikipedia:
"For the client side, WebSocket was to be implemented in Firefox 4, Google Chrome 4, Opera 11, and Safari 5, as well as the mobile version of Safari in iOS 4.2. Also the BlackBerry Browser in OS7 supports WebSockets."
To do this, you need your own provider server to push the messages to the clients.
If you want to use APN (Apple Push Notification) or C2DM (Cloud to Device Message), you must have a native application which must be downloaded through the online store.
I believe its real use comes when you want to have more than one config files or you have xyz.xml file instead of applicationcontext.xml for eg
<context-param><param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/training-service.xml,
/WEB-INF/training-data.xml</param-value>
</context-param>
Another approach to ContextLoaderListener is using ContextLoaderServlet like below
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Are you saying that you are having trouble inserting into a web page a link to a file that happens to have a .exe extension?
If that is the case, then take one step back. Imagine the file has a .htm extension, or a .css extension. How can you make that downloadable? If it is a static link, then the answer is clear: the file needs to be in the docroot for the ASP.NET app. IIS + ASP.NET serves up many kinds of content: .htm files, .css files, .js files, image files, implicitly. All these files are somewhere under the docroot, which by default is c:\inetpub\wwwroot, but for your webapp is surely something different. The fact that the file you want to expose has an .exe extension does not change the basic laws of IIS physics. The exe has to live under the docroot. The network share thing might work for some browsers.
The alternative of course is to dynamically write the content of the file directly to the Response.OutputStream. This way you don't need the .exe to be in your docroot, but it is not a direct download link. In this scenario, the file might be downloaded by a button click.
Something like this:
Response.Clear();
string FullPathFilename = "\\\\server\\share\\CorpApp1.exe";
string archiveName= System.IO.Path.GetFileName(FullPathFilename);
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "filename=" + archiveName);
Response.TransmitFile(FullPathFilename);
Response.End();
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
No, inside the views folder is not good.
Look: You must have 3 basic folders on your project:
system // This is CI framework there are not much reasons to touch this files
application //this is where your logic goes, the files that makes the application,
public // this must be your documentroot
For security reasons its better to keep your framework and the application outside your documentroot,(public_html, htdocs, public, www... etc)
Inside your public folder, you should put your public info, what the browsers can see, its common to find the folders: images, js, css; so your structure will be:
|- system/
|- application/
|---- models/
|---- views/
|---- controllers/
|- public/
|---- images/
|---- js/
|---- css/
|---- index.php
|---- .htaccess
What's the "largest" site that's built on Django today? (I measure size mostly by user traffic)
Pinterest
disqus.com
More here: https://www.shuup.com/en/blog/25-of-the-most-popular-python-and-django-websites/
Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?
Yes but use proper architecture, database design, use of cache, use load balances and multiple servers or nodes
Could a site like Stack Overflow run on Django?
Yes just need to follow the answer mentioned in the 2nd question
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process. Usually in a web container, this is something like the bin
folder.
getResourceAsStream()
will load a file path relative from your application's classpath.
Try this:
window.location.href = "http://PlaceYourUrl.com";
For me the error was misleading. I discovered the true error by testing the errant web service with SoapUI.
One important consideration that I think everybody is missing here is a load-balancing (web farm) scenario. Since the server that's executing global.asax may be different than the server that's about the execute the custom error page, stashing the exception object in Application is not reliable.
I'm still looking for a reliable solution to this problem in a web farm configuration, and/or a good explanation from MS as to why you just can't pick up the exception with Server.GetLastError on the custom error page like you can in global.asax Application_Error.
P.S. It's unsafe to store data in the Application collection without first locking it and then unlocking it.
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
Wireshark, Firebug, Fiddler all do similar things - capture network traffic.
Wireshark captures any kind of network packet. It can capture packet details below TCP/IP (HTTP is at the top). It does have filters to reduce the noise it captures.
Firebug tracks each request the browser page makes and captures the associated headers and the time taken for each stage of the request (DNS, receiving, sending, ...).
Fiddler works as an HTTP/HTTPS proxy. It captures every HTTP request the computer makes and records everything associated with it. It does allow things like converting post variables to a table form and editing/replaying requests. It doesn't, by default, capture localhost traffic in IE, see the FAQ for the workaround.
if none of the above worked for you try to make ajax requests on "POST" not "GET" , that worked for me nicely ... none of the above did. I also have the characterEncodingFilter.
I believe it is more to do with how your network is configured. Servlet is simply giving you the address it is finding.
I can suggest two workarounds. First try using IPV4. See this SO Answer
Also, try using the request.getRemoteHost() method to get the names of the machines. Surely the names are independent of whatever IP they are mapped to.
I still think you should discuss this with your infrastructure guys.
you can just find-out loaded config file by executing below command,
php -i | grep 'php.ini'
Then add below lines to correct php.ini file
extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so
Then restart web server,
service httpd restart
Even though the question is about gaining some space removing the address bar, you can also gain some space by toggling the bookmark bar on and off, using Ctrl + Shift + B, or ? Cmd + Shift + B, in Mac OS.
There is nothing like Silver Bullet. Everything comes with some cost associated with it. It is like if you eat oily food, you will compromise your health and healthy food does not come with spices like oily food. It is individual choice whether they want health or spices as in their food. Same way Node.js consider to be used in specific scenario. If your app does not fit into that scenario you should not consider it for your app development. I am just putting my thought on the same:
When to use Node.JS
When NOT to use Node.JS
Scalability Consideration with Node.JS
Node.JS Alternatives
There are other option to use in place of Node.JS however Vert.x seems to be pretty promising and has lots of additional features like polygot and better scalability considerations.
I have Visual Studio 2013 installed. This worked for me:
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' != ''">12.0</VisualStudioVersion>`
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
So I've changed the condition from ==
to !=
and the value from 10.0
to 12.0
.
I too was facing the same issue. Then discovered that the path for the lib folder in the classpath was not set properly.
After much pain, and great assistance from @vitr et al above, i decided to try
and that worked.
ENV LISTEN_PORT=""
ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}
e.g.
docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image
and
docker run --rm -p 8080:80 -d my-image
both set the port correctly in my container
see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html
<video width="320" height="240" controls autoplay>
<source src="movie.mp4" type="video/mp4"> Your browser does not support the video tag.
</video>
Remove autoplay
if you want to disable auto playing video.
If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html
AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.
So, you really can't make stuff that expects a file accept an asset 'file'.
Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:
File f = new File(getCacheDir()+"/m1.map");
if (!f.exists()) try {
InputStream is = getAssets().open("m1.map");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
mapView.setMapFile(f.getPath());
$client = new \GuzzleHttp\Client();
$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;
$res = $client->post($url, [ 'body' => json_encode($body) ]);
$code = $res->getStatusCode();
$result = $res->json();
use a css3 class "spinner". It's more beautiful and you don't need .gif
.spinner {
position: absolute;
left: 50%;
top: 50%;
height:60px;
width:60px;
margin:0px auto;
-webkit-animation: rotation .6s infinite linear;
-moz-animation: rotation .6s infinite linear;
-o-animation: rotation .6s infinite linear;
animation: rotation .6s infinite linear;
border-left:6px solid rgba(0,174,239,.15);
border-right:6px solid rgba(0,174,239,.15);
border-bottom:6px solid rgba(0,174,239,.15);
border-top:6px solid rgba(0,174,239,.8);
border-radius:100%;
}
@-webkit-keyframes rotation {
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(359deg);}
}
@-moz-keyframes rotation {
from {-moz-transform: rotate(0deg);}
to {-moz-transform: rotate(359deg);}
}
@-o-keyframes rotation {
from {-o-transform: rotate(0deg);}
to {-o-transform: rotate(359deg);}
}
@keyframes rotation {
from {transform: rotate(0deg);}
to {transform: rotate(359deg);}
}
Exemple of what is looks like : http://jsbin.com/roqakuxebo/1/edit
You can find a lot of css spinners like this here : http://cssload.net/en/spinners/
This CSS seems to work in Safari and Chrome:
div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}
and in the body:
<div id="div2"><img src="image.jpg" ></div>
But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.
With Scanner the default delimiters are the whitespace characters.
But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:
So useDelimiter()
methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:
And here is an Example:
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
Prints this output:
Anna Mills
Female
18
I had the same problem and just solved it. I had posted my own question on stackoverflow:
Can't PUT to my IHttpHandler, GET works fine
The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.
<modules runManagedModulesForWebDavRequests="true">
...
</modules>
So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.
I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).
This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.
Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.
Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h"
) then compile and link with B.lib:
cl A.cpp /c /EHsc
link A.obj B.lib
The first line generates A.obj, the second generates A.exe. The /c
flag tells cl not to link and /EHsc
specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).
If you don't specify /c
cl will call link
for you. You can use the /link
flag to specify additional arguments to link
and do it all at once if you like:
cl A.cpp /EHsc /link B.lib
If B.lib is not on the INCLUDE
path you can give a relative or absolute path to it or add its parent directory to your include path with the /I
flag.
If you're calling from cygwin (as I do) replace the forward slashes with dashes.
If you write #pragma comment(lib, "B.lib")
in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.
None of the solutions in Intellij is as elegant (or useful) as in Eclipse. What we need is feature request to the intellij so that we can add a hook (what actions to perform) when the IDE autosaves.
In Eclipse we can add "post-save" actions, such as organize imports and format the class. Yes you have to do a "save" or ctrl-s but the hook is very convenient.
NO, when you are using only one "=" you are assigning the variable.
You must use "==" : You must use "===" :
if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
$("#code").text(data.DATA[0].ID);
}
You could use fonction like .toLowerCase()
to avoid case problem if you want
When I installed Python 3.6.1 on Windows 7 recently, it also installed the Python Launcher for Windows, which is supposed to handle the shebang line. However, I found that the Python Launcher did not do this: the shebang line was ignored and Python 2.7.13 was always used (unless I executed the script using py -3).
To fix this, I had to edit the Windows registry key HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.File\shell\open\command
. This still had the value
"C:\Python27\python.exe" "%1" %*
from my earlier Python 2.7 installation. I modified this registry key value to
"C:\Windows\py.exe" "%1" %*
and the Python Launcher shebang line processing worked as described above.
It's simple, use $.getJSON()
function and in your URL just include
callback=?
as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/
In VB code, when trying to submit an INSERT
query, you must submit a double query in the same 'executenonquery' like this:
sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"
I used a ;
separator instead of a GO.
Works for me. Late but efficient!
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
Reassign again. Like example = new String[(size)]
In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.
When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.
The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).
If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.
Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.
This is almost like the other answer but you don't need a scatter
plot at all, you can simply specify a scatter-plot-like format (fmt
-parameter) for errorbar
:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()
Result:
A list of the avaiable fmt
parameters can be found for example in the plot
documentation:
character description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
There is an .Offset property on a Range class which allows you to do just what you need
ActiveCell.Offset(numRows, numCols)
follow up on a comment:
Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))
and you can verify by MsgBox newRange.Address
import subprocess
result = []
win_cmd = 'ipconfig'(curr_user,filename,ip_address)
process = subprocess.Popen(win_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
for line in process.stdout:
print line
result.append(line)
errcode = process.returncode
for line in result:
print line
Here is a little utility class that I created:
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Convenience utility to create a FilenameFilter, based on a list of extensions
*/
public class FileExtensionFilter implements FilenameFilter {
private Set<String> exts = new HashSet<String>();
/**
* @param extensions
* a list of allowed extensions, without the dot, e.g.
* <code>"xml","html","rss"</code>
*/
public FileExtensionFilter(String... extensions) {
for (String ext : extensions) {
exts.add("." + ext.toLowerCase().trim());
}
}
public boolean accept(File dir, String name) {
final Iterator<String> extList = exts.iterator();
while (extList.hasNext()) {
if (name.toLowerCase().endsWith(extList.next())) {
return true;
}
}
return false;
}
}
Usage:
String[] files = new File("myfile").list(new FileExtensionFilter("pdf", "zip"));
Use string concatenation:
href={'/posts/' + post.id}
The JSX syntax allows either to use strings or expressions ({...})
as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
As a complete new at javascript, I just had the same problem on my side here. The mistake I did, was that I used:
<script type="text.javascript">
console.log("bla bla bla");
</script>
instead of:
<script>
console.log("bla bla bla");
</script>
using the
type="text.javascript"
had the result of not producing the log in the console.
You need to give the body
and the html
a height too. Otherwise, the body will only be as high as its contents (the single div), and 50% of that will be half the height of this div.
Updated fiddle: http://jsfiddle.net/j8bsS/5/
Tab is [HT], or character number 9, in the unicode library.
You might have confusions between the different line endings. A Windows file will end each line with a carriage return and a line feed. Some programs on Unix will read that file as if it had an extra blank line between each line, because it will see the carriage return as an end of line, and then see the line feed as another end of line.
If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.
Reminder:
Func<X, Y, R>
is a function with two inputs of typeX
andY
, that returns a result of typeR
.
Enumerable.Aggregate has three overloads:
Overload 1:
A Aggregate<A>(IEnumerable<A> a, Func<A, A, A> f)
Example:
new[]{1,2,3,4}.Aggregate((x, y) => x + y); // 10
This overload is simple, but it has the following limitations:
InvalidOperationException
.Overload 2:
B Aggregate<A, B>(IEnumerable<A> a, B bIn, Func<B, A, B> f)
Example:
var hayStack = new[] {"straw", "needle", "straw", "straw", "needle"};
var nNeedles = hayStack.Aggregate(0, (n, e) => e == "needle" ? n+1 : n); // 2
This overload is more general:
bIn
).Overload 3:
C Aggregate<A,B,C>(IEnumerable<A> a, B bIn, Func<B,A,B> f, Func<B,C> f2)
The third overload is not very useful IMO.
The same can be written more succinctly by using overload 2 followed by a function that transforms its result.
The illustrations are adapted from this excellent blogpost.
Set Timer and auto call service after certain time
// Initialize from ngInit
ngOnInit(): void {this.getNotifications();}
getNotifications() {
setInterval(() => {this.getNewNotifications();
}, 60000); // 60000 milliseconds interval
}
getNewNotifications() {
this.notifyService.getNewNotifications().subscribe(
data => { // call back },
error => { },
);
}
Use LEFT combined with CHARINDEX:
UPDATE MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
Note that the WHERE clause skips updating rows in which there is no semicolon.
Here is some code to verify the SQL above works:
declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
insert into @MyTable ([id], MyText)
select 1, 'some text; some more text'
union all select 2, 'text again; even more text'
union all select 3, 'text without a semicolon'
union all select 4, null -- test NULLs
union all select 5, '' -- test empty string
union all select 6, 'test 3 semicolons; second part; third part;'
union all select 7, ';' -- test semicolon by itself
UPDATE @MyTable
SET MyText = LEFT(MyText, CHARINDEX(';', MyText) - 1)
WHERE CHARINDEX(';', MyText) > 0
select * from @MyTable
I get the following results:
id MyText
-- -------------------------
1 some text
2 text again
3 text without a semicolon
4 NULL
5 (empty string)
6 test 3 semicolons
7 (empty string)
First, the code:
from random import choices
def random_name(length=6):
return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---
from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink
def display_html_to_frame(html, width=600, height=600):
name = f"temp_{random_name()}.html"
with open(name, "w") as f:
print(html, file=f)
display(IFrame(name, width, height), metadata=dict(isolated=True))
# unlink(name)
def display_html_inline(html):
display(HTML(html, metadata=dict(isolated=True)))
h="<html><b>Hello</b></html>"
display_html_to_iframe(h)
display_html_inline(h)
Some quick notes:
metadata=dict(isolated=True)
does not isolate the result in an IFrame, as older documentation suggests. It appears to prevent clear-fix
from resetting everything. The flag is no longer documented: I just found using it allowed certain display: grid
styles to correctly render.IFrame
solution writes to a temporary file. You could use a data uri as described here but it makes debugging your output difficult. The Jupyter IFrame
function does not take a data
or srcdoc
attribute.tempfile
module creations are not sharable to another process, hence the random_name()
.HTML('Hello, <b>world</b>')
at top level of cell and its return value will render. Within a function, use display(HTML(...))
as is done above. This also allows you to mix display
and print
calls freely.I am late to this question, but I think the best way to handle JDK versions on MacOS is by using the script described at: http://www.jayway.com/2014/01/15/how-to-switch-jdk-version-on-mac-os-x-maverick/
You can set the key path in the storyboard
Set the text to your multiline title e.g. hello
? + ? multiline
You need to press ? + ? to move text to next line.
Then add the key path
titleLabel.textAlignment
as Number
and value 1
, 1
means NSTextAlignmentCenter
titleLabel.numberOfLines
as Number
and value 0
, 0
means any number of lines
This will not be reflected on IB/Xcode, but will be in centre at run time (device/simulator)
If you want to see the changes on Xcode you need to do the following: (remember you can skip these steps)
Subclass the UIButton to make the button designable:
import UIKit
@IBDesignable class UIDesignableButton: UIButton {}
Assign this designable subclass to the buttons you're modifying:
If you want to write the code, then do the long process
1.Create IBOutlet
for button
2.Write code in viewDidLoad
btn.titleLabel.textAlignment = .Center
btn.titleLabel.numberOfLines = 0
In newer version of xcode (mine is xcode 6.1) we have property attributed title
Select Attributed
then select the text and press centre option below
P.S. The text was not coming multiline for that I have to set the
btn.titleLabel.numberOfLines = 0
If you want headless browser support then there is another approach you might adopt.
https://github.com/detro/ghostdriver
It was announced during Selenium Conference and it is still in development. It uses PhantomJS as the browser and is much better than HTMLUnitDriver, there are no screenshots yet, but as it is still in active development.
Note that you can also multiply a string like "%.2f" (example: "%.2f "*10).
>>> print "%.2f "*len(yourlist) % tuple(yourlist)
2.00 33.00 4.42 0.31
You cannot do it. C compiler cannot do such a complex thing on stack.
You have to use heap and dynamic allocation.
What you really need to do:
Use *access(boardAux, x, y, size) = 42 to interact with the matrix.
Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView
will get it working on API level 21+
if (Build.VERSION.SDK_INT >= 21) {
videoViewContainer.setBackgroundColor(Color.BLACK);
((ViewGroup) webView.getParent()).addView(videoViewContainer);
webView.scrollTo(0,0); // centers full screen view
} else {
activityNonVideoView.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
activityVideoView.addView(videoViewContainer,vg);
activityVideoView.setVisibility(View.VISIBLE);
}
You will also need to reflect the changes in onHideCustomView
# Python 2.7.16 (default, Jul 13 2019, 16:01:51)
# [GCC 8.3.0] on linux2
g = globals()
listB = []
for i in range(10):
g["num%s" % i] = i ** 10
listB.append("num{0}".format(i))
def printNum():
print "Printing num0 to num9:"
for i in range(10):
print "num%s = " % i,
print g["num%s" % i]
printNum()
listA = []
for i in range(10):
listA.append(i)
listA = tuple(listA)
print listA, '"Tuple to unpack"'
listB = str(str(listB).strip("[]").replace("'", "") + " = listA")
print listB
exec listB
printNum()
Output:
Printing num0 to num9:
num0 = 0
num1 = 1
num2 = 1024
num3 = 59049
num4 = 1048576
num5 = 9765625
num6 = 60466176
num7 = 282475249
num8 = 1073741824
num9 = 3486784401
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) "Tuple to unpack"
num0, num1, num2, num3, num4, num5, num6, num7, num8, num9 = listA
Printing num0 to num9:
num0 = 0
num1 = 1
num2 = 2
num3 = 3
num4 = 4
num5 = 5
num6 = 6
num7 = 7
num8 = 8
num9 = 9
Add this line to the dependencies in build.gradle:
compile 'com.mcxiaoke.volley:library:1.0.+'
To resolve your problem, write the following line on your page's Page_Load method.
if (String.IsNullOrEmpty(Request.QueryString["aspxerrorpath"])) return;
.Net 4.0 provides more closer look to null, empty or whitespace strings, use it as shown in the following line:
if(string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"])) return;
This will not run your next statements (your business logics) if query string does not have aspxerrorpath.
Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr
from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.
In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.
The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:
"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."
Note the potential for an out-of-range index with "i+3". You could do something like:
with open("file.txt", "r") as f:
searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
if "searchphrase" in line:
k=min(i+3,j)
for l in searchlines[i:k]: print l,
print
Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.
I suppose that you are using an array to create your select
form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php @print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php @print($selected[$k]);?>>Yes</options>
<option value="2" <?php @print($selected[$k]);?>>No</options>
<option value="3" <?php @print($selected[$k]);?>>Fine</options>
Notes that I don't know:
$_REQUEST
, You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
In the question above the right answer would be to use Mock
, or to be more precise create_autospec
(because it will add spec to the mock methods of the class you are mocking), the defined spec
on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some
from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch
class MyClass:
@staticmethod
def method(foo, bar):
print(foo)
def something(some_class: MyClass):
arg = 1
# Would fail becuase of wrong parameters passed to methd.
return some_class.method(arg)
def second(some_class: MyClass):
arg = 1
return some_class.unexisted_method(arg)
class TestSomethingTestCase(TestCase):
def test_something_with_autospec(self):
mock = create_autospec(MyClass)
mock.method.return_value = True
# Fails because of signature misuse.
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_something(self):
mock = Mock() # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
mock.method.return_value = True
result = something(mock)
self.assertTrue(result)
self.assertTrue(mock.method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
class TestSecondTestCase(TestCase):
def test_second_with_autospec(self):
mock = Mock(spec=MyClass)
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second_with_patch_autospec(self):
with patch(f'{__name__}.MyClass', autospec=True) as mock:
# Fails because of signature misuse.
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
def test_second(self):
mock = Mock()
mock.unexisted_method.return_value = True
result = second(mock)
self.assertTrue(result)
self.assertTrue(mock.unexisted_method.called)
The test cases with defined spec used fail because methods called from something
and second
functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock
will display.
As a side note there is one more option: use patch.object to mock just the class method which is called with.
The good use cases for patch would be the case when the class is used as inner part of function:
def something():
arg = 1
return MyClass.method(arg)
Then you will want to use patch as a decorator to mock the MyClass.
In Swift 3 (Programmatically) I had to do this:
let lbl = UILabel()
lbl.numberOfLines = 0
lbl.lineBreakMode = .byClipping
lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5
lbl.font = UIFont.systemFont(ofSize: 15)
@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"
Removes (deletes) a directory.
RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree. /Q Quiet mode, do not ask if ok to remove a directory tree with /S
If you don't want to use the optgroup element, put the dashes in an option element instead and give it the disabled attribute. It will be visible, but greyed out.
<option disabled>----------</option>
For windows users:
To download into a file open your cmd and folow this:
cd <*the file-path where you want to save it*>
pip download <*package name*>
the package and the dependencies will be downloaded in the current working directory.
To install from the current working directory:
set your folder where you downloaded as the cwd then follow these:
pip install <*the package name which is downloded as .whl*> --no-index --find-links <*the file locaation where the files are downloaded*>
this will search for dependencies in that location.
I know this is too late but for those who are coming here for the first time, I'd like to post a solution. I have a float value index
and a string imgfile
and I had the same problem as you. This is how I fixed the issue
index = 1.0
imgfile = 'data/2.jpg'
out = '%.1f,%s' % (index,imgfile)
print out
The output is
1.0,data/2.jpg
You may modify this formatting example as per your convenience.
They are formatting String
. The Java specific syntax is given in java.util.Formatter
.
The general syntax is as follows:
%[argument_index$][flags][width][.precision]conversion
%02d
performs decimal integer conversion d
, formatted with zero padding (0
flag), with width 2
. Thus, an int
argument whose value is say 7
, will be formatted into "07"
as a String
.
You may also see this formatting string in e.g. String.format
.
These are just some commonly used formats and doesn't cover the syntax exhaustively.
System.out.printf("Agent %03d to the rescue!", 7);
// Agent 007 to the rescue!
You can use the -
flag for left justification; otherwise it'll be right justification.
for (Map.Entry<Object,Object> prop : System.getProperties().entrySet()) {
System.out.printf("%-30s : %50s%n", prop.getKey(), prop.getValue());
}
This prints something like:
java.version : 1.6.0_07
java.vm.name : Java HotSpot(TM) Client VM
java.vm.vendor : Sun Microsystems Inc.
java.vm.specification.name : Java Virtual Machine Specification
java.runtime.name : Java(TM) SE Runtime Environment
java.vendor.url : http://java.sun.com/
For more powerful message formatting, you can use java.text.MessageFormat
. %n
is the newline conversion (see below).
System.out.println(Integer.toHexString(255));
// ff
System.out.printf("%d is %<08X", 255);
// 255 is 000000FF
Note that this also uses the <
relative indexing (see below).
System.out.printf("%+,010.2f%n", 1234.567);
System.out.printf("%+,010.2f%n", -66.6666);
// +01,234.57
// -000066.67
For more powerful floating point formatting, use DecimalFormat
instead.
%n
for platform-specific line separatorSystem.out.printf("%s,%n%s%n", "Hello", "World");
// Hello,
// World
%%
for an actual %
-signSystem.out.printf("It's %s%% guaranteed!", 99.99);
// It's 99.99% guaranteed!
Note that the double
literal 99.99
is autoboxed to Double
, on which a string conversion using toString()
is defined.
n$
for explicit argument indexingSystem.out.printf("%1$s! %1$s %2$s! %1$s %2$s %3$s!",
"Du", "hast", "mich"
);
// Du! Du hast! Du hast mich!
<
for relative indexingSystem.out.format("%s?! %<S?!?!?", "Who's your daddy");
// Who's your daddy?! WHO'S YOUR DADDY?!?!?
MessageFormat
with exampleIn Bootstrap 3 with CSS you can simply use:
body .modal-dialog {
/* percentage of page width */
width: 40%;
}
This ensures you don't break the design of the page, because we're using .modal-dialog
instead of .modal
which will be applied even to the shading.
I think the method you give is the most portable on Linux. Instead of spawning unnecessary cat
and wc
processes, you can shorten it a bit:
$ grep --count ^processor /proc/cpuinfo
2
canvas.toDataURL()
will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>
, whereas the blue-bordered image is a copy in a <img>
, filled with the <canvas>
's data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
_x000D_
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
_x000D_
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
_x000D_
See also:
Another simple way to do it is with concat()
SELECT DISTINCT(CONCAT(a,b)) AS cc FROM my_table GROUP BY (cc);
Very late :) but you can get the original SQL from an OraclePreparedStatementWrapper by
((OraclePreparedStatementWrapper) preparedStatement).getOriginalSql();
In the first regex, each space character is being replaced, character by character, with the empty string.
In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +
.
However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.
If you change the replacement string to '#'
, the difference becomes much clearer:
var str = ' A B C D EF ';
console.log(str.replace(/\s/g, '#')); // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#
Just to add that there should be no space between the selector and the opening bracket.
td[someclass]
will work. But
td [someclass]
will not.
you can use skimage.img_as_ubyte(yourdata)
it will make you numpy array ranges from 0->255
from skimage import img_as_ubyte
img = img_as_ubyte(data)
cv2.imshow("Window", img)
I don't know exactly how C
calculates PI
directly as I'm more familiar with C++
than C
; however, you could either have a predefined C
macro
or const
such as:
#define PI 3.14159265359.....
const float PI = 3.14159265359.....
const double PI = 3.14159265359.....
/* If your machine,os & compiler supports the long double */
const long double PI = 3.14159265359.....
or you could calculate it with either of these two formulas:
#define M_PI acos(-1.0);
#define M_PI (4.0 * atan(1.0)); // tan(pi/4) = 1 or acos(-1)
IMHO I'm not 100% certain but I think atan()
is cheaper than acos()
.
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
Getting Datafrom MySQL database
hope this helps :)
I'm sure there's some nice library that does this sort of thing already for you... But to just stick with the approach you're already going with, Map#entrySet
gives you a combined Object
with the key
and the value
. So something like:
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue().toString());
}
will do what you're after.
If you're using java 8, there's also the new streaming approach.
map.forEach((key, value) -> System.out.println(key + ":" + value));
Had problems even when init.py existed in subfolder and all that was missing was adding 'as' after import
from folder.file import Class as Class
import folder.file as functions
On a Windows system, you can use free FileTimes library.
This will be easier in the future with Java NIO.2 (JDK 7) and the java.nio.file.attribute package.
But remember that most Linux filesystems don't support file creation timestamps.
There are many different things you can do when dealing with responsive tables.
I personally like this approach by Chris Coyier:
You can find many other alternatives here:
If you can leverage Bootstrap and get something quickly, you can simply use the class names ".hidden-phone" and ".hidden-tablet" to hide some rows but this approach might to be the best in many cases. More info (see "Responsive utility classes"):
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
The documentation explains it pretty well:
An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.
As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.
As with all performance optimizations, it is a good idea to avoid optimizing things prematurely (i.e. without hard data on where the bottlenecks are).
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
A problem that has not been mentioned with using magic numbers...
If you have very many of them, the odds are reasonably good that you have two different purposes that you're using magic numbers for, where the values happen to be the same.
And then, sure enough, you need to change the value... for only one purpose.
You can achieve you goal with below ways :-
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
or
// create a java calendar instance
Calendar calendar = Calendar.getInstance();
// get a java date (java.util.Date) from the Calendar instance.
// this java date will represent the current date, or "now".
java.util.Date currentDate = calendar.getTime();
// now, create a java.sql.Date from the java.util.Date
java.sql.Date date = new java.sql.Date(currentDate.getTime());
The default value for bool is false
. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.
You have to make the UL
inside the div
behave like a block. Try adding
.navigation ul {
display: inline-block;
}
In httpd.conf file you need to remove #
#LoadModule rewrite_module modules/mod_rewrite.so
after removing # line will look like this:
LoadModule rewrite_module modules/mod_rewrite.so
And Apache restart
Crontab files are simply text files and as such can be treated like any other text file. The purpose of the crontab
command is to make editing crontab files safer. When edited through this command, the file is checked for errors and only saved if there are none.
crontab [path to file]
can be used to specify a crontab stored in a file. Like crontab -e
, this will only install the file if it is error free.
Therefore, a script can either directly write cron tab files, or write them to a temporary file and load them with the crontab [path to temp file]
command. Writing directly saves having to write a temporary file, but it also avoids the safety check.
The overall dimensions of a range are in its Width
and Height
properties.
Dim r As Range
Set r = ActiveSheet.Range("A4:H12")
Debug.Print r.Width
Debug.Print r.Height
You can exchange this local variable for a global, it would be easier.
DROP PROCEDURE IF EXISTS ABC;
DELIMITER $$
CREATE PROCEDURE ABC()
BEGIN
SET @a = 0;
simple_loop: LOOP
SET @a=@a+1;
select @a;
IF @a=5 THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
For me (using the Ubuntu Subsystem for Windows) the error message changed to:
Permissions 0555 for 'key.pem' are too open
after using chmod 400. It turns out that using root as a default user was the reason.
Change this using the cmd:
ubuntu config --default-user your_username
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27
Be careful in comparing the find result with the the end like for map 'm' as all answer have done above map::iterator i = m.find("f");
if (i == m.end())
{
}
else
{
}
you should not try and perform any operation such as printing the key or value with iterator i if its equal to m.end() else it will lead to segmentation fault.
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();
. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox
and call it btnOK
. Set the DialogResult
property in the property window to DialogResult.OK
. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
More simple in Laravel 5.7 and 5.8
{{ Request()->parameter }}
Here is an example with @RequestBody, First look at the controller !!
public ResponseEntity<Void> postNewProductDto(@RequestBody NewProductDto newProductDto) {
...
productService.registerProductDto(newProductDto);
return new ResponseEntity<>(HttpStatus.CREATED);
....
}
And here is angular controller
function postNewProductDto() {
var url = "/admin/products/newItem";
$http.post(url, vm.newProductDto).then(function () {
//other things go here...
vm.newProductMessage = "Product successful registered";
}
,
function (errResponse) {
//handling errors ....
}
);
}
And a short look at form
<label>Name: </label>
<input ng-model="vm.newProductDto.name" />
<label>Price </label>
<input ng-model="vm.newProductDto.price"/>
<label>Quantity </label>
<input ng-model="vm.newProductDto.quantity"/>
<label>Image </label>
<input ng-model="vm.newProductDto.photo"/>
<Button ng-click="vm.postNewProductDto()" >Insert Item</Button>
<label > {{vm.newProductMessage}} </label>
I prefer do like this
img { float: left; }
to remove the space between images
Here is an extension method that overloads the AppendText
method with a color parameter:
public static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
}
And this is how you would use it:
var userid = "USER0001";
var message = "Access denied";
var box = new RichTextBox
{
Dock = DockStyle.Fill,
Font = new Font("Courier New", 10)
};
box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);
new Form {Controls = {box}}.ShowDialog();
Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.
To format the code in Visual Studio when you want, press: (Ctrl + K) & (Ctrl + F)
The auto formatting rules can be found and changed in: Tools/Options --> (Left sidebar): Text Editor / CSS (or whatever other language you want to change)
For the CSS language the options are unfortunately very limited. You can also make some changes in: .../ Text Editor / All Languages
Only @stefanB solution worked for me on iOS 9.3
Here what I have to change for Swift 2
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//prepare your cell here..
//Add background view for normal cell
let backgroundView: UIView = UIView(frame: cell!.bounds)
backgroundView.backgroundColor = UIColor.lightGrayColor()
cell!.backgroundView = backgroundView
//Add background view for selected cell
let selectedBGView: UIView = UIView(frame: cell!.bounds)
selectedBGView.backgroundColor = UIColor.redColor()
cell!.selectedBackgroundView = selectedBGView
return cell!
}
func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
This can be accomplished using the brand new CSS display: grid
(browser support)
HTML:
<div class='container'>
<label for="dummy1">title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">
<label for="dummy2">longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">
<label for="dummy3">even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">
</div>
CSS:
.container {
display: grid;
grid-template-columns: 1fr 3fr;
}
When using css grid, by default elements are laid out column by column then row by row. The grid-template-columns
rule creates two grid columns, one which takes up 1/4 of the total horizontal space and the other which takes up 3/4 of the horizontal space. This creates the desired effect.
You can copy an iterator to a new list like this:
Iterator<String> iter = list.iterator();
List<String> copy = new ArrayList<String>();
while (iter.hasNext())
copy.add(iter.next());
That's assuming that the list contains strings. There really isn't a faster way to recreate a list from an iterator, you're stuck with traversing it by hand and copying each element to a new list of the appropriate type.
EDIT :
Here's a generic method for copying an iterator to a new list in a type-safe way:
public static <T> List<T> copyIterator(Iterator<T> iter) {
List<T> copy = new ArrayList<T>();
while (iter.hasNext())
copy.add(iter.next());
return copy;
}
Use it like this:
List<String> list = Arrays.asList("1", "2", "3");
Iterator<String> iter = list.iterator();
List<String> copy = copyIterator(iter);
System.out.println(copy);
> [1, 2, 3]
Finally this is for Hibernate 5
in Tomcat
.
Compiled all the answers from the above and added my tips which works like a charm for Hibernate 5 and SQL Server 2014
.
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="hibernate.connection.driver_class">
com.microsoft.sqlserver.jdbc.SQLServerDriver
</property>
<property name="hibernate.connection.url">
jdbc:sqlserver://localhost\ServerInstanceOrServerName:1433;databaseName=DATABASE_NAME
</property>
<property name="hibernate.default_schema">theSchemaNameUsuallydbo</property>
<property name="hibernate.connection.username">
YourUsername
</property>
<property name="hibernate.connection.password">
YourPasswordForMSSQL
</property>
Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
Hope this will help you to think in another way
I strongly suggest you to read this blog post which appeared on HackerNews recently: How HashMap works in Java
In short, the answer is
What will happen if two different HashMap key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.
For perfomance:
$('#example').children().last()
or if you want a last children with a certain class as commented above.
$('#example').children('.test').last()
or a specific child element with a specific class
$('#example').children('li.test').last()
If you are trying to take a value from the same array and trying to update it, you can use the following code.
{ 'condition': {
'ts': [ '5a81625ba0ff65023c729022',
'5a8161ada0ff65023c728f51',
'5a815fb4a0ff65023c728dcd']}
If the collection is userData['condition']['ts'] and we need to
for i,supplier in enumerate(userData['condition']['ts']):
supplier = ObjectId(supplier)
userData['condition']['ts'][i] = supplier
The output will be
{'condition': { 'ts': [ ObjectId('5a81625ba0ff65023c729022'),
ObjectId('5a8161ada0ff65023c728f51'),
ObjectId('5a815fb4a0ff65023c728dcd')]}
Building on Kilhoffer's solution...
With C# 3.0 you can create an extension method as follows:
public static class ExtensionMethods
{
// Deep clone
public static T DeepClone<T>(this T a)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, a);
stream.Position = 0;
return (T) formatter.Deserialize(stream);
}
}
}
which extends any class that's been marked as [Serializable] with a DeepClone method
MyClass copy = obj.DeepClone();
As Selman22 said, you are overriding the default object.Equals
method, which accepts an object obj
and not a safe compile time type.
In order for that to happen, make your type implement IEquatable<Box>
:
public class Box : IEquatable<Box>
{
double height, length, breadth;
public static bool operator ==(Box obj1, Box obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null))
{
return false;
}
if (ReferenceEquals(obj2, null))
{
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(Box obj1, Box obj2)
{
return !(obj1 == obj2);
}
public bool Equals(Box other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return height.Equals(other.height)
&& length.Equals(other.length)
&& breadth.Equals(other.breadth);
}
public override bool Equals(object obj)
{
return Equals(obj as Box);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = height.GetHashCode();
hashCode = (hashCode * 397) ^ length.GetHashCode();
hashCode = (hashCode * 397) ^ breadth.GetHashCode();
return hashCode;
}
}
}
Another thing to note is that you are making a floating point comparison using the equality operator and you might experience a loss of precision.
I use this
def cleaned( aFile ):
for line in aFile:
yield line.strip()
Then I can do things like this.
lines = list( cleaned( open("file","r") ) )
Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.
The above answers address how to set the default minDate at init, but the question was actually how to dynamically alter the minDate, below I also clarify How to set the default minDate.
All that was wrong with the original question was that the minDate value being set should have been a string (don't forget the quotes):
$('#datePickerId').datepicker('option', 'minDate', '3');
minDate also accepts a date object and a common use is to have an end date you are trying to calculate so something like this could be useful:
$('#datePickerId').datepicker(
'option', 'minDate', new Date($(".datePop.start").val())
);
Just answering this for best practice; the minDate option expects one of:
@bogart setting the string to "0" is a solution as it satisfies option 2 above
$('#datePickerId').datepicker('minDate': '3');
I've resolved the issue. It was due to the SQL browser service.
Solution to such problem is one among below -
Check the spelling of the SQL Server instance name that is specified in the connection string.
Use the SQL Server Surface Area Configuration tool to enable SQL Server to accept remote connections over the TCP or named pipes protocols. For more information about the SQL Server Surface Area Configuration Tool, see Surface Area Configuration for Services and Connections.
Make sure that you have configured the firewall on the server instance of SQL Server to open ports for SQL Server and the SQL Server Browser port (UDP 1434).
Make sure that the SQL Server Browser service is started on the server.
Why don't you put your results into a vector? That way you don't have to know the size before hand.
If you use Bootstrap, try to assign margin-bottom 0 to the paragraph and after assign the property align-items-center to container, for example, like this:
<div class="row align-items-center">
<p class="col-sm-1 mb-0">
....
</p>
</div>
Bootstrap by default assign a calculate margin bottom, so mb-0 disabled this.
I hope it helps
as your service is already setup, simply add a broadcast receiver in your service:
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
//action for phone state changed
}
}
};
in your service's onCreate
do this:
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more
registerReceiver(receiver, filter);
and in your service's onDestroy
:
unregisterReceiver(receiver);
and you are good to go to receive broadcast for what ever filters you mention in onCreate
. Make sure to add any permission if required. for e.g.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
This doesn't have to be much more complicated than passing in a value for the 'q' parameter. Google is a search engine after all and can handle the same stuff it handles when users type queries into its text boxes
"maps.google.com?/q=32.5234,-78.23432"
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
Both John Conde's and ryeballar's answers are correct and will work.
If you want to get too geeky:
John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center
and it has to decide whether to add/remove left
), when clearly only one is needed.
Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)
So, you can do the following as an alternative:
ng-class="{true:'center',false:'left'}[page.isSelected(1)]"
The first solution is to use the java.util.Random
class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random()
:
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
Try the event delegation method, this works in almost all cases.
$(document.body).on('change',"#selectID",function (e) {
//doStuff
var optVal= $("#selectID option:selected").val();
});
If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.
The MSDN information on how to hit Excel using ADO can be found here.
Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.
const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]
const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)
const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)
This article is old, but I spent a hot minute trying to figure this out so I figured I would post an updated response. My main source is this wonderful PowerPoint: http://www.lrdc.pitt.edu/maplelab/slides/14-Plotting.pdf. Okay, here's what I did:
In this example, my data set is called 'Data' and I was comparing 'Touch' data against 'Gaze' data. The subjects were divided into two groups: 'Red' and 'Blue'.
`plot(Data$Touch[Data$Category == "Blue"], Data$Gaze[Data$Category == "Blue"], main = "Touch v Gaze", xlab = "Gaze(s)", ylab = "Touch (s)", col = "blue", pch = 20)`
This set of code creates a scatterplot of Touch v Gaze of my Blue group
par(new = TRUE)
This tells R to create a new plot. This second plot is laid over the first automatically by R when you run all the code together
plot(Data$Touch[Data$Category == "Red"], Data$Gaze[Data$Category == "Red"], axes = FALSE, xlab = "", ylab = "", col = "red", pch = 2)
This is the second plot. I found when I was coding these that R didn't just lay over the data points onto the Blue plot, but it also lay the axes, axes titles, and main title.
To get rid of the annoying overlap problem, I used the axes function to get rid of the axes themselves and set the titles to be blank.
legend(x = 60, y = 50, legend = c("Blue", "Red"), col = c("blue", "red"), pch = c(20, 2))
Adding a pretty legend to round out the project
This way may be a bit longer than the pretty ggplots but I did not want to learn something completely new today, hope this helps someone!
For what it is worth, i have ubuntu and many packages installed and it went in conflict with it.
For me the right answer was:
sudo -i -u postgres-xc
psql
My 2 cents.
This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.
On the other hand if its some client I don't control then it is a good idea to do thorough error checking.
The var
keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var
keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var
keyword has a type. For instance, you'll find that the following code outputs "String".
var myString = "";
Console.Write(myString.GetType().Name);
Furthermore, the code above is equivalent to:
String myString = "";
Console.Write(myString.GetType().Name);
The var
keyword is simply C#'s way of saying "I can figure out the type for myString
from the context, so don't worry about specifying the type."
var myVariable = (MyType)null
or MyType myVariable = null
should work because you are giving the C# compiler context to figure out what type myVariable
should will be.
For more information:
The inclusion of your comparison class (or more specifically the AsEnumerable
call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.
You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.
Recheck the naming convention of the images and the validity of the XML in your resource files- then rebuild the project after cleaning.
Try this,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
More here
Since Django 1.8 released, you can use from_db classmethod to cache old value of remote_image. Then in save method you can compare old and new value of field to check if the value has changed.
@classmethod
def from_db(cls, db, field_names, values):
new = super(Alias, cls).from_db(db, field_names, values)
# cache value went from the base
new._loaded_remote_image = values[field_names.index('remote_image')]
return new
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if (self._state.adding and self.remote_image) or \
(not self._state.adding and self._loaded_remote_image != self.remote_image):
# If it is first save and there is no cached remote_image but there is new one,
# or the value of remote_image has changed - do your stuff!
tl;dr
All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
Can you give us a better description and an example of what you are doing? Because all i have to do is put the line in there for the device and then save the file. Now just reconnect the device and it works.
I usually use something similar to this line:
;
;some name for the phone (this seems to be arbitrary)
%CompositeAdbInterface% = USB_Install, THE_HARDWARE_ID
What i do, is:
android_winusb.inf
. Your_Android_SDK_Directory/extras/google/usb_driver/
That seems to always work for me, is that what you are doing? Or does this even help?
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
AssertJ 3.9.1 supports direct predicate usage in anyMatch
method.
assertThat(collection).anyMatch(element -> element.someProperty.satisfiesSomeCondition())
This is generally suitable use case for arbitrarily complex condition.
For simple conditions I prefer using extracting
method (see above) because resulting iterable-under-test might support value verification with better readability.
Example: it can provide specialized API such as contains
method in Frank Neblung's answer. Or you can call anyMatch
on it later anyway and use method reference such as "searchedvalue"::equals
. Also multiple extractors can be put into extracting
method, result subsequently verified using tuple()
.
This one disables all bogus verbs and only allows GET and POST
<system.webServer>
<security>
<requestFiltering>
<verbs allowUnlisted="false">
<clear/>
<add verb="GET" allowed="true"/>
<add verb="POST" allowed="true"/>
</verbs>
</requestFiltering>
</security>
</system.webServer>
@NoCanDo: You cannot create an array with different data types because java only supports variables with a specific data type or object. When you are creating an array, you are pulling together an assortment of similar variables -- almost like an extended variable. All of the variables must be of the same type therefore. Java cannot differentiate the data type of your variable unless you tell it what it is. Ex: int
tells all your variables declared to it are of data type int
. What you could do is create 3 arrays with corresponding information.
int bookNumber[] = {1, 2, 3, 4, 5};
int bookName[] = {nameOfBook1, nameOfBook2, nameOfBook3, nameOfBook4, nameOfBook5}
// etc.. etc..
Now, a single index number gives you all the info for that book. Ex: All of your arrays with index number 0 ([0]) have information for book 1.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
Directory.GetCreationTime(path));
See this MSDN page.
Hope that helps out!
you can turn off the warning message as explained in the other answers or you can understand what's happening and fix it.
As of MySQL 5.7.5, the default SQL mode includes ONLY_FULL_GROUP_BY which means when you are grouping rows and then selecting something out of that groups, you need to explicitly say which row should that selection be made from.
Mysql needs to know which row in the group you're looking for, which gives you two options
group by rect.color, rect.value
which can be what you want in some cases otherwise would return duplicate results with the same color which you may not wantAVG()
MIN()
MAX()
complete list ANY_VALUE()
if you are sure that all the results inside the group are the same. doc1.One of the Way is by using cardview and recycler view together we can easily add effect like divider. ex.https://developer.android.com/training/material/lists-cards.html
2.and other is by adding view as divider to list_item_layout of recycler view.
<View
android:id="@+id/view1"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/colorAccent" />
The way to do this is to set the EnableHeadersVisualStyles
flag for the data grid view to False
, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor
property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):
_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;
If you do not set the EnableHeadersVisualStyles
flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.
What about this expect script?
#!/usr/bin/expect -f
spawn ssh root@myhost
expect -exact "root@myhost's password: "
send -- "mypassword\r"
interact
docker-compose -f [COMPOSE_FILE_NAME].yml restart [SERVICE_NAME]
Use Case #1: If the COMPOSE_FILE_NAME is docker-compose.yml
and service is worker
docker-compose restart worker
Use Case #2: If the file name is sample.yml
and service is worker
docker-compose -f sample.yml restart worker
By default docker-compose looks for the docker-compose.yml
if we run the docker-compose
command, else we have flag to give specific file name with -f [FILE_NAME].yml
increase javaMaxHeapsize in your build.gradle(Module:app) file
dexOptions {
javaMaxHeapSize "1g"
}
to (Add this line in gradle)
dexOptions {
javaMaxHeapSize "4g"
}
System.Reflection.Assembly.GetExecutingAssembly().Location
You should either get a window with a list of repositories or a text menu with some options. But if that is not appearing, you can always specify the mirror from where to download the packages yourself by using repos
parameter. By doing that, R will not ask you anymore about the repository. Example:
install.packages('RMySQL', repos='http://cran.us.r-project.org')
Here you have a list of mirrors for R.
Like T.J. Crowder stated above, the filter function does wonders. It wasn't working for me in my specific case. I needed to search multiple tables and their respective td tags inside a div (in this case a jQuery dialog).
$("#MyJqueryDialog table tr td").filter(function () {
// The following implies that there is some text inside the td tag.
if ($.trim($(this).text()) == "Hello World!") {
// Perform specific task.
}
});
I hope this is helpful to someone!
Simply restate the target field & condition;
where (field like "*AA*" and field not like "*BB*")
download putty connection manager from here http://www.thegeekstuff.com/scripts/puttycm.zip
Thanks
From the announcement Git 1.7.10 (April 2012):
git clone
learned--single-branch
option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.
Git actually allows you to clone only one branch, for example:
git clone -b mybranch --single-branch git://sub.domain.com/repo.git
Note: Also you can add another single branch or "undo" this action.
Allow only 2 ip , all other will block
Order Deny,Allow
Deny from all
Allow from 173.11.227.73 108.222.245.179
spring.jpa.hibernate.ddl-auto = update
change update
to create
, and run it
after run safely again change create
to update
so again all tables will not create and you can use your previous data
This working for me Try it
mongoexport --host cluster0-shard-dummy-link.mongodb.net:27017 --db yourdbname --forceTableScan --collection users --type json --out /var/www/html/user.json --authenticationDatabase admin --ssl --username Yourusername --password Yourpassword
Above cmd return whole data of the users collection if you want filter field then add --fields=email,name
I had the same problem, when I saw that my Node.js installation is outdated.
These few lines will handle everything (for Ubuntu):
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
After this node -v
will return you the latest available version.
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
Just remove the .val(). Like:
if ( $('html').attr('lang') == 'fr-FR' ) {
// do this
} else {
// do that
}
I was also curious if I can measure the speed of my script with apache abs or a construct / destruct php measure script or a php extension.
the last two have failed for me: they are approximate. after which I thought to try "ab" and "abs".
the command "ab -k -c 350 -n 20000 example.com/" is beautiful because it's all easier!
but did anyone think to "localhost" on any apache server for example www.apachefriends.org?
you should create a folder such as "bench" in root where you have 2 files: test "bench.php" and reference "void.php".
<?php
for($i=1;$i<50000;$i++){
print ('qwertyuiopasdfghjklzxcvbnm1234567890');
}
?>
<?php
?>
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
pause
Now if you pay attention closely ...
the void script isn't produce zero results !!! SO THE CONCLUSION IS: from the second result the first result should be decreased!!!
here i got :
c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/void.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software: Apache/2.4.33
Server Hostname: localhost
Server Port: 80
Document Path: /bench/void.php
Document Length: 0 bytes
Concurrency Level: 1
Time taken for tests: 11.219 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 2150000 bytes
HTML transferred: 0 bytes
Requests per second: 891.34 [#/sec] (mean)
Time per request: 1.122 [ms] (mean)
Time per request: 1.122 [ms] (mean, across all concurrent requests)
Transfer rate: 187.15 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.3 0 1
Processing: 0 1 0.9 1 17
Waiting: 0 1 0.9 1 17
Total: 0 1 0.9 1 17
Percentage of the requests served within a certain time (ms)
50% 1
66% 1
75% 1
80% 1
90% 1
95% 2
98% 2
99% 3
100% 17 (longest request)
c:\xampp\htdocs\bench>"c:\xampp\apache\bin\abs.exe" -n 10000 http://localhost/bench/bench.php
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software: Apache/2.4.33
Server Hostname: localhost
Server Port: 80
Document Path: /bench/bench.php
Document Length: 1799964 bytes
Concurrency Level: 1
Time taken for tests: 177.006 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 18001600000 bytes
HTML transferred: 17999640000 bytes
Requests per second: 56.50 [#/sec] (mean)
Time per request: 17.701 [ms] (mean)
Time per request: 17.701 [ms] (mean, across all concurrent requests)
Transfer rate: 99317.00 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.3 0 1
Processing: 12 17 3.2 17 90
Waiting: 0 1 1.1 1 26
Total: 13 18 3.2 18 90
Percentage of the requests served within a certain time (ms)
50% 18
66% 19
75% 19
80% 20
90% 21
95% 22
98% 23
99% 26
100% 90 (longest request)
c:\xampp\htdocs\bench>pause
Press any key to continue . . .
90-17= 73 the result i expect !
I did not get it. I had a similar problem but in my nav bar.
What I was doing is I kept my navBar code in this way: nav>div.navlinks>ul>li*3>a
In order to put hover effects on a I positioned a to relative and designed a::before
and a::after
then i put a gray background on before and after elements and kept hover effects in such way that as one hovers on <a>
they will pop from outside a to fill <a>
.
The problem is that the overflow hidden is not working on <a>
.
What i discovered is if i removed <li>
and simply put <a>
without <ul>
and <li>
then it worked.
What may be the problem?
git branch --set-upstream-to origin/solaris
The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.
If you do not have upstream for the current branch, however, Git changes its behavior on git push
, and on other commands as well.
The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push
was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default
which now defaults to simple
. For several versions of Git before and after 2.0, every time you ran git push
, Git would spew lots of noise trying to convince you to set push.default
just to get git push
to shut up.
You do not mention which version of Git you are running, nor whether you have configured push.default
, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default
to simple
to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default
set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.
An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.
Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.
The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B
or local like master
). That is, if the current branch B has upstream U, git rev-parse U
should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv
, will show the upstream setting but mark it as "gone".
If your push.default
is set to simple
or upstream
, the upstream setting will make git push
, used with no additional arguments, just work.
That's it—that's all it does for git push
. But that's fairly significant, since git push
is one of the places where a simple typo causes major headaches.
If your push.default
is set to nothing
, matching
, or current
, setting an upstream does nothing at all for git push
.
(All of this assumes your Git version is at least 2.0.)
git fetch
If you run git fetch
with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin
.)
git merge
and git rebase
tooIf you run git merge
or git rebase
with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.
git pull
You should never2 use git pull
anyway, but if you do, git pull
uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull
does the same thing as git fetch
—because it actually runs git fetch
—and then does the same thing as git merge
or git rebase
, because it actually runs git merge
or git rebase
.
(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)
git status
This may actually be the most important. Once you have an upstream set, git status
can report the difference between your current branch and its upstream, in terms of commits.
If, as is the normal case, you are on branch B
with its upstream set to origin/B
, and you run git status
, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.
This is because git status
runs:
git rev-list --count @{u}..HEAD
: how many commits do you have on B
that are not on origin/B
?git rev-list --count HEAD..@{u}
: how many commits do you have on origin/B
that are not on B
?Setting an upstream gives you all of these things.
master
already has an upstream set?When you first clone from some remote, using:
$ git clone git://some.host/path/to/repo.git
or similar, the last step Git does is, essentially, git checkout master
. This checks out your local branch master
—only you don't have a local branch master
.
On the other hand, you do have a remote-tracking branch named origin/master
, because you just cloned it.
Git guesses that you must have meant: "make me a new local master
that points to the same commit as remote-tracking origin/master
, and, while you're at it, set the upstream for master
to origin/master
."
This happens for every branch you git checkout
that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.
If you create a new branch:
$ git checkout -b solaris
there is, as yet, no origin/solaris
. Your local solaris
cannot track remote-tracking branch origin/solaris
because it does not exist.
When you first push the new branch:
$ git push origin solaris
that creates solaris
on origin
, and hence also creates origin/solaris
in your own Git repository. But it's too late: you already have a local solaris
that has no upstream.3
Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.
The fact is, it doesn't today, unless you use --set-upstream
or -u
during the git push
. That's what the message is telling you.
You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris
on origin
, through an earlier push, and as your git branch
output shows, you already have origin/solaris
in your local repository.
You just don't have it set as the upstream for solaris
.
To set it now, rather than during the first push, use git branch --set-upstream-to
. The --set-upstream-to
sub-command takes the name of any existing branch, such as origin/solaris
, and sets the current branch's upstream to that other branch.
That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch
, then look around, then run git merge
or git rebase
as appropriate, then make new commits and run git push
, without a bunch of additional fussing-around.
1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".
2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch
actually did, and they can then see what git merge
or git rebase
will do next.
3If you run your first git push
as git push -u origin solaris
—i.e., if you add the -u
flag—Git will set origin/solaris
as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u
on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to
is easier, if you forgot.
4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.
You can use random.uniform
import random
random.uniform(0, 1)
Pure JS solution, with date formatted YYYY-mm-dd
format
var someDate = new Date('2014-05-14');_x000D_
someDate.setDate(someDate.getDate() + 15); //number of days to add, e.x. 15 days_x000D_
var dateFormated = someDate.toISOString().substr(0,10);_x000D_
console.log(dateFormated);
_x000D_
If you are working in a browser that doesn't support tabindex="-1"
, you may be able to get away with just giving the things that need to be skipped a really high tab index. For example tabindex="500"
basically moves the object's tab order to the end of the page.
I did this for a long data entry form with a button thrown in the middle of it. It's not a button people click very often so I didn't want them to accidentally tab to it and press enter. disabled
wouldn't work because it's a button.
You missed underscore in argument document_root. But it's bad idea to use serve
in production. Use something like this instead:
import os
from django.conf import settings
from django.http import HttpResponse, Http404
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
reinterpret_cast
You dont inherit in css, you simply add another class to the element which overrides the values
.base{
color:green;
...other props
}
.basealt{
color:red;
}
<span class="base basealt"></span>
Using pyautogui
To install
pip install pyautogui
and to find the location of the mouse pointer
import pyautogui
print(pyautogui.position())
This will give the pixel location to which mouse pointer is at.
DELETE b FROM BLOB b
LEFT JOIN FILES f ON f.id = b.fileid
WHERE f.id IS NULL
DELETE FROM BLOB
WHERE NOT EXISTS(SELECT NULL
FROM FILES f
WHERE f.id = fileid)
DELETE FROM BLOB
WHERE fileid NOT IN (SELECT f.id
FROM FILES f)
Whenever possible, perform DELETEs within a transaction (assuming supported - IE: Not on MyISAM) so you can use rollback to revert changes in case of problems.
I've answered my own question. Call apply_filter
and there you go.
<?php
$id=47;
$post = get_post($id);
$content = apply_filters('the_content', $post->post_content);
echo $content;
?>
Clean solution while staying with the nio API:
Files.isDirectory(path)
Files.isRegularFile(path)
Address already in use
means that the port
you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
So if you encounter this error, just see which application/process is using the port.
In linux try using netstat -tulpn
. This command will list down a process list with all running processes.
Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
netstat -tulpn
to display the processeskill <pid>
This will terminate the processIf you are using windows,
netstat -a -o -n
to check for the port usagestaskkill /F /PID <pid>
to kill that processHere's how you should do it:
change_column :users, :admin, :boolean, :default => false
But some databases, like PostgreSQL, will not update the field for rows previously created, so make sure you update the field manaully on the migration too.
In reference to the quick reference list, specifically you can use the following :
\.\ Root Directory + Current directory (Drive Letter)
SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')
@echo off
for %%f in (*.txt) do (
ren "%%~nf%%~xf" "%%~nf 1.1%%~xf"
)
Since you're only dealing with a 3x3 matrix of possible locations, it'd be pretty easy to just write a search through all possibilities without taxing you computing power. For each open space, compute through all the possible outcomes after that marking that space (recursively, I'd say), then use the move with the most possibilities of winning.
Optimizing this would be a waste of effort, really. Though some easy ones might be:
There are 2 ways in which you can get the values:-
i solve it by using dataType='jsonp' at the place of dataType='json'
public void schedule(TimerTask task,long delay)
Schedules the specified task for execution after the specified delay.
you want:
public void schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
I know this is an old Question
But in case you want to do it programmatically or the java way
For Image Backgrounds; you can use BackgroundImage class
BackgroundImage myBI= new BackgroundImage(new Image("my url",32,32,false,true),
BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
BackgroundSize.DEFAULT);
//then you set to your node
myContainer.setBackground(new Background(myBI));
For Paint or Fill Backgrounds; you can use BackgroundFill class
BackgroundFill myBF = new BackgroundFill(Color.BLUEVIOLET, new CornerRadii(1),
new Insets(0.0,0.0,0.0,0.0));// or null for the padding
//then you set to your node or container or layout
myContainer.setBackground(new Background(myBF));
Keeps your java alive && your css dead..
The usual way is to use zip()
:
for x, y in zip(a, b):
# x is from a, y is from b
This will stop when the shorter of the two iterables a
and b
is exhausted. Also worth noting: itertools.izip()
(Python 2 only) and itertools.izip_longest()
(itertools.zip_longest()
in Python 3).
For properties configuration
# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.
You can use sed
:
sed -i 's/abc/XYZ/gi' /tmp/file.txt
You can use find
and sed
if you don't know your filename:
find ./ -type f -exec sed -i 's/abc/XYZ/gi' {} \;
Find and replace in all Python files:
find ./ -iname "*.py" -type f -exec sed -i 's/abc/XYZ/gi' {} \;
It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.
My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.
Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.
You can convert list in string with elements seperated by space and split it based on number/char to be searched..
Will be clean and fast for large list..
>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3
JSX tags (<Component/>
) are clearly not standard javascript and have no special meaning if you put them inside a naked <script>
tag for example. Hence all React files that contain them are JSX and not JS.
By convention, the entry point of a React application is usually .js instead of .jsx even though it contains React components. It could as well be .jsx. Any other JSX files usually have the .jsx extension.
In any case, the reason there is ambiguity is because ultimately the extension does not matter much since the transpiler happily munches any kinds of files as long as they are actually JSX.
My advice would be: don't worry about it.
First, your HTML markup looks like this:
<video id="awesome_video" src="first_video.mp4" autoplay />
Second, your JavaScript code will look like this:
<script type="text/javascript">
var index = 1,
playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
video = document.getElementById('awesome_video');
video.addEventListener('ended', rotate_video, false);
function rotate_video() {
video.setAttribute('src', playlist[index]);
video.load();
index++;
if (index >= playlist.length) { index = 0; }
}
</script>
And last but not least, your CSS:
#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.
Swift 3
Not sure about you guys, but I'm having a hard time with this one. I did something like this:
if let window = UIApplication.shared.delegate?.window {
if var viewController = window?.rootViewController {
// handle navigation controllers
if(viewController is UINavigationController){
viewController = (viewController as! UINavigationController).visibleViewController!
}
print(viewController)
}
}
I kept getting the initial view controller of my app. For some reason it wanted to stay the root view controller no matter what. So I just made a global string type variable currentViewController
and set its value myself in each viewDidLoad()
. All I needed was to tell which screen I was on & this works perfectly for me.
As of 2.6, set.intersection
takes arbitrarily many iterables.
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])
I ran into this problem debugging play framework version 2.x, turned out the server hadn't been started even though the play debug run command was issued. After a first request to the webserver which caused the play framework to really start the application at port 9000, I was able to connect properly to the debug port 9999 from eclipse.
[info] play - Application started (Dev)
The text above was shown in the console when the message above appeared, indicating why eclipse couldn't connect before first http request.
You can hijack your Android audio port using an Arduino board like this. Then, you have two options (as far as I'm concerned):
1) Buy another Arduino Shield that supports RFID. I haven't seen one that supports UHF so far.
2) Try to connect your Arduino hijack with a USB RFID reader and build some embedded hardware kit.
Right now, I'm working in the second option but with iPhone.
To expand one what CheeseConQueso is saying, here are the entire steps to update a view using PHPMyAdmin:
SHOW CREATE VIEW your_view_name
CREATE VIEW
... syntax) to make sure it runs as you expect it to.CREATE VIEW...
syntax).I hope that helps somebody. Special thanks to CheesConQueso for his/her insightful answer.
Paste following link to directly under link button click event, otherwise use javascript to call code behind function
Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Diagnostics.Process.Start(FilePath)
End Sub
Return the list directly. Benefits:
You should use the iterator (yield) from when you think you probably won't have to iterate all the way to the end of the list, or when it has no end. For example, the client calling is going to be searching for the first product that satisfies some predicate, you might consider using the iterator, although that's a contrived example, and there are probably better ways to accomplish it. Basically, if you know in advance that the whole list will need to be calculated, just do it up front. If you think that it won't, then consider using the iterator version.
You could do something like the following:
static int tableWidth = 73;
static void Main(string[] args)
{
Console.Clear();
PrintLine();
PrintRow("Column 1", "Column 2", "Column 3", "Column 4");
PrintLine();
PrintRow("", "", "", "");
PrintRow("", "", "", "");
PrintLine();
Console.ReadLine();
}
static void PrintLine()
{
Console.WriteLine(new string('-', tableWidth));
}
static void PrintRow(params string[] columns)
{
int width = (tableWidth - columns.Length) / columns.Length;
string row = "|";
foreach (string column in columns)
{
row += AlignCentre(column, width) + "|";
}
Console.WriteLine(row);
}
static string AlignCentre(string text, int width)
{
text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;
if (string.IsNullOrEmpty(text))
{
return new string(' ', width);
}
else
{
return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
}
}
Same symptom, in the context of a Rails application with Bootstrap provided by the bootstrap-sass
gem, and @merv's answer put me on the right track.
My application.js
file had the following:
//= require bootstrap
//= require bootstrap-sprockets
The fix was to remove one of the two lines. Indeed, the gem's readme warns you about this error. My bad.
mailto:[email protected]?subject=Your+subject
https://groups.google.com/group/golang-nuts/msg/71c307e4d73024ce?pli=1
The germane part:
Since integer types use two's complement arithmetic, you can infer the min/max constant values for
int
anduint
. For example,const MaxUint = ^uint(0) const MinUint = 0 const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1
As per @CarelZA's comment:
uint8 : 0 to 255
uint16 : 0 to 65535
uint32 : 0 to 4294967295
uint64 : 0 to 18446744073709551615
int8 : -128 to 127
int16 : -32768 to 32767
int32 : -2147483648 to 2147483647
int64 : -9223372036854775808 to 9223372036854775807
I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.
Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Go to "Fixed curl extensions" and download the extension that matches your PHP version.
Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)
Restart Apache
Done!
Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html
Cheers!
Here's the mysql reference for cursors. So I'm guessing it's something like this:
DECLARE done INT DEFAULT 0;
DECLARE products_id INT;
DECLARE result varchar(4000);
DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO products_id;
IF NOT done THEN
CALL generate_parameter_list(@product_id, @result);
SET param = param + "," + result; -- not sure on this syntax
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
-- now trim off the trailing , if desired
1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to
F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;
change your drive and folder depending on your requirement...
Open cmd and type the command below.
netstat -o -n -a | findstr 0.0:80
Last column of each row is the process identifier (PID)
You can find the application that reserves port 80, using taskmanager services tab or just type tasklist
in cmd.
Then follow this link: http://www.ttkalec.com/blog/resolving-yellow-wamp-server-status-freeing-up-port-80-for-apache/
For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:
import java.util.concurrent.atomic.AtomicInteger;
public class PrimitivePassByReferenceSample {
/**
* @param args
*/
public static void main(String[] args) {
AtomicInteger myNumber = new AtomicInteger(0);
System.out.println("MyNumber before method Call:" + myNumber.get());
PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
temp.changeMyNumber(myNumber);
System.out.println("MyNumber After method Call:" + myNumber.get());
}
void changeMyNumber(AtomicInteger myNumber) {
myNumber.getAndSet(100);
}
}
Output:
MyNumber before method Call:0
MyNumber After method Call:100
if (!$("input[name='html_elements']:checked").val()) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
For the sake of completeness, here's another possible solution:
SELECT sensorID,timestamp,sensorField1,sensorField2
FROM sensorTable s1
WHERE timestamp = (SELECT MAX(timestamp) FROM sensorTable s2 WHERE s1.sensorID = s2.sensorID)
ORDER BY sensorID, timestamp;
Pretty self-explaining I think, but here's more info if you wish, as well as other examples. It's from the MySQL manual, but above query works with every RDBMS (implementing the sql'92 standard).
SELECT
STATUS,
CASE
WHEN STATUS IN('a1','a2','a3')
THEN 'Active'
WHEN STATUS = 'i'
THEN 'Inactive'
WHEN STATUS = 't'
THEN 'Terminated' ELSE null
END AS STATUSTEXT
FROM
stage.tst;
<html>_x000D_
_x000D_
<head>_x000D_
<style type="text/css">_x000D_
div.box {_x000D_
background: #EEE;_x000D_
height: 100px;_x000D_
width: 500px;_x000D_
}_x000D_
div.left {_x000D_
background: #999;_x000D_
float: left;_x000D_
height: 100%;_x000D_
width: auto;_x000D_
}_x000D_
div.right {_x000D_
background: #666;_x000D_
height: 100%;_x000D_
}_x000D_
div.clear {_x000D_
clear: both;_x000D_
height: 1px;_x000D_
overflow: hidden;_x000D_
font-size: 0pt;_x000D_
margin-top: -1px;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="box">_x000D_
<div class="left">Tree</div>_x000D_
<div class="right">View</div>_x000D_
<div class="right">View</div>_x000D_
<div style="width: <=100% getTreeWidth()100 %>">Tree</div>_x000D_
<div class="clear" />_x000D_
</div>_x000D_
<div class="ColumnWrapper">_x000D_
<div class="ColumnOneHalf">Tree</div>_x000D_
<div class="ColumnOneHalf">View</div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
(setq indent-line-function 'insert-tab)
(setq c-default-style "linux")
(setq c-basic-offset 4)
(c-set-offset 'comment-intro 0)
this works for C++ code and the comment inside too
You don't need to escape it inside. You can use the |
character to delimit searches.
"\"foo\"\'bar\'".replace(/("|')/g, "")