w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
launching adhoc docker instances: Is it recommended to launch a docker instance per request?
Originally I said this should work well for low traffic sites, but upon further thought, no, this is a bad idea. Each time you launch a Docker container, it adds a read-write layer to the image. Even if there is very little data written, the layer exists, and each request will generate one. When a single user visits a website, rendering the page will generate 10's to 1000's of requests, for CSS, for javascript, for each image, for fonts, for AJAX, and each of these would create those read-write layers. Right now there is no automatic cleanup of the read-write layers -- they persist even after the Docker container has exited. By default, nothing is lost. So, even for a single low traffic site, you would find your disk use growing steadily over time. You could add your own automated clean

Categories : Nginx

syslog: does it remove the old logs if there would be less space on the storage
It completely depends how much stuff gets logged, but if you only have ~100MB, I would imagine that it's certainly likely that your storage will fill up before 30 years! You didn't say which syslog server you're using. If you're on an embedded device you might be using the BusyBox syslogd, or you may be using the regular syslogd, or you may be using rsyslog. But in general, no syslog server rotates log files all by itself. They all depend on external scripts run from cron to do it. So you should make sure you have such scripts installed. In non-embedded systems the log rotation functionality is often provided by a software package called logrotate, which is quite elaborate and has configuration files to say how and when which log files should be rotated. In embedded systems there is no s

Categories : Linux

What is the benefit of Docker container for a memcached instance?
There seems to be two questions here... 1 - The benefit is as you describe. You can sandbox the memcached instance (and configuration) in to separate containers so you could run multiple on a given host. In addition, moving the memcached instance to another host is pretty trivial and just requires an update to application configuration in the worst case. 2 - docker run -m <inbytes> <memcached-image> would limit the amount of memory a memcached container could consume. You can run as many of these as you want under a single host.

Categories : Linux

Web Deploy Command Line Logs in Event Logs (Updated / Inserted / Deleted Files) in event logs
I don't believe you can log the activities to the event log, but what you can do is use the -xml parameter to output the changes in XML format. You could then use this to log to the event log via a Powershell script, for example.

Categories : Iis

How to conveniently store common logs and client specific logs
I would have an xml file that contain the appenders to specify what packages go into what log file. You can then load the xml file in your application entry point. Below is an example I have used in my current project <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- appenders --> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <param name="threshold" value="error" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%t] %p %c - %m%n" /> </layout> </appender> <appender name="codebaseXAppender" class="org.apache.log4j.RollingFileAppender"> <

Categories : Java

Configuring an EC2 instance as a space to serve up all my RailsWordPress projects
It's surprisingly easy to get started but there are dozens of different ways to go about it. For the sake of giving you relevant resources I'm going to make a few assumptions about your setup and try to paint with broad strokes: You're running a Debian-based Linux distribution (Ubuntu is popular and has a great community) You're running a LAMP (Linux, Apache, MySQL, and PHP) stack (see Installing LAMP Server in the Ubuntu documentation). You'll be deploying your sites to the default server location of /var/www The first thing you'll want to do is read up on virtual hosts (vhosts). A common pattern is to put virtual hosts' web roots in subdirectories of /var/www/vhosts/ (e.g. /var/www/vhosts/example.com/), though these can technically live anywhere on the server. After creating your do

Categories : Ruby On Rails

How to set intellij to show logs in the logs tab and not the output tab
In the application server Run/Debug configuration open the Logs tab and specify the full log file path there. You can just search your disk for algo_js.log file and specify its location.

Categories : Spring

Get iPhone Logs(not crash logs)
Got a breakthrough!!. We need to re-direct NSLog to a file like this and then access the file. - (void)redirectNSLogToDocumentFolder{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fileName =[NSString stringWithFormat:@"%@.log",[NSDate date]]; NSString *logFilePath = [documentsDirectory stringByAppendingPathComponent:fileName]; freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr); } http://objcolumnist.com/2009/12/19/redirecting-nslog-to-a-log-file/

Categories : IOS

