id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_webmaster.18487 | We're in development of a website and we're looking into other options than just developing a chat engine ourselves.We've looked at CometChat and ArrowChat. Which look and seem to be great except that it uses PHP/MySQL. They offer to host your chat server which can handle 100,000+ but honestly we'd like to be hosting it on our own servers and handle way more than that.Know of any alternatives? We're looking for that Meebo/Facebook/CometChat/ArrowChat look and style but it needs to be fully customizable. | Is there a high-load chat software / script out there? | php;looking for a script;mysql;chat | null |
_codereview.20792 | I'm new to RSpec and testing in general. I've come up with a spec for testing my Content model and I need some feedback because I think there are many improvements that can be done. I don't know if the way I did it is considered over-testing, bloated/wrong code or something. This test is kinda slow but this doesn't bother me that much for now.app/models/content.rbclass Content < ActiveRecord::Base extend FriendlyId friendly_id :title, use: [ :slugged, :history ] acts_as_mediumable delegate :title, to: :category, prefix: true # Associations belongs_to :category has_many :slides, dependent: :destroy # Accessible attributes attr_accessible :title, :summary, :body, :category_id, :seo_description, :seo_keywords, :seo_title, :unpublished_at, :published_at, :is_draft # Validations validates :title, presence: true validates :body, presence: true validates :category, presence: true validates :published_at, timeliness: { allow_nil: false, allow_blank: false } validates :unpublished_at, timeliness: { allow_nil: true, allow_blank: true, after: :published_at }, :if => published_at.present? scope :published, lambda { |*args| now = ( args.first || Time.zone.now ) where(is_draft: false). where((published_at <= ? AND unpublished_at IS NULL) OR (published_at <= ? AND ? <= unpublished_at), now, now, now). order(published_at DESC) } def self.blog_posts joins(:category).where(categories: { acts_as_blog: true }) end def self.latest_post blog_posts.published.first end def to_s title end def seo meta = Struct.new(:title, :keywords, :description).new meta.title = seo_title.presence || title.presence meta.description = seo_description.presence || summary.presence meta endendspec/models/content_spec.rbrequire 'spec_helper'describe Content do it has a valid factory do create(:content).should be_valid end it is invalid without a title do build(:content, title: nil).should_not be_valid end it is invalid without a body do build(:content, body: nil).should_not be_valid end it is invalid without a category do build(:content, category: nil).should_not be_valid end it is invalid when publication date is nil do build(:content, published_at: nil).should_not be_valid end it is invalid when publication date is blank do build(:content, published_at: ).should_not be_valid end it is invalid when publication date is malformed do build(:content, published_at: !0$2-as-#{nil}).should_not be_valid end # TODO: You shall not pass! (for now) # it is invalid when expiration date is malformed do # build(:content, unpublished_at: !0$2-as-#{nil}).should_not be_valid # end it is invalid when publication date is nil and expiration date is set do build(:content, published_at: nil, unpublished_at: 3.weeks.ago).should_not be_valid end it is invalid when expiration date is before publication date do build(:content, published_at: 1.week.ago, unpublished_at: 2.weeks.ago).should_not be_valid end it returns a content's title as a string do content = create(:content) content.to_s.should eq content.title end describe filters by publication dates do before :each do @published_three_weeks_ago = create(:published_three_weeks_ago_content) @expiring_in_two_weeks = create(:expiring_in_two_weeks_content) @publish_in_tree_weeks = create(:publish_in_tree_weeks_content) end context with matching dates do it returns a sorted array of results that match for current time do Content.published.should include @published_three_weeks_ago, @expiring_in_two_weeks end it returns a sorted array of results that match for future time do Content.published(3.weeks.from_now).should include @published_three_weeks_ago, @publish_in_tree_weeks end end context without matching dates do it returns an empty array do Content.published(2.months.ago).should eq [ ] end end end describe filters contents by blog category do before :each do @blog_category = create(:blog_category) end context with matching contents do it returns only blog posts do one_page = create(:content) another_page = create(:content) first_post = create(:content, category: @blog_category) second_post = create(:content, category: @blog_category) Content.blog_posts.should include first_post, second_post end end context without matching contents do it returns an empty array do one_page = create(:content) another_page = create(:content) Content.blog_posts.should eq [ ] end end end describe retrieves latest post do before :each do @blog_category = create(:blog_category) end context with existing posts do it return the latest content that belongs to a blog category do first_post = create(:published_three_weeks_ago_content, category: @blog_category) second_post = create(:content, published_at: Time.zone.now, category: @blog_category) Content.latest_post.should eq second_post end end context without existing posts do it returns an nil object do Content.latest_post.should eq nil end end end describe uses seo attributes when present do before :each do @it = create(:content) end context seo title present do it returns seo title when present do @it.seo.title.should eq @it.seo_title end end context seo title non present do it returns title when seo title is blank do @it.seo_title = @it.seo.title.should eq @it.title end it returns title when seo title is nil do @it.seo_title = nil @it.seo.title.should eq @it.title end end context seo description present do it returns seo description when present do @it.seo.description.should eq @it.seo_description end end context seo description non present do it returns description when seo description is blank do @it.seo_description = @it.seo.description.should eq @it.summary end it returns description when seo description is nil do @it.seo_description = nil @it.seo.description.should eq @it.summary end end endendspec/factories/contents.rbFactoryGirl.define do factory :content do association :category title { Faker::Lorem.sentence } summary { Faker::Lorem.sentence(10) } body { Faker::Lorem.sentence(15) } seo_title { Faker::Lorem.sentence } seo_description { Faker::Lorem.sentence } seo_keywords { Faker::Lorem.words(8).join(, ) } published_at { Time.zone.now } is_draft { false } factory :published_three_weeks_ago_content do published_at { 3.weeks.ago } end factory :expiring_in_two_weeks_content do unpublished_at { 2.weeks.from_now } end factory :publish_in_tree_weeks_content do published_at { 3.weeks.from_now } end endend | Testing a Content model | ruby;ruby on rails;rspec | Nice job. Your tests are nicely compartmentalized. It is indeed good to test the factory independently. Good use of describe and context.Consider using the shoulda-matchers gemTests for many of the rails model associations and validations can be handled by the shoulda-matchers gem. For example, this line:validates :title, presence: truecan be tested like so:it {should validate_presence_of(:title)}Consider using pendingHere's a commented-out test:# TODO: You shall not pass! (for now)# it is invalid when expiration date is malformed do# build(:content, unpublished_at: !0$2-as-#{nil}).should_not be_valid# endRspec has a method for documenting tests that don't (and can't yet be made to) pass:it is invalid when expiration date is malformed do pending build(:content, unpublished_at: !0$2-as-#{nil}).should_not be_validendThe nice thing about pending is that it shows up in the test output, making it less easily forgotten than commented-out code. Also, you can give a reason, e.g.:pending Can't pass until the vendor fixes library xyzFor clarity, Consider redoing things the factory didThis test:context seo description present do it returns seo description when present do @it.seo.description.should eq @it.seo_description endendRelies upon the factory having having set the description, but the factory is a long way from the test. This would be clearer if explicit:context seo description present do it returns seo description when present do @it.seo_description = 'foo bar baz' @it.seo.description.should eq @it.seo_description endendConsider using subjectSome of your test sets a variable in a before block and later tests that variable:before :each do @it = create(:content) endcontext seo title present do it returns seo title when present do @it.seo.title.should eq @it.seo_title endendInstead of assigning to a variable, rspec lets you declare a subject:subject {create(:content)}Once you've declared a subject, some snazzy syntax becomes available to you:its('seo.title') {should == subject.title}subject.seo_title is a little awkward, so rspec lets you name your subject:subject(:content) {create(:content)}its('seo.title') {should == content.title}Consider using let along with subjectIn rspec, let defines a memoized, lazily-evaluated value. When used with subject, this can DRY up a spec:describe seo.title do let(:title) {'title'} subject {create :content, :title => title, :seo_title => seo_title} context 'seo title present' do let(:seo_title) {'seo title'} its('seo.title') {should eq seo_title} end context 'seo title missing' do let(:seo_title) {nil} its('seo.title') {should eq title} endend |
_scicomp.2414 | As motivation, consider a function which is smooth and continuous but for some reason it is very expensive to perform routine calculations of finding the Laplacian on it (maybe because it is over a large domain, etc.).Given an original function, say, in one dimension, is it possible to estimate (or slightly overestimate) the maximum absolute value (i.e., the magnitude) of the Laplacian of that function anywhere over its given domain (without actually computing the Laplacian at all points and just finding the maximum)?To start discussion, perhaps this can be done my taking a subset of points along the known function and using them as a basis for the estimate. | Estimating the maximum absolute value (magnitude) of the Laplacian for a given function? | numerics;algorithms | null |
_softwareengineering.304959 | I've started my own open source project, which is still in an early phase of development. I chose to use the MIT license for it. However, I've read that the Apache license is better for large projects, and it's going to become a large project later. So, I plan to study the Apache license later, and consider it for my project when the project becomes stable.Could transitioning from the MIT to the Apache license create any legal issues? Does a late transition involve any more risks?Disclaimer: I'm a programmer, not a lawyer. | Could there by any issues with transition from MIT to Apache License? | licensing;mit license;apache license | The owner, or copyright holder of the project is the one who gets to decide what license to use on each distribution of that project. The owner is completely free to use different licenses on different distributions.The tricky points to keep in mind are:1) If others contribute to the project, then you are no longer the sole owner, so changing the license would have to involve getting multiple people together to agree on it. If you're going the typical open source route of allowing pull requests from pretty much anyone, this can be a problem.2) The copies of the project that you have already distributed cannot have their licenses retroactively changed. The change can only apply to new distributions. In particular, anyone who has received old copies of the project under MIT is perfectly free to distribute copies of their copy under any license they please (since the MIT license imposes no restrictions on this behavior).3) Some people have strong opinions on licensing issues, and some people get understandably nervous when licenses change. So if you do have a non-trivial user base when you make this change, then you should post a very clear and specific explanation of why you want to make this change, solely for PR reasons. In particular, at the risk of taking your question too literally, you should have a more specific reason than because Apache is better for big projects and we are big now.Note that I am using the term distribution instead of version because it is fairly commonplace to release the same version of a program under multiple licenses, for various reasons. For instance, you may release a program for free under a copyleft license, while at the same time allowing corporations to purchase a version with a more permissive or closed source license. The version the corporations purchase would simply have different LICENSE, COPYRIGHT and/or README files.But in all honesty, MIT to Apache is not a huge change. It should be a perfectly harmless transition as long as you're aware of these potential issues ahead of time. |
_cseducators.3170 | I'm really looking for opinions from expertsI have been asked to teach a group of students How To Program, these students are really new to programming.What I want is to make them like programming and enjoy doing it (as I do), so which programming language should be used to teach them, in order to achieve that goal?The students are about 17 to 22 years old, and there are 25 students in the group.My background lies in 9 years of programming experience. I had used many programming languages like C++, Java, VB.NET, C#, JavaScript, PHP, Swift, Python. | Which of the following programming languages will help me better to teach the basic concepts of CS and why? | language choice | null |
_softwareengineering.309151 | My application is a generic enterprise application which can be deployed on any application server running on any OS.I don't know how/where to configure my application, except for the database information which are stored in the application server as datasource.While it's easy to do, I could use the database as a configuration container, but... the database shouldn't contain the configuration elements: I want to be able to use any database in any environment (dev, test, acceptance, production).Does Java EE offer any kind of configuration management similar to what is offered to the datasources? If yes, what is it? If not, what is the best practice on this?I often read the following advice: put these items in a properties file on the server. Fine, but in that case the location to the properties file becomes a configuration item in itself, so where/how do I define the location of that properties file and transmit that info to my application? | How to access environment-specific configuration in an enterprise application? | java;java ee;configuration | There are a couple options that present themselves in this case.The first, is the properties file. Its location is somewhere and typically in the class path. Typically, you will see it coupled with the getResource family of calls.Properties prop = new Properties();prop.load(this.getClass().getResourceAsStream(stuff.properties);Now, if you don't have the property file in the classpath, you could specify it in the system properties which can be accessed through the System class as described here.With the invocation of: java -Dtest=true -jar myApplication.jar the value can be extracted with: System.getProperty(test) and then used either to specify other resources or being a resource itself. While it isn't immediately visible with many application servers, its still there, somewhere. In Eclipse, you can easily see them by going to the run configuration and look at the VM arguments.Similar to the system properties, there are the environment properties accessed through System.getenv. The rest of that set of documents is a good read - The Platform Enviroment. While it speaks mostly to Java SE, nearly everything in it is still applicable and an option for Java EE (I don't think you'll be looking at Java Web Start or Java applets).Moving to the realm of the application server, we get to the names stored in the context of the application or server.InitialContext ic = new InitialContext();loc = (String) ic.lookup(java:com/env/app/location);This value is actually stored in the server configuration itself. The documentation for tomcat. Note that each app server is different and you might get some ugliness in there. The only difference between the database from JNDI and a string is the type that it presents. One is a DataSource, the other is a String. |
_softwareengineering.272506 | I have just started a new personal project (Python), and am writing what amounts to a rough draft of the program, the minimum required to do what I want to do. I am not yet putting in extensive error/exception handling or aesthetic UI elements (even in cases where I know these things will ultimately be needed), and the documentation is just enough to help future me see what I was doing.Is it against any set principles of project design/management to start so rough? I am a scientist, not a programmer, so am not up to speed on these things. So the main question is, is there a consensus on where one should aim to fall between the two extremes of:Write thorough, high-quality code from the start, with all the exceptionhandling and such that you know you will ultimately need.Write a minimally working rough draft from the start, and go in to fill in all theminutiae later.Related question: When is it OK to sacrifice the neatness of the design to get a project done? | How much detail to put into first iteration of project? | design;project management;time management | There is no single answer, as this depends entirely on the project. We need to think about two things here. What is your eventual target? How do you expect to get there?End ResultAre you writing Mars Orbiter control software? Then you better make damn sure you are writing the most robust code possible, You better be check every exception is handled in a sane matter.Are you writing a program that only you will run, and you'll only run manually every once in a while? Then don't bother with exceptions. Don't bother with heavy architecture. Get it working to the point where it works for you.How do you expect to get there?Are you doing heavy waterfall development, where you spend lots of time figuring out what is needed, and then you will go off for months, developing? If so, then you want to hit that target quality mentioned above fairly early. Get all your error checking infrastructure planned out at the start.Are you doing heavy agile development, where you are putting something together for a week or two, which will then be shown to stakeholders, who may ask for radical revisions, and where you expect to be able to iterate over many 1-2 wee sprints until you hit the target? Then you may be better off getting something working, but fragile together fast, and only adding belts-and-suspenders as the product requirements solidify.If you are in control over the waterfall or agile decision (which is actually a continuum not a binary choice) then make that decision based on expected change. If you are sure you know exactly what the end result will look like, then waterfall is your best choice. If you only have a vague notion of what you need to end up with, agile is your best choice. (Agile is more popular these days not because it is inherently better but because the second situation is far more common.)Now find your own answerFor most, the answer will lie somewhere in the middle. Answer both those questions about your project, and it should lead you in a basic direction.I can say that for myself, if I often write one-off scripts that are abysmally designed and have no error checking whatever. I also handle production code, where error handling and architecture get large amounts of attention. It all depends on what you are doing.One final caveat: If you decide you are doing one-off scripts that can be done quick-and-dirty, make sure. Unfortunately, it often happens that quick-and-dirty scripts that do something interesting get leveraged into broad usage when others notice them. Make sure that when this happens, time is given for hardening. |
_webmaster.38112 | This is going to sound terrible, but bear with me. I currently have a cron job that does a mysql dump, a git add all and commit, and a git push to bitbucket. I set this up almost a year ago, when I didn't know much about git, backups, and general web development and administration. I haven't had the time to fix this and do it properly, but the repo has now grown quite big from accumulating large temporary files from my forum, so now I have to do something and I want to do it properly this time around.What processes do semi-large websites and personal site admins use for backing up server content? Based on what I've learned since I set this up, what I'm currently think of doing is:Making changes on a development domain and committing the code frequentlyArchiving the entire site after a successful deployment from the development domainHaving automatic daily database and user-content backups. I still like the idea of backing up sqldumps with git, though. I know git isn't a backup tool and that this is beyond its purpose, but the textual queries that are exported would be easily managed by git and would save a lot of space in archives. | What's the canonical process for backing up a website? | web hosting;web development;backups;administration;git | null |
_webmaster.37758 | I've done searching for my answer and have tested a few solutions, but nothing has worked so far. I'm trying to get a URL like this http://baseball.sports.com to rewrite to http://pro.sports.com/baseball-index.php.However, I still need to keep the domain the same (http://baseball.sports.com). The reason being I have about 5 subdomains (baseball, football, soccer, etc.) that I want to run off the same code base (pro.sports.com). Everything is on the same server. I'd be happy to answer any other questions that would help me get a resolution. I truly appreciate any direction that can be given to me to solve this. | How can I rewrite a subdomain to go to a specific file in a specific folder? | apache;htaccess;redirects | null |
_webmaster.101519 | I've added meta description tag weeks ago. For some reason, Google is displaying blockqoute text and text around it, in search results instead of text from description tag. Do you have any experience with such problems? What is the common way to fix this? The two tags are shown below.<meta name=description content=my text here><blockquote class=quotes>Blockquote text goes here</blockquote><div class=pers><span> <b>Some text,</b></span><span class=weak> Another text</span></div> | google doesn't display contents of description tag in search resutls | seo;meta description | null |
_unix.345725 | Currently I run kernel with amd64-generic config and grsecurity applied. Will making config without everything I don't need provide me somehow 'GOOD' profit? Cause compiling time and kernel size are not problems. Also small things like 'speed up boot for 0.5%' does not matter. I built PC by myself so I know necessary specs. Thank you! | Will compiling linux kernel with low-config give any benefits compare to Ubuntu kernel? | linux kernel;configuration;optimization | null |
_unix.291752 | Is there any way to make mouse moves faster? I'm using 4K display, and 10x acceleration still too slow. | Faster mouse acceleration on XFCE4 | mouse | null |
_codereview.45893 | Please let me know your thoughts on the code below, please be brutal. Here is the question I solved:Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).For example:Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7return its zigzag level order traversal as:[ [3], [20,9], [15,7]] public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); if(root==null){ return res; } ArrayList<Integer> level = new ArrayList<Integer>(); level.add(root.val); res.add(level); int depth=1; queue.add(root); TreeNode empty = new TreeNode(2); queue.add(null); level = new ArrayList<Integer>(); while(!queue.isEmpty()){ TreeNode curr = queue.poll(); if(curr==null){ if(!queue.isEmpty()){ queue.add(null); } else{ break; } res.add(level); level = new ArrayList<Integer>(); depth++; } else{ if(depth%2==0){ if(curr.left!=null){ level.add(curr.left.val); queue.add(curr.left); } if(curr.right!=null){ level.add(curr.right.val); queue.add(curr.right); } } else{ if(curr.right!=null){ level.add(curr.right.val); queue.add(curr.right); } if(curr.left!=null){ level.add(curr.left.val); queue.add(curr.left); } } } } return res; } | ZigZag order of a tree traversal | java;algorithm;interview questions | Just the first few steps of refactoring:ArrayList<...> reference types should be simply List<...>:List<List<Integer>> res = new ArrayList<>();See: Effective Java, 2nd edition, Item 52: Refer to objects by their interfacesThis variable is never used, remove it:TreeNode empty = new TreeNode(2);I would avoid abbreviations like res, curr and val. They are not too readable and I suppose you have autocomplete (if not, use an IDE, it helps a lot), so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent and would not force readers to decode the abbreviations every time they read/maintain the code.Furthermore, if you type resu and press Ctrl+Space for autocomplete in Eclipse it founds nothing which is rather disturbing.These two lines are duplicated:level.add(curr.left.val);queue.add(curr.left);You could extract out a method for that: private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode left) { level.add(left.val); queue.add(left);}After that you might notice the similarity between the method above and the body of the following if statement:if(curr.right!=null){ level.add(curr.right.val); queue.add(curr.right);}You could use the same method here too:if (curr.right != null) { visit(level, queue, curr.right);}Of course, renaming the method's parameter will increase clarity:private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode node) { level.add(node.val); queue.add(node);}So, currently the end of the original method looks like the following:if (depth % 2 == 0) { if (curr.left != null) { visit(level, queue, curr.left); } if (curr.right != null) { visit(level, queue, curr.right); }} else { if (curr.right != null) { visit(level, queue, curr.right); } if (curr.left != null) { visit(level, queue, curr.left); }}You could remove some more duplication by moving the null check into the visit method:private void visit(List<Integer> level, Queue<TreeNode> queue, TreeNode node) { if (node == null) { return; } level.add(node.val); queue.add(node);}(I've used a guard clause here to make the code flatten.)Usage:if (depth % 2 == 0) { visit(level, queue, currentNode.left); visit(level, queue, currentNode.right);} else { visit(level, queue, currentNode.right); visit(level, queue, currentNode.left);}I would also invert the condition here to get a guard clause:if(!queue.isEmpty()){ queue.add(null);}else{ break;}Result:if (queue.isEmpty()) { break;}queue.add(null);There are seven lines between the declaration of the queue and its first usage:Queue<TreeNode> queue = new LinkedList<>();if (root == null) { return result;}List<Integer> level = new ArrayList<Integer>();level.add(root.val);result.add(level);int depth = 1;queue.add(root);It could have smaller scope and could be closer to its first usage:if (root == null) { return result;}List<Integer> level = new ArrayList<Integer>();level.add(root.val);result.add(level);int depth = 1;Queue<TreeNode> queue = new LinkedList<>();queue.add(root);(Effective Java, Second Edition, Item 45: Minimize the scope of local variables) |
_unix.26501 | What's the difference between patch -p0 and patch -p1?Is there any difference at all? | When patching what's the difference between arguments -p0 and -p1? | patch | The most common way to create a patch is to run the diff command or some version control's built-in diff-like command. Sometimes, you're just comparing two files, and you run diff like this:diff -u version_by_alice.txt version_by_bob.txt >alice_to_bob.patchThen you get a patch that contains changes for one file and doesn't contain a file name at all. When you apply that patch, you need to specify which file you want to apply it to:patch <alice_to_bob.patch version2_by_alice.txtOften, you're comparing two versions of a whole multi-file project contained in a directory. A typical invocation of diff looks like this:diff -ru old_version new_version >some.patchThen the patch contains file names, given in header lines like diff -ru old_version/dir/file new_version/dir/file. You need to tell patch to strip the prefix (old_version or new_version) from the file name. That's what -p1 means: strip one level of directory.Sometimes, the header lines in the patch contain the file name directly with no lead-up. This is common with version control systems; for example cvs diff produces header lines that look like diff -r1.42 foo. Then there is no prefix to strip, so you must specify -p0.In the special case when there are no subdirectories in the trees that you're comparing, no -p option is necessary: patch will discard all the directory part of the file names. But most of the time, you do need either -p0 or -p1, depending on how the patch was produced. |
_unix.251417 | I am trying to Enable Remote Connections after installing the chrome web app as well as the chrome remote desktop service as per the following article:https://support.google.com/chrome/answer/1649523?hl=enI am trying to get it working on Debian Jessie. After installation, it seemed to work briefly. i was able to RDP into my Linux box from my Mac. But after a reboot of my Linux machine, i kept getting the following error:Failed to start host servicePlease help. Thanks in advance. | chrome remote desktop gives Failed to start host service error | debian;chrome;remote desktop | null |
_vi.9962 | Is there a way to get filetype for given extension or filenameFor example:let my_f='text.rb'let my_ft=GetFileType(my_f)echo my_ft should output ruby | Get filetype by extension or filename in vimscript | vimscript | null |
_unix.15012 | In my code I generate a .dat file which is of the format:x \t y \t z \t charge \t type \t IDThere are about 3000 lines in the file and I want to display sphere (of radius 1 in my units). I tried to use paraview, pymol and rasmol. Paraview doesn't understand my file format. With pymol and rasmol I couldn't understand how they loaded my data. Do any of you know how to load data which is not in pdb format into pymol or rasmol? Also, I want to color the beads according to the last 3 properties is there any other way?I should note that I need the ability to browse through the 3d picture I get. My question might not be clear so please ask me for any clarification I might give. | How to display my data (molecules)? | software rec;scientific linux | I think it is pretty obvious -- convert your data to the format accepted by the program you would like to use (idea the program should somehow read your custom format is, ekhem, naive?). |
_codereview.171900 | I haven't found any implementation in C# of the LFSR so accordling to Wikipedia i have implment it to myself.https://en.wikipedia.org/wiki/Linear-feedback_shift_registerMy implementation accept some parameter so can be adapted to various feedback polynomials (my refernce table)https://web.archive.org/web/20161007061934/http://courses.cse.tamu.edu/csce680/walker/lfsr_table.pdfFor the testing pahse i generate as many number as the cycle will allow before a repetiton (i use a byte to my testing purpose).EDITED (PROBLEM SOLVED IT WAS DUE A TYPO, QUESTION REPHRASED AT THE END)The strange thing is in my test the period is exactly half of what expected/declared by the paper (not (2^n)-1 but 2^(n-1)).Here is my LFSR implementation public class Register{ private bool[] _register = null ; private bool[] _feedbackPoints = new bool[256] ; private int _registerLength = 0 ; public Register ( int length, int [] feedbackPoints ) : this ( length , feedbackPoints , new byte [0] ) {} public Register ( int length, int [] feedbackPoints, byte [] seed ) { if ( length > 256 ) throw new ArgumentOutOfRangeException ( length , Alloewed vaues need to be between 1 and 256 ) ; _registerLength = length ; _register = new bool[length] ; foreach ( int feedbackPoint in feedbackPoints ) if ( feedbackPoint > 256 ) throw new ArgumentOutOfRangeException ( feedbackPoints, Alloewed vaues of item of array need to be between 1 and 256 ) ; else _feedbackPoints[feedbackPoint] = true ; byte [] randomizedSeed = this.SeedRandomization ( seed ) ; string temporaryRegisterRepresantation = string.Empty ; foreach ( byte seedItem in randomizedSeed ) temporaryRegisterRepresantation += Convert.ToString ( seedItem , 2 ) ; int index = 0 ; foreach ( char bit in temporaryRegisterRepresantation ) if ( index < length ) _register[index++] = bit == '1' ; } public bool Clock () { lock ( this ) { bool output = _register[0] ; for ( int index = 0; index < _registerLength - 1; index++ ) _register[index] = _feedbackPoints[index] ? _register [index+1] ^ output : _register [index+1] ; _register [_registerLength - 1] = output ; return output ; } } private byte[] SeedRandomization ( byte[] inputSeed ) { SHA256Managed sha256 = new SHA256Managed (); int seedLength = inputSeed.Length ; byte [] seed = new byte [seedLength] ; Array.Copy ( inputSeed , seed , seedLength ) ; Array.Resize<byte> ( ref seed , seedLength + 4 ) ; byte[] dateTime = BitConverter.GetBytes ( DateTime.Now.Ticks ) ; seed[seedLength] = dateTime[0] ; seed[seedLength+1] = dateTime[1] ; seed[seedLength+2] = dateTime[2] ; seed[seedLength+3] = dateTime[3] ; return sha256.ComputeHash ( seed , 0 , seed.Length ) ; }}And there is my testing code class Program{ static void Main ( string [] args ) { Dictionary<int, bool> tester = new Dictionary<int, bool> (); List<int> duplicate = new List<int> (); Register register_1 = new Register ( 8 , new int[] { 5,4,3 } ) ; for ( int index = 0; index < 256; index++ ) { bool b00 = register_1.Clock (); bool b01 = register_1.Clock (); bool b02 = register_1.Clock (); bool b03 = register_1.Clock (); bool b04 = register_1.Clock (); bool b05 = register_1.Clock (); bool b06 = register_1.Clock (); bool b07 = register_1.Clock (); BitArray bitArray = new BitArray ( new bool [] { b00, b01, b02, b03, b04, b05, b06, b07 } ); int [] array = new int [1]; bitArray.CopyTo ( array, 0 ); if ( !tester.ContainsKey ( array[0] ) ) tester.Add ( array [0], true ) ; else duplicate.Add ( array[0] ) ; } duplicate = duplicate.OrderBy ( x => x ).ToList() ; }}I have manually followed the implementation with 2bit LFSR and i see nothing wrong about it, so i would ask if there are any fallacies in my test or implementation.EDITEDI have found my fault, i have omitted to write b00 so is correct that the period is exactly half of what expected.I keep the code but renew my question, now i wold ask if you found any issue with current implementation (that seems to work with current test). | Linear Feedback Shift Register | c#;cryptography | I totally agree with @Maxim about the spacing but need to say, that you didn't use spaces where you should for the sake of readability.This seed[seedLength] = dateTime[0] ;seed[seedLength+1] = dateTime[1] ;seed[seedLength+2] = dateTime[2] ;seed[seedLength+3] = dateTime[3] ;would be more readable if you place spaces like so seed[seedLength] = dateTime[0];seed[seedLength + 1] = dateTime[1];seed[seedLength + 2] = dateTime[2];seed[seedLength + 3] = dateTime[3]; Omitting braces {}, although they might be optional, can lead to hidden and therefor hard to track bugs. I would like to encourage you to always use them. This will avoid hidden bugs and the code looks better structured. SeedRandomization ()The SHA256Managed class implements IDisposable through inheriting HashAlgorithm so you should enclose its usage in a using block. These variables private bool[] _register = null ;private bool[] _feedbackPoints = new bool[256] ;private int _registerLength = 0 ; should be made readonly because they won't change anywhere except in the constructor.A little LINQ could simplify this foreach ( int feedbackPoint in feedbackPoints ) if ( feedbackPoint > 256 ) throw new ArgumentOutOfRangeException ( feedbackPoints, Alloewed vaues of item of array need to be between 1 and 256 ) ; else _feedbackPoints[feedbackPoint] = true ;but do you spot the spelling error which happened by using copy&pasta not carefully ? At least I would place the part about feedbackPoint > 256 at the top of the constructor where the input parameter validation belongs. A simple if (feedbackPoints.Any(p => p > 256)) { throw new ArgumentOutOfRangeException ( feedbackPoints, Allowed vaues of item of array need to be between 1 and 256 ) ;} could do the validation.But what about the length parameter ? Passing length == -1 seems valid but will throw an OverflowException at _register = new bool[length] ;. In addition the messages of the ArgumentOutOfRangeException's states ..... need to be between 1 and 256 but you only check in both cases value > 256 without checking the lower boundaries. If I read between 1 and 256 I will think that the allowed values are 2...255 but this could be because I am not native english.string temporaryRegisterRepresantation = string.Empty ;foreach ( byte seedItem in randomizedSeed ) temporaryRegisterRepresantation += Convert.ToString ( seedItem , 2 ) ; each time string += string happens a new string object is created because strings are immutable. If you want to concatenate strings in a loop most of the times it is better (time and space) to use a StringBuilder. |
_unix.91934 | I want to know why is this argument so important when lauching nautilus or pcmanfm. What happens if i don't?Also, i want to know what is the meaning of %U for:Exec=pcmanfm %U | --no-desktop and %U what for? | gnome;nautilus;arguments;file manager | There is an instance of Nautilus running behind the scenes that's managing your desktop, so when you run subsequent instances of Nautilus the --no-desktop is telling Nautilus not to try to manage the desktop icons etc.The %U means to pass in a list of URLS:%U A list of URLs. Each URL is passed as a separate argument to the executable program. Local files may either be passed as file: URLs or as file path.The rest of the list can be found here in the The Exec key section of the freedesktop.org documentation. Here are the rest.excerptCode Description---- -----------%f A single file name, even if multiple files are selected. The system reading the desktop entry should recognize that the program in question cannot handle multiple file arguments, and it should should probably spawn and execute multiple copies of a program for each selected file if the program is not able to handle additional file arguments. If files are not on the local file system (i.e. are on HTTP or FTP locations), the files will be copied to the local file system and %f will be expanded to point at the temporary file. Used for programs that do not understand the URL syntax.%F A list of files. Use for apps that can open several local files at once. Each file is passed as a separate argument to the executable program.%u A single URL. Local files may either be passed as file: URLs or as file path.%U A list of URLs. Each URL is passed as a separate argument to the executable program. Local files may either be passed as file: URLs or as file path.%d Deprecated.%D Deprecated.%n Deprecated.%N Deprecated.%i The Icon key of the desktop entry expanded as two arguments, first --icon and then the value of the Icon key. Should not expand to any arguments if the Icon key is empty or missing.%c The translated name of the application as listed in the appropriate Name key in the desktop entry.%k The location of the desktop file as either a URI (if for example gotten from the vfolder system) or a local filename or empty if no location is known.%v Deprecated.%m Deprecated. |
_softwareengineering.298969 | I currently experimenting with DSLs with xtext. I want to implement a quick fix for the dsl I'm writing and I'm wondering, if there is a possibility in xtext or xtend hook (or something else) to generate a dsl fragment code from the DSL grammar and a given Ecore node.For example Model: entities+=Entity*;Entity: 'entity' name = ID ('extends' superType=[Entity])? '{' attributes += Attribute* '}';I validate that the Supertype may not exist, and I want to suggest a Quickfix (Ctrl+1) to create a new Entity. I know how to do the validation part and know where to implement the quickfix. But since the DSL is in development i do not want to write two code generators (one for creating DSL code, and the second for the code derived from the model) since the DSL is subject to change. I guess, that there could be a more general solution, since the grammar is known, because of the xtext grammar definition and the Ecore node I want to create, whose name I know from the validator. I also guess I am not the only one providing such a feature and thus I assume there is already a solution which i did not found yet.My Question, is there a generic way in xtext/xtend building an ecore node or AST and serialize that AST back into xtext based DSL using the xtext grammar? | Create parts of DSL as Quickfix from xtext grammar | dsl | Yes, there is exactly that. You can provide your quickfix as a semantic modification to the EMF resource. Xtext's serialization mechanism will figure out how to convert your changes to the AST back to text.Something along these lines should do the trick:@Fix(MISSING_SUPERTYPE_ID)public void fixupSupertype(final Issue issue, IssueResolutionAcceptor acceptor) { acceptor.accept(issue, label, description, null, new ISemanticModification() { @Override public void apply(EObject element, IModificationContext context) { Model model = (Model)element.eResource().getContents().get(0); Entity newEntity = MyDslFactory.eInstance().createEntity() model.getEntities().add(newEntity); ((Entity)element).setSuperType(newEntity); } });} |
_unix.40920 | For example, if I did an ssh -X to localhost and invoked Firefox, would that be enough to be considered safe browsing, like if done on some public wifi? | Is encrypting your web browsing via SSH to localhost useful? | ssh;security;browser;web | null |
_softwareengineering.283556 | TL;DR: Can you publicly release your own implementation of a patented algorithm as a free research tool for others, under the GPL, when you do not hold the patent (but will happily give clear and thorough attribution to the owners of the patent)? see below for clarification.First off, apologies if this question has already been answered. After ~30 minutes of googling and stack-exchanging, I haven't found anything that quite answers what I'm facing.I work in an academic group and part of our work has been implementing a CT reconstruction algorithm similar to what is done clinically by a major manufacturer. This manufacturer has a patent that definitely covers what we have implemented. (I did the implementation from a paper published almost 10 years earlier, only to find that they had also patented the algorithm a little over a year ago. Damn.)They have a patent on the method of reconstruction and several of the equations utilized, but no source code or anything of the sort. The code implementation is 100% unique to our group. We're talking patents, not copyright.We are planning to write a technical note about our implementation (gpu-based, more detail on how we implemented the published algorithms (i.e. much more detail than what's patented), etc. all stuff which is not described in the patent) for publication in a major journal ** AND ** this would include releasing our source code. I would like to release it under GPLv2.0 to provide folks with a research tool.The GPL would prevent us and anyone down the road from using our code in proprietary software, and if anyone were to use it to make money, they would have to pay rights to the patent owner (and release any code derived from ours). I would like to somehow make clear that we are not claiming any rights to the algorithm, and the only the implementation would be covered by the GPL, however I recognize this distinction may not be possible under the current US legal setup (blegh).Even if we could somehow make that distinction clear when/if we release, are we violating any of their rights with the patent? I'm thinking they would have to somehow show that our release damaged their business covered by the patent. Any thoughts from more experienced folks are much appreciated! I think this may be kind of a gray area (or not! I'm not a lawyer! haha).We do NOT wish to infringe upon the patent and don't pretend to have any claim to. We have a good relationship with the vendor, so we'll most likely end up figuring it out with them, but if they said no, I was curious if it's just because of their feels or if thay have a legitimate claim against our group. | GPLing an implementation of a patented algorithm | algorithms;open source;gpl;patents | The short answerIn order to license something to others, you have to hold the rights to it. So your ability to license your code covered by the patent may depend on what you can work out with the patent holder.The long answerThere are a number of ways this can go. You can get a release from the patent holder. You can release your code and hope the patent holder doesn't care; they might not. You can come up with an algorithm that is unencumbered by the patent. You can pay a negotiated patent royalty.Whether anyone makes money from the GPL'd code may not matter, if public dissemination of the code hinders their ability to profit from the invention. The choice of license may not matter either; it's still a patent issue whether the source code is copyleft or not (though your vendor might have a preference as to which license you actually use).The actual answerThis is one of those times where it might be useful to consult an attorney that specializes in patent and licensing law. They can not only advise you how far you can go with your source code without invoking the patent, but also how an agreement can be correctly crafted between you and the vendor. |
_codereview.14503 | I'm very very fresh to programming. This is one of my first experiments with Python and I'm wondering in what ways I could have made this program less clunky. Specifically, is there a way that I could have used classes instead of defining my x, y, and z variables globally?def getx(): try: global x x = float(raw_input(Please give your weight (pounds): )) return x except ValueError: print(Use a number, silly!) getx()def gety(): try: global y y = float(raw_input(what is your current body fat percentage? (>1): )) return y except ValueError: print(Use a number, silly!) gety()def getz(): try: global z z = float(raw_input(What is your desired body fat percentage? (>1): )) return z except ValueError: print(Use a number, silly!) getz()def output(): getx() gety() getz() A = (x*(y/100-z/100))/(1-z/100) B = x - A print(Your necessary weight loss is %.1f pounds, and \your final weight will be %.1f pounds % (A,B)) more()def more(): again = raw_input(Calculate again? ) if again.lower() == yes or \ again.lower() == y or \ again.lower() == sure or \ again.lower() == ok or \ again.lower() == or \ again.lower() == okay: output() elif again.lower() == no or \ again.lower() == n or \ again.lower() == nah or \ again.lower() == nope: end() else: more()def end(): print(Ok, see ya later!)output() | Python beginner's body fat calculator | python;beginner;calculator | null |
_softwareengineering.189542 | BackgroundI revisited an old (but great) site I had not been to for ages - the Alioth Language Shootout (http://benchmarksgame.alioth.debian.org/).I started out programming in C/C++ several years ago, but have since then been working almost exclusively in Java due to language constraints in the projects I have been involved in. Not remembering the figures, I wanted to see, approximately, how well Java fared against C/C++ in terms of resource usage.The execution times were still relatively good, with Java at worst performing 4x slower than C/C++, but on average around (or below) 2x. Due to the nature of the implementation of Java itself, this was no surprise, and it's performance time was actually lower than what I expected.The real brick was the memory allocation - at worst, Java allocated: a whopping 52x more memory than Cand 25x more than C++. 52x the memory ... Absolutely nasty, right? ... or is it? Memory is comparatively cheap now.Question:If we do not speak in terms of target platforms with strict limits on working memory (i.e. embedded systems and the like), should memory usage be a concern when picking a general purpose language today? I am asking in part because I am considering migrating to Scala as my primary language. I very much like the functional aspects of it, but from what I can see it is even more expensive in terms of memory than Java. However, since memory seems to be getting faster, cheaper and more plentiful by the year (it seems to be increasingly hard to find a consumer laptop without at least 4GB of DDR3 RAM), could it not be argued that resource management is becoming increasingly more irrelevant as compared to (possibly implementation-wise expensive) high-level language features which allow for faster construction of more readable solutions? | Is memory management in programming becoming an irrelevant concern? | java;programming languages;scala;resources;engineering | Memory management is utterly relevant since it governs how fast something appears even if that something has a great deal of memory. The best and most canonical example are AAA-title games like Call of Duty or Bioshock. These are effectively real-time applications that require massive amounts of control in terms of optimization and usage. It's not the usage per se that's the issue but rather the management.It comes down to two words: Garbage Collection. Garbage Collection algorithms can cause slight hiccups in performance or even cause the application to hang for a second or two. Mostly harmless in an accounting app but potentially ruinous in terms of user experience in a game of Call of Duty. Thus in applications where time matters, garbage collected languages can be hugely problematic. It's one of the design aims of Squirrel for instance, which seeks to remedy the issue that Lua has with its GC by using reference counting instead.Is it more of a headache? Sure but if you need precise control, you put up with it. |
_unix.290265 | I temporarily had a static ip for my raspberry. Now the config looks like this./etc/network/interfacesauto loiface lo inet loopbackauto eth0iface eth0 inet dhcpBut this leads to a reservation of the complete range of the availble dhcp ips.$ ip a1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether b8:27:eb:94:90:82 brd ff:ff:ff:ff:ff:ff inet 192.168.2.29/24 brd 192.168.2.255 scope global eth0 valid_lft forever preferred_lft forever inet 192.168.2.30/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.31/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.32/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.33/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.34/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.35/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.36/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.37/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.38/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.39/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.41/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.42/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.43/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.44/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.45/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.40/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.46/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.47/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.49/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.50/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.51/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.52/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.53/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.54/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.55/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.56/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.57/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.58/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.59/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.60/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.61/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.62/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.63/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.64/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.65/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.66/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.67/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.68/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.69/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.70/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.71/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.72/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.73/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.74/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.75/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.77/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.78/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.79/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.80/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.81/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.82/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.83/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.84/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.85/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.86/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.87/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.88/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.89/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.90/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.91/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.92/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.93/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.94/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.95/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.96/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.97/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.98/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.99/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.100/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.101/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.102/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.103/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.104/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.105/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.106/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.107/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.108/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.109/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.110/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.111/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.112/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.113/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.114/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.115/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.116/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.117/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.118/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.119/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.120/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.121/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.122/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.123/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.124/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.125/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.126/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.127/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.128/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.129/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.130/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.131/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.132/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.133/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.134/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.135/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.136/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.137/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.138/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.139/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.141/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.142/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.143/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.144/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.145/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.146/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.147/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.148/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.149/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.150/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.151/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.152/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.153/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.154/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.155/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.156/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.157/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.158/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.159/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.161/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.162/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.163/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.164/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.165/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.166/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.167/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.168/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.169/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.170/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.171/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.172/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.173/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.174/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.175/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.176/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.177/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.178/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.179/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.180/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.181/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.182/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.183/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.184/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.185/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.186/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.187/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.188/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.189/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.190/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.191/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.192/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.193/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.194/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.195/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.196/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.197/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.198/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.200/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.199/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.24/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.26/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.27/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft forever inet 192.168.2.28/24 brd 192.168.2.255 scope global secondary eth0 valid_lft forever preferred_lft foreverWhat is the problem? (Raspbian GNU/Linux 8) | Raspbian uses the complete dhcp range | raspbian;dhcp;ipv4 | null |
_webmaster.12014 | I am trying to figure out where do all sites that use the 'Helvetica Neue' font get it from. There are certainly too many sites using it for it not to be free. But frankly, there are only two fontsites which have it in their catalog, and it is for sale (and not as a webfont).Moreover, can you give some examples of webfonts which are similar to this 'Helvetica Neue' and are (mostly) free?Thank you! | 'Helvetica Neue' webfont | fonts | Based on the examples you posted in response to my comment above, you're confused.Dribbble and Foursquare aren't using web font/font-face embedding at all. They're simply specifying Helvetica Neue in their font-family stacks. If a visitor happens to have that font installed on their system, then they'll see it. They quite likely don't, in which case their system will try the next font down, and so on until either something matches or it just ends up using their default for sans-/serif/monospace. |
_unix.178180 | I tried import drawings from OpenClipArt in my Ubuntu using Inkscape, but appear this problem below:Failed to receive the Open Clip Art Library RSS feed. Verify if the server name is correct in Configuration->Import/Export (e.g.: openclipart.org)How can I fix this and import drawings from OpenClipArt.org? | Failed to receive the Open Clip Art Library RSS feed | ubuntu;inkscape | null |
_computergraphics.4936 | I have got a texture ID and would like to retrieve its data. The data should be stored in a BufferedImage for future use. I am using the LWJGL library in Java, so if there are some library-specific shortcuts I'd like to use them.My naive approach is to first fill a buffer with the image data and then pass it to the image. int id = ...; IntBuffer buff = BufferUtils.createIntBuffer(1024*512*4); GL11.glBindTexture(GL11.GL_TEXTURE_2D, id); System.out.println(buff.remaining()); GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, buff); System.out.println(buff.remaining()); buff.flip(); buff.rewind(); System.out.println(buff.remaining()); // Somehow create a BufferedImage from buff hereI don't know why, but the first and to buff.remaining() return the same value, indicating that nothing has been written which should not be the case. | LWJGL/OpenGL get BufferedImage from texture ID | opengl;image | To make it a more complete example, let's also consider loading a texture from a BufferedImage as well.First let's assume:int texture = glGenTextures();glBindTexture(GL_TEXTURE_2D, texture);First we need to load an image. For this we can use ImageIO.read(). Then we put all the pixels from the BufferedImage into a ByteBuffer.BufferedImage image = ImageIO.read(new File(image.png));int width = image.getWidth(), height = image.getHeight();int[] pixels = new int[width * height];image.getRGB(0, 0, width, height, pixels, 0, width);ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * 4); // 4 because RGBAfor(int y = 0; y < height; ++y) { for(int x = 0; x < width; ++x) { int pixel = pixels[x + y * width]; buffer.put((byte) ((pixel >> 16) & 0xFF)); buffer.put((byte) ((pixel >> 8) & 0xFF)); buffer.put((byte) (pixel & 0xFF)); buffer.put((byte) ((pixel >> 24) & 0xFF)); }}buffer.flip();glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);Before we go ahead and call glGetTexImage() lets assume that the only thing we have is the texture name (texture). Thus we consider that we don't know the size or format of the texture. We can get all this by doing:int format = glGetTexLevelParameteri(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT);int width = glGetTexLevelParameteri(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH);int height = glGetTexLevelParameteri(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT);Using that information we again create a ByteBuffer as well as a BufferedImage. Reading the pixels from the ByteBuffer and placing them on the BufferedImage.int channels = 4;if (format == GL_RGB) channels = 3;ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * channels);BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, buffer);for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { int i = (x + y * width) * channels; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; int a = 255; if (channels == 4) a = buffer.get(i + 3) & 0xFF; image.setRGB(x, y, (a << 24) | (r << 16) | (g << 8) | b); }}Now go ahead and save that BufferedImage to a file.ImageIO.write(image, PNG, new File(out.png));Last but not least, you can get rid of all those GL11. prefixes, by statically importing GL11. You do that by doing:import static org.lwjgl.opengl.GL11.*; |
_codereview.77007 | Let me know if it seems right to you and if anything can be optimized. My concern is that I'm unsure if circular linked lists are supposed to have a tail. I've implemented it just using a head. Is that wrong? If so, how would you change it to make it proper?/* * Circular Linked List * */#include <stdio.h>#include <stdlib.h>typedef struct Node { int data; struct Node *next;} Node;void insert_beg_of_list(Node *current, int data);void delete(Node *current, int data);void print_list(Node *current);int find_in_a_list(Node *current, int data);void insert_beg_of_list(Node *current, int data) { //keep track of first node Node *head = current; while(current->next != head) { current = current->next; } current->next = (Node*)malloc(sizeof(Node)); current = current->next; current->data = data; current->next = head;}void delete_from_list(Node *current, int data) { Node *head = current; while(current->next != head && (current->next)->data != data) { current = current->next; } if(current->next == head) { printf(%d element is not found\n\n, data); return; } Node *tmp; tmp = current->next; current->next = tmp->next; free(tmp); return;}void print_list(Node *current) { Node *head = current; current = current->next; while(current != head){ printf( %d , current->data); current = current->next; }}int find_in_a_list(Node *current, int data) { Node *head = current; current = current->next; while(current != head) { if(current->data == data) { // Key found return 1; } current = current->next; } // Key is not found return 0;}int main() { Node *head = (Node *)malloc(sizeof(Node)); head->next = head; int data = 0; int usr_input = 0; while(1){ printf(0. Exit\n); printf(1. Insert\n); printf(2. Delete\n); printf(3. Print\n); printf(4. Find\n); scanf(%d, &usr_input); // can also use a switch instead if( usr_input == 0) { exit(0); } else if(usr_input == 1) { printf(\nEnter an element you want to insert: ); scanf(%d, &data); insert_beg_of_list(head, data); } else if(usr_input == 2) { printf(\nEnter an element you want to delete: ); scanf(%d, &data); delete_from_list(head, data); } else if( usr_input == 3) { printf(The list is ); print_list(head); printf(\n\n); } else if( usr_input == 4) { printf(\nEnter an element you want to find: ); scanf(%d, &data); int is_found = find_in_a_list(head, data); if (is_found) { printf(\nElement is found\n\n); } else { printf(\nElement is NOT found\n\n); } } } return 0;} | Circular linked list in C | c;linked list;circular list | null |
_webapps.50142 | How is this done? Maybe with PHP or JavaScript? | How can I make this integration with Facebook for comments in the botton of my web page? | comments;facebook like;facebook integration | One solution is to use this Facebook plugin: https://developers.facebook.com/docs/reference/plugins/comments/ |
_webapps.42263 | I've gone about setting up a new email address, the one i'm signed on here with, and I picked out three friends to send codes to. I received two of them back, but the third friend deleted the email with the code and can't retrieve it. I've filed exactly 5 different reports and so far no response at all. I've checked my spam folder it's spotless.What should I do? | I can't get back on to my Facebook. Email address no longer available to me | facebook;account management | null |
_softwareengineering.323295 | This is part of the code of a calculator that works on command line. It works fine and the math is correct but it's a little redundant:switch(Operator) { case +: result = num1 + num2; printResult(); break; case - : result = num1 - num2; printResult(); break; case *: result = num1 * num2; printResult(); break; case /: result = num1 / num2; printResult(); break; case ^: result = Math.Pow(num1, num2); printResult(); break; case root: result = Math.Pow(num1, (1/num2)); Console.WriteLine(Root degree + num2 + of + num1 + is + result); break; default: Console.WriteLine(Invalid operator.); break;}//END SWITCH Is there a way to avoid this redundant code like result = num1 Operator num2;or for char o = Operatorresult = num1 Operator num2;Even just for the + - / * operations ? | Simplifying code of a calculator (help) | c# | First, remove the duplication by moving PrintResult() below your switch. You call it every time (nearly, you'll need to make it a touch more robust I imagine). Then, change your method to return a result instead. This method calculates and prints. It shouldn't, that break SRP. Now, you could create a dictionary of functions to be invoked. var operations = new Dictionary<string, Func<int, int, double>>(){ { +, (a, b) => a + b }, { -, (a, b) => a - b }, //...}return operations[Operator](num1, num2);May not compile, I'm typing on my phone. Exception handling left to OP.Of course, if you get really froggy, you could go create a calculator parser and really overkill the solution. |
_unix.367772 | It seems adding desktop icons are a pain in Fedora. Can someone please tell me how I can place the Terminal icon on the desktop ? I have downloaded the gnome-tweak-tool and enabled icons on Desktop.Also is there an application that I can use to do this ? Rather than editing the files in ~/local ? | Fedora 25 - Place terminal icon on Desktop | fedora;icons | Assuming you've logged out & back in after enabling desktop icons in the tweak tool; using the gnome file browser, go to:/usr/share/applicationsSearch for, or find the file called 'terminal' in this directory, and drag it to the desktop. |
_unix.100707 | I've been using rsync for Android to backup my phone to a remote NTFS filesystem on a Linux system for a while.Recently, the HDD containing the NTFS filesystem has started to fail (or throw I/O Errors) so I took the opportunity to copy all the files onto a new HDD and new NTFS filesystem. In this instance I used the FastCopy v2.11 tool for Windows.My problem is that when I do an rsync dry run I can see that it wants to recopy files which already exist on the remote rsync folder. For example, when I run with -iv I get this kind of output:Which, as I understand it means that rsync wants to copy this file to the remote rsync because of a timestamp difference.The strange thing is that if I use Astro for Android to look at the local file properties, I can see that the file's size, modified time, and MD5 checksum are exactly the same as that of the remote file (using ls -l to check the modified time).Given that I recently copied the remote rsync files from an old NTFS filesystem, the remote file's ctime is different (using ls -lc).Does rsync look at the remote ctime, and if so is there any way I can use rsync, or ntfs-3g to get around this problem? | rsync vs mtime and ctime | rsync;android;ntfs | null |
_webapps.45785 | I want to delete a date range of emails (from jan 2011-sept 2011). I do NOT want to delete all my emails, and I would rather not have to do it page by page. (100 conversations at a time) Is this possible? | How to delete a range of emails in Gmail | gmail | null |
_cstheory.17038 | I became familiar with the BSS model of computation recently. I find it to be a better model of computation to study complexity of numerical analysis methods (cf. Complexity and Real Computation; Blum, Cucker, Shub, Smale.) Most of the existing PAC learning theory is concerned with standard computation model. I was wondering, are there any research or literature regarding PAC learning in the BSS model?The reason is that most of practical methods of computation over real numbers are based on numerical analysis which seem disconnected from the standard PAC learning developed in TCS community. Whereas the BSS model seems natural and well-suited for such studies. | PAC learning and computation over real numbers | cc.complexity theory;reference request;machine learning;lg.learning | null |
_codereview.40430 | My code snippet is like this:public static string EventId{ get { return HttpContext.Current.Request[eventId]; }}And I will call this property EventId whenever I need it. Is it a good practice? | Is it a good idea to keep Request querystring as a property? | c#;asp.net | Can you guarantee that eventId will never change? If so it might not be a bad idea, but this comes down to a few thingseventId never changes;how and where you're using it. It might be somewhat difficult for a new programmer in the project to locate and realize what it actually does (it returns the eventId for the current Http Request), solely based on the property name; andAre you sure that both HttpContext.Current and Current.Request are initialized before retrieving eventId. There is a change these will throw a null reference exception. It might be a very good idea to do a simple if != null check before invoking the Request property.If your code can accommodate for these points I don't see any inherently wrong with doing this. |
_unix.217181 | I do have a small pc(router_office) that runs debian wheezy (7) and it gets internet from wlan0 and acts as router for eth0 (NAT). Everything works fine.My setup is pretty simple in /etc/network/interfaces:auto wlan0iface wlan0 inet static address 192.168.2.49 netmask 255.255.255.0 broadcast 192.168.2.255gateway 192.168.2.1 wpa-ssid ATUX_wifi wpa-psk passw0rd4!dns-nameservers 8.8.8.8auto eth0 iface eth0 inet static address 192.168.1.10 netmask 255.255.255.0 dns-nameservers 8.8.8.8I have an second wifi that i could get connected to, which has SSID:be_sec_office with passwd:passwfooWhile in my laptop debian 7 with lxde in the connection manager if one wifi fails, then it connects automatically to the next one. How can I do that in my small pc(router_office), please? | debian wifi setup for failover | debian;wifi | null |
_unix.349314 | A server with no operating system will be plugged into an Ethernet network using an Ethernet cable. Can another machine on the network run an automated script that will remotely install CentOS 7 as the host OS on the new server? If so, how do I set this up? Currently, I have to manually install the new CentOS 7 host using a DVD or USB copy of the CentOS 7 iso file. This includes a GUI-based installation process that I would like to replace with a fully-automated process. I know that some hardware manufacturer's have administration tools that accomplish this on hardware that they manufacture themselves, but I am looking for something that is agnostic to hardware-vendor. | Automated install of remote Linux host OS | centos;system installation | The existing machine that the new machine will be connecting to will need to have a server which can provide PXE boot services. Your best source of information for CentOS would be the RHEL official documentation. PREPARING FOR A NETWORK INSTALLATIONhttps://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/chap-installation-server-setup.htmlYou can also look into Kickstart Fileshttps://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Installation_Guide/chap-kickstart-installations.html |
_codereview.133238 | I am in the process of making a game, and during this endeavour, I have come across problems maintaining a good frames per second while drawing my sprites. When I draw my background image, my frames drop from ~65 to ~30. My background image is simply a green tile 2000x2000 wide, constructed from 900 50*50 tiles.What can I do to increase my frames per second?My Main classimport java.awt.*;import java.awt.event.*;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.*;import javax.imageio.ImageIO;import javax.swing.*;import javax.swing.Timer;public class Main extends JPanel implements ActionListener, KeyListener{ static int WIDTH; static int HEIGHT; static int SCREENWIDTH; static int SCREENHEIGHT; static int GRAVITY = 2; BufferedImage background; Tower tower; Entity debug = new Entity(0, 0, 0, 30, 30, 300); ArrayList<Entity> entities = new ArrayList<Entity>(); Random random = new Random(); public Main(){ addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); requestFocus(); Thread thread = new Thread(new Runnable() { @Override public void run() { gameLoop(); } }); thread.start(); tower = new Tower(WIDTH, HEIGHT, 10, 10, 7); background = generateBackground(); entities.add(debug); } public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; AffineTransform plain = g2d.getTransform(); float xscale = (float)SCREENWIDTH/WIDTH; float yscale = (float)SCREENHEIGHT/HEIGHT; g2d.scale(xscale, yscale); g2d.rotate(Math.toRadians(45), WIDTH/2, HEIGHT/2); AffineTransform normal = g2d.getTransform(); g2d.drawImage(background, 0, 0, this); for (int e=0;e<entities.size();e++){ Entity entity = entities.get(e); if (entity.x + entity.w >= tower.x-tower.d && entity.x < tower.x + tower.w || entity.y + entity.h >= tower.y-tower.d && entity.y < tower.y + tower.h){ entity.draw(g2d, normal, this); } } for (int i=0;i<tower.map.size();i++){ for (int j=0;j<tower.map.get(i).size();j++){ for (int k=0; k<tower.map.get(i).get(j).size();k++){ Block renderBlock = tower.map.get(i).get(j).get(k); int x = renderBlock.x;int y = renderBlock.y;int w = renderBlock.w;int h = renderBlock.h;int z = renderBlock.z;int d = renderBlock.d; //block g2d.setTransform(normal); g2d.drawImage(renderBlock.top1, x-d-z,y-d-z, this); g2d.transform(AffineTransform.getShearInstance(1, 0)); g2d.drawImage(renderBlock.side1, x-y-w, y-z-(d-h), this); g2d.setTransform(normal); g2d.transform(AffineTransform.getShearInstance(0, 1)); g2d.drawImage(renderBlock.side2, x-z-(d-w), y-x-h, this); } } } for (int e=0; e<entities.size();e++){ Entity entity = entities.get(e); if (!(entity.x + entity.w >= tower.x-tower.d && entity.x < tower.x + tower.w) || !(entity.y + entity.h >= tower.y-tower.d && entity.y < tower.y + tower.h) || entity.z >= tower.d){ entity.draw(g2d, normal, this); } } FPSticks++; g2d.setTransform(normal); g2d.drawLine(WIDTH/2, 0, WIDTH/2, HEIGHT); g2d.drawLine(0, HEIGHT/2, WIDTH, HEIGHT/2); g2d.setTransform(plain); g2d.drawString(FPS: + currentFPS + | Logic Ticks: + currentTPS, 0, 10); g2d.drawLine(SCREENWIDTH/2, 0, SCREENWIDTH/2, SCREENHEIGHT); g2d.drawLine(0, SCREENHEIGHT/2, SCREENWIDTH, SCREENHEIGHT/2); } public void update(){ if (debug.velx != 0 || debug.vely != 0 || debug.velz != 0){ //say(x: + debug.x); //say(y: + debug.y); } debug.z-=GRAVITY; doCollision(); debug.update(); } public void doCollision(){ for (int e=0; e<entities.size();e++){ Entity entity = entities.get(e); if (entity.x+entity.w>=tower.x && entity.x<=tower.x+tower.w && entity.y+entity.h>=tower.y && entity.y<=tower.y+tower.h){ int leftDistance = (entity.x+entity.w)-tower.x; int rightDistance = entity.x-(tower.x+tower.w); int topDistance = (entity.y+entity.h)-tower.y; int bottomDistance = entity.y-(tower.y+tower.h); int[] distanceArr = {leftDistance, rightDistance, topDistance, bottomDistance}; int[] smallestArr = findSmallest(distanceArr); int index = smallestArr[1]; if (entity.z < tower.d){ entity.z+=GRAVITY; } if (entity.z < tower.d){ if (index == 0){ entity.x-=entity.speed; } else if (index == 1){ entity.x+=entity.speed; } else if (index == 2){ entity.y-=entity.speed; } else if (index == 3){ entity.y+=entity.speed; } } } } } public BufferedImage generateBackground(){ Image grass1 = null; File grass1f = new File(grass1.png); File backgroundf = new File(background.png); try { grass1 = ImageIO.read(grass1f); }catch (Exception e){ } background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = background.getGraphics(); for (int h=0;h<HEIGHT/50;h++){ for (int w=0;w<WIDTH/50;w++){ g.drawImage(grass1, w*50, h*50, this); } } try { ImageIO.write(background, PNG, backgroundf); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return background; } public int[] findSmallest(int[] arr){ int smallest = arr[0]; int index = 0; for (int i=0; i<arr.length;i++){ if (arr[i]<0){ arr[i]*=-1; } if (arr[i]<smallest){ smallest=arr[i]; index = i; } } int[] returnArr = {smallest, index}; return returnArr; } public static void main(String[] args){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); SCREENWIDTH = (int) screenSize.getWidth(); SCREENHEIGHT = (int) screenSize.getHeight(); //SCREENWIDTH = 800; //SCREENHEIGHT = 600; WIDTH = 2000; HEIGHT = 2000; Main main = new Main(); JFrame frame = new JFrame(); frame.setTitle(360 ATTACK); frame.setSize(SCREENWIDTH, SCREENHEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setUndecorated(true); frame.setLocationRelativeTo(null); frame.add(main); frame.setVisible(true); } long targetFPS = 60; long currentFPS = targetFPS; long currentTPS = targetFPS; long FPSticks = 0; long TPSticks = 0; long oldFPSTime = time(); long newFPSTime = oldFPSTime; public void gameLoop(){ long previous = time(); long lag = 0; while (true){ long current = time(); long elapsed = current-previous; previous = current; lag+= elapsed; while (lag >= 1000/targetFPS){ update(); lag-= 1000/targetFPS; TPSticks++; } repaint(); newFPSTime = time(); if (newFPSTime > oldFPSTime + 1000){ oldFPSTime = newFPSTime; currentFPS = FPSticks; currentTPS = TPSticks; FPSticks = 0; TPSticks = 0; } } } @Override public void actionPerformed(ActionEvent e) { } public long time(){ return System.currentTimeMillis(); } public void say(String str){ System.out.println(str); } @Override public void keyPressed(KeyEvent e) { int c = e.getKeyCode(); if (c == KeyEvent.VK_ESCAPE){ System.exit(0); } if (c == KeyEvent.VK_W){ debug.vely = -2; } if (c == KeyEvent.VK_S){ debug.vely = 2; } if (c == KeyEvent.VK_A){ debug.velx = -2; } if (c == KeyEvent.VK_D){ debug.velx = 2; } if (c == KeyEvent.VK_Q){ debug.velz = -2-GRAVITY; } if (c == KeyEvent.VK_E){ debug.velz = 2+GRAVITY; } } @Override public void keyReleased(KeyEvent e) { int c = e.getKeyCode(); if (c == KeyEvent.VK_W){ debug.vely = 0; } if (c == KeyEvent.VK_S){ debug.vely = 0; } if (c == KeyEvent.VK_A){ debug.velx = 0; } if (c == KeyEvent.VK_D){ debug.velx = 0; } if (c == KeyEvent.VK_Q){ debug.velz = 0; } if (c == KeyEvent.VK_E){ debug.velz = 0; } } @Override public void keyTyped(KeyEvent e) { }}Tower classimport java.util.ArrayList;public class Tower { ArrayList<ArrayList<ArrayList<Block>>> map = new ArrayList<ArrayList<ArrayList<Block>>>(); int blockw = 30, blockh = 30, blockd = 30; int WIDTH;int HEIGHT; int x;int y;int z;int d;int w;int h; public Tower(int WIDTH, int HEIGHT, int towerw, int towerh, int towerd){ this.WIDTH = WIDTH; this.HEIGHT = HEIGHT; ArrayList<Block> blocks; ArrayList<ArrayList<Block>> height; ArrayList<ArrayList<ArrayList<Block>>> depth; x = ((WIDTH/2)-(towerw*blockw)/2)+(0); y = ((HEIGHT/2)-(towerh*blockh)/2)+(0); z = 0; d = towerd*blockd; w = towerw*blockw; h = towerh*blockh; depth = new ArrayList<ArrayList<ArrayList<Block>>>(); for (int d=0; d<towerd;d++){ height = new ArrayList<ArrayList<Block>>(); for (int h=0; h<towerh;h++){ blocks = new ArrayList<Block>(); for (int w=0; w<towerw;w++){ blocks.add(new Block(x+(w*blockw), y+(h*blockh), (d*blockd), blockw, blockh, blockd)); } height.add(blocks); } depth.add(height); } map = depth; }}Entity classimport java.awt.Graphics2D;import java.awt.Image;import java.awt.geom.AffineTransform;import java.awt.geom.Path2D;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class Entity { int velx = 0; int vely = 0; int velz = 0; int speed = 2; int x; int y; int z; int w; int h; int d; Image side1; Image side2; Image top1; public Entity(int x, int y, int z, int w, int h, int d){ this.x = x; this.y = y; this.z = z; this.w = w; this.h = h; this.d = d; assignImages(); } private void assignImages(){ File fside1 = new File(side1.png); File fside2 = new File(side2.png); File ftop1 = new File(top1.png); try { side1 = (ImageIO.read(fside1)).getScaledInstance(w, d, Image.SCALE_DEFAULT); side2 = (ImageIO.read(fside2)).getScaledInstance(d, h, Image.SCALE_DEFAULT); top1 = (ImageIO.read(ftop1)).getScaledInstance(w, h, Image.SCALE_DEFAULT); } catch (IOException e) { } } public void update(){ this.x+=this.velx; this.y+=this.vely; this.z+=this.velz; if (this.z < 0){ this.z=0; } } public void draw(Graphics2D g2d, AffineTransform normal, Main observer){ // entity g2d.setTransform(normal); g2d.drawImage(this.top1,this.x-this.d-this.z,this.y-this.d-this.z,observer); g2d.transform(AffineTransform.getShearInstance(1, 0)); g2d.drawImage(this.side1, this.x-this.y-this.w, this.y-this.z-(this.d-this.h), observer); g2d.setTransform(normal); g2d.transform(AffineTransform.getShearInstance(0, 1)); g2d.drawImage(this.side2, this.x-this.z-(this.d-this.w),this.y-this.x-this.h, observer); }}Block classimport java.awt.Image;import java.awt.Shape;import java.awt.geom.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class Block { Image side1; Image side2; Image top1; int x,y,z,w,h,d; public Block(int x, int y, int z, int w, int h, int d){ this.x = x; this.y = y; this.z = z; this.w = w; this.h = h; this.d = d; assignImages(); } private void assignImages(){ File fside1 = new File(side1.png); File fside2 = new File(side2.png); File ftop1 = new File(top1.png); try { side1 = ImageIO.read(fside1); side2 = ImageIO.read(fside2); top1 = ImageIO.read(ftop1); } catch (IOException e) { } }}Imagestop1, side2, side1, are all this image:and grass1 is this image:If you need any of the related classes, Just comment and I can add them. I'm not sure if they are necessary though to post. | Unexpected Low FPS while drawing images | java;performance;game;graphics | As strange as it sounds, the performance drain really is on this one line of code right here:g2d.drawImage(background, 0, 0, this);The reason is that background is a rather large image, and the g2d is performing a scale and a rotate every time. Enabling OpenGL via -Dsun.java2d.opengl=True as suggested here might help, but I haven't been able to enable it on my machine.Do note as well that it may be worth just using an existing game engine.That said, the solution to the problem is to take the work out of the paintComponent method. If you never will view the background from a different angle, just draw it at this tilt to begin with. Otherwise, you need yet another thread. So there would be three threads:The GUI threadYour game loop threadThe rendering threadIn a proof-of-concept style, I added another volatile BufferedImage drawnBackground as a field, and I added this to the end of your Main constructor:new Thread(() -> { while(true) { if (background == null) continue; // A new BufferedImage to avoid concurrency issues; in this way, // the reference to this.drawnBackground is always a valid image // to be drawn. If we reassign this.drawnBackground = drawnBackground // while paintComponent() is running, that's fine, as it will simply // draw the old image. // It's also important to note that assignment to references // is an atomic operation, but we still have to declare the field // as volatile BufferedImage drawnBackground = new BufferedImage(background.getWidth(), background.getHeight(), background.getType()); Graphics2D g2d = (Graphics2D) drawnBackground.getGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, background.getWidth(), background.getHeight()); float xscale = (float) SCREENWIDTH / WIDTH; float yscale = (float) SCREENHEIGHT / HEIGHT; g2d.scale(xscale, yscale); g2d.rotate(Math.toRadians(45), WIDTH / 2, HEIGHT / 2); g2d.drawImage(background, 0, 0, this); this.drawnBackground = drawnBackground; }}).start();The paintComponent method changes to look like so:public void paintComponent(Graphics g){ super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; AffineTransform plain = g2d.getTransform(); float xscale = (float)SCREENWIDTH/WIDTH; float yscale = (float)SCREENHEIGHT/HEIGHT; g2d.drawImage(drawnBackground, 0, 0, this); g2d.scale(xscale, yscale); g2d.rotate(Math.toRadians(45), WIDTH/2, HEIGHT/2); AffineTransform normal = g2d.getTransform(); // g2d.drawImage(background, 0, 0, this); // rest of codeIn this way, we move the expensive operation of rendering the image to another thread. Note that that other thread will still be getting around 30 fps instead of 60 fps, but the game itself will be running at a better framerate. In other words, the background image will be updating at closer to 30 fps, while everything else will be faster. |
_softwareengineering.74848 | I'm a developer who mostly does web stuff in ruby and C#.I'd like to start tinkering with iOS and Mac development.Over the last few month i've been trying to get fluent in one set of key bindings (vi / vim because it just feels right).I have the awesome ViEmu installed for visual studio on windows which gives me a ton of the vim awesomeness side by side with visual studio power toys.Is there anything like this for xcode?I know I could set up MacVim as the default editor, but I'm not too interested in this as it means losing all of xcode's cocoa awareness.The other option of course would be to go for the lowest common denominator and switch to emacs (as the mac keybindings are based massively on emacs) but let's not think about that for too long. :P | Vim key mappings / plugin XCode? | xcode;mac;vim | null |
_cs.68422 | Forgive me for my brief knowledge on hash functions as I am not from a computer science background, however I am researching password security for my thesis and have been looking into hashing functions for password security. I understand that a password goes through a hashing function and is stored in a separate database, at which point if the user enters the same password at a later date, that entry is then ran through the same hashing function and checked the output is the same. My question is, if lots of companies are being breached and passwords have been found out using the algorithms, would it be more secure to then use a second hashing function on the already hashed password and store all the password entries 'double hashed'? | Using two hash functions for increased password security? | security;hashing | Current best practice goes like this: Step 1, the password is combined with a random sequence of characters (the salt), which means that even if two users use the same password, the combination salt + password will be unique for each user, and cracking one combination salt + password does not help at all cracking anyone else's password. Step 2, the combination salt + password is hashed using a cryptographic hashing function, but not once, not twice, but a gazillion times so that calculating the hashed password takes a significant amount of time. Step 3, the salt is stored, but the hashed password is not actually stored, but used to encrypt a master password for that user which is required to decrypt that user's information. The hashed password is not stored, so someone who manages to steal the complete information on the server still cannot access any user's data. To steal one user's data, an attacker has to guess passwords. Turning each password into a hashcode takes significant amounts of time, so cracking just one good (hard to guess) password should be very hard to crack. And that's just one password. |
_unix.242197 | Is there a portable way to do this?On Linux, I can use ps a -Nbut this option isn't available on other (POSIX) systems.Of course I can use grep '^?' with, say, -o tty,... but is there something more reliable? | List all processes without controlling terminal (only)? | ps;controlling terminal | null |
_hardwarecs.1935 | I'm reaching the limits of my old Notebook, since it only has a GeForce 630M and I want to use it for a bit of gaming, too. It's kinda sad, because the i7-2670QM still does the job quite well...I'm thinking about buying a new one, but I'd like to have a nice graphics card that does it's job without beeing too expensive. So what is the graphics card (I prefer Nvidia, but if AMD has something way better I would also consider using it) with the best Price-performance ratio?Requirements:Laptop GPU available in normal sized Notebooks (I don't want a monster, it should still be portable)at least 1 HDMI outputat least 2 outputs in sum, preferable VGA able to be used for games on the market right now (not high settings, just playable - my current 630M doesn't even manage 5 FPS for Rise of the Tomb Raider on lowest settings)I don't want to spend mroe than 1k for the full system (or rather I can't afford T.T), and since I also want an i7 and a good amount of RAM, the GPU itself mustn't be too expensive If you have suggestions for a full system, this would be nice, too, but the question aims to give me a overview of Graphic Cards which would meet my requirements. Afterwards I'll search for a new Notebook with one of these built in.I just had a quick look into the comparison site suggested by Adrian, an found the GeForce GTX 775M - this would be, from the performance aspect, top notch. I don'T even know how the price range is, and if this is available in non-gaming-notebooks (meaning normal sized cases), but anyway - this performance would be awesome. For the lower bound I'd name the GeForce GTX 580M - it shouldn't be much less performance than this, else I don't think buying a new notebook is really worth it. | Laptop GPU by Price-performance | laptop;gaming;graphics cards | null |
_unix.33435 | I cannot remember this command (and googling was unsuccessful), but there is a way to get the list of actions performed by a process, that outputs something like # listprocessactions -p 1234 0.321 Open A /var/log/nginx/supersite.log 0.322 Write to /var/log/nginx/supersite.log 0.401 Close /var/log/nginx/supersite.log 0.555 Opens TCP connection with slashdot.org ...I'm interested in the files aspect (open / RW files).The question is what is that command (and if possible in which package on deb / ubuntu) | Command to list in real time all the actions of a process | process;files;real time | You want strace(1) for that; it lists all the system calls made. See the manual page for details on various ways to present the trace data.You might also find ltrace(1) useful if you want inter-library calls rather than system calls traced. |
_codereview.79014 | This question is a follow-up to:High-Low Guessing GameNow with shiny new graphics in JavaFX.You now have the awesome ability to choose which numbers to guess between.Now with Git Repository!Main.javapackage sample;import javafx.application.Application;import javafx.fxml.FXMLLoader;import javafx.scene.Parent;import javafx.scene.Scene;import javafx.stage.Stage;public class Main extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource(highlow_view.fxml)); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); }}Controller.javapackage sample;import javafx.event.ActionEvent;import javafx.fxml.FXML;import javafx.scene.control.Label;import javafx.scene.control.TextField;import javafx.scene.input.KeyCode;import javafx.scene.input.KeyEvent;import java.util.Random;public class Controller { @FXML private Label guessLabel; @FXML private Label numberGuessLabel; @FXML private TextField txtAddItem; @FXML private TextField fromAddItem; @FXML private TextField toAddItem; @FXML private Label systemOut; private static Random rand = new Random(); private boolean isInt; public int randomNumberFrom = 1; public int randomNumberTo = 10; private int numberGuess = 0; private int theRandomNumber = randomInt(randomNumberFrom, randomNumberTo); public int getTheRandomNumber() { return theRandomNumber; } public static int randomInt(int from, int to) { return rand.nextInt(to - from + 1) + from; } public void countGuess(int numberIn) { numberGuess++; numberGuessLabel.setText(Guess counter: + numberGuess); if (numberIn < theRandomNumber) { systemOut.setText(Too low); } else if (numberIn > theRandomNumber) { systemOut.setText(Too high); } else { systemOut.setText(Congratz you were right!); } } public int textInt(TextField textField) { if(!textField.getText().matches(^\\d+$)) { systemOut.setText(Pleas enter a number); isInt = false; return 0; }else{ isInt = true; return Integer.parseInt(textField.getText()); } } public void guessing(int numberIn){ if (isInt == true) { if (numberIn < randomNumberFrom || numberIn > randomNumberTo) { systemOut.setText(Pleas enter number: + randomNumberFrom + - + randomNumberTo); } else { countGuess(numberIn); } } } @FXML public void getNewNumber(ActionEvent action){ int fromInt = textInt(fromAddItem); if (isInt == true) { int toInt = textInt(toAddItem); if (isInt == true && fromInt < toInt) { numberGuess = 0; numberGuessLabel.setText(Guess counter: + numberGuess); theRandomNumber = randomInt(fromInt, toInt); randomNumberFrom = fromInt; randomNumberTo = toInt; guessLabel.setText(Guess a number: + fromInt + - + toInt); } else{ systemOut.setText(The second number must be bigger then the first); } } } @FXML private void handleEnterPressed(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { guessing(textInt(txtAddItem)); } } @FXML private void guessButton(ActionEvent action){ guessing(textInt(txtAddItem)); }}highlow_view.fxml<?xml version=1.0 encoding=UTF-8?><?import javafx.scene.control.*?><?import javafx.scene.layout.*?><?import javafx.scene.text.*?><AnchorPane id=AnchorPane prefHeight=200.0 prefWidth=500.0 xmlns:fx=http://javafx.com/fxml fx:controller=sample.Controller><children> <VBox fx:id=VBoxMain alignment=TOP_CENTER prefHeight=500.0 prefWidth=400.0 AnchorPane.bottomAnchor=40.0 AnchorPane.leftAnchor=100.0 AnchorPane.rightAnchor=100.0 AnchorPane.topAnchor=20.0> <children> <Label fx:id=systemOut text=Hello :D alignment=CENTER prefHeight=200.0> <font> <Font name=System Bold size=18.0 /> </font> </Label> <Label fx:id=numberGuessLabel text=Guess counter:0 /> <Label fx:id=guessLabel text=Guess a number:1-10 /> <TextField fx:id=txtAddItem prefWidth=200.0 onKeyPressed=#handleEnterPressed /> <HBox id=HBox fx:id=HBox4Btns alignment=CENTER spacing=5.0> <children> <Button mnemonicParsing=false onAction=#guessButton text=Guess/> <Button mnemonicParsing=false onAction=#getNewNumber text=New Number/> <TextField fx:id=fromAddItem prefWidth=50.0/> <Label fx:id=fromToo text=- /> <TextField fx:id=toAddItem prefWidth=50.0/> </children> </HBox> </children> </VBox></children></AnchorPane> | Numbers are high, numbers are low. Will you guess the right answer, though? | java;beginner;number guessing game;javafx | private static Random rand = new Random();This variable can/should be finalpublic int randomNumberFrom = 1;public int randomNumberTo = 10;In Java it is better practice, if you want to allow access to your variables, to make getters and setters and make the variables themselves private.private int randomNumberFrom = 1;private int randomNumberTo = 10;public int getRandomNumberFrom() { return this.randomNumberFrom;}public int getRandomNumberTo() { return this.randomNumberTo;}In this case, since these values are so tightly tied together, you could have one method to set both values:public void setRandomRange(int from, int to) { this.randomNumberFrom = from; this.randomNumberTo = to;}Ideally, you should also do some validation in this method to ensure that to > from. Like this:public void setRandomRange(int from, int to) throws IllegalArgumentException { if (to <= from) { throw new IllegalArgumentException(to must be greater than from); } this.randomNumberFrom = from; this.randomNumberTo = to;}numberGuess++;numberGuessLabel.setText(Guess counter: + numberGuess);This variable numberGuess has a bad name. It's not until I read this code that I realize ok, it counts the number of guesses. It could just as well have been the number you guessed at. guessCount would be a better name.Your textInt method smells because it modifies the isInt field. It also sets the error message in case it's not a valid number. And it also returns an int.public int textInt(TextField textField) { if(!textField.getText().matches(^\\d+$)) { systemOut.setText(Pleas enter a number); isInt = false; return 0; }else{ isInt = true; return Integer.parseInt(textField.getText()); }}One small improvement, because you are not using return values less than 0, is to return -1 as a special case to indicate that it is not a valid integer. This would get rid of the isInt variable as a startpublic int textInt(TextField textField) { if(!textField.getText().matches(^\\d+$)) { systemOut.setText(Pleas enter a number); return -1; }else{ return Integer.parseInt(textField.getText()); }}Then you just check for value >= 0 instead of isInt.However, it might be better to use the fact that Integer.parseInt throws a NumberFormatException to do this. I think it might be best if you use the following approach, without using it as a method:try { int value = Integer.parseInt(textField.getText()); // do something if value is integer}catch (NumberFormatException ex) { systemOut.setText(Please enter a number);} @FXML private void handleEnterPressed(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { guessing(textInt(txtAddItem)); } } @FXML private void guessButton(ActionEvent action){ guessing(textInt(txtAddItem)); }In this case you can have one method call the other one: @FXML private void handleEnterPressed(KeyEvent event) { if (event.getCode() == KeyCode.ENTER) { guessButton(null); } } |
_cogsci.4659 | Successful leadership appears to depend on the personality of the leader. Judge et al. (2002) found the following correlations with the big five personality factors in a meta-analysis:Personality trait Correlation with leadership successNeuroticism -.24Extraversion .31Openness .24Agreeableness .08Conscientiousness .28Kock (1965) found the following correlations between the needs for achievement, power, and affiliation, and economic success: Achievment Power Affiliation Ach+Pow-AffGross Production Value .39 .49* -.61** .67**Number of Employees .41 .42 -.62** .66**Turnover .46* .41 -.53* .60*Gross Investment .63* -.06 .20 .45*Profit .27 .01 -.30 .34These two studies found that leaders must not be neurotic, need not be agreeable, and must not have a need for affiliation.But personality influences not only a person's workplace behavior and success, but also his choice of a romantic partner and how he shapes his relationships to the members of his family. I wonder therefore:Are there studies on the family situations of leaders, how they relate to their spouses and children, and how they influence their children's development?Sources:Judge, T. A., Bono, J. E., Ilies, R., & Gerhardt, M. W. (2002). Personality and leadership: A qualitativ and quantitative review. Journal of Applied Psychology, 87, 765-780. doi:10.1037/0021-9010.87.4.765 Available online at http://workforceuniverse.com/wp-content/uploads/2011/05/Judge_2002.pdfKock, S. W. (1965). Management and motivation. Summary of a doctoral thesis presented at the Swedish School of Economics, Helsingfors, Finland. | How does the personality of a successful leader influence the development of his children? | developmental psychology;personality;io psychology;parenting;leadership | null |
_cs.65045 | It seems to me that in order to construct the union and the product of two DFA we use basically the same method. The difference is that when we make the accepting states for the resulting DFA. Suppose $A_{1}$ an DFA with $F_{1}$ as an accepting state, and $A_{2}$ an DFA with $F_{2}$ as an accepting state. In the case of an union of $A_{1}$ and $A_{2}$, the accepting states have either $F_{1}$ or $F_{2}$ or both, and in the case of a product, the accepted state is {$F_{1},F_{2}$}. Am I correct? | Is the difference between between an union and a product of two DFA lies in their accepting states? | finite automata | Please use the terminology correctly. The union operation is an operation defined on sets. It does not make sense to speak of the union of two automata. The product construction can be used to give a constructive proof that the class of regular languages is closed under union. But with minor modifications, the product construction can also be used to show that the class of regular languages is closed under intersection as well as under set difference.Assume that we have two DFA $M_1 = (Q_1,\delta_1,\Sigma,q^1_0,F_1)$ and $M_1 = (Q_2,\delta_2,\Sigma,q^2_0,F_2)$. In the case of intersection, define the set of accepting states as$$F = \{ (q_1,q_2) \mid q_1 \in Q_1 \wedge q_2 \in Q_2 \} $$For set difference, define the set of accepting states as$$F = \{ (q_1,q_2) \mid q_1 \in Q_1 \wedge q_2 \notin Q_2 \} $$ |
_softwareengineering.237657 | Is it possible to implement generic routines in any language (C#, Java, etc). By generic routines I mean, in specific event Handlers. Lets say, I have 2 Buttons and 2 text boxes. One Button, when pressed, takes the first text box text and converts to Uppercase and second button prints the length of the string in the other text box. Now, Can I have a function as button(type, textbox) {if(type==1)/*Convert to upper case*/else if(type==2)/*Print the length*/}The type takes any button as input and further processes it. I want to implement this because of redundancy in my code and I want to make my code portable to other languages. So that I need to modify only the syntax to make it work. Is it feasible? | Implementing Generic Routines | programming practices | Normally, this should be done by having one handler for each logic. void handleUppercase(object sender, EventArgs args){ // convert text to uppercase}void handleLength(object sender, EventArgs args){ // display length}// then assign those handlers properlybutton1.OnClick += handleUppercasebutton2.OnClick += handleLengthAlso, you are not going to have much luck changing code for different languages, because different languages use different UI frameworks. And there are too big differences between those frameworks to allow any kind of sharing. If you want to have same code in different languages, you have to make sure it doesn't depend on any specific framework. Which UI frameworks are.The case is quite different when you have same logic, but on different buttons with different parameters. In this case, you have 2 basic options.First is to use similar approach as Robert suggests:void handleUppercase(object sender, EventArgs args){ if (sender == buttonA) // do logic for first arguments if (sender == buttonB) // do logic for second arguments}buttonA.OnClick += handleUppercasebuttonB.OnClick += handleUppercaseSecond option is to parametrize the handler itself. In OOP, that could be done if the handler was a Command. Simply create different instances of command with different parameters for each button. In functional way, you could use partial application. But because C# doesn't have this concept, you have to help yourself with lambdas:void handleUppercase(object sender, EventArgs evArgs, Argument arg){ // do logic for arg}buttonA.OnClick += (s, e) => { handleUppercase(s, e, arg1); }buttonB.OnClick += (s, e) => { handleUppercase(s, e, arg2); } |
_webapps.79811 | I'm trying to get the HLOOKUP function working in my sheet but it's not working like it should.The function is:=HLOOKUP(TEXT(NOW(), yyyy-MM-dd), INDIRECT(TEXT(NOW(), MMMM) & !B1:AE5), 3, FALSE) Translating the functions, that would be:=HLOOKUP(2015-07-01, July!B1:AE5, 3, FALSE)I get an error however:Did not find value '2015-07-01' in HLOOKUP evaluationThat doesn't make sense since '2015-07-01' is in cell B1 in the sheet, July.Why isn't it working and what can I do to fix it?Sheet | Using HLOOKUP for date values | google spreadsheets | null |
_softwareengineering.274877 | I've got a program that validates it's input, and then errors.So far for each kind of error I created a new derived class. But this was getting pretty unwieldy (the input is complex so there are many possible errors) so instead I made the base more flexible and removed all the derived classes.The core resulting issue is that now when I test with certain invalid inputs, I'm not sure how to identify the correct error anymore. If the program produces an error on invalid input but it's the wrong one, how am I going to identify the correct error without effectively hardcoding internal error implementation details?Edit: I also intended to specify that the reason I went with a new derived class per error type is that I need dynamically extensible error types. Something like an enumeration would never be suitable. | Testing generic errors | testing;error handling | null |
_unix.203222 | I Have a list file File_Transfer_List.txt which contains list of file to do scpMy requirement is I need to do scp that files given in the list file and then delete the files from source location. I tried this :scp File_Name user@server:/destination && rm File_Name ;I am unable to test it, I don't have my scp ready to test it; can any one correct me if I am wrong. | SCP and delete a files from source | scp | null |
_unix.334373 | My Laptop has 3 Windows 7, and 2 Linux distributions, Ubuntu & Mint.When booting the Laptop, Grub would show up with Mint as my first option, Ubuntu as the second, and Windows EFI Bootloader as the third.When selecting the third option, a Windows bootloader would be prompted with my 3 options of Windows.Also, it's worth mentioning that I have both an SSD and a HDD and the operating systems and the boot info are installed in the SSD, in GPT format (not MBR anymore). Thus, the Windows are installed as EFI, whereas the Linuxes are not.Recently I removed my SSD and plugged another one, just to erase all data. I booted a live CD of Ubuntu and ran a Secure Wipe on the new SSD. Everything went smoothly. After that, I plugged my original SSD back. Interestingly, Windows bootloader was appearing first with the 3 options of Windows. To use Linux, I have to hit Esc, then the BIOS let me choose a device from the boot list,then I have to select the SSD device (Internal HDD: Crucial_...), and Ubuntu's grub version appears (The purple one, whereas the original was black & white which I installed from Mint)I figured the problem was in the BIOS that was booting Windows's bootloader first, so I checked itAs you can see, EFI appears at the top, apart from Boot Priority. Internal HDD: Crucial_... is correctly set at the top of Boot Priority, but somehow EFI is loading first. I cannot, through BIOS, set the EFI to a low priority.As everything was normal before, and I didn't change BIOS settings, I cannot understand what happened. Also, it's very curious that it seems to have affected my cookies. I use Google Chrome, and I had to re-login into my e-mail, facebook, etc accounts. As far as the computer is concerned, a device was replaced, and then replaced back in. No settings were changed by me, so what could have happened and how can I change things back to how they were before (grub booting first)? | How to make Grub boot before Windows bootloader? | dual boot;grub;boot loader;uefi;bios | null |
_webapps.95469 | I have a Trello board with a list named TODO. I'd like to have the contents of my TODO list sent to me every morning through Slack - either automatically or by running a command, which I could then automate using another integration/bot.What's a good way to implement this?So far I've looked into:the Trello bot - allows you to display cards and boards, but not listsTrello Alerts - can't be polled on demandWorkbot - can only create Trello entities, not read them | Bot/command to display the contents of a Trello list? | trello;slack | null |
_codereview.40096 | I have a (control engineering) controller. These controllers usually need several parameters to do their thing, and in my application it is desirable that these parameters can be changed while the controller is running - in a thread safe and well defined manner.I came up with this design (extremely simplified):// This is the class that the user instanciates.public class Controller{ public ControllerInfo Info { get; set; } public void Start() { ... } public void Stop() { ... } private ControllerBody body = new ControllerBody(); private void ControllerThreadProc() { while (true) { var elapsedTime_ms = ...; var currentInfo = this.Info; // the actual calculation is done in another class this.body.SingleStep(currentInfo, elapsedTime_ms); Thread.Sleep(currentInfo.SampleTime_ms); } }}// This exists as a separate class so it is possible to test the// mathematical model without having to do it in real-time.public class ControllerBody{ public void SingleStep(ControllerInfo info, long elapsedTime_ms) { var referenceValue = info.ReferenceValueGetter(); var calculationResult = math; info.ControlValueSetter(calculationResult); }}// Immutable class that contains all the info necessary to do stuff.public class ControllerInfo{ public Func<double> ReferenceValueGetter { get; private set; } public Action<double> ControlValueSetter { get; private set; } public int SampleTime_ms { get; private set; } public double SomeConstant { get; private set; } public double OtherConstant { get; private set; } ... public ControllerInfo(/* 1 argument per property :( */) { /* many assignments */ }}Usage example:var controller = new Controller();controller.Info = new ControllerInfo(/* values */);controller.Start();// later:controller.Info = new ControllerInfo(/* new values */);// Application is done:controller.Stop();Again, it should be possible to change the controller while it is running. Therefore I gave Controller a publicly settable ControllerInfo.However, if the user decides to change the values of SomeConstant and OtherConstant in this example, it must be guaranteed that no calculation step is executed where only one of these are changed. In other words, changing a bunch of parameters must be an atomic operation. That's why ControllerInfo is not mutable.I have identified 2 downsides to this architecture:If I add another mathematical constant to ControllerInfo, I have to add (1) a property, (2) a parameter to the constructor (can be forgotten even if (1) has been done!), and (3) an assigment inside the constructor (can be forgotten even if (1) and (2) have been done!).If the user wants to change a parameter while the controller is running, they must make another tedious constructor call, passing in values that have changed, as well as values that haven't changed.To get around the usability problem, I considered introducing a ControllerInfoFactory class, which is basically a mutable copy of ControllerInfo:public class ControllerInfoFactory{ public (SamePropertiesAsControllerInfo) { get; set; } public ControllerInfo CreateControllerInfo() { return new ControllerInfo(/* pass all parameters from this */); }}However, that makes the first problem even worse: For each property, I now also have to add the property to ControllerInfoFactory. Luckily, this time it's not possible to forget updating the CreateControllerInfo method as long as the ControllerInfo constructor has already been updated.Now to code review:Does this design make sense? Is the usability OK?Can the large amount of repetitive code per property be reduced? | Allow changing the properties of a mutable controller in a thread safe way | c#;thread safety;immutability | null |
_unix.182129 | I have a dual boot system (Win7 for my company) and (UBUNTU 14.10) .. My company is using Encryption for the image of Win7.After Win7 installation i installed UBUNTU 14.10 and i was able to boot both.My HDD is partitioned as follows:3 Primary partitions (c: for windows , D: , E: for data ) and 5 Logical partitions (3 data and 1 for Ubuntu and 1 for swap).Firstly, (N.B. Problem_1) I noticed that from Ubuntu i'm unable to mount any of the primary partitions, but i can normally mount the other logical ones.Secondly, (N.B. Problem_2) I decided to test Ubuntu Vivid 15.04 so i installed it on one of the logical partitions.After the installation i lost the Windows totally and i'm unable to boot to it, and from both Ubuntu versions, i'm unable to mount the primary partitions (ERROR: wrong fs type, bad option, bad superblock on /dev/sda1, missing codepage or helper program, or other error )I used Boot Repair software on both Ubuntu versions, but none of them detected the Windows.During boot of Ubuntu Vivid, it shows error (TPM error) and I understood that it is related to TPM Chip that is implemented for the security on Bios, i logged in to BIOS and disabled TPM option then the error disappeared.I'm currently unable to boot from windows as it is not seen by Grub. And unable to mount the NTFS partition for windows.If i understand well, this could be related to the security option done by the company that is preventing accessing the primary partition if the HDD is used outside the laptop, but at least i should be able to mount it even as Read-only or to boot from it in parallel with other OSs especially that it was working before and that i also disabled TPM.Can anyone explain to me how to mount windows7 partition or to get its boot option back ? | Lost Win7 boot after installing UBUNTU Vivid | ubuntu;mount;windows;dual boot;ntfs | null |
_codereview.13359 | I need to create a class with two properties:LogOutputExceptionOutputThese properties (of type Action) send a message or a exception depending on the target function. This target function is set via properties.Currently, I have the following code:public class Output{ private Action<string> logOutput; private Action<Exception, string> exceptionOutput; public Action<string> LogOutput { set { this.logOutput = value; } get { return this.logOutput; } } public Action<Exception, string> ExceptionOutput { set { this.exceptionOutput = value; } get { return this.exceptionOutput; } } public Output() : this(null, null) { } public Output(Action<string> logAction, Action<Exception, string> exceptionAction) { this.logOutput = logAction; this.exceptionOutput = exceptionAction; } public void WriteLogMessage(string format, params object[] args) { if (this.logOutput != null) logOutput(string.Format(format, args)); } public void WriteExceptionMessage(Exception ex, string format, params object[] args) { if (this.exceptionOutput != null) exceptionOutput(ex, string.Format(format, args)); }}And this is my form code:private void MainForm_Load(object sender, EventArgs e){ Output myOutput = new Output(); myOutput.ExceptionOutput = this.WriteExceptionMessageToTextBox; myOutput.LogOutput = this.WriteLogMessageToTextBox; myOutput.WriteLogMessage(this is my log message to text box); myOutput.WriteExceptionMessage(new Exception(this is my exception), this is my exception message to text box);}private void WriteLogMessageToTextBox(string message){ if (this.txtBox.IsDisposed) return; if (this.InvokeRequired) { BeginInvoke(new MethodInvoker(delegate() { WriteLogMessageToTextBox(message); })); } else { this.txtBox.AppendText(message + Environment.NewLine); }}private void WriteExceptionMessageToTextBox(Exception ex, string message){ if (this.txtBox.IsDisposed) return; if (this.InvokeRequired) { BeginInvoke(new MethodInvoker( delegate() { WriteExceptionMessageToTextBox(ex, message); })); } else { string msg = ; msg += string.Format(Program:{0}, message); msg += string.Format(Message{0}, ex.Message); msg += string.Format(StackTrace:{0}, ex.StackTrace); msg += string.Format(Source:{0}, ex.Source); this.txtBox.AppendText(msg + Environment.NewLine); }}The thing is I don't know if this is correct (although it's working). If it's not correct, how can I change it? How can I implement it with events? | Is it correct to use delegates as properties? | c#;delegates;properties | Yes, I think this is reasonable code. If you want to set more delegates at the same time or unsubscribe a delegate, events would be more appropriate. But if you don't want to do that, delegate properties are fine.There are some things to think about though:The code you use to invoke the delegates is not thread-safe. If one thread called WriteLogMessage() and another thread set logOutput to null at the same time, you might get a NullReferenceException. The thread-safe version would be:var logOutputTmp = this.logOutput;if (logOutputTmp != null) logOutputTmp(string.Format(format, args));Consider using automatic properties. They do the same thing as your code, only with less writing. Also, get accessor is usually written before the set accessor, but that's only a minor style issue.public Action<string> LogOutput { get; set; }Do you need the public setters and the parameterless constructor? If you expect that both delegates will be always set at construction, then it's better to make that clear and have only one constructor and no public setters. |
_computergraphics.2014 | I am implementing a simple Phong shader in OpenGL GLSL, and the test object is the utah teapot. However on the bottom I get a solid red circle, and on the top there is are sharp sectors that are coloured incorrectly.Is there any way to fix these issues? What would be the issue in the first place? | Artefacts on top and bottom of utah teapot | opengl | null |
_codereview.64258 | I've implemented the queue data structures using array in java. Anything I need to change in my code?Queue.javaimport java.util.Arrays;public class Queue<T> { private int front; private int rear; int size; T[] queue; public Queue(int inSize) { size = inSize; queue = (T[]) new Object[size]; front = -1; rear = -1; } public boolean isempty() { return (front == -1 && rear == -1); } public void enQueue(T value) { if ((rear+1)%size==front) { throw new IllegalStateException(Queue is full); } else if (isempty()) { front++; rear++; queue[rear] = value; } else { rear=(rear+1)%size; queue[rear] = value; } } public T deQueue() { T value = null; if (isempty()) { throw new IllegalStateException(Queue is empty, cant dequeue); } else if (front == rear) { value = queue[front]; front = -1; rear = -1; } else { value = queue[front]; front=(front+1)%size; } return value; } @Override public String toString() { return Queue [front= + front + , rear= + rear + , size= + size + , queue= + Arrays.toString(queue) + ]; }}QueueImpl.javapublic class QueueImpl { public static <T> void main(String[] args) { Queue newQueue = new Queue(5); newQueue.enQueue(10); newQueue.enQueue(20); newQueue.enQueue(30); newQueue.enQueue(40); newQueue.enQueue(50); System.out.println((T) newQueue.toString()); System.out.println((T) newQueue.deQueue().toString()); System.out.println((T) newQueue.deQueue().toString()); System.out.println((T) newQueue.toString()); newQueue.enQueue(60); newQueue.enQueue(70); System.out.println((T) newQueue.toString()); System.out.println((T) newQueue.deQueue().toString()); System.out.println((T) newQueue.deQueue().toString()); System.out.println((T) newQueue.deQueue().toString()); System.out.println((T) newQueue.deQueue().toString()); System.out.println((T) newQueue.deQueue().toString()); System.out.println((T) newQueue.toString()); }} | Array Implementation of Queue | java;beginner;array;queue | Your fields size and queue have package access, they need to be private so only your class can control them.private final int size;private final T[] queue;And because their values are known at initialization, its good practice to declare them final.your isempty method is not Camelcase, use isEmpty instead.Some validation on the size parameter is needed as well. if(size<=0){ throw new IllegalArgumentException(Size cannot be less than or equal to zero); }Something I love about the this keyword is that it helps you finding a name for your variables public Queue(int size) { // size is more relevant than inSize if(size<=0){ throw new IllegalArgumentException(Size cannot be less than or equal to zero); } this.size = size; queue = (T[]) new Object[size]; front = -1; rear = -1;} |
_unix.67969 | I'm attempting to use Solaris 11's ILB to create a loadbalancer across two backend DNS servers. Here's my requirements:Two external IPs: .XXX.YYY, .XXX.ZZZ - these are the DNS IP's that our clients hitTwo ILB boxes in a HA configuration over those two external IPsTwo backend DNS serversI'd like to have the two ILB boxes (ilb1 and ilb2) each load balance across the two DNS servers (ns1 and ns2) on two different incoming IPs. I'd like ilb1 to be primary on .XXX.YYY and secondary on .XXX.ZZZ, and ilb to be the inverse of this. This way, if either of the DNS servers or the ILB servers goes down, DNS requests should continue unimpacted. However, we can't go Full NAT on this due to our requirements that the backend servers have to be able to see the actual SRC_IP of the DNS request - going full NAT makes it look to the DNS servers that all requests are coming from the ILB boxes, not the clients themselves.Going HALF-NAT will correctly maintain the SRC_IP of the DNS request, however that means that the packet now has to be routed through the ILB box that it was requested from, so that the correct IP is on the packet when it gets to the client, otherwise the client will throw it out (response from unexpected source and the like). Here's the sticky issue – since there are two IPs, how do I reliably route the request back through the correct ILB box? /etc/defaultrouter on the DNS boxes only lets you use 1 IP, so roughly half of our responses would be trashed.Is this setup possible? Is my description clear as mud? | Solaris 11: How to use ILB to create HA loadbalancer across two backend servers? | networking;solaris;routing;load balancing | null |
_codereview.101091 | I have some functionality that allows the user to create a Meter, which counts your gas, water, and electricity usage.A Meter has one or more Counter objects, which keeps track of your usage for a certain date via CounterReading.Once a Meter is created, you can edit it by adding a new Reading.This is the caller:Create:internal void CreateUtilityTransferButton_Click(Premise selectedPremise){ var printUtilitiesWindow = new TransferUtilitiesWindow(); if (selectedPremise != null) printUtilitiesWindow.TransferUtilitiesWindowViewModel.SelectedTransferPremise = selectedPremise; if (printUtilitiesWindow.ShowDialog() == true) { PdfFiller filler = new PdfFiller(); var documentType = printUtilitiesWindow.TransferUtilitiesWindowViewModel.DocumentType; try { switch (documentType) { case UtilityDocumentType.Transfer: filler.Fill(printUtilitiesWindow.TransferUtilitiesWindowViewModel.Transfer); break; case UtilityDocumentType.Connection: filler.Fill(printUtilitiesWindow.TransferUtilitiesWindowViewModel.Connection); break; case UtilityDocumentType.Water: filler.Fill(printUtilitiesWindow.TransferUtilitiesWindowViewModel.Water); break; default: throw new ArgumentException(Verkeerd documenttype gekozen); } } catch (ArgumentException e) { var popup = new ErrorMessage(e); popup.ShowDialog(); } }}Edit:internal void EditMeterButton_Click(Meter _meter){ if (_meter == null) return; var premise = _meter.Premise; var createMeterWindow = new CreateMeterWindow(_meter); if (createMeterWindow.ShowDialog() == true) { var meter = createMeterWindow.CreateMeterViewModel.Meter; meter.AddReading(createMeterWindow.CreateMeterViewModel.NewReading); if (meter is DoubleElectricityMeter) { var doubleElectricityMeter = meter as DoubleElectricityMeter; doubleElectricityMeter.CounterNight.Readings.Add(createMeterWindow.CreateMeterViewModel.NewNightReading); } VivendaContext.SaveChanges(); }}This is my codebehind:public partial class CreateMeterWindow : Window{ private CreateMeterViewModel _CreateMeterViewModel; public CreateMeterViewModel CreateMeterViewModel { get { return _CreateMeterViewModel; } } public CreateMeterWindow() { _CreateMeterViewModel = new CreateMeterViewModel(this); InitializeComponent(); DataContext = _CreateMeterViewModel; } public CreateMeterWindow(Meter meter) { _CreateMeterViewModel = new CreateMeterViewModel(this, meter); InitializeComponent(); DataContext = _CreateMeterViewModel; } private void OkButton_Click(object sender, RoutedEventArgs e) { _CreateMeterViewModel.OkButton_Click(); } private void CancelButton_Click(object sender, RoutedEventArgs e) { _CreateMeterViewModel.CancelButton_Click(); } private void ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { _CreateMeterViewModel.ComboBox_SelectionChanged(); }}The viewmodel:public class CreateMeterViewModel : INotifyPropertyChanged{ private Window _Window; private Meter _Meter; private CounterReading _Reading; private CounterReading _NightReading; private MeterType _MeterType; private Visibility _isDoubleMeterVisibleVisible = Visibility.Hidden; public Premise Premise { get; set; } public Meter Meter { get { if (_Meter == null) { } return _Meter; } set { _Meter = value; NotifyPropertyChanged(Meter); } } public CounterReading Reading { get { if (_Reading == null) { _Reading = new CounterReading(); } return _Reading; } set { _Reading = value; NotifyPropertyChanged(Reading); } } public CounterReading NightReading { get { if (_NightReading == null) { _NightReading = new CounterReading(); } return _NightReading; } set { _NightReading = value; NotifyPropertyChanged(NightReading); } } public MeterType MeterType { get { return _MeterType; } set { _MeterType = value; NotifyPropertyChanged(MeterType); } } public Visibility IsDoubleMeterVisible { get { return _isDoubleMeterVisibleVisible; } set { _isDoubleMeterVisibleVisible = value; NotifyPropertyChanged(IsDoubleMeterVisible); } } private bool _isEdit = false; public bool IsEdit { get { return _isEdit; } set { _isEdit = value; } } //Used for enabling / disabling controls. public bool IsNotEdit { get { return !IsEdit; } } public bool IsNightEdit { get { return _isEdit && (_Meter is DoubleElectricityMeter); } } private CounterReading _NewReading; public CounterReading NewReading { get { if (_NewReading == null) { _NewReading = new CounterReading(); } return _NewReading; } set { _NewReading = value; } } private CounterReading _NewNightReading; public CounterReading NewNightReading { get { if (_NewNightReading == null) { _NewNightReading = new CounterReading(); } return _NewNightReading; } set { _NewNightReading = value; } } public CreateMeterViewModel(Window window) { _Window = window; } public CreateMeterViewModel(Window window, Meter meter) : this(window) { IsEdit = true; // This is only called when we already have a created meter. _Meter = meter; _MeterType = meter.Type; Premise = meter.Premise; _Reading = meter.Counter.CurrentReading; IsDoubleMeterVisible = _Meter is DoubleElectricityMeter ? Visibility.Visible : Visibility.Hidden; if (_Meter is DoubleElectricityMeter) { _NightReading = (meter as DoubleElectricityMeter).CounterNight.CurrentReading; } } internal void CancelButton_Click() { _Window.DialogResult = false; _Window.Close(); } internal void OkButton_Click() { _Window.DialogResult = true; _Window.Close(); } internal void ComboBox_SelectionChanged() { if (IsEdit) { return; } if (_MeterType != MeterType.Unknown) { var eanNumber = _Meter == null ? : _Meter.EANNumber; var meterNumber = _Meter == null ? : _Meter.MeterNumber; CreateMeter(); if (Meter != null) Meter.EANNumber = eanNumber; if (Meter != null) Meter.MeterNumber = meterNumber; NotifyPropertyChanged(Meter); IsDoubleMeterVisible = _Meter is DoubleElectricityMeter ? Visibility.Visible : Visibility.Hidden; } else { Meter = null; } } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } private void CreateMeter() { if (_MeterType != MeterType.Unknown) { try { _Meter = MeterFactory.Create(Premise, _MeterType); } catch (MeterTypeAlreadyExistsException e) { MeterType = MeterType.Unknown; var popup = new ErrorMessage(e); popup.ShowDialog(); } } }}Please keep in mind this is my first serious C# / WPF project, so I'd appreciate any remarks or suggestions. | Creating and Editing a UtilityMeter | c#;.net;wpf | null |
_cs.69056 | For example, lets consider the simplest model of cipher: the Caesar cipher. According to the theory I read the Caesar cipher consist in substitute a letter by another in considering a shift in an alphabet given by a certain number.I know that a Turing machine consist of: a tape, a header that writes or reads information from that tape, and a set of states that consist in moving to the left or right on the tape. Also the initial state and the final state and reject states.So if I would like to make a TM that accept the Caesar cipher I suppose that the information that would be on the tape, for example, the message hello, that I want to convert to a cipher text by a shift of n=3 in each character so I will get the word khoor.Because I need to put that message on a TM tape I guess that I can convert it into a binary string, would that be necessary or can I work with original characters?For example if my TM tape look like this (I am supposing that h is 0011 and that k is 1010 for example):|0|0|1|1|e|e|e|e|where e is the empty character and the header is in the leftmost position pointing to 0, so if I want to convert this h into k I can read one by one each binary digit (from left to right), converting into its corresponding binary digit to the converted letter and writing it in some beginning position at the right. Would that be ok? So I will have something like:|e|0|1|1|e|1|e|e|After the first iteration, I have read the leftmost digit, 0, changed into 1 and then copy it after the empty position. I can do the same with all the remaining digits.Would that approach be good enough, in this case, to simulate the Caesar cipher in a TM, and also if I want to decipher the converted text can I do a similar process?Bottomline, maybe somebody could show a model for a Caesar cipher using a TM?Thanks for your help. | how to make a Turing machine of a cipher? | turing machines | null |
_webapps.50250 | As of today, I find that Google has changed its interface for filtering searched results to be from a certain language (such as Chinese). I can't find a way to do that. Can you please help? | How to search results from certain language in Google? | google search;localization | Open the settings menu by clicking the Gear icon (upper right). Choose Languages.Beneath the setting for the Google products language interface is a heading for Currently showing search results in: with your current language and an Edit link.Click the Edit link. You should now see a long list of languages. Check the checkboxes against the languages you want to see results from, uncheck those you don't. |
_codereview.122699 | I came up with an extension method to find a Cartesian product of multiple IEnumerable sets. I was able to achieve lazy enumeration via yield return, but I didn't think of a way to do it non-recursively. The result ended up being a recursive lazy enumeration iterator method, the first of its kind! At least as far as I've ever written.The idea of the problem came from a Stack Overflow question where a guy had many sets of characters, and wanted to generate a combination of all of them. Now I'm just interested because it's a fun problem!I'd appreciate any kind of review, although here's two specific things I'm most interested in:Can this algorithm can be de-recursed? If so - should it be, and how?Is there some way it could be generalized even more, beyond what I've done?public static class MultiCartesianExtension{ public static IEnumerable<TInput[]> MultiCartesian<TInput>(this IEnumerable<IEnumerable<TInput>> input) { return input.MultiCartesian(x => x); } public static IEnumerable<TOutput> MultiCartesian<TInput, TOutput>(this IEnumerable<IEnumerable<TInput>> input, Func<TInput[], TOutput> selector) { // Materializing here to avoid multiple enumerations. var inputList = input.ToList(); var buffer = new TInput[inputList.Count]; var results = MultiCartesianInner(inputList, buffer, 0); var transformed = results.Select(selector); return transformed; } private static IEnumerable<TInput[]> MultiCartesianInner<TInput>(IList<IEnumerable<TInput>> input, TInput[] buffer, int depth) { foreach (var current in input[depth]) { buffer[depth] = current; if (depth == buffer.Length - 1) { // This is to ensure usage safety - the original buffer // needs to remain unmodified to ensure a correct sequence. var bufferCopy = (TInput[])buffer.Clone(); yield return bufferCopy; } else { // Funky recursion here foreach (var a in MultiCartesianInner(input, buffer, depth + 1)) { yield return a; } } } }}Usage:var input = new string[]{ AB, 123, @#,};foreach (var result in input.MultiCartesian(x => new string(x))){ Console.WriteLine(result);}// Results:// A1@// A1#// A2@// A2#// A3@// A3#// B1@// B1#// B2@// B2#// B3@// B3# | Finding a Cartesian product of multiple lists | c#;algorithm;recursion;iterator;lazy | null |
_webapps.57152 | When I first open Gmail and my inbox loads there is a long blue line to the left of the top email. This disappears after I have opened an email and gone back to the Inbox. Has anyone heard of this issue or know a solution? | Gmail blue bar issue | gmail | null |
_webmaster.19525 | I am using Opencart 1.5.1 but have a theme made for 1.4.9.The following template code won't work with 1.5.1:<?php foreach ($modules as $module) { ?> <?php echo $module; ?><?php } ?>Undefined variable: modules. Invalid argument supplied for foreach().What do I replace it with to work in 1.5.1? | OpenCart template $module code | php;theme;opencart | Is modules defined? Do you know if you have modules set to show where that code is in the template?You can do this:<?php if($modules){ foreach ($modules as $module) { echo $module; } }?>This way if $modules is not set to anything, it ignores the foreach loop. |
_softwareengineering.329812 | I have found several documents about statement and decision/branch coverage in testing, but these terms aren't clear for me.There are two types of this problems, that you can see below.Code: if(a || b)) { test1 = true; } else { if(c) { test2 = true } }}Text:Consider the following: Pick up and read the newspaper Look at what is on television If there is a program that you are interested in watching then switch the television on and watch the program Otherwise Continue reading the newspaper If there is a crossword in the newspaper then try and complete the crosswordCould you please best practices, how to found out sc and dc values in an easy way? I can't some exact methodology behind these values. | Test coverage measurements | testing;methodology;test coverage | Test coverage indicates if all code paths are being covered.So, in your example above you have 3 paths or outcomes:test1 is set to truetest2 is set to trueNeither test1 and test2 are set to trueSo, you only need 3 tests to cover the code paths/outcomes.But we have 3 data points, a,b,c. Let's say these are Boolean values so we would need 2 to the 3rd power or 8 tests to test all possible scenarios.So, if you wrote 1 test you would cover 33% of the code and 12.5% percent of all possibilities.For complex programs covering all possibilities is not very feasible from a time and effort standpoint so there are tools to measure code coverage (how much code are your tests are covering). But one should strive for good code coverage so that all system behavior is tested. Covering all possibilities is usually not feasible because of combinational explosion. |
_cs.14416 | If the running time of an algorithm scales linearly with the size of its input, we say it has $O(N)$ complexity, where we understand N to represent input size.If the running time does not vary with input size, we say it's $O(1)$, which is essentially saying it varies proportionally to 1; i.e., doesn't vary at all (because 1 is constant).Of course, 1 is not the only constant. Any number could have been used there, right? (Incidentally, I think this is related to the common mistake many CS students make, thinking $O(2N)$ is any different from $O(N)$.)It seems to me that 1 was a sensible choice. Still, I'm curious if there is more to the etymology therewhy not $O(0)$, for example, or $O(C)$ where $C$ stands for constant? Is there a story there, or was it just an arbitrary choice that has never really been questioned? | Why is it O(1) (and not, say, O(2))? | terminology;asymptotics;landau notation | null |
_softwareengineering.163981 | I want to be able to call javac <class file name>, and then automatically run java on the compiled .class file.I thought initially to use a x86 disassembler to hack it (javac.exe) but bumped that idea; I then found the open source code for JDK, and concluded that maybe a batch file would be easier. How can I do this? | Have javac call automatically run java | java;interpreters;compiling | null |
_unix.148060 | I have Linux mint installed on my system as primary partition.I want to install windows 8 along side with it (Dual boot).But when I try to install windows 8 installer says (windows can only be install Primary partition).I have only 1 primary partition in which Linux is running, other are extended or logical ones.I want to use my last Partition (Label : Apps) for installing Windows.Can I convert a logical partition to primary or any other better suggestion? | Windows installer complains that it can only be installed on a primary partition | linux mint;partition;windows;system installation | null |
_unix.263265 | Is there a way I could eliminate the last four characters with regex in the below one line script as I convert .wav files into .mp3 files. As of right now my single line script produces files ending in .wav.mp3for i in *.wav; do avconv -i $i $i.mp3;done Produces the below output Sanctify, Separate, & Success Success.wav.mp3 There four types of love.wav.mp3 Theres too much love to let you fail.wav.mp3 | regex to remove last four characters | shell script;scripting;regular expression;for | You don't want a regex, you want to use Bash's parameter expansion to remove the file extension in transit:for i in *.wav; do avconv -i $i ${i%.*}.mp3; doneHere, ${i%.*} is expanded as the pattern at the end of the parameter, as defined by everything (*) after the . deleting the shortest match, ie., .wav.You could also do a literal substitution with ${i/.wav/.mp3}. |
_codereview.135167 | I'm creating a simple android app for pre-highschool students which teaches the very basics of addition or multiplication of integers or decimals. The part of the program in this question is aimed at allowing them to practice without the need of a teacher giving them exercises and checking their results. Note: This is the first time I m using unit tests so I'm not experienced at unit-testing at all.The following are of great interest to me: Unit tests: What should I improve? I don't aim for 100% code coverage since thatfeels more of a fixation on following blindly a rule without theactual need for it (but of course I might be wrong).Since my methods contain random.random() numbers I was thinking of creating tests that test a method millions or billions of times (e.g. assertIsInstance(_int_term(), int) inside a for _ in range(10**8) loop). This would very strongly indicate (but not with absolute certainty) that the methods work correctly. Should I create such tests?Methods with optional parameters, e.g. Terms._int_term(max_val): The parameters are made optional only because I wanted to be able to test the method easily (that is, call it without the need to instantiate Terms() class. If I were not using unit tests, I would simply make it a non static method, and would remove the parameter completely. Is this a bad practice? Docstrings: Are more docstrings needed? Or do good method names suffice? The reason I didn't create dosctings for everything is that they could go stale in case I change code without also updating all the related docstrings. Of course any other comments unrelated to the above 2 points are also very welcome.Directory treeproject_dirmain.pyteststest_maintest_questionandanswer.pytest_terms.pyCodeMain module: Used for the creation of questions for the user,along with the expected answer (that is, the result of the operation)Some examples of questions and their answers:+2-4 , -2(-2)(+7), -14-1.60-2.04, -3.64The program should be aimed specifically at teachingthe very basics of addition or multiplication of integers or decimals,in a scaling difficulty.Exercises that deviate from those specific concepts should be avoided.Examples of what should NOT be implemented:2-4, # Deviates (slightly) since it also teaches that 2 == +2-2(+7), # Deviates (same as example above)+2-4(-5), # Deviates since it combines addition and multiplicationimport decimalfrom random import randint, choice, randomclass Terms(object): MIN_TERMS_COUNT = 2 MAX_TERMS_COUNT = 3 TERMS_TYPES = {'int', 'float'} MAX_ABS_VALUE = 10 DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP = { 1: dict( terms_count=2, terms_type='int' ), 2: dict( terms_count=3, terms_type='int' ), 3: dict( terms_count=2, terms_type='float' ) } TOTAL_DIFFICULTY_LVLS = len(DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP) def __init__(self, difficulty_lvl): self.difficulty_lvl = difficulty_lvl self.terms_count = self.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP[self.difficulty_lvl]['terms_count'] self.terms_type = self.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP[self.difficulty_lvl]['terms_type'] @staticmethod def _int_term(max_val=MAX_ABS_VALUE): return randint(0, max_val) @staticmethod def _float_term(max_val=MAX_ABS_VALUE): return random() * max_val @staticmethod def final_term(term_without_sign): Creates a single term. :param term_without_sign: :return: (num) sign = choice(['-', '+']) if sign == '-': final_term = -1 * term_without_sign else: final_term = term_without_sign return final_term def all_terms(self): lst = [] if self.terms_type == 'int': func = self._int_term elif self.terms_type == 'float': func = self._float_term else: raise NotImplemented('{}'.format(self.terms_type)) for _ in range(self.terms_count): term_without_sign = func() final_term = self.final_term(term_without_sign=term_without_sign) lst.append(final_term) return lstclass QuestionAndAnswer(object): Based on difficulty and operation type, creates terms (either float or ints) which are then rounded to allow specific number of decimals. OPERATIONS_TYPES = {'addition', 'multiplication'} def __init__(self, difficulty_lvl, op_type): self.terms_as_numbers = Terms(difficulty_lvl=difficulty_lvl).all_terms() self.op_type = op_type @staticmethod def round_single_term_2_decimals(given_float): num = decimal.Decimal(str(given_float)) return num.quantize(decimal.Decimal('.01'), decimal.ROUND_HALF_UP) def terms_to_rounded_numbers(self): Ensures all terms have an appropriate number of decimals. :return: (list) lst = [] for t in self.terms_as_numbers: if isinstance(t, int): lst.append(t) else: t = self.round_single_term_2_decimals(given_float=t) lst.append(t) return lst def terms_as_strings(self): lst = [] for t in self.terms_to_rounded_numbers(): if t > 0: lst.append('+{}'.format(t)) elif t == 0: random_sign = choice(['+', '-']) lst.append('{sign}{term}'.format(sign=random_sign, term=t)) else: lst.append(str(t)) return lst def operation_str(self): Creates the operation string presented to the user. :return: (str) terms_as_strings = self.terms_as_strings() if self.op_type == 'addition': op_str = ''.join(terms_as_strings) elif self.op_type == 'multiplication': op_str = '' for t in terms_as_strings: op_str += '({})'.format(t) else: raise NotImplemented('{}'.format(self.op_type)) return op_str def expected_answer(self): if self.op_type == 'addition': result = 0 for t in self.terms_to_rounded_numbers(): result += t elif self.op_type == 'multiplication': result = 1 for t in self.terms_to_rounded_numbers(): result *= t else: raise NotImplemented('{}'.format(self.op_type)) return resultif __name__ == '__main__': # VISUAL TESTS if 1: TOTAL_DIFFICULTY_LVLS = Terms.TOTAL_DIFFICULTY_LVLS # -------------------------------------------------- # all_terms() print('\n'+'-'*80) print('TERMS') def print_all_terms(difficulty_lvl): print('\nDifficulty {}'.format(difficulty_lvl)) # (terms' lists printed for each difficulty lvl) terms_lsts_count = 3 for _ in range(terms_lsts_count): print(Terms(difficulty_lvl=difficulty_lvl).all_terms()) # (tests all difficulties) for d in range(1, TOTAL_DIFFICULTY_LVLS + 1): print_all_terms(difficulty_lvl=d) # -------------------------------------------------- # operation_str() and answer print('\n'+'-'*80) print('OPERATION STRING') for d in range(1, TOTAL_DIFFICULTY_LVLS + 1): print('\nDifficulty: {}'.format(d)) for operation in QuestionAndAnswer.OPERATIONS_TYPES: for _ in range(3): inst = QuestionAndAnswer(difficulty_lvl=d, op_type=operation) question = inst.operation_str() answer = inst.expected_answer() msg = '{q} = {a}'.format(q=question, a=answer) print(msg)Test module test_terms.py: from unittest import TestCaseclass TestDifficultyMap(TestCase): def setUp(self): import main self.Term = main.Terms self.difficulty_dct = self.Term.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP self.terms_counts_found = {v['terms_count'] for v in self.difficulty_dct.values()} self.terms_types_found = {v['terms_type'] for v in self.difficulty_dct.values()} def test_min_terms_count_DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP(self): min_terms_count_allowed = self.Term.MIN_TERMS_COUNT min_terms_count_found = min(self.terms_counts_found) self.assertGreaterEqual( min_terms_count_found, min_terms_count_allowed ) def test_max_terms_count_DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP(self): max_terms_count_allowed = self.Term.MAX_TERMS_COUNT max_terms_count_found = max(self.terms_counts_found) self.assertGreaterEqual( max_terms_count_found, max_terms_count_allowed ) def test_terms_types_DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP(self): self.assertEquals( self.terms_types_found, self.Term.TERMS_TYPES )class TestIntAndFloatTerm(TestCase): def setUp(self): import main self.Term = main.Terms # _int_term def test__int_term(self): self.assertEqual( self.Term._int_term(max_val=0), 0 ) def test_is_int__int_term(self): self.assertIsInstance( self.Term._int_term(max_val=1), int ) # _float_term def test__float_term(self): max_val = 15 term_val = self.Term._float_term(max_val=max_val) self.assertTrue(0 <= term_val <= max_val) def test_is_float__float_term(self): self.assertIsInstance( self.Term._float_term(max_val=1), float )class TestAllTermsMethod(TestCase): def setUp(self): import main self.Term = main.Terms self.difficulties_available = self.Term.DIFFICULTY_TO_TERMS_COUNT_AND_OP_TYPE_MAP.keys() def test_len_above_min_all_terms(self): inst = self.Term(difficulty_lvl=1) min_terms_count_allowed = self.Term.MIN_TERMS_COUNT terms_lst = inst.all_terms() self.assertGreaterEqual(len(terms_lst), min_terms_count_allowed) def _contains_x_type_all_terms(self, x_type): found_type = False for lvl in self.difficulties_available: inst = self.Term(difficulty_lvl=lvl) terms = inst.all_terms() for t in terms: if type(t) is x_type: found_type = True self.assertTrue(found_type, msg='Did not find {}.'.format(x_type)) def test_contains_float_all_terms(self): self._contains_x_type_all_terms(x_type=float) def test_contains_int_all_terms(self): self._contains_x_type_all_terms(x_type=int)Test module test_questionandanswer.py: from unittest import TestCaseclass TestQuestion(TestCase): def setUp(self): from decimal import Decimal from main import QuestionAndAnswer self.positive_float_to_expected_2nd_decimal_rounded = { 0.0049: Decimal('0.00'), 0: Decimal('0'), 0.005: Decimal('0.01'), 2.255: Decimal('2.26'), 9.999: Decimal('10'), 0.004: Decimal('0'), } self.negative_float_to_expected_2nd_decimal_rounded = { -k: -v for k, v in self.positive_float_to_expected_2nd_decimal_rounded.items()} self.QuestionAndAnswer = QuestionAndAnswer def test_positive_round_single_term_2_decimals(self): for given_float, expected in self.positive_float_to_expected_2nd_decimal_rounded.items(): self.assertEqual(self.QuestionAndAnswer.round_single_term_2_decimals(given_float=given_float), expected) def test_negative_round_single_term_2_decimals(self): for given_float, expected in self.negative_float_to_expected_2nd_decimal_rounded.items(): self.assertEqual(self.QuestionAndAnswer.round_single_term_2_decimals(given_float=given_float), expected) | Multiplication or addition of decimals or integers for prehighschool; non deterministic testing | python;python 3.x;unit testing;quiz | null |
_unix.341876 | I'm thinking a way of storing large files on vfat file system. Obviously, the only way to store files larger than 4GiB is to split them. I'm aware that we can use split and cat commands for splitting and merging files. However, to use those commands, more space is needed for resulting file(s). If I'm understanding how file systems work correctly, no file is actually deleted and deallocated until they're closed. To use as little space as possible, it would take funky technique that involves truncate() and reversing the file content(reading and shrinking the original file as it goes).Is there any kernel module that creates a loop device out of multiple split files? Or a util command that does the exact same idea as mine?Or I'll start making one of them. Oh! Can I do that with mdadm? The linear level? | Using split files without merging them | linux;filesystems;large files | null |
_codereview.94011 | There was some online test where I was asked about finding all possible distinct palindromes of a string.Here I had to give the count of all possible distinct palindromes of a given string (continuous substring). Here, a single character word is considered a palindrome.Below is what I did. Can you please tell me if it is good OR there is a scope of improvement?public class Solution {/** Complete the function below.*/static int palindrome(String str) { String[] strArray = str.split(); List<String> list = Arrays.asList(strArray); list = list.subList(1, list.size()); //Set does'nt allow duplicates. //Sublist is required because split method gives an extra space. Set<String> palindromeSet = new HashSet<>(list); String palindromeStr = null; for(int i = 0;i<list.size();i++){ palindromeStr = list.get(i); for(int j = i+1;j<list.size();j++){ palindromeStr = palindromeStr+list.get(j); if(isPalindrome(palindromeStr)){ palindromeSet.add(palindromeStr); } } } return palindromeSet.size();}static boolean isPalindrome(String str){ char[] chars = str.toCharArray(); for(int i =0;i<(chars.length/2);i++){ if(chars[i] != chars[chars.length-1-i]){ return false; } } return true;}public static void main(String[] args) throws IOException{ System.out.println(palindrome(arewenotdrawnonwardtonewera));}} | Finding all possible distinct palindromes of a string | java;strings;palindrome | /** Complete the function below.*/Do you still need it?String[] strArray = str.split();List<String> list = Arrays.asList(strArray);list = list.subList(1, list.size());That's ugly. You could work with the original String or use str.toCharArray() if you really needed an array. But you don't.//Set does'nt allow duplicates.True, but rather well-known. And a typo.//Sublist is required because split method gives an extra space.True, but misplaced by a few lines. Full line comments belong before the block they describe.String palindromeStr = null;for(int i = 0;i<list.size();i++){ palindromeStr = list.get(i);This should befor(int i = 0; i < list.size(); i++){ String palindromeStr = list.get(i);Note the spacing. for(int j = i+1;j<list.size();j++){ palindromeStr = palindromeStr+list.get(j);This is a pretty slow way of creating what String palindromeStr = str.substring(i, j);could give you. By creating your string incrementally you gain nothing: Because of strings being immutable, their whole content gets copied on every step.This way the complexity is O(n**3) and could be reduced(*) to O(n**2) by simply defining a method working on a substring like static boolean isPalindrome(String str, int start, int end) ...You should improve both spacing (just press Ctrl-Shift-F in Eclipse) and naming, maybe as follows:str -> inputstrArray -> nothing, just inline itpalindromeSet -> palindromes as it's clearly a setpalindromeStr -> substring or candidate as it's not always a palindromeYour naming is not really bad, but you concentrate on the type too much and I can imagine to get lost in a bunch of names like intListSetArray and strDoubleMap without any clue what's the variable good for.I'd bet there's a faster algorithm, but I haven't figured it out yet.(*) I'm assuming that isPalindrome is O(1) on the average, which is true for normal strings, but not for e.g. aaaa....a. |
_webmaster.1271 | I know about captcha. However, often it is stated that captcha stops legitimate users due to the inconvenience. Are there other solution, that in particular look for pattern in the input similar to e-mail spamfilters, or for random sequences of letters? (In particular, a solution that works with drupal would be good). | What solutions to prevent spam of web forms are less intrusive for users? | spam blocker;drupal | Here are 3 ways I have seen to do this: One way - https://stackoverflow.com/questions/8472/practical-non-image-based-captcha-approaches.Another way - https://stackoverflow.com/questions/2475806/captcha-replacementMsft has even made a one with Ajax! http://www.asp.net/AJAX/AjaxControlToolkit/Samples/NoBot/NoBot.aspxIn general there are 3 ways to solve this:Make the user do something to prove they are human. CAPTCHA or anything like it where the user must do extra work.See how long it take the user to enter data. Computers are much faster at filling forms out.Obfuscate what inputs are being used for what in the HTML itself. All of these methods have shortcomings. CAPTCHA requires more work and eventually developers can find ways to solve the CAPTCHA programatically. Some have even resourted to paying cheap labor to manually overcome them. Waiting will work well until it becomes prevalent and then hackers will just make their programs wait until they submit. Finally, obfuscation except you have to tell the user what to enter so that will give some of it away. You can further obfuscate those fields by using Javascript to populate names later. It is all basically a cat and mouse game. I think CAPTCHA ends up being the most effective and the most annoying for the user though. |
_unix.347174 | I have the following script setup at the moment:#!/bin/bashwhile true; do echo Type in keyword & press enter... read KEYWORD HERE=$(grep -i $KEYWORD */*/webvirtualmx) echo $HERE ANSWER2=y;read -p Do you want to move to old? y or n? ANSWER2; if [ $ANSWER2 = y ] then mv -i -v $HERE /u1/OLD fi ANSWER=n;read -p Do you have more keywords? y or n? ANSWER; if [ $ANSWER = n ] then break fi doneNow the output of the echo part of the script looks like this:> u/umind/webvirtualmx:servingtruth.orgI basically need to cut the webvirtualmx:servingtruth.org portion off from the path, so that the part of the code that runs the mv command, moves the entire directory, not just the file.How would I go about telling to ignore the entire path, and only grab the directories path and apply it to the variable $HERE?I.Emv -i -v u/umind/ /u1/OLD/I have about a hundred directories like this, obviously all named differently but they all follow this pattern:letter/name/webvirtualmx:filenameanother example:l/laicc/webvirtualmx:si2tech.comso on and so forth. | Cut file name and grep search result from path | grep;variable;mv;cut | If $HERE holds a filename, then I think the simplest would be to do the following:mv -i -v `dirname $HERE` /u1/OLDIf you want some safety, then you could do:DIR=`dirname $HERE`if test -d $DIR; then mv -i -v $DIR /u1/OLDfi |
_softwareengineering.200110 | Say you have a list of vehicles - you have an observableArray of these ko.observable()s. You let your user add a new vehicle with the following: var emptyVehicle = { make: chevrolet, model: corvette};app.on('CLICKED_ADD_VEHICLE', function () { var vehicle = new vehicleViewModel(emptyVehicle); vehicle.hasWheels(true); innerModel.sets.push(set); });If they save the vehicle, you get a real vehicle from your dataservice, and then replace the blank one with this: app.on('CLICKED_SAVE', function (oldVehicle) { var newVehicle = new vehicleViewModel(dataservice.createVehicle(oldVehicle)); innerModel.vehicles.remove(oldVehicle); innerModel.vehicles.push(newVehicle); });I know I'm leaving some code out here, but this is more of a practices/approach question than a code question. Is this an acceptable approach to adding new items to a list? New up a temporary template, and throw it away in place of an actual item if the user saves? | Adding new objects to a clientside array - best practices? | javascript | It's acceptable, but it's not really preferred. What happens if someone changes the code latter on, and it fails to send oldVehicle? What happens if the CLICKED_SAVE event is triggered again? What happens if the AJAZ call itself just fails?Better practice is to design your app to begin with an empty innerModel.vehicles array, and then have addVehicle be a method of app that spools up a new vechicleViewModel and pushes it to the array. Generally, events should call methods, even if they aren't UI events, unless you have a good reason not to. |
_softwareengineering.333336 | I have seen many questions on whether to design data first or code first when designing a new application. I wonder if some have the same conclusions/ideas as me. I come from painting/digital design/UI background and naturally I went into Front-End. Currently I can code and build UI's quickly in HTML5,JS,jQuery and AngularJS. I have also touched on PHP and the popular stacks for it (LAMP, WAMP,XAMP etc.) and WordPress. I have also worked with Oracle SQL and TSQL on MS Server on a few different jobs.For the last year I have been working with C# and ASPX and then for the last 6 months MVC5,JSON APIs with SOAP.Recently I have also picked up AngularFire for Firebase. 9-5 I work for big corporations so the stack is usually .NET however outside of this I build sites for clients in open source usually and Front-end languages.From this we can see I have touched on many different languages (some not named) and web application/software design and building but I still struggle at times to know whether to design my data first or code first? In the MVC applications (2-5 applications) I have built and worked on, the database was already created so I am starting to get a little used to (and enjoy) following the data first approach and in VS generating my model automatically (+ the T4's) then designing the Controllers and finally either Views or back to Controllers or some API.With AngularFire showing us you CAN only code first and the database can be 100% automatically built for you (creation of the DB object and columns).From this I wonder if many more are in this almost 'limbo' mode because of many different design practices and if any can offer tips of how to not get too confused and possibly offer one way to follow for solid practices of software/application engineering/coding/design.Pros and cons:I do note though what I have seen so far is that AngularJS and Firebase offer application building at rapid pace as it's quick to define Controllers in JS and check data changes at real-Time in Firebase, this also allowed me to focus more on the features I want rather than looking constantly looking for library's, add JSON and the application starts to become powerful and still executes fast.With .NET (MVC5, C#,EF5, JSON) it's quicker than a LAMP stack for CRUD operations as there is lot's available right out of the box as well as complex data pull and pushes with JSON, so still favour this over ASPX thus producing powerful web apps quite quickly too, although when the project grows execution can be slow locally and once deployed. | Data first or code first? | design;programming practices;web applications;database design | null |
_unix.184562 | I would like to know how I can use start up scripts in .xsession in order to change the look of my Desktop, I assumed .xsession was in my home directory so I performed at my home directory: ls -a to list all the hidden files, that start with a dot, but there was no .xsession file. So, I searched the whole file system beginning from the root with: ls -Ra / | grep .xsessionbut unfortunately it did not find this .xsession file either. | Where is the .xsession file in linux mint? | linux mint;xfce;desktop;desktop environment | null |
_codereview.171881 | Is this a proper Count sort implementation?Code and style improvements? Followup to this.Some of the array index is different as the WIKI is 1 based and these arrays are zero based.public static void CountSort(int[] arr){ int maxRange = 100000; int max = int.MinValue; int min = int.MaxValue; foreach (int i in arr) { max = Math.Max(max, i); min = Math.Min(min, i); } if(max - min > maxRange) { throw new ArgumentOutOfRangeException($Maximum range is {maxRange.ToString(N0)}); } for (int i = 0; i < arr.Length; i++) { arr[i] -= min; } int n = arr.Length; // The output character array that will have sorted arr int[] output = new int[n]; // Create a count array to store count of inidividul // characters and initialize count array as 0 int[] count = new int[max - min + 1]; // store count of each character foreach (int i in arr) count[i]++; // Change count[i] so that count[i] now contains actual // position of this character in output array for (int i = 1; i < count.Length; ++i) count[i] += count[i - 1]; // Build the output character array for (int i = 0; i < n; ++i) { output[count[arr[i]] - 1] = arr[i]; count[arr[i]]--; } // Copy the output array to arr, so that arr now // contains sorted characters for (int i = 0; i < n; ++i) { arr[i] = output[i] + min; }}public static void CountSortTest(){ List<int[]> la = new List<int[]>() { new int[] { } , new int[] {0, 0, 0 ,0 } , new int[] {5, 5, 5 ,5 } , new int[] { -20, -29, 90, 90, 71, 82, 93, 75, 81, 0, 12, 54, 36, 13, 102, 99, 34, 103, 78, 196, 52, 5, 215 } , new int[] { 100000, -10000, 0 } }; rand = new Random(); int[] at = new int[100000]; for(int i = 0; i < 100000; i++) { at[i] = rand.Next(201) - 200; } la.Add(at); foreach(int[] ar in la) { int[] aNet = new int[ar.Length]; Array.Copy(ar, aNet, ar.Length); Array.Sort(aNet); try { CountSort(ar); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (!ar.SequenceEqual(aNet)) { Debug.WriteLine(fail); } } } | Count sort implementation again | c#;.net;sorting | null |
_codereview.52560 | I've been experimenting with the Twitter Streaming API and would like some critical feedback. Specifically code correctness, code smells, overall structure, and my usage of collections and queues.The application leverages the Twitter Streaming API to identify the top trending hashtags for the supplied hashtag, or string.Sample invocation:java -jar ./target/lotus-1.0-SNAPSHOT-jar-with-dependencies.jar appleTop 10 Hashtags{#Apple=223, #iTunes=182, #iPhone=160, #Music=62, #Mac=59, #apple=43, #Apps=38, #Movies=25, #iTunesU=21, #Video=19}.Total Tweets Processed: 1935AbstractClient.javapackage com.gmail.lifeofreilly.lotus;/** * An Abstract client for retrieving messages that contain hashtags. Can be extended for target social network. */public abstract class AbstractClient implements Runnable { private final String trackedTerm; private final MessageData messageData; public AbstractClient(final String trackedTerm, final MessageData messageData) { this.trackedTerm = trackedTerm; this.messageData = messageData; } public MessageData getMessageData() { return messageData; } public String getTrackedTerm() { return trackedTerm; } @Override public String toString() { return AbstractClient{ + trackedTerm=' + trackedTerm + '\'' + , class= + this.getClass() + '}'; }}MessageData.javapackage com.gmail.lifeofreilly.lotus;import org.apache.log4j.Logger;import com.google.common.collect.Multiset;import com.google.common.collect.Multisets;import com.google.common.collect.TreeMultiset;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;/** * A blocking message queue and the hashtags extracted. */public class MessageData { private final static Logger log = Logger.getLogger(MessageData.class); private final Multiset<String> hashTags = TreeMultiset.create(); private final BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>(); private volatile long messageCount; /** * Add a message to the queue to be processed. * * @param message the message. */ public void addMessage(final String message) { messageQueue.add(message); messageCount++; log.debug(Current Queue size: + messageQueue.size()); } /** * Get the total number of messages submitted for processing. * * @return the number of messages. */ public long getMessageCount() { return messageCount; } /** * Removes and returns the head message in the queue, waiting if necessary until an element becomes available. * * @return the message. */ public String takeMessageFromQueue() { String message = ; try { message = messageQueue.take(); } catch (InterruptedException ex) { log.error(InterruptedException thrown: + ex); Thread.currentThread().interrupt(); } return message; } /** * Adds a hashtag to the collection. * * @param hashtag the hashtag. */ public void addHashTag(final String hashtag) { hashTags.add(hashtag); } /** * Prints the top ten hashtags to standard out */ public void printTopTenHashTags() { System.out.println(Top 10 Hashtags + getTopHashtags(10) + . Total Tweets Processed: + getMessageCount()); } /** * Get the top hashtags. * * @return the top hashtags and occurrence of each. */ public Map<String, Integer> getTopHashtags(int maxNumberOfHashTags) { Set<String> sortedSet = Multisets.copyHighestCountFirst(hashTags).elementSet(); Iterator<String> iterator = sortedSet.iterator(); Map<String, Integer> topTerms = new LinkedHashMap<String, Integer>(); for (int i = 0; i < maxNumberOfHashTags; i++) { if (iterator.hasNext()) { String term = iterator.next(); topTerms.put(term, hashTags.count(term)); } else { break; } } return topTerms; }}MessageProcessor.javapackage com.gmail.lifeofreilly.lotus;import java.util.StringTokenizer;/** * Extracts hashtags from messages. */public class MessageProcessor implements Runnable { private final MessageData messageData; /** * Constructs a MessageProcessor. * * @param messageData the MessageData. */ public MessageProcessor(final MessageData messageData) { this.messageData = messageData; } @Override public void run() { while (true) { extractHashtagsFromMessage(messageData.takeMessageFromQueue()); } } private void extractHashtagsFromMessage(final String message) { String deliminator = \t\n\r\f,.:;?![]'; StringTokenizer tokenizer = new StringTokenizer(message, deliminator); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (token.startsWith(#)) { messageData.addHashTag(token); } } }}TwitterClient.javapackage com.gmail.lifeofreilly.lotus;import org.apache.log4j.Logger;import twitter4j.FilterQuery;import twitter4j.StallWarning;import twitter4j.Status;import twitter4j.StatusDeletionNotice;import twitter4j.StatusListener;import twitter4j.TwitterStream;import twitter4j.TwitterStreamFactory;/** * Utilizes the Twitter Streaming API to collect messages. */public class TwitterClient extends AbstractClient { private final static Logger log = Logger.getLogger(TwitterClient.class); /** * Constructs a Twitter Client using the supplied MessageData object and tracked term. * * @param trackedTerm the term to track on Twitter. * @param messageData the data structure for the Twitter data. */ public TwitterClient(final String trackedTerm, final MessageData messageData) { super(trackedTerm, messageData); } @Override public void run() { TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(new TwitterListener(this.getMessageData())); twitterStream.filter(getFilterQuery()); log.info(Start listening to the Twitter stream.); } private FilterQuery getFilterQuery() { FilterQuery filterQuery = new FilterQuery(); String keywords[] = {this.getTrackedTerm()}; filterQuery.track(keywords); return filterQuery; } private class TwitterListener implements StatusListener { private final MessageData messageData; public TwitterListener(MessageData messageData) { this.messageData = messageData; } @Override public void onStatus(final Status status) { log.debug(Received onStatus: + status.getText()); messageData.addMessage(status.getText()); } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { log.info(Received a status deletion notice id: + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { log.info(Received track limitation notice: + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { log.info(Received scrub_geo event userId: + userId + upToStatusId: + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { log.info(Received stall warning: + warning); } @Override public void onException(Exception ex) { log.error(Received Exception: , ex); } }}Lotus.javapackage com.gmail.lifeofreilly.lotus;import org.apache.log4j.Logger;import twitter4j.Twitter;import twitter4j.TwitterException;import twitter4j.TwitterFactory;import java.util.Timer;import java.util.TimerTask;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * Identifies the top trending hashtags on Twitter for the supplied hashtag, term, or string. */public class Lotus { private final static Logger log = Logger.getLogger(Lotus.class); private final MessageData messageData; private final TwitterClient twitterClient; private final ExecutorService pool = Executors.newFixedThreadPool(2); /** * Constructs a client using the supplied keyword. * * @param trackedTerm the term to track on Twitter. */ public Lotus(final String trackedTerm) { messageData = new MessageData(); twitterClient = new TwitterClient(trackedTerm, messageData); } /** * Identifies the top trending hashtags on Twitter for the supplied hashtag, term, or string. * Usage: Lotus [keyword] * * @param args required argument. Specifies the keyword or hashtag to track on Twitter. */ public static void main(String[] args) { if (args.length == 1 & validCredentialsSupplied()) { Lotus lotus = new Lotus(args[0]); lotus.startTrackingTerm(); lotus.startProcessingMessages(); lotus.outputTopTenEveryThirtySeconds(); } else { if (args.length != 1) { System.out.println(Invalid number of arguments. Usage: Lotus [keyword]); } System.exit(-1); } } private static boolean validCredentialsSupplied() { try { Twitter twitter = TwitterFactory.getSingleton(); twitter.verifyCredentials(); return true; } catch (TwitterException ex) { System.out.println(Please supply a valid twitter4j.properties file in your working directory. + ex.getMessage()); return false; } } private void startTrackingTerm() { log.info(Starting Twitter client: + twitterClient.toString() + .); pool.execute(twitterClient); } private void startProcessingMessages() { log.info(Starting message processor.); pool.execute(new MessageProcessor(messageData)); } private void outputTopTenEveryThirtySeconds() { Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { messageData.printTopTenHashTags(); } }, 0, 30000); }} | Twitter Streaming Client - Round#2 | java;queue;collections;twitter;guava | The following comment is a very bad sign:/** * A blocking message queue and the hashtags extracted. */public class MessageData {Right there in the JavaDoc you are telling the world that MessageData is filling two completely different roles. You should separate the two roles out - make it explicitly clear that the queue of work to be done, and the report of the work done thus far, are two different things.Another way of saying the same thing: your pipeline has two different stages in it. Stage one reads messages and writes hashtags. Stage two reads hashtags and writes updates to an in memory database. Create classes to manage each of those responsibilities.Currently the hashtags are stored in memory, but in a subsequent version I plan to move to mongoYeah - that right there is a big hint that you are going to want to be able to swap out different implementations of your hash tag store.You'll know that you have the right design when you can create a single-threaded unit test that is able to verify the flow of a message all the way through the processing.@Overridepublic void run() { while (true) { extractHashtagsFromMessage(messageData.takeMessageFromQueue()); }}public String takeMessageFromQueue() { String message = ; try { message = messageQueue.take(); } catch (InterruptedException ex) { log.error(InterruptedException thrown: + ex); Thread.currentThread().interrupt(); } return message;}These two functions show that you don't understand what the InterruptedException is for.The InterruptedException wasn't left in the method signature by mistake; it signals a condition that correctly written programs should be prepared to handle -- namely, that some other thread has discovered that the blocking process should be cancelled.The quick fix would be to simply handle the interrupted condition in the Runnable.public void run() { while (! Thread.interrupted()) { extractHashtagsFromMessage(messageData.takeMessageFromQueue()); }} But it's still a little bit weird that MessageData returns a fake message during cancellation. That would mean that MessageProcessor is consuming more messages than MessageData.getMessageCount() claims were put in the queue.There are two ways you might fix that. One would be to move the InterruptedException to the throws clause, and let the Runnable handle it. Another option would be to modify the signature of takeMessageFromQueue so that it accepts a Listener.public void takeMessageFromQueue(Listener listener) { try { String message = messageQueue.take(); listener.onMessage(message); } catch (InterruptedException ex) { log.error(InterruptedException thrown: + ex); Thread.currentThread().interrupt(); }}This approach has the additional advantage that it allows you to experiment with other strategies for handling a backlog of messages; you could drain the entire queue in one go, or process a batch of messages (which allows you to take advantage of other data structures that are optimized for that use case).public void run() { TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(new TwitterListener(this.getMessageData())); twitterStream.filter(getFilterQuery()); log.info(Start listening to the Twitter stream.);}Ick - use Dependency Injection. It's ever so much friendlier to build the object graph explicitly, right where everyone is looking for it. If you must create a new graph each time run() is called, well that's what Factories are for....I'm alarmed that you seem to be dismissing the big chicken in the yard. Your message source is Twitter; you're drinking from the fire hose, but you don't seem to have given yourself a way to purge the data being shoved down your throat.private final Multiset<String> hashTags = TreeMultiset.create();How many different tags do you think you are going to see exactly once? They are useless for your report, but your memory is going to be flooded with them.You can probably get away with the heuristic that any tag that hasn't appeared in some reasonable time interval isn't going to be a top 10 tag. Simplest tool in the box would likely be a cache with a reasonable eviction policy built into it.public Map<String, Integer> getTopHashtags(int maxNumberOfHashTags) { Set<String> sortedSet = Multisets.copyHighestCountFirst(hashTags).elementSet(); Iterator<String> iterator = sortedSet.iterator(); Map<String, Integer> topTerms = new LinkedHashMap<String, Integer>(); for (int i = 0; i < maxNumberOfHashTags; i++) { if (iterator.hasNext()) { String term = iterator.next(); topTerms.put(term, hashTags.count(term)); } else { break; } } return topTerms;}Ow. Look carefully at this code -- you are going to sort every hash tag you have in memory, and then crop away only the top N? That's a lot of wear and tear on your CPU for a very small result.Now, if your requirement really is that you have to provide the top 1 billion hash tags on request, then you may be stuck. But if the real number you need is in the ballpark of 10 or 100, then you should keep a running count going in memory, and hand out the latest snapshot as needed (which can be trimmed down if the caller doesn't need as many items as you provide).A PriorityQueue gets you a lot of the way there - it's a data structure that can tell you the minimum element in it in O(1) time. A simple approach would be to scan all of your tags, and if the tag is larger than the current minimum, then remove the old minimum and offer the new tag -- the data structure knows how to order the new value correctly.Of course, scanning all of the tags each time somebody asks for the top 10 list may still be too expensive. You might prefer to pre-calculate the top tags. That's a fine idea, but you have to be a careful when the priority of an item already in the queue changes. You can manage that by removing and re-inserting each object in the queue that updates. The cost of that operation for queue size N is O(N), which shouldn't be a problem when N is 10 or 100. You can get O(log(N)) performance if you feel up to writing your own Heap |
_unix.297458 | So basically I have a JS app that is inside a directory in /var/lib/app/. To start this node app I execute a start script startapp.sh from inside the directory. Now I need it to start at boot time, so I created an upstart job in my Ubuntu server inside /etc/init and gave the absolute path of the startapp.sh, to get trigger at boot time.But whenever I try to execute any script that triggers startup.sh, it fails to start as it depends on an activator file to start, which is inside the /var/lib/app/ directory. I have exported the path in .bashrc, but still I am unable to execute the job from anywhere in Ubuntu server, except the /var/lib/app/ directory.How can I execute a shell script from anywhere on my server? | How to execute a shell script from anywhere on my server? | shell script;command line | null |
_unix.226009 | I am using the following commands after setting the color scheme to make my vim transparent:highlight Normal ctermbg=nonehighlight NonText ctermbg=nonehighlight SpecialKey ctermbg=noneHowever, when editing tex(latex) files (with the vimtex plugin installed) I still get a background for some tokens: As you can see for example the token 12pt or \date has a background. What else do I need to add to remove this background? | Not all Vim Text Transparent | vim;vimrc | null |
_unix.331165 | Hello, I am trying to recover unallocated space in my flash drive. I'm not quite sure how it got to this point. I have tried the following commands:resize2fssudo resize2fs /dev/sdc1resize2fs 1.42.13 (17-May-2015)The filesystem is already 1011875 (4k) blocks long. Nothing to do!badblocksudo resize2fs /dev/sdc1resize2fs 1.42.13 (17-May-2015)The filesystem is already 1011875 (4k) blocks long. Nothing to do!When I use Check in gparted, nothing happens.How can I recover the space on my flashdrive? Sorry for the poor formatting, still learning... | Unallocated space in empty flash drive | ubuntu;flash memory | null |
_codereview.124323 | I made a basic website to practice HTML and CSS that will display 3 fruits with their given scores in an Olympic podium sort of way.Have I used any bad practices and what I should do instead?What can I do to fully optimize and shorten my code?How readable is my code? How can I make it more readable?<html><head> <link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'> <style> .bronze { transform: scale(0.75); } .bronze span { background-color: #CD7F32; } .gold span { background-color: #FFD700; } .silver { transform: scale(0.75); } .silver span { background-color: #C0C0C0; } body { background-color: #AAFF00; } caption { color: #000000; font-family: 'Lato', sans-serif; font-size: 50px; } span { border: 1px solid; color: #000000; font-family: 'Lato', sans-serif; font-size: 25px; padding: 12.5px; position: relative; top: -25px; } table { border-collapse: collapse; margin: auto; text-align: center; } td { padding-bottom: 50px; padding-top: 50px; } </style></head><body> <table> <caption>Highest Fruit Score: <b>83</b></caption> <tr> <td class=silver><img src=http://i.imgur.com/LGuyqx6.png><br/><span>65</span></td> <td class=gold><img src=http://i.imgur.com/uBDRMVu.png><br/><span>83</span></td> <td class=bronze><img src=http://i.imgur.com/eOsWQe5.png><br/><span>34</span></td> </tr> </table></body></html> | Fruit score leaderboard | html;css | HTMLYour HTML should have a DOCTYPE declaration. Nowadays, the HTML 5 doctype (<!DOCTYPE html>) is considered standard practice.You should always declare a charset, and the charset should be UTF-8. The <title> element is required.In an <img> tag, the alt attribute is considered mandatory, and in this case there are very obviously appropriate descriptions to assign to each image.You are using a <table> to do the layout, for content which is not semantically tabular. This is considered vulgar in HTML: the document should represent the meaning, and the layout should be performed using CSS. (The user agent might not be a typical graphical browser; it might be a screen reader for the sight-impaired.) The semantically appropriate element to use should be an <ol> ordered list. The fruits should be listed in first, second, and third place in the document.CSSFor ease of maintenance, avoid repeating declarations. For example, you can set the font-family just once on an ancestor element. Also, you can write the transform: scale(0.75) declaration just once, using a .silver, .bronze selector.How can we change the display order using CSS? Using the CSS order property would be really nice, but it relies on CSS flex boxes, which is a newer feature.body { background-color: #AAFF00; font-family: 'Lato', sans-serif; text-align: center;}div.fruits { display: inline-block; width: auto;}div.fruits p { margin-top: 0; color: #000000; font-size: 50px;}div.fruits p span.score { font-weight: bold;}ol, li { /* CSS reset: make lists not work like lists */ list-style: none; margin: 0; padding: 0;}ol { display: flex;}li { display: inline-block;}li.silver { order: -1;}.silver, .bronze { transform: scale(0.75);}li img { display: block;}li span.score { position: relative; top: -25px; border: 1px solid black; padding: 12.5px; font-size: 25px;}li.gold .score { background-color: gold;}li.silver .score { background-color: silver;}li.bronze .score { background-color: #CD7F32;}<!DOCTYPE html><html><head> <meta charset=UTF-8> <title>Top three fruits</title> <link rel='stylesheet' type=text/css href='https://fonts.googleapis.com/css?family=Lato'></head><body> <div class=fruits> <p>Highest Fruit Score: <span class=score>83</span></p> <ol> <li class=gold><img alt=banana src=//i.imgur.com/uBDRMVu.png> <span class=score>83</span></li> <li class=silver><img alt=apple src=//i.imgur.com/LGuyqx6.png> <span class=score>65</span></li> <li class=bronze><img alt=raspberry src=//i.imgur.com/eOsWQe5.png> <span class=score>34</span></li> </ol> </div></body></html>For compatibility, we can resort to using floats to put the silver element on the left. A very unfortunate consequence of that hack is that the width of the list needs to be hard-coded to help position the floats properly.body { background-color: #AAFF00; font-family: 'Lato', sans-serif; text-align: center;}div.fruits { margin-left: auto; margin-right: auto; width: 750px; /* Unfortunately hard-coded width */}div.fruits p { margin-top: 0; text-align: center; color: #000000; font-size: 50px;}div.fruits p span.score { font-weight: bold;}ol, li { /* CSS reset: make lists not work like lists */ list-style: none; margin: 0; padding: 0;}li { display: inline-block; width: 250px;}.silver, .bronze { transform: scale(0.75);}/* Change the display order to silver-gold-bronze */li.silver { float: left;}li.bronze { float: right;}ol:after { clear: both;}li span.score { position: relative; top: -25px; border: 1px solid black; padding: 12.5px; font-size: 25px;}li.gold .score { background-color: gold;}li.silver .score { background-color: silver;}li.bronze .score { background-color: #CD7F32;}<!DOCTYPE html><html><head> <meta charset=UTF-8> <title>Top three fruits</title> <link rel='stylesheet' type=text/css href='https://fonts.googleapis.com/css?family=Lato'></head><body> <div class=fruits> <p>Highest Fruit Score: <span class=score>83</span></p> <ol> <li class=gold><img alt=banana src=//i.imgur.com/uBDRMVu.png> <span class=score>83</span></li> <li class=silver><img alt=apple src=//i.imgur.com/LGuyqx6.png> <span class=score>65</span></li> <li class=bronze><img alt=raspberry src=//i.imgur.com/eOsWQe5.png> <span class=score>34</span></li> </ol> </div></body></html> |
_unix.39904 | I installed catalyst, so I needed to downgrade to xorg-server-1.11 from xorg-server-1.12. Now I use the [xorg111] repo and I understood that because of the udev, which works for the new xorg-server I have to recompile it. I don't really know how to recompile it so it works with it.Q: How do I do the manual compilation?Here is the thread in Arch forum if this helps. | How to recompile my xorg-server in ArchLinux | xorg;arch linux;compiling | Solution A: use ARMFind and download proper packages here (also dependencies) , and use pacman -U XX.xz to rollbackhttp://arm.konnichi.com/search/index.php?a=32&q=xorg-server&core=1&extra=1&community=1Solution B: bulid from sourceClone this repository:git://pkgbuild.com/aur-mirror.gitAnd find the old version of package you need , and use makepkg to build the Arch package , and install them with pacman -U XX.xzGet ready for damaging your system ;-P |
_codereview.90697 | I'm implementing a lock-free, multiple consumer, multiple producer FIFO queue/pipe as an exercise in thinking about atomicity in operations.My main concern is correctness of operation, my second concern is good practices around atomics and general C++11. Performance is interesting but not important for this exercise.Without futher ado, here's the code:#include <atomic>#include <exception>// For dump#include <iostream>#include <string>/// <summary> A lock free queue implementation./// /// Design notes: Here be dragons. The queue is implemented as a single linked /// list with a head, divider and tail pointer. These are always ordered such /// that head -> divider -> tail and are always non-null. The divider's next/// pointer points to the first node with data or is null. In other words, this/// means that divider == tail -> empty container. Nodes between head and /// divider are empty and will be freed lazily. </summary>////// <remarks> * Thread Safety : Full./// * Exception Safety: Basic. </remarks>////// <tparam name=T> Generic type parameter. </tparam>template<typename T>class lockfree_queue{ struct link; using link_ptr = std::atomic < link* > ; struct link{ link() noexcept = default; link(const link&) = delete; link& operator = (const link&) = delete; link_ptr m_next{ nullptr }; }; struct node : link{ template<typename... Args> node(Args&&... args) : m_data(std::forward<Args>(args)...) {} T m_data; };public: using size_type = std::size_t; using value_type = T; /// <summary> Destructor, it's the users responsibility to make sure that /// no one uses the class after it's destruction and that no /// thread is in any of the function bodies. </summary> ~lockfree_queue(){ free_nodes(m_head.m_next.load()); } /// <summary> Tests if this container is empty. This operation only makes /// sense if there is only one thread reading/consuming the queue. /// </summary> /// <returns> True if the queue is empty, false otherwise. </returns> bool empty() const noexcept{ return m_divider.load() == m_tail.load(); } /// <summary> Gets the instantaneous number of elements in the queue. /// Mostly useful as a debug probe to monitor the queue size. /// </summary> /// <returns> The number of elements in the queue. </returns> size_type size() const noexcept{ return m_size; } /// <summary> Emplaces a new node on the queue. If the construction of the /// data throws, the queue is unmodified. </summary> /// <tparam name=Args> Type of the arguments. </tparam> /// <param name=args> Variable arguments providing the arguments to /// construct the data with.</param> template<typename... Args> void emplace(Args&&... args){ auto l_new_node = new node(std::forward<Args>(args)...); // m_tail->m_next can have two states: // 1) It's non-null, means an insertion is in progress but has not bee completed. // 2) It's null, means no insertion is in progress. // m_tail->m_next will only be written from this function. // This loop does a CAS with m_tail->m_next to see if it is null and if it is it // inserts the new node. At which point any concurrent push will retry until (3) // below completes. link* l_null = nullptr; while (!m_tail.load()->m_next.compare_exchange_weak(l_null, l_new_node)); m_tail = l_new_node; // 3) Commit/publish the new tail. m_size++; } void dump(){ auto n = &m_head; while (n != nullptr) { std::string special = ; if (n == m_divider.load()) special += D; if (n == m_tail.load()) special += T; std::cout << [( << special << ); if (n != &m_head) std::cout << \ << static_cast<node*>(n)->m_data << \; else std::cout << sentinel; std::cout << ( << n << )] -> ; n = n->m_next.load(); } std::cout << [null] << std::endl; } /// <summary> Consumes one item from the queue. The item is move assigned /// to result. If the assignment throws, the queue is will have /// dropped consumed item but is otherwise unmodified. </summary> /// <param name=result> [in,out] The result. </param> /// <returns> An auto. </returns> bool consume(T& result){ link* l_divider = nullptr; link* l_snack = nullptr; // Try to temporarily unlink the head if it is not already unlinked and // it's not the divider auto l_head = m_head.m_next.load(); if (l_head == nullptr || &m_head == m_divider.load() || !m_head.m_next.compare_exchange_strong(l_head, nullptr)){ l_head = nullptr; // We didn't get to unlink the head this time. } do{ // The divider's next pointer points to the next node with data. l_divider = m_divider.load(); l_snack = l_divider->m_next.load(); // divider is never null. if (nullptr == l_snack) return false; // empty // If the CAS below succeeds, then no one has moved the divider since // we loaded the new divider position (which is non-null) and we have // moved the divider to the next node without interruption. } while (!m_divider.compare_exchange_weak(l_divider, l_snack)); m_size--; try{ result = std::move(static_cast<node*>(l_snack)->m_data); cleanup_pop(l_head, l_divider); } catch (...){ cleanup_pop(l_head, l_divider); std::rethrow_exception(std::current_exception()); } return true; }private: void free_nodes(link* from, link* up_until = nullptr) noexcept { assert(from != &m_head); while (from != up_until){ auto next = from->m_next.load(); // All links but the head are nodes, necessary to destroy data. delete static_cast<node*>(from); from = next; } } void cleanup_pop(link* l_head, link* l_divider) noexcept { if (l_head){ // The head has been unlinked by us and we are the only ones // with a handle to the detached head. We can now safely free // all nodes from the detached head up until the divider. auto new_divider = l_divider->m_next.load(); free_nodes(l_head, new_divider); // Oh, and re-link the head m_head.m_next = new_divider; } } link m_head; link_ptr m_divider{ &m_head }; link_ptr m_tail{ &m_head }; std::atomic<size_type> m_size{ 0 };};int main(){ lockfree_queue<double> q; assert(true == q.empty()); assert(0 == q.size()); q.dump(); q.emplace(0); q.dump(); q.emplace(1); q.dump(); q.emplace(2); q.dump(); q.emplace(3); q.dump(); double ans; q.consume(ans); q.dump(); assert(ans == 0); q.consume(ans); q.dump(); assert(ans == 1); q.consume(ans); q.dump(); assert(ans == 2); q.consume(ans); q.dump(); assert(ans == 3); q.emplace(3.14); q.dump(); q.consume(ans); q.dump(); assert(ans == 3.14);}I'm also interested in if anyone has some ideas on good test cases for the correctness under concurrency. | Lock-free, multiple consumer, multiple producer queue | c++;c++11;queue;lock free | ABA problemI was able to break your queue (but it wasn't easy). I inserted some code to freeze one thread here in consume(): do{ // The divider's next pointer points to the next node with data. l_divider = m_divider.load(); l_snack = l_divider->m_next.load(); // divider is never null. if (nullptr == l_snack) return false; // empty // Special hack to freeze one thread at a dangerous spot. if (freeze) { freeze = 0; frozen = 1; while (frozen); } // If the CAS below succeeds, then no one has moved the divider since // we loaded the new divider position (which is non-null) and we have // moved the divider to the next node without interruption. } while (!m_divider.compare_exchange_weak(l_divider, l_snack));At this point, one thread was trying to move the divider from A to B like this:divider(A) -> B -> C -> D trying to swap A with B to end up like this:divider(B) -> C -> DSo the thread was frozen with l_divider being A and l_snack being B.Then I ran another thread and caused it to consume the whole queue (ABCD all freed). In that other thread, I used emplace() to put new nodes on the stack, and I carefully manipulated the allocator to force this situation:divider(A) -> C -> DWhen I say I manipulated the allocator, I mean I did an extra allocation to make sure that B was skipped. At that point, I set frozen = 0 to unfreeze the first thread. What happened was that it swapped A with B like this:divider(B) -> ?But of course B was no longer part of the queue. So after that, any future consumes were broken. I actually made B point at itself, so the consumes kept consuming B forever.This problem is known as the ABA problem in case you have not already learned about it. |
_cs.32931 | I don't understand how to work backwards to work out a truth table that has been filled out already (I don't know the logical operators). E.gP | Q | Output1 | 1 | 11 | 0 | 00 | 0 | 00 | 1 | 0I need to find the logical operators and connectives (and, or, not, implies etc.) that is equivalent to the output.Please guide me through the steps or teach me how to work out how to do this. Thanks. | Working out the connectives (And, Or, Not) in a Truth Table that has the outputs | algorithms;logic | null |
_unix.127757 | I'm not able to ls on a folder that I have just transferred from win7 to OSX via a FAT32 drive. I don't know how to search for an answer for this issue. I've attempted the following:sudo chmod u=rwx myfolder/sudo chmod a+rx myfolder/...to no avail.I have found that sudo ls seems to work. Why would this be? | `ls` fails for directory copied from Win and OSX | permissions;directory;ls | wow, i would have never thought this could happen, but turns out that there was a file in that directory named 'ls' without an extension, so it was overriding the sys default while i was in that directory and running ls via the cwd's supposed executable of it.a rare and embarrassing case, but true and not completely obvious while attempting to troubleshoot. i suppose this is one of the oldest issues in the book. |
_webapps.41041 | Is there a way to get Google Calendar to show my whole day? I don't want to scroll up and down. I want one click to see everything. Is there a way to lock the view to 7am to 9pm or something like that? | Google Calendar view whole day at once | google calendar | How about the Hide morning and night Lab?How often do you have something scheduled at 3am? What about 10pm? If the answer is almost never, you might want to try out the Hide morning and night lab in Google Calendar.With a simple drag of a slider you can fold all those empty hours into a single row to set the time range you want to hide. The folded rows still show all your events, just in more compact form.It may not completely remove any scrolling but, depending on how big your browser window is, should reduce it significantly. |
_softwareengineering.69892 | Almost every advanced programmer says that it's very useful to read the code of other professionals. Usually they advice open source. Do you read it or not? If you do, how often and what's the procedure of reading the code? Also, it's a bit difficult for newbies to deal with SVN - a bunches of files. What's the solution? | How do you read other's code? | open source;source code;svn | Do you read it or not? Yes.If you do, how often Daily. Constantly. I work with numerous open-source projects (mostly Python-related) and must read the source because it's the most accurate documentation.and what's the procedure of reading the code? Um. Open and Read.Also, it's a bit difficult for newbies to deal with SVN - a bunches of files. What's the solution?Open and Read. Then read more.It's not easy. Nothing makes it easy. There's no Royal Road to understanding. It takes work. |
_unix.171209 | I'm trying to read user input char by char, silently, as follows:while [ 1 ]; do read -s -N 1 ...doneWhile this loop works perfectly using VNC (xterm), it works only partially using putty (xterm) or a Linux terminal, and most of other text terminals.The problem is encountered when I become wild with the keyboard and striking multiple keys at the same time, and than some of the keys are echoed despite of the -s mode.I've also tried to redirect output and stty -echo. while the first did not make any difference, the latter would be somehow helpful, minimizing the echos to be less frequent, but not perfect.Any Ideas? | Reading char-by-char silently does not work | bash;terminal;terminal emulator;read | read -s disables the terminal echo only for the duration of that read command. So if you type something in between two read commands, the terminal driver will echo it back.You should disable echo and then call read in your loop without -s:if [ -t 0 ]; then saved=$(stty -g) stty -echofiwhile read -rN1; do ...doneif [ -t 0 ]; then stty $savedfi |
_softwareengineering.348171 | When designing a framework API is it better to have something that accepts Promises or have executor functions and have the framework build the promises when needed.The Promise API is defined by the syntax:new Promise( /* executor */ function(resolve, reject) { ... } );I have tried both and I am leaning towards having framework users implement a function(resolve, reject) to do their data retrievals. I am thinking that I cannot really reuse a promise once it has been resolved so if I wanted to do a reload of the data I would need to re-execute the executor function. | Framework accepts Promises or executor functions | javascript;api design;promises | null |
_codereview.60629 | Given a list of Players with score, I want to find the ones with the highest score. There can be multiple players with the same score. I'm doing it like this now:class Player { final String name; final int score; Player(String name, int score) { this.name = name; this.score = score; }}class PlayerComparatorByScore implements Comparator<Player> { @Override public int compare(Player o1, Player o2) { return -Integer.compare(o1.score, o2.score); }}class PlayerUtil { static Collection<Player> getHighestScoringPlayers(Collection<Player> players) { List<Player> sortedPlayers = new ArrayList<>(players); Collections.sort(sortedPlayers, new PlayerComparatorByScore()); Set<Player> highestScoringPlayers = new HashSet<>(); Iterator<Player> iterator = sortedPlayers.iterator(); Player highestScoringPlayer = iterator.next(); highestScoringPlayers.add(highestScoringPlayer); while (iterator.hasNext()) { Player player = iterator.next(); if (player.score == highestScoringPlayer.score) { highestScoringPlayers.add(player); } else { break; } } return highestScoringPlayers; }}public class PlayersSortedByScoreTest { @Test public void testSortingByScore() { Collection<Player> players = new HashSet<>(); players.add(new Player(Alice, 3)); players.add(new Player(Bob, 1)); players.add(new Player(Mike, 3)); Collection<Player> highestScoringPlayers = PlayerUtil.getHighestScoringPlayers(players); assertEquals(2, highestScoringPlayers.size()); assertEquals(3, highestScoringPlayers.iterator().next().score); }}So this is pretty awkward... Is there a better way? | Finding the Players with the highest score | java | This is a terrible approach. Sorting the list (an \$O(n \log(n)\$) step) and then iterating through it (an \$O(n)\$ operation) to collect the highest scoring players is simply inefficient.Instead, just iterate through the list in this way:List<Player> playersList = new ArrayList<>(players);Set<Player> highestScoringPlayers = new HashSet<>();int maxScore = Integer.MIN_VALUE;for (Player player : playersList) { maxScore = Math.max(maxScore, player.score)}for (Player player : playersList) { if (player.score == maxScore) { highestScoringPlayers.add(player); }}return highestScoringPlayers;This uses 2 loops and the minimal amount of space (just enough for the original list and the highest scorers) and so is \$O(n)\$, which is better than your \$O(n \log(n))\$ solution.If you would like to only use 1 loop, at the cost of some additional overhead here is the code:List<Player> playersList = new ArrayList<>(players);Set<Player> highestScoringPlayers = new HashSet<>();int maxScore = Integer.MIN_VALUE;for (Player player : playersList) { if (player.score >= maxScore) { if (player.score > maxScore) { maxScore = player.score; highestScoringPlayer.clear(); } highestScoringPlayer.add(player); }} |
_softwareengineering.242657 | Say Alice and Peter each have a 4GB USB flash memory stick. They meet and save on both sticks two files named alice_to_peter.key (2GB) and peter_to_alice.key (2GB) which contain randomly generated bits. They never meet again, but communicate electronically. Alice also maintains a variable called alice_pointer and Peter maintains variable called peter_pointer, both of which are initially set to zero.When Alice needs to send a message to Peter, she does (where n is the nth byte of the message):encrypted_message_to_peter[n] = message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]encrypted_payload_to_peter = alice_pointer + encrypted_message_to_peteralice_pointer += length(encrypted_message_to_peter)(and for maximum security, the used part of the key can be erased)Peter receives encrypted_payload_to_peter, reads alice_pointer stored at the beginning of message and does:message_to_peter[n] = encrypted_message_to_peter[n] XOR alice_to_peter.key[alice_pointer + n]And for maximum security, after reading of message also erase the used part of the key.- EDIT: In fact this step with this simple algorithm (without integrity check and authentication) decreases security, see Palo Ebermann post below.When Peter needs to send a message to Alice they do the reverse, this time with peter_to_alice.key and peter_pointer.With this trivial schema they can send each day for the next 50 years 2GB / (50 * 365) = ~115kB of encrypted data in both directions. If they need more data to send, they could use larger keys, for example with today's 2TB HDs (1TB keys) it would be possible to exchange 60MB/day for the next 50 years! That's a lot of data in practice; for example, using compression it's more than hour of high quality voice communication.It seems to me that there is no way for an attacker to read the encrypted messages without the keys, because even if they have an infinitely fast computer, with brute force they can get every possible message under the limit, but this is an astronomical number of messages and the attacker doesn't know which of them is the actual message.Am I right? Is this communication scheme really absolutely secure? And if it is secure, does it have its own name? XOR encryption is well-known, but I'm looking for the name of this concrete practical application using large keys on both sides? I am humbly expecting that this application has been invented someone before me. :-)Note: If it's absolutely secure then it's amazing, because with today's low cost large storage devices, it would be much cheaper to do secure communication than with expensive quantum cryptography, and this has equivalent security!EDIT:I think this will be more practical in the future as storage costs decrease. It can solve secure communication forever. Today you have no certainty if someone successfully attacks existing ciphers even a year later and makes its often expensive implementations insecure. In many cases before communication occurs, when both sides meet personally, that's the time to generate the keys. I think it's perfect for military communication, for example between submarines which can have HDs with large keys, and military central can have a HD for each submarine. It could also be practical in everyday life, for example to control your bank account, because when you create your account you meet with the bank etc. | Is this simple XOR encrypted communication absolutely secure? | communication;encryption | Yes, this is a One-time pad. If the key material is never re-used, it is theoretically secure.The downsides are that you would need one key per communicating pair of principals and you would need a secure way of exchanging the key material in advance of communicating. |
_webmaster.67863 | I've reviewed other questions and answers, but none fit my use case. Frankly, I'm not even sure if I'm asking the right question.Here's my scenario: I work for an organization that is in the process of rewriting their website.Let's assume we want to list a phonebook with some entries on a web page. There is a phonebook component, designed in JavaScript and uses Handlebars as templates. Using grunt it is all uglified, concatenated, and minified in one file called phonebook.js. The way it works is this:Content editor opens up the page where s/he wants to insert the phonebook. All that person has to do is open the CMS HTML editor and insert this:<div class=phonebook-component></div>And that's it.Now, what happens is that there's a global.js file that's loaded with every page. This script recognizes any class names that end with -component. When it recognizes the component, it makes a sync call to load the phonebook.js. The component is inserted, and it looks wonderful. The problem is probably obvious. When you look up at the source code, there where the source code should be is just hat div tag I mentioned. This is what crawlers see too. My question is: how can I make this crawlable? Is there any way? All my searches so far resulted in answers like oh, this is how you make your AJAX SPAs crawlable. | SEO for dynamically inserted content? | seo;javascript | null |
_unix.128674 | I need help figuring out how to input my data to bsqldb. I have been looking for a manual or some examples or tutorial but I cant find anything online beside its command line help.I am planning to pass my data to bsqldb from within a bash script using a variable using this command:/usr/bin/bsqldb -S servername -U username -P password <<< ${VARIABLE}$VARIABLE will contain data organized in this manner:USE databasenamecustomsqlfunction ('param1','param2','param3','param4','param5')customsqlfunction ('param1','param2','param3','param4','param5')customsqlfunction ('param1','param2','param3','param4','param5')customsqlfunction ('param1','param2','param3','param4','param5')The sql server im connecting to is a MSSQL 2008 and it seems to be running TDS v 7.1 (which seems weird... read everywere 2008 is suposed to be on 7.2 but the tds tools keep saying its downgrading the protocol to 7.1 when i connect... but that is another issue)Thanks for your help. | What is the format of the data that must be fed to the freetds tool bsqldb? | shell script;sql | I managed to test this and figured it out.Here is the proper way to structure the data contained in the variable you will send to bsqldb:MyVariable=select @@servername$'\n'select @@language$'\n'select @@versionAs you see each sql commands sent to bsqldb must be on a separate line. This is where \n comes in, it represents the newline or linefeed character. The rest select @@servername for example, are the actuall SQL commands.Here is what bsqldb will see when I feed it $MyVariable from above:select @@servernameselect @@languageselect @@versionUsually you need to send a GO command to execute a series or batch of commands but as the Freetds userguide points out in chapter 6 Use Freetds the last batch of commands sent to bsqldb doesn't need to be followed by GO to be executed, it will run automatically. I also confirmed that at the end of your cmd list, in contrary to tsql, the EXIT command is not required to close the connection to the server. It exits automatically once it reached the end of your cmd list.Now that we have our variable figured out, we can feed it to bsqldb from within a bash script using this syntax:/usr/bin/bsqldb -S servername -U username -P password <<< $MyVariableEnjoy. |
_unix.132426 | I have an XML files to read and load into database daily at night (cron)So i planed to do this in a batch.Is there any command line tool to :1. Create a postgres schema using an XSD file?2. Transform an XML file into SQL commands for postgres?Any other solution is welcome. | XML command line tool postgres | bash;cron;xml;database | You can generate SQL commands to import your file using xmlstarlet.Here is an example. |
_softwareengineering.298249 | Given that SAP modules are architected and managed by SAP itself.However, small changes are possible at the customer's end.How can an ABAPer on the client's side take the role of an architect at SAP that designs SAP modules? So what does an architect at the client's side have left to do? | Role of an architect in SAP ABAP or SAP BI projects | sap;abap | Given that SAP modules are architected and managed by SAP itself.This is only partially true. The large system design is done by SAP. However many organizations have custom implementations of some sort.There are often required changes, whether small or large, that fit business applications into SAP. Or custom requirements for the business applications which are caused by SAP.In an ideal world, you could easily just fit your applications that the business is developing (whether SAP transactions or a system feeding SAP). That process takes a fair bit of architecting.However, small changes are possible at the customer's end.You are (likely) kidding yourself if every customer implementation is identical. Unless someone is starting a business from nothing, where they can design their business around SAP's system.Someone needs to make sure that the SAP design is correct. Understanding how pieces fit together.How can an ABAPer on the client's side take the role of an architect at SAP that designs SAP modules? So what does an architect at the client's side have left to do?So, the key piece is understanding how everything fits together. An ABAPer might understand this - but might have a very limited scope of experience. A good architect will have enough experience to see how pieces fit together, so when decisions are required, they can properly evaluate and identify the right decisions - and make them.It is likely that an ABAPer on the client will not have this experience/broad system understanding. If they do, then that's great, but likely they will not.An architect should be doing design types of work - not implementation work. An ABAPer is responsible more for implementation. |
_unix.203965 | I seem to be unable to automount nfsv4 shares in FreeBSD 10.1.All of my mounting information is stored in an LDAP database and the shares are on a NFSv4 server.I've gotten the mapping right so that if I do automout -L (shown below) I get the correct mapping; however, I can't seem to see where I would pass in -o nfsv4. /home/user nfs:/user # indirect map referenced at +auto.home:1If I edit /etc/autofs/include to try and pass in an option there, autofs doesn't seem to understand what to do with that information.Any ideas on what else to try? | Passing automount options in FreeBSD | freebsd;nfs;autofs | null |
Subsets and Splits