id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_softwareengineering.338252 | I've just recently noticed there is an option to have static methods in interfaces. Same as with static fields of interface, there is an interesting behavior: These are not inherited.I'm unsure it's any useful in the actual interfaces that are to be implemented. However, it enables the programmer to create interfaces that are just envelopes for static stuff, like e.g. utility classes are.A simple example is just an envelope for global constants. Compared to a class, you can easily notice the missing boilerplate of public static final as those are assumed (making it less verbose).public interface Constants { String LOG_MESSAGE_FAILURE = I took an arrow to the knee.; int DEFAULT_TIMEOUT_MS = 30;}You could also make something more complex, like this pseudo-enum of config keys.public interface ConfigKeys { static createValues(ConfigKey<?>... values) { return Collections.unmodifiableSet(new HashSet(Arrays.asList(values))); } static ConfigKey<T> key(Class<T> clazz) { return new ConfigKey<>(clazz); } class ConfigKey<T> { private final Class<T> type; private ConfigKey(Class<T> type) { this.type = type; } private Class<T> getType() { return type; } }}import static ConfigKeys.*;public interface MyAppConfigKeys { ConfigKey<Boolean> TEST_MODE = key(Boolean.class); ConfigKey<String> COMPANY_NAME = key(String.class); Set<ConfigKey<?>> VALUES = createValues(TEST_MODE, COMPANY_VALUE); static values() { return VALUES; }}You could also create some utility class this way. However, in utilities, it is often useful to use private or protected helper methods, which is not quite possible in classes.I consider it a nice new feature, and especially the fact the static members aren't inherited is an interesting concept that was introduced to interfaces only.I wonder if you can consider it a good practice. While code style and best practices aren't axiomatic and there is room for opinion, I think there are usually valid reasons backing the opinion.I'm more interested in the reasons (not) to use patterns like these two.Note that I don't intend to implement those interfaces. They are merely an envelope for their static content. I only intend to use the constants or methods and possibly use static import. | Is static interface a good practice? | java;java8 | null |
_unix.304622 | Somewhat of a bizarre issue, I'm using irssi in iterm3, and I have iterm set to read the left escape key as +ESC as this is how I've gotten irssi to recognize pressing option and a number key to switch windows. However recently, while this works as usual for switching to windows 2 or higher, I can't use this shortcut to switch to window 1. I have to type out /window 1 every time I want the main window.Anybody have this issue, or know where to look? I can't see any conflicting shortcuts in iterm or anything. | Irssi: Using ALT + # to switch windows works for all windows but the first one | osx;keyboard shortcuts;irssi;iterm | null |
_codereview.153331 | I have been implementing the OAuth 2.0 implicit flow to secure the API I use in an Angular SAP. Please, could you review my code? I am sure there is a lot of stuff to improve in it.I have separated the API into two instances:Authentication server which checks the user and password and issues tokens.Resource server which holds the actual API which is protected with the use of tokens generated in the Authentication server.Is it a viable option to consider substituting my Authentication server with some open source solution like Thinktecture IdentityServer?The use of OAuth 2.0 in the resource server boils down to including the following in the Startup class: private void ConfigureOAuthTokenConsumption(IAppBuilder app) { OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); //Token Consumption app.UseOAuthBearerAuthentication(OAuthBearerOptions); }Here is the code I use in Authentication server:public class Startup{ public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); ConfigureOAuth(app); WebApiConfig.Register(config); var container = ConfigureAutoFac(config); app.UseAutofacMiddleware(container); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); app.UseWebApi(config); } public void ConfigureOAuth(IAppBuilder app) { OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString(/token), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10), Provider = new SimpleAuthorizationServerProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); } private IContainer ConfigureAutoFac(HttpConfiguration config) { var builder = new ContainerBuilder(); builder.RegisterType<AccountController>().InstancePerRequest(); // Set the dependency resolver to be Autofac. var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); return container; }}Here is the authorization server provider:public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider{ public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { // We are dealing with a browser based javascipt app so no clientId and client secret are transmitted. // There is nothing to validate context.Validated(); return Task.FromResult<object>(null); } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var allowedOrigin = context.OwinContext.Get<string>(as:clientAllowedOrigin); if (allowedOrigin == null) allowedOrigin = *; context.OwinContext.Response.Headers.Add(Access-Control-Allow-Origin, new[] { allowedOrigin }); using (AuthRepository _repo = new AuthRepository()) { IdentityUser user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError(invalid_grant, The user name or password is incorrect.); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(sub, context.UserName)); identity.AddClaim(new Claim(role, user)); var props = new AuthenticationProperties(new Dictionary<string, string> { { userName, context.UserName } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult<object>(null); }}Here is the AuthContext class allowing access to the database. I'm not really sure if it is necessary:public class AuthContext : IdentityDbContext<IdentityUser>{ public AuthContext() : base(AuthContext) { }}The actual AuthRepository which requires the AuthContext:public class AuthRepository : IDisposable{ private AuthContext _ctx; private UserManager<IdentityUser> _userManager; public AuthRepository() { _ctx = new AuthContext(); _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx)); } public async Task<IdentityResult> RegisterUser(UserModel userModel) { IdentityUser user = new IdentityUser { UserName = userModel.Username }; var result = await _userManager.CreateAsync(user, userModel.Password); return result; } public async Task<IdentityUser> FindUser(string userName, string password) { IdentityUser user = await _userManager.FindAsync(userName, password); return user; } public async Task<IdentityUser> FindAsync(UserLoginInfo loginInfo) { IdentityUser user = await _userManager.FindAsync(loginInfo); return user; } public async Task<IdentityResult> CreateAsync(IdentityUser user) { var result = await _userManager.CreateAsync(user); return result; } public async Task<IdentityResult> AddLoginAsync(string userId, UserLoginInfo login) { var result = await _userManager.AddLoginAsync(userId, login); return result; } public void Dispose() { _ctx.Dispose(); _userManager.Dispose(); }}Is that approach correct? If not, what should i change? | OAuth 2.0 implicit flow implementation | c#;security;asp.net;asp.net web api;oauth | null |
_softwareengineering.209819 | I am starting with this project of mine of writing a custom UI for linux. What would happen is:The computer would boot into this UI which would not be the typical taskbar/icons/startbutton kind of thing. Think more like a dedicated UI instead of a general purpose one.It would provide access to wifi, ethernet, bluetooth etc. Basically have access to most system resources.Up until this point, I don't planning on having a file manager for the user. The app would take care of this. Sort of the way apps on mobile phones work.My first instinct was to work (fork an existing one) on a custom DE like Gnome/KDE. So I read up a lot about window managers and desktop environments and while window managers seem to be the best option for what I am trying to do, another idea occurred to me which would be much less complicated. I could simply (I know!) write an app which the native OS boots into, without any splash screen etc. So, take a distro like Arch Linux, strip it down to the basics and then build an app on top of that.I would like to get some advice on what the best way to go forward with this would be. Do you guys concur that an app is better to go with? Please excuse me if the question seems naive. Any suggestions/ideas welcome. | Creating a custom GUI. App/DE/WM? | c++;linux;startup;desktop application;development | null |
_softwareengineering.190935 | This question is similar to the question posted on Does groovy call partial application 'currying'?, but not completely the same, and the answers given there do not really satisfy me.I would like to state right at this point, before I go any further, that currying is one of the concepts that have been hard to fully understand. I think the reason for that is the fact that there seem to be two general definitions of currying, and they don't really mean the same thing both in theory and in application.That being said, I think currying is a very simple concept once you decide to take only one of the two definitions and stick to it. In fact, currying should not be difficult to understand at all, but in my experience, understanding currying has been the equivalent of showing a little boy an apple and telling him that fruit is called apple, and then you go on calling that fruit an orange. The boy will never understand the simple concept of an apple because you have caused an enormous amount of confusion by calling the apple an orange.The definition of currying that I've accepted as the right one is that currying is taking a function of an arbitrary arity and turning it into multiple chainable functions each of which accepts only one parameter (unary functions). In code, it would look like this:f(1,2,3);//becomesf(1)(2)(3);However, some people, including well known programmers like John Resig, explain currying as something completely different. For them, currying is no more than simple partial application. There is even a generally accepted javascript function for currying:Function.prototype.curry = function() { var fn = this, args = Array.prototype.slice.call(arguments); return function() { return fn.apply(this, args.concat( Array.prototype.slice.call(arguments))); }; };This functions does not really curry anything, but rather partially applies the supplied arguments. The reason why I don't think this function curries anything is because you can end up with a function that accepts more than one argument:var f2 = f.curry(1); //f accepts 3 arguments f(1,2,3);f2(2,3); // calling the resulting curried function.So, my question is, have I misunderstood currying or have they?I will leave you with this post that explains currying in javascript, but in a way in which I don't really see any currying: https://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/ | Have they missunderstood currying or have I? | javascript;currying | null |
_cstheory.1699 | In this question, a 3CNF formula means a CNF formula where each clause involves exactly three distinct variables. For a constant 0<s<1, Gap-3SATs is the following promise problem:Gap-3SATsInstance: A 3CNF formula .Yes-promise: is satisfiable.No-promise: No truth assignments satisfy more than s fraction of the clauses of .One of the equivalent ways to state the celebrated PCP theorem [AS98, ALMSS98] is that there exists a constant 0<s<1 such that Gap-3SATs is NP-complete.We say that a 3CNF formula is pairwise B-bounded if every pair of distinct variables appears in at most B clauses. For example, a 3CNF formula (x1x2x4)(x1x3x4)(x1x3x5) is pairwise 2-bounded but not pairwise 1-bounded because e.g. the pair (x1, x4) appears in more than one clause.Question. Do there exist constants B, a>0, and 0<s<1 such that Gap-3SATs is NP-complete even for a 3CNF formula which is pairwise B-bounded and consists of at least an2 clauses, where n is the number of variables?The pairwise boundedness clearly implies that there are only O(n2) clauses. Together with the quadratic lower bound on the number of clauses, it roughly says that no pair of distinct variables appears in significantly more clauses than the average.For Gap-3SAT, it is known that the sparse case is hard: there exists a constant 0<s<1 such that Gap-3SATs is NP-complete even for a 3CNF formula where each variable occurs exactly five times [Fei98]. On the other hand, the dense case is easy: Max-3SAT admits a PTAS for a 3CNF formula with (n3) distinct clauses [AKK99], and therefore Gap-3SATs in this case is in P for every constant 0<s<1. The question asks about the middle of these two cases.The above question arose originally in a study of quantum computational complexity, more specifically two-prover one-round interactive proof systems with entangled provers (MIP*(2,1) systems). But I think that the question may be interesting in its own right.References[AKK99] Sanjeev Arora, David Karger, and Marek Karpinski. Polynomial time approximation schemes for dense instance of NP-hard problems. Journal of Computer and System Sciences, 58(1):193210, Feb. 1999. http://dx.doi.org/10.1006/jcss.1998.1605[ALMSS98] Sanjeev Arora, Carsten Lund, Rajeev Motwani, Madhu Sudan, and Mario Szegedy. Proof verification and the hardness of approximation problems. Journal of the ACM, 45(3):501555, May 1998. http://doi.acm.org/10.1145/278298.278306[AS98] Sanjeev Arora and Shmuel Safra. Probabilistic checking of proofs: A new characterization of NP. Journal of the ACM, 45(1):70122, Jan. 1998. http://doi.acm.org/10.1145/273865.273901[Fei98] Uriel Feige. A threshold of ln n for approximating set cover. Journal of the ACM, 45(4):634652, July 1998. http://doi.acm.org/10.1145/285055.285059 | Is Gap-3SAT NP-complete even for 3CNF formulas where no pair of variables appears in significantly more clauses than the average? | cc.complexity theory;sat;approximation hardness | null |
_cs.74725 | There are two commonly mentioned partition methods:algorithm lomuto_partition(A, lo, hi) ispivot := A[hi]i := lo - 1 for j := lo to hi - 1 do if A[j] pivot then i := i + 1 swap A[i] with A[j]swap A[i+1] with A[hi]return i + 1algorithm hoare_partition(A, lo, hi) ispivot := A[lo]i := lo - 1j := hi + 1loop forever do i := i + 1 while A[i] < pivot do j := j - 1 while A[j] > pivot if i >= j then return j swap A[i] with A[j](excerpt from Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2009) [1990]. Introduction to Algorithms. MIT Press and McGraw-Hill. pp. 170190.)And it has been suggested that Lomuto's method is simple and easier to implement, but should not be used for implementing a library sorting method.But why does Lomuto partitioning scheme use rightmost element(A[hi]) as pivot value and Hoare scheme use leftmost element (A[lo]) as pivot value?It seems that there is no difference in number of comparisons or swaps and they will produce worst case behavior on already sorted arrays.Is it just because they implemented and introduced them with rightmost element and leftmost element as pivot value respectively? Or is there a reason? | Selection of pivot in quicksort partitioning of Hoare and Lomuto | algorithms;sorting;quicksort | null |
_unix.192511 | I am trying to understand the load average on my system when idle. Here are some results after the system has been running for a few hours, with almost nothing installed. vmstatroot@arm:~# vmstat 1procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu---- r b swpd free buff cache si so bi bo in cs us sy id wa 0 0 0 62092 17860 135940 0 0 9 21 158 245 1 1 97 0 0 0 0 62092 17860 135940 0 0 0 0 105 137 0 0 100 0 0 0 0 62060 17860 135940 0 0 0 0 105 128 0 0 100 0 0 0 0 62060 17860 135940 0 0 0 0 105 174 0 0 100 0 0 0 0 62060 17860 135940 0 0 0 0 105 155 0 0 100 0 0 0 0 62092 17860 135940 0 0 0 0 105 134 0 0 100 0 0 0 0 62092 17860 135940 0 0 0 0 105 127 0 0 100 0 0 0 0 62092 17860 135940 0 0 0 0 106 133 0 0 100 0 0 0 0 62092 17860 135940 0 0 0 0 105 129 0 0 100 0 0 0 0 62092 17868 135940 0 0 0 52 2101 4081 0 4 95 1 0 0 0 62092 17868 135940 0 0 0 0 103 173 0 0 100 0 0 0 0 62060 17868 135940 0 0 0 0 103 129 0 0 100 0mpstatroot@arm:~# mpstat 1Linux 3.10.0 (arm) 03/25/15 _armv7l_ (1 CPU)20:02:04 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle20:02:05 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:06 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:07 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:08 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:09 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:10 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:11 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:12 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:13 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.0020:02:14 all 0.00 0.00 0.00 0.00 0.00 0.99 0.00 0.00 99.0120:02:15 all 0.00 0.00 0.00 0.00 0.00 0.99 0.00 0.00 99.0120:02:16 all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00sarroot@arm:~# sarLinux 3.10.0 (arm) 03/25/15 _armv7l_ (1 CPU)17:53:42 LINUX RESTART17:54:01 CPU %user %nice %system %iowait %steal %idle17:55:01 all 0.25 0.00 0.63 0.00 0.00 99.1217:56:01 all 0.07 0.00 0.47 0.00 0.00 99.4717:57:01 all 0.25 0.00 0.43 0.02 0.00 99.3017:58:01 all 0.20 0.00 0.47 0.03 0.00 99.3017:59:02 all 0.13 0.00 0.30 0.03 0.00 99.5318:00:01 all 0.08 0.00 0.36 0.02 0.00 99.5418:01:01 all 0.12 0.00 0.45 0.02 0.00 99.4All three utliities have similar results. Now for top..toptop - 19:50:39 up 2:47, 1 user, load average: 0.81, 0.77, 0.77Tasks: 50 total, 1 running, 49 sleeping, 0 stopped, 0 zombie%Cpu(s): 1.4 us, 0.8 sy, 0.0 ni, 97.3 id, 0.4 wa, 0.0 hi, 0.1 si, 0.0 stKiB Mem: 251692 total, 189540 used, 62152 free, 17724 buffersKiB Swap: 0 total, 0 used, 0 free, 135920 cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 5249 root 20 0 3100 1176 864 R 10.7 0.5 0:00.07 top 1 root 20 0 2104 708 612 S 0.0 0.3 0:01.16 init 2 root 20 0 0 0 0 S 0.0 0.0 0:00.01 kthreadd 3 root 20 0 0 0 0 S 0.0 0.0 0:00.05 ksoftirqd/0 5 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 kworker/0:0H 6 root 20 0 0 0 0 S 0.0 0.0 0:00.25 kworker/u2:0 7 root 20 0 0 0 0 S 0.0 0.0 0:00.01 rcu_preempt 8 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_bh 9 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_sched 10 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 khelper 11 root 20 0 0 0 0 S 0.0 0.0 0:00.00 kdevtmpfs 202 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 writeback 204 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 bioset 206 root 0 -20 0 0 0 S 0.0 0.0 0:00.00 kblockd 235 root 20 0 0 0 0 S 0.0 0.0 0:00.00 khubd Notice that the load average is [0.81, 0.77, 0.77]! Any idea to what's going on to cause such high load average?EDIT: This question isn't about what load average is.load average figures giving the number of jobs in the run queue (state R) or waiting for disk I/O (state D)How can there be state D processes if i/o is almost zero, and how are there so many jobs in the run queue? Is there a way to tell which jobs are on there? | Understanding high load average with vmstat, mpstat, sar, and top | linux;performance | null |
_codereview.150139 | I am trying to make file read and update operations thread safe and prevent race conditions in Python. Am I missing out something, or would this work in production?import osimport timefrom contextlib import contextmanagerimport errnocurrent_milli_time = lambda: int(round(time.time() * 1000))lock_retry_wait = 0.05 # in seconds@contextmanagerdef exclusive_file(filename, mod, lock_wait_timeout=3000): lockfile = filename + .lock wait_start = current_milli_time() while True: try: # acquire lock fd = os.open(lockfile, os.O_CREAT|os.O_EXCL) break except OSError as exception: if exception.errno != errno.EEXIST: raise else: t = current_milli_time() if (t - wait_start) > lock_wait_timeout: raise time.sleep(lock_retry_wait) with open(filename, mod) as f: yield f os.close(fd) os.unlink(lockfile)with exclusive_file(test.txt,a+) as f: previous_value = f.read() f.truncate() f.write(previous_value + str(time.time())) time.sleep(20) | Thread Safe File Operation | python;file;thread safety | null |
_codereview.101086 | I didn't write the login code yet.Mainstatic AccountLogin objAccountLogin = new AccountLogin();static AccountRemover objAccountRemover = new AccountRemover();static AccountCreator objAccountCreator = new AccountCreator();static Accounts objAccounts = new Accounts();public static void main(String[] args) { startDiary(); }public static void mainMenu(){ System.out.println(); System.out.println(Welcome to Diary!); System.out.println(1- New Account); System.out.println(2- Login To Your Account); System.out.println(3- Remove Account); System.out.println(4- Exit); System.out.println(); usersChoice();}public static void usersChoice(){ int choice = 0; while(true){ try{ Scanner scan = new Scanner(System.in); System.out.print(Choose an option: ); choice = scan.nextInt(); break; } catch(Exception e){ System.out.println(Invalid Input!\n); } } switch (choice){ case 1: choiceNewAccount(); case 2: choiceLogin(); case 3: choiceRemoveAccount(); case 4: exit(); break; default: System.out.println(Invalid Input!\n); usersChoice(); }}public static void startDiary(){ objAccounts.loadAccounts(); mainMenu();}public static void choiceNewAccount(){ objAccountCreator.createAccount(); mainMenu();}public static void choiceLogin(){ objAccountLogin.login(); mainMenu();}public static void choiceRemoveAccount(){ objAccountRemover.removeAccount(); mainMenu();} public static void exit(){ while(true){ try{ Scanner exit = new Scanner(System.in); System.out.print(Are you sure you want to exit? (y/n): ); char choice = exit.next().charAt(0); if(choice == 'y') System.exit(0); else if(choice == 'n') mainMenu(); else System.out.println(Invalid character!); } catch(Exception e){ System.out.println(Invalid character!); } } } Accountsprotected File usernamesFile = new File(D:Usernames.txt);protected File passwordsFile = new File(D:Passwords.txt);private static ArrayList<String> accounts_Usernames = new ArrayList<>();private static ArrayList<String> accounts_Passwords = new ArrayList<>(); protected void addToAccountsList(String username, String password){ addToAccounts(username,password); loadAccounts();}private void addToAccounts(String username,String password){ addToUsernames(username); addToPasswords(password);}private void addToUsernames(String username){ if(usernamesFile.exists()){ try (PrintWriter usernamesWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.usernamesFile, true)))) { usernamesWriter.println(username); usernamesWriter.flush(); } catch (IOException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); } } else System.err.println(File: Usernames Does Not Exist!); }private void addToPasswords(String password){ if(passwordsFile.exists()){ try (PrintWriter passwordsWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.passwordsFile, true)))) { passwordsWriter.println(password); passwordsWriter.flush(); } catch (IOException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); } } else System.err.println(File: Usernames Does Not Exist!); }protected void loadAccounts(){ loadUsernames(); loadPasswords();}private void loadUsernames(){ try (Scanner usernamesScanner = new Scanner(usernamesFile)) { while(usernamesScanner.hasNext()){ String username = usernamesScanner.next(); if(!accounts_Usernames.contains(username))accounts_Usernames.add(username); } } catch (FileNotFoundException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); }}private void loadPasswords(){ try (Scanner passwordsScanner = new Scanner(passwordsFile)) { while(passwordsScanner.hasNext()){ String password = passwordsScanner.next(); if(!accounts_Passwords.contains(password))accounts_Passwords.add(password); } } catch (FileNotFoundException ex) { Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex); }}protected ArrayList<String> getUsernamesList(){ return accounts_Usernames;}protected ArrayList<String> getPasswordsList(){ return accounts_Passwords;} AccountCreatorpublic void createAccount(){ Scanner scan = new Scanner(System.in); System.out.print(Enter Your Username: ); String username = scan.next(); if(!isValidUsername(username)) System.out.println(Username Already Exists!); else{ while(true){ System.out.print(Enter Your Password: ); String pass1 = scan.next(); System.out.print(Re-Enter Your Passowrd: ); String pass2 = scan.next(); if(!arePasswordsMatch(pass1,pass2)) System.out.println(Passowrds Don't Match!); else { addToAccountsList(username,pass1); createTheUsersFile(username); System.out.println(The Account Has Been Successfully Created!); break; } } }}private boolean isValidUsername(String username){ return getUsernamesList().stream().noneMatch((valid) -> (valid.equals(username)));}private boolean arePasswordsMatch(String pass1, String pass2){ return pass1.equals(pass2); }private boolean createTheUsersFile(String username){ File newUserFile = new File(D:+username+.txt); try { newUserFile.createNewFile(); } catch (IOException ex) { Logger.getLogger(AccountCreator.class.getName()).log(Level.SEVERE, null, ex); } return newUserFile.exists();}AccountRemoverpublic void removeAccount(){ try{ remove(); refresh(); System.out.println(Account Has Been Successfully Removed!); } catch(Exception e){ System.out.println(Could Not Remove Account!); } }public void remove(){ String accountName = canLogin(); removeFile(accountName); removeFromList(accountName); }public void removeFile(String accountName){ File deleteUsername = new File(D:+accountName+.txt); deleteUsername.delete(); }public void removeFromList(String accountName){ if(!accountName.equals(-1)) { for(int i = 0; i < getUsernamesList().size();i++) if(getUsernamesList().get(i).equals(accountName)){ getUsernamesList().remove(i); getPasswordsList().remove(i); break; } } else System.out.println(Can Not Erase Account!);}public void refresh(){ refreshUsernames(); refreshPasswords();}public void refreshUsernames(){ try (PrintWriter usernamesOverWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.usernamesFile)))){ getUsernamesList().stream().forEach((b) -> { usernamesOverWriter.println(b); }); usernamesOverWriter.flush(); } catch (IOException ex) { Logger.getLogger(AccountRemover.class.getName()).log(Level.SEVERE, null, ex); }}public void refreshPasswords(){ try (PrintWriter passwordsOverWriter = new PrintWriter(new BufferedWriter(new FileWriter(this.passwordsFile)))){ getPasswordsList().stream().forEach((b) -> { passwordsOverWriter.println(b); }); passwordsOverWriter.flush(); } catch (IOException ex) { Logger.getLogger(AccountRemover.class.getName()).log(Level.SEVERE, null, ex); }} Follow up: diary-application-with-accounts-v-2 | Diary applications with accounts | java | Let's start at the beginning...usersChoice() tends to call itself again and again and again, leaving stuff on the stack. I would suggest putting the whole choice thing inside a...while(true) {... do your stuff here}...as the System.exit() in exit() will end the program anyway. Also you are not closing your scanner. In one piece of code you used the try-catch-with-resources...try (Scanner usernamesScanner = new Scanner(usernamesFile)) {...stick with that.You are creating at least 3 scanners, might be a good idea to see if you can move that read something from file or console code into its own method. loadUsernames() and loadPasswords() are the same code, and they only differ in where the text is stored, so you can merge that into one method. Same with the addToUsernames() and addToPasswords() - you even forget to change the error message when copy and pasting. Copy and paste, especially your own code, is not a good idea: If you need to change the code, you will very likely need to remember two places to change it. Merge them into one method by identifying which parts change.You are using a method canLogin(), but never declare it. Also, the name implies that the answer is true or false, but it seems to return the loginName. Method names should intuitively make clear what they will do, this one absolutely doesn't. Your methods tend to be a bit long. For example, the exit-method effectively does three things:Read from consoleCheck if the text is somethingExit, if yesYou could write that clearer by removing at least one of this things into its own method, for example...public void tryExit() { String userConfirmedExit = askFromConsole(Are you sure you want to exit? (y/n)); // implement that method if (y.equals(userConfirmedExit)) { System.exit(0); } else if (!n.equals(userConfirmedExit)) { System.out.println(Invalid character!) } // in all other cases, simply return and the loop (see above) will bring back the menu}The whole code is still very static-based. I would try to remove every static method besides the main one. |
_vi.4379 | How commonly is Vim used in professional software development today, inside a company? By Vim, I mean the actual Vim editor, not a Vim/vi plugin/setting or usage within Eclipse.Has Vim hindered your daily programming work when you had to interact with other tools or frameworks?Has Vim hindered your social interaction with other team members in some way?How did your colleagues and bosses respond in general, that you wanted to use an editor which forces you to configure it, instead of an ready-to-use IDE?(Sure, every IDE needs to be configured for the project. I just think Vim requires more configuration before being able to use it effectively. I assume this wouldn't create a good impression at work.)Have you pair-programmed with non-Vim users? I assume that people are already familiar with Vim and don't start configuring Vim at work. | Is vim suitable for professional development inside a company? | vimrc;ide | This an odd question, and would be equally odd if asked of any editor IMHO.No, vim (nor any other vi-variant) has ever hindered any my work. I've only ever been hindered when not using it.I'm not sure how vim would hinder my social interaction with other team members. It's not like vim gives you bad breath.My colleagues and bosses couldn't care less what editor I use. About 70% of them use vim/vi too, a handful use emacs, most of the GUI developers use Eclipse, and one or two might use something else like jEdit or Notepad++. They don't care what brand of pen I take notes with either.Also, I don't see how vim forces you to configure it. Out of the box, it works pretty much like any version of vi ever has. Yeah, you end up tweaking it to your liking over time, but probably less than any IDE.I haven't done any official pair programming, although two of use sometimes do work together to solve a particularly thorny problem. But then again, I don't see that the choice of editor matters much (everyone here except perhaps some of the GUI developers at least know how to use vim/vi, even if it's not their editor of choice). |
_codereview.104446 | Currently, the code will generate a range of natural numbers from 1 to N and store it in a list. Then the program will iterate through that list, marking each multiple of a prime as 0 and storing each prime in a secondary list.This is a translation of a TI-Basic program, shown here, so the same description still applies.Here's an animation:One of the main optimizations that I want to see implemented would be the actual removal of prime multiples from the list instead of simply setting them to 0. As it is currently written, this would be a challenge to perform without adding in another if statement. Any suggestions would be helpful.def sieve(end): prime_list = [] sieve_list = list(range(end+1)) for each_number in range(2,end+1): if sieve_list[each_number]: prime_list.append(each_number) for every_multiple_of_the_prime in range(each_number*2, end+1, each_number): sieve_list[every_multiple_of_the_prime] = 0 return prime_listHere's a link to PythonTutor, which will visualize the code in operation. | Sieve of Eratosthenes in Python 3 | python;performance;python 3.x;primes;sieve of eratosthenes | Just a couple things:sieve_list = list(range(end+1))You don't actually need your list to be [0, 1, 2, ... ]. You just need an indicator of whether or not it's true or false. So it's simpler just to start with:sieve_list = [True] * (end + 1)That'll likely perform better as well. When you're iterating over multiples of primes, you're using:range(each_number*2, end+1, each_number)But we can do better than each_number*2, we can start at each_number*each_number. Every multiple of that prime between it and its square will already have been marked composite (because it will have a factor smaller than each_number). That'll save a steadily larger increment of time each iteration. As an optimization, we know up front that 2 and 3 are primes. So we can start our iteration at 5 and ensure that we only consider each_number to not be multiples of 2 or 3. That is, alternate incrementing by 4 and 2. We can write this function:def candidate_range(n): cur = 5 incr = 2 while cur < n+1: yield cur cur += incr incr ^= 6 # or incr = 6-incr, or howeverFull solution:def sieve(end): prime_list = [2, 3] sieve_list = [True] * (end+1) for each_number in candidate_range(end): if sieve_list[each_number]: prime_list.append(each_number) for multiple in range(each_number*each_number, end+1, each_number): sieve_list[multiple] = False return prime_listImpact of various changes with end at 1 million, run 10 times:initial solution 6.34s[True] * n 3.64s (!!)Square over double 3.01scandidate_range 2.46sAlso, I would consider every_multiple_of_the_prime as an unnecessary long variable name, but YMMV. |
_webmaster.55961 | We are doing a competitive analysis of our competition, but we can't figure out how to find out the website's hosting provider, if it's protected with CloudFlare. Is it possible? | How to find out the hosting provider of a website protected with CloudFlare? | web hosting;cloudflare | null |
_unix.117168 | Has anyone else seen this behavior?I created a simple Ruby script for giggles to see how fast it would count up on a couple machines I have. Here's the source: for n in 1...1000000 do puts #{n}endI ran the script using time ruby ./rubytest.rbOn my not-newest-generation MacBook, running this locally took about 15 seconds.If I SSH from work to my MacBook and run it over that SSH session (over the Internet), it takes nearly 55 seconds.If I use ssh localhost on my MacBook, from the local console, running the script takes about 10 seconds.Questions: Do Ruby scripts somehow get blocked when dumping output to a console, so it is slowed down when pumping data to a remote terminal? Does SSH compress a connection, so that when I SSH'd in locally the script was faster because it was compressing the display of data fast enough that even with the compression overhead the script could run faster because it was somehow acknowledging the output faster? | Time running a Ruby script is different locally than over SSH | ssh;time;ruby | It's because you're echoing all the numbers out to the screen via the puts. These then have to be sent over the SSH connection which extends the amount of time the scripts takes to run. The output is also buffered locally but the effects aren't as noticeable.You can confirm this by dumping all the output to a file instead.Exampleslocal on laptop to screen$ time ruby r.rbreal 0m19.474suser 0m3.236ssys 0m3.207slocal on laptop to file$ time ruby r.rb >& rb_local.txtreal 0m0.785suser 0m0.760ssys 0m0.020sSSH to desktop to screen$ time ruby r.rbreal 0m18.026suser 0m4.118ssys 0m3.815sSSH to desktop to file$ time ruby r.rb >& rb_remote.txtreal 0m3.942suser 0m3.036ssys 0m0.741sWhen writing scripts such as this its generally a good idea to dump the contents to a file instead and then use a tool such as tail to watch the file periodically.NOTE: The notation >& will redirect both STDERR and STDOUT to the .txt files. However the output from time will still get displayed to the console. This notation is equivalent to cmd > some_file.txt 2>&1. |
_unix.77290 | I am trying to installing on Centos java from Oracle. Following are my steps. yum install /usr/local/jdk-7u3-linux-x64.rpmalternatives --install /usr/bin/java java /usr/java/latest/jre/bin/java 20000alternatives --install /usr/bin/javaws javaws /usr/java/latest/jre/bin/javaws 20000alternatives --install /usr/bin/javac javac /usr/java/latest/bin/javac 20000alternatives --config java I pick the latest version here.The problem now only my java is pointing to the new version wheras the javac is not pointing to it below is how I trace for java and javac.Java ls -la /usr/bin/java lrwxrwxrwx. 1 root root 22 May 22 13:09 /usr/bin/java -> /etc/alternatives/java ls -la /etc/alternatives/java lrwxrwxrwx. 1 root root 25 May 22 13:09 /etc/alternatives/java -> /usr/java/latest/bin/javaJavac ls -la /usr/bin/javac lrwxrwxrwx. 1 root root 23 May 22 11:37 /usr/bin/javac -> /etc/alternatives/javac ls -la /etc/alternatives/javac lrwxrwxrwx. 1 root root 48 May 22 11:37 /etc/alternatives/javac -> /usr/lib/jvm/java-1.7.0-openjdk.x86_64/bin/javac Any solution to overcome this? I have tried previously on other machines on Centos 6.3 works fines. | Alternatives not working well for Java installation on Centos 6.4 | centos;java | See 'air-dex' example on this post: https://askubuntu.com/questions/159575/how-do-i-make-java-default-to-a-manually-installed-jre-jdk . Note: sometimes people install Java JDK's into '/usr/lib/jvm', and as you can see in the output on my blog post, the system came with default JVMs in this location, but personally I don't recommend that for a JDK. Maybe I would choose '/usr/lib/jvm' if it was a JRE I was installing. If you wanted an alternative location for JDKs and JREs, I would choose either: 1. /usr/java/ 2. /opt/java/If I were comparing to windows, I might say:JDKs: /usr/java = C:\JavaJREs: /usr/lib/jvm = C:\Program Files\JavaAlt: /opt/java = E:\Java |
_cstheory.668 | Rice's theorem states that every nontrivial property of the set recognized by some Turing machine is undecidable.I am looking for complexity-theoretic Rice-type theorem that tells us which nontrivial properties of NP sets are intractable. | Is there a complexity theory analogue of Rice's theorem in computability theory? | cc.complexity theory;computability;np | Proving such a complexity theoretic version of Rice's Theorem was a motivation for me to study program obfuscation. Rice's theorem says in essence, that it is hard to understand the functions that programs compute, given the program. However, the reason these problems are undecideable is that they are infinitary. Even on one input, a program may never halt, and we need to consider whatthe program does on infinitely many inputs.A finitary version of Rice's theorem would fix the input size and running time of a program,and say that the program is hard to understand. Once you've fixed these, you might as wellview the program as a Boolean circuit. What properties of the function computed by a Boolean circuit are hard to compute? One example is ``not always 0'', which is the NP-completeSatisfiability problems. But unlike Rice's Theorem, there are some properties that arenon-trivial but easy, even without understanding the circuit. We can always know that:the function computed by a circuit has a bounded circuit complexity (the size of the circuit). Also, we can always evaluate the circuit on inputs of our choice. So say a property of $f_C$ is easy with Black-box access if it can be compute,din probabilistic polynomial time by an algorithm that gets as input $n$, a bound on $|C|$ and oracle access to $f_C$. For example, satisfiability is not easy with black-box access, because we could imagine a circuit of size $n$ that only produces answer 1 on arandomly chosen input $x$. No black box algorithm could distinguish such a circuit from one that always returned 0, since the probability of querying the oracle on $x$ is exponentially small. On the other hand, the property $f(0..0)=1$ is black-box easy.The question is: are there any properties of $f_C$ that are decideable in probabilistic polynomial-time that are not easy with Black-box access?While this question is open as far as I know, our intended approach was ruled out. We hadhoped to prove this by showing that cryptographically secure program obfuscation was possible. However, Boaz proved the opposite: that it was impossible. This implicitly shows that black-box access to circuits is more limited than full access to the circuit description, but the proof is non-constructive, so I can't name any property as abovethat is easy given the circuit description but not with black-box access. It is interesting (at least to me) if such a property could be reverse engineered from our paper.Here is the reference:Boaz Barak, Oded Goldreich, Russell Impagliazzo, Steven Rudich, Amit Sahai, Salil P. Vadhan, Ke Yang: On the (Im)possibility of Obfuscating Programs. CRYPTO 2001:1-18 |
_unix.237082 | I have a bunch of tar files in my machine which I want to transfer to an external hard drive (EHD); they where created preserving permissions (using the -p flag). I plan to use rsync to copy them to the EHD, but I wonder if it's necessary to transfer them in the so called archive mode (using the -a flag), since, as I understand, the main purpose of this mode is to preserve permissions, ownerships, etc. | Is it necessary to transfer `tar` files through `rsync` in archive mode? | rsync;backup;tar | null |
_webapps.98049 | If I post a photo to Facebook and adjust the date so as to indicate that it is in the past, will this photo show up in my friends' timelines as any other recently posted photo would? Essentially what I want to do is sneak in a photo or two from a while back just to add to my profile, but not have it show up in my friends' feeds, and I was wonder if changing the date would accomplish this. If it doesn't, is there any way to make such a post? | Facebook: visibility of posts with old dates | facebook | If you want add a photo and do not want to show it to your friends feed, change the audience settings. Choose Only Me option in audience selector and post. After sometime (say one day) you can change the audience and it will not show friends newsfeed until some activity will not happen on the post.When we post a photo there is no option to change the date, but once it posted we can use edit button and change the date, description and location. But it will show in edited section and anyone can see what changes have made. |
_unix.378887 | I did some remote work on a machine that I have infrequent access to and, at the end of my session, I issued sudo halt to terminate the connection and shut down the machine. Unfortunately, now I don't know whether or not the commands I used in the session were written to the .bash_history file. According to man halt it sends all running processes a SIGTERM and then a SIGKILL (I presume that it only does this if the process does not die in a timely manner):The halt and reboot utilities flush the file system cache to disk, send all running processes a SIGTERM (and subsequently a SIGKILL) and, respectively, halt or restart the system.I tested this out on my personal machine by first sending SIGTERM to bash, to which bash did not seem to respond. I then sent a SIGKILL, which obviously forced bash to die. I then checked the .bash_history file to see if anything was written there from my session, and nothing was. This makes sense to me since, according to my understanding, SIGTERM can be ignored by a process and it may perform its shutdown procedures as it desires since it can interpret how to respond to this signal. However, again according to my own understanding, SIGKILL may not be ignored and does not grant the process any time to perform clean-up or other dying rites.According to this test and the conclusions I came to from this test, it seems that it is quite unlikely that my remote session was saved when I issued sudo halt on the remote host. Is there some way I could be wrong about this and that my remote session was saved to .bash_history? | Does `sudo halt' give bash a chance to write its history? | bash;command history;shutdown | ssh killed by SIGTERMssh closes its pseudo-terminal (pty) master devicepty sends SIGHUP to bash.The shell exits by default upon receipt of a SIGHUP.https://stackoverflow.com/questions/5527405/where-is-sighup-from-sshd-forks-a-child-to-create-a-new-session-kill-this-chi |
_webmaster.47623 | For example, is there a chance that Chrome 25 will render an element differently than Chrome 26? If the answer is no, a link to a resource that explains why there are no differences in redering between versions would be ideal.EditThanks for the feedback. Everyone seems to indicate that, yes, it's possible that something could change in the redering engine. In my original question, I asked for a resource if the answer was no. Now that the answer seems to be yes can anybody point to a specific redering difference between to versions of non-IE browsers?For example, Chrome 23 renders X as inline, while Chrome 24 reders x as block. | Is it necessary to browser QA different versions of non-IE Browsers? | browsers;testing | Yes there is but there is no way for you to be exhaustive. The best bet is to check the last few versions of each browser with an emphasis on what your visitors use. Even one version of a browser can render slightly differently on different platforms. I have seen Firefox and Safari recently behave differently on Windows and Mac and Chrome differently between Linux and Windows.Chrome is constantly changing and, while not every version makes it on user's machines, there are literally hundreds of versions out there. The only way to know the differences would be to look at the Change Lists but this is a monumental task.Chrome has just changed its rendering engine to Blink which is a fork of WebKit. It will take time before most people transition to it but from this point on you have to expect that differences in rendering between browsers will increase as Safari and Chrome will no longer share a rendering engine. Opera will shift from WebKit to Blink later but that will only change the mix and not add variety.Plenty of Linux distributions build their own Chromium which have a different release schedule which makes for plenty more potential versions. The good news is that actual differences are usually small, so it is better to check various major versions than several continuous minor ones. |
_reverseengineering.15086 | I'm testing a malware sample :hxxps://www.virustotal.com/en/file/55f4cc0f9258efc270aa5e6a3b7acde29962fe64b40c2eb36ef08a7a1369a5bd/analysis/This is a malicious executable file. When executed in Windows XP, it exhibits its behavior (ransomware). But the same file when executed in windows 7, it does't show its actual behavior.Need your help to identify that specific condition in the which makes the malware run only in a specific operating system. | Need help in understanding the code of a Malicious file | malware;static analysis | null |
_cs.55485 | Can someone give me the best search algorithm in a max heap?In particular simply implemented as an array. I knew it has complexity of $O(N)$ but it can be done better. For example, if $A[i] < \mathrm{key}$ it's useless to search in the sub-tree with that root in the $i$th position. | Best search in Heap Array | algorithms;data structures;search algorithms;arrays;heaps | null |
_codereview.67334 | This is an XML Writer in C++. It doesn't do much but the basics, and I've tested it, so it should hold up well enough. I hope in the near future, I can bring you an XML Reader.I kinda built the function names after the Visual Basic names for their standard XML Writer (Microsoft's anyways), so if you see the similarities, that's where I got the names from. As for the actual function internals, I don't know if they are the same or not.XmlWriter.h:#ifndef XmlWriter_H#define XmlWriter_H#include <fstream>#include <iostream>#include <string>#include <vector>class XmlWriter {public: bool open(const std::string); void close(); bool exists(const std::string); void writeOpenTag(const std::string); void writeCloseTag(); void writeStartElementTag(const std::string); void writeEndElementTag(); void writeAttribute(const std::string); void writeString(const std::string);private: std::ofstream outFile; int indent; int openTags; int openElements; std::vector<std::string> tempOpenTag; std::vector<std::string> tempElementTag;};#endifXmlWriter.cpp:#include XmlWriter.h//=============================================================================//== Function Name : XmlWriter::exists//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== fileName const std::string The name of the file that is in use//==//== Description//== --------------------------------------------------------------------------//== This function is used to check if the XML file exists//=============================================================================bool XmlWriter::exists(const std::string fileName){ std::fstream checkFile(fileName); return checkFile.is_open();}//=============================================================================//== Function Name : XmlWriter::open//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== strFile const std::string The name of the file that the user passes//== in the code//==//== Description//== --------------------------------------------------------------------------//== This function is used to open the XML file, first checking to see if it//== exists first//=============================================================================bool XmlWriter::open(const std::string strFile) { if (exists(strFile)){ std::cout << Error: File alread exists.\n; return false; } outFile.open(strFile); if (outFile.is_open()) { std::cout << File created successfully.\n; outFile << <!--XML Document-->\n; outFile << <?xml version='1.0' encoding='us-ascii'>\n; indent = 0; openTags = 0; openElements = 0; return true; } return false;}//=============================================================================//== Function Name : XmlWriter::close//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== N/a N/a N/a//==//== Description//== --------------------------------------------------------------------------//== This function is used to close the XML file//=============================================================================void XmlWriter::close() { if (outFile.is_open()) { outFile.close(); } else { std::cout << File already closed.\n; }}//=============================================================================//== Function Name : XmlWriter::writeOpenTag//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== openTag const std::string The name of the tag being created//==//== Description//== --------------------------------------------------------------------------//== This function creates a new tag, checking that the file is open, and saves//== the tag name in a vector to keep track of it//=============================================================================void XmlWriter::writeOpenTag(const std::string openTag) { if (outFile.is_open()) { for (int i = 0; i < indent; i++) { outFile << \t; } tempOpenTag.resize(openTags + 1); outFile << < << openTag << >\n; tempOpenTag[openTags] = openTag; indent += 1; openTags += 1; } else { std::cout << File is closed. Unable to write to file.\n; }}//=============================================================================//== Function Name : XmlWriter::writeCloseTag//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== N/a N/a N/a//==//== Description//== --------------------------------------------------------------------------//== This function closes the currently open tag//=============================================================================void XmlWriter::writeCloseTag() { if (outFile.is_open()) { indent -= 1; for (int i = 0; i < indent; i++) { outFile << \t; } outFile << </ << tempOpenTag[openTags - 1] << >\n; tempOpenTag.resize(openTags - 1); openTags -= 1; } else { std::cout << File is closed. Unable to write to file.\n; }}//=============================================================================//== Function Name : XmlWriter::writeStartElementTag//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== elementTag const std::string The name of the element being created//==//== Description//== --------------------------------------------------------------------------//== This function creates a new element tag and saves the name to a vector//=============================================================================void XmlWriter::writeStartElementTag(const std::string elementTag) { if (outFile.is_open()) { for (int i = 0; i < indent; i++) { outFile << \t; } tempElementTag.resize(openElements + 1); tempElementTag[openElements] = elementTag; openElements += 1; outFile << < << elementTag; } else { std::cout << File is closed. Unable to write to file.\n; }}//=============================================================================//== Function Name : XmlWriter::writeEndElementTag//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== N/a N/a N/a//==//== Description//== --------------------------------------------------------------------------//== This function closed the currently opened element tag//=============================================================================void XmlWriter::writeEndElementTag() { if (outFile.is_open()) { outFile << </ << tempElementTag[openElements - 1] << >\n; tempElementTag.resize(openElements - 1); openElements -= 1; } else { std::cout << File is closed. Unable to write to file.\n; }}//=============================================================================//== Function Name : XmlWriter::writeAttribute//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== outAttribute const std::string The attribute being written out//==//== Description//== --------------------------------------------------------------------------//== This function writes an attribute (if any) after the element tag is first//== opened and before the output for the element is written//=============================================================================void XmlWriter::writeAttribute(const std::string outAttribute) { if (outFile.is_open()) { outFile << << outAttribute; } else { std::cout << File is closed. Unable to write to file.\n; }}//=============================================================================//== Function Name : XmlWriter::writeString//==//== Perameters//== Name Type Description//== ---------- ----------- --------------------//== writeString const std::string The string to be written to the element//==//== Description//== --------------------------------------------------------------------------//=============================================================================void XmlWriter::writeString(const std::string outString) { if (outFile.is_open()) { outFile << > << outString; } else { std::cout << File is closed. Unable to write to file.\n; }}main.cpp:#include XmlWriter.hint main() { XmlWriter xml; if (xml.open(C:\\Users\\UserNameHere\\Desktop\\test.xml)) { xml.writeOpenTag(testTag); xml.writeStartElementTag(testEle1); xml.writeString(This is my first tag string!); xml.writeEndElementTag(); xml.writeOpenTag(testTag2); xml.writeStartElementTag(testEle2); xml.writeAttribute(testAtt=\TestAttribute\); xml.writeString(I sometimes amaze myself.); xml.writeEndElementTag(); xml.writeOpenTag(testTag3); xml.writeStartElementTag(testEle3); xml.writeAttribute(testAtt2=\TestAttrib2\); xml.writeString(Though i'm sure someone can make something even better); xml.writeEndElementTag(); xml.writeCloseTag(); xml.writeCloseTag(); xml.writeCloseTag(); xml.close(); std::cout << Success!\n; } else { std::cout << Error opening file.\n; } system(pause); return 0;} | Basic XML Writer in C++ | c++;xml | I'm going to second guess a bunch of decisions that you made. I don't know that you made them all incorrectly, but I think that alternatives deserve consideration.std::ofstream outFile;Why not make this an ostream instead? Then you could output to things other than just a file. An ofstream is a limiting choice here. My quick read is that the best choice would be to have both an XmlWriter and an XmlWriterFile which extends it. int indent;I'd call this current_indent for readability. Otherwise, one might guess that it reflects the overall indent rather than a value that changes over time. int openTags;int openElements;If I had these variables, I'd call these something like openTagCount and openElementCount respectively. When I see a plural variable, I expect it to contain multiple things. That is, I expect plurals to indicate collections. These don't hold the open tags and elements, just the counts. But I actually wouldn't have these variables. More in a moment. std::vector<std::string> tempOpenTag;std::vector<std::string> tempElementTag;OK, these two vectors (along with the count variables) are used to implement stacks. Here's the thing though, why not just make them std::stack? You can even have the stack implementation use std::vector as the storage medium. That way, you don't have to worry about managing the stack variables as you do here. void XmlWriter::writeCloseTag() { if (outFile.is_open()) {This seems unlikely enough to not be checked. You already check that the file opens in the open method. It shouldn't close itself arbitrarily often enough that you would need to check it in each write function. indent -= 1;It's more common to just say indent--; rather than to specify a decrement of 1. for (int i = 0; i < indent; i++) { outFile << \t; }Why not just outFile << std::string(indent, '\t');That saves you having to do indent calls to your stream. You also may want to make the indent character (\t here) a constructor option. outFile << </ << tempOpenTag[openTags - 1] << >\n; tempOpenTag.resize(openTags - 1); openTags -= 1;You shouldn't resize a std::vector by 1. It's an expensive operation, so if you're going to do it, do it up large. A typical expansion is more like 50% or 100%. It's not evident that this program would need to make a vector smaller at all. Either the stack is going to grow again or it will end and the entire data structure can be released. You do three things to implement a pop operation on your stack. If openTags was a stack variable, you could just say outFile << </ << openTags.top() << >\n;openTags.pop();The pop() will trigger any resizes that may be necessary. You don't have to manage the number of open tags yourself. } else { std::cout << File is closed. Unable to write to file.\n; }}This isn't necessary if you don't do the excess is_open check. What you should be doing is to check if writeCloseTag is called when the stack is empty. If you use the stack variable, this looks something like if ( openTags.empty() ) { // do something to handle this special case // maybe write to STDERR cerr << No tag to close. << endl; return; // or exit or throw an exception}You can put that code at the beginning of the function. You should also consider what should happen if writeCloseTag and writeEndElementTag are called in the wrong order. I don't see how your code would even notice. Perhaps open tags and elements should share the same stack rather than having two different stacks. Rather than storing them as strings, you could store them as objects of classes which extend the same class. That way you could know what is supposed to come next. What would happen if writeString were called twice in a row? Consider adding logic to auto-close the element only if one is open rather than every time writeString is called. It should also check if it is currently in a context where a string can exist. Check if an element tag is open before adding an attribute to it. |
_scicomp.5023 | I have been trying to simulate a simple problem of taking about 100-1000 Ar molecules in a NVE (fixed vol, energy) system with equal speed but randomized velocity, and evolving them to obtain a Maxwellian speed distribution. I am choosing a Lennard Jones pair potential with no cutoff (despite being computationally expensive), periodic boundary conditions, and a varying integration time step to keep numerical error on energy to below 2%. I observe that my system reaches Maxwellian-like speed distribution (visually looks like a good Gaussian) from the initial rather uniform speed distribution. But very soon after some (about 10 in 100) particles accelerate to very large speeds even if my total energy is being held constant (to within 2% of initial energy) skewing the distribution to one side.I have tried to vary the no. of particles, increased temperature to allow re-equilibration of what appears like a growing fluctuation but can't make this effect go away. I am puzzled because I am managing to keep total energy with a 2% bound. Has anyone else has observed such long-time behavior in simple MD simulations, and/or is it well-known behavior? I am using the velocity Verlet scheme. I am using a well-scaled system (i.e., not trying to code actual atomic dimensions) and using a reasonable well distributed initial condition. | NVE MD simulation of inert gas: Problem maintaining equilibrium | molecular dynamics | Did you check the centre-of-mass velocity of your particles, i.e. did you set it to zero at the beginning of your simulation? The centre-of-mass velocity should be preserved throughout the simulation, and should be zero to get correct temperatures (see Flying Ice Cube). |
_webmaster.45258 | I have uploaded my sitemap to the server root folder. Do I need to submit it to Google Search Console (formerly Webmaster Tools)? | Need I submit sitemap to Google Search Console (Webmaster Tools)? | seo;google search console;sitemap | null |
_webmaster.91339 | How can pageviews differ very much for 2 sites that have nearly the same global ranking in Alexa?I have nearly the same global ranking but my pageviews are 1/50th of my comparison. What is it in the measure that accounts for the unexpected proximity in global ranking when pageviews differ by factor 50?The data is:Site 1: My site. Global ranking 105 000. Local ranking 10 000 in India. My google analytics reports that I have abt 100 daily visitors and abt 800 daily pageviews. Site 2, the comparison, has global ranking 98 000 in Alexa but with 7000 daily visitors and 50 000 daily pageviews. Local ranking 51 in Tanzania. How can the global rank not differ that much when pageviews and visitors differ that much? | Alexa ranking and the pageview measure | alexa | Alexa rank is measuring the rank, according to the number of people visited your website and who have the Alexa toolbar (or any other SEO toolbar with Alexa rank tracker) installed. And who has such toolbars nowadays? mainly SEOs and webmasters. If your targeted audience isn't one of them, then your Alexa rank will be low, but visits high |
_cs.28310 | Given a connected graph $G$ and a vertex $v$, is it polynomially solvable to find a maximal cardinality set of edges incident to $v$, which deletion (still) leaves vertex $v$ to be connected with all the other vertices in $G$? | Preserving connectivity from a vertex by edges deletion | algorithms;complexity theory;time complexity;graph algorithms | null |
_cogsci.4986 | It seems that researchers agree that physical exercise increases cognitive abilities. This seems to work universally for all ages: children, adults and old people. It is suggested that everyone should exercise for half an hour at least 3 times a week. I'm wondering if there are any studies which try to find dependencies between the amount of training and the effect of it on cognitive abilities? | What is the optimal exercise regime for improving cognitive functioning? | intelligence;performance;brain training;exercise | null |
_webmaster.46866 | I find the W3C's official Offline Web Applications specification to be rather vague about how the cache manifest interacts with headers such as ETag, Expires, or Pragma on cached assets. I know that the manifest should be checked with each request so that the browser knows when to check the other assets for updates. But because the specification doesn't define how the cache manifest interacts with normal cache instructions, I can't predict precisely how the browser will react.Will assets with a future expiration date be refreshed (no matter the cache headers) when the cache manifest is updated? Or, will those assets obey the normal caching rules?Which caching mechanism, HTTP cache versus cache manifest, will take precedence, and when? | How do Expires headers and cache manifest rules work together? | html5;cache;http headers | null |
_unix.207546 | I am trying to un-tar into a different directory using thistar xvf BACKUP.tar -C testBut I am getting the following errorsFile -C not present in the archive.File test not present in the archive.Using tar xv -C test -f BACKUP.tarI get the following errortar: /dev/rmt0: A file or directory in the path name does not exist.I do have a test directory and the file BACKUP.tar in the pwd that I am running the tar command inStill the same errortar -xvf BACKUP.tar -C testFile -C not present in the archive.File test not present in the archive.And tar --versiongives this errortar: Not a recognized flag: -Usage: tar -{c|r|t|u|x} [ -BdDEFhilmopRUsvwZ ] [ -Number ] [ -f TarFil e ] [ -b Blocks ] [ -S [ Feet ] | [ Feet@Density ] | [ Blocksb ] ] [ -L InputList ] [-X ExcludeFile] [ -N Blocks ] [ -C Directory ] File ...Usage: tar {c|r|t|u|x} [ bBdDEfFhilLXmNopRsSUvwZ[0-9] ] ] [ Blocks ] [ TarFile ] [ InputList ] [ ExcludeFile ] [ [ Feet ] | [ Feet@Density ] | [ Blocksb ] ] [-C Directory ] File ... | tar with -C not working | linux;tar | null |
_codereview.4922 | I'm looking to improve this class - any suggestions? It checks for empty, name, email, and password.The regex for email is very simple. A very lengthy article from the Linux Journal for improving upon this is here. The character set for password I borrowed from the NASA signup page. For name I allow letters, periods, and dashes. Testing for empty was developed with in this SO Postclass check { static function empty_user($a) { return (int)!in_array('',$a,TRUE); } static function name($a) { return preg_match('/^[a-zA-Z-\.]{1,40}$/',$a); } static function email($a) { return preg_match('/^[a-zA-Z0-9._s-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/',$a); } static function pass($a) { return preg_match('/^[a-zA-Z0-9!@#$%^&*]{6,20}$/',$a); } } | class design improvement - user validation | php | null |
_codereview.33369 | I was just wondering if this is a good example, following good practices, of a C program for launching an interpreted script from a native binary executable. Here the interpreter is Perl and the script an implementation of something analogous to du --apparent-size, but the idea is general.Also, is this code secure against potentially hostile users, at least if Perl is the interpreter (for instance, in a suid or sgid program)?#include <unistd.h>#include <stdio.h>#include <string.h>#include <errno.h>int main(int argc, char** argv){ char* command[argc+3]; command[0] = /usr/bin/perl; command[1] = -W; command[2] = -T; command[3] = /home/demetri/bin/awklikeperl.pl; for (int i = 0; i < argc; i++) { command[i+4] = argv[i+1]; } execv(command[0], command); int error = errno; fprintf(stderr, Failed to exec: %s\n, strerror(error)); if (error == ENOENT) { return(127); } else { return(126); }} | Launching an interpreted script | c;security;perl;unix | No it is not safe:Classic off-by-one error. You reserve space for 3 additional entries with command[argc+3] but you add 4. argv[i+1] and command[i+4] will be out of bounds on the last iteration (last valid index is argv[argc-1] and command[argc+2] respectively)execv expects a NULL terminated array of NULL terminated strings. So the last entry in commands needs to be NULL (otherwise how would execv know how many arguments to pass when starting the process?). |
_hardwarecs.7306 | I'm looking for a motherboard for a pfSense-based firewall with low power consumption (about 10 watts) and 3 LAN ports. Looking for a solution I found these motherboards: Alix 2d13 and Apu2c4 but I'm more inclined to apu2c4 because it should have gigabit LAN ports. What's the best for you?If you know other motherboards that meet my requirements please propose them as well. | Advice for low power consumption motherboard for pfSense firewall with almost 3 lan (Alix 2d13, Apu2c4 or others) | motherboard;firewall;pfsense | null |
_webmaster.101682 | I search certain keywords in desktop google search and mobile version of my website shows up, vise versa.I use some methods to solve this problem:use <link rel=alternate> and <link rel=canonical> to map desktop and mobile version web page respectively.use 301 redirect instead of 302 redirect when desktop webpage url redirect to mobile webpage url, vise versa.Are these correct methods to solve this problem? Are there any better idea? Thanks. | Mobile version of a website showing up on my desktop google search | google search;301 redirect;302 redirect;rel canonical;rel alternate | null |
_unix.206296 | I have got following simple shell script, in which I am trying to send STDERR & STDOUT to both screen and log it in a file(test.log). Also, while exiting I am trying to exit with appropriate exit codes.In this code, I would expect it to echo first message (within the block) and exit. But, it is echoing both the statements and always exit with 0.$ cat test.sh#!/bin/kshn_exitstatus=0{ n_exitstatus=1 echo Inside block : $n_exitstatus exit $n_exitstatus} 2>&1 | tee -a test.logecho Before last exit : $n_exitstatusexit $n_exitstatus$ sh test.shInside block : 1Before last exit : 0$ echo $?0How to amend this script to exit just after echo'ing first statement (to be logged in both screen and file) ? | Shell script exit code and logging | linux;shell;logs;exit | null |
_codereview.93344 | I am new to Node.js and Socket.io. I implemented a realtime chat service that has a chatroom feature. When the actual product is launched, there will be at least 200 concurrent users with 50 groups of 4 people. I would appreciate any advice on its performance and any recommendations. Server (remote server)var express = require('express');var app = express();var http = require('http').Server(app);var io = require('socket.io')(http);app.use(express.static(__dirname + '/'));//setup IO io.on('connection', function(socket){ console.log(A user is connected); var notice = {'content' : 'Hello World'}; socket.emit(notice, notice); //listen for reply socket.on(reply,function(data){ //extract group id, make sure the msg is sent to the particular group var groupid = data.group; var groupname = groupid + chat; socket.emit(groupname, data); console.log(got msg); //save the data into mongo db }); socket.on('disconnect', function(){ console.log(A user is disconnected); });});//Open serverhttp.listen(3000, function(){ console.log('listening on *:3000');});Client<!DOCTYPE html><html lang=en><head> <meta charset=utf-8> <title>WebSockets Demo</title></head><body> <div id=page-wrapper> <h1>WebSockets Test</h1> <p>Entry</p> <input id=entry type=text> <input id=button type=submit value=Enter> <div id=msg> </div> </div> <script src=//code.jquery.com/jquery-1.11.3.min.js></script> <script src=https://cdn.socket.io/socket.io-1.3.5.js></script> <script> $(function(){ var groupid = 2; //this groupid will change in the actual app. Right now is hardcoded. At tun time, this roupid is passed from php. var socket = io(http://104.236.19.119:3000); socket.on('connect',function(){ window.alert(You are connected.); }); $('#button').on('click',function(){ var entry = $(#entry).val(); var reply_msg = {content : entry, group:groupid}; socket.emit('reply',reply_msg); $(#entry).val(); }); var groupname = groupid + chat; //got the msg and append to chat window socket.on( groupname , function(data){ var new_msg = $(<p> + data.content + </p>); $('#msg').append(new_msg); }); }); </script></body></html> | Realtime chat service | javascript;node.js;mongodb;chat;socket.io | Your client JavaScript indentation is very, very messed up. I can hardly understand what's going on.Some lines are missing an indentation, and some have an extra indentation, or even an extra space (which is extra very messed up, because you are leaving the alignment of a tab/indentation).Everything inside the very first function should be indented one tab. Everything inside the socket.on's second parameter should be indented another tab. Everything inside $(#button).on's first parameter should be indented another tab.Here is your tab code cleaned up:$(function(){ var groupid = 2; //this groupid will change in the actual app. Right now is hardcoded. At tun time, this roupid is passed from php. var socket = io(http://104.236.19.119:3000); socket.on('connect',function(){ window.alert(You are connected.); }); $('#button').on('click',function(){ var entry = $(#entry).val(); var reply_msg = {content : entry, group:groupid}; socket.emit('reply',reply_msg); $(#entry).val(); }); var groupname = groupid + chat; //got the msg and append to chat window socket.on( groupname , function(data){ var new_msg = $(<p> + data.content + </p>); $('#msg').append(new_msg); });})This code is much, much easier to read.$('#button').on('click',function(){ var entry = $(#entry).val(); var reply_msg = {content : entry, group:groupid}; socket.emit('reply',reply_msg); // <-- $(#entry).val();});You have a potential error here: in this function, you attempt to send a signal to the server that you are connected to. However, if the client had not yet connected to the server, socket.emit will fail.To fix this, create a variable called isConnected and set it to false. Then, when the first socket.on fires you can set this variable to true. That way, you can setup an if statement in the code above so that you don't try to reply to the server without first connecting to the server.Here is what I mean:var isConnected = false;socket.on('connect',function(){ window.alert(You are connected.); isConnected = true;});$('#button').on('click',function(){ if(isConnected) { var entry = $(#entry).val(); var reply_msg = {content : entry, group:groupid}; socket.emit('reply',reply_msg); $(#entry).val(); } else { alert(You are not connected yet.); }}); |
_cs.63151 | We use electronics to build computers and do computation. Is computation independent of the hardware we use? Would it be possible to do whatever a computer does with pen and paper? If computation is not dependent of how we make our computers, then does the same principle which apply to a computer apply to how brain works? I want to know if computation is an abstract object which then is realized as computers. In other words, if we visit some alien civilization we expect that our mathematicians and physicists understand the alien physics and math. Is it the same as with the notion or concept of computation? It seems that in order to consider computation first we need consider a realization of a machine or a model. For example according to the first two lines of this question there are Turing machine, circuits and lambda calculation. How do we know that there is not another way of computation? For example, the way the brain works and does computation might not be describable by the computation which we consider in Turing machine. To put it another way, are there axioms which we build a theory of computation based on them? like the way we build Euclidean geometry. | Is computation independent of hardware? | turing machines;computation models | null |
_codereview.96354 | Here is my code for printf() implementation in C. Please share your thoughts for improvements.#define PRINTCHAR(c) putchar(c)#define MAXLEN 256// Write a printf function which simulates printf() in C.int formatAndPrintString(char *pcFmt, va_list lList){ //Holds the number of characters printed, 0 on error int nChars = 0;while(*pcFmt != '\0'){ if(*pcFmt == '%') { pcFmt++; int iTemp = 0; char acTemp[MAXLEN] = ; char *pcTemp = NULL, cTemp = 0; switch (*pcFmt) { case 'd': iTemp = va_arg(lList, int); itoa(iTemp, acTemp, 10); for(int i = 0; i < strlen(acTemp); i++) { PRINTCHAR(acTemp[i]); nChars++; } break; case 's': pcTemp = va_arg(lList, char*); while(*pcTemp != '\0') { PRINTCHAR(*pcTemp); nChars++; pcTemp++; } break; case 'c': cTemp = va_arg(lList, int); PRINTCHAR(cTemp); nChars++; break; default: break; } pcFmt++; } else // print the char to console { PRINTCHAR(*pcFmt); pcFmt++; nChars++; }}return nChars;}// Print function identical to printf() in stdio.hint printfunc(char *pcFormat, ...){ if(!pcFormat) { return 0; } va_list lList; va_start(lList, pcFormat); return(formatAndPrintString(pcFormat, lList));} | Sample printf implementation | c;reinventing the wheel;formatting;variadic | null |
_unix.246259 | I have to write a script that reads a number and counts it down to 0.I keep getting this error:practice123.sh: line 10: let: 1=[: attempted assignment to non-variable (error token is =[) I can't seem to get the loop to count down properly. I'm using shell check, and my syntax seems fine. Any input would be appreciated.#!bin/bash# This script will take one number from the CLI and see if the argument given is a valid variable. Then it will count that variable down to 0.var1=var1echo Enter a number.read var1until [ $var1 -le 0 ]do echo $var1 let $var1=[ $var1 -1 ]done | Write a script that reads a number and counts down to 0? | bash;shell script | null |
_unix.86254 | I realize sched_rt_period_us and sched_rt_runtime_us are meant to prevent freezing the system in case of runaway RT task. I wonder though, if it's possible to use a small value of sched_rt_period_us to assure the task is running smoothly.I have a simple job that requires no more than a millisecond or so of CPU time per call - say, driving a stepper motor over GPIO pins. I'd like to achieve no less than 100 cycles per second though, sustained. That's no more than 10% of the CPU time - discounting pre-emption and scheduler overhead.I've read very small values in sched_rt_period_us can result in an unstable system1 but it wasn't said what order of magnitude counts for a very small value. Can I reliably count on no more than 0.01s delay between calls to my program if I set sched_rt_period_us to 10000 and return control (sched_yield()) in timely manner?The underlying CPU would likely be 850MHz ARM with a number of other tasks than said control, but none of them realtime or even required to feel responsive, still, unlike with defaults of sched_rt_period_us and sched_rt_runtime_us (95% out of 1s) I can't allow the RT task to sleep whole 0.05s at a time. | Using sched_rt_period_us for setting maximum time between task calls of order of 10ms | scheduling;real time | null |
_webmaster.25105 | My domain would look like tiltblah.com. I don't want to mention the real domain name here, because it might be registered by someone else then.I'd like to register this domain, because I want to create a website with about PC games. I've searched the US and EU trademark databases and found trademark holders like Full Tilt and simmilar.Let's say my domain name goes like tiltfun.com, and my website is about games, Full Tilt poker (ignoring the fact that they might be out of business) is about games too. This seems to be a risk to me. Same branch of trade & the word Tilt is used => risk?And if there's a trademark holder from a completely different branch of trade, dish washers or anything, owning the trademark Tilt. Would they want to sue me? In Germany branch of trade is important. If it differs, simmillar domain name holders can peacefully coexist.I was never so cautios until there was somebody sued by BMW for using the word MINI and somebody in Germany was imho sued because he used a t- in his domain name. Deutsche Telekom owns T-.In case this question is too specific, how do you generally find out the riskiness of a domain name? | How do you generally find out the riskiness of a domain name? (concerning trademarks) | domain registration | null |
_webapps.40067 | With Microsoft Excel and Microsoft Word, it is easy to merge rows from a spreadsheet into pages in a Word file. This was traditionally used to make paper mailings. How can I do the same with Google Drive / Google Docs?There are plenty of templates that offer spreadsheet-to-email mail merge: How do I do a mail merge with Gmail? but that's not what I'm after. | How do I mail merge from Google Spreadsheet to a Google Document? | google spreadsheets;google apps script;google documents | You will need to write a Google Apps Script for that. You could let the first row of the spreadsheet be field names, and create a template document where the fields are referenced like [FIELD].So if your spreadsheet looks like:NAME | STREET | ZIP | TOWN---------------------------------------------Vidar | Karl Johans gate 15 | 0200 | OsloJohn | 3021 Arlington Road | 123456 | Memphis, TN... you could have a template document likeDear [NAME], living at [STREET], [TOWN] [ZIP] ...Your script will need to create a new, empty document, and for each row in your spreadsheet, add a new page and search/replace the field placeholders with row values.I have a somewhat working version, which might need some polishing. It can be invoked here. It will create a new document named Result of mail merge.You could use it as a starting point for your own script. Let me know if you're into that, or I can spend some more time finishing the script.Script content:var selectedTemplateId = null;var selectedSpreadsheetId = null;var spreadsheetDocPicker = null;var templateDocPicker = null;function mailMerge(app) { var app = UiApp.createApplication().setTitle(Mail Merge); templateDocPicker = createFilePicker(app, Choose template, UiApp.FileType.DOCUMENTS, templateSelectionHandler); templateDocPicker.showDocsPicker(); return app;};function createFilePicker(app, title, fileType, selectionHandlerName) { Logger.log(Creating file picker for + fileType); var docPicker = app.createDocsListDialog(); docPicker.setDialogTitle(title); docPicker.setInitialView(fileType); var selectionHandler = app.createServerHandler(selectionHandlerName); docPicker.addSelectionHandler(selectionHandler); return docPicker;}function templateSelectionHandler(e) { var app = UiApp.getActiveApplication(); selectedTemplateId = e.parameter.items[0].id; UserProperties.setProperty(templateId, e.parameter.items[0].id); Logger.log(Selected template: + selectedTemplateId); var spreadsheetDocPicker = createFilePicker(app, Choose spreadsheet, UiApp.FileType.SPREADSHEETS, spreadsheetSelectionHandler); spreadsheetDocPicker.showDocsPicker(); return app;}function spreadsheetSelectionHandler(e) { var app = UiApp.getActiveApplication(); UserProperties.setProperty(spreadsheetId, e.parameter.items[0].id); selectedSpreadsheetId = e.parameter.items[0].id; Logger.log(Selected spreadsheet: + selectedSpreadsheetId); doMerge(); return app;}function doMerge() { var selectedSpreadsheetId = UserProperties.getProperty(spreadsheetId); var selectedTemplateId = UserProperties.getProperty(templateId); Logger.log(Selected spreadsheet: + selectedSpreadsheetId); var sheet = SpreadsheetApp.openById(selectedSpreadsheetId); Logger.log(Spreadsheet opened); Logger.log(Opening template: + selectedTemplateId); var template = DocumentApp.openById(selectedTemplateId); Logger.log(Template opened); var templateFile = DocsList.getFileById(selectedTemplateId); var templateDoc = DocumentApp.openById(templateFile.getId()); //var mergedFile = templateFile.makeCopy(); var mergedDoc = DocumentApp.create(Result of mail merge); var bodyCopy = templateDoc.getActiveSection().copy(); Logger.log(Copy made); var rows = sheet.getDataRange(); var numRows = rows.getNumRows(); var values = rows.getValues(); var fieldNames = values[0]; for (var i = 1; i < numRows; i++) { var row = values[i]; Logger.log(Processing row + i + + row); var body = bodyCopy.copy(); for (var f = 0; f < fieldNames.length; f++) { Logger.log(Processing field + f + + fieldNames[f]); Logger.log(Replacing [ + fieldNames[f] + ] with + row[f]); body.replaceText(\\[ + fieldNames[f] + \\], row[f]); } var numChildren = body.getNumChildren(); for (var c = 0; c < numChildren; c++) { var child = body.getChild(c); child = child.copy(); if (child.getType() == DocumentApp.ElementType.HORIZONTALRULE) { mergedDoc.appendHorizontalRule(child); } else if (child.getType() == DocumentApp.ElementType.INLINEIMAGE) { mergedDoc.appendImage(child); } else if (child.getType() == DocumentApp.ElementType.PARAGRAPH) { mergedDoc.appendParagraph(child); } else if (child.getType() == DocumentApp.ElementType.LISTITEM) { mergedDoc.appendListItem(child); } else if (child.getType() == DocumentApp.ElementType.TABLE) { mergedDoc.appendTable(child); } else { Logger.log(Unknown element type: + child); } } Logger.log(Appending page break); mergedDoc.appendPageBreak(); Logger.log(Result is now + mergedDoc.getActiveSection().getText()); }}function testMerge() { UserProperties.setProperty(templateId, 1pAXWE0uklZ8z-O_Tejuv3pWSTiSv583ptUTGPt2Knm8); UserProperties.setProperty(spreadsheetId, 0Avea1NXBTibYdFo5QkZzWWlMYUhkclNSaFpRWUZOTUE); doMerge();}function doGet() { return mailMerge();} |
_unix.134703 | Is there a system or product that can be used in automating the process of building 32bit and 64bit libraries for multiple platforms (Solaris (Sparc & x86), and windows) used in building C++ based software applications that is replicable by other users and on different machines?I'm searching to see if there is a product or system that is available to automate the process of compiling libraries as new ones come out for our software builds. We build software products in Solaris and Windows both 32bit and 64bit. We want to build the new libraries and then place them out in SVN or on a server for developers to grab. We need a process that is documentable and able to be done by any of our developers and able to be easily setup and reproduced on any machine.The two options we are using so far is OSC scripting and bash scripting. I'm looking for more options. All I am concerned mostly about building the libraries, not the applications. I want the new libraries available for the developers to use in their builds. This is C++ development. | What is the best tool for automating the building 32-64bit libraries for Unix & Windows building C++ software, replicable by users and machines? | shell script;compiling;libraries;c++;development | You need a build automation tool, of which many exist. Even if you restrict to decent tools for building C++ programs that work on both Solaris and Windows, there are probably hundreds of choices. The classic language-agnostic build automation tool in the Unix and Windows world alike is make. There is a general consensus that it's possible to do better but no consensus as to who has actually done better.Build automation tools merely execute a series of instructions to produce the resulting binaries and other products from the source. It sounds like you probably want a continuous integration tool, which could do things like checking out from svn (possibly automatically in a commit hook), calling make, calling test scripts, uploading the resulting product and test result somewhere, send a notice when the build is finished and show some kind of dashboard with the history of builds.There isn't a de facto standard continuous integration tool, let alone best. Check through the Wikipedia list, pick a few likely-looking ones and spend a few minutes looking through their documentation. Then select one and set it up. Unless you have other requirements that you didn't mention, most of these products should be suitable. |
_codereview.2140 | In this post I asked about what would be idiomatic haskell database abstraction. I had been thinking for it a while, and the first answer was similar to what I had in mind, and I wrote a proof-of-concept of it. Discarding the abomination that is the schema, what would you change, and why?Database.hs{-# LANGUAGE GeneralizedNewtypeDeriving #-}module Database ( runDB , quickQuery , prepare , execute , fetchRowAl , DB (..) , module Database.HDBC.SqlValue) whereimport qualified Database.HDBC as Himport Database.HDBC.SqlValueimport Database.HDBC.Sqlite3import Control.Monad.Readernewtype DB a = D (ReaderT Connection IO a) deriving (Monad, MonadReader Connection, MonadIO)runDB :: FilePath -> DB b -> IO brunDB path (D x) = do c <- connectSqlite3 path mkSchema c r <- runReaderT x c H.disconnect c return rmkSchema conn = do tables <- H.getTables conn unless (Location `elem` tables) $ do H.handleSqlError $ H.quickQuery' conn CREATE TABLE Location (location TEXT PRIMARY KEY) [] return () unless (Person `elem` tables) $ do H.handleSqlError $ H.quickQuery' conn (unwords [ CREATE TABLE Person , (id INTEGER PRIMARY KEY AUTOINCREMENT, , name TEXT NOT NULL, , age INT NOT NULL, , location TEXT, , FOREIGN KEY (location) REFERENCES Location (location))]) [] return ()quickQuery :: String -> [SqlValue] -> DB [[SqlValue]]quickQuery q v = ask >>= \c -> liftIO $ H.quickQuery c q vprepare :: String -> DB H.Statementprepare q = ask >>= \c -> liftIO $ H.prepare c qexecute :: H.Statement -> [SqlValue] -> DB Integerexecute stmt v = liftIO $ H.execute stmt vfetchRowAl :: H.Statement -> DB (Maybe [(String, SqlValue)])fetchRowAl = liftIO . H.fetchRowALModel.hsmodule Model whereimport Databasedata Person = Person (Maybe Int) String Int Locationnewtype Location = Location String deriving (Eq)instance Eq Person where (Person _ a b c) == (Person _ a' b' c') = a == a' && b == b' && c == c'saveLocation :: Location -> DB ()saveLocation (Location x) = quickQuery INSERT OR IGNORE INTO Location VALUES (?) [toSql x] >> return ()retrieveLocation :: String -> DB (Maybe Location)retrieveLocation x = do r <- quickQuery SELECT location FROM Location WHERE location=? [toSql x] case r of [] -> return Nothing [[y]] -> return $ Just $ Location $ fromSql ysavePerson :: Person -> DB ()savePerson (Person _ n a l@(Location loc)) = do saveLocation l quickQuery INSERT INTO Person (name, age, location) VALUES (?, ?, ?) [toSql n, toSql a, toSql loc] return ()retrievePersons name = do r <- quickQuery SELECT id, name, age, location FROM Person WHERE name=? [toSql name] let persons = map makePerson r return persons where makePerson [sid, sname, sage, slocation] = Person (fromSql sid) (fromSql sname) (fromSql sage) (Location (fromSql slocation))tests.hsimport Test.HUnitimport Test.Framework.Providers.HUnitimport Test.Framework (defaultMain, testGroup)import System.Directoryimport Database.HDBC (quickQuery')import Control.Monad.Readerimport Control.Applicativeimport Data.Maybeimport Databaseimport ModelrunTest f = runDB /tmp/test.db f <* removeFile /tmp/test.dbtestConnected = runTest $ do c <- ask r <- liftIO $ quickQuery' c SELECT 'foo' AS value [] liftIO $ assertBool Return value should not be empty (length r > 0)testQuickQuery = runTest $ do [[x]] <- quickQuery SELECT ? AS value [toSql foo] liftIO $ assertBool quickQuery (fromSql x == foo)testPrepared = runTest $ do stmt <- prepare SELECT ? AS value execute stmt [toSql foo] (Just r) <- fetchRowAl stmt let (Just x) = lookup value r liftIO $ assertBool prepared (fromSql x == foo)testRetrieveLocationNothing = runTest $ do r <- retrieveLocation Turku liftIO $ assertBool Location nothing (isNothing r)testSaveLocation = runTest $ do let turku = Location Turku saveLocation turku (Just loc) <- retrieveLocation Turku liftIO $ assertBool loc == turku (loc == turku)testSavePerson = runTest $ do let person = Person Nothing Person 25 $ Location Turku savePerson person [per] <- retrievePersons Person liftIO $ assertBool model == db $ validate person per where validate _ (Person Nothing _ _ _) = False validate a b = a == btests = [ testGroup Database [ testCase connected testConnected , testCase quickQuery testQuickQuery , testCase testPrepared testPrepared ] , testGroup Model [ testCase saveLocation testSaveLocation , testCase savePerson testSavePerson , testCase testRetrieveLocationNothing testRetrieveLocationNothing ] ]main = defaultMain tests | Idiomatic haskell database connectivity | sql;haskell | null |
_softwareengineering.291506 | Passwords are recommended to be stored in char[] instead of String, as Strings are stored in StringPool.Read more hereAs per this question Strings in StringPool are not available directly.To obtain Strings in Stringpool, we would need a password-dictionary to check them in StringPool. If we have a password-dictionary, we don't need to worry about StringPool, we can anyhow try directly on password fields.To prevent Brute-force attack we are limiting number of re-tries for passwords and checking for any suspicious activities.If all that is in place still should we not use String as a datatype for passwords?The answer obtained from similar questions is: We can have access to memory dump and get access to Strings in stringpool.Follow up questions:How can one access the memory dump?Can the access be prevented? If access to memory dump is prevented, Is it safe to use String as a type for passwords? | Why are Strings in StringPool considered insecure? | java;security;strings;passwords;server security | null |
_cs.52462 | I would like to find all Euler PATHs in a directed graph.Counting (instead of finding) all the Euler PATHs is sufficient.Circuits are not good for me, only Paths.I am doing a problem, that I have derived to a point, where knowing the number of paths fast would help.Currently, I have written (in c++) a recursive function that finds all of them, but it complexity grows quickly, so my algorithm gets slow fast. My algorithm is ~O(2^n). I would like a faster one for counting, if possible.I have researched the topic, but I can only find proofs (for being NP complete, or polynomial) and algorithms for Euler Circuits in directed and undirected graphs. But again, I am looking for Euler Paths in directed graphs.My graphs have only two nodes, but a lot of edges, that should be touched only once, like in an Euler Path.So in summary:Euler Path.Directed Graph.Only two nodes.High edge count.Edge costs are the same.Here is an image to illustrate a possible set up. | Count the number of Euler PATHs in directed graph? | algorithms;graphs;counting;eulerian paths | You can actually come up with a formula for this. Let $\ell_0,\ell_1$ be the number of self-loops at $0,1$, and let $e_{01},e_{10}$ be the edges from $0$ to $1$ and in the other direction. We must have $|e_{01}-e_{10}| \leq 1$. If $e_{01} = e_{10}+1$ then the path must start at $0$; if $e_{10} = e_{01}+1$ then it must start at $1$; if $e_{01} = e_{10}$ then both are possible. We will count paths starting at $0$.Given an Eulerian path starting at $0$, we can write it as$$L_0 E_1 L_1 E_2 \cdots E_m L_m,$$where $L_0,L_2,\ldots$ are collections of self-loops at $0$, $L_1,L_3,\ldots$ are collections of self-loops at $1$, $E_1,E_3,\ldots$ are $0\to 1$ edges, and $E_2,E_4,\ldots$ are $1\to 0$ edges. We can decompose this path into three components:$$E_1 E_2 \ldots E_m \\L_0 L_2 \ldots \\L_1 L_3 \ldots$$We can choose the first component in $e_{01}! e_{10}!$ ways, the second component in $\ell_0!$ ways, and the third component is $\ell_1!$ ways. It remains to choose a way of partitioning the latter two strings into their components. In order to count this, assume that $m$ is even (the case $m$ odd is very similar) and divide the original path differently:$$L_0 E_1 L_2 E_3 L_4 \ldots E_{m-1} L_m \\L_1 E_2 L_3 E_4 L_5 \ldots E_{m-2} L_{m-1} E_m$$The first line contains $m/2$ breakpoints out of $\ell_0 + m/2$ symbols in total, so the number of ways of breaking $L_0L_2\ldots L_m$ into its $m/2+1$ parts is $\binom{\ell_0+m/2}{m/2}$. The computation is similar for the second line, once we remove the $E_m$ which must appear at the end; we get $\binom{\ell_1+m/2-1}{m/2-1}$.I'll leave you the task of bringing everything together to one formula. |
_cogsci.12983 | It's my understanding there are 150 trillion synapses in the human brain (give or take). Is there a way to calculate the cumulative width of all synaptic clefts associated with the synapses? I would expect that some would be shared by several synapses. At 20-40nm per synaptic cleft, 150 trillion of them would add up to a sizeable distance, which seems implausible, given the size of the brain's surface.Anyone have any suggestions on the best way to calculate this -- if there is one? | Is there any way to calculate the cumulative width of synaptic clefts? | neurobiology | null |
_unix.181962 | I've spent the last two days trying to get my computer working. It's a Dell Inspiron 15R SE.I have Windows 7 Professional and Linux Mint installed.I've tried the recovery disk for Windows and that just leaves me with a boot loop and a blue screen of death.On the Linux side I've tried using boot-repair ( http://paste.ubuntu.com/9952105 ) but I still just get a no operating system message when trying to boot from the Hard Disk.Here is the output of my partition info etc from Boot-repair: http://paste.ubuntu.com/9953024/If anyone can point me in the right direction I'd be so grateful. | Unable to boot Linux Mint or Windows anymore | linux mint;boot;dual boot | null |
_unix.381702 | Can somebody please help how to combine multiple excel files into single sheet (in Linux) with multiple tabs. I can use either python or perl.I have used below perl script, but getting blank output, with error Worksheet name 'Sheet1', with case ignored, is already in use at xlsmerge.pl line 49.#!/usr/bin/perl -wuse strict;use Spreadsheet::ParseExcel;use Spreadsheet::WriteExcel;use File::Glob qw(bsd_glob);use Getopt::Long;use POSIX qw(strftime);GetOptions( 'output|o=s' => \my $outfile, 'strftime|t' => \my $do_strftime,) or die;if ($do_strftime) { $outfile = strftime $outfile, localtime;};my $output = Spreadsheet::WriteExcel->new($outfile) or die Couldn't create '$outfile': $!;for (@ARGV) { my ($filename,$sheetname,$targetname); my @files; if (m!^(.*\.xls):(.*?)(?::([\w ]+))$!) { ($filename,$sheetname,$targetname) = ($1,qr($2),$3); warn $filename; if ($do_strftime) { $filename = strftime $filename, localtime; }; @files = glob $filename; } else { ($filename,$sheetname,$targetname) = ($_,qr(.*),undef); if ($do_strftime) { $filename = strftime $filename, localtime; }; push @files, glob $filename; }; for my $f (@files) { my $excel = Spreadsheet::ParseExcel::Workbook->Parse($f); foreach my $sheet (@{$excel->{Worksheet}}) { if ($sheet->{Name} !~ /$sheetname/) { warn Skipping ' . $sheet->{Name} . ' (/$sheetname/); next; }; $targetname ||= $sheet->{Name}; #warn sprintf Copying %s to %s\n, $sheet->{Name}, $targetname; my $s = $output->add_worksheet($targetname); $sheet->{MaxRow} ||= $sheet->{MinRow}; foreach my $row ($sheet->{MinRow} .. $sheet->{MaxRow}) { my @rowdata = map { $sheet->{Cells}->[$row]->[$_]->{Val}; } $sheet->{MinCol} .. $sheet->{MaxCol}; $s->write($row,0,\@rowdata); } } };};$output->close;Please suggest possible solutions. | How To Combine Multiple Excel Files With Multiple Tabs | linux;shell;python;perl | null |
_datascience.18123 | What are the meanings of Bias and Under fitting which are used in machine learning contexts? I have faced biased data in sampling in Statics but it seems they are different things in learning concepts.I have heard that some data sets are biased, also have heard the model (for example neural networkd) is low bias. Are these bias different? | What is Bias and Under fitting? | machine learning | Bias can mean different things in statistics:If your model is biased, it's likely your model is under-fitting.Some data set is biased in sample collection. For instance, if you assume your sample responses are independent, but somehow it's not, this is a bias in your data set. If you want to sample everybody in the country, but you skip some cities for no reason, this causes bias in your data set.Your estimators could be biased - the expectation of your estimator is not equal to the true value in the population. |
_cstheory.12351 | I would like to ask about a special case of the question Deciding if a given NC0 circuit computes a permutation by QiCheng that has been left unanswered.A Boolean circuit is called an NC0k circuit if each output gate syntactically depends on at most k input gates. (We say that an output gate g syntactically depends on an input gate g when there is a directed path from g to g in the circuit as viewed as a directed acyclic graph.)In the aforementioned question, QiCheng asked about the complexity of the following problem, where k is a constant:Instance: An NC0k circuit with n-bit input and n-bit output.Question: Does the given circuit compute a permutation on {0, 1}n? In other words, is the function computed by the circuit a bijection from {0, 1}n to {0, 1}n?As Kaveh commented on that question, it is easy to see that the problem is in coNP. In an answer, I showed that the problem is coNP-complete for k=5 and that it is in P for k=2.Question. What is the complexity for k=3?Clarification on May 29, 2013: A permutation on {0, 1}n means a bijective mapping from {0, 1}n to itself. In other words, the problem asks whether every n-bit string is the output of the given circuit for some n-bit input string. | Deciding whether an NC${}^0_3$ circuit computes a permutation or not | cc.complexity theory;open problem;permutations;circuit families | null |
_cstheory.21392 | While thinking about natural language processing, I came up with the following NP problem:OCCAM-k: Given a fixed natural number $k$, consider the following input: a natural number of states $S$ in unary in a Turing machine $M$, a finite collection $A$ of strings that $M$ accepts, and a finite collection $R$ of strings that $M$ rejects. Assuming that $M$ is polylimited by the polynomial $n^k+k$, that it contains at most $S$ states, that it accepts every string in $A$, and that it rejects every string in $R$, find a valid deterministic Turing machine that satisfies these conditions for $M$.The problem is NP because after guessing a Turing machine $M$ of size $S = |S|$ ($S$ is unary), all that remains is to verify that the machine accepts every string in $A$ and rejects every string in $R$. Since $M$'s running time is bounded above by $n^k+k$, this can be accomplished in polynomial time.I am skeptical that this problem is NP-complete, as I cannot think of an NP-complete problem that sounds likely to reduce to it in polynomial time. I would be excited if someone could prove that it is a member of P, as this would help with my motivation, which is to build a simple natural language processing system.(My reason for calling the language OCCAM is that I believe that one could theoretically try to find a natural language processing algorithm that determines the binary truth value of sentences. Suppose I provided 1 million true natural-language sentences and 1 million false natural-language sentences as part of the input; I could try to find a small enough polytime algorithm that gets all of these sentences right and hope that the algorithm would work on all natural language sentences in that language (e.g., English)).My question is: To which complexity class should we say OCCAM-k belongs? NP-complete? NPI? P? Is there an algorithm that could solve it? | Is the following Occam's razor decision problem a member of P? | ds.algorithms;complexity classes | null |
_webmaster.93445 | I have a custom report set in Google Analytics and when I view the metrics via Country, it's telling me the lowest page views didn't have any sessions but a small number of page views. I'm trying to get my head around sessions are really entrances, but I can't see how this applies when viewing by country? The custom report only tracks users who are logged in to my site and not the register/sign in page. | Google Analytics Country has more Page Views than Sessions | google analytics | null |
_cs.38067 | I'm reading a Wikipedia article on the Traveling Salesman problem as an Integer Programming formulation (http://en.wikipedia.org/wiki/Travelling_salesman_problem). The authors have all their constraints and I don't understand the final one. The following statement is in there. To prove that every feasible solution contains only one closed sequence of cities, it suffices to show that every subtour in a feasible solution passes through city 0 (noting that the equalities ensure there can only be one such tour). For if we sum all the inequalities corresponding to x[ij]=1 for any subtour of k steps not passing through city 0, we obtain: n * k <= (n-1) * kI specifically don't understand the For if we sum all the inequalities... part. Sum which inequalites?A little further the author states the following.Without loss of generality, define the tour as originating (and ending) at city 0. Choose u[i]=t if city i is visited in step t (i, t = 1, 2, ..., n). Then u[i]-u[j] <= n-1, since u_i can be no greater than n and u_j can be no less than 1; hence the constraints are satisfied whenever x_{ij}=0. For x_{ij}=1, we have:u[i] - u[j] + nx[ij] = (t) - (t+1) + n = n-1,satisfying the constraint.I guess I don't understand how this detects that we pass through all the nodes. Okay, looking at this some more, I think I've discovered a bit more. This equation is the MTZ formulation (Miller-Tucker-Zemlin) and it's geared at finding subtours.Having digested some snippets from papers like Gabor Pataki's Teaching Integer Programming Formulations using the Traveling Salesman Problem, there's a statement in there that if a subtour did not contain node 1, then along this subtour the u[i] value would have to increase to infinity. I'm not 100% sure, but what I think this means is that if you had nodes 3 and 4 linked together (edge from 3 to 4 and another from 4 to 3), you would have the following constraints...$u_3 - u_4 + 1 \le (n-1)*(1-x_{34}) \le 0$$u_4 - u_3 + 1 \le (n-1)*(1-x_{43}) \le 0$The contradiction here is that $u_4$ is one step greater than $u_3$ which is one step greater than $u_4$. | Integer Programming Traveling Salesman - Checking if Tour is Complete | traveling salesman;integer programming | First, an overview is as follows:The last constraints enforce that there is only a single tour covering all cities, and not two or more disjointed tours that only collectively cover all cities. To prove this, it is shown below (1) that every feasible solution contains only one closed sequence of cities, and (2) that for every single tour covering all cities, there are values for the dummy variables $u_i$ that satisfy the constraints.Interpreting the last constraints as a theorem:$$u_i - u_j + n x_{ij} \le n - 1 \quad 1 \le i \neq j \le n \Leftrightarrow \text{there is only a single tour covering all cities.}$$then part (1) is the necessary condition ($\Rightarrow$): every feasible solution in ILP implies a unique tour; and part (2) is the sufficient condition ($\Leftarrow$): every single tour corresponds to (at least) one feasible solution.For your questions:I specifically don't understand the For if we sum all the inequalities... part. Sum which inequalities?We aim to prove the part (1): every feasible solution contains only one closed sequence of cities. To this end, we should exclude the case that two or more disjointed subtours that only collectively cover all cities: For instance, subtours $0 \to 1 \to 2 \to 0 \bigcup 3 \to 4 \to 3 \bigcup 5 \to 6 \to 5$ covering all cities $0, \cdots, 6$ is not a legal tour, but it does satisfy the first and the second set of equalities. Consider any subtour which does not pass through the city $0$ and sum the inequalities of $u_i - u_j + n x_{ij} \le n - 1 \quad 1 \le i \neq j \le n$ for the subtour (taking $3 \to 4 \to 3$ as an example): Summing up $$(u_3 - u_4 + n \cdot 1 [x_{34} = 1] \le n-1) \text{ and } (u_4 - u_3 + n \cdot 1 [x_{43} = 1] \le n-1),$$ we have $$2n \le 2 (n-1).$$Generally, for a subtour (which does not pass through the city $0$) with length $k$, we will get $nk \le (n-1) k$. Contradiction.Therefore, every subtour must pass through the city $0$. Further, the first and the second equalities enforce that all subtours must be disjoint. As a consequence, there can only be a single tour covering all cities.I guess I don't understand how this detects that we pass through all the nodes.As I mentioned in the overview, part (2) is the sufficient condition: We are given a single tour covering all cities, we aim to show that this tour corresponds to some feasible solution in this ILP. Because such a given tour trivially satisfies other constraints which do not involve these $u_i$ variables, it suffices to show that there are values for $u_i$ that satisfy the last constraints. This is proved by construction: Choose $u_{i}=t$ if city $i$ is visited in step $t$. |
_codereview.42691 | The following PHP code does exactly what I need it to do but, as a complete PHP novice, I am wondering: what can be improved here?$theurl='./section-1.html';function getbody1($filename) { $file = file_get_contents($filename); $bodypattern = .*; $bodyendpattern = .*; $thecontainer = id=\container\; $thecleanup = ; $noheader = preg_replace(/.$bodypattern./, , $file); $noheader = preg_replace(~.$bodyendpattern.~, , $noheader); $noheader = preg_replace(|.$thecontainer.|, , $noheader); $noheader = preg_replace(#.$thecleanup.#, , $noheader); return $noheader;}echo getbody1($theurl); | Get contents from file | php;beginner | First things first, you are not using the right tool for the job. Regular expressions can't reliably parse markup. Full stop. But more on that later, let's first take a look at your patterns, as this may help you in the future:$bodypattern = .*;//for example//laterpreg_replace('/'.$bodypattern.'/',...);Now, whenever you quote a string into a regex pattern, you have to stop and think: what if the string happens to contain special chars?. I mean: half of the characters can mean a variety of things depending on the context. Thankfully, there's a handy function called preg_quote to help you with that. The safe option here would be:preg_replace('/'.preg_quote($bodypattern, '/').'/', ...);Now, you seem to be under the impression that a dot matches anything. And it does, except line-feeds. If I were to apply preg_match('/.+/', $thisAnswer, $matches); to this answer, the pattern would only match the text until a \n is encountered.You need a PCRE modifier: s:preg_match('/.+/s', $thisAnswer, $match);That's more like it. However, this is just as an aside, because what you really should be looking into are ways to actually treat markup as markup: a DOM needs to be parsed, if you want to get the most out of it. Here's my actual (and as-originally-posted) answer:Ouch, The first thing I noticed is that you're processing markup, and have chosen to do so using regular expressions. That's a bad idea from the off.It's especially bad considering you have a tool at your disposal that is specifically built to parse markup, the DOMDocument object.Basically, what you're trying to do can be written as simple as this:$DOM = new DOMDocument;//create DOM$DOM->loadHTMLFile($theUrl);//parse HTML$container = $DOM->getElementById('container');//get the id=container elementif ($container){//make sure it was found $container->removeAttribute('id');//remove the id attribute}$body = $contents = $dom->getElementsByTagName('body')->item(0);//get body//remove attributeswhile ($body->hasAttributes()){//while tag has attributes //remove attribute $body->removeAttribute($body->attributes->item(0)->nodeName);}//Get the body as string, use saveXML//as saveHTML adds DOCTYPE, html, head and title tag again$body = substr($DOM->saveXML($body), 6, -7);The reason why you need to remove the attributes for the body tag, is because DOMDocument::saveXML will return the markup string with the outer <body> and </body> tags. Their length is a given, but only if the opening <body> tag hasn't got any attributes. Thankfully, we can remove them quite easily, and slice them off with substr.If you want, you could easily use:$body = str_replace( array('<body>', '</body>'), '', $DOM->saveXML($body));Perhaps this is a bit easier to understand. Anyway: read the DOMDocument docs, there's a lot you can do there. Just click on the methods I used, and click the objects they return, too, so you know what instances you're working with.Now wrap all this in a function, and we can add some checks to avoid exceptions or errors from showing up:function getBody($file, DOMDocument $dom = null){//optionally pass existing DOMDocument instance //to avoid creating a new one each time we call this function if (!file_exists($file)) {//check if the file exists, if not: throw new InvalidArgumentException($file. ' does not exist!'); } $dom = $dom instanceof DOMDocument ? $dom : new DOMDocument; $dom->loadHTMLFile($file); $container = $dom->getElementById('container'); if ($container) $container->removeAttribute('id'); $body = $dom->getElementsByTagName('body')->item(0); while($body->hasAttributes()) { $body->removeAttribute( $body->attributes->item(0)->nodeName ); } $body = substr($dom->saveXML($body), 6, -7); //optionally remove trailing whitespace: return trim($body);}Call this function either like this:$body1 = getBody('path/to/file1.html');or, since you're going to process more than 1 file, and we can avoid creating a new DOMDocument instance for every function call:$dom = new DOMDocument;$files = array('file1.html', 'file2.html');$bodyStrings = array();foreach ($files as $file) $bodyStrings[] = getBody($file, $dom);That's it.As a guide-to-the-DOMDocument-docs:Every class extends from the DOMNode class, except for the DOMNodeList class, which is a Traversable containing only DOMNode instances, accessible through the item method. Anyway, check the DOMNode methods and properties. Learn that class by heart, as almost every object you work with inherits its properties and methods.The other class to check is the DOMElement class. Instances of this class represent a node (a tag if you will). It has some methods that I've used here (like removeAttribute).Finally, everything, of course starts with the DOMDocument class. I had already linked to the docs, but an extra link never hurt anyone. |
_webmaster.32950 | I have been working on a blog via wordpress that was setup through my hosting account for a while now. I currently have a plugin called, Restricted Site Access 4.0 for WordPress that displays a restriction message to visitors that prevents them from seeing the actual site.I plan to deactive the plugin upon finishing but was wondering if this affects the SEO or SERP? | Will using the production domain for testing/developing affect SERP rankings? | seo | You should install a plugin in your browser to view the status code the plugin is returning.If it's restricting access it may be returning a 403 which is not advised when you're developing a site you should return a 410 server under maintenance. This tells Google and others yes your sites there, working but under maintenance so come back later. With this they wont cache your page.Ideally though you should put up some content relevant to the final site and be working in a development environment that is not accessible at all by bots. Leaving them your main domain with the basic relevant content on your site to begin getting cached. |
_unix.76766 | I am not a linux/unix expert but everytime when I read about some local privilege escalation exploit (e.g. this),I wonder if an OS can detect that there is someone logging in as root (or new root process starting)? Imagine a linux machine prepared with a configuration that if root logs in into it (or detects some exploit to gain root privileges) the machine will interrupt/shutdown itself and a backup machine (with different configuration) will start or an admin will be notified...Does my idea makes sense, or are most of the exploits undetectable due their nature? | Privilege escalation detection? | linux;security;root | Exploits by their very nature are trying to not be detected. So most exploits are not coming into the system through normal means, at least not initially. They'll typically use something like a buffer overflow to gain access to the system.buffer overflowThis style of attack looks for portions of an application that are looking to take input from a user. Think about a web page and the various text boxes where you have to provide information by typing things into these text boxes. Each of these text boxes is a potential entry point for a would-be attacker. The good news:most of these attacks are not gaining root access, they're gaining access to a user account specifically setup for the web server, so it typically has limited access to only web server files and functions.in breaking in the attacker has left a considerable trail in a number of areas.The firewall logsWebserver logsOther potential security tool logsThe bad news:They've gained access to a system, and so have a beachhead where they can continue trying to break in further. The logs. Yes most of the time break-ins are not detected for weeks/months/years given that analyzing logs is both time consuming and error prone.detecting root loginsMost systems are designed to not allow root logins so this attack vector isn't really an issue. Most attacks gain access to some other lower level account and then leverage up by finding additional vulnerabilities once they've established a beachhead on your system.example #1:A would be attacker could gain root access by doing the following:Break into a system's web server account by finding a vulnerable web page that processes a user's input from some form through text boxes.Once access to the web server account has been achieved, attempt to either gain shell access through the web server's account or attempt to get the web server account to run commands on your behalf.Determine that there's a weakness in this particular system's version of a tool such as the command ls.Overflow the tool ls to gain access to the root account.example #2:A would be attacker might not even be interested in gaining full control of your system. Most break-ins are only interested in collecting systems to be used as slaves for other uses. So often the attacker is only interested in getting their software installed on your system so that they can use the system, without ever even gaining full control of the system.Determine that a certain web site has made available webapp X. Attacker knows that webapp X has a vulnerability where webapp X allows users to upload image files.Attacker prepares a file called CMD.gif and uploads it. Maybe it's a user's avatar image on a forum site, for example. But CMD.gif isn't a image, it's actually a program, who's named CMD.gif.Attacker uploads image to the forum site.Now attacker tricks webapp X into running his image.Attacker makes calls with his browser to webapp X, but he calls it in ways the authors of webapp X never imagined. Nor did they design webapp X to disallow it.web server log file of such an attack201-67-28-XXX.bsace703.dsl.brasiltelecom.net.br - - [16/Sep/2006:15:18:53 -0300] GET /cursosuperior/index.php?page=http://parit.org/CMD.gif? &cmd=cd%20/tmp;wget%20http://72.36.254.26/~fanta/dc.txt;perl%20dc.txt %2072.36.21.183%2021 HTTP/1.1 200NOTE: sample log from an Apache web server courtesy OSSEC.net.Here the attacker is getting webapp X (index.php) to run CMD.gif which can then do the following:cd /tmpwget http://72.36.254.26/~fanta/dc.txtperl dc.txt 72.36.21.183 21So they've coaxed webapp X into changing directories to /tmp, download a file, dc.txt, and then run the file making a connection back to IP address 72.36.21.183 on port 21.Disabling a compromised serverThe idea that you can shut a server down that has detected an exploit is a good attempt, but it doesn't work for a couple of reasons.If the attacker can get into the first system, then they can probably get into the second system.Most systems are essentially clones of each other. They're easier to maintain, and keeping things simple (the same) is a hallmark of most things in IT and computers.Different configurations means more work in maintaining the systems and more opportunities to make mistakes, which is usually what leads to a vulnerability to begin with.The attackers goal might not be to break in, they might be trying to deny access to your service. This is called a denial of service (DoS).Attempting to limit damageI could go on and on but in general you have a few resources available when it comes to securing a system.Use tools such as tripwire to detect changes on a system's file system.Firewalls - limit access so that it's only explicitly allowed where needed, rather then having full access to everything.Analyze log files using tools to detect anomalies.Keep systems current and up to date with patches.Limit exposure - only install software that's needed on a system - if it doesn't need the gcc compiler installed, don't install it.IDS - intrusion detection software. |
_webmaster.26739 | I would like to include an expert Q and A system into my site that works like stackoverflow but also gives the user the option to promise money for the answer. | looking for a Q and A tool with payment for answer | looking for a script;qa | null |
_unix.351067 | I have 2 Apache servers and 2 Loadbalance servers and one File server (CentOS 7) for moodle and I am using maria db cluster.I want to download some file from students in moodle but I face a problem with this error: 504 Gateway Time-out The server didn't respond in time.I have changed my php.ini: max_execution_time = 1330000 And in my Loadbalancer the set up for haproxy.cfg is:contimeout 5000clitimeout 50000srvtimeout 50000Many Thanks for your help | 504 Gateway Timeout error | centos;apache httpd;mysql | null |
_softwareengineering.269509 | Consider you wanting to implement a simple game of checkers. There would be a rectangular game board and the player would able to move the pieces around according to a particular set of rules.General good design principles suggest that we decouple the display of the game from it's data and logic.That is, the display of the game board and the ability to click and move stuff around would be decoupled from the actual representation of a game board in memory. The data in memory doesn't know what displays it.Now, let's talk about JavaScript specifically. JavaScript is a language designed mainly to be used as a lightweight client-side language. (I know, JS has grown far beyond it's original intended usage, but it is still generally regarded and used as what I described). All JavaScript does on the client side is manipulate Html and Css.This means that, by it's nature, JavaScript is very coupled to the Html and Css; the GUI. That is it's nature.So my question is: when designing a client-side JavaScript app, how loosely coupled should I make the business logic and data, and the user interface?Should I make an effort to entirely separate the display and the logic, as I would have done in a e.g. a C# app? Or is it acceptable in JavaScript to allow a certain amount of coupling between logic and display? | JavaScript program design: to what degree should I separate logic and display? | design;javascript | null |
_webapps.65924 | I have the following gmail filter which is currently workingMatches: to:(-{[email protected] [email protected]}) label:label1Do this: Skip InboxI'd like to modify it to not have it run on emails that contain word1 OR word 2. So if an email has word1 OR word2 OR is sent to [email protected] OR is sent to [email protected] then it would not run. | Do not apply filter if sent to specific email address or contains specific word | gmail;gmail filters | null |
_softwareengineering.87972 | I've heard many times about the aspect-oriented programming, mostly that it is the next generation technology in programming and is going to 'kill' OOP. Is it right? Is OOP going to die or what can be reason for that? | OOP technology death | object oriented | Any time someone tells you that one software technology will kill another one or dominate the whole market/use/audience, remember this :A sane (dynamic but stable) ecosystem is made of a variety of widely different species.That means that any new hyped technology will go through the hype curve and in the end will find it's specific(s) purpose through time and experience with it.That also mean that such an extreme concept as aspect-oriented programming is useful if it's needed, meaning, not always and not very often, because of implied costs.But it already have it's place, like OOProgramming, like generic programming, like functional programming, like procedural programming, etc.Did you notice that the languages that are the more used (and controversly popular) and widely spread in real life are not pure? That's because allowing several paradigms makes them more flexible to change of context through time and they fill more usage niches. |
_codereview.96162 | I'm writing my own framework (purely for learning purposes, SPL, OOP, patterns, etc) and have written a class to manage config data throughout the framework (not front end/view, just the core framework). Example of config data:The framework requires a specific PHP version to run correctly, and that required PHP version is stored in config settings. That config data is needed in a class which checks if the running PHP version is not lower than the required PHP version.I've read about various options for configs (for tens of hours over weeks), and the main ones seem to be:Constants; ini files; an array in an included file; static classes.They all have pros and cons, but the main con is they push things into global, which I'm really trying to avoid. They also don't lend themselves to dependency injection, which I'm really trying to achieve.I've made my own class for managing this data, and would like it reviewed, please.Class DescriptionThe config class is instantiated in the bootloader file before any classes which need it, so the object variable is ready to be used in any class to call the method.Note: I'll be changing how this class is instantiated when I get around to Dependency Injection Container, so please review based on that, and ignore that the object variable for this class is global - it eventually won't be.The config class' method getConfig() is used in the __construct (or getter method etc) in any class wanting config data. The getConfig() accepts parameters so specific config data can be retrieved.The classNOTE: In code comments and later text, by sub array I mean one of the single sub arrays within the config array - such as the php array, or router array. class coreConfig { private $configData; private $returnData; private function setConfigData($key, $value = '') { $configData = array ( 'php' => array( 'current' => PHP_VERSION_ID, 'required' => '50400', 'test-index' => 'php test data', ), 'framework' => array( 'name' => 'frameworky', 'version' => '1.0', 'date' => '01/01/2015', 'email' => '[email protected]', ), 'router' => array( 'allowedchars' => 'A-z', 'url-prefix' => 'http://', 'test-index' => 'router test data', ), ); if (!isset($configData[$key]) || (!empty($value) && !isset($configData[$key][$value]))) { return false; }elseif (empty($value)) { return $configData[$key]; } else { return $configData[$key][$value]; } } public function getConfig($request = array()) { $this->returnData = ''; // No data requested if (empty($request)) { $this->returnData = false; } elseif (!is_array($request)) { // Returns 1 single sub array $this->returnData[$request] = $this->setConfigData($request); } else { // Array(s) requested foreach ($request as $key => $value) { if (!is_array($value)) { // Returns entire sub array $this->returnData[$value] = $this->setConfigData($value); } else { // Specific sub array value(s) requested foreach ($value as $subKey => $subValue) { // 3rd level sub arrays not expected if (is_array($subValue)) { $this->returnData[$subKey] = false; } else { // Returns sub array value $this->returnData[$key][$subValue] = $this->setConfigData($key, $subValue); } } } } } return $this->returnData; }}OptionsNote: By key I mean send in a key which exists in the config array.The options to send to the getConfig() method are:A single key: Returns an entire single sub arrayAn array of single keys: Returns multiple entire single sub arraysAn array with a key and value(s), or multiple arrays with a key andvalue(s): Returns specific value(s) from the sub array(s) for eachspecified keyAny mixture of 2 and 3 can be sent in one call to the methodHere are some example usages based on the above options. The results are from print_r():$obj = new coreConfig;//*Option 1*: $config1 = $obj->getConfig('php');// Returns single entire sub array:Array ( [php] => Array ( [current] => 50609 [required] => 50400 [test-index] => php test data ))//*Option 2*: $config2 = $obj->getConfig(array('php', 'router'));// Returns 2 entire sub arrays:Array ( [php] => Array ( [current] => 50609 [required] => 50400 [test-index] => php test data ) [router] => Array ( [allowedchars] => A-z [url-prefix] => http:// [test-index] => router test data ) )//*Option 3*: $config3 = $obj->getConfig(array('php' => array('current', 'test-index')));// Returns partial sub array:Array ( [php] => Array ( [current] => 50609 [test-index] => php test data ) ) //*Option 4*: $config4 = $obj->getConfig(array( 'php' => array('current', 'test-index'), 'router' ));// Returns partial sub array, and entire sub array:Array ( [php] => Array ( [current] => 50609 [test-index] => php test data ) [router] => Array ( [allowedchars] => A-z [url-prefix] => http:// [test-index] => router test data ) )My QuestionsIs my general approach sane and decent for retrieving system configdata within a framework?Is it acceptable using the public (get) method to call a private(set) method (same class) to set the config array and retrieve data?e.g. $this->returnData[$value] = $this->setConfigData($value);Unit testing - I have no experience, but know of its existence andsome coding practices to following to cater for unit testing. Withmy class, the config data cannot be mocked in a test, is that aproblem for unit testing?Does the code set the array in setConfigData() every time data isrequested by getConfig()? If so, would this be resolved/improvedif I made the array an object - i.e. $this-configData? In tryingto potentially re-use objectsIs the setConfigData() method ok having those if/else? It's likethat because it allows the setConfigData() method to return onlythe required data, whereas this functionality being in thegetConfig() method meant getting the entire array to check if keysexisted etc.My main niggle is to add config settings for the framework, one hasto edit an array within a class method. This seems.. fiddly forconfig, but there are also benefits of it being in a class (DI, DIC,etc). Do you see this as a major issue as a developer adding configdata in a class method array?Is it worthwhile having the class take in so many options? Such as full config array request, partial, and a mixture, etc, all in one method call. Or would it be better to instead have the class only accept a single value and return an entire single sub array for each method call, and then call the method as many times as needed? //*Currently*: $allConfigData = $obj->getConfig('everything-I-could-possibly-need')//*Alternative with class only accepting and returning one full sub array*: $configData1 = $obj->getConfig('data-I-need');$configData2 = $obj->getConfig('more-data-I-need');$configData3 = $obj->getConfig('additional-data');I know this is a bit broad, but I'm asking you as a seasoned developer if this could potentially be useful. Currently I do not need more than one config sub array in any class, but my framework is expanding so potentially this could become useful. | Class to manage config data to allow DI | php;object oriented | IntroductionFirst of all: well done you for writing your own framework!(Just don't forget to throw it away once you feel you've learned enough). Configuration is, architecturally speaking, much more solid than relying on convention, so you score points there to!Some minor issuesComposer is a dependency management tool but it has some added functionality like a class autoloader and requirement enforcement for PHP versions and/or PHP modules. Especially if your framework will consist of separate libraries it might be useful to leverage the power of Composer to allow users to defined which parts they would/wouldn't want to use instead of having to do this through custom configuration. I say might because it will most likely depend on how complex your configuration is/will become and how well versed you (and/or users of your code) are in Composer usage.As for the specific example of the framework requiring a certain PHP version, I would use a Composer and simply state a PHP version as a Platform package. Configuration should definitely go in a text file somewhere but you are correct that you will need a code wrapper for easy access. To avoid abuse and to keep things simple, using a format that can not contain logic (like XML, INI, JSON or YAML) is preferable over using code, even if it is just a PHP array.The text values can be parsed and passed to a configuration object which is then given to the framework as configuration. As you observed in the comments, this would effectively replace the setConfigData method with a (preferably immutable) data object.I would also suggest you might want to have separate objects for different kinds of data instead of having everything cobbled together. Instead of splitting the array into single sub arrays I would opt for having separate specific config objects per responsibility (php/router/etc). These would not have to be separate classes but they could be if you feel this improves your design. Whether or not this is wise (as opposed to your suggestion in the comments of having one object with specific functions per responsibility) depends mostly on how the config is going to be used elsewhere in the framework.You may also want to take a look at immutable objects (basically a class with no setters, with data being injected through constructor parameters).The convention is for classnames to start with an uppercase letter.Using var_export instead of print_r yields a more natural output format. That is to say, a format that read more like natural PHP and thus requires less of a mind-switch when reading.Comment in regard to the codeLooking through the provided code, a view points of concerns:The function setConfigData doesn't actually do any setting. It just returns a value. Also, the $value parameter would be better of being called $subKey or something similar, as it currently gives the illusion that $value will be assigned to $key. The logic could also be more elegant but that's a matter for another review.The local variable $configData would be better of as a class property.The class property $returnData isn't needed, just use a local variable in the getConfig() function instead.Answers to your questions1. I find it hard to judge either Sane or Decent. I think Clean is more important: single responsibility, clear separation of concerns, no side-effects, etc. Reading Clean Code by Robert C. Martin can be invaluable there.2. If the set method actually set anything this would be less clean as it causes side-effects. Since it is really only another getter, there's no real problem.3. Yes. This can become problematic. The best thing for it is simply to learn how to write unit tests (it honestly isn't all that difficult) and having tests with your code will teach you how to create code that is easy to test.4. Yes, the array in setConfigData() is set again every time data is requested by getConfig. This is because it is being used from local scope and not from the class scope since it does not have a $this-> in front of the variable name. You don't need to make the array an object to resolve this, just load it from class scope using $this->configData.5. OK or not is mostly a point of view. Most folks will probably think it is fine. In my personal taste the conditions could be cleaner/less muddled.6. Yes, MAJOR issues. Configuration should live outside of the class. It can be injected into an object at the point where it is being instantiated. You really don't want for me to edit the framework code when I want an application I build on top of it to alter its behaviour!7. Personally I would not put all of that functionality into one method. I'd create separate methods for separate scenarios to keep the class signature (or interface) simple and easy to understand.In closingIf you feel inclined to look at this from other angles, you should probably also take a look at other data structures that can/could be used for configuration other than an array. For instance, the ARC config component uses a tree structure.If any of my comments seem unclear or need more elaboration, don't hesitate to ask. I will update my answer as needed.Furthermore, as you stated that building a framework was mostly about the educational values, I think you will agree that something as essential as configuration has a lot of lessons in it. You seem to be learning them quite well.Keep it up! |
_codereview.3993 | Each product in my e-commerce website has Arabic and English values for the title, description and excerpt. I have this method EditProduct to update those values based on current culture (Arabic or English)public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture){ var product = DoSomeMagicToGetAProduct(); if (element == title) { if (culture == en) { if (edit1) { product.Title = text1; } if (edit2) { product.TitleAr = text2; } } if (culture == ar) { if (edit1) { product.TitleAr = text1; } if (edit2) { product.Title = text2; } } } if (element == description) { // similar codes here } if (element == excerpt) { // similar codes here } product.Save();}The method works well, but I think I can improve the way I write it to be more elegant.Any suggestions? | Editing e-commerce website values | c# | I think the code is a little dodgy, and the design is dodgy. I'd store the translation in a dictionary of some sort.But addressing your immediate question, to simplify the code you have, you could do....public void EditProduct(string element, string text1, string text2, bool edit1, bool edit2, string culture) { var product = DoSomeMagicToGetAProduct(); var arText = culture == ar ? text1 : text2; var enText = culture == en ? text1 : text2; var updateEn = culture == en ? edit1 : edit2; var updateAr = culture == ar ? edit1 : edit2; if (element == title) { if (updateEn) product.Title = enText; if (updateAr) product.TitleAr = arText; } if (element == description) { if (updateEn) product.Description = enText; if (updateAr) product.DescriptionAr = arText; } if (element == excerpt) { if (updateEn) product.Excerpt = enText; if (updateAr) product.ExcerptAr = arText; } product.Save(); } |
_unix.354843 | I want to know the equivalent of grep -oE '[^ ]+$' pathnameto awk or sed.If someone can answer and explain that would be great.Thank you. | Equivalent of grep to awk or sed | awk;sed;grep | Let's go over what your grep command does first:the -o tells grep to output only the matching part instead of the whole linethe -E flag allows use of extended regular expressions'[^ ]+$' will match any non-space character repeated one or more times at the end of the line - basically a word at the end of the line.Test run:$ cat input.txtto be or not to bethat is the question$ grep -oE '[^ ]+$' input.txt bequestionNow, how can we do the same in awk ? Well that's easy enough considering that awk operates by default on space-separated entries of each line (we call them words - awk calls them fields). Thus we could print $NF with awk - take the NF variable for number of fields and treat it as referring to specific one. But notice that the grep command would only match non-blank lines, i.e. there is at least one word there. Thus, we need to a condition for awk - operate only on lines which have NF number of fields above zero.awk 'NF{print $NF}' input.txtIt should be noted that GNU awk at least supports extended regex (I'm not familiar with others as extensively, so won't make claims about others). Thus we could also write a variation on cuonglm's answer:$ awk '{if(match($0,/[^ ]+$/)) print $NF}' input.txt bequestionWith GNU sed one can use extended regular expressions as well - that requires -r flag, but you can't simply use same regular expression. There's a need to use backreference with \1.$ cat input.txt to be or not to bethat is the questionblah $ sed -r -e 's/^.* ([^ ]+)$/\1/' input.txt bequestionblahIt is possible to obtain desired result with basic regular expression like so:$ cat input.txt to be or not to bethat is the questionblah $ sed 's/^.* \([^ ].*\)$/\1/' input.txt bequestionblah For more info, please refer to these posts:can we print the last word of each line in linux using sed command?https://unix.stackexchange.com/a/31479/85039 |
_cs.52341 | I'm trying to understand how oblivious RAM works, specificallypath oblivious RAM. While I understand how this technique offers protection when reading data - multiple randomly distributed reads obfuscate the access pattern of the data actually requested - I can't tell how that helps protect against an attacker who is interested in the users write access. Surely multiple randomly addressed writes would potentially overwrite critical data that is later required by the program. Similarly, while batching the writes would stop an attacker knowing exactly which addresses were written to at a given time, this would not stop them discovering which addresses were written to, nor the presence of those writes. | Oblivious RAM write protection | security | Surely multiple randomly addressed writes would potentially overwrite critical data...Nope. The oblivious RAM data structures take care to ensure that, when doing reads and writes at random locations, they don't mess up the data. For instance, if doing an extra write, then they make sure to write the same value that was already there (except in encrypted form), so that it doesn't change what value is stored there.batching the writes would stop an attacker knowing exactly which addresses were written to at a given timeBut the attacker would still know which set of addresses were written, which is leakage of partial information. Oblivious RAM aims to eliminate even this partial leak. So oblivious RAM achieves a stronger property than batching could ever provide. |
_unix.202333 | I have a wireless PS3 controller adapter that is plugged in to my Ubuntu 14.04 box. It has 2 modes: XInput and DInput, which as far as I can tell, it just passes two different vendor/product id's over USB (XInput has a Microsoft XBOX id, the other is generic). The XInput mode works fine (loads xpad driver), but in the DInput mode the kernel identifies the device as a mouse, instead of as a joystick. Related Questions:What do I need to change to make it identify as a joystick?How does the usbhid driver assign minor numbers to a character device?dmesg[ 1692.151837] usb 3-1: new full-speed USB device number 8 using ohci-pci[ 1692.325523] usb 3-1: New USB device found, idVendor=0079, idProduct=1801[ 1692.325528] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0[ 1692.325530] usb 3-1: Product: Mayflash PS3 Game Controller Adapater[ 1692.325531] usb 3-1: Manufacturer: HJZ[ 1692.341586] input: HJZ Mayflash PS3 Game Controller Adapater as /devices/pci0000:00/0000:00:12.0/usb3/3-1/3-1:1.0/input/input14[ 1692.341854] hid-generic 0003:0079:1801.0006: input,hidraw3: USB HID v1.11 Joystick [HJZ Mayflash PS3 Game Controller Adapater] on usb-0000:00:12.0-1/input0sudo udevadm info --path=/devices/pci0000:00/0000:00:12.0/usb3/3-1/3-1:1.0/input/input14P: /devices/pci0000:00/0000:00:12.0/usb3/3-1/3-1:1.0/input/input14E: ABS=ffffffE: DEVPATH=/devices/pci0000:00/0000:00:12.0/usb3/3-1/3-1:1.0/input/input14...E: ID_INPUT_TABLET=1E: ID_MODEL=Mayflash_PS3_Game_Controller_Adapater...E: ID_TYPE=hidE: ID_USB_DRIVER=usbhidll /dev/input/by-id/lrwxrwxrwx 1 root root 9 May 8 16:18 usb-HJZ_Mayflash_PS3_Game_Controller_Adapater-event-mouse -> ../event4lrwxrwxrwx 1 root root 9 May 8 16:18 usb-HJZ_Mayflash_PS3_Game_Controller_Adapater-mouse -> ../mouse1sudo udevadm monitor --property --kernel --udev...KERNEL[1693.830143] add /devices/pci0000:00/0000:00:12.0/usb3/3-1/3-1:1.0/input/input14/mouse1 (input)ACTION=addDEVNAME=/dev/input/mouse1DEVPATH=/devices/pci0000:00/0000:00:12.0/usb3/3-1/3-1:1.0/input/input14/mouse1MAJOR=13MINOR=33SEQNUM=2196SUBSYSTEM=inputUDEV_LOG=7...UpdateIn my quest for knowledge, I found a site that lists the Major/Minor numbers for the usbhid driver. As you can see below, my device is 13,32, which is reserved by the driver for mouse0. It would appear that I need to trick(?) the driver into assigning a different Minor number to it? ...or am I headed down the wrong path? (Admittedly, I'm more familiar with Windows driver dev, than linux)ReferenceUSB device number mappings~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 13 char Input drivers 0 = /dev/input/js0 First joystick 1 = /dev/input/js1 Second joystick ... 32 = /dev/input/mouse0 First mouse 33 = /dev/input/mouse1 Second mousels -l /dev/input/crw-r----- 1 root root 13, 32 May 9 11:48 mouse0lsusb -vBus 003 Device 003: ID 0079:1801 DragonRise Inc.Device Descriptor: bLength 18 bDescriptorType 1 bcdUSB 2.00 bDeviceClass 0 (Defined at Interface level) bDeviceSubClass 0 bDeviceProtocol 0 bMaxPacketSize0 64 idVendor 0x0079 DragonRise Inc. idProduct 0x1801 bcdDevice 1.00 iManufacturer 1 HJZ iProduct 2 Mayflash PS3 Game Controller Adapater iSerial 0 bNumConfigurations 1 Configuration Descriptor: bLength 9 bDescriptorType 2 wTotalLength 34 bNumInterfaces 1 bConfigurationValue 1 iConfiguration 0 bmAttributes 0x80 (Bus Powered) MaxPower 500mA Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 0 bAlternateSetting 0 bNumEndpoints 1 bInterfaceClass 3 Human Interface Device bInterfaceSubClass 0 No Subclass bInterfaceProtocol 0 None iInterface 0 HID Device Descriptor: bLength 9 bDescriptorType 33 bcdHID 1.11 bCountryCode 0 Not supported bNumDescriptors 1 bDescriptorType 34 Report wDescriptorLength 428 Report Descriptors: ** UNAVAILABLE ** Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 3 Transfer Type Interrupt Synch Type None Usage Type Data wMaxPacketSize 0x0008 1x 8 bytes bInterval 1Device Status: 0x0002 (Bus Powered) Remote Wakeup Enabled | Change hidraw device from mouse to joystick | linux kernel;udev | The HID system checks for a specialized driver matching the vendor and product ids, and if there is none it is treated as a generic HID device : the descriptors sent by the device are used to determine what it is.In your case there is a specialized hid driver, but it looks like it wasn't loaded. You can try modprobe hid-dr, but you probably don't have it installed. On Ubuntu, it is in the linux-image-extra package. |
_cogsci.13242 | AI, to the level that we attempt to create it these days, involves creating neural networks that learn from stimulus (experience, data) and reinforcement. A higher score such as in a Go game, or a higher % of matched words, faces or signs seems to equate to positive reinforcement within classical conditioning.Given that behaviourism is mostly seen as somewhat outdated, if the above makes sense, could this model of learning be limiting progress in AI? | Is the current approach to AI learning essentially behaviourism? | behaviorism;artificial intelligence | null |
_bioinformatics.161 | The peak calling tool MACS2 can call peaks in either narrow peak mode (for focused signals like transcription factor ChIPseq) or broad peak mode (for more defuse signals, like certain histone modifications). The algorithm for narrow peak calling is well described in the MACS publication. But I don't find much documentation for how peak calling is different in broad peak mode. The manual only contains the following:--broadWhen this flag is on, MACS will try to composite broad regions in BED12 ( a gene-model-like format ) by putting nearby highly enriched regions into a broad region with loose cutoff. The broad region is controlled by another cutoff through --broad-cutoff. The maximum length of broad region length is 4 times of d from MACSBut this doesn't really describe exactly how this is performed. So what is the algorithm MACS uses for calling broad peaks? | How are MACS2's narrow peak and broad peak algorithms different? | algorithms;chip seq;macs2 | The key function is call_broadpeaks:The description attached to the function says:This function try to find enriched regions within which, scores are continuously higher than a given cutoff for level 1, and link them using the gap above level 2 cutoff with a maximum length of lvl2_max_gap.scoring_function_s: symbols of functions to calculate score. 'p' for pscore, 'q' for qscore, 'f' for fold change, 's' for subtraction. for example: ['p', 'q']lvl1_cutoff_s: list of cutoffs at highly enriched regions, corresponding to scoring functions.lvl2_cutoff_s: list of cutoffs at less enriched regions, corresponding to scoring functions.min_length :minimum peak length, default 200.lvl1_max_gap : maximum gap to merge nearby enriched peaks, default 50.lvl2_max_gap : maximum length of linkage regions, default 400.Return both general PeakIO object for highly enriched regions and gapped broad regions in BroadPeakIO.To give some basic explanation, the algorithm (briefly) appears to be as follows:Two separate levels of peaks are called, level 1 (a higher pval, ie more significant) and level 2 (a lower pval). Level 1 is controlled by -p and level 2 is controlled by --broad-cutoff. When each peakset is called, they are immediately linked by the max gap parameter for each set.Then, assuming that all level 1 peaks should be inside level 2 peaks (this is an explicit assumption by MACS2), the algorithm groups level 1 peaks inside level 2 peaks to output a broad peak....This has a few implications:The broad peak calls really come from the level 2 peaks alone (+ linking). The level 1 peak calls allow you to distinguish sub peaks (so that you can have gapped peaks).Aside from the linking, the broad peak calls would be the same as narrow peak calls, if you called both with the same pval threshold (for example, if you set --broad-cutoff 0.1 in broad peak mode, and the -p 0.1 for narrow peak mode) |
_scicomp.7623 | Following Hundsdorfer approach the finite volume discretisation of the advection-diffusion equation (conservative form) on non-uniform cell centered grid can be written as,$$w_j^{\prime} = \frac{w_{j-1}}{h_j}\left( \frac{ah_j}{2h_{-}} + \frac{d}{h_{-}} \right) - \frac{w_j}{h_j}\left( \frac{a}{2}\left[ \frac{h_{j-1}}{h_{-}} - \frac{h_{j+1}}{h_{+}} \right] + d\left[-\frac{1}{h_{-}} - \frac{1}{h_{+}} \right]\right) + \frac{w_{j+1}}{h_j}\left(- \frac{ah_j}{2h_{+}} + \frac{d}{h_{+}} \right)$$I am having trouble implementing this stencil because the edge terms have a dependence on the position of ghost cells which are outside of the domain.For example, if we write the equation at the left hand side boundary (this corresponds to cell centre $x=x_1$),$$w_1^{\prime} = - \frac{w_1}{h_1}\left( \frac{a}{2}\left[ \frac{h_{0}}{h_{-}} - \frac{h_{2}}{h_{+}} \right] + d\left[-\frac{1}{h_{-}} - \frac{1}{h_{+}} \right]\right) + \frac{w_{2}}{h_1}\left(- \frac{ah_1}{2h_{+}} + \frac{d}{h_{+}} \right)$$N.B. The terms in the first bracket depend on the position of the ghost point. To make this clear see the diagram below and notice that the $h_0$ and $h_{-}$ term stray outside of the domain.Am I free to choose the position and size of the ghost cell? For example,Can I set $h_{-}\equiv h_{+}$? Or, can I set $h_{-}=0$? Regarding the latter, does it make sense to have a cell with zero volume? This would mean that the cell center and vertex coincide.The value of the variable at the ghost point ($w_0$) is never used in numerical methods (this is clear!). However, the stencil above would seem to imply that we must at least choose a location and size for the ghost cell and this must be included in the discretisation. Is that assessment correct? | Are we free to choose the position of ghost cells on a non-uniform finite-volume mesh? | boundary conditions;finite volume;advection diffusion | Including an actual ghost cell for FVM discretization is more or less a matter of convenience. For instance, if the boundary condition on the wall is a Neumann type, you actually do not need to discretize in the $x^-$ direction since the flux is given by the boundary condition and is known.If the boundary condition is of Dirichlet type, what you need is to approximate the flux using the interior point(s) and the value on the boundary. In the simplest case, this would result from a simple linear extrapolation using $x_1$ and the wall point $x_w$. This effectively means that the value of the flux will be independent of the location of the ghost cell (slope of the extrapolating function for a simple linear method).Given this observation, I'd say anything but $h^- = 0$ would be good. I always personally choose $h^- = h^+$ as that makes life easier! |
_unix.125973 | I have an embedded device with this SD card:[root@(none) ~]# busybox fdisk -lDisk /dev/mmcblk0: 3965 MB, 3965190144 bytes4 heads, 16 sectors/track, 121008 cylindersUnits = cylinders of 64 * 512 = 32768 bytes Device Boot Start End Blocks Id System/dev/mmcblk0p1 305 8497 262144+ 83 Linux/dev/mmcblk0p2 8497 16689 262144+ 83 Linux/dev/mmcblk0p3 16689 60352 1397247 b Win95 FAT32and these partitions:[root@(none) ~]# dfFilesystem 1K-blocks Used Available Use% Mounted on/dev/root 253871 140291 113580 55% /none 16384 4 16380 0% /tmpnone 127016 4 127012 0% /devnone 16 4 12 25% /var/libnone 16 0 16 0% /var/lognone 128 16 112 13% /var/run/dev/mmcblk0p3 1394520 118036 1276484 8% /mnt/onboardI have a u-boot kernel image file, uImage, of ~2 Mb. What happens exactly if I do the following?dd if=uImage of=/dev/mmcblk0 bs=512 seek=2048Why am I asking this?This command is strange for me because:the copied image is smalled than target partitionit seems that the image is extracted on /dev/mmcblk0p1, that is the root partition. It starts at 305, while dd skips 2048 blocks EDIT: see Anthon's answerthere's not a boot partitionuImage is extracted; on the contrary I expected it will be used by u-boot as-isBackground: the device is a Kobo Glo, and the command is executed by update scripts to update the kernel. | What does this dd command do exactly? | kernel;embedded;dd;u boot | I am guessing here, as I have no Kobo Glo (I wish my Bookeen HD was reprogrammable).You seem to have a 2Gb SD memory internally ( 60352 cylinders of 32K each)The dd does skip 2048 blocks of 512 (1048576), which is less than the 305 cylinder offset (9994240). In fact have to write more than 8Mb to reach the /dev/mmcblk0p1 partition that way.How the device boots depends on its firmware, but it is likely that there is some basic bootstrapping done via the first 1Mb on the SD memory, that in turn then calls the image written with dd./dev/mmcblk0p1 is 256Mb ( (8497 - 305)*32768 ) and that seems to be mounted as / with maybe a backup of it on /dev/mmcblk0p2 or vv. |
_codereview.104428 | I've always wanted to be able to steer stream indentation, so that I could write code like this:/// This probably has to be called once for every program:// http://stackoverflow.com/questions/26387054/how-can-i-use-stdimbue-to-set-the-locale-for-stdwcoutstd::ios_base::sync_with_stdio(false);std::cout << I want to push indentation levels:\n << indent_manip::push << To arbitrary depths\n << indent_manip::push << and pop them\n << indent_manip::pop << back down\n << indent_manip::pop << like this.\nFinally, I've done it, but I had to do a kind of nasty hack.The problem is:I need to call a facet that is called on every string, which appears to mean that I have to use codecvt.I need the indentation level to persist, which means using iosbase::iword.codecvt doesn't have a reference to iosbase anywhere.Combine all that with the fact that facets have to be constant objects, and you get a kind of tricky problem. I solved it with a dirty trick:I use iword to keep track of the indentation level, since I get stream tracking for free that way. If I was only dealing with a single stream it would useless information.Whenever indent_manip::push is called, the iword is incremented, a new fact is created, a locale is created with that facet, and the current stream is imbued with that locale.I put the implementation, along with a more involved demo/test on GitHub.Tested on gcc 5.1 with:g++ -o indenter --std=c++14 indent_test.cppWhat I'm most interested inObviously it's not going to win performance prizes, and there's some easy places to optimize. I'm curious about the safety of what I'm trying to do. Is there a cleaner alternative?Obviously I can create a custom ostream, and that'll be phase two, but I have a use case where I want to imbue this behavior into an existing std::ostream, and this was the only way I could figure out how to do it.How's the usability?#pragma once#include <locale>#include <algorithm>#include <iostream>#include <iomanip>#include <cassert>class indent_facet : public std::codecvt<char, char, std::mbstate_t> {public: explicit indent_facet( int indent_level, size_t ref = 0) : std::codecvt<char, char, std::mbstate_t>(ref), m_indentation_level(indent_level) {} typedef std::codecvt_base::result result; typedef std::codecvt<char, char, std::mbstate_t> parent; typedef parent::intern_type intern_type; typedef parent::extern_type extern_type; typedef parent::state_type state_type; int &state(state_type &s) const { return *reinterpret_cast<int *>(&s); }protected: virtual result do_out(state_type &need_indentation, const intern_type *from, const intern_type *from_end, const intern_type *&from_next, extern_type *to, extern_type *to_end, extern_type *&to_next ) const override; // Override so the do_out() virtual function is called. virtual bool do_always_noconv() const throw() override { return m_indentation_level==0; } unsigned int m_indentation_level = 0;};indent_facet::result indent_facet::do_out(state_type &need_indentation, const intern_type *from, const intern_type *from_end, const intern_type *&from_next, extern_type *to, extern_type *to_end, extern_type *&to_next ) const{ result res = std::codecvt_base::noconv; for (; (from < from_end) && (to < to_end); ++from, ++to) { // 0 indicates that the last character seen was a newline. // thus we will print a tab before it. Ignore it the next // character is also a newline if ((state(need_indentation) == 0) && (*from != '\n')) { res = std::codecvt_base::ok; state(need_indentation) = 1; for(int i=0; i<m_indentation_level; ++i){ *to = '\t'; ++to; } if (to == to_end) { res = std::codecvt_base::partial; break; } } *to = *from; // Copy the next character. // If the character copied was a '\n' mark that state if (*from == '\n') { state(need_indentation) = 0; } } if (from != from_end) { res = std::codecvt_base::partial; } from_next = from; to_next = to; return res;};/// I hate the way I solved this, but I can't think of a better way/// around the problem. I even asked stackoverflow for help:////// http://stackoverflow.com/questions/32480237/apply-a-facet-to-all-stream-output-use-custom-string-manipulators//////namespace indent_manip{static const int index = std::ios_base::xalloc();static std::ostream & push(std::ostream& os){ auto ilevel = ++os.iword(index); os.imbue(std::locale(os.getloc(), new indent_facet(ilevel))); return os;}std::ostream& pop(std::ostream& os){ auto ilevel = (os.iword(index)>0) ? --os.iword(index) : 0; os.imbue(std::locale(os.getloc(), new indent_facet(ilevel))); return os;}/// Clears the ostream indentation set, but NOT the raii_guard.std::ostream& clear(std::ostream& os){ os.iword(index) = 0; os.imbue(std::locale(os.getloc(), new indent_facet(0))); return os;}/// Provides a RAII guard around your manipulation.class raii_guard{public: raii_guard(std::ostream& os): start_level(os.iword(index)), oref(os) {} ~raii_guard() { reset(); } /// Resets the streams indentation level to the point itw as at /// when the guard was created. void reset() { oref.iword(index) = start_level; oref.imbue(std::locale(oref.getloc(), new indent_facet(start_level))); }private: std::ostream& oref; int start_level;};} | Stream manipulating indenter | c++;formatting;stream | null |
_unix.154144 | Based on this section of the Linux Advanced Routing & Traffic Control HOWTO, I can't get tc to limit the network speed in my computer.The router is a Motorola SurfBoard modem with a few routing capabilities and firewall. The machine I want to limit the traffic is 192.168.0.5, and also the script is being run from 192.168.0.5.Here is my adaption of the commands on the link above for /etc/NetworkManager/dispatcher.d/:#!/bin/sh -eu# clear any previous queuing disciplines (qdisc)tc qdisc del dev wlan0 root 2>/dev/null ||:# add a cbq qdisc; see `man tc-cbq' for detailsif [ $2 = up ]; then # set to a 3mbit interface for more precise calculations tc qdisc add dev wlan0 root handle 1: cbq avpkt 1000 \ bandwidth 3mbit # leave 30KB (240kbps) to other machines in the network tc class add dev wlan0 parent 1: classid 1:1 cbq \ rate 2832kbit allot 1500 prio 5 bounded isolated # redirect all traffic on 192.168.0.5 to the previous class tc filter add dev wlan0 parent 1: protocol ip prio 16 \ u32 match ip dst 192.168.0.5 flowid 1:1 # change the hashing algorithm every 10s to avoid collisions tc qdisc add dev wlan0 parent 1:1 sfq perturb 10fiThe problem is that I have tried setting 2832kbit to very small values for testing (like 16kbit), but I still can browse the web at high speed. The problem is not in NetworkManager, because I'm testing the script manually.EDIT: I have found that by changing dst 192.168.0.5 to src 192.168.0.5, the upload speed is reliably limited, but I still haven't figured how to get the download speed to work, which is the most important for me. | Can't get tc to limit network traffic | networking;tc;qos | You cannot limit incoming traffic on the destination machine because it has already arrived.To properly do what you want to do, you need to put tc onto your gateway. This is probably not an option for you, but it's the way.Ingress traffic can only be policed, in that it discards packets that exceed the speed limit. This is inefficient because you now take more bandwidth later to receive the same packet again. This works somewhat roughly because TCP is designed to handle traffic loss by slowing down when packets are lost, but you end up constantly going slower and faster as TCP scales which your most recent comment shows you are experiencing.However, there is a way to make your system into a gateway for itself by shoving an 'Intermediate Functional Block Device' into your network pathway. I suggest reading up on it and then trying that for inbound rate limiting.See this 'Theory' discussion re INGRESS / EGRESS shaping / policing on the Gentoo site. |
_unix.149297 | EnvironmentUbuntu 14.04 LTS Desktop 64-bitProblemonly members of group_name should be allowed to mount,unmount and read,write,execute drive_namePotential Solutionedit /etc/fstab add line: /dev/abc /media/drive_name ext4 group 0 2create group: sudo groupadd group_nameadd users to group: sudo adduser user1 group_name mount point owned by group: sudo chgrp /media/drive_name group_nameQuestionIs this the correct, secure way of solving the problem?Thank you :) | fstab group option? | linux;ubuntu;fstab | null |
_unix.30238 | I have a simple small app that suports cin/cout interaction. But there are times (lots of them) when I do not care about that interaction and just want to run my app in background. So I start it with command like nohup ./myServer >& /dev/null &but it eats 100% of one of my cores because nohup sends eof then endl or something like that to my app, my app thinks that this is dull user and proposes him with list of interaction commands and waits for new commad, nohup sends eof then endl again and so on recursively.So one core gets eaten up with this crappy interaction. I want to start nohup so that it would send no data at all to my app - no eof, endl, etc how to do such thing?How to make nohup send no data at all to my app after it started it? | nohup sends eof (or some other data) info my app when running recursively. How to make it stop or not send at all? | linux;nohup | The fix for that is to fix your application.nohup doesn't send anything to anyone. Your application on the other hand is assuming that stdin is a valid, open file descriptor. It should be checking the return code of whatever primitive it is using to get the data from standard input, and react accordingly if the input stream is found to be closed or invalid.Since you say cin, I'm going to assume you're coding in C++. This is a safe way of getting strings from std::cinvoid get_input(){ std::cout << getting input << std::endl; std::string input; while (std::cin >> input) { // Good, got something from cin std::cout << * << input << std::endl; } std::cout << out of input loop << std::endl; std::cout << std::cin.eof() << std::endl; std::cout << std::cin.bad() << std::endl;}This is a bad way of getting user input:void bad_input(){ std::cout << getting input << std::endl; std::string input; while (!std::cin.bad()) { std::cin >> input; // BAD: not checking if the extractor succeeded std::cout << input << std::endl; // do stuff } // Not reached if `std::cin` reaches EOF std::cout << out of input loop << std::endl;}Since a stream at eof isn't bad(), this will loop forever once cin reaches OEF. There are many variations for this (both good and bad versions), and similar problems can arise in plain C (and many other languages) for similar reasons. |
_webapps.108532 | I'm working with repeat groups. As soon as I input a number of repeats for the repeat group to run over, I get this error:cannot convert multiple nodes to a raw value. Refine path expression to match only one node.How should I begin to troubleshoot? | Cannot convert to multiple nodes error message in CommCare | commcare | That repeat group number has to be a single hidden value reference (such as /data/num_children). You cannot have a raw number like 5 and you also cannot have a calculation such as /data/num_children + 1. |
_unix.244875 | I am trying to use a .htaccess file to setup specific behaviors for one directory.My .htaccess is as follows:ErrorDocument 401 /var/www/secret/logging.phpAuthName My Password Protected SiteAuthUserFile /var/www/secret/.htpasswdAuthType BasicRequire valid-user# Set REMOTE_USER env variable on 401 ErrorDocumentRewriteEngine OnRewriteBase /secret/RewriteCond %{ENV:REDIRECT_STATUS} ^401$RewriteRule .* - [E=REMOTE_USER:%{ENV:REDIRECT_REMOTE_USER}]However, when attempting to test this, the Apache default error page states a 404 was encountered while trying to use an ErrorDocument to handle the request. All permissions are correct, all filepaths are correct.What am I doing wrong? | ErrorDocument not working with .htaccess file | apache httpd | null |
_unix.288715 | Test video https://twitter.com/NHL/status/740577888735526912. In ChromiumUnsuccessfuly attemptsI followed the guide here > https://get.adobe.com/flashplayer/ > 64 bit apt Ubuntu 10+. After install, I get the notice you already have the plugin. masi@masi:~$ sudo apt-get install adobe-flash-properties-gtkmasi@masi:~$ sudo apt-get install adobe-flashpluginIn Firefox, the .swf files work with the plugin browser-plugin-gnash however. Internal differences of two systems - Ubuntu's glue!Please, see my answer about Debian 8.5 for the case where the hardware is more stable: Asus Zenbook UX303UA. The solution works with only a single package in Debian, while Ubuntu requires also the second package. This proposes me that there is something internal going on in Ubuntu, which should be profiled and fixed. Flash Player: gnash 0.8.11Internet browser: Chromium, 51.x, Google Chrome 52.xSystem: Ubuntu 16.04 64 bitHardware: Macbook Air 2013-mid | Why internal differences in Flash Player of Ubuntu and Debian? | debian;ubuntu;chrome;adobe flash | Gnash can't work with Chromium. Uninstall it first before doing the following installation. The solution is to install Google's PepperFlash plugin (disclaimer: nonfree) and the freshplayer component:sudo apt install pepperflashplugin-nonfree browser-plugin-freshplayer-pepperflash |
_scicomp.687 | In an application I have to solve a series of positive definite linear systems of the form $A^TA x = A^Tb$ (i.e. normal equations). The next system is obtained from the previous one by adding and/or removing a small number of columns to $A$ (usually one or two). The vector $b$ stays the same throughout. It seems clear that some kind of up-/downdating strategy should be applied, however, my questions are:What kind of up-/downdating shall I choose (QR, Cholesky, Matrix-Inversion-Lemma,others?,...)?On what conditions and requirements shall I make my choice (high precision needed, ill-conditioned matrices, well-conditioned ones, speed,...)?P.S.: You may assume that $A$ and $A^T$ can be applied fast. | Up-/downdating methods for a series of normal equations | linear algebra | null |
_unix.93054 | I've been looking for an all around Linux Programmers manual but there isn't one... So that leads me to ask if the Unix Programmers Manual is relevant for Linux?The manual is here: http://cm.bell-labs.com/7thEdMan/v7vol1.pdf | Is the Unix Programmers Manual relevant for Linux? | linux;documentation;programming | The Unix Programmers Manual you linked to is probably mostly relevant for Linux also. However, that manual was published in 1979. Things have changed since then in all descendants of the original Unix. |
_unix.255092 | Many Linux players (like Audacious, Banshee, Amarok, Exaile) can easily access audio CDs tracks info (names and other metadata) but Deadbeef cannot, although it has a cdda plugin that should do just that.Along VLC, Amarok, Rhythmbox, Xine and Kaffeine, Deadbeef is one of the players that can read CD-Text (tracks info accessible offline, from the cd itself), but it oddly fails at accessing online CDDB, a somewhat trivial task these days.Can those settings be adjusted to make this work? | Deadbeef audio player does not retrieve online (freedb, CDDB) info about CD tracks | audio;music player;audio cd;file metadata;deadbeef | The problem is with the option Prefer CD-Text over CDDB (under Preferences-Plugins-Audio CD player-Configure): that should NOT be checked.When it was, instead of preferring CD-Text when available, it just showed CD-Text and never CDDB info. And as CD-Text is usually absent, it showed generic names of tracks ('Track 1, 2 etc) even if CDDB data was available and CD-Text was not. (It surely looks like a bug.) |
_webmaster.26180 | I have discovered several review sites that link to blog reviews on the same subject.How do these review sites get their links and can this be done programmatically?One example is this site (Look under Bloggers' Review).Another example is urbanspoon.com which also has Blogger Reviewsection. | How do review sites backlink to review blogs? | blog | null |
_unix.141301 | What does the -z flag mean in the code below:if [ -z $TEST_PARAM ]; thenAnd is there a list of such flags?For a flag like ls -l, I know where to find it, but for a single flag, I didn't get any website describes it. | what does the -z flag mean here | shell script;test | -z STRING means:the length of STRING is zeroYou can see a list of all of these with man test.[ is an alias for the test command, although usually implemented by your shell in practice. You probably have a /bin/[, though. All of these -X tests are options to test. |
_codereview.118290 | I have a list of non-unique values. I want to output a list of the same length where each value corresponds to how many times that value has appeared so far.The code I have written to do this seems over-complicated, so I think there has to be a better way.x = [1,1,2,3,1,3]def times_so_far(ls): out = [0]*len(x) counted = {} for i,v in enumerate(x): if v in counted: counted[v] += 1 else: counted[v] = 0 out[i] = counted[v] return outtimes_so_far(x)#[0, 1, 0, 0, 2, 1] | Count how many times values has appeared in list so far | python;algorithm | Maybe using list.count() you can achieve the same with less lines?x = [1,1,2,3,1,3]def times_so_far(ls): out = [0]*len(ls) for i in xrange(len(ls)): out[i] = ls[:i].count(ls[i]) return outThis can be written with list comprehension as mentioned by Caridorc, and it removes the first len(ls) call this way (though maybe at the cost of resizing out for every element of the list):def times_so_far(ls): return [ls[:i].count(ls[i]) for i in xrange(len(ls))]Now, if you're going to work with lists of positive integers of a small value, I would recommend the following, as it's similar to yours but it works with indices instead of dict keys:def times_so_far(ls, maxValue): temp = [0]*(maxValue+1) out = [0]*len(ls) for i in xrange(len(ls)): out[i] = temp[ls[i]] temp[ls[i]] += 1 return out |
_unix.191348 | Using PulseAudio is awesome as long as everything works as expected, but it can also be a huge pain in the neck.Recently, I found myself glancing at pavucontrol more often than I'd like to, because PA seems to remember every change I made. For example, I occasionally use pavucontrol whenever I run a game and maybe TeamSpeak at the same time, so I get to hear everything as I want. I think, that's about the average scenario where PA is awesome.What bothers me: If I don't reset the game output volume (or whatever I wanted to shut up for maybe just a moment) to 100%, it just stays, even through reboots. So next time I fire up the game it caps at maybe 50% volume and I might end up in extensive research what went wrong ... just to find out the PA-slider was still down (which requires me to start pavucontrol). And sometimes I see sliders in weird positions, of streams which I can't even remember to have touched ...So I want PulseAudio to forget the Application/Stream specific settings and reset every slider to 100% at reboot.There has to be either a setting, or this could be achieved by a script. Not sure where to begin. | Reset PulseAudio (Application) Sliders on reboot? | pulseaudio;volume | null |
_codereview.42550 | I got a random image rotator working by using the following script (demo). But I was told that it is a bad practice to extend Array.prototype. And it does. It conflicts with the chained select box unless I modify the selected box script. So I guess it's better to not use Array.prototype.shuffle ,isn't it? Here's The script: Array.prototype.shuffle = function() { var s = []; while (this.length) s.push(this.splice(Math.random() * this.length, 1)); while (s.length) this.push(s.pop()); return this; } var picData = [ ['img1','url_1'], ['img2','url_2'], ['img3','url_3'], picO = new Array(); randIndex = new Array(); for(i=0; i < picData.length; i++){ picO[i] = new Image(); picO[i].src = picData[i][0]; picO[i].alt = picData[i][1]; randIndex.push(i); } randIndex.shuffle(); window.onload=function(){ var mainImgs = document.getElementById('carouselh').getElementsByTagName('img'); for(i=0; i < mainImgs.length; i++){ mainImgs[i].src = picO[randIndex[i]].src; mainImgs[i].parentNode.href = picData[randIndex[i]][1]; mainImgs[i].alt = picData[randIndex[i]][1]; } }I'm not sure where to start. I'm reading this article, should I do something like Array.shuffle = function() {for(var a=[];this.length;)a.push(array.splice(Math.random()*array.length,1));for(;a.length;)this.push(a.pop());return this};Would anyone please point me in some directions to rewrite that part? | Trying to convert an extended Array.prototype to a function | javascript;jquery;array | null |
_unix.336688 | I've got the following script:#!/bin/bashSINGLE=`cut -c 7-21 Data.txt`cd ../FASTA_SEC/for i in ${SINGLE}; do if [ -r ../FASTA_SEC/${i}.fa ]; then HEAD=`sed -n 2p ../FASTA_SEC/${i}.fa | head -c 3` TAIL=`tail -c 4 ../FASTA_SEC/${i}.fa` if [ ${HEAD} = AAA ] then echo Cut heading A's $i elif [ ${TAIL} = AAA ] then echo Cut tailing A's $i while [ `tail -c 2 ../FASTA_SEC/$i.fa` == A ] do TRITAIL=`cat ../FASTA_SEC/$i.fa` echo ${TRITAIL/A/} > ../FASTA_SEC/$i.fa done fi else echo does not exist $i fidoneIt seems to work in all processed text files including the while loop. But there are a couple of text files where all A's are removed and some spaces are introduced instead of deleting only the tailing A's.I'm quite surprised because it actually works but in some cases it produces a mess. Let me show you an example:Input file which contains A tailing:>B4-0K032_18670_015NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNGNNNTAGATACAAGCGAGCGGCGGACGGGTGAGTAACACGTGGGTAACCTGCCCAAGAGACTGGGATAACACCTGGAAACAG[Cuted here for shortness]GGNTGTCNTCNGCTNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNAAAAAAAAOutput messed up file:>G4-0K047_18670_010 NNNNNNNNNNCCNCCTGTNNNTTTGCCCCCGGGGGCCTGTCTCTCGGTGTC GTGTCGCCTGGTGGTTCTTCGCGTTGCTTCGTTCCCTGCTCCC[Cuted here for shortness]CGTCCGCCNTCGTTCCTGNTGTCTCGGTGCNNGCCCGTNTNNNNNNNNNN NNNNNNNNNNNNNI want only tailing A's to be cut but in some text files a mess occurs but in most of them it works smoothly. In some files where tailing A's are supposed to be trimmed I get this mess (even other characters might are deleted as well..).I wonder wwy it does work in some cases but in some it does not..Would there be a way to trim tailing A's? | Problem Trimming tailing characters | bash;shell script;string;tail;bioinformatics | The whole script ends up depending of this two lines to remove trailing A's:tritail=$(cat ../FASTA_SEC/$i.fa)echo ${tritail/A/} > ../FASTA_SEC/$i.faSince you are already placing the whole file content in a variable, you do not need a loop to remove all trailing A's. You could just do:tritail=$(cat ../FASTA_SEC/$i.fa)shopt -s extglobecho ${tritail#+(A)} > ../FASTA_SEC/$i.faOr, if you dislike changing the extglob setting:tritail=$(cat ../FASTA_SEC/$i.fa)echo ${tritail%${tritail##*[!A]}} > ../FASTA_SEC/$i.faIn fact, those two commands is all you need to remove trailing A's.The second line works by selecting all the trailing A's. Or, as the command actually does it, by removing everything that is not an A ([!A]) at the leading part of the variable:tail=${tritail##*[!A]} # Select all the trailing A'sAnd then, the resulting string is removed from the trailing part of the variable:result=${tritail%$tail} # Remove the trailing A'sBoth parameter expansions are join together into one single command:result=${tritail%${tritail##*[!A]}}And that is what is sent to the (modified) file:echo ${tritail%${tritail##*[!A]}} > ../FASTA_SEC/$i.faTo remove leading A's, switch all the selections:echo ${tritail#${tritail%%[!A]*}} > ../FASTA_SEC/$i.fa |
_scicomp.26178 | Note: This was cross-posted from comp-sci, as I didn't know this community existed!I have a problem which I'm looking to see if there is literature on:Consider three types of actors, a Director, Aggregator, and Follower. The Director talks to multiple Aggregators, the Aggregator talks to multiple Followers. The director gives simple commands to the Aggregator, who then can portion out the commands to each Follower as she sees fit.The question then is, how can the Director know whether or not an Aggregator can complete a given request at time step T? T+1? If T is now, then this is relatively easy as the Aggregator can simply sum up the capabilities of each of the Followers and return it, saying this is what I can do in total. The problem then is, if the Director is doing her own optimization problem in deciding how to direct two different Aggregators, given each command she must be able to predict how the Aggregator will react. I.e., what are the Aggregator's capabilities in time step T+1 given a direction D in time step T?Due to the complexity of the Aggregator, I think it's likely best to create an estimator across the current state of the Aggregator (or all of their followers). Further, the Aggregator can give whatever knowledge it wants to the Director, though ideally this would be of constant size no matter the size of the set of Followers. This is therefor an optimization problem on the Aggregator's side for creating an optimal estimator, which is well studied.What I want to know: Is there any literature about creating an estimator when you know the exact function you are estimating? So if I am the aggregator, how can I tell the Director, in a constant space for the amount of information I give no matter the number of followers, the information require to best predict I would react to a given direction?Put another way: How can I create an optimal estimator in which I have full knowledge of the shape and composition of the functions I am estimating?I can think of a number of places where this might occur, potentially in networking, data compression, etc., though I think I don't have the necessary vocabulary. I've tried searching through aggregation, optimization, estimation, forecasting, prediction, which a number of different combinations of keywords relating to these. There is a ton of generalized work on making estimators and predictors, though none which target the assumption that they already have perfect knowledge of that which they're estimating.[Post note after finding this stack exchange]I read a bit, finding this for instance, and felt that my question was still unique. In this case all functions are known beforehand. | Optimizing estimator of composed functions when function is known | optimization;reference request;machine learning | null |
_codereview.28315 | This function code works very slowly. How can I speed it up?CREATE OR REPLACE FUNCTION bill.ReportIngredients( _from date, _to date, _beginning_date date, _has_inventory boolean, _inventory_id uuid, _restaurant_id uuid, _stock_id uuid, _ingredientIds uuid [], _sort_by character varying, _limit integer, _offset integer ) RETURNS TABLE( json json ) AS$BODY$declare ingredientFilter character varying = ''; ingredient_id uuid; ss_date date;begin if ( _ingredientIds is not null ) then ingredientFilter = 'and i.id IN ('; FOREACH ingredient_id in array _ingredientIds loop ingredientFilter := ingredientFilter || '''' || ingredient_id || ''','; end loop; Select trim(trailing ',' from ingredientFilter) into ingredientFilter; ingredientFilter := ingredientFilter || ') '; end if; if ( _has_inventory ) then return query execute 'select array_to_json(array_agg(row_to_json(t))) From ( Select i.id, i.title, ( ( SELECT coalesce(sum(ii.delta_count), 0) FROM inventory_ingredients ii Inner Join inventories inven On inven.id = ii.inventory_id WHERE ii.ingredient_id = i.id And inven.is_active = true And inven.stock_id = ''' || _stock_id || ''' And inven.id = ''' || _inventory_id || ''' ) + ( SELECT coalesce(sum(ii.count), 0) FROM invoice_ingredients ii Inner Join invoices invo On invo.id = ii.invoice_id WHERE ii.is_active = true And ii.ingredient_id = i.id And invo.is_active = true And invo.restaurant_id = ''' || _restaurant_id || ''' And invo.receiver_id = ''' || _stock_id || ''' And invo.date >= ''' || _beginning_date || ''' And invo.date < ''' || _from || ''' ) + ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.receiver_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _beginning_date || ''' And r.date < ''' || _from || ''' ) - ( SELECT coalesce(sum(wi.count), 0) FROM write_off_ingredients wi Inner Join write_offs w On w.id = wi.write_off_id WHERE wi.ingredient_id = i.id And w.is_active = true And w.stock_id = ''' || _stock_id || ''' And w.date >= ''' || _beginning_date || ''' And w.date < ''' || _from || ''' ) - ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.sender_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _beginning_date || ''' And r.date < ''' || _from || ''' ) - ( Select (( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _beginning_date || ''' And bc.date < ''' || _from || ''' And bc.calculate_type = ''subtract'' And b.bill_type <> 5 ) - ( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _beginning_date || ''' And bc.date < ''' || _from || ''' And bc.calculate_type = ''add'' And b.bill_type <> 5 )) AS sum ) ) AS start_count, ( SELECT coalesce(sum(ii.count), 0) FROM invoice_ingredients ii Inner Join invoices invo On invo.id = ii.invoice_id WHERE ii.is_active = true And ii.ingredient_id = i.id And invo.is_active = true And invo.restaurant_id = ''' || _restaurant_id || ''' And invo.receiver_id = ''' || _stock_id || ''' And invo.date >= ''' || _from || ''' And invo.date <= ''' || _to || ''' ) AS invoice_count, ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.receiver_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _from || ''' And r.date <= ''' || _to || ''' ) AS relocation_in_count, ( SELECT coalesce(sum(wi.count), 0) FROM write_off_ingredients wi Inner Join write_offs w On w.id = wi.write_off_id WHERE wi.ingredient_id = i.id And w.is_active = true And w.stock_id = ''' || _stock_id || ''' And w.date >= ''' || _from || ''' And w.date <= ''' || _to || ''' ) AS write_off_count, ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.sender_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _from || ''' And r.date <= ''' || _to || ''' ) AS relocation_out_count, ( Select (( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _from || ''' And bc.date <= ''' || _to || ''' And bc.calculate_type = ''subtract'' And b.bill_type <> 5 ) - ( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _from || ''' And bc.date <= ''' || _to || ''' And bc.calculate_type = ''add'' And b.bill_type <> 5 )) AS sum ) AS solds_count, ( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _from || ''' And bc.date <= ''' || _to || ''' And bc.calculate_type = ''add'' And b.bill_type <> 5 ) AS resign_count From ingredients i Where i.is_active = true And i.restaurant_id = ''' || _restaurant_id || ''' ' || ingredientFilter || ' Group by i.id order by ' || _sort_by || ' limit ' || _limit || ' offset ' || _offset || ' ) t'; else return query execute 'select array_to_json(array_agg(row_to_json(t))) From ( Select i.id, i.title, ( ( SELECT coalesce(sum(ii.count), 0) FROM invoice_ingredients ii Inner Join invoices invo On invo.id = ii.invoice_id WHERE ii.is_active = true And ii.ingredient_id = i.id And invo.is_active = true And invo.restaurant_id = ''' || _restaurant_id || ''' And invo.receiver_id = ''' || _stock_id || ''' And invo.date >= ''' || _beginning_date || ''' And invo.date < ''' || _from || ''' ) + ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.receiver_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _beginning_date || ''' And r.date < ''' || _from || ''' ) - ( SELECT coalesce(sum(wi.count), 0) FROM write_off_ingredients wi Inner Join write_offs w On w.id = wi.write_off_id WHERE wi.ingredient_id = i.id And w.is_active = true And w.stock_id = ''' || _stock_id || ''' And w.date >= ''' || _beginning_date || ''' And w.date < ''' || _from || ''' ) - ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.sender_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _beginning_date || ''' And r.date < ''' || _from || ''' ) - ( Select (( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _beginning_date || ''' And bc.date < ''' || _from || ''' And bc.calculate_type = ''subtract'' And b.bill_type <> 5 ) - ( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _beginning_date || ''' And bc.date < ''' || _from || ''' And bc.calculate_type = ''add'' And b.bill_type <> 5 )) AS sum ) ) AS start_count, ( SELECT coalesce(sum(ii.count), 0) FROM invoice_ingredients ii Inner Join invoices invo On invo.id = ii.invoice_id WHERE ii.is_active = true And ii.ingredient_id = i.id And invo.is_active = true And invo.restaurant_id = ''' || _restaurant_id || ''' And invo.receiver_id = ''' || _stock_id || ''' And invo.date >= ''' || _from || ''' And invo.date <= ''' || _to || ''' ) AS invoice_count, ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.receiver_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _from || ''' And r.date <= ''' || _to || ''' ) AS relocation_in_count, ( SELECT coalesce(sum(wi.count), 0) FROM write_off_ingredients wi Inner Join write_offs w On w.id = wi.write_off_id WHERE wi.ingredient_id = i.id And w.is_active = true And w.stock_id = ''' || _stock_id || ''' And w.date >= ''' || _from || ''' And w.date <= ''' || _to || ''' ) AS write_off_count, ( SELECT coalesce(sum(ri.count), 0) FROM relocation_ingredients ri Inner Join relocations r On r.id = ri.relocation_id WHERE ri.ingredient_id = i.id And r.is_active = true And r.restaurant_id = ''' || _restaurant_id || ''' And r.sender_stock_id = ''' || _stock_id || ''' And r.date >= ''' || _from || ''' And r.date <= ''' || _to || ''' ) AS relocation_out_count, ( Select (( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_solds bcs on bcs.id = bc.object_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _from || ''' And bc.date <= ''' || _to || ''' And bc.calculate_type = ''subtract'' And b.bill_type <> 5 ) - ( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _from || ''' And bc.date <= ''' || _to || ''' And bc.calculate_type = ''add'' And b.bill_type <> 5 )) AS sum ) AS solds_count, ( SELECT coalesce(sum(bc.count), 0) FROM bill_calculations bc Inner Join bill.bill_course_resigns bcr on bcr.id = bc.object_id Inner Join bill.bill_course_solds bcs on bcs.id = bcr.bill_course_sold_id Inner Join bill.bills b on b.id = bcs.bill_id WHERE bc.ingredient_id = i.id And bc.stock_id = ''' || _stock_id || ''' And bc.date >= ''' || _from || ''' And bc.date <= ''' || _to || ''' And bc.calculate_type = ''add'' And b.bill_type <> 5 ) AS resign_count From ingredients i Where i.is_active = true And i.restaurant_id = ''' || _restaurant_id || ''' ' || ingredientFilter || ' Group by i.id order by ' || _sort_by || ' limit ' || _limit || ' offset ' || _offset || ' ) t'; end if;end;$BODY$ LANGUAGE plpgsql STABLE COST 50 ROWS 1000;ALTER FUNCTION bill.ReportIngredients(date, date, date, boolean, uuid, uuid, uuid, uuid[], character varying, integer, integer) OWNER TO developer;EXPLAIN ANALYZE resultResult (cost=0.00..5.13 rows=1000 width=0) (actual time=38859.253..38859.254 rows=1 loops=1) Total runtime: 38859.296 ms | Optimize postgres function | optimization;sql;postgresql | null |
_unix.154386 | About 1 month ago I installed the newest version of Fedora, so that I had both Windows and Fedora on one machine. Today I installed some software and some updates and rebooted the system, but unfortunately Fedora won't start anymore:It just shows me the Fedora logo instead of the login screen Update: My graphic card is AMD Radeon HD 5000 Series. | Fedora won't start after update | fedora;startup | null |
_reverseengineering.15499 | I've been trying to use IDA Pro as a database to aid me in reverse engineering GBA games. I didn't know how to gdb connect the VisualBoyAdvance or No$GBA emulators to IDA pro, but I managed to do it with the mGBA emulator. But when I add a breakpoint at a specific function and resume the process, it somehow doesn't break, but it does recognize that there is a breakpoint there, and causes weird glitches to happen. In my case, in-game objects suddenly disappear, and the function that was supposed to execute, either does not, or does not execute correctly. I apologize that I don't have more concrete data, since I don't know how to approach this... | Adding breakpoint to GBA games emulated by mGBA with IDA Pro | ida | null |
_unix.41753 | Unix is not my native language and I'm getting confused by their concept of filesystems.When I look at my free space I see:/$ df -khFilesystem Size Used Avail Use% Mounted on/dev/xvda1 7.9G 7.1G 397M 95% /none 3.7G 120K 3.7G 1% /devnone 3.7G 4.0K 3.7G 1% /dev/shmnone 3.7G 48K 3.7G 1% /var/runnone 3.7G 0 3.7G 0% /var/lock/dev/xvdf 100G 19G 82G 19% /db/dev/xvdg 100G 15G 86G 15% /images/dev/xvdb 414G 199M 393G 1% /mntTo me this means all files and directories under /db is on filesystem xvdf, everything under /images is on xvdg and everything under /mnt is on xvdb. Everything else is on xvda1.However, xvda1 has only 7.9G of space. So why does/$ sudo du -sh var25G varshow me that /var is taking up 25G? I thought at first that maybe it's counting the contents at the destinations of symbolic links but I know a few directories down there's a symbolic link to the /images directory and that's got 86G of content so var should be >86G if symbolic links are followed.So how can /var take up 25G on a drive that has only 7.9G?btw, this is an ubuntu instance running in amazon's EC2, if that's significant. | How does this directory use so much space | linux;filesystems;disk usage | This will give you proper answer of your trouble.du -ch --max-depth=1 -x /var-x will show only data usage of one file-system so skipping other filesystem's content from /var directory --max-depth=1 will give data usage of only first level e.g. /var/a /var/b and so on |
_unix.230355 | For instance, let's say I mounted dev/sda1 and dev/sda2 in the distant past. I'm in media and I see folders drive1 and drive2. What command can I use to see which one is sda1 and which one is sda2? | How do I find which external drive a folder is mounted from? | mount | lsblk should do the trick. Or mount. Or findmnt. |
_unix.225621 | I want to install claws-mail into my centos7 with three different methods,all of them fails.method1:intall directly[root@localhost ~]# yum install claws-emailLoaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfile * base: mirrors.163.com * epel: ftp.cuhk.edu.hk * extras: centos.ustc.edu.cn * updates: mirrors.pubyun.comNo package claws-email available. method2:install from rpm package.I have downloaded claws-mail-3.12.0-1.fc24.x86_64.rpm from official web.[root@localhost ~]# rpm -ivh /root/Downloads/claws-mail-3.12.0-1.fc24.x86_64.rpm warning: /root/Downloads/claws-mail-3.12.0-1.fc24.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 81b46521: NOKEYerror: Failed dependencies: libcompface.so.1()(64bit) is needed by claws-mail-3.12.0-1.fc24.x86_64 libetpan.so.17()(64bit) is needed by claws-mail-3.12.0-1.fc24.x86_64 libgnutls.so.30()(64bit) is needed by claws-mail-3.12.0-1.fc24.x86_64 libgnutls.so.30(GNUTLS_3_4)(64bit) is needed by claws-mail-3.12.0-1.fc24.x86_64 liblockfile.so.1()(64bit) is needed by claws-mail-3.12.0-1.fc24.x86_64 libpisock.so.9()(64bit) is needed by claws-mail-3.12.0-1.fc24.x86_64 I want to install the depended package first.[root@localhost ~]# yum install -y libcompface.so.1Loaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfile * base: mirrors.163.com * epel: ftp.cuhk.edu.hk * extras: centos.ustc.edu.cn * updates: mirrors.pubyun.comNo package libcompface.so.1 available.Error: Nothing to do[root@localhost ~]# yum install -y libcompface.soLoaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfile * base: mirrors.163.com * epel: ftp.cuhk.edu.hk * extras: centos.ustc.edu.cn * updates: mirrors.pubyun.comNo package libcompface.so available.Error: Nothing to do[root@localhost ~]# yum install -y libcompfaceLoaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfile * base: mirrors.163.com * epel: ftp.cuhk.edu.hk * extras: centos.ustc.edu.cn * updates: mirrors.pubyun.comNo package libcompface available.Error: Nothing to domethod3:install according the tutorial .http://linuxpitstop.com/install-claws-mail-3-12-on-ubuntu-linux/For Fedora: Once these dependencies have been installed, download the new version of Claws mail from following URL.yum install -y libc6 libcairo2 libcompfaceg1 libdbus-glib-1-2 libenchant1c2a libgdk-pixbuf2.0-0 libglib2.0-0 libgtk2.0-0 libice6 libldap-2.4-2 libpango1.0-0 libpisock9 libsm6 xdg-utilsNo package available.Error: Nothing to doMaybe the problem is repo files?How to add repo in my centos7? | how to install claws-mail rpm package? | centos | null |
_codereview.172673 | This is my first code here and also my first program of this size. I don't really know what is expected from a programmer who writes good, readable code. This is my first program which will be used in a real-world application. Also I'm extremely new to Python. So while reviewing please be kind enough to give constructive criticism about how this code or my code in general can be better with respect to both Python and programming in general. I'll try to explain the problem in the following paragraph in the best way possible. If any clarifications are needed about my code/logic/the problem, feel free to ask in the comments, I'll try my best to clear the doubts.The problem - Consider two files.Each containing a list of strings.One list has strings of some combination of 'a','t','g', and 'c'One list has strings of some combination of 'A',U','G', and 'C'I have to convert the strings from the capitalized list as a's tot's, c's to g's, u's to a's and g's to c's [ a-t, c-g, g-c, u-a ].And another special condition is that there can be at most of twoinstances where u's convert to g's and/or g's convert to t's [ u-g,g-t ]The conversions only need to be done for four regions of the strings, indices 2-7(6 characters), 2-8(7 characters), 1-7(7 characters) and 1-8(8 characters), provided the starting index is 1After generating all possible conversions, I have to check each of them against all the strings in the other list and find out the locations where they match.If you are looking for an output of sorts, I won't be able to provide it yet, since the comparisons I need to do are about (38869 * 2588 * all possibble combinatons of each of the 2588) + time taken to generate all the permutations. So my machine is extremely inadequate of doing something like that.My Program -## Date : 2017-08-10## Author : dadyodevil## Contact : [email protected]#### A python program to detect all indices of complimentary Micro-RNA(miRNA) target sites on Messenger-RNAs(mRNA)#### As an input, this program needs two lists - ## 1. A list of mRNAs where each entry is represented in a two line format:## >hg19_refGene NM_032291 range=chr1:67208779-67210768...## Sequence of mRNA## 2. A list of miRNAs where each entry is represented in a two line format:## >hsa-miR-576-3p MIMAT000...## Sequence of miRNA#### Pre-requisites for the reader - ## 1. Understanding of programming concepts## 2. A moderate understanding of the Python programming language version 2.7## 3. Knowledge of terms regarding miRNA-mRNA target detectionimport redef extractSeed(miRNA): ## There are 4 seed regions with indices from 2-7, 2-8, 1-7 and 1-8 miRNAfor6mer.append(miRNA[1:7][::-1]) miRNAfor7mer.append(miRNA[1:8][::-1]) miRNAfor7a1.append(miRNA[:7][::-1]) miRNAfor8mer.append(miRNA[0:9][::-1])def createCompliment(allCompliments, miRNA, wobbleCount, compliment): ## For the compliment, the convertions include a:t, u:a, g:c, c:g and for Wobble-Pairs, u:g and g:u if wobbleCount == 2: for letter in miRNA: if letter == 'a': compliment += 't' elif letter == 'c': compliment += 'g' elif letter == 'g': compliment += 'c' else: compliment += 'a' allCompliments.append(compliment) else: for index, letter in enumerate(miRNA): if letter == 'a': compliment += 't' elif letter == 'c': compliment += 'g' elif letter == 'g': createCompliment(allCompliments, miRNA[index+1:], wobbleCount + 1, compliment + t) createCompliment(allCompliments, miRNA[index+1:], wobbleCount + 1, compliment + c) compliment += 'c' elif letter == 'u': createCompliment(allCompliments, miRNA[index+1:], wobbleCount + 1, compliment + g) createCompliment(allCompliments, miRNA[index+1:], wobbleCount + 1, compliment + a) compliment += 'a' ## Now that all possibilities are generated, the duplicates need to be removed allCompliments = sorted(list(set(allCompliments)))def checkForMatch(miRNACompliments, seedRegion, miRNAname): ## Each miRNA that is recived by this function will be compared against the whole list of mRNAs and the matching indices will be saved ## Since the mRNA sequences are in alternate lines the sequences will be extracted as such and the when matches are found, the name of the mRNA will be extracted from teh index just before the current one for index in range(1, len(mRNA_List), 2): for entry in miRNACompliments: mRNA = mRNA_List[index] matchesStart = [m.start() for m in re.finditer(entry, mRNA)] if (len(matchesStart) > 0): mRNAname = mRNA_List[index-1][14:mRNA_List[index-1].find( ,15)] matchesEnd = [] for index2 in range(0, len(matchesStart)): matchesEnd.append(matchesStart[index2] + len(entry)) allindices = zip(matchesStart, matchesEnd) complimentarySiteList.append([miRNAname, mRNAname, seedRegion, allindices])def prepareForMatch(miRNA, miRNAname): global miRNAfor6mer, miRNAfor7mer, miRNAfor7a1, miRNAfor8mer miRNAfor6mer, miRNAfor7mer, miRNAfor7a1, miRNAfor8mer = [], [], [], [] ## First the seed sites will be extracted and reversed extractSeed(miRNA) ## Empty lists will be generated to store all the compliments miRNAfor6mer.append([]) miRNAfor7mer.append([]) miRNAfor7a1.append([]) miRNAfor8mer.append([]) ## Then the compliments will be generated from the seed regions along with atmost of two Wobble-Pairs miRNAfor6mer.append(createCompliment(miRNAfor6mer[1], miRNAfor6mer[0], 0, )) miRNAfor7mer.append(createCompliment(miRNAfor7mer[1], miRNAfor7mer[0], 0, )) miRNAfor7a1.append(createCompliment(miRNAfor7a1[1], miRNAfor7a1[0], 0, )) miRNAfor8mer.append(createCompliment(miRNAfor8mer[1], miRNAfor8mer[0], 0, )) ## After generating all possible compliments, they will be checked for matching sites checkForMatch(miRNAfor6mer[1], 6mer, miRNAname) checkForMatch(miRNAfor7mer[1], 7mer, miRNAname) checkForMatch(miRNAfor7a1[1], 7A1, miRNAname) checkForMatch(miRNAfor8mer[1], 8mer, miRNAname)def Main(): global mRNA_List, miRNA_List, complimentarySiteList miRNA_List = open('miRNA_list.txt').read().splitlines() mRNA_List = open('mRNA_list.txt').read().splitlines() complimentarySiteList = [] ## Since the sequences are in every alteRNAte lines, the 'index' needs to be incremeted by 2 to access only the sequences ## The miRNA lengths are also checked whether they are atleast 8 neucleotides long, if they are not, they will not be checked for index in range(1,len(miRNA_List),2): miRNAname = miRNA_List[index-1][5:miRNA_List[index-1].find(' ')] if (len(miRNA_List[index]) < 8): print %s at %d has insufficient length. %(miRNAname, index) else: prepareForMatch(miRNA_List[index].lower(), miRNAname) for entry in complimentarySiteList: print entryif __name__ == '__main__': Main() | Python program to check substring match locations with a lot of permutations of the substring | python;beginner;strings;recursion | Please stop abusing lists. Mutations are hard to reason with, and so when a function can mutate the data it makes the function a lot harder to understand.The function createCompliment is doesn't return anything, instead it mutates allCompliments. This mutation doesn't work when you assign to it, such as on the last line. allCompliments = sorted(list(set(allCompliments))). This does nothing, as you don't use it afterwards.Rather than using two slow for loops in createCompliment, you could instead do all the standard conversions, and then handle the special conversions, by looping through all the combinations of the special indexes.By this, if you perform the loop when if wobbleCount == 2:, first, so that you get the basic conversion, then you don't have to care about them, when doing the special conversions. By this, if you have the input ccagaa, then you convert it to ggtctt, without caring about g. The simplest way to do this would be to use str.translate.After that, you want to convert the special conversions, which are g -> t and u -> g. However, since we performed the above, they are c -> t and a -> g. To convert these, you want to get the indexes of c and a. Which you can do with a list comprehension. [i for i, c in enumerate(rna) if c in 'ac'].After this you want to convert all combinations of one to two occurrences of these characters. This means we can use itertools.combinations to loop through all the combinations we want to change.Finally, we have to convert the values, and so making a copy of the list using [:], which is a slice over the entire list. Then looping through the indexes, we can convert the value in the list, and yield the string version of the list.An example of this is:We start with rna = 'cagu', we convert it to the basic conversion, gtca. After this, we get all the indexes of the special characters, which are [2, 3]. We then go through all combinations of these, which are [(2,), (3,), (2, 3)], and yield the converted word, being gtta, gtcg, and gttg.The simplest way to think of yield is as array.append. So the following to functions, are kinda the same:def fn_1(): yield 1 yield 2def fn_2(): array = [] array.append(1) array.append(2) return arraydef fn_3(): return [1, 2]list(fn_1()) == fn_2() == fn_3() # TrueTo simplify check_for_match, as you're looping through a flattened list of 2d tuples, you want to un-flatten the list. So [0, 1, 2, 3] would become [(0, 1), (2, 3)], allowing for the simpler looping method of for a, b in ....To do this, you could use the grouper recipe:def grouper(iterable, n, fillvalue=None): Collect data into fixed-length chunks or blocks # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args)The way this works is as [item] * n doesn't perform a copy on item, and by exploiting how iterators work. The former means that [item] * 2 is the same as [item, item], rather than say [item, copy(item)]. This is important, as this ensures that both items are the same iterator.Using a single iterator multiple times is important as zip basically uses [(next(it), next(it)), (next(it), next(it)), ...], it's a little more complex, as it works with any size it, and also knows when it stops. However it's pretty much how it works.You should follow PEP8.And so I'd change your code to:import reimport stringimport itertoolsTRANS = string.maketrans('acgu', 'tgca')CONVS = {'a': 'g', 'c': 't'}SEEDS = [ 6mer, 7mer, 7A1, 8mer]def create_compliments(rna): rna = rna.translate(TRANS) yield rna all_indexes = [i for i, c in enumerate(rna) if c in CONVS] rna = list(rna) for n in (1, 2): for indexes in itertools.combinations(all_indexes, n): t = rna[:] for index in indexes: t[index] = CONVS[t[index]] yield ''.join(t)def grouper(iterable, n, fillvalue=None): Collect data into fixed-length chunks or blocks # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return itertools.izip_longest(*args, fillvalue=fillvalue)def check_for_match(mi_RNAs, seed, mi_RNA_name, m_RNA_list): mi_RNAs = list(mi_RNAs) for m_RNA_name, m_RNA in grouper(m_RNA_list, 2): m_RNA_name = m_RNA_name[14:m_RNA_name.find( , 15)] for entry in mi_RNAs: matches = [m.start() for m in re.finditer(entry, m_RNA)] if matches: all_indices = tuple( (match, match + len(entry)) for match in matches ) yield mi_RNA_name, m_RNA_name, seed, all_indicesdef prepare_for_match(mi_RNA, mi_RNA_name, m_RNA_list): mi_RNAs = [ mi_RNA[1:7][::-1], mi_RNA[1:8][::-1], mi_RNA[:7][::-1], mi_RNA[0:9][::-1] ] for mi_RNA, seed in zip(mi_RNAs, SEEDS): for entry in check_for_match(create_compliments(mi_RNA), seed, mi_RNA_name, m_RNA_list): yield entrydef main(): mi_RNA_list = open('miRNA_list.txt').read().splitlines() m_RNA_list = open('mRNA_list.txt').read().splitlines() for index in range(1, len(mi_RNA_list), 2): mi_RNA_name = mi_RNA_list[index-1][5:mi_RNA_list[index-1].find(' ')] if (len(mi_RNA_list[index]) < 8): print {} at {} has insufficient length..format(mi_RNA_name, index) else: for entry in prepare_for_match(mi_RNA_list[index].lower(), mi_RNA_name, m_RNA_list): print tuple(entry)if __name__ == '__main__': main() |
_codereview.48502 | I'm changing the inner implementation of a project. In order to do so, I've created an interface that will be implemented in 2 different ways.One of this ways is by class A, which is a wrapper for an outside class (class B) from a .dll file (a product of other team).Class B is a private a member of class A. Class B ctor takes an argument, which does not change during the run of my application. It needed to be created only once, and to stay available for class A everywhere in the code.Class A is an implementation of interface. It use the capabilities of class B in order to implement it's functions, and obviously needed to be available also everywhere in the code. I've concluded that:Class A has to be:explicitly created once (hence, not static) only once, (because I need B to be created only once.) accessible from anywhere in the codehave a member (B) that must initialized once, and only once (private member, needed only inside class A)Concerning condition #4, ideally I would like to initialize B in the constructor.A bit similar to singleton pattern, with the exception of wanting to initialize a member in the constructor.I've come to a solution, and would like to get feedback.public sealed class A{ private static SomeClass B = null; // the must initialized only once member // setting B: private void setB(int i) { B = new SomeClass(i); } // ctor public A(int i) { if(B == null) setB(i); else throw new Exception(An instance of A can be created only once); } }The idea is to assign the class to static object at the beginning of the code. It's not very neat, but it compiles and seems to do the job just right. I don't use singleton since it won't be possible to initialize the member in the ctor. By the way, thread safety is not a concern here. SomeClass needed only inside class A. SomeClass comes from dll, and class A kind of wrapping it. A does answering cross-cutting concern, it is an implementation of Interface used all over the code. I've tried to implement singleton, but as much as I tried it didn't answer my needs. | Singleton-like pattern for a project | c#;singleton | null |
_softwareengineering.326035 | I'm trying to figure out how to do something, and I can't quite seem to get it to work. Let me describe the situation:Using a hosts file, we redirect the resources (CSS/JS/etc) of a website, let's say blah.website.com, to our local machine 127.0.0.1.We then can do some development on any JS/CSS/etc on our local machine. Let's say the only change we do is making the background: green;.This allows us to see our changes to the website, blah.website.com without messing with anyone else's view. Only our computer can see the green background when we go to blah.website.com; if anyone else goes there, they don't see it. E.g., if a resource, the.css on the website is located at blah.website.com/the.css, we can have our own version of the.css on our local machine somewhere (127.0.0.1) that is loaded instead (assuming I've set up the hosts correctly, which I have).Here's where my problem comes in: I want to be able to see these changes on other devices, such as a phone. That is, when I go to blah.website.com on a different device, such as my phone, I want to see the green background. Note that I want to do this without changing the files on blah.website.com. How can I do this? (Please note: I have to develop on OSX :P) Steps I've taken:I've tried sharing internet with the phone (have my laptop broadcast WiFi that my phone can connect to), however, despite the laptop being able to see the green background, my phone can't. It seems the phone ignores the hosts file on the laptop, even though the laptop is what is supplying the internet.Thanks all :)EDIT:Also, I'd like to clarify: Only our local machine (let's say our laptop) has the changes. The server and the second device (let's say our phone) do not have the changes. Ideally, no changes should be made to the second device (e.g., the second device's hosts file) in order for it to see the green background. That is, the second device should just connect to the laptop or something like that and be able to see the changes as well. | Viewing local changes to website on separate device | web development;websites;networks | null |
_cstheory.7862 | Given an integer $N$ of length $n$ bits, how hard is it to output the number of prime factors (or alternatively number of factors) of $N$?If we knew the prime factorization of $N$, then this would be easy. However, if we knew the number of prime factors, or the number of general factors, it is not clear how we'd find the actual prime factorization.Is this problem studied? Are there known algorithms that solve this question without finding the prime factorization?This question is motivated by curiosity and partially by a math.SE question. | How hard is it to count the number of factors of an integer? | cc.complexity theory;counting complexity;nt.number theory;factoring | This isn't my answer, but Terrence Tao gave a beautiful answer to this question on MathOverflow.Here are the first few lines of his answer. To read the complete answer, follow the link.There is a folklore observation that if one was able to quickly count the number of prime factors of an integer n, then one would likely be able to quickly factor n completely. So the counting-prime-factors problem is believed to have comparable difficulty to factoring itself.(I wasn't sure whether this should be an answer or a comment. But it is really an answer, although it isn't written by me. I've made the answer Community Wiki so that it may be upvoted or accepted without unnecessarily giving me reputation.) |
_webmaster.76868 | I am trying to work out how to redirect an existing website to a new intermediate page which then links back to the customers existing website. I can change DNS records to point to the new hosting server but problem is how to redirect from there back to their existing website.Their existing website only works when it is called using the domain name, do an nslookup on the domain name and try and use the ip number to access it fails with 'You don't have permission to access / on this server.' I guess it is probably hosted on some sort of VPS which operates using the URL in the header.Any suggestions how I can do this redirection. | How to redirect a website to a holding page with a link back to the original website | redirects | null |
_unix.48087 | Drive A is 2TB in a closet at home.Drive B is 2TB in my office at work.I'd like drive A to be the one I use regularly andto have rsync mirror A to B nightly/weekly.The problem I have with this is that multiple users havestuff on A.I have root run rsync -avz from A to $MYNAME:BRoot can certainly read everything on A, but doesn'thave permission to write non-$MYNAME stuff on B.How am I supposed to be doing this? Should I have apasswordless private key on A that logs into root on B?That seem's super dangerous.Also, I'd prefer to use rsnapshot but it looks like they demand that I draw from B to A using the passwordless private key to root's account that I'm so frightened by. | How do I backup via rsync to a remote machine, preserving permissions and ownership? | ssh;permissions;backup;rsync;rsnapshot | If it is intended as a backup (I'm looking at the tag), not as a remote copy of working directory, you should consider using tools like dar or good old tar. If some important file gets deleted and you won't notice it, you will have no chance to recover it after the weekly sync.Second advantage is that using tar/dar will let you preserve ownership of the files.And the third one - you will save bandwidth because you can compress the content. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.