Running only one instance of an application,(Quit new instance and Display old instance or give Focus)
What you need to do is to add this to your main class: [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); Then you need to obtain a reference to the process that is already running, and then call the SetForegroundWindow method like this: SetForegroundWindow(SameProcess.MainWindowHandle); You do not need to kill the current process like you are currently doing, just return after focusing the other process' main window as shown above This is a full working example: [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { var currentProcess = Process.GetCurrentProcess(); foreach (Process p in Process.GetP

Categories : C#

We would like to register a user if space is available or put on waiting list if space is full. Any ideas how to approach this?
Maybe I'm missing something, but it doesn't seem that complicated to me. This answer only uses the SQL pieces that matter to preserve legibility, since I'm mainly referring to queries and not the VB. First, you do what you were already doing--check to see if they're already signed up/on the waiting list. SELECT Count(*) FROM ( SELECT * FROM tblTrainings UNION SELECT * FROM waitingList ) AS t WHERE Username = XXX AND CourseID = XXX AND LocationID = XXX AND dateID = XXX /* Tells you whether the person is signed up already, whether for the course itself or the waiting list. */ SELECT Count(*) FROM tblTrainings WHERE CourseID = XXX AND LocationID = XXX AND dateID = XXX -- This will give you the number of people in the course. Then, once you have that, you can decide whether to add th

Categories : Asp Net

