id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.327285
Similar to this thread, I have a remote machine with 8 cores that I want to use for running scripts in parallel (1 script per core at a time).However, I don't have multiple bash scripts but a single Python3 script that I want to run with different inputs. I tried parallel python3 -c main.py input*, parallel -j 100% python3 -c main.py ::: input*, and parallel python3 main.py input* but nothing worked.The exact error message is:parallel: Error: -g has been retired. Use --group.parallel: Error: -B has been retired. Use --bf.parallel: Error: -T has been retired. Use --tty.parallel: Error: -U has been retired. Use --er.parallel: Error: -W has been retired. Use --wd.parallel: Error: -Y has been retired. Use --shebang.parallel: Error: -H has been retired. Use --halt.parallel: Error: --tollef has been retired. Use -u -q --arg-sep -- and --load for -l.I don't understand how this is related to my input. I didn't use any of these options.I'm fairly new and inexperienced with Unix and couldn't get it to work myself or with googling. Any help is appreciated. Do I have to write a shell-script to help me with that?
Parallel Python scripts on a remote machine
shell script;python;remote;parallelism
The problem was actually with how parallel was installed on the remote machine (running the newest Ubuntu). I came across a thread solving my problem:Run sudo rm /etc/parallel/config after installation on Ubuntu to get rid of the config which caused my error messages.The command I use to run my python script with different inputs in parallel is: parallel -j 100% python3 main.py ::: inputs*Nevertheless, thanks to everyone who was helping!
_webapps.92113
Does deleting my uploads delete them from soundcloud.com or will they still be live because people reposted them?
If I delete my own uploads are they deleted from Soundcloud if they've been reposted?
soundcloud
null
_datascience.9818
Neural networks get top results in Computer Vision tasks (see MNIST, ILSVRC, Kaggle Galaxy Challenge). They seem to outperform every other approach in Computer Vision. But there are also other tasks:Kaggle Molecular Activity ChallengeRegression: Kaggle Rain prediction, also the 2nd placeGrasp and Lift 2nd also third place - Identify hand motions from EEG recordingsI'm not too sure about ASR (automatic speech recognition) and machine translation, but I think I've also heard that (recurrent) neural networks (start to) outperform other approaches.I am currently learning about Bayesian Networks and I wonder in which cases those models are usually applied. So my question is:Is there any challenge / (Kaggle) competition, where the state of the art are Bayesian Networks or at least very similar models?(Side note: I've also seen decision trees, 2, 3, 4, 5, 6, 7 win in several recent Kaggle challenges)
Is there any domain where Bayesian Networks outperform neural networks?
machine learning;pgm
One of the areas where Bayesian approaches are often used, is where one needs interpretability of the prediction system. You don't want to give doctors a Neural net and say that it's 95% accurate. You rather want to explain the assumptions your method makes, as well as the decision process the method uses. Similar area is when you have a strong prior domain knowledge and want to use it in the system.
_softwareengineering.72206
does Java have graphs as an intergrated data structure? How about Python? I was assigned to write a program, that solves the TSP (travelling salesman problem) via the GRASP (greedy randomized adaptive search procedure). I'm just familiarizing myself with GRASP, and I would like to have a good working data structure for graphs, that includes plotting the graph and the option to assign special colour to edges (so I can colour the final solution: cheapest hamiltonian path). I'm gonna have a presentation, explaining my final solution, whence the need for plotting the graph. Also, it would be desirable to have the option to generate a random graph on n vertices, so I have some easily accessible examples.I was really hoping this has been done by someone before, so I don't start from scratch. I'm a mathematician (or atleast trying to be), so please, no fancy programmer slang.thank you
graph data structure in Java (or Python)
java;python;data structures
For python.http://networkx.lanl.gov/http://cneurocvs.rmki.kfki.hu/igraph/also check out graphviz.org. you generate a text file, feed it to graphviz, and it makes a graph as png, pdf, etc.
_webapps.8786
I notice that when I use Google Voice on my iPhone (through the web interface) and I tap a number to call a contact, it asks if I want to place the call or not. However, instead of placing a call to my contact's phone number, it places it to some random number in a completely different area code. My guess is that this is one of Google's phone numbers that aren't currently in use and it knows how to handle the call I place to that number.My questions are as follows:If I call this number without using the Google Voice interface, will it always call the same contact? Will it ever change? (If so, I'm thinking I'll add a Google Voice number to each of my contacts and call this through the Phone app instead of having to launch the browser each time I want to place a call.)Is there an easy way to find out what this custom number is for each contact, or is the only way to place a call to them?Can the same trick be used for sending text messages to their phone number through Google Voice?
Custom calling numbers for Google Voice
google voice
null
_unix.306614
Bluehost Shared Server ruby -v 2.2.2rails -v 5.0.0.1gem -v 2.4.5~/.bashrcexport HPATH=$HOMEexport GEM_HOME=$HPATH/ruby/gemsexport GEM_PATH=$GEM_HOME:/lib64/ruby/gems/1.9.3export GEM_CACHE=$GEM_HOME/cacheexport PATH=$HPATH/ruby/bin:$PATHexport PATH=$HPATH/ruby/gems/bin:$PATHexport PATH=$HPATH/ruby/gems:$PATHClean Install, but when creating new app it throws an invalid platform error. create vendor/assets/javascripts/.keep create vendor/assets/stylesheets create vendor/assets/stylesheets/.keep remove config/initializers/cors.rb run bundle install`x64_mingw` is not a valid platform. The available options are: [:ruby, :ruby_18, :ruby_19, :ruby_20, :mri, :mri_18, :mri_19,:mri_20, :rbx, :jruby, :mswin, :mingw, :mingw_18, :mingw_19, :mingw_20] run bundle exec spring binstub --all`x64_mingw` is not a valid platform. The available options are: [:ruby, :ruby_18, :ruby_19, :ruby_20, :mri, :mri_18, :mri_19,:mri_20, :rbx, :jruby, :mswin, :mingw, :mingw_18, :mingw_19, :mingw_20]Gemfile# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'gem 'rails', '~> 5.0.0', '>= 5.0.0.1'# Use sqlite3 as the database for Active Recordgem 'sqlite3'# Use Puma as the app servergem 'puma', '~> 3.0'# Use SCSS for stylesheetsgem 'sass-rails', '~> 5.0'# Use Uglifier as compressor for JavaScript assetsgem 'uglifier', '>= 1.3.0'# Use CoffeeScript for .coffee assets and viewsgem 'coffee-rails', '~> 4.2'# See https://github.com/rails/execjs#readme for more supported runtimes# gem 'therubyracer', platforms: :ruby# Use jquery as the JavaScript librarygem 'jquery-rails'# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinksgem 'turbolinks', '~> 5'# Build JSON APIs with ease. Read more: https://github.com/rails/jbuildergem 'jbuilder', '~> 2.5'# Use Redis adapter to run Action Cable in production# gem 'redis', '~> 3.0'# Use ActiveModel has_secure_password# gem 'bcrypt', '~> 3.1.7'# Use Capistrano for deployment# gem 'capistrano-rails', group: :developmentgroup :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platform: :mriendgroup :development do # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. gem 'web-console' gem 'listen', '~> 3.0.5' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0'end# Windows does not include zoneinfo files, so bundle the tzinfo-data gemgem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]Would that mean only comment out gem tzinfo-data, or are other changes required as well?
x64_mingw not a valid platform - Rails 5
ruby;xming;gem;rails
null
_unix.178522
For some reason, my system sets an environment variable with no name. This can be seen in the output from printenv as a line containing only = and causes problems for Python (more specifically the os.environ object).How do I unset this environment variable? Is there any other workaround (e.g. prevent the variable to be set in the first place)?To reproduce do e.g. env -i printenv, or for the Python problem do env -i = python -c import os; os.environ.clear()
Unsetting environment variable with an empty name
environment variables
Environment variables aren't supposed to have an empty name, so many utilities don't support them.The env command from GNU coreutils supports setting the environment variable with an empty name but not unsetting it. That's a bug.$ env '=wibble' env |grep wibble =wibble$ env '=wibble' env -u '' envenv: cannot unset `': Invalid argumentCommon shells can't unset the empty name either. That's ok, since the empty name isn't supposed to be used as an environment variable, and can't be used as a shell variable. Zsh is the only buggy one in the lot: it pretends to do the job but in fact does nothing.$ env '=wibble' dash -c 'unset 'dash: 1: unset: : bad variable name$ env '=wibble' bash -c 'unset 'bash: line 0: unset: `': not a valid identifier$ env '=wibble' ksh -c 'unset 'ksh[1]: unset: : invalid variable name$ env '=wibble' mksh -c 'unset 'mksh: : is read only$ env '=wibble' posh -c 'unset 'posh: unset: is read only$ env '=wibble' zsh -c 'unset '$ env '=wibble' zsh -c 'unset ; env' | grep wibble=wibblePython, as you've noticed, bugs out when it finds the empty name for an environment variable.Perl has no such problem, so it may be a solution for you. Note that you have to execute a new shell to use an external process to change the environment.perl -e 'delete $ENV{}; exec $ARGV[0] @ARGV' $SHELL -$-
_codereview.15835
I understand that this animation code is outdated:[UIView beginAnimations:@Move context:nil];[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];[UIView setAnimationDelay:0.08];self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);[UIView commitAnimations];What are the modern best practices for achieving the same result?
Upgrading animation code
objective c;ios;animation;cocoa touch
In iOS 4 and later you are encouraged to use animation blocks.[UIView animateWithDuration: 0.5f delay: 0.08f options: UIViewAnimationCurveEaseIn animations: ^{ self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); } completion: ^(BOOL finished){ // any code you want to be executed upon animation completion }];One advantage of using block-based animation is thatWhen this code executes, the specified animations are started immediately on another thread so as to avoid blocking the current thread or your applications main thread.This means that the rest of your application will not be locked up while your animation is executing.
_unix.365276
I understand that we must first create a file system on our physical block device before mounting it successfully (to define which drivers to use and how to control the underling disk), but I'm left wondering which parts of the file system are needed to successfully mount.My intuition tells me that just the superblock should be needed, but I'm unsure of how to go about testing or verifying this.From the kernel's point of view, what would be the minimal amount of file system information needed to mount a disk? The Super Block? The Super Block and other information (like an I-node table)?
What file system information is needed to mount a disk?
linux;filesystems;mount;superblock
null
_unix.305796
I am trying to delete all *.pyc and pycache, and any other silly files languages need to run that i don't want to see. The closest I've gotten issudo rm -rf **/*__pycache__answer, which doesn't work deep down the path, and sudo rm -R -f {__pycache__,.*.pyc}which didn't work for pycache folder. webapi/__pycache__webapi/cool_app/__pycache__webapi/cool_app/bad_file.pycwebapi/cool_app/keep_this_awesomeness.pywebapi/cool_app/sweet_folder/__pycache__webapi/cool_app/sweet_folder/bad_file.pycwebapi/cool_app/sweet_folder/keep_this_awesomeness.pyOnly webapi/cool_app/keep_this_awesomeness.py webapi/cool_app/sweet_folder/keep_this_awesomeness.pyremain. Any help awesome, ty
recursively delete all files, empty directories, and directories with files of multiple names under current directory, including current directory
linux;ubuntu;files;find;rm
find . \( -name __pycache__ -o -name *.pyc \) -delete
_unix.241823
Essentially I need to create a code that backs up files. One of the specifications is that if there is a .pdf file (lets call it test1.pdf for example) and a .doc file with the exact same name (test1.doc) then the code is meant to only copy the .doc file.I'm a huge Linux noob so I won't be able to do any advanced methods, here's what I've got so far, the code does 90% of what it's meant to do except this final requirement. I've utilized a for loop:for file in $(find ${sourcePath} -name *.pdf); dofileName=$(echo ${file} | cut -d '.' -f1)if $(find $(sourcePath) -name ${fileName}.doc &>/dev/nulll; then echo Sorry, a .doc file with that extension already exists, skipping copy continuefidoneI'm sure people will find out instantly why it doesn't work (I'm just that bad) but essentially what this loop is doing when I run the script via bash -x is:Checks for any files with .pdfRemoves the name before the .Checks for any other files with the same filename before the . and if it's a .doc file it echos a warning messageProblem is, the code still copies the files anywayI suspect it's because I've not specified WHAT the code should do if it finds the two files but I'm really clueless here. Any help?Here's my full code for reference.#!/bin/bashsourcePath=$1destPath=$2Filedoc=*.docFilepdf=*.pdfFilePDF=*.PDFif [[ $# -ne 2 ]]; then echo Usage ; dar doc_path archive_path exit 1fiif [ ! -d sourcePath ] then echo Directory does not existfiif [ ! -d destPath ] then mkdir -p $destPathfifor file in $(find ${sourcePath} -type f -exec basename {} \; | sort | uniq -d); do num=1 fileName=$(echo ${file} | cut -d '.' -f1) fileExtension=$(echo ${file} | cut -d '.' -f2) dirName=$(dirname ${duplicate}) for duplicate in $(find ${sourcePath} -name ${file} | tail -n +2 ); do mv ${duplicate} ${duplicate}${fileName}_${num}.${fileExtension} echo Renamed duplicate file ${duplicate} ${duplicate}_${num}.${fileExtension} (( num = num + 1 )) donedonefor file in $(find ${sourcePath} -name *.pdf); do fileName=$(echo ${file} | cut -d '.' -f1) if $(find $(sourcePath) -name ${fileName}.doc &>/dev/nulll; then echo Sorry, a .doc file with that extension already exists, skipping copy continue fidonefind ${sourcePath} -name $Filedoc -exec cp -r {} ${destPath} \;find ${sourcePath} -name $FilePDF -exec cp -r {} ${destPath} \;
How to skip a file with a specific file extension if there is another file (with another extension) with the exact same filename?
bash
null
_webapps.54855
I have the following data in a Google Spreadsheet:1 shiplu rice2 sharmin rice3 sharmin fast food4 sharmin salad5 rafiq burger6 nazia noodles7 rafiq salad8 rafiq noodles9 nazia rice10 razib riceThe first column is in fact a timestamp, but I used integer to make it more readable.The other columns are username and food item.I need to get the last food inputed by an user. The output should looke like this:1 shiplu rice4 sharmin salad8 rafiq noodles9 nazia rice10 razib riceI used the following query, but it does not give the desired output:=QUERY(A1:C10;select B, C group by B order by A)How can I achieve this?This is the spreadsheet in question.
Group by and ordering inside a group in Google Spreadsheets
google spreadsheets;google spreadsheets query
null
_softwareengineering.260198
I wanted to as this question about VMs in general, but focused it to JVM implementations only so this doesn't get closed as too broad.The JVM has a concept of a heap. If my understanding is correct, the heap is simply the free store where you can save data, i.e. anywhere in RAM that doesn't have another purpose (such as the stack).When we say the heap in the context of the JVM, are we talking about somewhere inside the VM itself (which may or may not be allocated on the heap of the underlying physical computer)? Or do we refer to the heap of the physical computer?
Is the JVM heap inside the JVM software, or inside the physical computer?
virtual machine;jvm;cpu;heap
The specification is very clear about it 2.5.3. HeapThe Java Virtual Machine has a heap that is shared among all Java Virtual Machine threads. The heap is the run-time data area from which memory for all class instances and arrays is allocated.The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java Virtual Machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements. The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.A Java Virtual Machine implementation may provide the programmer or the user control over the initial size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the maximum and minimum heap size.The following exceptional condition is associated with the heap:If a computation requires more heap than can be made available by the automatic storage management system, the Java Virtual Machine throws an OutOfMemoryError.To answer your question:When we say the heap in the context of the JVM, are we talking about somewhere inside the VM itself (which may or may not be allocated on the heap of the underlying physical computer)? Or do we refer to the heap of the physical computer?When we speak of heap, we speak of already allocated memory for the JVM. So, it is inside (?) the JVM (if that makes any sense to say). The JVM has its own memory management.
_unix.72988
I just upgraded my gnome-terminal to use 256 colors, yet I am a bit puzzled on the reason why a terminal emulator can't support the full palette any modern desktop environment provides. I guess there's a technical reason for this, but I am not aware of it.
Why don't Linux terminal emulators support full colors?
linux;terminal;gnome terminal
null
_webmaster.10412
Right now I'm using statcounter and Google analytics. They are great. But my counts are currently separated. Ex: website.com = 1000 visits a day, website.com/about = 50 visits a day, website.com/privacy = 10 visits a day, etc..How can have a combined count of all of my sub-pages? (mainpage + about page + about 100 other sub-pages )I can of course manually add them all together, but that's time consuming because there are many pages. I tried placing a separate tracking code in a PHP include that sits in each of the sub-pages, but it doesn't seem to be working. It seems to require a single URL to create it, which it then only counts the visits from the one URL, rather than ALL of them. Ex: website.com)
how can i track visits to ALL of the subpages of my website COMBINED TOGETHER?
google analytics
I'm confused about the issue here - On Google Analytics this is in the top site usage section of the dashboard and on statcounter it's on the summary report (the first one on the list).
_unix.197355
Fedora's ability to forward ports using the apparently native networking software, firewalld, appears to continue to be broken beyond credulity. Please note that it hasn't really worked since at least Fedora 19 (see https://serverfault.com/questions/541087/fc19-firewalld-debugging-help-requested-ports-not-forwarding)Note that it can't even permanently put an interface into a given zone in the current (21) release (with all updates through to this date) - a fundamental capability for this software, to be sure, as evidenced here, https://serverfault.com/questions/683783/fedora-21-firewalld-firewall-cmd-wont-permanently-assign-interfaces-to-zones/683792#683792.As suggested by the accepted answer under this question, https://serverfault.com/questions/524200/configuring-firewalld-in-fedora-18-19IP tables is still in use under the sheets with firewalld (firewall-cmd). I have had NO SUCCESS whatsoever with getting firewalld (firewall-cmd) to successfully do any port forwarding - not that I've tried everything possible, but I've tried a lot - and it makes me wonder if it's even possible.Somehow, some way, we need to know if we should even BOTHER with this codeline. WHY ON EARTH should we spend DAYS of our time, individually (and collectively many man-years) if the codeline is so inept?! Maybe the authors should Pull The Code until it's READY for prime-time? MAYBE someone should say, No, use ip-tables until we fix this thing, quit wasting your time, sorry!What I can tell you DOES NOT WORK is a most basic example:Take the forwarding of a port of obscurity, say, 9876, from an external interface to port 22, the SSH port, to a particular internal system. So, on a newly installed system, after sorting out the IP addresses of the interfaces, assigning them permanently to their respective zones (see https://serverfault.com/questions/683783/fedora-21-firewalld-firewall-cmd-wont-permanently-assign-interfaces-to-zones/683792#683792), the forwarding is then assigned. First, the port is opened and then forwarded using something like this:firewall-cmd --zone=external --add-port=9876/tcpfirewall-cmd --zone=external --add-forward-port=port=9876:proto=tcp:toport=22:toaddr=192.168.1.1The problem is, this does NOT work. (The result is a simple timeout, nothing found in the logs.) I can provide citations to the documentation to support that this is the right syntax - that's trivial, however, I'd also like to point out that someone thinks this can work, here: http://www.certdepot.net/rhel7-get-started-firewalld/. I'd like to know how they managed it! Or, is this a difference between the codelines of Fedora and Centos and / or RHEL7?!I'm thinking that after the failures of this codeline from Fedora 19 through to 21, it's been released WAY before its time. But, I'd be delighted to learn I'm wrong. Otherwise, I'm BACK TO IP-TABLES, and not happy about it.
Fedora 21 Port Forwarding with firewalld (firewall-cmd); how does it REALLY work? Or, does it?
iptables;fedora;port forwarding;firewalld
null
_unix.136228
There are two files called install.log and install.shThe find command will find both of these and pass them to -exec lsWith the addition of an or (-o), it only passes one argument to -exec lsWithout an -exec, find does indeed find all the filesSame with anything passed to -exec, like cat. It doesn't get passed all the arguments.Why is there a suddenly difference when I use an or (-name install.log -o -name install.sh) vs. when I use a wildcard (-name install.\*)?
-exec isn't being passed all the files found by find
find;exec
null
_webmaster.27309
Small team of developers doing their work here and there. We have a team leader, and is sole responsible for uploading updated source files from the development server to the production server. So let's say, so if an updated files needs to be uploaded to the prod server, that concerned developer shall notify the team lead about it, and then the team lead will update the files to the prod server. So no developer has an access to the prod server except for the team lead. That's our current setup.Now, what we want to do is to give developers a way for uploading their updated files to the server without the team lead intervening in the process. What do you think is the best way to go about this?
Best way for developers to upload files to production server
development
null
_cs.80013
If we view the value table of a function as a long string (concate row after row), we can ask what its kolmogorov complexity is. My question is, taking all of those functions with Alice and Bob each getting n bits, what is the average communication complexity over all functions with kolmogorov complexity under k?
Average communication complexity with limitied kolmogorov complexity
combinatorics;communication complexity
null
_unix.39071
When I type in google.com, firefox tells me that the server is not found. When I type in the IP address of google, it works just fine.I was playing with this computer at another place and it didn't have any problems.I have no idea what's wrong. Also: this is a fresh install and the computer is a little old.
debian, problem with DNS
debian;dns
The configuration file /etc/resolv.conf contains information that allows a computer connected to a network to resolve names into addresses.Change it to, for example, Google's DNS servers:nameserver 8.8.8.8nameserver 8.8.4.4Also check that your dhclient is activated.http://www.malgouyres.fr/linux/configreseau_en.html#resolv
_webmaster.98675
I have an issue that I really cannot wrap my head around and was hoping that someone could help me with. I manage a e-commerce website that is active on multiple markets. Two with a marketspecific domain (mysite.co.uk and mysite.nl) and four with subfolder URLs (mysite.com/ie, mysite.com/fr etc)The websites have the same content, product pages, architecture etc and managed by home made CMS. Problem is that when looking in the GA Search Console > Links to your site report the mysite.co.uk has about 10K links from mysite.com and the mysite.com/market have about 300K from mysite.com.The only place where we link from one market to another is in the footer, and I have no idea why the difference is so big. if the mysite.com links 300K times that should be the same towards .co.uk as for the .com/fr. On the .com sites we have gotten a manual action against Unnatural links to your site, and we can see loss in organic traffic. The only difference between .co.uk and .com in inbound links is the huge amount from our own domain on .com. Anyone have any idea what have happend and possible solutions?
Issue with huge amount of inbound links for multiple sub folder website
google search console;links
null
_unix.349968
I currently have problems determining if the hypervisor bit (31 bit) is set to true using CPUID on command line.I'm using the following command cpuid -1 -r to retrieve the hex data as shown in the screenshot below.I'm unsure how exactly to retrieve the hypervisor bit value from this list of hex values.Any help on solving this problem would be appreciated.
How to check if the hypervisor present bit is set using CPUID
linux;cpu;x86
I would just use the textual representation given by cpuid by default:cpuid -1 | grep 'hypervisor guest status'If you really want to use the raw values, you need to filter on CPUID#1 and then check that ECX is greater than or equal to 0x80000000:cpuid -1 -r | grep '^ 0x00000001.*ecx=0x[89a-f]'If that produces output, the bit is set, otherwise it isnt; you can also use grep's exit status.
_codereview.163620
I'm looking for guidance/review on an approach that I've taken.StructureWindows ServiceShopify Module (API)Official Shopify APIThe Scenario Our Windows Service connects to the Shopify Module which in turn connects to the Shopify API - I chose to build a custom Micro Service pattern where as the e-commerce module (Shopify module + others) pulls down/maps a common set of objects, which ultimately is pushed into our data module.Everything works perfectly and the Windows Service doesn't need to know where the data is coming from, just that it needs to conform to a common set of objects.Snippet (Method)As described, the Windows Service will check some configuration, call a module, which maps into data module objects, to pass to the data module. public List<Models.Model.DataAPI.Order> ParsedOrders() { //Get orders- deserializes into shopify objects var orders = Orders().Where(x => x.Order_Number != _identity.LastOrderNumber); var dataApiOrders = new List<Models.Model.DataAPI.Order>(); //Map/Parse orders into readable format for the data api foreach (var item in orders) { ////Randomly generate key as, a shipping line can be null and it needs to be unique passing up to the data api var shipping_method_id = Guid.NewGuid().ToString(); //Get Shipping Total var shippingLineItems = item.Shipping_Lines.FirstOrDefault(); if (shippingLineItems != null) { if (string.IsNullOrWhiteSpace(shippingLineItems.Price)) { shippingLineItems.Price = 0; } shippingLineItems.Id = shipping_method_id; } else { //Generate fake as shopify sometimes passes null line item shippingLineItems = new Models.Model.Shopify.ShippingLineItem(); shippingLineItems.Title = No Shipping Method; shippingLineItems.Id = shipping_method_id; shippingLineItems.Price = 0; } //Randomly generate key as shopify does not create a unique id for shipment var shipment_id = Guid.NewGuid().ToString(); //Map shipping method var dataApiShippingMethod = Models.Mapping.DataAPI.MapShippingMethod.ModelToEntityCollection(shippingLineItems); //Map Data Api Shipments var dataApiShipments = Models.Mapping.DataAPI.MapShipment.ModelToEntityCollection(item.Shipping_Address, shippingLineItems.Id, shipment_id); //Map DataApiCustomer var dataApiCustomer = Models.Mapping.DataAPI.MapCustomer.ModelToEntity(item.Customer); var dataApiproducts = new List<Models.Model.DataAPI.Product>(); var productLineItems = item.Line_Items.OrderByDescending(x => x.Price); foreach (var l in productLineItems) { //Code Omitted, needs to call shopify again because the core request does not fetch image or variance //Map product into data api collection var dataApiProductModel = Models.Mapping.DataAPI.MapProduct.ModelToEntity(l, shipment_id, mainImageSRC); dataApiproducts.Add(dataApiProductModel); } //Map order offers var dataApiOrderOffers = Models.Mapping.DataAPI.MapOrderOffer.ModelToEntityCollection(item.Discount_Codes); //Get complete mapped order var dataApiOrder = new Models.Model.DataAPI.Order() { order_number = item.Order_Number, order_created_at = item.Created_At, total_shipping_price = Decimals.Parse(shippingLineItems.Price), currency = item.Currency, total_price = Decimals.Parse(item.Total_Price), total_tax = Decimals.Parse(item.Total_Tax), billing_address = new Models.Model.DataAPI.BillingAddress() { city = (item.Billing_Address != null) ? item.Billing_Address.City : , first_name = (item.Billing_Address != null) ? item.Billing_Address.First_Name : , last_name = (item.Billing_Address != null) ? item.Billing_Address.Last_Name : , address1 = (item.Billing_Address != null) ? item.Billing_Address.Address1 : , address2 = (item.Billing_Address != null) ? item.Billing_Address.Address2 : , phone = (item.Billing_Address != null) ? item.Billing_Address.Phone : , zip_postalcode = (item.Billing_Address != null) ? item.Billing_Address.Zip : , }, customer = dataApiCustomer, shipping_methods = dataApiShippingMethod, order_offers = dataApiOrderOffers, shipments = dataApiShipments, products = dataApiproducts }; dataApiOrders.Add(dataApiOrder); } return dataApiOrders; }To reiterate, I call the Shopify API, it then deserializes into Shopify objects, which I then map into data module objects. The Windows Service receives the data module objects which are pushed to the data module.
Manually mapping complex objects using Windows Service & Shopify
c#;api;e commerce
null
_cs.55353
What algorithm can be used to correct a two-bit error in a message protected by a 32-bit CRC, assuming the CRC polynomial allows that? I'm seeking something for 480-bit payload, able to detect uncorrectable errors, fast in the worst case, and compact.Because I have hardware support for that, I'm most interested in the CRC-32 IEEE 802.3 primitive polynomial (allowing two-bit error correction for payloads up to 2974 bits), $$x^{32}+x^{26}+x^{23}+x^{22}+x^{16}+x^{12}+x^{11}+x^{10}+x^8+x^7+x^5+x^4+x^2+x+1$$but the question is of theoretical interest for others, such as the CRC-32K polynomial proposed by Koopman (allowing two-bit error correction for payloads up to 16360 bits)$$(x+1)(x^3+x^2+1)(x^{28}+x^{22}+x^{20}+x^{19}+x^{16}+x^{14}+x^{12}+x^9+x^8+x^6+1)$$Assume payload data of $b$ bits (assimilated to the coefficients of a binary polynomial $B(x)$ of degree less than $b$), to which is appended a CRC computed with binary polynomial $P(x)$ of degree $c=32$, as $C(x)=(B(x)\;x^c)\bmod P(x)$. It is then stored in memory $b+c$ bits of $B(x)\;x^c+C(x)$. On reading is it computed the syndrome $S(x)=(B'(x)\;x^c+C'(x))\bmod P(x)$. Assuming there has been at most two bits in error, and $b$ is small enough:If $S(x)=0$, then there has been no error.Otherwise, if there exists $i$ with $0\le i<b+c$ such that $S(x)=x^i\bmod P(x)$, then there has been a single error, and $i$ tells where, allowing correction.Otherwise, there has been two errors and there exists $i$ and $j$ with $0\le i<j<b+c$ such that $S(x)=(x^j+x^i)\bmod P(x)$; again finding $(i,j)$ allows correction.The case of a single bit in error is relatively easy; that's a discrete logarithm problem, with an easy size versus speed compromise: we can have a precomputed table allowing solving in a single lookup for $i$ multiple of $k$, and use that $k$ times. But I'm stuck with the case of two bits where I have nothing much better than trying all $j$ and doing as for a single bit in error.
Correcting two-bit error using a CRC
error correcting codes;crc
One approach: Use a meet-in-the-middle algorithm. Build a precomputed table that stores $T_i = x^i \bmod P(x)$ for all $i$ up to the maximum message length. Now, given $S$, you are looking for $i,j$ such that $S = T_i + T_j$. This can be found by enumerating all $i$, and for each $i$, computing $S-T_i$ and checking whether it is present in the precomputed table.The running time is proportional to the maximum length of the message. I'd imagine that in a real deployment, two-bit errors will be rare enough that this running time is affordable. (If two-bit errors are common, then three-bit errors will have non-negligible probability, which is a problem of its own.)If you want to reduce space complexity, instead of storing the entire precomputed table and looking up $S-T_i$ in the table, compute the discrete log of $S-T_i$ for each $i$ using whatever method you prefer (such as the one you listed in your question).I don't know if there are smarter methods that exploit the structure of $\mathbb{F}_2^{32}$ in a more intelligent manner.
_unix.180315
UsingGNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)I am a bash scripting novice, not sure where to begin except at shebang #!. The following command.touch -a -m -t 201501010000.00 somefile.txt, will modify somefile.txt access time and modification time. Is there a way to have a bash script?Operating within the directory /mnt/harddrive/BASE/ Prompt user input for. somefilename.txt, or somedirectoryname.Prompt user input for. datetime sequence. Instead of using the current time-stamp, explicitly specify the time/date using -t and -d options. Recursively change/modify. atime, mtime on sub-directorys within the BASE directory and files within that sub-directory.ANDChange/modify. atime, mtime of somefilename.txt located in the /mnt/hardrive/BASE/ directory.Optional 6. Append mtime to somefilename and somedirectoryname before the file extension. ie: somefilename-01-01-2015.txt or somedirectoryname-01-01-2015. Prompt user: do you want to append mtime to somefilename.txt YES/NO if YES/NO continue. stat the directory and file output to the console or /tmp directory text file and display with cat then delete the sometmpfile rm -r.
Bash script, ask for user input, to change a directory, sub directorys, and file's mtime atime linux recursively
bash;shell script;files;date;touch
It could look like this:#!/bin/bash# 1. change directorycd /mnt/harddrive/BASE/ # 2. prompt for name of file or directoryecho -n file or directory name: # ... and read itread HANDLE# 2. b - check if it exists and is readableif [ ! -r $HANDLE ] then echo $HANDLE is not readable; # if not, exit with an exit code != 0 exit 2;fi# 3. prompt for datetimeecho -n datetime of file/directory: # ... and read itread TIMESTAMP# 4. set datetime for HANDLE (file or directory + files) find $HANDLE | xargs touch -a -m -t $TIMESTAMP# 5. ask, if the name should be changedecho -n change name of file by appending mtime to the name (y/n)?: # ... and read itread YES_NOif [ $YES_NO == y ]then # get yyyy-mm-dd of modification time SUFFIX_TS=$(stat -c %y $HANDLE | cut -f 1 -d ) # rename, supposed, the suffix is always .txt mv $HANDLE $(basename $HANDLE txt)-$SUFFIX_TS.txt # let HANDLE hold the name for further processing HANDLE=$HANDLE-$TIMESTAMP.$SUFFIXfi# 7. stat to consolestat $HANDLEThis is just partly tested, but should be a start.To get a an understanding of what is happening here, you should look up the following commands:echo, read, test, cut, touch, find, xargsBesides you should understand several basic bash concepts, i.e. parameter substitution, command substitution and pipes.
_softwareengineering.68201
Let us say, I am browsing the internet and stumble upon a SO answer/forum/blog with code that perfectly solves a problem I have. The only trouble is they didn't specify any sort of licensing for their code.Is this code usable in my project or would I break copyright laws?What would be required for me to include it in a closed source project?An open source project?What licenses would be compliant or non-compliant with it? (e.g. Could I take their code and release it with GPL code?)
Licensing for code that I find in forums or on SO?
licensing
IANALAt the bottom of each page on the StackExchange sites is a line that reads something like:site design / logo 2011 stack exchange inc; user contributions licensed under cc-wiki with attribution requiredSo, anything you find on StackExchange (including StackOverflow, ServerFault, and SuperUser) is licenced under the terms specified on the page.
_unix.291217
I use Ubuntu and someone advised me to change permissions to a file with sudo chmod +x .It is not clear to me if +x means to change permissions to something very general as 777 or 775, or something totally different.I've tried to Google +x unix and +x linux, but I couldn't find data regarding it in a fast search.Here are the orders I have done (thus I'm stuck in stage 4):install wgetrun wget http://files.drush.org/drush.pharrun sudo mv drash.phar /usr/local/bin/drushrun sudo chmod +x /usr/local/bin/drushtest drush
What does the argument +x means in Unix? (Regarding permissions)?
permissions
null
_unix.99332
How can I use mouse with panes in vim? I tried :set mouse=a but it does not seem to work when doing :sp or :vsp or vim -O
How can I enable mouse in Vim?
linux;vim
null
_unix.311036
For no reason LVM volume group is inactive after every boot of OS. Manual activation works fine. Didn't touch any configs for several months.I do not use RAID and OS is booting from usual partition.The only thing I do regularly is: apt-get update && apt-get upgrade.How can I force it to activate as it was a day ago?My system details:Linux server 4.4.0-36-generic #55-Ubuntu SMP Thu Aug 11 18:01:55 UTC 2016 x86_64 x86_64 x86_64 GNU/Linuxroot@server:~# pvdisplay --- Physical volume --- PV Name /dev/sdb VG Name data PV Size 2.73 TiB / not usable 3.46 MiB Allocatable yes (but full) PE Size 4.00 MiB Total PE 715396 Free PE 0 Allocated PE 715396 PV UUID Lcd805-EmRG-mk6o-eXgV-psP9-V6rp-7fGfderoot@server:~# vgdisplay --- Volume group --- VG Name data System ID Format lvm2 Metadata Areas 1 Metadata Sequence No 4 VG Access read/write VG Status resizable MAX LV 0 Cur LV 2 Open LV 2 Max PV 0 Cur PV 1 Act PV 1 VG Size 2.73 TiB PE Size 4.00 MiB Total PE 715396 Alloc PE / Size 715396 / 2.73 TiB Free PE / Size 0 / 0 VG UUID GlZi9o-8zQ2-Jnao-twAh-XjEE-mAEN-5EMOIfroot@server:~# lvdisplay --- Logical volume --- LV Path /dev/data/web LV Name web VG Name data LV UUID afnB4a-SCrl-XHDt-R1mb-flSc-Rto5-1CdaOJ LV Write Access read/write LV Creation host, time server, 2014-12-26 23:56:51 +0300 LV Status available # open 1 LV Size 2.00 TiB Current LE 524288 Segments 1 Allocation inherit Read ahead sectors auto - currently set to 256 Block device 252:0 --- Logical volume --- LV Path /dev/data/data LV Name data VG Name data LV UUID KKo37f-qg2a-VBUt-3Qch-ULhC-YccS-Iaxwxz LV Write Access read/write LV Creation host, time server, 2014-12-27 00:02:59 +0300 LV Status available # open 1 LV Size 746.52 GiB Current LE 191108 Segments 1 Allocation inherit Read ahead sectors auto - currently set to 256 Block device 252:1
LVM volume group is inactive after reboot of Ubuntu
ubuntu;lvm
null
_unix.321405
I have video playback issues with vlc while mplayer performs correctly.Sample fileCaminandes 1: Llama DramaType : Vido Codec : H264 - MPEG-4 AVC (part 10) (avc1) Resolution: 1920x1090 Display resolution: 1920x1080 Frame rate: 24 Decoded format: Planar 4:2:0 YUVStream 1 Type: Audio Codec: MPEG AAC Audio (mp4a) Channels: Stereo Sample rate: 44100 HzMy machineDell XPS 600i with Radeon R7 240Intel(R) Core(TM)2 Quad CPU Q8200 @ 2.33GHz : 2331,00MHzIntel(R) Core(TM)2 Quad CPU Q8200 @ 2.33GHz : 2331,00MHzIntel(R) Core(TM)2 Quad CPU Q8200 @ 2.33GHz : 2331,00MHzIntel(R) Core(TM)2 Quad CPU Q8200 @ 2.33GHz : 2331,00MHzVGA compatible controller : Advanced Micro Devices, Inc. [AMD/ATI] Oland PRO [Radeon R7 240] Audio device : Advanced Micro Devices, Inc. [AMD/ATI] Cape Verde/Pitcairn HDMI Audio [Radeon HD 7700/7800 Series]Using vlcWhen opening the video with vlc, it stutters to a point it is not watchable.vlc spits a lot of warnings about skipped frames:vlc -v 01_llama_drama_1080p.mp4 VLC media player 2.2.4 Weatherwax (revision 2.2.3-37-g888b7e89)[00000000006df178] core libvlc: Running vlc with the default interface. Use 'cvlc' to use vlc without interface.[00007f95a0c01598] mp4 stream warning: unknown box type btrt (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gsst (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gstd (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gssd (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gspu (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gspm (incompletely loaded)[00007f95a0c01598] mp4 stream warning: unknown box type gshh (incompletely loaded)[00007f95a0c01808] mp4 demux warning: STTS table of 1 entries[00007f95a0c01808] mp4 demux warning: STTS table of 1 entries[00007f95a0daa508] faad decoder warning: decoded zero sampleFailed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory[00000000007b9308] pulse audio output warning: starting late (-15366 us)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 84 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 44 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 88 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 47 ms)[00007f958c0c9318] core video output warning: picture is too late to be displayed (missing 85 ms)Those warnings go on forever.Using mplayerOn the other hand, it goes smooth with mplayer / smplayer:mplayer 01_llama_drama_1080p.mp4 MPlayer2 2.0-728-g2c378c7-4+b1 (C) 2000-2012 MPlayer TeamCannot open file '/home/jerome/.mplayer/input.conf': No such file or directoryFailed to open /home/jerome/.mplayer/input.conf.Cannot open file '/etc/mplayer/input.conf': No such file or directoryFailed to open /etc/mplayer/input.conf.Playing 01_llama_drama_1080p.mp4.Detected file format: QuickTime / MOV (libavformat)[lavf] stream 0: video (h264), -vid 0[lavf] stream 1: audio (aac), -aid 0, -alang undClip info: major_brand: mp42 minor_version: 0 compatible_brands: isommp42 creation_time: 2013-02-08 18:56:45Load subtitles in .Failed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory[vdpau] Error when calling vdp_device_create_x11: 1[VO_XV] It seems there is no Xvideo support for your video card available.[VO_XV] Run 'xvinfo' to verify its Xv support and read[VO_XV] DOCS/HTML/en/video.html#xv![VO_XV] See 'mplayer -vo help' for other (non-xv) video out drivers.[VO_XV] Try -vo x11.[ass] auto-openSelected video codec: H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 [libavcodec]Selected audio codec: AAC (Advanced Audio Coding) [libavcodec]AUDIO: 44100 Hz, 2 ch, floatle, 192.0 kbit/6.80% (ratio: 23999->352800)AO: [pulse] 44100Hz 2ch floatle (4 bytes per sample)Starting playback...VIDEO: 1920x1080 24.000 fps 2925.7 kbps (365.7 kB/s)VO: [x11] 1920x1080 => 1920x1080 Planar YV12 [swscaler @ 0x7f1c88119640]using unscaled yuv420p -> bgra special converterColorspace details not fully supported by selected vo.A: 3.1 V: 3.1 A-V: 0.001 ct: 0.002 0/ 0 6% 49% 1.0% 0 0 And when I say smooth, I mean it. All 4 cores are around 30-45%.But... why ?Any idea why mplayer outperforms vlc so much on this?Any setting I could check/enforce on vlc?Is it possible mplayer makes better use of my hardware (GPU)?
vlc can't play H264 smoothly while mplayer can
performance;video;vlc;mplayer
null
_cogsci.8192
My friend is working on a robot that can be mind controlled. He basically wears a headset, and that headset translate brain signal into control signal to move a robot. https://www.youtube.com/watch?v=XewJh_0nLvMWhat could be the potential advantage of these kind of robots versus robots controlled by remotes (99.99% of all robots nowadays)?
Neural robots vs conventional robots
eeg;artificial intelligence
The advantage (at the current state of the technology) is that you don't need to use a remote with your hands, so the paralyzed could move their exoskeletons, for instance. For now, there is still the downside that the the device needs to be trained and the commands that can be read are rather simplistic. However, in the future these types of devices will greatly enhance human-computer interaction by allowing the brain the communicate in the same way as it communciates naturally with the environment. So, imagining yourself as the robot moving around (and the robot following your imagined moves) is a lot more fluent, intuitive, and precise than pressing a bunch of buttons! The technology still needs to get to this stage, however.
_cs.71703
i have 4 question regarding relation between starvation and bounded waiting.1.Does starvation-freedom imply deadlock-freedom?My Answer-:From here,definition of starvation free isFreedom from Starvation -:Every thread that attempts to acquire the lock eventually succeedsFreedom from Deadlock -:f some thread attempts to acquire the lock, then some thread (not necessarily the thread referred to in the if statement; emphasis added) will succeed in acquiring the lock.so i can state that starvation-freedom imply deadlock-freedom 2.Does starvation-freedom imply bounded-waiting?Approach-:Starvation free implies that every thread that will attempt to acquire lock will succeed.on the other handbounded wait insures that there exists a bound, or limit, on the number of times other processes are allowed to enter their critical sections after a process has made request to enter its critical section and before that request is grantedwhich implies that there must not be any starvation.Am i correct? but the explanation is here confuses me.Please help me out !!Thanks!!!
Bounded waiting and starvation free in critical section problem
operating systems;synchronization;deadlocks;critical section
No, starvation-free doesn't imply bounded waiting.For instance, consider a procedure that never even attempts to acquire any lock; but the amount of time it takes is variable and can be arbitrarily long. Then there is no bound on the amount of time it might take to complete its operation.Here is another example of how it can fail. Starvation-free means that every attempt to acquire the lock eventually succeeds -- but that says nothing about how long it might take. Maybe the amount of time it will take to acquire the lock is variable and can be arbitrarily long -- there is no upper bound on how long it takes to acquire the lock. Then a procedure that first attempts to acquire the lock before doing anything else won't satisfy bounded waiting.
_softwareengineering.195426
I notice that a property of codebases that I like hacking on is that it's quick to find the relevant code for some feature, without knowing much about the code base at all. For example, searching for a label in the GUI, and immediately hitting the code that implements that feature.This seems to be in direct tension with abstraction layers, where the label is probably buried behind an I18N module, and the business logic is probably further removed in an MVC framework. (It can be mitigated by including GUI labels in comments though, for example.)It's obviously part of maintainability, but is there a name for this specific, desirable, property?
Is there a name for being able to quickly find the relevant code?
design patterns;programming practices;source code;abstraction;maintainability
null
_unix.337450
I'm running nginx on raspberry pi.I ran update and upgrade commands and then installed nginx.1. sudo apt-get update2. sudo apt-get upgrade3. sudo apt-get install nginxStarted the server4. sudo /etc/init.d/nginx startOutput[ ok ] Starting nginx (via systemctl): nginx.service.When I enter ip address into the browser nothing appears. What could be the problem here?
Nginx doesn't show the default html page
raspberry pi;nginx
null
_cs.76659
What are the advantages of fully polynomial time approximation scheme over polynomial time approximation scheme?
Algorithms Design and Analysis
algorithms;complexity theory;np hard
null
_bioinformatics.2173
Take for instance, this hypothetical example:bam <- system.file(extdata,package = SomePackage,snps.bam)reads <- readGAlignments(bam)How do I display reads in a plot with the second and fourth graph of this picture (mismatch and reads) , and the first graph of this picture? I've tried getting additional columns from readGAlignments, but it still seems to break.I've also tried using Gviz, but that doesn't support indels, which is crucial to my work.Finally, is there a way to see individual mismatches on the reads like in the first graph of the second picture, or like in Gviz? I've looked at the varying graphs for ggbio and the karyogram seems like the closest thing.
Using the ggbio package in R, how do you display a GenomicAlignments object as a mismatch plot and reads plot using autoplot?
r;visualization;genome browser
null
_webapps.104676
How to precisely find the Facebook email address of the person that only have a Facebook number ID, that is a profile, for instancehttps://www.facebook.com/profile.php?id=606247083
What is the Facebook mail address of an account that only have an ID?
facebook;facebook pages;facebook groups;facebook timeline;facebook chat
null
_unix.322029
So I know that there is a way to change the color of text for directories, regular files, bash scripts, etc. Is there a way to change the color to the file based on the _file extension_? Example:$ ls -lfoo.txt [is red] foo.text [is blue] foo.secret [is green] foo.txt [is red]
How to change the color of different files in ls
bash;shell;ls
Yes, using the LS_COLORS variable (assuming GNU ls). The easiest way to manipulate that is to use dircolors:dircolors --print-database > dircolors.txtwill dump the current settings to dircolors.txt, which you can then edit; once you've added your settings,eval $(dircolors dircolors.txt)will update LS_COLORS and export it. You should add that to your shell startup script.To apply the example settings you give, the entries to add to dircolors.txt would be.txt 00;31.text 00;34.secret 00;32
_unix.280009
I have DNS server to my domain abc.com.Need to point my sub domain xx.abc.com to another subdomain xx.def.com. As it's hosted in xx.def.com, I will get any IP, so they will provide only subdomain name xx.def.com. Will it possible to point my subdomain to other subdomain instead of IP in DNS record?
pointing Linux DNS server from one sub domain to another subdomain
dns;domain
As you are mentioning different domains abc.com & def.com, you use web server redirection of xx.abc.com to xx.def.com. For example the below sample syntax is used to do redirection in Apache server:<VirtualHost x.x.x.x:80> ServerName xx.abc.com Redirect Permanent / xx.def.com</VirtualHost>This will redirect all request coming from xx.abc.com to xx.def.com.
_unix.245670
I attempted yesterday to install Debian on an external HDD. Created my partition on the external drive, booted from CD, set up file structure during graphical install on the desired partition of said external. I completed the install, then following the restart my computer said my USB drive had no bootable partition. So, I restarted again, unplugged my external, and went to boot into windows only to have it tell me BOOTMGR not present. (Got that fixed though)So my question is, is this even possible? To create a bootable Linux from an external HDD that is partitioned. Or did I just botch a step.
Installing a bootable Debian Jessie on partitioned external HDD
debian;debian installer
null
_codereview.143065
I was given an assignment to create an implementation of a tokenizer object (by object, I mean a struct with associated functions that operate on instances of the struct). This tokenizer retrieves tokens from an input string given the following rules:The input string cannot be changedTokens can only contain digits 0-9, hex digits, E and e, X and x, +, -, and periods(.). Tokens are delimited by white spaceIf a character that is not a delimiter or a valid token character is encountered in the input string, a message containing its ASCII and hexadecimal representation is printed.The program then uses the tokenizer object to retrieve tokens from an input string and classify them as zero, integer, float, octal, hexadecimal, or malformed. The classification is done using a finite state machine.This is my first C program so I'd like pointers on where I could improve.(And to ease any worries about cheating, this assignment was due September 29 and has already been turned in)Code:#include <stdio.h>#include <stdlib.h>#include <ctype.h>typedef enum { STATE_A, STATE_B, STATE_C, STATE_D, STATE_E, STATE_F, STATE_G, STATE_H, STATE_I, STATE_J, STATE_ENTRY, STATE_DECIMAL, STATE_FLOAT, STATE_OCTAL, STATE_HEXADECIMAL, STATE_MALFORMED, STATE_ZERO} state_t;static char *classifications[] = {Decimal, Float, Octal, Hexadecimal, Malformed, Zero};static state_t A(char *); static state_t B(char *); static state_t C(char *);static state_t D(char *); static state_t E(char *); static state_t F(char *);static state_t G(char *); static state_t H(char *); static state_t I(char *);static state_t J(char *); static state_t entryState(char *);typedef state_t (state_func)(char *);static state_func *STATE_FUNCTIONS[] = {A, B, C, D, E, F, G, H, I, J, entryState};struct TokenizerT_ { char *current;};typedef struct TokenizerT_ TokenizerT;int isoctal(int c) { return c >= '0' && c <= '7';}static void failedToAllocateMemory() { printf(\nFailed to allocate memory. Program is exiting.); exit(EXIT_FAILURE);}state_t entryState(char *token) { if (*token == '0') { return STATE_A; } else if (isdigit(*token)) { return STATE_B; } else { return STATE_MALFORMED; }}state_t A(char *token) { if (!*token) { //Token is 0 return STATE_ZERO; } else if (isoctal(*token)) { return STATE_C; } else if (tolower(*token) == 'x') { return STATE_D; } else if (*token == '.') { return STATE_E; } else { return STATE_MALFORMED; }}state_t B(char *token) { if (!*token) { return STATE_DECIMAL; } else if (isdigit(*token)) { return STATE_B; } else if (*token == '.') { return STATE_E; } else if (tolower(*token) == 'e') { return STATE_H; } else { return STATE_MALFORMED; }}state_t C(char *token) { if (!*token) { return STATE_OCTAL; } else if (isoctal(*token)) { return STATE_C; } else { return STATE_MALFORMED; }}state_t D(char *token) { if (isxdigit(*token)) { return STATE_F; } else { return STATE_MALFORMED; }}state_t E(char *token) { if (isdigit(*token)) { return STATE_G; } else { return STATE_MALFORMED; }}state_t F(char *token) { if (!*token) { return STATE_HEXADECIMAL; } else if (isxdigit(*token)) { return STATE_F; } else { return STATE_MALFORMED; }}state_t G(char *token) { if (!*token) { return STATE_FLOAT; } else if (isdigit(*token)) { return STATE_G; } else if (tolower(*token) == 'e') { return STATE_H; } else { return STATE_MALFORMED; }}state_t H(char *token) { if (isdigit(*token)) { return STATE_J; } else if (*token == '+' || *token == '-') { return STATE_I; } else { return STATE_MALFORMED; }}state_t I(char *token) { if (isdigit(*token)) { return STATE_J; } else { return STATE_MALFORMED; }}state_t J(char *token) { if (!*token) { return STATE_FLOAT; } else if (isdigit(*token)) { return STATE_J; } else { return STATE_MALFORMED; }}static void notifyUnexpectedSymbol(char c) { printf(\nUnexpected symbol '%c' [%#02X] in input string, c, c);}static int isValidTokenCharacter(char c) { return isdigit(c) || isxdigit(c) || c == '+' || c == '-' || c == '.' || tolower(c) == 'x' || tolower(c) == 'e';}static char *buildToken(TokenizerT *tk) { size_t size = 0; char *token = malloc(1); if (!token) { failedToAllocateMemory(); } while (*tk->current && !isspace(*tk->current)) { if (isValidTokenCharacter(*tk->current)) { size++; token = realloc(token, size); if (!token) { failedToAllocateMemory(); } token[size - 1] = *tk->current; } else { notifyUnexpectedSymbol(*tk->current); } tk->current++; } token = realloc(token, size + 1); if (!token) { failedToAllocateMemory(); } token[size] = '\0'; return token;}char *TKGetNextToken(TokenizerT *tk) { int space_c = 0; int valid_c = 0; while (*tk->current && ( (space_c = isspace(*tk->current)) || !(valid_c = isValidTokenCharacter(*tk->current)) )) { if (!valid_c && !space_c) { notifyUnexpectedSymbol(*tk->current); } tk->current++; } if (!*tk->current) { return NULL; } return buildToken(tk);}static int isFinalState(state_t st) { return st >= STATE_DECIMAL;}void classifyTokens(TokenizerT *tk) { char *token; while ((token = TKGetNextToken(tk))) { char *cp = token; state_t currentState = STATE_ENTRY; while (!isFinalState(currentState)) { currentState = STATE_FUNCTIONS[currentState](cp++); } printf(\n%-11s %s, classifications[currentState - STATE_DECIMAL], token); free(token); }}TokenizerT *TKCreate(char *ts) { TokenizerT *tokenizer = malloc(sizeof(TokenizerT)); if (!tokenizer) { return NULL; } tokenizer->current = ts; return tokenizer;}void TKDestroy(TokenizerT *tk) { free(tk);}int main(int argc, char **argv) { if (argc < 2) { printf(\nOne argument must be provided.\n); } else { TokenizerT *tok = TKCreate(argv[1]); if(!tok) { failedToAllocateMemory(); } classifyTokens(tok); TKDestroy(tok); } return 0;}
Implementation of tokenizer object and finite state machine in C
beginner;c;parsing;state machine
null
_codereview.49541
I have a Cache Helper Class.using System;using System.Web;public static class CacheHelper{ /// <summary> /// Insert value into the cache using /// appropriate name/value pairs /// </summary> /// <typeparam name=T>Type of cached item</typeparam> /// <param name=o>Item to be cached</param> /// <param name=key>Name of item</param> public static void Add<T>(T o, string key) { // NOTE: Apply expiration parameters as you see fit. // I typically pull from configuration file. // In this example, I want an absolute // timeout so changes will always be reflected // at that time. Hence, the NoSlidingExpiration. HttpContext.Current.Cache.Insert( key, o, null, DateTime.Now.AddMinutes(1440), System.Web.Caching.Cache.NoSlidingExpiration); } /// <summary> /// Remove item from cache /// </summary> /// <param name=key>Name of cached item</param> public static void Clear(string key) { HttpContext.Current.Cache.Remove(key); } /// <summary> /// Check for item in cache /// </summary> /// <param name=key>Name of cached item</param> /// <returns></returns> public static bool Exists(string key) { return HttpContext.Current.Cache[key] != null; } /// <summary> /// Retrieve cached item /// </summary> /// <typeparam name=T>Type of cached item</typeparam> /// <param name=key>Name of cached item</param> /// <param name=value>Cached value. Default(T) if /// item doesn't exist.</param> /// <returns>Cached item as type</returns> public static bool Get<T>(string key, out T value) { try { if (!Exists(key)) { value = default(T); return false; } value = (T) HttpContext.Current.Cache[key]; } catch { value = default(T); return false; } return true; }}and usage:string key = EmployeeList;List<Employee> employees;if (!CacheHelper.Get(key, out employees)){ employees = DataAccess.GetEmployeeList(); CacheHelper.Add(employees, key); Message.Text = Employees not found but retrieved and added to cache for next lookup.;}else{ Message.Text = Employees pulled from cache.;}Do you see any improvement / issue?
ASP.Net caching manager
c#;asp.net
null
_codereview.39817
Attempting to jump into the Windows Server ServiceBus 1.1 code-base along with adopting the new TPL async methods. But I could not find an easy way to just spin up N number of handlers for message sessions (might have 100 or so concurrent sessions). So it would be great to get some feedback on the following code, any suggestions on an easier way would be great... note tried to keep code sample simple for the questions purpose.///==============================================================/// SAMPLE USAGESubClient = SubscriptionClient.Create(TopicName, SubscriptionName);SessionsMessagingOptions opts = new SessionsMessagingOptions(){ NumberOfSesssions = 5, ReceiveTimeOut = TimeSpan.FromSeconds (5), AutoMarkMessageComplete = true, MessageHandler = msg => { _logger.Log(string.Format(Processing recived Message: SessionId = {0}, Body = {1}, msg.SessionId, msg.GetBody<string>())); }};SubClient.HandleSessions(opts);///==============================================================public class SessionsMessagingOptions{ public Int32 NumberOfSesssions { get; set; } public TimeSpan ReceiveTimeOut { get; set; } public Boolean AutoMarkMessageComplete { get; set; } public Action<BrokeredMessage> MessageHandler { get; set; }}///==============================================================public static class SubscriptionClientExtensions{ public static void HandleSessionsV2(this SubscriptionClient sc, SessionsMessagingOptions opts) { for (Int32 nIndex = 0; nIndex < opts.NumberOfSesssions; nIndex++) { HandleSession(sc, opts); } } public static async Task<MessageSession> HandleSession(SubscriptionClient sc, SessionsMessagingOptions opts) { do { MessageSession ms = null; try { ms = await sc.AcceptMessageSessionAsync().ConfigureAwait(false); foreach (var msg in await ms.ReceiveBatchAsync(5, opts.ReceiveTimeOut).ConfigureAwait(false)) { if (msg == null) break; try { opts.MessageHandler(msg); if (opts.AutoMarkMessageComplete) msg.Complete(); } catch (Exception) { // log the exception } } } catch (TimeoutException) { // log timeout occurred } catch (Exception) { // look into other exception types to handle here } finally { if (ms != null) { if (!ms.IsClosed) ms.Close(); } } } while (true); } public static void HandleSessions(this SubscriptionClient sc, SessionsMessagingOptions opts) { Action<Task<MessageSession>> sessionAction = null; Action<Task<BrokeredMessage>> msgHandler = null; sessionAction = new Action<Task<MessageSession>>(tMS => { if (tMS.IsFaulted) // session timed out - repeat { sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); return; } MessageSession msgSession = null; try { msgSession = tMS.Result; } catch (Exception) { return; // task cancelation exception } msgHandler = new Action<Task<BrokeredMessage>>(taskBM => { if (taskBM.IsFaulted) return; BrokeredMessage bMsg = null; try { bMsg = taskBM.Result; } catch (Exception) { return; // task cancelation exception } if (bMsg == null) { sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); // session is dead return; } opts.MessageHandler(bMsg); // client code to handle the message if (opts.AutoMarkMessageComplete) bMsg.Complete(); msgSession.ReceiveAsync(opts.ReceiveTimeOut).ContinueWith(msgHandler); // repeat }); msgSession.ReceiveAsync(opts.ReceiveTimeOut).ContinueWith(msgHandler); // start listening }); for (Int32 nIndex = 0; nIndex < opts.NumberOfSesssions; nIndex++) { sc.AcceptMessageSessionAsync().ContinueWith(sessionAction); } }}
Easy way to handle AcceptMessageSessionAsync and ReceiveAsync - Windows Server ServiceBus
c#;task parallel library
null
_webmaster.65317
I recently completed a website for a client, which was hosted on my own personal server until we were ready to move it to their own dedicated domain. Inadvertently, the sub-directory got indexed when it still resided on my domain, and thus searches for the site show up for its existence on my server.I set up a 301 Permanent Redirect and put in a crawl request to Google hoping to rectify the search results, but unfortunately the results are still the same.All the literature I have been reading talks about setting up 301s when moving from domain to domain, but little to none talks about moving a site from a sub-directory to its own TLD.Is there a specific process to go about when moving a site from a sub-directory to its own domain while maintaining its preexisting SEO?
Moving directory to domain and maintaining SEO
seo;redirects;subdirectory
You have a few options. A 301 redirect, or 404 not found, 410 gone, or block access using robots.txt. Each option depends upon the situation.If you have links to the sub-domain, then a 301 redirect is a temporary solution to maintain any value of that link. If you are not concerned about links to the sub-domain, then the following options may be better. I caution you that any links to the sub-domain will have to dealt with eventually. You have to decide if any of the links have enough value to preserve for a period. If they have value you do not want to lose, then a 301 redirect can help with this. Keep in mind that 301 redirects only have value as long as they continue to exist. In the end, they will likely have to be broken so that the sub-domain can be taken down if that is the plan.If there are no links to the sub-domain, then there are better options that would help resolve your issue faster.Any 301 redirect would preserve links. If there are no links to be concerned with, then a 301 redirect would preserve both sets of URLs in the index: the sub-domain URLs and the (proper) domain URLs. Which does not seem to be what you want and will slow down any bubbling-up of the (proper) domain in the SERPs.A 404 not found error could remove the sub-domain pages from the index, but it will take a while because you are in a sense, not telling a searcher or spider that the page is gone. However, a 404 error is naturally an easy thing to do. For a period, Google will try each page repeatedly until Google decides that each page is actually gone. Google uses a TTL (time to live) style metric based upon freshness. In this case, because these are new pages, the TTL may be kind of long. Therefore this could be a longer process.A 410 gone error could remove the sub-domain pages from the index, but each page has to be accessed again on whatever time schedule that Google has for each page. Google uses a TTL (time to live) style metric based upon freshness. In this case, because these are new pages, the TTL may be kind of long. Therefore this could be a longer process. Still, it would be much shorter a process than a 404 not found error.Using the robots.txt file to block access to the sub-domain can drop all of the pages from the index much faster. In this case, when the robots.txt file is read again and Google is blocked from the sub-domain site, then Google will drop the indexed pages generally within days. This can still take a while based upon the TTL metric for the site overall. Google will not check the robots.txt file more than once in a 24 hour period. If Google has a shorter TTL value for the sub-domain site, then the robots.txt can be re-read within a few days. Though it can be weeks also. However, once the robots.txt file is read, the process to drop the sub-domain pages from the index can be just a few days.If there is no advantage to retaining the sub-domain, it is a much faster process to simply use the robots.txt file to block accesses from the sub-domain to drop these pages from the index allowing the (proper) domain to then perform in the SERPs as you intend. IF you are in a hurry, then blocking access to the sub-domain within the robots.txt will be the fastest option.As far as SEO is concerned, there likely is no value you can preserve outside of links and existing search. The links may be of little value. You have to decide. The primary reason is because it is a new site. I would assume that not enough soaking-in has occurred in the search engines to be of real value. Certainly, your customer will want that value for their own site and breaking the sub-domain is the fair and proper thing to do for your customer. The only realistic value that I can see would exist is search traffic. If it is low, then it costs you almost nothing to break the sub-domain and let the (proper) domain to bubble-up in the SERPs. If this is what you decide is the best option for your scenario, then it should be a relatively fast process in the search engine world, 30-60 days, to begin building search traffic which is quite normal. Remember, depending upon the site, it can take 6-12 months to properly soak-in to the SERPs anyway. If your sub-domain has only existed for a few months, it has not really soaked-in very much at all. Sometimes the best thing to do is in business and SEO is to cut-bait and fish.
_webmaster.44098
I'm sure you've spotted search results in google that aren't really pages with content, but pre-built search result pages within the site itself. A few examples: http://www.indeed.cl/Empleos-de-Ingeniero-Comercial http://empleo.trovit.cl/trabajo-ingeniero-comercialThese come out first when you search Trabajo Ingeniero Comercial in Google. Their effectiveness in SEO is obvious. Questions:- Does this technique have a name?- Are they generated dynamically with the Google search term, or are they pre-built and cached? And if they are dynamic, how is the search term retrieved?I would love some insight in this technique. Thanks
How are these pre-built search results page made, and are those considered black hat SEO?
seo;search engines
null
_unix.205453
My host OS is Windows. Using VMWare I installed an image of Linux CentOS 5. In this VM I have installed a software named mySoft.I want to sell the VM to one person to run only on his computer. This person will have permission to run and use mySoft and won't be root.I want to restrict this VM so it can't be used (or at least mySoft can't be used) on any another computer even if it belongs to the same person I sold it originally.In another word, I want a restriction on distribution (copy or move) of VMWare Linux!
Restrict VM Linux installed on a computer to run in another one
vmware
null
_unix.329856
I've written the following line of code to delete the contents of a directory.rm -rf $dir && mkdir -p $dirHowever, this will not work if the first statement failed. Does it ever return 1?
Does rm -rf $dir ever return false?
rm;return status
Sure, if some part of the deletion would violate permissions. For example$ mkdir -p p/q$ sudo chown root p p/q$ sudo chmod 700 p p/q$ rm -rf prm: cannot remove 'p': Permission denied$ echo $?1Note, however, that you can remove a directory that's not yours from a directory that is. So the above would not fail if I only tried with p without the contents.
_webapps.101626
YouTube allows to combine multiple videos to create a longer videos using the Video Editor. I have uploaded multiple videos to my account but on this page I see only couple of videos in the source list, the one are shorter than 10 min.Is there a limitation on the length of the source videos, which can be used to make combined longer video?
Combine/merge long YouTube videos
youtube;video;video editing
null
_unix.335986
Here is my current setup:Machine A with a single ipA: general purpose debian server with ssh, web server, etc...Machine B with a single ipB: openvpn server (also on debian)My aim is to use the same physical machine to do the same (Machine C with both ipA and ipB on the same physical interface) :everything (ssh, web server, ...) through ipAexcept openvpn through ipB.My requirement is that an external user should not be able (excluding side-channels) to infer that ipA and ipB route to the same physical machine.As an example, all current services of Machine A should not listen on ipB.Moreover, since Machine B is only used for openvpn, I would like to avoid a hypervisor-based solution. I hope there is a way to jail openvpn and ipB under my existing OS.Which technology/packages should I use in this case?Since openvpn is latency sensitive and resources hungry, light technologies are preferred.
Assign specific IP to application
debian;networking;ip
The best choice is to do that in every service configuration and set every service to listen for specific ip not any ip, but, you can do that in iptables so you can drop any packet that have destination ipB and the port is not openvpn port or only allow destination ipB and port openvpn but you here you will lose the ability to use the port with ipA.For exmpale:iptables -t filter -A INPUT -p udp -d <ipB> --dport 1194 -j ACCEPTiptables -t filter -A INPUT -p tcp -d <ipB> --dport 1194 -j ACCEPTiptables -t filter -A INPUT -p udp --dport 1194 -j DROPiptables -t filter -A INPUT -p tcp --dport 1194 -j DROPHere am only allowing the connection on port 1194 for the packet that have destination ipB
_unix.43844
On a Gentoo Linux box which I'm not administering (and to which I don't have root access), how can I find out the options which were used to compile the package?(Please note I've never worked with Gentoo before, but have good working knowledge of Debian-based distros)
Find out a package's configure/compile options in Gentoo
gentoo
If the portage package manager is used (it most likely is) then the CPU flags can be found in /etc/make.conf as CFLAGS and CXXFLAGS. Note that individual ebuilds may filter certain flags, so the flags you see in /etc/make.conf may not be the ones that were used to compile the package. Looking at the ebuild (under /usr/portage/<category name>/<program name>/) might tell you if that is the case.This assumes of course that the contents of /etc/make.conf weren't changed after the compilation of the package.
_codereview.174065
I have 148 lines of code... from tkinter import *from math import sqrtfrom random import shuffleHEIGHT = 768WIDTH = 1366window = Tk()colors = [darkred, green, blue, purple, pink, lime]health = { ammount : 3, color: green}window.title(Bubble Blaster)c = Canvas(window, width=WIDTH, height=HEIGHT, bg=darkblue)c.pack()ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill=green)ship_id2 = c.create_oval(0, 0, 30, 30, outline=red)SHIP_R = 15MID_X = WIDTH / 2MID_Y = HEIGHT / 2c.move(ship_id, MID_X, MID_Y)c.move(ship_id2, MID_X, MID_Y)ship_spd = 10score = 0def move_ship(event): if event.keysym == Up: c.move(ship_id, 0, -ship_spd) c.move(ship_id2, 0, -ship_spd) elif event.keysym == Down: c.move(ship_id, 0, ship_spd) c.move(ship_id2, 0, ship_spd) elif event.keysym == Left: c.move(ship_id, -ship_spd, 0) c.move(ship_id2, -ship_spd, 0) elif event.keysym == Right: c.move(ship_id, ship_spd, 0) c.move(ship_id2, ship_spd, 0) elif event.keysym == P: score += 10000c.bind_all('<Key>', move_ship)from random import randintbub_id = list()bub_r = list()bub_speed = list()bub_id_e = list()bub_r_e = list()bub_speed_e = list()min_bub_r = 10max_bub_r = 30max_bub_spd = 10gap = 100def create_bubble(): x = WIDTH + gap y = randint(0, HEIGHT) r = randint(min_bub_r, max_bub_r) id1 = c.create_oval(x - r, y - r, x + r, y + r, outline=white, fill=lightblue) bub_id.append(id1) bub_r.append(r) bub_speed.append(randint(5, max_bub_spd))def create_bubble_e(): x = WIDTH + gap y = randint(0, HEIGHT) r = randint(min_bub_r, max_bub_r) id1 = c.create_oval(x - r, y - r, x + r, y + r, outline=black, fill=red) bub_id_e.append(id1) bub_r_e.append(r) bub_speed_e.append(randint(6, max_bub_spd))def create_bubble_r(): x = WIDTH + gap y = randint(0, HEIGHT) r = randint(min_bub_r, max_bub_r) id1 = c.create_oval(x - r, y - r, x + r, y + r, outline=white, fill=colors[0]) bub_id.append(id1) bub_r.append(r) bub_speed.append(randint(6, max_bub_spd))def move_bubbles(): for i in range(len(bub_id)): c.move(bub_id[i], -bub_speed[i], 0) for i in range(len(bub_id_e)): c.move(bub_id_e[i], -bub_speed_e[i], 0)from time import sleep, timebub_chance = 30def get_coords(id_num): pos = c.coords(id_num) x = (pos[0] + pos[2]) / 2 y = (pos[1] + pos[3]) / 2 return x, ydef del_bubble(i): del bub_r[i] del bub_speed[i] c.delete(bub_id[i]) del bub_id[i]def clean(): for i in range(len(bub_id) -1, -1, -1): x, y = get_coords(bub_id[i]) if x < -gap: del_bubble(i)def distance(id1, id2): x1, y1 = get_coords(id1) x2, y2 = get_coords(id2) return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)def collision(): points = 0 for bub in range(len(bub_id) -1, -1, -1): if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]): points += (bub_r[bub] + bub_speed[bub]) del_bubble(bub) return pointsdef cleanAll(): for i in range(len(bub_id) -1, -1, -1): x, y = get_coords(bub_id[i]) del_bubble(i)def collision_e(): for bub in range(len(bub_id_e) -1, -1, -1): if distance(ship_id2, bub_id_e[bub]) < (SHIP_R + bub_r_e[bub]): window.destroy() print(You were killed by a red bubble...) print(You got , score, score!) sleep(100) c.create_text(50, 30, text=SCORE, fill=white)st = c.create_text(50, 50, fill=white)c.create_text(100, 30, text=TIME, fill=white)tt = c.create_text(100, 50, fill=white)def show(score): c.itemconfig(st, text=str(score))evil_bub = 50#MAIN GAME LOOPwhile True: if randint(1, bub_chance) == 1: create_bubble() if randint(1, evil_bub) == 1: create_bubble_e() if randint(1, 100) == 1: create_bubble_r() move_bubbles() collision_e() clean() score += collision() if score >= 400: evil_bub = 40 bub_chance = 25 if score >= 1000: evil_bub = 30 bub_chance = 20 show(score) window.update() shuffle(colors) sleep(0.01)I would like to know if There is any way to make this better ALSO I have a few things I need done but cant find an awnser:Have a time variable that the larger it is the harder the game isWhen I try this it gets stuck on <built-in-function-time>Thanks!
Python TKinter game, Bubble, Blaster
python;python 3.x;gui;tkinter
This part of your codeif event.keysym == Up: c.move(ship_id, 0, -ship_spd) c.move(ship_id2, 0, -ship_spd)elif event.keysym == Down: c.move(ship_id, 0, ship_spd) c.move(ship_id2, 0, ship_spd)elif event.keysym == Left: c.move(ship_id, -ship_spd, 0) c.move(ship_id2, -ship_spd, 0)elif event.keysym == Right: c.move(ship_id, ship_spd, 0) c.move(ship_id2, ship_spd, 0)elif event.keysym == P:may become shorter and more readable, too, if you will employ a dictionary for your four directions:directions = dict(Up=(0, -1), Down=(0, +1), Left=(-1, 0), Right=(1, 0))direction = event.keysym # for better readability only if direction in directions: x_fact, y_fact = directions[direction] # unpacking tuple cx = x_fact * ship_spd cy = y_fact * ship_spd c.move(ship_id, cx, cy) c.move(ship_id2, cx, cy)Note the construction of that dictionary (using keywords to avoid typing quotes).
_codereview.114915
After almost completely redoing the first version I think I finally have it. I still have a few things to add/change, but I think it's pretty good and safe. I've improved security features as well as overall functionality.I haven't run this program through pycharm yet, so there might be a few PEP 8 errors. It took me a few weeks just trying to learn about cryptography (not an easy subject). For @GarethRees post, I really didn't even start on version 2 until I implemented some sort of encryption that worked perfectly on Version 1. I tried using gpg as he recommended, but could never figure it out. I even tried it again after figuring out how to use pycrypto.If there are any bugs just point them out you don't have to write a full review just whatever you think should be changed or added post it. I really appreciate feedback and will upvote all. If you want a .exe version just ask and I'll post a link. Hope everyone likes it.#Programmer: DeliriousSyntax#Date: 12-9-15#File: AccountKeeperV2.py#This program lets you store and create passwordsimport CustomFunctions as CFimport pyperclipimport randomimport shelveimport EcstaticCryptionimport string#Encrypting and Decrypting is done with pycryptoTask List:Hide key after hitting enterCreate a settings GUILet user continuously generate a password untill satisfiedWhen changing password let user pick a new random passwordUse string.punctuation in character list without messing up printingAdd Exclude similar characters optionLet user save settings without opening scriptclass main: LOWER = True UPPER = True NUMBERS = True SYMBOLS = True COPY = True File = Keeper.dat template = ('\n- Account: {} ' '- Username: {} ' '- Password: {} ' ' -') key = input('Key: ') EC = EcstaticCryption.AESCipher(key) @property def CHARACTERS(self): CHAR = [] if self.LOWER:CHAR.append(string.ascii_lowercase) if self.UPPER:CHAR.append(string.ascii_uppercase) if self.SYMBOLS:CHAR.append('!#$%&()*+,-.:;<=>?@[]^_`{|}~') if self.NUMBERS:CHAR.append(string.digits) return CHAR def all_accounts(self): with shelve.open(self.File) as f: print('\n') for account in f: print(account, end=' ') print('\n') def all_users(self, account): with shelve.open(self.File) as f: print('\n') for user in f[account]: print(user, end=' ') print('\n') def check_account(self, account): list_of_accounts = [] with shelve.open(self.File) as f: if account in f: return True else: return False def check_username(self, account, username): list_of_users = [] with shelve.open(self.File) as f: try: if username in f[account]: return True else: pass except KeyError: pass return False def generate_password(self, digits_in_pass): holder = [] for _ in range(digits_in_pass): temp = random.SystemRandom().choice(self.CHARACTERS) holder.append(random.SystemRandom().choice(temp)) return ''.join(holder) def save_account(self, entry): with shelve.open(self.File) as f: try: holder_account = f[entry[0]] except KeyError: holder_account = {} holder_account[entry[1]] = entry f[entry[0]] = holder_account def new_account(self, log=True): Creates a new random password print('\n') account = input(Account: ) with shelve.open(self.File) as f: while True: username = input(Username: ) existing_username = self.check_username(account, username) if not existing_username: break print(This account already exists!) password = input(Password (Type \random\ for random password): ) if password.lower() == 'random': digits_in_pass = CF.valid_int(Length of password: ) password = self.generate_password(digits_in_pass) encrypted_password = self.EC.encrypt(password) entry = [account, username, encrypted_password] self.save_account(entry) if self.COPY: pyperclip.copy(password) if log: print(self.template.format(entry[0], entry[1], password)) def print_account(self, account, username): with shelve.open(self.File) as f: entry = f[account][username] password = self.EC.decrypt(entry[2]) print(self.template.format(entry[0], entry[1], password)) if self.COPY: pyperclip.copy(password) def change_username(self, account, username, log=True): new_username = input('\nEnter new username: \n ->') with shelve.open(self.File) as f: account_holder = f[account] account_holder[new_username] = account_holder.pop(username) account_holder[new_username][1] = new_username f[account] = account_holder if log: entry = f[account][new_username] password = self.EC.decrypt(entry[2]) print(self.template.format(entry[0], entry[1], password)) def change_password(self, account, username, log=True): new_password = input('Enter new password: \n ->') with shelve.open(self.File) as f: f[account][username][2] = self.EC.encrypt(new_password) if log: entry = f[account][username] print(self.template.format(entry[0], entry[1], new_password)) def delete_account(self, account, username): confirmation = input(\nType 'DELETE' to confirm deletion of this account...\n ->) if confirmation.lower() == 'delete': with shelve.open(self.File) as f: account_holder = f[account] try: del account_holder[username] f[account] = account_holder print('\nAccount deleted...') except KeyError: print('Error deleting account!') def account_menu(self, account, username): print(\nAccount Found! What's next?\n 1) Print account\n 2) Change username\n 3) Change password\n 4) Delete account\n 5) Cancel) account_choice = input( ->) if account_choice == '1': self.print_account(account, username) elif account_choice == '2': self.change_username(account, username) elif account_choice == '3': self.change_password(account, username) elif account_choice == '4': self.delete_account(account, username) else: pass def find_account(self): account = input('\n\nAccount: ') while account == 'all accounts': self.all_accounts() account = input('Account: ') existing_account = self.check_account(account) if existing_account: username = input('Username: ') while username == 'all users': self.all_users(account) username = input('Username: ') existing_user = self.check_username(account, username) if existing_user: self.account_menu(account, username) else: print('\nWe could not find your account.') else: print('\nCould not find any {} accounts.'.format(account)) def program_start(self): MAIN choice = None while True: print(\n\n\nMenu:\n 1) Add an account\n 2) Search for an existing account\n 3) Exit) choice = input( ->) if choice == 1: self.new_account() elif choice == 2: self.find_account() else: breakif __name__ == '__main__': print(Welcome to Account Keeper V2) m = main() m.program_start()
Outstanding password keeper w/ password generator
python;python 3.x
I've seen your question and would like to give you a full review, but haven't had the time yet. So now I decided to give you some of the recommendations, and then we'll see if I get the time to complete it or add to it later on.Move shelve handling to class level Instead of opening/closing the shelve all the time, I would suggest to let it follow the lifetime of the class, and add a sync method to the class. This would reduce the file operations, and you can keep the shelve open within the class.This would allow for all of the read access to be almost instant as the file is already read into memory (and the encrypted password should still be encrypted). And when doing changing password methods, you could trigger a sync, writing the shelve back to the file. Two links which might be helpful in doing this:Persistent dict with multiple standard file formats (Python recipe Which provides some structural stuff related to you use of shelveSafely using destructors in Python Related to handling lifetime opening and closing of the shelve (in a slightly different context)A better class name main is a terrible name, you should choose a better name like PasswordHandler or AccountHandler. As already suggested I would move the shelve handling to the outer level, and possibly add a few class methods. I.e. a static class method to verify if a user has entered the correct password would be nice to have.Allow methods not to use input To improve the interface, I would change the methods allowing input to accept that input to be predefined as a parameter. I'll show some code for one of the functions which could accomplish this:def change_password(self, account, username, new_password=None, log=True): if not new_password: new_password = input('Enter new password: \n ->') with shelve.open(self.File) as f: f[account][username][2] = self.EC.encrypt(new_password) if log: entry = f[account][username] print(self.template.format(entry[0], entry[1], new_password))This still uses the old code for the shelve handling, but you'll get the gist of the idea.Let methods return list, not do the actual output Instead of letting your methods, like all_users, do the print, in general it's better to let the method returning the list of users for extra handling, i.e. printing or sorting before printing or whatever...Move class level code into __init__ Doing stuff like key = input(...) is very strange, and should be moved into a method of it's own, namely the __init__, which is automatically called whenever you create an instance of your class. There are some other minor aspects still not covered (neither in mine, nor the other answer which just came in), but these matters are some of the main issues I see in your code.
_cs.63484
I'm new to regular languages and I've been struggling to solve one for a while.The question is:If there exists a regular language L1 which has an alphabet {0,1}, prove that L2 is also a regular language if L2 comprises of strings x where x = ABC where B is an element in L1 and A and C are strings comprised of 0's and 1's.I intuitively believe that since we know L1 is a regular language, we know that any string of 0's and 1's is a regular language. Hence, L2 should be a regular language as it is comprised of only 0's and 1's (by definition). Apparently, this is the wrong approach. Can someone assist me in solving this problem? Thank you! EDIT:I realize my explanation was off. We know that L1 is a regular language composed of strings of 0 and 1, for example, 000111, 010101, could exist as elements in this language. If there are finite elements inside the language, then clearly by mutlipying it by two constant strings, we will get a finite output (hence regular). However, if it is not finite, that means it must have a regular expression that describes the language. Thus, any concatenation with two similar strings will still be that same regular expression with two constants added on top of it (hence still represented by a reg ex and thus a regular language).Where is my logic flawed? Thank you!
Prove a language is regular - Regular language of 0's and 1's
formal languages;regular languages;closure properties
null
_codereview.4557
I have been making this FSM today. However, as this is probably the biggest practical program I have ever written in CL, I don't know if there are some things that could be improved, or if using a closure is the best thing here.Any feedback is appreciated.;;; States: -- EnterMineAndDigForNugget ;;; -- QuenchThirst;;; -- GoHomeAndSleepTillRested;;; -- VisitBankAndDepositGold(defmacro while (test &rest body) `(do () ((not ,test)) ,@body))(defmacro enter (state) `(setf state ,state))(defun make-miner () (let ((wealth 0) (thirst 0) (rested 0) (state 'EnterMineAndDigForNugget)) (list (defun EnterMineAndDigForNugget () ; (setf location 'mine) (format t ~&Diggin' up gold!) (incf wealth) (incf thirst) (cond ((>= thirst 7) (enter 'QuenchThirst)) (t (enter 'VisitBankAndDepositGold)))) (defun QuenchThirst () (format t ~&Drinkin' old good whiskey) (setf thirst 0) (enter 'EnterMineAndDigForNugget)) (defun VisitBankAndDepositGold () (format t ~&All this gold ought to be stored somewhere!) (incf wealth) (cond ((>= wealth 5) (progn (format t ~&Too much gold for today, let's sleep!) (enter 'GoHomeAndSleepTillRested) (setf wealth 0))) (t (EnterMineAndDigForNugget)))) (defun GoHomeAndSleepTillRested () (while (<= rested 3) (format t ~&Sleepin') (incf rested)) (enter 'EnterMineAndDigForNugget) (setf rested 0)) (defun controller () (dotimes (n 30) (cond ((equal state 'QuenchThirst) (QuenchThirst)) ((equal state 'VisitBankAndDepositGold) (VisitBankAndDepositGold)) ((equal state 'GoHomeAndSleepTillRested) (GoHomeAndSleepTillRested)) ((equal state 'EnterMineAndDigForNugget) (EnterMineAndDigForNugget))))))))EDITI have applied all the suggested changes but for the flet/labels one. Everything worked fine until I changed the one of set the state to the next function. Now, the macro enter doesn't seem to be ever called.This is the current state of the code, with the required code to make it work;;; States: -- enter-mine-and-dig-for-nugget ;;; -- quench-thirst;;; -- go-home-and-sleep-till-rested;;; -- visit-bank-and-deposit-gold(defmacro enter (state) `(setf state ,state))(defun make-miner () (let ((wealth 0) (thirst 0) (rested 0) (state #'enter-mine-and-dig-for-nugget)) (list (defun enter-mine-and-dig-for-nugget () (format t ~&Diggin' up gold!) (incf wealth) (incf thirst) (if (>= thirst 7) (enter #'quench-thirst) (enter #'visit-bank-and-deposit-gold))) (defun quench-thirst () (format t ~&Drinkin' old good whiskey) (setf thirst 0) (enter #'enter-mine-and-dig-for-nugget)) (defun visit-bank-and-deposit-gold () (format t ~&All this gold ought to be stored somewhere!) (incf wealth) (if (>= wealth 5) (progn (format t ~&Too much gold for today, let's sleep!) (enter #'go-home-and-sleep-till-rested) (setf wealth 0)) (enter #'enter-mine-and-dig-for-nugget))) (defun go-home-and-sleep-till-rested () (dotimes (i 4) (format t ~&Sleepin')) (enter #'enter-mine-and-dig-for-nugget)) (defun controller () (dotimes (n 30) (funcall state))))))(let ((a (make-miner))) (funcall (fifth a)))
Finite State Machine code
lisp;common lisp
DEFUNThe most basic mistake in your code is that DEFUN is not correct for nested functions. DEFUN is a top-level macro, defining a top-level function and should be used in top-level forms.Nested functions are defined in Common Lisp with FLET and LABELS. LABELS is used for recursive sub-functions.NamingSymbols like FooBarBaz are not use in Common Lisp. By default Common Lisp upcases all names internally, so the case information gets lost.Usually we write foo-bar-baz.Checking symbolsUse CASE (or ECASE) instead of (cond ((equal foo 'bar) ...)).ArchitectureUsually I would write that piece of code using CLOS, the Common Lisp Object System.In a more functional style I would propose the following:use LABELS for the local procedures.set the state to the next function. A function is written as (function my-function) or #'my-function.the controller just calls the next function from the state variable. It is not necessary to list all cases.
_softwareengineering.246322
I'm working on an app which talks to a bluetooth low energy (BLE) device and exchanges customized data with it. Our team has defined the data models and there's a method that will parse the data payload and assign values to the corresponding characteristics. It works all fine until we have introduced a new firmware.In this new firmware some values in the data payload have been re-defined or the offset of a specific value has been changed. So the parsing method will need to be updated/re-written according to the new payload definition. Then here comes the problem: both two versions of the firmware need to be supported! Of course I could write a lot of if/else in the parsing method right now, but what happend if 3 other firmware updates arrive one after other? I can imagine the code will become hard to read and lose it's simplicity. I'm wondering if there's an elegant way to manage the co-existence of firmware versions. Maybe a design pattern that can be adopted here?To make it more specific:In my model class Temperature I've the following properties:@property (nonatomic, readonly) float temp_outside;@property (nonatomic, readonly) float temp_inside;The library has to support 3 different firmware versions:V1 does only support temp_outsideV2 does support temp_outside and temp_insideV3 does support temp_outside and temp_inside, but temp_inside has to be obtained differently compared to V1 & V2Assuming the firmware provides their information within the manufacturer data of the advertisings as raw data:V1 firmware: 00 42 0a(byte 1: sw id, byte 2: protocol id, byte 3: temp_outside)V2 firmware: 00 43 0a 10(byte 1: sw id, byte 2: protocol id, byte 3: temp_outside, byte 4: temp_inside)V3 firmware: 00 44 10 0a(byte 1: sw id, byte 2: protocol id, byte 3: temp_inside, byte 4: temp_outside)What is the best way to implement this? There are several things to consider:The model has values which might not be filled by a specific firmware; should I have separate models per firmware or how can I make sure that only supported properties will be accessed?The method responsible for parsing the bytes into the model has to support all firmwares. Should there be one method / parser with several conditions based on the protocol id or several parser classes?The usage of the library within view controllers should be as convenient as possible.
How to support multiple firmware versions?
design
Your problem isn't so much that you need to support different firmware versions, but rather that all these firmware versions use slightly different protocols to communicate.If you have any influence on the protocol used by the device's firmware, you should aim for a protocol that is both backwards and forwards compatible, so that a newer sender can communicate with an older receiver and vice versa.For the protocol versions that you already have, you can use the Strategy pattern, where you have a parser for each protocol version as a strategy and you select the right parser based on the identification fields in each message (or in the first message).Inside your Model classes (and your Views), you should plan for the possibility that not all properties are guaranteed to be available. The two ways to handle this is to have a secondary boolean property/method for each property to indicate if the value is available, or to use a special, out-of-bounds marker value to indicate the value is not available.
_datascience.17223
Hi guys I'm very new to data science,I have intermediate background on programming and have used Pentaho Data Integration tool once for DB migration & data cleansing. Let's say I have this kind of data:item_details, timestampWooden chairs, 01-07-2017Plastic chairs, 02-07-2017Stainless table, 11-07-2017Decorated window, 12-07-2017and so onI want to know based on monthly time frame what are the top trending items in that month. Let's say in January the top 3 item is:1. Table2. Chairs3. WindowIn February :1. Door2. Chair3. Cupboard.. And so onHow can I achive this and using what kind of tool? (preferably free or open source tools, can be GUI based or script library, having a visualization or dashboard is a plus) Thanks for the help. Sorry for noob questions
How to extract most occuring words based on month & what tool to use?
tools
If you are new to data science and data munging, this could be kind of a tricky task, but a good one to get your feet wet. Many programming languages have the capability to do this (R, Python, Matlab, etc.). I use R primarily, so I'll give you a brief heuristic for how I'd approach the task in R. Perhaps looking into these steps will get you started.Install RInstall some packages that will help you along ('tm' for text mining,'dplyr' for cleaning/organizing your data, and perhaps also 'lubridate' for working with dates/times)Read in your data from your source, be it a text file, spreadsheet, or some database (if a database, you'll have to conquer connecting R to said database too)You want to do a word frequency analysis for each month. How you accomplish this will depend on how the data is organized, which I do not know, but it would involve first rounding all your dates to month (using lubridate's 'floor_date()' function is one way), then parsing the text for each month into a corpus that can be analyzed (using package tm).Finally, for each month I would make a table counting words, sorting by frequency. That would give you, for each month, the top 'trending' words. To discount words like 'the' and 'a', I might also use some of the tools in the 'tm' package to clean things up.Note that in #5 I said 'words', not 'terms'. If you want to account for terms consisting of > 1 words, you'll have to 'tokenize' them, but that's beyond the scope of this very brief intro.As with many data science tasks, there are many ways to attack this; the above is but one of many possibilities.Hope that helps.
_webapps.10109
What is the point of the Google Mail app by Google on the Web App Store? by default it opens in a normal tab, has the address bar etc visible and is basically just a big bookmark on the new tab page. Or am I missing something?What advantage is there to using a web app than just have a bookmark on the bookmark bar?
Advantage of Google Mail App
gmail;google chrome
There are no advantages, it's essentially just a link.Mainly it's so you have your mail link with the other apps you use in Chrome.
_unix.366727
I have a shared library compiled with -g -O0 including:void MyClass::whatever(){ ... doSomething(myImage, myPoints); ...}bool MyClass::doSomething(const Image& image, std::vector<cv::Vec2f>& points) const{ const int32_t foo = 1; const float bar = 0.1f; ...}Now I'm stepping through whatever() with s, but it doesn't step into doSomething(), but over it. It's not a matter of source availability, because (1) it's in the same file and (2) I can set a breakpoint in doSomething() and step there through the sources with no problem. But s seems to believe that there is no source available.If I set step-mode on, I get output like0xb5d51148 in myClass::doSomething (this=0xb25e4, image=..., points=std::vector of length -91315, capacity 372871920 = {...})from /path/to/myclass.solike you get when there is no source available. After a couple of n the foo initialization is displayed with source.So there could be some inline magic from my parameter (an opencv type, release build) put at the beginning of the function. Is it possible that gdb sees this stuff, thinks weird stuff, let's continue after this function and doesn't find that there is really source availible for most of the function?(If should matter, it's compiled with LLVM/clang 3.5 on an ARM box with Ubuntu)
gdb doesn't step into function although source is available
debugging;gdb;clang
null
_softwareengineering.284884
As I understand, GPL allows use of a GPL program along with a proprietary program as long as they are separate programs and communicate at arms length.In order to do this, if I spawn a process from my commercial android app which would only contain the gpl code and communicate with the main process via sockets,would this violate the GPL? If so, is there any other way to use a gpl program (or code) in a commercial android app?Relevant portions of gpl-faq:http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystemhttp://www.gnu.org/licenses/gpl-faq.html#MereAggregationthank you,
Use GPL code in commercial android app by spawning a separate process
licensing;gpl;android
null
_unix.212235
I need to print the data starting from the line that matches Data after AB process=1234 (full 10): till end of the file. Could you help please.I tried putting the data in a variable called value and using sed as below. However, it gives an error extra characters at the end of D command.value=Data after AB process=1234 (full 10):sed -n ' '$value' ' p datasourcefile.log
sed and string of data
sed
sed -n '/Data after AB process=1234 (full 10):/,$p' fileorvalue='Data after AB process=1234 (full 10):'sed -n '/'${value}'/,$p' fileTake a look at: Difference between single and double quotes in bash
_unix.308994
Kali 2016.2 in Qemu:/usr/bin/qemu-system-x86_64 -boot d -m 5000 --enable-kvm -cdrom kali-linux-2016.2-amd64.iso I'm trying to list root dir:# /usr/bin/dconf list /org/But dconf-editor shows me five dirs: apps, ca, desktop, org and system.Moreover, full dump:# /usr/bin/dconf dump /does not match GUI version...Taking look at compilations:# ldd `which dconf` | awk '{print $1}' | while read i;do echo; echo $i;ldd /usr/bin/dconf-editor | grep $i;doneEverything matches. Both of applications compiled against the same set of libraries. Moreover, dconf-editor must be just a GUI, it must use dconf as a call inside. Why it is different? Is it retard of development? As I can read from License field, it was Canonical couple of years ago, but now it is one man. Canonical sucked every juices from project and lived it alone...And how can I list from console/terminal this fields of dconf-editor(GUI) which are not visible in dconf??
Why does dconf differ from dconf-editor?
kali linux;xdg;dconf
null
_codereview.140335
I created this regex in Javascript that returns a boolean for Domain validation that meets the criteria to allow IP addresses and ascii domain name. The assumption is that the TLD should be atleast two letters./^((([0-9]{1,3}\.){3}[0-9]{1,3})|(([a-zA-Z0-9]+(([\-]?[a-zA-Z0-9]+)*\.)+)*[a-zA-Z]{2,}))$/I used the following Javascript to test the regex:var func = function(val) { return /^((([0-9]{1,3}\.){3}[0-9]{1,3})|(([a-zA-Z0-9]+(([\-]?[a-zA-Z0-9]+)*\.)+)*[a-zA-Z]{2,}))$/.test(val);}It works correctly: func('192.168.1.1') //return true; func('a-a.com') //returns true; func('aa.com') //returns true; func('aa.cc') //returns true; func('aa.c') //returns false;I have basic knowledge of regex's and hence seeing if there anyway to optimize it.
Regex for domain validation name validation
javascript;regex
null
_cs.43461
In most statically typed languages, each expression has an intrinsic type. E.g. in Java, 3 is an int, 3.0 is a double, 3+3.0 is also a double. Types do not depend on the context of the expression.However, in the CSS type system described in the spec, some expressions have a type depending on the context. For example, the red token can be a <color>, a <custom-ident>, or an <attr-name>, depending on the context in which it is used.I want to build a type system for a CSS-based programming langauge. In this type system, I want to use a typing strategy that does not go from the bottom up (starting from the leaves in the AST), but top down (starting from the root of the AST).For example, when the compiler needs to derive that the linear(red, yellow) expression inhabits the <bg-image> type, it would do the following derivation:we want to derive that linear(red, yellow) :: <bg-image> <bg-image> is defined as <url> | linear(<color>, <color>), so linear(red, yellow) :: <url> | linear(<color>, <color>)let us try the second branch linear(red, yellow) :: linear(<color>, <color>)let us check sub-expressions red :: <color> yellow :: <color>everything fine, OKCan you point me to scholarly articles where this kind of typing strategy is discussed?P.s. I don't know of other languages where a type of the expression depends on the context, except for Perl. In Perl, (a,b) can be interpreted as either a list or an integer (its length), depending on the context:print (a,b) # => abprint 0+(a,b) # => 2
Top-down typing strategy - is there a name for this?
programming languages;compilers;type theory;type inference;language design
null
_unix.226906
I just searched on this page, but the answer does not meet my idea. My idea is when user called Bob access ssh and run a command, for example sudo apt-get update, then the bash sheell will respond with sudo: command not found. How to make this happen instead of using lsh (limited shell)?
Restrict bash command for specific user
bash;ssh
Basically, you are talking about a chroot environment, when a user or group meets some usage restrictions by having only specific binaries and configs in their directory root level. It is possible to configure sshd to do that./etc/ssh/sshd_config options:Match user john ChrootDirectory /var/john/Put /bin, /etc, /sbin, /usr and other required elements to their chroot directories and here you are.Take a look at this article, it may help as well.
_cs.70788
There is a question I'm trying to do however it doesn't match with the answer given and I can't seem to understand why this would be the case. I feel like I haven't completely understood something.Question: Let y be the percentage of a program code which can be executed simultaneously by n processors in a computer system. Assume that the remaining code must be executed sequentially by a single processor. Each processor has an execution rate of x MIPS, and all processors are equally capable. All overheads are neglected.Derive an expression for the effective MIPS rate when using the system for exclusive execution of this program in terms of parameters y,x and n.My attempt: Speedup by n processors is simply n. (Ideal case, no hazards etc)Amdahl's law: Speedup $= \frac{1}{(1-y)n+\frac{y}{n}}$MIPS rate = $\frac{No. of instructions}{(10^6 * Total time for execution)}$Time taken by 1 processor(T1) $$= \frac{(nT1)}{(1-y)n+y}$$Time taken by n processors = Time taken by 1 processor * Speedup $$= \frac{(nT1)}{(1-y)n+y}$$Effective MIPS rate thus: $$= \frac{(No. of instructions)}{(10^6)(T)}$$$$= \frac{x((1-y)n+y)}{n}$$Given answer is:Effective MIPS $$= x(ny-y+1)$$
Effective MIPS rate using Amdahl's law
computer architecture;parallel computing;performance
null
_cogsci.985
Computational learning theory (CoLT) is a branch of theoretical computer science associated with the mathematical analysis of machine learning. A lot of the early ideas of the field take inspiration from human learning. The field has developed into a very rigorous, mathematical, and precise science, but I have not seen it used much in the cognitive sciences directly. There is some indirect use through CoLT's interaction with statistics and machine learning algorithms (say, analyzing neural networks through VC-dimension).Are there examples of rigorous uses/applications of CoLT to build theories in psychology, neuroscience, and/or cognitive science?Notes:The only two examples I am familiar with are:Gold's theorem on the unlearnability in the limit of certain sets of languages, among them context-free ones.Ronald de Wolf's master's thesis on the impossibility to PAC-learn context-free languages.The first made quiet a stir in the poverty-of-the-stimulus debate, and the second has been unnoticed by cognitive science.I am interested in approaches of this flavor. I am relatively comfortable with CoLT as it is studied in mathematics, and am only interested (for this question) in approaches that have direct bearing on theories of human/animal cognition/learning, and not classic machine learning results. I am looking for general mathematical and asymptotic approaches, not the running of specific types of algorithms (be it neural-nets, bayesian, or otherwise) to simulate human performance as is typical in computational modeling in cogsci (which I am relatively familiar with).I am not interested in arguments that try to trivially undercut the whole approach, even if they have empirical validity. For instance, the whole approach can be derailed by asserting that human brains are finite and thus asymptotic arguments are useless. This is the same as arguing that all of computational complexity theory is pointless because computers (and the whole universe, for that matter) are finite. It is a valid empirical argument, but boring from the point of view of theory building.Related questions:General mathematical frameworks of language acquisition since Gold on ling.SEWhat is the complexity class most closely associated with what the human mind can accomplish quickly? on cstheory.SE
Applications of computational learning theory in the cognitive sciences
learning;computational modeling;mathematical psychology;theoretical neuroscience
null
_cs.42128
I understand what a multilayer neural network is, but what about them allows them to solve non-linear problems unlike perceptrons? Is it the fact that they can extend to any number of outputs/hidden layers? Or is it another feature?
Why can Multilayer neural networks solve non-linear problems
artificial intelligence;neural networks;intuition
null
_codereview.126313
I have been developing a simple login registration page with PHP using the repository pattern. Following are the business rules :During registrationEmail must be unique.Email must be a valid email address.User table columns:id, name, username, password, created_at, updated_atregister.php pageif($_POST){ try{ $input['name'] = $_POST['name']; $input['email'] = $_POST['email']; $input['username'] = $_POST['username']; $input['password'] = $_POST['password']; $user_register_obj = new UserRegister(new UserInfoRepository()); $user_register_obj->register($input); header('Location: login.php'); exit(); } catch(CustomException $e) { var_dump($e->getCustomMessage()); }}?>Following is the userinfo interface: This is for the user table.IUserInfo.phpinterface IUserInfo { public function getId(); public function getName(); public function getEmail(); public function getUserName(); public function getCreatedAt(); public function getUpdatedAt(); public function getPassword();}User.php file :class User implements IUserInfo{ private $id; private $name; private $email; private $username; private $created_at; private $updated_at; private $password; public function __construct($id, $name, $email, $username, $created_at, $updated_at, $password) { $this->id = $id; $this->name = $name; $this->email = $email; $this->username = $username; $this->created_at = $created_at; $this->updated_at = $updated_at; $this->password = $password; } public function getEmail() { return $this->email; } public function getId() { return $this->id; } public function getName() { return $this->name; } public function getUserName() { return $this->username; } public function getCreatedAt() { return $this->created_at; } public function getUpdatedAt() { return $this->updated_at; } public function getPassword() { return $this->password; }}UserInfoRepository :interface IUserInfoRepository { public function getById($id); public function getByEmail($email); public function getAll(); public function insert($input); public function update($id, $input); public function delete($id);}This is the repository class for userinfo :class UserInfoRepository implements IUserInfoRepository{ private $table = 'users'; private $db_obj; public function __construct() { $this->db_obj = new \DatabaseHandler\Database(); } public function getById($id) { $query = 'select * from users where id = ' . $id; return $this->db_obj->GetOneRow($query); } public function getAll() { // TODO: Implement getAll() method. } public function getByEmail($email) { $query = select * from user where email = '$email'; $obj = $this->db_obj->GetOneRow($query); if(!$obj) { return null; } else { return new User($obj['id'], $obj['name'], $obj['email'], $obj['username'], $obj['created_at'], $obj['updated_at'], $obj['password']); } } public function insert($input) { $name = $input['name']; $email = $input['email']; $username = $input['username']; $password = md5($input['password']); $query = insert into user (name, email, username, password) values ('$name', '$email', '$username', '$password' ); return $this->db_obj->InsertAndGetId($query); } public function update($id, $input) { // TODO: Implement update() method. } public function delete($id) { // TODO: Implement delete() method. }}UserRegister class :class UserRegister { private $userRepo; public function __construct(\IUserInfoRepository $userRepo) { $this->userRepo = $userRepo; } public function register($input) { $email = $input['email']; $result = filter_var( $email , FILTER_VALIDATE_EMAIL ); if(!$result) throw new \CustomException(Invalid Email); $obj = $this->userRepo->getByEmail($email); if(!is_null($obj)) throw new \CustomException(Email already found); $this->userRepo->insert($input); return true; }}Please ignore the database handler Database right now. That class seems fine and I am not posting it as it may make it more complex. Can you please review my code design ? I will accept answer in any languages.
User registration with Repository pattern
php;object oriented;repository
SecuritySQL InjectionYou are (very likely) open to SQL injection, as you put user input directly into SQL queries. You need to use prepared statements instead. This goes for all statements (select, insert, ...).HashingYou also have to use a proper password hashing function. md5 hasn't been acceptable for at least 15 years. Use password_hash instead. MiscStructureyour interfaces are unneeded, as they are unlikely to be used in different situations. Your IUserInfoRepository may work as a generic IRepository though, as likely other objects need to be selected, inserted, etc. Your IUserInfo interface could partly work as an IBaseObject interface which contains getId and possibly getCreatedAtand getUpdatedAt (if these are values that you store for all objects).Your getById function returns an array, while your getByEmail function returns a User. This should be handled the same way. You should pass on the specific required fields to insert, not just some input array. Arrays are bad for usability, as a user of your class would need to read the documentation, or in your case - as you don't have any - actually look at the code.Otheradd PHPDoc style comments to your functions to explain what the arguments need to be, what the return values are, etc.I would throw an exception if an email doesn't exist instead of returning null, to avoid excessive null checks.always use curly bracketsyou don't need one-time variables such as $email = $input['email'];.upper-case your SQL keywords to increase readabilitybe less generic with your variable names. obj could be userData, query could be userSelectQuery, etc.
_datascience.2275
Automated Time Series Forecasting for Biosurveillancein the above paper, page 4, two models, non-adaptive regression model, adaptive regression model, the non-adaptive regression model's parameter estimation method is least squares, what is the parameter estimation for the adaptive regression model? is there any package in R to do parameter estimation for this kind of adaptive regression model? If I add more predictors in the adaptive regression model, can R still solve it? and how?
What are the parameter estimation methods for the two methods in this paper?
r;statistics
null
_codereview.132673
Controller classnamespace App\Http\Controllers\Website\SportsType;use App\Classes\Contract\SportsType\ISportsType;use \App\Http\Requests\SportsType\SportsTypeRequest as SportsTypeRequest;class SportsTypeController extends \App\Http\Controllers\BaseController{ private $AllSportsTypes = SportsTypes; private $sportstype; public function __construct(ISportsType $_sportstype) { $this->sportstype = $_sportstype; parent::__construct(); } public function index() { $SportsTypes = $this->sportstype->All(); return view('SportsType.List')->with('SportsTypes', $SportsTypes); } public function create() { return view('SportsType.Create'); } public function edit($SportsTypeID) { $SportsType = $this->sportstype->Get($SportsTypeID); return view('SportsType.Edit', array('SportsType' => $SportsType)); } public function save(SportsTypeRequest $request) { $data = [ 'SportsType' => $request['SportsType'], 'SportsTypeID' => $request['SportsTypeID'], ]; $result = $this->sportstype->Save($data); return redirect()->route($this->AllSportsTypes); }}Business logic classnamespace App\Classes\BusinessLogic\SportsType;use App\Classes\DatabaseLayer\SportsType\SportsTypeDb;use App\Classes\Contract\SportsType\ISportsType;class SportsTypeBL implements ISportsType { public function All() { $SportsTypes = (new SportsTypeDb())->All(); return $SportsTypes; } public function Get($SportsTypeID) { $SportsType = (new SportsTypeDb())->Get($SportsTypeID); if($SportsType == null) { \App::abort(404); return; } return $SportsType; } public function Save($data) { return (new SportsTypeDb())->Save($data); }}Database classnamespace App\Classes\DatabaseLayer\SportsType;class SportsTypeDb { public function All() { $SportsTypes = \App\Models\SportsType\SportsTypeModel::all(); return $SportsTypes; } public function Get($SportsTypeID) { $SportsType = \App\Models\SportsType\SportsTypeModel ::where('SportsTypeID', $SportsTypeID) ->first(); return $SportsType; } public function Save($data) { if($data[SportsTypeID] == 0) { $SportsType = new \App\Models\SportsType\SportsTypeModel(); } else { $SportsType = $this->Get($data[SportsTypeID]); } $SportsType->SportsType = $data[SportsType]; $SportsType->save(); return true; }}Which class should have code for caching?Am I writing bad or very bad code? Can you please suggest good ways to improve it?
Basic CRUD in Laravel 5.2.37
php;laravel
null
_codereview.113519
I was thinking of building a really flexible fluent API for my persistence layer. One of my goals is to achieve somehow the following result:IEnumerable<User> users = _userRepo.Use(users => users.Create(new User(MattDamon), new User(GeorgeClooney), new User(BradPitt)) .Where(u => u.Username.Length > 8) .SortAscending(u => u.Username));For this, I got a few ideas, the one I like the most is the use of Command objects to defer each action on the data source until a Resolve() method is called.This my implementation of a command object: /** * Represents an action to be executed **/ public interface ICommand<TResult> { // The action's result (so anyone can inspect the output without executing it again) TResult Result { get; } // Executes the action TResult Execute(); } public class SimpleCommand<TResult> : ICommand<TResult> { // The action to execute private Func<TResult> _execution; private TResult _result; public TResult Result { get { return _result; } } // Creates a new command that will execute the specified function public SimpleCommand(Func<TResult> executeFunction) { _execution = executeFunction; } public TResult Execute() { return (_result = _execution()); } }I would then have the following base persistence strategy:/** * Represents a persistence strategy that has deferred behaviour**/public abstract class BaseDeferredPersistenceStrategy<TSource> : IDeferredPersistenceStrategy<TSource> where TSource : IPersistable{ protected abstract ICommand<IEnumerable<TSource>> DeferredGetAll(); // DeferredWhere and DeferredSort methods receive the previous command // because the implementation may reuse it. // (For example, a filter condition may be sent along the same request // that gets all the entities, so this should reuse the previous // command and not create a new one); protected abstract ICommand<IEnumerable<TSource>> DeferredWhere(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, bool>> expression); protected abstract ICommand<IEnumerable<TSource>> DeferredSort(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, object>> expression, bool ascending); protected abstract ICommand<IEnumerable<TSource>> DeferredGet(IEnumerable<object> keys); protected abstract ICommand<IEnumerable<TSource>> DeferredAdd(TSource persistable); protected abstract ICommand<IEnumerable<TSource>> DeferredUpdate(TSource persistable); protected abstract ICommand<IEnumerable<TSource>> DeferredDelete(IEnumerable<object> keys); private ICollection<ICommand<IEnumerable<TSource>>> _commands; public BaseDeferredPersistenceStrategy() { _commands = new HashSet<ICommand<IEnumerable<TSource>>>(); } public BaseDeferredPersistenceStrategy<TSource> GetAll() { _commands.Add(DeferredGetAll()); return this; } public BaseDeferredPersistenceStrategy<TSource> Where(Expression<Func<TSource, bool>> expression) { _commands.Add(DeferredWhere(_commands.LastOrDefault(), expression)); return this; } public BaseDeferredPersistenceStrategy<TSource> Sort(Expression<Func<TSource, object>> expression, bool ascending = true) { _commands.Add(DeferredSort(_commands.LastOrDefault(), expression, ascending)); return this; } public BaseDeferredPersistenceStrategy<TSource> Get(params object[] keys) { _commands.Add(DeferredGet(keys)); return this; } public BaseDeferredPersistenceStrategy<TSource> Add(TSource persistable) { _commands.Add(DeferredAdd(persistable)); return this; } public BaseDeferredPersistenceStrategy<TSource> Update(TSource persistable) { _commands.Add(DeferredUpdate(persistable)); return this; } public BaseDeferredPersistenceStrategy<TSource> Delete(params object[] keys) { _commands.Add(DeferredDelete(keys)); return this; } /** * Executes all the deferred commands in the order they were created **/ public IEnumerable<TSource> Resolve() { IEnumerable<TSource> result = Enumerable.Empty<TSource>(); // If the result of the command's execution is null, it means it was not a query, so leave the result as it is. foreach (var command in _commands) result = command.Execute() ?? result; return result; }}And this is one possible childs of the base class:/** * Represents a Cache Persistence Strategy**/public class CachedDeferredPersistenceStrategy<TSource> : BaseDeferredPersistenceStrategy<TSource> where TSource : IPersistable{ private ICache<TSource> _cache; // ICache<TSource> is injected public CachedDeferredPersistenceStrategy(ICache<TSource> cache) { _cache = cache; } protected override ICommand<IEnumerable<TSource>> DeferredGetAll() { return new SimpleCommand<IEnumerable<TSource>>(() => _cache.FetchAll()); } protected override ICommand<IEnumerable<TSource>> DeferredWhere(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, bool>> expression) { Func<TSource, bool> compiledExpression = expression.Compile(); return new SimpleCommand<IEnumerable<TSource>>(() => { // If the previous command was a query, then use the previous command's result. If not, then operate on all stored entities IEnumerable<TSource> persistables = previous != null && previous.Result != null ? previous.Result : _cache.FetchAll(); return persistables.Where(compiledExpression); }); } protected override ICommand<IEnumerable<TSource>> DeferredSort(ICommand<IEnumerable<TSource>> previous, Expression<Func<TSource, object>> expression, bool ascending) { Func<TSource, bool> compiledExpression = expression.Compile(); return new SimpleCommand<IEnumerable<TSource>>(() => { // If the previous command was a query, then use the previous command's result. If not, then operate on all stored entities IEnumerable<TSource> persistables = previous != null && previous.Result != null ? previous.Result : _cache.FetchAll(); return ascending ? persistables.OrderBy(compiledExpression) : persistables.OrderByDescending(compiledExpression); }); } protected override ICommand<IEnumerable<TSource>> DeferredGet(IEnumerable<object> keys) { return new SimpleCommand<IEnumerable<TSource>>(() => { string key = BuildCacheKey(keys); TSource value = _cache.Fetch(key); return value != null ? new [] { value } : Enumerable.Empty<TSource>(); }); } protected override ICommand<IEnumerable<TSource>> DeferredAdd(TSource persistable) { return new SimpleCommand<IEnumerable<TSource>>(() => { string key = BuildCacheKey(persistable); if(!_cache.Store(key, persistable, TimeSpan.FromMinutes(10))) throw new ArgumentException(Entity is already persisted, persistable); return null; }); } // ... Remaining methods ...}This would allow me to have a persistence strategy that can be queried like this:var result = _strategy.Where(u => u.IsValid).Sort(u => u.Id).Resolve();Of course, having an even higher layer (a repository) with the following method:// IDataAccessObject<TSource> is a collection of IDeferredPersistenceStrategy<TSource>.// It delegates each action to each registered strategies. // For instance, _dao.Create(user) will execute _cacheStrategy.Add(user), _sqlStrategy.Add(user), etc...public IEnumerable<TSource> Use(Func<IDataAccessObject<TSource>, IDataAccessObject<TSource>> operation){ return operation(_dao).Resolve();}would allow me to:var result = _userRepo.Use(users => users.Where(u => u.Username.Length > 8) .SortAscending(u => u.Username));What are the advantages and disadvantages of my approach? More importantly, is it scalable? Would it take too much effort to add a new persistence strategy? Is it too generic? Is it not generic enough?
Using commands as deferred behaviour
c#;object oriented;design patterns;api
null
_unix.152026
I am using latest BusyBox v1.22.1 in my target. I want to check the filesystem type using stat -f or df -T but busybox doesn't support such commands. busybox help shows stat command as supported but while executing its showing as stat: not found.How can I check the filesystem type using BusyBox?
Check the filesystem format with BusyBox (stat -f and df -T do not work)
linux;filesystems;busybox;stat
null
_webmaster.19664
I registered a couple of domains, and consider buying a few more, simply because I'm afraid they would be taken by someone else and I plan to create websites for them in the distant future. Right now they point to the information page of my registrar. Could I put them to better use for the time being without much hassle? Is it worth creating very minimal domain-related content and hosting it? Would that help SEO in the future or the contrary? Is there a chance of getting some adverts for a website stub, so that I could generate some income towards hosting costs?
what to do with temporarily unused domains?
domains
You can park them but it's common for Google and Bing to remove parked domains from their indexes when they notice this. It can be a problem/delay getting a domain to re-index with new content after this happens. Note that parking doesn't typically bring in much money at all.If you want to develop these domains later, then I'd recommend creating a simple coming soon type website with about 10 pages or so of meaningful content and no ads. Another option is to redirect them to an active domain you own although this can also cause temporary indexing problems with search engines when the site goes online completely.
_unix.302395
tl;dr version: I have a localdb.kdbx.tmp file on a local network drive that I can't rename/delete/copy/overwrite/open/etc. All attempts, sudo or otherwise, throw a Device or resource busy error. Running fuser and lsof shows nothing; as far as I can tell nothing is actively accessing the file and there is no associated PID or parent process. Remounting the drive with FUSE set to allow root and other users makes no difference. File permissions are normal and everything else in the directory (backups etc.) are behaving as expected.details: I have a KeePass shared database that's hosted on a local network drive shared between several on-site computers. Some of the machines run Windows, some run Linux. I'm personally using 32-bit Ubuntu 14.04 with keepass2 2.34 installed.When attempting to save some recent updates to the localdb.kdbx KP database yesterday (I was the only person accessing the file at the time), Keepass threw an error and said the database may be corrupted. I shut down my machine, assuming I could overwrite the file the next day. But when I came in and connected to the drive this morning, localdb.kdbx only existed as localdb.kdbx.tmp and no one can get it to open (KeePass specifically throws a lock violation on path error).I'd troubleshoot the issue on KeePass's forums, but we only need to be able to use the filename, so I'd be happy with just deleting it so I can recreate it from a backup. Problem is, I get a Device or resource busy error whenever I try to do anything with the file. Using lsof and fuser on the .tmp file just returns a blank with no PID, so there's nothing to kill and no way to free up the file for deletion. I thought it might be a FUSE issue and tried the solutions at How to get sudo access to shares mounted by Gigolo and WARNING: can't stat() fuse.gvfsd-fuse file system with no luck.Any tips?
Ubuntu: Immovable .tmp file on network drive with no PID
ubuntu;networking;files;process
ETA: I was mistaken; the drive is not an SMB Windows machine, but a machine running a QNAP Linux 3.2.26 build (which avahi-discover was picking up as Windows).Turned out the network drive was an SMB Windows machine (I'd mistakenly thought it was Linux) (see ETA) and the process locking the file was being run by Windows. I didn't take into account that lsof and fuser only return processes for the machine they're being run on (ie. my local machine, and not the network drive :).The network drive didn't have ssh enabled and smbclient didn't enable me to override the lock, so I asked our network admin to reboot the drive. The process terminated and I was able to delete the file.(For others' reference: I used avahi-discover to get the network drive's OS and other details.)Props to @derobert for pointing me in the direction of the server processes.
_softwareengineering.119203
At the moment we are writing modules for an open source cms.We would like to sell these with a license.But which are the best options?Any suggestions and experiences.
Which license for commercial software?
php;open source;licensing
null
_cs.19525
I would like to be able to represent circles in x-y coordinates.Each circle contains an x and y coordinates and radius in double data type.My goal is to compare circles with each other whether they are partially or completely overlapping.I am looking for efficient ideas. Honestly the only idea that comes to my mind is draw a line(let's say l1) from x1,y1 to x2,y2 and the length of this line is larger than addition of r1 and r2 then it does not overlap, if r1+r2 =< l1 then it overlaps, but I don't know how to find whether it is completely overlapping or partially. Also this wouldn't work for cases where I am combining more than one circle.
How to represent circles in x-y coordinates
algorithms;computational geometry;modelling
This answer considers two cases:the overlapping relation between two disks, which is a very simple problem.the ovelapping or covering of a disk by a set of other disks, which is somewhat harder in general.Case of two disksIt is indeed a good idea to use center and radius to represent yourcircles. However I think you are not thinking of circles, which areclosed planar lines formed of all points at a given distance $r$,called radius, of a point $c$ called the center. The planar surfaceenclosed by a circle, which also includes all points at a lesserdistance fron $c$ is called adisk (alsospelled disc).Regarding the various overlap situations for two disks, you have thefollowing test, assuming the two circles have radius $r_1$ and $r_2$(assuming witout loss of generality that $r_1\geq r_2$), with theircenters at distance $d$ (computable from the centers coordinates,thanks to Pythagoras):$r_1+r_2<d$ : disks are disjoint, no overlap.$r_1+r_2=d$ : disks are tangent externally, a single point of overlap.$r1-r2<d<r_1+r_2$ : disks are partially overlapping.$r_1-r_2=d$ : disks are tangent internally, total overlap of disk 2 by disk 1.$d<r_1-r_2$ : disk 1 overlap totally disk 2.There can be exact overlap of each disk by the other only when$r_1=r_2 \wedge d=0$Regarding the case of several disk, it is not clear whether you wantto see whether one distinguished disk is overlapped totally, partiallyor not at all by the others, or whether you want to check that foreach disk with everyone of the others, or possibly something else. You should make that more precise.Case of several disksThis is only a rough sketch, hopefully correct. Working out all details is a lot more work than can be included in an answer.As suggested in the question, we can represent a disk $D$ by atriple $(x,y,r)$ which gives the coordinates of the center, and the radius.Now if you have a disk $D_0=(x_0,y_0,r_0)$ and a set of disks$L=\{D_i\mid D_i=(x_i,y_i,r_i),\; i\in[1,n]\}$, your question, asmade more precise in a comment, ishow to check whether the disks of set $L$ together overlap partially,totally or not at all the disk $D_0$.First you want to make a list of the disks in $L$ that actuallyoverlap $D_0$. For that you can simply apply the above test to $D_0$ and$D_i$ for every $D_i$ in $L$. You get a set $I\subseteq[1,n]$ of indicessuch that D overlaps every $D_i$ for $i\in I$.If this set $I$ is not empty, you know that $D_0$ is overlapped by $L$.The question remains of a total overlap of $D_0$ by $L$.For this, you create a new set $J\subseteq I$ by removing indices ofdisks $D_i$ that are only externally tangent to $D_0$, overlapping it ononly one point.If $J$ is empty, you had only tangential overlapping in a finitenumber of point, but the set $L$ does not cover (fully overlap) the disk $D_0$.If $J$ is not empty, then $L$ completely overlap $D_0$ iff it does itwith the disks $D_i$ such that $i\in J$. Tangential overlapping on asingle point cannot contribute usefully to overlapping a surface.Now, all disks in $M=\{D_i\mid i\in J\}$ overlap $D_0$ on a fragmentof its surface.If one disk in $M$ completely overlaps $D_0$, then we have an answerof complete overlap. We can now assume it is not the case.Then the problem is to find an orderly strategy to check whether thedisks in $M$ completely cover $D_0$. We will now use disks from $M$one by one, removing them from M, to cover $D_0$. The strategy is inchoosing them.We chose first a disk in M (which we remove from M), such that it is notinternally tangent to $D_0$, but intersect the edge circle of $D_0$. Theremust be at least two such disks, else $D_0$ cannot be covered, as itsperimeter circle will nor be covered except for a finite number ofpoints.We compute the two points where the two circles intersect. They definetwo arcs, one on each circle, that delimit a surface yet to be coveredby the other circles. With respect to this surface, the arc belongingto $D_0$ is convex, while the other is concave.For simplicity and intuition, we call these intersections the anglesof the remaining surface. We call sides or edges the arcs between 2angles that delimit the remaining surface to be covered.We then chose one of the two angles, and look in M for another circlecovering this intersection. This new circle removes at least thisangle, and adds usually two new angles. We discuss this further below.One remark is that the arcs coming from $D_0$ are always convex, whilethe others are always concave. This is useful to visualize what can occur.Then we repeat the same step, until there are no angles left, in whichcase we have a covering of $D_0$, which is tested first, or untilthere are no disk left in M that can cover a chosen angle, in whichcase the overlap is incomplete.To understand this we have to look at intermediate steps in moredetails. During execution of the algorithm, we may have actuallycreated an uncovered curvy polygon with many angles. When we chose anew disk $D_i$ to cover a chosen angle $A$, we may actually coverseveral angles of the polygon, and the edges in between, so that weactually reduce the number of edges.So after choosing the disk $D_i$, we have to find the first edge onboth sides of the angle $A$ (not necessarily adjacent to $A$) that areintersected by the circle bounding $D_i$. These two intersections, oneon each side, define two new angles and a new edge provided $D_i$, andmay replace several edges and angles. Hence the number of sides of thepolygon may be reduced rather than increased. It may be also that allsides are covered, in wich case we have covered the whole disk.There may be cases when the new disk will cut the curvy polygon into twopolygons, that will both have to be covered. To check for that, thecircle bounding the disk has to be checked for intersection with alledges of the curvy polygon(s).All this implies of course to keep an up-to-date description of thecurvy polygon and the relations between angles, edges and disks.To keep correspondence between the relative positions of angles, ifthey are listed counter-clockwise on the curvy polygon(s), then theyshould be counter-clockwise on the circle of the disk $D_0$ andclockwise on the disks from $M$.There are quite a few details to be worked out, which I would not trywithout at least checking an implementation. But I believe this basicidea can be implemented.From this analysis, I think the time complexity is $O(n^2)$, sinceevery steps considers a new disk, and has to look at intersectionspotentially with all disks that have already been considered.The extension to spheres is left as an exercise.
_webmaster.74133
I have created a PDF presentation including links to a site I own on the last slide. So far, such links are not reported in Google Webmaster Tools. When I search Google for the presentation, I can find it. It is indexed.I know GWT can be slow at detecting backlinks, but should I expect those links to be reported in GWT? Would they be reported as SlideShare backlinks? Or not? Has anyone noticed such backlinks in their link profile?
Are links within SlideShare presentations indexed by search engines?
google search console;search engines;indexing;backlinks;pdf
this google article say linksin pdfs are crawled and can not be no followedhttp://googlewebmastercentral.blogspot.com.au/2011/09/pdfs-in-google-search-results.html
_unix.175148
I intend to start incremental backups of my Fedora 20 system, and would like to know what root directories I should include, and what directories it is useful to exclude. I know there is a lot of information on this on the 'net already, but none of it seems to answer this simple specific question. Looking at the answers already available on this site, they are useful, but so many end in etc, instead of being specific, which is not really very helpful.I assume that I needn't or shouldn't backup directories that are created or filled in by the system as it runs, for instance certainly not /run/media/Harry/CA6C321E6C32062B which is the hard drive that I will be saving the backup on. Are there any more like this?I will be using rsync in the system described here, which I have already tested on small runs. I have looked into luckyBackup as a GUI front end, but get lost in its technicalities (please see my footnote). I will use its task manager to form the command I need for rsync, when I know what files to include and exclude.In the event of a crash I envisage a re-installation of Fedora, then using the backup as a resource as I get going again, rather than trying to exactly reproduce the state just before the crash.What files should I include and exclude specifically?Footnote: In luckyBackup I do not see the way to use datestamps as in the reference I give, and I do not understand how to use the log of a dry run: why is it printed red, after some black lines at the start which I can no longer access because the log is so long?, and how do I find details of the errors to know if they matter? These are rhetorical questions, my real question is still only : what files to include and exclude, please?
What root directories should I back up?
fedora;rsync;backup
The important things are your data! Programs (and the rest of the system) can always be re-installed from scratch from DVD and your distro's repositories. That said, it may be a good idea to back-up /etc with your configurations (if you've done many changes) and perhaps /usr/local if you've installed many packages locally.The important stuff is /home with all your data... /var/mail or /var/spool/mail if you run a mail-server... local webpages (/var/www etc. )... and the content of your databases - MySQL, MariaDB, PostgreSQL (probably located somewhere in /var , but it may be better to do the backup with the database-server or a suitable program for dumping the databases).Of course you may make a back-up of your whole system, but since most (except /home, mail and databases) aren't likely to change much, it's hardly necessary to do incremental backups of everything. If you have the storage-space and want to make a complete backup of the whole system, doing so once every 3rd month or so should be sufficient - as long as you do incremental back-ups of your data! But remember, except for your data and configurations, the whole system may be reinstalled from DVD and your distro's repository; so you don't need to back it up.As for /home, mail and databases... Do a complete backup once a month... then a backup each week with weekly changes... and then finally each day - or perhaps several times a day - changes during the last day/since the last back-up. It depends on how much your home-directories, databases and mail changes each day and how important the data is.Alternatively, if your data changes a whole lot over just a week, you may concider making a full backup once every week (instead of monthly). You may also concider different cycles for different type of data - eg. full backup of /home monthly, /mail daily and databases several times aday. It depends on what services you run and how important the data are.PS: Making backup of a database that is running and therefore being changed, is a problem. Check your options and find the best solution for you.
_cseducators.2793
This is a question for those of you who have an intro class before AP Computer Science (or maybe even just an intro class). What order do you teach the topics in your intro class? I start with if statements, then go in the following order:While LoopsVariables (I do some hand-waving with variables before this point)For LoopsArraysOOPI used to start with variables a few years ago, but students seemed to have trouble getting the concept that early in the course. I'm not sure if I should go back to that now that I have more teaching experience and have a better idea of how to teach variables.
Order to Teach Topics in an Intro Programming Class
curriculum design;variables
I think this depends entirely on the programming language you use. Or maybe more accurately, you should choose a language that allows you to introduce the concepts in the order you want.I would use a language called Processing, which is built on top of Java and allows you to create visual, animated programs without any boilerplate code.I'd start with calling functions. Here's an entire Processing program:ellipse(20, 30, 40, 50);This program shows a window and draws a 40x50 oval at coordinates 20,30. There are other functions in Processing. Have the students draw a basic scene.Then I'd talk about using variables. Processing has a few predefined variables that come in handy:size(500, 500);ellipse(width/2, height/2, 200, 200);This program creates a 500x500 window and shows a circle in the middle of it. Have the students modify their scenes so they stretch to fit the screen, using the width and height variables.Then I'd talk about creating variables. Have students create their own variables that allow them to move their scene around, or easily change the color, etc.Then comes creating functions. Here's an example program:void setup(){ size(500, 500);}void draw(){ ellipse(mouseX, mouseY, 25, 25);}This program shows a window that draws a circle wherever the mouse is, 60 times per second.Hopefully this gives you an idea of Processing and the general approach. From here I'd cover these topics:DebuggingIf StatementsAnimationFor LoopsArraysUser InputUsing ObjectsCreating ClassesArrayListsImagesLibrariesDeploying your codeShameless self-promotion: I've put together a series of tutorials that cover all of these topics, available at HappyCoding.io. I'd be happy to help adapt these tutorials into an introductory curriculum.
_unix.245259
How do I export variables from a PHP script in Bash?I'm writing a Bash script to read database names from config.php files of each website, and then import the database from the backup repository.I tried to use source config.php but it seems it doesn't recognize PHP variables.Any help would be appreciated.
How to read variables from a php file in bash
bash;php
A very simplified version would be something as follows:2 lines in config.php:cat config.php$variable1 = 'foo with bar';$variable1 = 'foo2 with bar2';Set Bash $variable1 to last matching instance of $variable1 in config.php, just in case it has been reset. If you want to change it to the first match, simply change tail -1 to head -1 in the following code:variable1=$(grep -oE '\$variable1 = .*;' config.php | tail -1 | sed 's/$variable1 = //g;s/;//g')Confirm Bash variable via echo:echo $variable1'foo2 with bar2'Note that this will mostly work for strings. There are many types of PHP variables that cannot be directly converted to Bash variables. The code above will grab the last $variable1 referenced in config.php. Like I said, if that variable has been set multiple times, you can set to the first value or last value by toggling head or tail in the Bash command that sets the variable.
_unix.312424
I want to change my OS to Linux Mint in my Windows 7 laptop without loosing any of the files in my hard disk. Please help me.
How to install without loosing any data in my HDD
linux mint;windows;system installation
null
_unix.37492
I need to install a linux distribution; i like the distro debian-like. I used to use ubuntu, i tryied the new version..it seems to me to be a fake of Mac OS...something just to let you say: yeee i have a dock too...:(Can you suggest me some distributions that are similar to the previous ubuntu versions?I mean professional and user friendly, not just eyecandy that use 30% CPU to open a window...
Suggest me a distro beetwen debian and ubuntu?
distribution choice;distros
Are you sure it isn't mac saying, Look we have a desktop like GNOME!.openSUSE is nice and comes in several flavours like KDE (windows like with several add-ons), gnome (like mac...), and lxde/xfce (lighweight distros).It uses an RPM based package management system with zypper (libzypp).YaST is also awesome in openSUSE. It makes system management very user-friendly.If you don't like what you see, build your own with suseStudio!Not sure if they are like 'previous ubuntu' versions. But the open source world is always advancing/changing and it doesn't hurt to adapt and learn new things.
_webapps.60449
I have installed Mozilla Thunderbird, now it updated to version 24.5.0 .I am trying to download all the emails from my Gmail account to Thunderbird. The problem is that only emails from 8 August 2013 are being downloaded, whereas my actual first emails date to 17 October 2011.How can I download the remaining ( older ) emails too ?
Mozilla Thunderbird Get Mail doesn't get all the mail from the beginning
gmail;email;thunderbird
null
_codereview.12545
We are building a interactive tile-based (32x32 px) (game) map where the user can move around. However we experience lag (some sort of a delay on the movement) and we need to work around this problem. The hack/lag also happen on a local server so it's not because of the traffic yet.Any suggestions how we can make the rendering of the map and performance of the map faster?DISCLAIMER: The code is fast-written, we are beware of the security issues, please do not point them outmap.php<?phpsession_start();$_SESSION['angle'] = 'up';$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());mysql_select_db('hol', $conn) or die(mysql_error());$query = mysql_query(SELECT x, y FROM hero WHERE id = 1);$result = mysql_fetch_assoc($query);$startX = $result['x'];$startY = $result['y'];$fieldHeight = 10;$fieldWidth = 10;//x = 0 = 4//y = 0 = 4$sql = SELECT id, x, y, terrain FROM map WHERE x BETWEEN .($startX-$fieldWidth). AND .($startX+$fieldWidth). AND y BETWEEN .($startY-$fieldWidth). AND .($startY+$fieldHeight);$result = mysql_query($sql);$map = array();while($row = mysql_fetch_assoc($result)) { $map[$row['x']][$row['y']] = array('terrain' => $row['terrain']);}ob_start();echo '<table border=\'0\' cellpadding=\'0\' cellspacing=\'0\'>';for ($y=$startY-$fieldHeight;$y<$startY+$fieldHeight;$y++) { echo '<tr>'; for ($x=$startX-$fieldWidth;$x<$startX+$fieldWidth;$x++) { if ($x == $startX && $y == $startY) { echo '<td style=width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');><img src=char/medic_' . $_SESSION['angle'] . '.png alt= /></td>'; } else { //echo '(' . $x . ',' . $y . ')';echo '<td style=width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');></td>'; } } echo '</tr>';}echo '</table>';$content = ob_get_contents();ob_end_clean();?><!DOCTYPE html><html> <head> <title>Map</title> <meta charset=utf-8> <script type=text/javascript src=js/jquery.js></script> <script type=text/javascript> $(document).ready(function() { $(document).keyup(function(e){ if (e.keyCode == 37) { move(West); return false; } if (e.keyCode == 38) { move(North); return false; } if (e.keyCode == 39) { move(East); return false; } if (e.keyCode == 40) { move(South); return false; } }); $(.direction).click(function() { move($(this).text()); }); function move(newDirection) { var direction = newDirection; $.ajax({ type: POST, url: ajax/map.php, data: { direction: direction }, success: function(data) { $('#content').html(data); } }); } /* $(#content).click(function() { var x = 3; var y = 3; $.ajax({ type: POST, url: ajax.php, data: { x: x, y: y }, success: function(data) { $('#content').html(data); } }); }); */ }); </script> <style type=text/css>td {margin: 0; border: none; padding: 0;}img{ display:block;margin:0;} . </style> </head> <body> <div id=content><?php echo $content; ?></div> <div class=result></div> <button class=direction>South</button> <button class=direction>North</button> <button class=direction>West</button> <button class=direction>East</button> </body></html>ajax/map.php<?phpsession_start();$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());mysql_select_db('hol', $conn) or die(mysql_error());//Get Player's current position$query = mysql_query(SELECT x, y FROM hero WHERE id = 1);$result = mysql_fetch_array($query);$current_x = $result['x'];$current_y = $result['y'];switch ($_POST['direction']) { case 'North': if ($current_y - 1 < 0) { echo 'Invalid path'; } //Next tile $x = $current_x; $y = $current_y - 1; $_SESSION['angle'] = 'up'; break; case 'South': if ($current_y + 1 > 500) { echo 'Invalid path'; } $x = $current_x; $y = $current_y + 1; $_SESSION['angle'] = 'down'; break; case 'West': $x = $current_x - 1; $y = $current_y; $_SESSION['angle'] = 'left'; break; case 'East': $x = $current_x + 1; $y = $current_y; $_SESSION['angle'] = 'right'; break;}$result = mysql_query(SELECT walkable FROM map WHERE x = $x AND y = $y);$row = mysql_fetch_array($result);//Is the next tile walkable?if ($row['walkable'] == 1) { //Update Player's position mysql_query(UPDATE hero SET x=$x, y=$y WHERE id = 1); $startX = $x;$startY = $y;} else { $startX = $current_x; $startY = $current_y;}$fieldHeight = 10;$fieldWidth = 10;//x = 0 = 4//y = 0 = 4$sql = SELECT id, x, y, terrain FROM map WHERE x BETWEEN .($startX-$fieldWidth). AND .($startX+$fieldWidth). AND y BETWEEN .($startY-$fieldWidth). AND .($startY+$fieldHeight);$result = mysql_query($sql);$map = array();while($row = mysql_fetch_assoc($result)) { $map[$row['x']][$row['y']] = array('terrain' => $row['terrain']);}ob_start();echo '<table border=\'0\' cellpadding=\'0\' cellspacing=\'0\'>';for ($y=$startY-$fieldHeight;$y<$startY+$fieldHeight;$y++) { echo '<tr>'; for ($x=$startX-$fieldWidth;$x<$startX+$fieldWidth;$x++) { if ($x == $startX && $y == $startY) { echo '<td style=width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');><img src=char/medic_' . $_SESSION['angle'] . '.png alt= /></td>'; } else { //echo '(' . $x . ',' . $y . ')';echo '<td style=width:32px; height:32px; background-image:url(\'tiles/' . (isset($map[$x][$y]['terrain']) ? $map[$x][$y]['terrain'] : 'water') . '\');></td>'; } } echo '</tr>';}echo '</table>';$content = ob_get_contents();ob_end_clean();echo $content;
Improve the performance of jquery/php generated map
php;performance;mysql;ajax
null
_unix.13706
I'm running Grub .97 with an OpenSuSE 11.2 and Windows XP installation. I configure the grub password in OpenSuSE 11.2 via the Boot Loader module. However, when I type in the password in grub, during bootup, I simply get a Failed message. I have tried about three or four different passwords. I can boot up, I just can't use the password to edit anything about grub.I have also tried setting the grub password via the command line by typing grub to go to the interactive menu, typing md5crypt, typing my password, and copying the hashed password to the menu.lst file. Still no luck when I enter the password.
Grub does not recognize password
grub;opensuse;dual boot
I found the answer to my problem here. If I use the md5crypt command to generate my password, I need to enter --md5 between my password and the encrypted password. Now this works. So, before the title entries in my /boot/grub/menu.lst file I have the line with a password. This now reads password --md5 encrypted_password.Based on my experience, it appears that setting the password for the Boot Loader via YaST does not work correctly for OpenSuSE 11.2. I have not yet checked to see if adding a --md5 to the encrypted password provided by YaST would cause it to work, I've only tried the md5crypt method with this.
_unix.88621
I'm currently planning my business servers and I would like to know what's the best Linux distro for these needs:Nginx + MySQL + PHP 5.4Zimbra Collaboration - Open SourceNode.js w/ ForeverI know it's a objective question but I asked a lot of people and they didn't answer me other thing than It's your choice...I have a 2 CPU, 1GB RAM, 30GB SSD server...
Best Linux for a small Web server
email;php;mysql;nginx;node.js
You might want to use a distribution that has a low footprint. Debian quickly comes to mind, but I can't see why you wouldn't use ubuntu or centos or even gentoo or arch.In the end of the day, you should use the distribution you feel more comfortable with.
_unix.208036
I have a Raspberry Pi connected to a router (Router1) with internet connection in en0, with IP 192.168.1.110,however I have my RPi's wifi port (wlan0) connected to another router (Router2) with IP 172.31.198.123 (another LAN network).Now my Macbook is connected to Router2(e.g. with IP 172.31.198.100), and I want to reach the internet through my Raspberry Pi (maybe setting up a VPN server or something like that on the Pi).Only when I take out my cable (en0), can I ping through 172.31.198.123 from my Mac.Otherwise the Pi will use en0 and I can't ping through 172.31.198.123.Could anyone tell me how to do it?auto loiface lo inet loopbackauto eth0allow-hotplug eth0iface eth0 inet staticaddress 192.168.1.110netmask 255.255.255.0broadcast 192.168.1.255gateway 192.168.1.1auto wlan0allow-hotplug wlan0iface wlan0 inet manualwpa-conf /etc/wpa_supplicant/wpa_supplicant.confauto wlan1allow-hotplug wlan1iface wlan1 inet manualwpa-conf /etc/wpa_supplicant/wpa_supplicant.conf~$ sudo cat /etc/wpa_supplicant/wpa_supplicant.confctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdevupdate_config=1network={ ssid=XXXX-WiFi key_mgmt=NONE}
How to share one internet connection from LAN to another LAN?
networking;raspberry pi
null
_cs.43816
I'm in doubt about that because in Google's results for a search on bill clinton [1],the server The 'Unofficial' Bill Clinton (94.06%) appears first than the server President Bill Clinton - The Dark Side (97.27%) and there is no feedback mechanism modifing the ranks.Since I've noticed that, I am wondering if google uses some algorithm for efficiently intesecting inverted indices that exploits the PageRank although not completely preserving order.[1] The Anatomy of a Large-Scale Hypertextual Web Search Enginehttp://infolab.stanford.edu/~backrub/google.html
Does Google's search algorithm really respect order of relevance imposed by PageRank?
information retrieval
null
_softwareengineering.13786
I was asked to make some small technical presentation about specific application scalability. The application is developed using Java, Spring MVC, Hibernate. I have access to the application source code.How can I measure software scalability (using sources) and what metrics do I need to look after when measuring software scalability?
How is software scalability measured?
scalability;metrics
I would start with reading Wikipedia article on the subject.In short, scalability is how system performance grows with adding more resources or, alternatively, how the resource utilization grows with increasing load. For example, how many concurrent users can your site handle until response time grows beyond 0.3 sec? The same question after you double the available RAM/disk/CPU/etc. You probably can use your knowledge of the application internals to decide which parameters are worth checking. Setup a test bench with a server machine and one or more client machines. Use some tool to limit the amount of resources available to the server (e.g. ulimit) or run some interfering application on the server. Measure how the server deals with client requests. Repeat the above gradually increasing/decreasing interfering load/available resources. At the end you get n-dimensional space with dots in it. It may be simpler to change only one parameter at a time while fixing all the others at some typical value (or a couple of values). In this case you can represent the result as a bunch of 2D graphs with server performance (e.g. number of users/requests) on one axis and resource utilization/availability on the other.There are more complex scenarios where your application uses several servers for several part of the application and you can vary their amount and ratio, but I guess it's not your case. At most, you probably may want to vary the number of threads/processes, if this matters.If you measure the whole application you usually don't need source code access. However, you may be interesting in measuring some specific part of the code (e.g. only DB or UI). Then you can use the source code to expose only this module for measurements and run your tests. This is called a microbenchmark.If you're looking for examples, there is a plenty of them in academic articles. Search the google scholar for performance evaluation + your preferred terms.
_softwareengineering.236451
I'm seeking vital naming of string filename parameter in parameter list used in various methods where filename with full path is expected. In many cases also UNC path can be actually supplied as full path because many libraries handle it natively.I usually call the parameter just filename, but it can be misleading in two ways:Beginners tend to think it is only name of file without path.If there is a need of splitting the value into path and filename, term filename sticks better with filename part without path which appeared after split. Anyway, it is not easy to give that second part better name than filename. Alternative of splitting filename to path and filenameOnly looks weird to me.I think it might be better to use clearly distinguishable term for filename with path than borrowing filename which already has stronger meaning for something else.I was thinking about term absoluteFilePath or fullyQualifiedFilename to stand as argument names. Maybe they are good and I need only some encouragement to start using them, but I would like to understand your best practices.EDIT: I would still like to stick with official VB.NET naming and capitalization conventions, so the only thing I need help sharpening is clear self-documenting wording of the term. (Not whether I should use Hungarian notation or not I cannot.)
How to name filename parameter to make clear it should contain full path?
naming;file handling;conventions
It sounds like you'd be safer defining a code contract.You can say a precondition of this method is that the path supplied is an absolute path.You can make this clearer by naming the input parameter String absolutePathToFile.And finally, you can make your method fail early if the preconditions aren't met. Do this by checking if the absolutePathToFile is indeed an absolute path. If not, throw an argument exception.So, instead of simply picking a parameter name and hoping the next developers a) pay attention to it, and b) understand it the same way you do (both of which are unlikely), you do the following:Code Contract: Explicitly declare your method preconditions. You can put this in your documentation, or as inline method documentation (if your language/ide supports it)Self Documenting Code: Choose a parameter name that describes what you want as clearly as possible (not always easy)Defensive Programming: Check your method parameters to see if they're valid. If not, fail hard and fail early.
_unix.87941
I'm trying to do the following:set a = kittenset temp_kitten = purrecho ${temp_$a}I want the echo command to return purr.The overall idea is that I have a bunch of variables in an array and a bunch of temp_variables in another array and I want to loop through them in a single foreach loop for comparison.
How achieve variable indirection (refer to a variable whose name is stored in another variable) in tcsh
shell script;tcsh;variable substitution
You can use eval:eval echo \$temp_$aReferencesBash variable indirection
_codereview.44482
Given an array start from the first element and reach the last by jumping. The jump length can be at most the value at the current position in the array. Optimum result is when u reach the goal in minimum number of jumps. For example: Given array A = {2,3,1,1,4} possible ways to reach the end (index list) i) 0,2,3,4 (jump 2 to index 2, then jump 1 to index 3 then 1 to index 4) ii) 0,1,4 (jump 1 to index 1, then jump 3 to index 4) Since second solution has only 2 jumps it is the optimum result.A lot of input has been derived from previous review here.public final class JumpGame { private JumpGame() {} /** * Returns the shortest jump path from the source to destination * * @param jump The jump array * @return Returns one of the shortest paths to the destination. */ public static List<Integer> getShortestJumps(int[] jump) { final List<Integer> list = new ArrayList<Integer>(); list.add(0); for (int i = 0; i < jump.length - 1; ) { int iSteps = Math.min(jump.length - 1, i + jump[i]); // iSteps is all the consecutive steps reachable by jumping from i. int maxStep = Integer.MIN_VALUE; // max step is one of the step in iSteps, which has the max potential to take us forward. /* trying each step of iSteps */ for (int j = i + 1; j <= iSteps; j++) { /* being greedy and picking up the best step */ if (maxStep < jump[j]) { maxStep = j; } } list.add(maxStep); i = maxStep; // jump to the maxStep. } return list; } public static void main(String[] args) { int[] a1 = {2,3,1,1,4}; List<Integer> expected = new ArrayList<Integer>(); expected.add(0); expected.add(1); expected.add(4); Assert.assertEquals(expected, getShortestJumps (a1)); int[] a2 = {3, 1, 10, 1, 4}; expected = new ArrayList<Integer>(); expected.add(0); expected.add(2); expected.add(4); Assert.assertEquals(expected, getShortestJumps (a2)); }}
Jump game to find minimum hops from source to destination
java;algorithm
Code-StyleFor the most part, this is good:return types are good.Collections are well typedmethod names are goodapart from list, a1, and a2, variable names are goodThe list is a bad name for a List. The fact that it is a list is obvious... but, what is the list...? I prefer result to list.a1 and a2 are not bad, but they are not good either. They are just 'OK'.AlgorithmI have worked the code through, and figure there is a plane-jane O(n) solution to the problem. Your algorithm is something larger than O(n), It is closer to O(n * m) where m is the longest jump.The alternate algorithm I cam up with sets up a 'range' for the next jump.... It seaches all the values from the current cursor to the current range, and it looks for the jump within that range that would extend the range the furthest.The method looks like:public static List<Integer> getShortestJumps(int[] jump) { final List<Integer> list = new ArrayList<Integer>(); if (jump.length == 0) { return list; } int cursor = 0; int best = 0; int range = 0; int remaining = 1; while (cursor + 1 < jump.length) { if (cursor + jump[cursor] > range) { // jumping from here would extend us further than other alternatives so far range = cursor + jump[cursor]; best = cursor; if (range >= (jump.length - 1)) { // in fact, this jump would take us to the last member, we have a solution list.add(best); break; } } if (--remaining == 0) { // got to the end of our previous jump, move ahead by our best. list.add(best); remaining = range - cursor; } cursor++; } // always add the last member of the array list.add(jump.length - 1); return list;}
_webmaster.69477
I'm learning HTML at www.w3schools.com/html/html_urlencode.asp and don't understand this sentence:host - defines the domain host (default host for http is www)Example scheme://host.domain:port/path/filenameExplanation: scheme - defines the type of Internet service (most common is http) host - defines the domain host (default host for http is www) domain - defines the Internet domain name (w3schools.com) port - defines the port number at the host (default for http is 80) path - defines a path at the server (If omitted: the root directory of the site) filename - defines the name of a document or resourceWhat is the relation between domain host and www?
How to understand scheme://host.domain:port/path/filename?
domains;web hosting;dns;subdomain
http://www.w3schools.com/html/html_urlencode.aspThe domain = w3schools.comwww is the host.The path is /html/ And the file is html_urlencode.asp
_codereview.151566
I have solved Project Euler's problem number 47, which reads:The first two consecutive numbers to have two distinct prime factors are:14 = 2 7 15 = 3 5The first three consecutive numbers to have three distinct prime factors are:644 = 22 7 23 645 = 3 5 43 646 = 2 17 19.Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?The correct answer is : 134043.I used some sort of memoization to work out the problem but the performance is still pretty bad: 5.45.5 seconds. The trick in this question here is that the prime factors can actually be on some power which if evaluated doesn't result in a prime number but if the base is prime it's fine: e.g., 22 = 4.Here is my solution:public class Problem47 : IProblem{ public int ID => 47; public string Condition => ProblemsConditions.ProblemConditions[ID]; //Key - value to power //Value - factorized value private readonly Dictionary<int, bool> passedNumbers = new Dictionary<int, bool>(); private readonly Dictionary<int, int> factorizedPowers = new Dictionary<int, int>(); private readonly HashSet<int> primes = new HashSet<int>(); private const int primeFactorCount = 4; public ProblemOutput Solve() { Stopwatch sw = Stopwatch.StartNew(); for (int i = 2 * 3 * 5 * 7; ; i++) { int[] numbers = { i, i + 1, i + 2, i + 3 }; int skipAmount = 0; foreach (int n in numbers) { bool value; if (passedNumbers.TryGetValue(n, out value)) { if (!value) { skipAmount = n - (i - 1); } } else { passedNumbers.Add(n, HasNPrimeFactors(n, primeFactorCount)); if (!passedNumbers[n]) { skipAmount = n - (i - 1); } } } if (skipAmount != 0) { i += skipAmount - 1; continue; } sw.Stop(); return new ProblemOutput(sw.ElapsedMilliseconds, numbers[numbers.Length - primeFactorCount].ToString()); } } private bool HasNPrimeFactors(int input, int n) { Dictionary<int, int> factors = new Dictionary<int, int>(); for (int i = 2; input > 1 ; i++) { if (input % i == 0) { if (primes.Contains(i) || IsPrime(i)) { if (!primes.Contains(i)) { primes.Add(i); } if (factorizedPowers.ContainsValue(i)) { int maximizedPower = GetMaximizedFactor(input, i); input /= maximizedPower; if (factors.ContainsKey(i)) { factors[i] += GetPowerOfValue(maximizedPower, i); } else { factors.Add(i, GetPowerOfValue(maximizedPower, i)); } } else { input /= i; if (factors.ContainsKey(i)) { factors[i]++; factorizedPowers.Add((int) Math.Pow(i, factors[i]), i); } else { factors.Add(i, 1); } } } } if (i > input) { i = 1; } } return factors.Count == n; } private int GetMaximizedFactor(int input, int value) { var matches = factorizedPowers.Where(x => x.Value == value && input % x.Key == 0); return matches.Any() ? matches.Max().Key : value; } private static int GetPowerOfValue(int input, int value) { int count = 0; while (input > 1) { input /= value; count++; } return count; } private bool IsPrime(int value) { if (value < 2) { return false; } if (value % 2 == 0) { return value == 2; } if (value % 3 == 0) { return value == 3; } if (value % 5 == 0) { return value == 5; } if (value == 7) { return true; } for (int divisor = 7; divisor * divisor <= value; divisor += 30) { if (value % divisor == 0) { return false; } if (value % (divisor + 4) == 0) { return false; } if (value % (divisor + 6) == 0) { return false; } if (value % (divisor + 10) == 0) { return false; } if (value % (divisor + 12) == 0) { return false; } if (value % (divisor + 16) == 0) { return false; } if (value % (divisor + 22) == 0) { return false; } if (value % (divisor + 24) == 0) { return false; } } return true; }}Please ignore the inheritance, the ID and Condition properties, and the ProblemOutput class. Those are irrelevant for this question and have no effect on the program whatsoever.
Project Euler #47: Distinct primes factors
c#;performance;programming challenge;primes
If you're working through the Project Euler questions, you should become familiar with the Seive of Eratoshenes.Not only is it a very simple way to generate a bunch of prime numbers at once, but it's an algorithm which can be subtly modified to solve other problems.In this problem, we want to calculate how many prime factors each number in a range has. We've going to be testing a lot of numbers, so it would be great if we can calculate all of the factor counts at once. And we can!First, pick a safe top number that we're going to test up to. I'll guess that the answer will be a number less than a million.Create an array of a million zeros. It starts as an array of zeros, but we want to transform this array so that:array[i] == count_of_factors(i)Start at 2. array[2] == 0, so therefore 2 is prime. Now we can add 1 to {array[4], array[6], array[8] ... array[999998]}, because they are factors of 2.Move to 3. array[3] == 0, so add 1 to {array[6], array[9], array[12] ... array[999999]}Move to 4. array[4] == 1. (We've already incremented it) Because it is not 0, we know it is not a prime number, so we ignore it.Move to 5. array[5] == 0, so add 1 to {array[10], array[15], array[20], array[25]...array[999995]And so on. When you're done, every number will either be 0 (if the index is prime), or it will be the count of prime factors of that index. Now it's as simple as finding the first four contiguous fours.This solution takes around 130 milliseconds:static int SolveProblem(){ int[] factorCounts = new int[1000000]; for(int i = 2; i < factorCounts.Length; ++i) { if(factorCounts[i] == 0) // It's Prime { for(int j = i*2; j < factorCounts.Length; j+=i) { ++factorCounts[j]; } } } // Now find the first four contiguous fours int contiguousFours = 0; for (int i = 210; i < factorCounts.Length; ++i) { contiguousFours = factorCounts[i] == 4 ? contiguousFours + 1 : 0; if(contiguousFours == 4) { return i - 3; } } return -1;}But we can do better than this. The above code has two loops: one which calculates the factor counts and one which searches for the contiguous fours. Lets merge this into one loop: that way it will stop generating factor counts as soon as it finds the fours.static int SolveProblem(){ int[] factorCounts = new int[1000000]; int contiguousFours = 0; for(int i = 2; i < factorCounts.Length; ++i) { contiguousFours = factorCounts[i] == 4 ? contiguousFours + 1 : 0; if (contiguousFours == 4) { return i - 3; } if (factorCounts[i] == 0) // It's Prime { for(int j = i*2; j < factorCounts.Length; j+=i) { ++factorCounts[j]; } } } return -1;}Now we're down to 85 milliseconds.
_codereview.24431
Requirements:Given a long section of text, where the only indication that a paragraph has ended is a shorter line, make a guess about the first paragraph. The lines are hardwrapped, and the wrapping is consistent for the entire text.The code below assumes that a paragraph ends with a line that is shorter than the average of all of the other lines. It also checks to see whether the line is shorter merely because of word wrapping by looking at the word in the next line and seeing whether that would have made the line extend beyond the maximum width for the paragraph.def get_first_paragraph(source_text): lines = source_text.splitlines() lens = [len(line) for line in lines] avglen = sum(lens)/len(lens) maxlen = max(lens) newlines = [] for line_idx, line in enumerate(lines): newlines.append(line) try: word_in_next_line = lines[line_idx+1].split()[0] except IndexError: break # we've reached the last line if len(line) < avglen and len(line) + 1 + len(word_in_next_line) < maxlen: # 1 is for space between words break return '\n'.join(newlines)Sample #1Input:This is a sample paragaraph. It goes on and on for several sentences. Many OF These Remarkable Sentences are Considerable in Length.It has a variety of words with different lengths, and there is not aconsistent line length, although it appears to hover supercalifragilisticexpialidociously around the 70 character mark.Ideally the code should recognize that one line is much shorter thanthe rest, and is shorter not because of a much longer word followingit which has wrapped the line, but because we have reached the end ofa paragraph.This is the next paragraph, and continues onwards formore and more sentences.Output:This is a sample paragaraph. It goes on and on for several sentences.Many OF These Remarkable Sentences are Considerable in Length.It has a variety of words with different lengths, and there is not aconsistent line length, although it appears to hoversupercalifragilisticexpialidociously around the 70 character mark.Ideally the code should recognize that one line is much shorter thanthe rest, and is shorter not because of a much longer word followingit which has wrapped the line, but because we have reached the end ofa paragraph.Using other sample inputs I see there are a few issues, particularly if the text features a short paragraph or if there is more than one paragraph in the source text (leading to the trailing shorter lines reducing the overall average).
Given a random section of text delimited by line breaks, get the first paragraph
python;strings
null
_codereview.71523
I'm not really even sure if this counts as a game. There is so little code, but it works. It is a game where you have to guess the computers number, and it tells you how many times you took to get it right. I kind of want feedback, and not ways to improve the code. I want to know ways to improve my future projects and what to avoid again.def main(): # Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random def ask_number(question, low, high, step): response = None while response not in range(low, high): response = int(input(question)) return response tries += step #Opening Remarks print(Welcome to 'Guess My Number'!) print(I'm thinking of a number between 1 and 100.) print(Try to guess it in as few attempts as possible.) # set the initial values the_number = random.randint(1, 100) # Create the priming read here tries = 0 guess= 0 while int(guess) != int(the_number): guess = ask_number(Enter your guess:, 1, 100, 1) if int(guess) == int(the_number): print(Your right on the money!) elif int(guess) > int(the_number): print(To high!) elif int(guess) < int(the_number): print(To low!) tries += 1 #Didnt know how to make it reloop to the start... print(You guessed it! The number was, the_number) print(And it only took you, tries, tries!) #Program Closing input(Press the enter key to exit.)main()
Number-guessing game
python;number guessing game
import random should be at the top of the script.The call to main should be guarded by if __name__ == __main__:.the_number and guess are already int, so the repeated calls to e.g. int(the_number) are redundant.Docstrings should be formatted properly, as multi-line strings not comments #. Many of the actual comments are redundant - it's generally obvious what's going on (well done!)The step argument to ask_number doesn't make much sense, and there's no error handling for non-numeric inputs.The magic numbers 1 and 100 should be factored out.Use str.format for combining strings with other objects.Think about your logic more carefully - if guess isn't equal to or greater than the_number it must be less, you can just use else.100 isn't in range(1, 100).I would write it as:import random def main(low=1, high=100): Guess My Number The computer picks a random number between low and high The player tries to guess it and the computer lets the player know if the guess is too high, too low or right on the money print(Welcome to 'Guess My Number'!) print(I'm thinking of a number between {} and {}..format(low, high)) print(Try to guess it in as few attempts as possible.) the_number = random.randint(low, high) tries = 0 while True: guess = ask_number(Enter your guess:, low, high) if guess == the_number: print(You're right on the money!) break elif guess > the_number: print(Too high!) else: print(Too low!) tries += 1 print(You guessed it! The number was {}..format(the_number)) print(And it only took you {} tries!.format(tries)) input(Press the enter key to exit.)def ask_number(question, low, high): Get the user to input a number in the appropriate range. while True: try: response = int(input(question)) except ValueError: print Not an integer else: if response in range(low, high+1): return response print Out of rangeif __name__ == __main__: main()To play again, you could recursively call main, or have a loop at the end of the script:if __name__ == __main__: while True: main() again = input(Play again (y/n)? ).lower() if again not in {y, yes}: break
_unix.84616
I've checked out GPU usage monitoring (CUDA), but are there similar tools for AMD/ATI cards? Or kind of universal tools? I want to check out if my applications use the 256 MB of RAM of the video card at all, since I've seen applications that uses lots system memory, while they should rather use the video cards.glxinfo does not provide the information I'm looking for, but maybe you will ask if I have HW Acceleration:$ glxinfo | grep renderdirect rendering: YesOpenGL renderer string: Gallium 0.4 on ATI RV515The info about the card:03:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] RV515 [Radeon X1300/X1550] (prog-if 00 [VGA controller]) Subsystem: VISIONTEK Device 2352 Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx- Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx- Latency: 0, Cache Line Size: 16 bytes Interrupt: pin A routed to IRQ 19 Region 0: Memory at d0000000 (64-bit, prefetchable) [size=256M] Region 2: Memory at bffe0000 (64-bit, non-prefetchable) [size=64K] Region 4: I/O ports at e000 [size=256] Expansion ROM at bffc0000 [disabled] [size=128K] Capabilities: [50] Power Management version 2 Flags: PMEClk- DSI- D1+ D2+ AuxCurrent=0mA PME(D0-,D1-,D2-,D3hot-,D3cold-) Status: D0 NoSoftRst- PME-Enable- DSel=0 DScale=0 PME- Capabilities: [58] Express (v1) Endpoint, MSI 00 DevCap: MaxPayload 128 bytes, PhantFunc 0, Latency L0s <4us, L1 unlimited ExtTag+ AttnBtn- AttnInd- PwrInd- RBE- FLReset- DevCtl: Report errors: Correctable- Non-Fatal- Fatal- Unsupported- RlxdOrd+ ExtTag- PhantFunc- AuxPwr- NoSnoop+ MaxPayload 128 bytes, MaxReadReq 128 bytes DevSta: CorrErr- UncorrErr- FatalErr- UnsuppReq- AuxPwr- TransPend- LnkCap: Port #0, Speed 2.5GT/s, Width x16, ASPM L0s L1, Latency L0 <64ns, L1 <1us ClockPM- Surprise- LLActRep- BwNot- LnkCtl: ASPM Disabled; RCB 64 bytes Disabled- Retrain- CommClk- ExtSynch- ClockPM- AutWidDis- BWInt- AutBWInt- LnkSta: Speed 2.5GT/s, Width x1, TrErr- Train- SlotClk+ DLActive- BWMgmt- ABWMgmt- Capabilities: [80] MSI: Enable- Count=1/1 Maskable- 64bit+ Address: 0000000000000000 Data: 0000 Kernel driver in use: radeonI know there is Process Explorer in Windows, and it works with my card so the thing is Linux Kernel - driver/module - tool.
Is there any tool to view live statistics about a Radeon GPU?
hardware;performance;utilities
There's a program called radeontop which should provide some or all of the information you're after.I've installed and run it on my debian laptop (which has a Radeon HD 6320 GPU) and it seems to work as advertised.If you need data for further processing rather than a top-like display, it has a -d or --dump option for dumping the data to a file (unfortunately, only as percentages rather than as raw numbers). Examining the source code will tell you how to get at the raw data yourself.The debian packaged version has the following description.Package: radeontopDescription-en: Utility to show Radeon GPU utilization radeontop is a small utility which allows one to monitor the utilization of Radeon GPUs starting from the R600 series and newer using undocumented performance counters in the hardware. The utility works with the free drivers. . It displays the utilization of the graphics pipe, event engine, vertex cache, vertex group and tesselator, texture addresser and cache, the shader units and more, both with a relative percent value as well as a colorful bar diagram.Homepage: https://github.com/clbr/radeontop
_softwareengineering.209930
Insofar as I understand it, tools like Git and Mercurial derive checksums from their data, and those checksums are used to derive other checksums used in aggregate, leading to a kind of accumulative checksumming (checksums being the input to other checksums), that ensures a high level of integrity.Is there a name for that, and if so, what is it? (Other than accumulative checksumming (which, according to Google, is not well used, or I just made up.) My Google foo is failing me here...Another way to put it, is there a name for the way a Git repository ensures its integrity?Sorry for the vagueness - grasping for terminology I sense should exist but I can't actually find.
Is there a name for the concept of a cumulative checksum?
version control;terminology;hashing
It's called a hierarchical checksum.The corresponding tree is known as a Merkle Tree or hash tree or more rarely authentication tree.
_unix.194199
OS - linux lite.I don't get why all the files in the desktop suddenly disappeared. It is not moved anywhere. I searched through command line and checked trash folder too.What would be the cause for it? How can I get back my files? In Desktop, most were shortcuts of application and some files there. I need atleast files.
Desktop files disappeared suddenly
linux;desktop
null
_codereview.88782
One day, I was thinking:Wouldn't it be nice to set a class and have all the styles defined?And that is exactly what I did: a PHP file that generates CSS with pre-defined styles. So, for fun, I built the following:<?php if( @is_file($file = basename(__FILE__, '.css.php') . '-config.php' ) ) { $config = (array)include( $file ); } else { $config = array( 'class'=>'color', 'force'=>true, 'text'=>true, 'border'=>true, 'back'=>true, 'shadow'=>true, 'sizes'=>true, 'styles'=>true, 'send_header'=>true, 'custom'=>null ); } if( isset( $config['send_header'] ) && $config['send_header'] && !headers_sent() ) { header('Content-type: text/css'); } $colors = array( 'black', 'red'=>array('dark','indian','mediumviolet','orange','paleviolet'), 'green'=>array('dark','light','forest','yellow','lawn','lime','pale','darkolive','sea','darksea','lightsea','mediumsea','spring','mediumspring'), 'blue'=>array('alice','cadet','cornflower','dark','darkslate','deepsky','dodge','light','lightsky','lightsteel','medium','mediumslate','midnight','powder','royal','sky','slate','steel'), 'white' ); $sizes=array( 'em'=>array(0.3,0.5,1,1.25,1.3,2,2.5,3,3.3,3.5,4), 'px'=>array(0,1,2,3,4,5,6,7,8,9,10,11,12,12.5,13,14,15,16,17,17.5,18,19,20), 'mm'=>range(0,9), 'cm'=>range(0,9), '%'=>array(0,1,2,3,4,5,6,7,8,9,10,12.5,15,20,25,30,33.3,35,40,45,50,55,60,62.5,65,66.6,65,70,75,80,85,90,95,99,100) ); $styles=array( 'border'=>array('none','doted','dashed','solid'), 'text'=>array('none','underline') ); $important = ( isset($config['force']) && $config['force'] ? '!important' : '' ); $class = ( !isset($config['class']) || $config['class'] === null ? '.color' : ( $config['class'] == false ? '' : '.'.$config['class'] ) ); foreach($colors as $color_name=>$color) { if( is_array($color) ) { foreach( $color as $sub_color ) { if( isset($config['text']) && $config['text'] ) { echo $class, '.', $color_name, '-', $sub_color, '-text{color:', $sub_color, $color_name, $important, ';}'; } if( isset($config['border']) && $config['border'] ) { echo $class, '.', $color_name, '-', $sub_color, '-border{border-color:', $sub_color, $color_name, $important, ';}'; } if( isset($config['back']) && $config['back'] ) { echo $class, '.', $color_name, '-', $sub_color, '-back{background-color:', $sub_color, $color_name, $important, ';}'; echo $class, '.', $color_name, '-', $sub_color, '-background{background-color:', $sub_color, $color_name, $important, ';}'; } if( isset($config['shadow']) && $config['shadow'] ) { echo $class, '.', $color_name, '-', $sub_color, '-shadow{text-shadow-color:', $sub_color, $color_name, $important, ';box-shadow-color:', $sub_color, $important, ';}'; } if( isset($config['outline']) && $config['outline'] ) { echo $class, '.', $color_name, '-', $sub_color, '-outline{outline-color:', $sub_color, $color_name, $important, ';}'; } } } else { if( isset($config['text']) && $config['text'] ) { echo $class, '.', $color, '-text{color:', $color, $important, ';}'; } if( isset($config['border']) && $config['border'] ) { echo $class, '.', $color, '-border{border-color:', $color, $important, ';}'; } if( isset($config['back']) && $config['back'] ) { echo $class, '.', $color, '-back{background-color:', $color, $important, ';}'; echo $class, '.', $color, '-background{background-color:', $color, $important, ';}'; } if( isset($config['shadow']) && $config['shadow'] ) { echo $class, '.', $color, '-shadow{text-shadow-color:', $color, $important, ';box-shadow-color:', $color, $important, ';}'; } if( isset($config['outline']) && $config['outline'] ) { echo $class, '.', $color, '-outline{outline-color:', $color, $important, ';}'; } } } unset($colors,$color,$color_name,$sub_color,$sub_color_name); if( isset($config['custom']) ) { foreach( $config['custom'] as $color=>$hex ) { if( isset($config['text']) && $config['text'] ) { echo $class, '.custom-', $color, '-text{color:#', $hex, $important, ';}'; } if( isset($config['border']) && $config['border'] ) { echo $class, '.custom-', $color, '-border{border-color:#', $hex, $important, ';}'; } if( isset($config['back']) && $config['back'] ) { echo $class, '.custom-', $color, '-back{background-color:#', $hex, $important, ';}'; echo $class, '.custom-', $color, '-background{background-color:#', $hex, $important, ';}'; } if( isset($config['shadow']) && $config['shadow'] ) { echo $class, '.custom-', $color, '-shadow{text-shadow-color:#', $hex, $important, ';box-shadow-color:#', $hex, $important, ';}'; } if( isset($config['outline']) && $config['outline'] ) { echo $class, '.custom-', $color, '-outline{outline-color:#', $hex, $important, ';}'; } } } unset($color,$hex); if( isset($config['sizes']) && $config['sizes']) { foreach($sizes as $size_name=>$size_list) { foreach($size_list as $size_value) { if( isset($config['text']) && $config['text'] ) { echo '.text-', str_replace('.', '_', $size_value), $size_name, '{font-size:', $size_value, $size_name, $important, ';}'; } if( isset($config['border']) && $config['border'] ) { echo '.border-', str_replace('.', '_', $size_value), $size_name, '{border-width:', $size_value, $size_name, $important, ';}'; } } } } unset($sizes,$size_name,$size_list,$size_value); if( isset($config['styles']) && $config['styles']) { if( isset($config['text']) && $config['text'] ) { foreach($styles['text'] as $style) { echo '.text-',$style,'{text-decoration:',$style,$important,';}'; } } if( isset($config['border']) && $config['border'] ) { foreach($styles['border'] as $style) { echo '.border-',$style,'{border-style:',$style,$important,';}'; } } } unset($styles,$style,$config,$important,$class);It is a lot of code.The color list isn't finished (there are tons of colors missing), but the functionality is all there.Everything is customizable.To set other settings, without changing code, save this file as <name>.css.php, and create a file called <name>-config.php.It will be detected automatically and the settings will be loaded.Example of a file with the settings: return array( 'class'=>'color', 'force'=>true, 'text'=>true, 'border'=>true, 'back'=>true, 'shadow'=>true, 'sizes'=>true, 'styles'=>true, 'send_header'=>true, 'custom'=>array() );Each setting in detail:'class'Class that must be used for colors.'force'Forces the styles, by applying !important.'text'Defines if it is to send the styles and colors to apply to texts.'border'Defines if it is to send the styles and colors to apply to borders.'back'Defines if it is to send the background colors.'shadow'Defines if it is to send the shadow colors.'sizes'Defines if it is to send the sizes for text and borders.'styles'Defines if it is to send the styles for text and borders.'send_header'Defines if it is to send the header Content-type: text/css. - 'custom'Defines new colors. To avoid problems, these will have the name <class>.custom-<color>.This works with the color name as the key and the value as the hexadecial representation without #.E.g.: array('gold'=>'CFB53B') (will produce, for example, .color.custom-gold-<style>{color:#CFB53B!important;})How to use it:Simply call it like any CSS file:<link href=quickstyle.css.php rel=stylesheet type=text/css/>Or include it (with the option send_header set to false):<style><?php include 'quickstyle.css.php'; ?></style>How to use the classes:Simply set them to your heart's content:<div class=color black-background white-text blue-border border-2px border-solid>Hello World!</div>Which would look like this:<div style=background:black;color:white;border:2px solid blue;>Hello World!</div>(Disregard the choice of color, please)In terms of readability, features and performance, what else can I change or improve?
Quick CSS style generator
php;performance;css
@cimmanon addressed some very good points on the concept itself, so I thought I would address the code. $colorsYou assume that all we want is colors in hexadecimal. But what about rgba and hsl?You should change how the colors are made, so that you detect when a color is missing the # and add it accordingly.$sizes$sizes=array( 'em'=>array(0.3,0.5,1,1.25,1.3,2,2.5,3,3.3,3.5,4), 'px'=>array(0,1,2,3,4,5,6,7,8,9,10,11,12,12.5,13,14,15,16,17,17.5,18,19,20), 'mm'=>range(0,9), 'cm'=>range(0,9), '%'=>array(0,1,2,3,4,5,6,7,8,9,10,12.5,15,20,25,30,33.3,35,40,45,50,55,60,62.5,65,66.6,65,70,75,80,85,90,95,99,100));This is also not very flexible, since all the values are hard-coded into the inner arrays. What if I wanted to make something 24px, or 42% or 110%? I think you should make something that accepts any integer and/or decimal value then have a function to concatenate the extension (like em, px, %) after it. It could also be good to define a reasonable range, but the good thing with CSS is if you enter a ridiculous value, like -50% or 99999999px it will either just not display, or look really weird.$styles$styles=array( 'border'=>array('none','doted','dashed','solid'), 'text'=>array('none','underline'));You have a typo that could lead to weird bugs. It should be dotted, not doted. I think other than that, it's a pretty creative idea and is pretty well executed.