UNIX:Create array from space delimited string while ignoring space in quotes
This is bash specific, may work with ksh/zsh inp='ROLE_NAME="Business Manager" ROLE_ID=67686' set -- $inp arr=() while (( $# > 0 )); do word=$1 shift # count the number of quotes tmp=${word//[^"]/} if (( ${#tmp}%2 == 1 )); then # if the word has an odd number of quotes, join it with the next # word, re-set the positional parameters and keep looping word+=" $1" shift set -- "$word" "$@" else # this word has zero or an even number of quotes. # add it to the array and continue with the next word arr+=("$word") fi done for i in ${!arr[@]}; do printf "%d %s " $i "${arr[i]}"; done 0 ROLE_NAME="Business Manager" 1 ROLE_ID=67686 This specifically breaks words on arbitrary whitespace but joins

Categories : Shell

javascript regex replace all doublequotes in string unless the doublequote is followed by space or comma space
A way: rebuild the json string: var str = '{"description":"This is my 12" pizza I ordered.","value":"1"}'; var regex = /"(.*?)"(?=s*([,:])s*"|(}))/g; var result = '{'; var arr = regex.exec(str); while (arr != null) { result += '"' + arr[1].replace(/\?"/g, '\"') + '"'; if (arr[2]) result += arr[2]; if (arr[3]) result += arr[3]; arr = regex.exec(str); } console.log(result);

Categories : Javascript

What is the linux command line to check kernel space and User space Memory used
Try: sudo slabtop or sudo cat /proc/slabinfo These should give you enough information to estimate the total kernel memory consumption. You can read more info about kernel and userspace memory here.

Categories : Linux

Adding empty rows or space in fo:table inly if there's enough space for next data
As a workaround, you can add 'padding-bottom' to each row except the last row in the table. You may end up with row 5 of your example being moved to the second page, but you can at least be sure that there's no extra space at the top of the page.

Categories : Xml

How to capitalize each word after a space leaving the rest of it as is and preserve the space in the end if it exists
Use re.sub: >>> import re >>> re.sub(r'[a-z]', lambda m: m.group().upper(), 'home swe eeeet home') 'Home Swe Eeeet Home' >>> re.sub(r'[a-z]', lambda m: m.group().upper(), 'heLLo OoO ooo ') 'HeLLo OoO Ooo ' re.sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function. If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. [a-z] match any lowercase character([a-z]) after the word boundary (). The lambda function

Categories : Python

Windows batch file to get C: drive total space and free space available
cut 9 digits of the size by bytes to get the size in GB: @echo off & setlocal ENABLEDELAYEDEXPANSION SET "volume=C:" FOR /f "tokens=1*delims=:" %%i IN ('fsutil volume diskfree %volume%') DO ( SET "diskfree=!disktotal!" SET "disktotal=!diskavail!" SET "diskavail=%%j" ) FOR /f "tokens=1,2" %%i IN ("%disktotal% %diskavail%") DO SET "disktotal=%%i"& SET "diskavail=%%j" (ECHO(Information for volume %volume% ECHO(total %disktotal:~0,-9% GB ECHO(avail. %diskavail:~0,-9% GB)>size.txt TYPE size.txt cmd can calculate only with numbers up to 2^31-1   (2,147,483,647 ~ 2.000001 Gigabytes)

Categories : Windows

Are Java threads created in user space or kernel space?
Java threads are "user" threads, but under the hood, the Java Virtual Machine is using kernel threads and delegating the user threads CPU time on each kernel thread in its kernel thread pool. See this question for a better explanation. It seems that threading is JVM-vendor specific, and my understanding might not hold for all JVM implementations.

Categories : Java

delete img tag and remove double space into single space using preg_replace
I think, you can use strip_tags instead $str = '<img src="xxxxxx"/> Title'; echo strip_tags($str); // Title Also using preg_replace $str = '<img src="xxxxxx"/> Title'; echo preg_replace('#<img.*?(/>|$)#s', '', $str, 1); // Title DEMO.

Categories : PHP

Splitting a string containing space-delimited "key=value" pairs when the value can also contain space
You can search for the unwanted spaces by using a lookahead that ensures that they don't preced a key: $input =~ s/[ ](?!S+=)/_/g; The lookahead makes sure that there is no = before the next space character. Then you can split on spaces. Alternatively, to match right away, you can use a similar technique: while ($input =~ m/(S+)=((?:S|[ ](?!S+=))+)/g) { # $1 is the key # $2 is the value } For the value we repeat either non-space characters or spaces that do not preced a key. Working demo. If your keys are always upper case, you can replace all S+ in my code with [A-Z]+.

Categories : Regex

How do I fix the right column space and bottom container space in html
Take a look at what are called Reset Sheets here: http://meyerweb.com/eric/tools/css/reset/ The specific CSS you are looking for is: html, body { margin: 0; padding: 0; }

Categories : Javascript

Why do you use camera space instead of model space for normals?
The main reason is, that usually your light positions will not be given in model space, but world space. However for illumination to work efficiently all calculations must happen in a common space. In your usual transformation chain, model local coordinates are transformed by the modelview matrix directly into view space p_view = MV · p_local Since you normally have only one modelview matrix it would be cumbersome to separate this steap into something like p_world = M · p_local p_view = V · p_world For that you required MV to be separated. Since the projection transformation traditionally happens as a separate step, view space is the natural "common lower ground" on which illumination calculation to base on. It just involves transforming transforming your light positions from wo

Categories : C++

How can i Access service Identities from one ACS name space with another ACS name space
I can't really understand what are you asking! ACS is a passive service! There is no such process like Service Identities to be able to call those Relying Party applications! Service Identity is a way to authenticate Active Clients - these server side processes that do not invoke user interaction. If you want to be able to authenticate in Relying Party X both with [IdP via ACS Namespace A] and Server side code identified by Service Identity in ACS Namespace B, then you just need to establish trust relationship between *Relying Party X and both ACS Namespaces. You cannot use ACS Namespace as an Identity Provider for another ACS Namespace. Which is what I understand you want to achieve.

Categories : Azure

Splitting a string on space except for single space
Like this: myString.split("\s{2,}"); or like this, myString.split(" \s+"); // notice the blank at the beginning. It depends on what you really want, which is not clear by reading the question. You can check the quantifier syntax in the Pattern class.

Categories : Java

regex to match space but escaped space
For the second case you can use: (?<!\) Edit: I don't usually work with javascript so i don't know of any quick shortcut, so i think you can do this at two steps: Perform a substitution (replace) using this regex: \s, replace with semicolon ; like this: var newCommand = command0.replace(/\s/g, ";"); Then perform split using this regex: s like this: var result = newCommand.split(/s/);

Categories : Javascript

Can a child instance access dynamic parent instance attributes and attribute values?
You're misusing inheritance. Rule doesn't need to inherit from Map to access a Map's attributes, and attaching a Rule to a Map won't make it see the Map's attribute values as its own. Inheriting from Map means a Rule is a Map, not that it's linked to or managed by a Map. If you want a Rule to know about its Map, have it record which Map it's associated with: class Rule(object): def __init__(self, number, map): super(Rule, self).__init__() self.number = number self.map = map def __str__(self): # __str__, not __repr__, because __repr__ should be unambiguous, # have a clear beginning and ending, and obviously indicate the type. return "Map {} rule number {}".format(self.map.mapName, self.number) Rule(1, map) # makes a rule associated

Categories : Python

Is there a way to reset a class instance's initialized attribute to the value entered when the instance was created?
There's nothing in Ruby that saves the initial value passed on, so nothing in Ruby that will let you automatically reset it. However, you can certainly save the value in an another instance variable and reset it as you wish, as in: def initialize(..., meat_quality) ... @original_meat_quality = @meat_quality = meat_quality end def reset_meat_quality @meat_quality = @original_meat_quality end

Categories : Ruby

Newly created instance takes the primary id of a deleted instance with same Account name
This is a known behavior of AUTO_INCREMENT fields in MySQL: http://forums.mysql.com/read.php?10,167180 If this is really your problem, you will have to find an other strategy to keep track of deleted user accounts. For more information, see Stop MySQL Reusing AUTO_INCREMENT IDs

Categories : SQL

Pass in an instance variable to a static method -- and modifies another instance variance?
Am I correct in saying that it is impossible for the other HashMap to be modified by foo as a result of just this one method call? Answer is may be. It is true that if you dont pass the reference of a object to method, you can not access it. But Map stores key-value Object pair refernece, it does not store the Objects, if both map share Object as key or value, then it would effect.

Categories : Java

Error: unbound method Dragon( ) must be called with Enemy instance as first argument (got Player instance instead)
You have to create an instance of a class first before you call any functions from it: myenemy = Enemy() myenemy.Dragon() In your code, it looks like you created self.enemy, but later you call self.enemy = Enemy.Dragon(self). Instead of this last line, put self.enemy = self.enemy.Dragon(self). It seems to be a recurring issue in the rest of your code as well. Commands = {'explore': Player.explore} should probably be Commands = {'explore': p.explore} (after you have created the instance p). Since your updated code, I think you're getting functions and classes mixed up. Dragon is a function, and when you do enemy = m.Dragon, you are simply copying the function onto enemy. And thus when you do enemy.name, thinking it's a class, an error is raised, because enemy is now a function, not a

Categories : Python

Are object of my classes being created everytime there is a request or does it only create one instance of a class per instance server
Instances of resource classes are created "per-request" by default. You can mark them as singletons however and then one instance would be used for all requests. To do this you can use the following annotations: @com.sun.jersey.spi.resource.Singleton for Jersey 1.x (JAX-RS 1.1) @javax.inject.Singleton for Jersey 2.x (JAX-RS 2.0)

Categories : Java

Calling an Instance method when user inputs the instance name as a String
You can use a Map for this. E.g.: Map<String, Skill> skills = new HashMap<String, Skill>(); To insert the values you put the values into the Map: skills.put(skill.getName(), skill); To retrieve your skill you can get the skill by name: Skill skill = skills.get(name);

Categories : Java

Assign instance id when the wpf app has multiple controls on page identified as one instance
An addendum to AdrianHHH's excellent suggestion is to iterate through the FindMatchingControls collection and figure out which one is the one you want. If it's always collection[3] then you can identify it and act on it as such. Your code would look like this: var button = new WinButton(winWindowChild(mainParentCtName, childParentCtName)); //if you pass parents when you construct an object it can speed up find button.SearchProperties.Add(/*any identifying properties*/); var allButtons = button.FindMatchingControls(); //test code foreach (var btn in allButtons) Mouse.Click(btn); //watch this to figure out what order the buttons are iterating through, then remove loop Mouse.Click(allButtons[3]); Mouse.DoubleCli

Categories : Wpf

Objects and Arrays of one instance are getting referenced by new instance of Backbone model
There is a hack I have used to solve this problem. Reset all the objects and arrays used as attributes in Backbone model in initialize method. var myModel = Backbone.Model.extend({ defaults: { exp: [], name: '', json: { } }, getExp: function() { return this.get('exp'); }, getJSON: function() { return this.get('json'); }, initialize: function() { this.set('exp', []); this.set('json', {}); } }); var m1 = new myModel(); var experiences = m1.getExp(); experiences.push('arrayitem1'); experiences.push('arrayitem2'); m1.set('name', 'my name'); var json = m1.getJSON(); json.key = 'somevalue'; var m2 = new myModel(); console.log(m1.attributes); console.log(m2.attributes); Working Demo at JSBIN

Categories : Javascript

How to use Angular.js service instance inside module config and keep the same instance
From the doc - Services as singletons All Angular services are application singletons. This means that there is only one instance of a given service per injector. Since Angular is lethally allergic to global state, it is possible to create multiple injectors, each with its own instance of a given service, but that is rarely needed, except in tests where this property is crucially important. It mean if you do injector.get for a single injector, it will always returns the singleton like this var injector = angular.injector(['app.services']); var singletonService1 = injector.get('singletonService'); var singletonService2 = injector.get('singletonService'); console.log(singletonService1 === singletonService2) // prints true However if you inject it to another the controller

Categories : Javascript

WPF, how to make a single instance and shows the MainWindow when another instance is launched in c#
If I havent misunderstood your question try something like this [STAThread] public static void Main(string[] args) { Task task = new Task(() => { Thread.Sleep(200); MessageBox.Show("what a marvelous engineering"); }); task.Start(); //If you want application not to run untill task is complete then just use wait task.Wait(); App app = new App(); app.InitializeComponent(); app.Run(); } But I am wondering if you want your C# work done before the your MainWindow instantiate why dont you just do your other wor just before App app=new App() and let the code run sequentially.

Categories : C#

How do foundation classes know what instance to act upon when an instance method is called?
In your example: [array count]; you are sending the count message to the instance named array. The instance the message is sent to is determined by the array part of that expression. Inside the method definition, the instance you are acting on is referred to by self. In your incrementByOne example, the instance method might do something like - (NSInteger)incrementByOne { return [self length] + 1; } The name self will refer to whatever instance that message was sent to.

Categories : Objective C

Create EC2 instance from another instance via command line or dynamically
You can utilize EC2 APIs for this purpose. ec2-run-instances (http://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ApiReference-cmd-RunInstances.html) is a command that allows you to create a new instance from your own (or public) AMI. You can also specify the number of instances you wish to create. There are also Web Service operation (RunInstances) for this purpose: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RunInstances.html Which one to use is up to you. However, I don't think starting a new instance from a master instance is a good practice in AWS. You can rely on Elastic Load Balancing (http://aws.amazon.com/elasticloadbalancing/) and Auto Scaling (http://aws.amazon.com/autoscaling/) to scale up/down your server fleet depending on incoming t

Categories : Amazon

An error in my singleton method, when create an instance. I want one instance only
You check if there is a value but you should check key instead. You should not use in_array() function use array_key_exists() instead. From PHP manual: in_array — Checks if a value exists in an array array_key_exists — Checks if the given key or index exists in the array change if (in_array($class, self::$objects)) { to if (array_key_exists($class, self::$objects)) { Working demo

Categories : PHP

Does python allow calling of an instance variable name from an instance method?
globals() return a dictionary that represents the namespace of the module (the namespace is not this dictionary, this latter only represents it) class A(object): def get_instance_name(self): for name,ob in globals().iteritems(): if ob is self: return name obj = A() print obj.get_instance_name() blah = A() print blah.get_instance_name() tu = (obj,blah) print [x.get_instance_name() for x in tu] result obj blah ['obj', 'blah'] . EDIT Taking account of the remarks, I wrote this new code: class A(object): def rondo(self,nameinst,namespace,li,s,seen): for namea,a in namespace.iteritems(): if a is self: li.append(nameinst+s+namea) if namea=='__builtins__': #this condition prev

Categories : Python

Instance methods and thread-safety of instance variables
There are many situations in which an instance may be accessible from multiple classes. For example, if your instance is a static variable in another class, then all threads would share that instance, and you can get into big trouble that way. That's just the first way that pops into my mind...

Categories : Java

© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.