id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_scicomp.10388
|
I downloaded the bundle adjustment data from this link:original data for bundle adjustmentwhich is the supporting data for a paper titled:Bundle Adjustment in the LargeI want to use the data for triangulation algorithm testing, which requires 3x4 pinhole camera matrices; however the pinhole cameras were all calibrated into 9 parameters:e.g.1.5741515942940262e-02 //first three represent the `R` rotation,-1.2790936163850642e-02-4.4008498081980789e-03-3.4093839577186584e-02// 4~6 are the `t' translation vector-1.0751387104921525e-011.1202240291236032e+003.9975152639358436e+02 // the 7th is focal length-3.1770643852803579e-07 // the last two are radial distortion parameters.5.8820490534594022e-13.though there is already a reference on how to recover the R from the first three numbers:Rodrigues's vector per the original authors:description here I still feel it is difficult for me to understand it, especially the how to recover the R from the first three numbers. Anyone has suggestions?Camera ModelWe use a pinhole camera model; the parameters we estimate for each camera area rotation R, a translation t, a focal length f and two radial distortion parameters k1 and k2. The formula for projecting a 3D point X into a camera R,t,f,k1,k2 is:P = R * X + t (conversion from world to camera coordinates)p = -P / P.z (perspective division)p' = f * r(p) * p (conversion to pixel coordinates)where P.z is the third (z) coordinate of P. In the last equation, r(p) is a function that computes a scaling factor to undo the radial distortion:r(p) = 1.0 + k1 * ||p||^2 + k2 * ||p||^4.This gives a projection in pixels, where the origin of the image is the center of the image, the positive x-axis points right, and the positive y-axis points up (in addition, in the camera coordinate system, the positive z-axis points backwards, so the camera is looking down the negative z-axis, as in OpenGL).Data FormatEach problem is provided as a bzip2 compressed text file in the following format.<num_cameras> <num_points> <num_observations><camera_index_1> <point_index_1> <x_1> <y_1>...<camera_index_num_observations> <point_index_num_observations> <x_num_observations> <y_num_observations><camera_1>...<camera_num_cameras><point_1>...<point_num_points>Where, there camera and point indices start from 0. Each camera is a set of 9 parameters - R,t,f,k1 and k2. The rotation R is specified as a Rodrigues' vector.
|
How to recover the 3x4 pinhole camera from 9 parameters
|
least squares;data sets;computer vision
|
To convert from Rodrigues vector to a rotation matrix (and back) please check the MATLAB code here:http://www.cs.ucla.edu/~soatto/vision/courses/268/rodrigues.mSo this gives you the rotation matrix.You use the translation parameters directly. Additionally, you might want to form the camera matrix. It would be a good idea to get a fully calibrated K (which involves the camera center). If you can't, just do as follows:The authors claim to have it as the image center, so will use it as our center. Again in MATLAB notation: K=[f, 0, w/2; 0, f, h/2; 0, 0, 1], where w and h are image width and height respectively. Then you can form P = K*[R | t] which you could directly use for projecting to image coordinates (if you ignore the distortion only). If you need to take into account the distortion, then do the computation as the authors describe.
|
_softwareengineering.229232
|
When Murray Gell-Mann was asked how Richard Feynman managed to solve so many hard problems Gell-Mann responded that Feynman had an algorithm:Write down the problem.Think real hard.Write down the solution.Gell-Mann was trying to explain that Feynman was a different kind of problem solver and there were no insights to be gained from studying his methods. I kinda feel the same way about managing complexity in medium/large software projects. The people that are good are just inherently good at it and somehow manage to layer and stack various abstractions to make the whole thing manageable without introducing any extraneous cruft.So is the Feynman algorithm the only way to manage accidental complexity or are there actual methods that software engineers can consistently apply to tame accidental complexity?
|
How to manage accidental complexity in software projects
|
design;project management;software;complexity
|
When you see a good move, look for a better one. —Emanuel Lasker, 27-year world chess championIn my experience, the biggest driver of accidental complexity is programmers sticking with the first draft, just because it happens to work. This is something we can learn from our English composition classes. They build in time to go through several drafts in their assignments, incorporating teacher feedback. Programming classes, for some reason, don't.There are books full of concrete and objective ways to recognize, articulate, and fix suboptimal code: Clean Code, Working Effectively with Legacy Code, and many others. Many programmers are familiar with these techniques, but don't always take the time to apply them. They are perfectly capable of reducing accidental complexity, they just haven't made it a habit to try.Part of the problem is we don't often see the intermediate complexity of other people's code, unless it has gone through peer review at an early stage. Clean code looks like it was easy to write, when in fact it usually involves several drafts. You write the best way that comes into your head at first, notice unnecessary complexities it introduces, then look for a better move and refactor to remove those complexities. Then you keep on looking for a better move until you are unable to find one.However, you don't put the code out for review until after all that churn, so externally it looks like it may as well have been a Feynman-like process. You have a tendency to think you can't do it all one chunk like that, so you don't bother trying, but the truth is the author of that beautifully simple code you just read usually can't write it all in one chunk like that either, or if they can, it's only because they have experience writing similar code many times before, and can now see the pattern without the intermediate stages. Either way, you can't avoid the drafts.
|
_softwareengineering.344165
|
I'm trying to provide a convention, or standard, for a parent controller to communicate with a directive in Angular. Basically the directive will have a settings object containing callbacks and initial data received from the controller, and an api object containing public functions.I've created a service called gabby but it doesn't do much, just a convenience. HTML <div ng-app=myApp ng-controller=appCtrl> <my-dir settings=myDirSettings api=myDirApi></my-dir> </div>Parent Controller angular.module('myApp').controller('appCtrl', function($scope) { $scope.myDirSettings = { onStart: function() { //start the logic }, defaultName: 'My App Name' }; $scope.someClick = function() { $scope.myDirApi.fetchData(); }; });DirectiveJust Angular angular.module('myApp').directive('myDir', function() { return { controller: 'myDirCtrl', scope: { settings: '<', api: '=' } }; });Or with the Gabby Service angular.module('myApp').directive('myDir', function(gabby) { return { controller: 'myDirCtrl', scope: gabby.scope() }; });Directive's ControllerJust Angular angular.module('myApp').controller('myDirCtrl', function($scope) { angular.extend($scope, { onStart: function() {}, onSubmit: function() {}, defaultName: 'John' }, $scope.settings); $scope.api = $scope.api || {}; $scope.api.clearValues = function() { //do magic things }; $scope.api.fetchData = function() { //do magic things }; $scope.api.getValues = function() { //do magic things }; $scope.onSomeKeyPress = function() { $scope.onStart(); };});Or with the Gabby Service angular.module('myApp').controller('myDirCtrl', function($scope, gabby) { gabby.for($scope) .settings({ //These are the default settings for the directive, //allowing the reader to easily understand what can //be passed to the directive onStart: function() {}, onSubmit: function() {}, defaultName: 'John' }) .api({ //These are the public functions of the directives clearValues: function() { //do magic things }, fetchData: function() { //do magic things }, getValues: function() { //do magic things } }); $scope.onSomeKeyPress = function() { $scope.onStart(); }; });More details:https://github.com/yellowblood/gabbyAm I trying to solve an already solved problem?Do you think this approach is readable and clear?
|
Communication between Angular directives and their parent controller
|
design patterns;angularjs
| null |
_webmaster.18466
|
Is there a way to +1 something via a URL, just like you would with Twitter or Facebook?e.g.With Twitter you have:http://twitter.com/home?status={url}With Facebook you have: http://www.facebook.com/sharer.php?u={url}&t={title}With Digg you have:http://digg.com/submit?phase=2&url={url}&title={title}
|
Google +1 something via a URL
|
google;google plus one
| null |
_unix.289740
|
How to get/know where is apt package's cache directory location?
|
How to get apt package cache directory location?
|
apt;deb
|
Simply with this command for cache directory location:apt-config shell Cache Dir::CacheAnd this command for cache/archive directory location:apt-config shell Cache Dir::Cache::Archives
|
_scicomp.1841
|
I have have multiple large matrices for which I need to find the largest absolute eigenvalue. I know that there is a large submatrix that does not vary. Is it possible to ignore/discard the submatrix?My question is also related to this question: What is the fastest way to calculate the largest eigenvalue of a general matrix?
|
Is it possible to ignore/discard part of a matrix when finding eigenvalues?
|
linear algebra;algorithms;eigensystem;sparse
|
If the part that is unchanged does not cover most of the matrix there is little you can do to save work. If the part that is unchanged can be permuted by a symmetric permutation to occupy the top left corner of yopur matrix, you can first similarity transform it to (tri)diagonal form. Extending the transform to the whole matrix leaves a matrix of the form $\pmatrix{ T & A\cr B & C}$ with (tri)diagonal $T$, whose eigenvalues are those of the original matrix. Its eigenvalues are relatively cheap to find by some subspace iteration steps followed by inverse iteration for extracting the absolutely largest eigenvalues once reasonable approximations are available.
|
_opensource.4285
|
I know that GPL requires linking application to be licensed under GPL. Some database lisense covers data usage. I'm sure there's something for API too. But from the comments here on OSSE I also know that there seems to be no consensus.Is there a general rule for these aspects?Should I check each license each time or can I assume something from the opensource fact? Is there something like TLDRLegal.com which covers specifically these points? Are they considered distinct? Is there a general rule which specifies what is what? Are they even a part of an application or rather a product of it?Some bonus questions to further describe my confusion:is web API considered linking over net?or is it only data usage?do I use API if I'm only sending a request but do not check for response?PS: I know that I should read licenses but this question is more about general coverage.
|
Linking vs API vs data
|
linked libraries;api;open data
| null |
_codereview.29945
|
How can I make my library more flexible towards programmers? Here is my library. It's a basic library that provides a simple interface to organise your game (with scenes, and engine/game connection). The only problem that I dislike about it, is the fact that you cannot create a custom 'game loop', you must let the GameLoop class deal with that for you. You can only instead, call to update/draw of the loop if you cannot use a while loop and manually clog the main thread (e.g. Ogre3d and it's call backs to update your game).I'm also curious on what I can improve upon this library. Does my tutorial make sense? Is my code clean?https://github.com/miguelishawt/pine
|
Improving the flexibility of my library/what can be improved?
|
c++;c++11;library;library design
| null |
_unix.71673
|
What exactly is the difference, operationally, between plugins and themes in oh-my-zsh? I.e. how would things break (if at all) if a plugin were instead put among the themes, or a theme among the plugins? Or is the distinction purely organizational?
|
difference between omz plugins and themes?
|
zsh;oh my zsh
|
Both the theme and the plugins are sourced in oh-my-zsh/oh-my-zsh.sh, so technically there should be no difference.But a theme should only be used to change the appearance and a plugin is there to add new functionality.With appearance I mean setting the values of $PS1, $PS2, $RPS1 and etc. There are some plugins which also set some appearances, like the vi-mode plugin which sets the right hand side prompt ($RPS1) when it is not already set.
|
_unix.251114
|
Situation:Two machines (A & B, with local drives dA & dB) connected via slow network.Drive dA has initial backup to dB, while locally attached on machine A.btrfs send RO-snapshot-1-dA | btrfs receive btrfsmount_dir_on_dBMachine A/dA sends incremental snapshots to B/dB over slow network.btrfs send -p RO-snapshot-1-dA RO-snapshot-2-dA | ssh B btrfs receive btrfsmount_dir_on_dBThis works great.But now I need to replace the drive dB on machine B with dC.On machine B:btrfs send RO-snapshot-on_dB | btrfs receive btrfsmount-on_dCbut now, from machine A:btrfs send -p RO-snaphot-2-dA RO-snapshot-3-dA | ssh B btrfs receive btrfsmount-on_dC...results in cannot find parent UUID.Is there a way for me to fix this? (I can change the btrfs partition UUID with btrfstune, but this is not capable of altering a subvolume UUID.)
|
Copy remote btrfs incremental snapshot to new drive w/ UUID
|
networking;backup;btrfs;uuid
| null |
_vi.9729
|
In vi it's very helpful to be able to place the cursor on a '(' or '{' or '[' character, press the '%' key, and move to the matching ')', '}', or ']'. But this does not work for me with angle brackets ( '<' and '>' ), even though page 130 of my Learning the vi Editor O'Reilly book (6th edition) says it should! I am using Centos 7.2 and my 'vi' editor is actually vim 7.4.160.Is this a version-specific thing? Or is there some switch that I can set/clear to make this work? It'd be handy for trying to make sense of HTML and Javascript.
|
Percent key ( % ) matching behavior for angle brackets ( < > )
|
key bindings;search;cursor movement
|
'matchpairs' controls what characters form pairs which % will work upon. You can add angle brackets by doing the following command as suggested by :h 'matchpairs'::set matchpairs+=<:>Since 'matchpairs' is a buffer local setting it would be best do this for the filetype you want. An example of for cpp filetype which can be added to your vimrc file:augroup AngleBrackets autocmd! autocmd FileType cpp set matchpairs+=<:>;augroup ENDHowever my preferred method of setting filetype specific options is to use the after-directory. Add the following to ~/.vim/after/ftplugin/cpp.vim:set matchpairs+=<:>Note: These examples use cpp as the filetype. You can use a different filetype to fit your needs.If you truly want to make this a global change no matter the filetype add the following to your vimrc file:setglobal matchpairs+=<:>For more help see::h 'matchpairs':h local-options:h 'filetype':h :autocmd:h after-directory:h setglobal
|
_cs.32497
|
The Y combinator has the type $(a \rightarrow a) \rightarrow a$. By the Curry-Howard Correspondence, because the type $(a \rightarrow a) \rightarrow a$ is inhabited, it must correspond to a true theorem. However $a \rightarrow a$ is always true, so it appears as if the Y combinator's type corresponds to the theorem $a$, which is not always true. How can this be?
|
Does the Y combinator contradict the Curry-Howard correspondence?
|
logic;recursion;type theory;curry howard
| null |
_unix.367151
|
I have the following output whenever I issue task:TASKRC override: /path/taskrcTASKDATA override: /path/.taskIt's because I put the config and data files in non-default external location specified by $TASKRC and $TASKDATA environment variables of Taskwarrior.How could I make task to be quiete and not warn me everytime.I'd like to find the command line switch to make it quiet for the issueing time (once) and the also config file option to make it permanent, if any.
|
How to override warning in Taskwarrior?
|
command line;configuration;utilities
| null |
_datascience.16150
|
I have a number of domain names that may or may not be related to a particular brand. For instance, if the brand is UPS, www.upssucks.com, www.upspackagesupplier.com, and www.ihateups.com might all be labeled as related because the website content is talking about UPS. www.ilovepups.com and www.pushupssuck.com aren't related to the website UPS. I want to use my trained dataset to create a prediction of whether a given domain is related to a brand using only the registered domain name as the input. It seems like some off-the-shelf classifiers should work, but I am very new to this type of ML project. What would be the first approach one would take to start making predictions? I am planning on doing this in Python with scikit learn if that makes any difference.
|
What is the general approach I can use to predict whether a domain is related to a brand using a supervised learning algorithm?
|
predictive modeling;scikit learn
| null |
_codereview.29275
|
Are there any ways I could improve speed and less code? The elevator that uses this script works fine. Could anything be better?print( Teknikk xPower 9700 PRE DEV V1 Intialised)-- Develoment sample, May have functions added or removed. --local Floor = script.Parent.Floorlocal Floors = script.Parent.Floorslocal FireLock = falselocal Alarm = falselocal Open = falselocal Closed = truelocal IsOpening = falselocal IsClosing = falselocal Moving = falselocal Busy = falselocal Locked = falselocal DoorSpeed = 0.00001local MotorStartSpeed = 0.13local MotorStopSpeed = 0.13local MotorSpeed = 12local MotorCurrentSpeed = 8local MoveDirection = Nonelocal CallDirection = Nonelocal FloorIndicatorOffset = 6local LevelOffset = 3local TargetFloor = 0local TotalFloors = 0local Car = script.Parent.Car.Controllocal duck = falselocal WaitCall = falselocal CallQuene = {}local CardLock = truelocal CardNumber = {0,1}local LockedFloors = {2,3,4,5,6,7,8}function ProcessCall(xFloor, xDest) if TargetFloor == 0 and xFloor ~= xDest then if xDest > xFloor then TargetFloor = xDest Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=119917350 Start(Up) end if xDest < xFloor then TargetFloor = xDest Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=119917359 Start(Down) end endendfunction Start(xDirection)Busy = trueif Open or IsOpening thenrepeat DoorClose(Floor.Value) wait(0.1) until Closed == true and IsOpening == falseendMoving = true-- Some code for just 1 floor up, not too fast -- if (Floors:FindFirstChild(Floor..TargetFloor).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 14 then MotorCurrentSpeed = 5 MotorStopSpeed = 0.05 LevelOffset = 5 else MotorCurrentSpeed = MotorSpeed MotorStopSpeed = 0.05 LevelOffset = 6.5 endCar.Platform.BodyPosition.P = 0Car.Platform.BodyPosition.D = 0Car.Platform.BodyVelocity.P = 5000 if xDirection == Up then MoveDirection = Up for i = 0, MotorCurrentSpeed, 1 do Car.Platform.BodyVelocity.velocity = Vector3.new(0,i,0) wait(MotorStartSpeed) end end if xDirection == Down then MoveDirection = Down for i = 0, MotorCurrentSpeed, 1 do Car.Platform.BodyVelocity.velocity = Vector3.new(0,-i,0) wait(MotorStartSpeed) end endendfunction Stop(TF)if TargetFloor ~= TF then return endBtn(TargetFloor,0)Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=0FPos = script.Parent.Floors:FindFirstChild(Floor..TF).FloorLevel.Position.YCar.Platform.BodyPosition.position = Vector3.new(Car.Platform.BodyPosition.position.X,FPos,Car.Platform.BodyPosition.position.Z)Car.Platform.BodyVelocity.P = 0Car.Platform.BodyPosition.P = 10000Car.Platform.BodyPosition.D = 6000Car.Platform.BodyVelocity.velocity = Vector3.new(0,0,0)repeat print((script.Parent.Floors:FindFirstChild(Floor..TF).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude) wait(0.1) until (script.Parent.Floors:FindFirstChild(Floor..TF).FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 0.4wait(1)TargetFloor = 0if Floor.Value == TotalFloors then MoveDirection = Downendif Floor.Value == 1 then MoveDirection = UpendDirInd(TF,MoveDirection)Moving = falsewait(1)DoorOpen(TF)print(Waiting 4 sec before delete and check)Quene(TF,Remove)Busy = falsewait(4)Quene(0,Check)endfunction DoorOpen(TF)if Closed and not IsOpening and TF ~= nil and not Moving thenIsOpening = trueif Car:FindFirstChild(DoorOpen) ~= nil then Car:FindFirstChild(DoorOpen).BrickColor = BrickColor.New(Lime green)endif MoveDirection == Up then Car.FloorIndicator.Ding.Pitch = 0.5 Car.FloorIndicator.Ding:Play()endif MoveDirection == Down then Car.FloorIndicator.Ding.Pitch = 0.5 Car.FloorIndicator.Ding:Play() wait(0.5) Car.FloorIndicator.Ding.Pitch = 0.3 Car.FloorIndicator.Ding:Play()endCarRight = script.Parent.Car.Control.DoorRightCarLeft = script.Parent.Car.Control.DoorLeftDoorRight = script.Parent.Floors:FindFirstChild(Floor..TF).DoorRightDoorLeft = script.Parent.Floors:FindFirstChild(Floor..TF).DoorLeftif DoorRight == nil and DoorLeft == nil then print(Cant open doors, No shaft doors) return endCarRight.Anchored = trueCarLeft.Anchored = truefor i=0, 51 doCarRight.CFrame = CarRight.CFrame * CFrame.new(0, 0, 0.05)CarLeft.CFrame = CarLeft.CFrame * CFrame.new(0, 0, -0.05)DoorRight.CFrame = DoorRight.CFrame * CFrame.new(0, 0, 0.05)DoorLeft.CFrame = DoorLeft.CFrame * CFrame.new(0, 0, -0.05)wait(DoorSpeed)endCarRight.Anchored = trueCarLeft.Anchored = trueClosed = falseOpen = trueif Car:FindFirstChild(DoorOpen) ~= nil then Car:FindFirstChild(DoorOpen).BrickColor = BrickColor.New(Institutional white)endIsOpening = falseendendfunction DoorClose(TF)if Open and not IsClosing and TF ~= nil and not Moving thenIsClosing = trueDirInd(TF,None)if Car:FindFirstChild(DoorClose) ~= nil thenCar:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Lime green)endCarRight = script.Parent.Car.Control.DoorRightCarLeft = script.Parent.Car.Control.DoorLeftDoorRight = script.Parent.Floors:FindFirstChild(Floor..TF).DoorRightDoorLeft = script.Parent.Floors:FindFirstChild(Floor..TF).DoorLeftif DoorRight == nil and DoorLeft == nil then print(Cant open doors, No shaft doors) return endCarRight.Anchored = trueCarLeft.Anchored = truefor i=0, 51 doCarRight.CFrame = CarRight.CFrame * CFrame.new(0, 0, -0.05)CarLeft.CFrame = CarLeft.CFrame * CFrame.new(0, 0, 0.05)DoorRight.CFrame = DoorRight.CFrame * CFrame.new(0, 0, -0.05)DoorLeft.CFrame = DoorLeft.CFrame * CFrame.new(0, 0, 0.05)wait(DoorSpeed)endCarRight.Anchored = falseCarLeft.Anchored = falseClosed = trueOpen = falseif Car:FindFirstChild(DoorClose) ~= nil thenCar:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Institutional white)endIsClosing = falseendendfunction Btn(xFloor,xMode) local xCar = Car.FloorBtn:FindFirstChild(F..xFloor) local xCall = Floors:FindFirstChild(Floor..xFloor):FindFirstChild(CallButton) local xDual = script.Parent.Parent:FindFirstChild(CallFloor) if xMode == 1 then if xCar ~= nil then xCar.BrickColor = BrickColor.new(Lime green) end if xCall ~= nil then xCall.BrickColor = BrickColor.new(Lime green) end if xDual ~= nil then if xDual:FindFirstChild(F..xFloor) ~= nil then xDual:FindFirstChild(F..xFloor).CallButton.BrickColor = BrickColor.new(Lime green) end end end if xMode == 0 then if xCar ~= nil then xCar.BrickColor = BrickColor.new(Institutional white) end if xCall ~= nil then xCall.BrickColor = BrickColor.new(Institutional white) end if xDual ~= nil then if xDual:FindFirstChild(F..xFloor) ~= nil then xDual:FindFirstChild(F..xFloor).CallButton.BrickColor = BrickColor.new(Institutional white) end end endendfunction DirInd(xFloor,xDir) local Dup = Floors:FindFirstChild(Floor..xFloor):FindFirstChild(DirIndUp) local Ddn = Floors:FindFirstChild(Floor..xFloor):FindFirstChild(DirIndDown) if xDir == Up then Dup.BrickColor = BrickColor.new(Bright green) end if xDir == Down then Ddn.BrickColor = BrickColor.new(Really red) end if xDir == None then Dup.BrickColor = BrickColor.new(Really black) Ddn.BrickColor = BrickColor.new(Really black) endendfunction Quene(xFloor,Mode,isCall) if Mode == Check then for i = 1, #CallQuene do if CallQuene[i] ~= nil then ProcessCall(Floor.Value, CallQuene[i]) end end end if Mode == Add then Btn(xFloor,1) local IgnoreCall = false if isCall ~= true then for i = 1, #LockedFloors do if LockedFloors[i] == xFloor then print(Call is in Lock list.) if CardLock then IgnoreCall = true end end end end for i = 1, #CallQuene do if CallQuene[i] == xFloor then print(Call exist, Not adding floor: ..CallQuene[i]) IgnoreCall = true end end if not IgnoreCall and xFloor ~= Floor.Value and not Locked or not IgnoreCall and xFloor ~= Floor.Value and xFloor == 1 then table.insert(CallQuene,xFloor) print(Floor added, Value: ..xFloor) Btn(xFloor,1) if not Busy then Quene(0,Check) end else if xFloor == Floor.Value and not Locked or IgnoreCall then wait(0.2) Btn(xFloor,0) end if Locked then wait(0.2) Btn(xFloor,0) end end end if Mode == Remove then for i = 1, #CallQuene do if CallQuene[i] == xFloor then print(Removed: ..CallQuene[i]) table.remove(CallQuene,i) end end Btn(xFloor,Off) endendfunction FireMode(Player) if not FireLock then Car.LockInd.BrickColor = BrickColor.new(Really red) Floors.Floor1:FindFirstChild(FireService).Key.Texture = http://www.roblox.com/asset/?id=121879581 FireLock = true Locked = true for i = 1, #CallQuene do print(Removed: ..CallQuene[i]) table.remove(CallQuene,i) end Car.DirectionalIndicator.Decal.Texture = http://www.roblox.com/asset/?id=0 if Floor.Value ~= 1 then DoorClose(Floor.Value) Moving = true Car.Platform.BodyVelocity.P = 2560 Car.Platform.BodyVelocity.velocity = Vector3.new(0,0,0) TargetFloor = 1 MoveDirection = Down wait(1) Car.Platform.BodyVelocity.velocity = Vector3.new(0,-6,0) end elseif FireLock then Car.LockInd.BrickColor = BrickColor.new(Really black) Floors.Floor1:FindFirstChild(FireService).Key.Texture = http://www.roblox.com/asset/?id=121879579 FireLock = false Locked = false endendif Car:FindFirstChild(DoorOpen) ~= nil then Car:FindFirstChild(DoorOpen).ClickDetector.MouseClick:connect(function() if not FireLock then DoorOpen(Floor.Value) end end)endif Car:FindFirstChild(DoorClose) ~= nil then Car:FindFirstChild(DoorClose).ClickDetector.MouseClick:connect(function() if not FireLock then local Close = false for i = 1, #CallQuene do if CallQuene[i] ~= nil then Close = true end end if Close then DoorClose(Floor.Value) Quene(0,Check) else Car:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Lime green) wait(0.2) Car:FindFirstChild(DoorClose).BrickColor = BrickColor.New(Institutional white) endendend)endCarCalls = Car.FloorBtn:GetChildren()x = script.Parent.Floors:GetChildren()for i = 1, #x do TotalFloors = TotalFloors + 1 if x[i]:FindFirstChild(CallButton) ~= nil then local fRep = string.gsub(x[i].Name, Floor, ) local fFloor = tonumber(fRep) x[i].CallButton.ClickDetector.MouseClick:connect(function() Quene(fFloor,Add,true) end) endend if game.CreatorId ~= 0 then if game.CreatorId ~= 6623575 then x = Instance.new(Hint,Workspace) x.Text = This place is using a Stolen Teknikk elevator. We apperiate the No support. script.Parent:Remove() end endfor i = 1, #CarCalls do local bRep = string.gsub(CarCalls[i].Name, F, ) local cFloor = tonumber(bRep) CarCalls[i].ClickDetector.MouseClick:connect(function() Quene(cFloor,Add,false) end)endscript.Parent.ScriptCall.Changed:connect(function () if script.Parent.ScriptCall.Value ~= 0 then Quene(script.Parent.ScriptCall.Value,Add,true) script.Parent.ScriptCall.Value = 0 endend)script.Parent.FireMode.Changed:connect(function () if script.Parent.FireMode.Value == true then FireMode() script.Parent.FireMode.Value = false endend)Car.Alarm.ClickDetector.MouseClick:connect(function () if not Alarm then Alarm = true for i=0,20 do Car.FloorIndicator.Alarm:Play() wait(0.1) end Alarm = false endend)if Car:FindFirstChild(ElevatorLock) ~= nil thenCar.ElevatorLock.ClickDetector.MouseClick:connect(function (Player) if Player ~= nil and Player.Name == Heisteknikk then if not Locked then Locked = true Car.ElevatorLock.BrickColor = BrickColor.new(Really red) else Locked = false Car.ElevatorLock.BrickColor = BrickColor.new(Dark stone grey) end endend)endif Car:FindFirstChild(RFID) ~= nil then Car:FindFirstChild(RFID).Touched:connect( function (Card) local Accepted = false if Card.Parent:FindFirstChild(CardNumber) ~= nil and CardLock then for id=1, #CardNumber do if Card.Parent.CardNumber.Value == CardNumber[id] then Car.RFID.BrickColor = BrickColor.new(Bright green) CardLock = false wait(5) CardLock = true Car.RFID.BrickColor = BrickColor.new(New Yeller) Accepted = true end wait() end if not Accepted then Car.RFID.BrickColor = BrickColor.new(Really red) wait(1) Car.RFID.BrickColor = BrickColor.new(New Yeller) end end end)endif Floors.Floor1:FindFirstChild(FireService) ~= nil then Floors.Floor1:FindFirstChild(FireService).ClickDetector.MouseClick:connect(function(Player) if Player ~= nil and Player.Name == Heisteknikk then FireMode() end end)endprint(Floor served: ..TotalFloors)while true dowait() for i = 1, #x do local xs = string.gsub(x[i].Name, Floor, ) local xx = tonumber(xs) if (x[i].FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < LevelOffset then if Floor.Value ~= xx then Floor.Value = xx Stop(xx) -- InCase f stops end end if duck == false then if (x[i].FloorLevel.Position - script.Parent.Car.Control.FloorLevel.Position).Magnitude < 0.5 then duck = true DirInd(1,Up) DoorOpen(1) end end endend
|
Elevator code for a game called ROBLOX
|
game;lua
| null |
_unix.103859
|
I know that I can define wanted package version in pacman like shown in its manual pacman -S bash>=3.2. But how do I know what versions are available? I also know that pacman is creating copy of mirrors upon syncing in .db files in /var/lib/pacman/sync/, but those files are not human-readable.And what if I want to install some version virtualbox for example, that I hope is in mirrors somewhere, that wouldn't require newer version of linux (set as IgnorePkg in pacman.conf) than I have installed (because of nvidia drivers)? How do I know what version that is and if it is available?
|
Arch Linux pacman specifying package version
|
arch linux;package management;pacman;version
|
You can't specify a version that easily, as a rolling release, pacman will only provide the latest. When you install something, that package is stored in your computer on the /var/cache/pacman/pkg/ dir, so if you want to downgrade one version or specify another, you have to use pacman -U and the name of the package on your cache. There are time machine repos out there where people just stores old packages, you can download the version you want and use pacman -U to install it. Be aware that you have to block the updates of that package if you don't want it to update, to see how, check the wiki in the pacman page or this https://wiki.archlinux.org/index.php/Downgrading_Packages#Q:_I_cannot_downgrade_a_package.2C_because_of_dependencies.
|
_opensource.4831
|
We are planning to use an Open Source GNU GPL License software for distribution also with the hardware we sell. We will make several changes to GP, software to make it work with our device and are ok to make derived source code open source. However below situation do exist for us in order to complete the whole package. I will be grateful is someone can answer below question for us and suggest alternatives.We do have other Open source component that we would need to integrate with original GPL software in order to achieve our goal. Is it permissible under GPLWe do have few proprietary DLLs provided by our vendors that we need to integrate but we do not have source code for them. Will this still satisfy GNU GPL requirement?We have a licensing module which derives the licensing logic for this application. This is a DLL but the source code is owned by us. Do this source code have to be made public?We have plans to submit derived software along with our medical devices for FDA approvals? Is GPL ok with it?We license our software as permanent as well trial version. Trial version expires after certain period. Can this cause any problem with GPL?The license is also controlled by a hardware dongle which is again provided by outside vendor. Is this ok with GNU GPL?Do we have to package source code with every media (CD, USB) we distribute? Will adding a statement for availability of source code on demand or from a public location acceptable for GNU GPL?We plan to add a few module such as apps for android and iOS. This will not be linked to derived software but will only use data and images collected by derived software from end users. Do we have to make source code of those apps also under GNU GPL?
|
GNU GPL Licensing
|
licensing;gpl;gnu
|
This is a lot of questions, and should perhaps be split into several different questions. But I'll answer what I can.We do have other Open source component that we would need to integrate with original GPL software in order to achieve our goal. Is it permissible under GPLIf the other licenses are GPL-compatible, yes. You will have to offer them under the terms of the GPL as well; the compatibility list contains licenses that the FSF believes can be met while also meeting the terms of the GPL.We do have few proprietary DLLs provided by our vendors that we need to integrate but we do not have source code for them. Will this still satisfy GNU GPL requirement?Not for the GPL, no; any derivative software, including the entire package that has your vendors' libraries, must be offered under the terms of the GPL.If you are not stuck with the choice of license (that is, you're just deciding this yourself, and aren't forced into it via modification of a GPLed project), then you may wish to use the LGPL, which has an exception for things that are linked in.We have a licensing module which derives the licensing logic for this application. This is a DLL but the source code is owned by us. Do this source code have to be made public?Under the GPL, yes. Under the LGPL, no.We have plans to submit derived software along with our medical devices for FDA approvals? Is GPL ok with it?Sure, there's no restriction in the license about whether you can submit it to a government agency. If you are providing a modified version, the FDA has the right to ask for the source code.We license our software as permanent as well trial version. Trial version expires after certain period. Can this cause any problem with GPL?The first of the four essential freedoms of free software is the right to run the software however and whenever you wish.The GPLv2 had a loophole that lead to tivoization, where the user could technically run modified versions of the software, but the hardware would refuse it. The GPLv3 is designed to prevent this. I'm not sure if section 2 prevents a license of the type you talk about; you should consult your legal counsel.Anyways, users are allowed to modify the source code, so they could dig in and remove the code that requires a valid license.The license is also controlled by a hardware dongle which is again provided by outside vendor. Is this ok with GNU GPL?Unsure, see previous point.Do we have to package source code with every media (CD, USB) we distribute? Will adding a statement for availability of source code on demand or from a public location acceptable for GNU GPL?Section 6 covers the full range of options. In summary, providing it in a public location or in response to specific requests is fine.We plan to add a few module such as apps for android and iOS. This will not be linked to derived software but will only use data and images collected by derived software from end users. Do we have to make source code of those apps also under GNU GPL?Files generated by the program are not considered part of it for licensing purposes (this would otherwise be a major issue in using gcc). Other programs that communicate with it via a network API also do not trigger the viral licensing clause.
|
_unix.31379
|
I have ubuntu server edition installed and I want to install firefox inside it , I don't want full ubuntu-desktop package just a minimal setup which would let me run firefox inside ubuntu-server 10.04 LTS
|
install firefox in ubuntu-server edition
|
ubuntu;package management;firefox
|
If you just want to install Firefox and run it remotely, install the firefox package. If you also want to run Firefox locally, you'll need a GUI environment: install the x-window-system package. If you also want to run Firefox locally comfortably, you'll need a window manager (any of the packages that provide the x-window-manager virtual package) or desktop environment (the Ubuntu default is Gnome, install at least gnome-core).I assume you only have a command line at your disposal; use the apt-get command to manipulate packages, or aptitude for a command line or text mode interactive program.apt-get install firefox x-window-system gnome-coreStrictly speaking, this won't be a minimal system, as it'll pull up a few packages that are recommended but not strictly necessary. Install all recommended packages unless you understand why you don't need them (in other words, if you need to ask, install them all).
|
_unix.102561
|
I installed the latest version of Apache2 / PHP / MYSQL on my PC.In the directory /src/www/htdocs I created a directory wordpress with all wordpress files.Then, when I tried to create the wp-config file through the web interface I get this error: Sorry, but I can't write the `wp-config.php' file.I tried this command to change the group of /src/www/htdocs/wordpresschown -R root:root /srv/www/htdocs/wordpressBut it was not working. After some research, I have seen lot of people saying change the group to www-data but I do not see www-data using this command:cut -d: -f1 /etc/groupAnyone know what I am doing wrong?
|
Linux Wordpress can't write wp-config file
|
permissions;wordpress
| null |
_webmaster.56404
|
For example http://www.google.com/search?client=safari&rls=en&q=tom+brady&ie=UTF-8&oe=UTF-8#q=tom+hanks&rls=enI have seen this on famous and non famous people and I was wondering how to get this done so my name and picture will appear on the sidebar of the Google search results.Do I need to make an account or send Google a request?
|
How to get my name on the side of the Google search results?
|
google;search;name
| null |
_unix.388329
|
I'm having trouble with sudo when I try to start an interactive session. It always changes the directory to the root's home directory. But I want to run commands in the directory I started the session from.How can I get sudo to start an interactive session in my current directory?
|
Start sudo interactive session in current directory?
|
sudo
| null |
_unix.331410
|
I am making a GFFS backup script for a school assignment but I've encountered some issues with it. It works like this:/etc/backup/backup.sh PERIOD NUMBER I have added the following lines in cron:# m h dom mon dow command# Backup for fileserver:#daily: 5 times/week0 23 * * 1-5 /etc/backup/backup.sh daily $(date -d -1 day +%w)#weekly: 5 times/month10 23 * * 7 /etc/backup/backup.sh weekly $((($(date +%-d)-1)/7+1))#monthly: 12 times/year20 23 1 * * /etc/backup/backup.sh monthly $(date -d -1 day +%m)#yearly: each year0 3 1 1 * /etc/backup/backup.sh yearly $(date -d -1 day +%Y)The calculations at the end is to know what previous backup to override. This works perfect when triggered manually but when triggered by cron it does something weird. i'm talking about the weekly backup entry. the calculation is supposed to give me the week number in the current month. i did 'grep CRON /var/log/syslog' and found this line:Dec 19 14:33:01 BE-SV-04 CRON[5445]: (root) CMD (/etc/backup/backup.sh weekly $((($(date +)It appears as if cron is not executing the calculation correctly. Any help?
|
Script working manually but not in cron - not calculating var?
|
linux;bash;debian;scripting;cron
|
I think you have to escape the %- signsso this:0 23 * * 1-5 /etc/backup/backup.sh daily $(date -d -1 day +\%w)... should work.I dont know which have to be escaped, it think + and %, please try out.*when I did it in cron I used the uglyer backtick-syntax for command execution and had to escapte them, too, like: *0 1 * * * something >> bla\`date \+\%Y_\%m_\%d\`.log
|
_webapps.44487
|
I have a sheet with employee time logs, as follows:Name Day1 Day2 Subtotal of 'OFF' days this periodJess PRESENT OFF 1Bob PRESENT PRESENT 0Name Day3 Day4 Subtotal of 'OFF' days this periodJess PRESENT PRESENT 0Bob OFF OFF 2I need to create an automatic total of the number of days off each employee has had. How could I do this? =COUNTIF(1:100,OFF) would return the total number of off days, but is there a way to get this total only rows where the first cell contains Jess?(In this example, OFF is STRING in my question, while Jess is IFTEXT)
|
How to count the occurrences of 'STRING' in a row, but only if that row begins with 'IFTEXT'
|
google spreadsheets;formulas
|
If you don't want to precalculate the subtotal of off days, you can use an array formula:=arrayformula(SUM((A:A=Jess)*(B:C=OFF)*1))A:A=Jess returns a bunch of TRUE and FALSE, in your sample, it would be {TRUE, FALSE, FALSE, TRUE, FALSE}B:C=OFF returns another bunch of TRUE and FALSE, in your sample, it would be {FALSE, TRUE; FALSE, FALSE; FALSE, FALSE; FALSE, FALSE; FALSE, FALSE} (note semicolons denoting the different rows)And those two multiplied is evaluated as:From A:A=Jess From B:C=OFF ResultTRUE (FALSE, TRUE ) = FALSE TRUEFALSE (FALSE, FALSE) = FALSE FALSEFALSE (FALSE, FALSE) = FALSE FALSETRUE (FALSE, FALSE) = FALSE FALSEFALSE (TRUE , TRUE ) = FALSE FALSEOnly a TRUE multiplied by another TRUE gives a result of TRUE. The *1 last converts every TRUE to 1. SUM then adds all the 1 together.
|
_vi.3231
|
Say that I am on line 20 and I would like to yank line 4, how can I do that?And similarly, how can I yank a line relative to my cursor position, say the one 3 lines up?
|
How to yank a line with a certain line number?
|
cut copy paste
|
From :help :yank::[range]y[ank] [x] Yank `[range]` lines [into register x].So, to yank line 4, one would type::4yankNote you can easily do this from insert mode with <C-o>; this allows you toexecute one command, after which you're returned to insert mode; for example:<C-o>:4yankYou can, of course, also use other ranges. Some examples:Lines 1 to 3: :1,3yankThe entire buffer: :%yankFrom the current line to the end of the buffer: :.,$:yankThe current line and the next 3: :.,+3yankThe current line and the previous 3: :-3,.yankThe line 3 lines above the current line: :-3yankThe most useful things to remember about ranges:It's in the form of :line1,line2command.A . is the current line (you can actually omit the dot in most cases; :.,+3yank and :,+3yank are the same)You specify lines relative to the current position with +n and -n.See :help [range] for moreinformation.
|
_datascience.15965
|
When would a neural network be defined as a Deep Neural Network (DNN) and not a NN?A DNN as I understand them are neural networks with many layers, and simple neural networks usually have fewer layer... but what a many and a few in numbers? or is there some other definition?What are networks trained used Tensorflow, Caffee as such? I haven't (as far I know) seen anybody manually design a network with many many layers. They seem to promote their tools for creating DNN, but is it actually DNN if you only make a network with two layers?
|
When is something a Deep Neural Network (DNN) and not NN?
|
neural network;deep learning
|
You are right. Mainly any network with more than two layers between the input and output is considered a deep neural network. Libraries like tensorflow provide efficient architecture for deep learning applications such as image recognition, or language modelling using Convolutional neural networks and Recurrent neural networks. Another thing to keep in mind, is the depth of the network also has to do with the number of units being used in the layer. Mainly, as your non-linear hypotheses get complex you will need deep neural networks.
|
_unix.181738
|
Please guide me to get out of it.Thanks in advance.I am having a situation that I have to write a awk script which takes the input of two .out files and generate a single .txt file.$ cat file1.shawk -f awk_file.awk < outfile1.out outfile2.out > text_file.txtI want to display the .txt file like,----------------Output from File1----------column1 column2 column3--------------------------------------------columns i will pick from outfile1.outcolumns i will pick from outfile1.out--------------------------------------------Total no. of columns from outfile1.out////////////////////////////////////////////////----------------Output from File2----------column1 column2 column3 column4 column5-------------------------------------------columns i will pick from outfile2.outcolumns i will pick from outfile2.outcolumns i will pick from outfile2.outcolumns i will pick from outfile2.out----------------------------------------Total no. of columns from outfile2.outHow resulting the text_file.txt???
|
multiple input in a awk file
|
shell script;awk
| null |
_unix.388262
|
I'm trying to install vim from source, but I'm facing an error saying I need to install a terminal library. But when I try to install these libraries, the error is shown:The following packages have unmet dependencies: libncurses5-dev : Depends: libtinfo5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed Depends: libncurses5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed Depends: libtinfo-dev (= 5.9+20140913-1+b1) but it is not going to be installed libncursesw5-dev : Depends: libtinfo5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed Depends: libncursesw5 (= 5.9+20140913-1+b1) but 6.0+20161126-1 is to be installed Depends: libtinfo-dev (= 5.9+20140913-1+b1) but it is not going to be installedI tried installing the required version, but then, the opposite happens, I will require the latest version. How to solve this?
|
Impasse on libtinfo5 version. Versions are required but others will be installed
|
vim;dependencies
| null |
_webmaster.65512
|
I'm trying to troubleshoot some problems with users being blocked from our website by CloudFlare. We run a Joomla 2.5 installation with RSFirewall. I have the list of IP blocks that CloudFlare uses, but I'm not versed enough with IP block math to figure out whether several of the addresses that are currently showing in the blacklist are actually CF servers. For example, the following IP is in our blacklist:103.22.201.147And CloudFlare uses the following block:103.22.200.0/22Based on what I read here it looks like that address is indeed a CloudFlare address and I need to remove it from the blacklist. Can anybody confirm whether I'm understanding it correctly or not? Thanks for your help.
|
Need help with understanding IP blocks
|
joomla;ip address;cloudflare
|
Yes. The IP address 103.22.201.147 is CloudFlare within the IP address range of 103.22.200.0 - 103.22.201.255.
|
_unix.44948
|
I'm working on an embedded Linux system (128MB RAM) without any swap partition. Below is its top output:Mem: 37824K used, 88564K free, 0K shrd, 0K buff, 23468K cachedCPU: 0% usr 0% sys 0% nic 60% idle 0% io 38% irq 0% sirqLoad average: 0.00 0.09 0.26 1/50 1081 PID PPID USER STAT VSZ %MEM CPU %CPU COMMAND 1010 1 root S 2464 2% 0 8% -/sbin/getty -L ttyS0 115200 vt10 1081 1079 root R 2572 2% 0 1% top 5 2 root RW< 0 0% 0 1% [events/0] 1074 994 root S 7176 6% 0 0% sshd: root@ttyp0 1019 1 root S 13760 11% 0 0% /SecuriWAN/mi 886 1 root S 138m 112% 0 0% /usr/bin/rstpd 51234 <== 112% MEM?!? 1011 994 root S 7176 6% 0 0% sshd: root@ttyp2 994 1 root S 4616 4% 0 0% /usr/sbin/sshd 1067 1030 root S 4572 4% 0 0% ssh passive 932 1 root S 4056 3% 0 0% /sbin/ntpd -g -c /etc/ntp.conf 1021 1 root S 4032 3% 0 0% /SecuriWAN/HwClockSetter 944 1 root S 2680 2% 0 0% dbus-daemon --config-file=/etc/db 1030 1011 root S 2572 2% 0 0% -sh 1079 1074 root S 2572 2% 0 0% -sh 1 0 root S 2460 2% 0 0% init 850 1 root S 2460 2% 0 0% syslogd -m 0 -s 2000 -b 2 -O /var 860 1 root S 2460 2% 0 0% klogd -c 6 963 1 root S 2184 2% 0 0% /usr/bin/vsftpd /etc/vsftpd.conf 3 2 root SW< 0 0% 0 0% [ksoftirqd/0] 823 2 root SWN 0 0% 0 0% [jffs2_gcd_mtd6]ps (which doesn't understand any options besides -w on busybox) shows: PID USER VSZ STAT COMMAND 1 root 2460 S init 2 root 0 SW< [kthreadd] 3 root 0 SW< [ksoftirqd/0] 4 root 0 SW< [watchdog/0] 5 root 0 SW< [events/0] 6 root 0 SW< [khelper] 37 root 0 SW< [kblockd/0] 90 root 0 SW [pdflush] 91 root 0 SW [pdflush] 92 root 0 SW< [kswapd0] 137 root 0 SW< [aio/0] 146 root 0 SW< [nfsiod] 761 root 0 SW< [mtdblockd] 819 root 0 SW< [rpciod/0] 823 root 0 SWN [jffs2_gcd_mtd6] 850 root 2460 S syslogd -m 0 -s 2000 -b 2 -O /var/log/syslog 860 root 2460 S klogd -c 6 886 root 138m S /usr/bin/rstpd 51234 945 root 2680 S dbus-daemon --config-file=/etc/dbus-system.conf --for 964 root 2184 S /usr/bin/vsftpd /etc/vsftpd.conf 984 root 4616 S /usr/sbin/sshd 987 root 952 S /sbin/udhcpd /ftp/dhcpd.conf 1002 root 4056 S /sbin/ntpd -g -c /ftp/ntp.conf 1022 root 2464 S -/sbin/getty -L ttyS0 115200 vt102 1023 root 7176 S sshd: root@ttyp0 1028 root 2572 S -sh 1030 root 2572 R psWhen you look at process 886, you see that it uses 112% of the availble memory and has VSZ (virtual memory size) of 138MB. That doesn't make any sense to me.In the top man page it says: %MEM -- Memory usage (RES) A task's currently used share of available physical memory. How can this process consume more than 100% memory?And if it's such a memory hog, why are there still 88564K RAM free on the system?
|
What do top's %MEM and VSZ mean?
|
linux;memory;resources
|
The man page you refer to comes from the procps version of top.But you're on an embedded system, so you have the busybox version of top.It looks like busybox top calculates %MEM as VSZ/MemTotal instead of RSS/MemTotal.The latest version of busybox calls that column %VSZ to avoid some confusion. commit log
|
_codereview.4130
|
I wrote the following code to give an HTML element max width/height in its parent container.I think I address the box model issues but I am wondering if anyone can see issues and or shortcomings.Are there other solutions out there that accomplish this? I want to make sure I didn't re-invent the wheel.function heightBuffer(control) { return parseInt((control.outerHeight(true)) - control.height());}function widthBuffer(control) { return parseInt((control.outerWidth(true)) - parseInt(control.width()));}function MaxHeightInParent(control, minHeight, controlHeightsToSubtract) { var h = parseInt(control.parent().height()) - heightBuffer(control); if (controlHeightsToSubtract != null) $.each(controlHeightsToSubtract, function(index, value) { h = h - parseInt(value.outerHeight(true)); }); if (minHeight != null && h < minHeight) h = minHeight; control.height(0); control.css('min-height', h);}function MaxWidthInParent(control, minWidth, controlWidthsToSubtract) { var w = parseInt(control.parent().width()) - widthBuffer(control); if (controlWidthsToSubtract != null) $.each(controlWidthsToSubtract, function(index, value) { w = w - parseInt(value.outerWidth(true)); }); if (minWidth != null && w < minWidth) w = minWidth; control.width(0); control.css('min-width', w);}Note controlHeightsToSubtract / controlWidthsToSubtract are if you wish to pass an array of controls that share the containing element with the element you are attempting to maximize in Height/Width.
|
Javascript to compute max width and height for a nested HTML element
|
javascript;jquery;html;css
|
What isparseInt((control.outerHeight(true)) - control.height());supposed to achieve?The result of - is always going to be a number, so what this does is convert the number to a string and back to a number. This can only lose precision and waste time.Similarly, the use of parseInt on the first argument is also unnecessaryparseInt(control.parent().height()) - heightBuffer(control)since4 - 1 === 3In fact, the automatic conversion that - does is better than that done by parseInt since parseInt falls back to octal on some interpreters but not others.10 - 1 === 9parseInt(10) - 1 === 90x10 - 1 === 15parseInt(0x10) - 1 === 15010 - 1 // throws reliablyparseInt(010) - 1 === 7 // on some and 9 on othersso I'd get rid of all the uses of parseInt as an operand to -.You seem to be setting min-height but the method is called MaxHeight. That confuses me.When you change the CSScontrol.css('min-height', h)you might want to specify units as incontrol.css('min-height', h + px)I'm not sure how you're handling the widths of margins and borders on the controls. Is that important to you?
|
_unix.197601
|
How to add vertical space after each command in bash?Looking for a wee bit of vertical space, not a full line. 1/4 or 1/3 of the line height should do it.[edit] The space to add is only after the command+output bundle. The lines between command and associated output still use default spacing. Example: do ls, the output is shown using regular line spacing; only after the output do we get the increased spacing to clearly separate command+output pair from the next command+output.
|
Adding vertical space after command in bash
|
bash;command line;terminal
| null |
_unix.120964
|
I'm trying to upgrade some package in a VM, but I dpkg refuses to apply the upgrades due the following:dpkg: error processing /var/cache/apt/archives/ifupdown_0.7.5ubuntu2.2_amd64.deb (--unpack): unable to make backup link of `./sbin/ifquery' before installing new version: No such file or directoryPreparing to replace unzip 6.0-8ubuntu1 (using .../unzip_6.0-8ubuntu2_amd64.deb) ...Unpacking replacement unzip ...dpkg: error processing /var/cache/apt/archives/unzip_6.0-8ubuntu2_amd64.deb (--unpack): unable to make backup link of `./usr/bin/unzip' before installing new version: No such file or directorydpkg-deb: error: subprocess paste was killed by signal (Broken pipe)What it means? The permissions are fine and the file definitively exist:ls -l /sbin/ifquery-rwxr-xr-x 1 1500000 1500000 58496 dic 12 2012 /sbin/ifquery
|
What means unable to make backup link of /binary before installing new version: No such file or directory?
|
dpkg
|
This means that for some motive, you can't move the binary in the file system:sudo mv /sbin/ifquery{,.bk}[sudo] password for braiam: mv: cannot move /sbin/ifquery to /sbin/ifquery.bk: Input/output errorYou should check the filesystem for problems or ask your system administrator.
|
_codereview.71413
|
This is a follow up to Messenger supporting notifications and requestsI've written a lightweight (I think) class that acts as a messenger service between classes for both notifications (fire and forget updates to other classes) and requests (a notification sent out that expects a returned value).Since the last question, I have altered the request system to return an IEnumerable filled with all the results from all of the registered functions. This allows the caller to pick from the results or operate on all of them, although I imagine typical use will be to call .Single() or .First().I have also removed the default static instance to prevent laziness and poor code practices, and I have removed a pointless cast between Action and DelegateI'm looking for a general review here on style, usability, best practices, etc.Here's the code (.NET Fiddle here)public class Messenger{ /// <summary> /// The actions /// </summary> private Dictionary<Type, Delegate> actions = new Dictionary<Type, Delegate>(); /// <summary> /// The functions /// </summary> private Dictionary<Type, Collection<Delegate>> functions = new Dictionary<Type, Collection<Delegate>>(); /// <summary> /// Register a function for a request message. /// </summary> /// <typeparam name=T> Type of message to receive. </typeparam> /// <typeparam name=R> Type of the r. </typeparam> /// <param name=request> The function that fills the request. </param> public void Register<T, R>(Func<T, R> request) { if (request == null) { throw new ArgumentNullException(request); } if (functions.ContainsKey(typeof(T))) { functions[typeof(T)].Add(request); } else { functions.Add(typeof(T), new Collection<Delegate>() { request }); } } /// <summary> /// Register an action for a message. /// </summary> /// <typeparam name=T> Type of message to receive. </typeparam> /// <param name=action> The action that happens when the message is received. </param> public void Register<T>(Action<T> action) { if (action == null) { throw new ArgumentNullException(action); } if (actions.ContainsKey(typeof(T))) { actions[typeof(T)] = (Action<T>)Delegate.Combine(actions[typeof(T)], action); } else { actions.Add(typeof(T), action); } } /// <summary> /// Send a request. /// </summary> /// <typeparam name=T> The type of the parameter of the request. </typeparam> /// <typeparam name=R> The return type of the request. </typeparam> /// <param name=parameter> The parameter. </param> /// <returns> The result of the request. </returns> public IEnumerable<R> Request<T, R>(T parameter) { if (functions.ContainsKey(typeof(T))) { var applicableFunctions = functions[typeof(T)].OfType<Func<T, R>>(); foreach (var function in applicableFunctions) { yield return function(parameter); } } } /// <summary> /// Sends the specified message. /// </summary> /// <typeparam name=T> The type of message. </typeparam> /// <param name=message> The message. </param> public void Send<T>(T message) { if (actions.ContainsKey(typeof(T))) { ((Action<T>)actions[typeof(T)])(message); } } /// <summary> /// Unregister a request. /// </summary> /// <typeparam name=T> The type of request to unregister. </typeparam> /// <typeparam name=R> The return type of the request. </typeparam> /// <param name=request> The request to unregister. </param> public void Unregister<T, R>(Func<T, R> request) { if (functions.ContainsKey(typeof(T)) && functions[typeof(T)].Contains(request)) { functions[typeof(T)].Remove(request); } } /// <summary> /// Unregister an action. /// </summary> /// <typeparam name=T> The type of message. </typeparam> /// <param name=action> The action to unregister. </param> public void Unregister<T>(Action<T> action) { if (actions.ContainsKey(typeof(T))) { actions[typeof(T)] = Delegate.Remove(actions[typeof(T)], action); } }}Example usage:public class Receiver{ public Receiver(Messenger messenger) { messenger.Register<string>(x => { Console.WriteLine(x); }); messenger.Register<string, string>(x => { if (x == hello) { return world; } return who are you?; }); messenger.Register<string, string>(x => { if (x == world) { return hello; } return what are you?; }); }}public class Sender{ public Sender(Messenger messenger) { messenger.Send<string>(Hello world!); Console.WriteLine(); foreach (string result in messenger.Request<string, string>(hello)) { Console.WriteLine(result); } Console.WriteLine(); foreach (string result in messenger.Request<string, string>(world)) { Console.WriteLine(result); } }}
|
Shoot the Messenger pt. 2
|
c#
|
GoodYou are following the naming guidelines The method and parameternames are well choosen and meaningful Improvable XML comments should, if used, be complete e.g /// <typeparam name=R> Type of the r. </typeparam> instead of often calling typeof(T) call it once and reuse it. using early returns removes horizontal spacing creation of the Collection<Delegate>() functions.Add(typeof(T), new Collection<Delegate>() { request }); this is less readable than this functions.Add(type, new Collection<Delegate>() { request });So this public void Register<T, R>(Func<T, R> request){ if (request == null) { throw new ArgumentNullException(request); } if (functions.ContainsKey(typeof(T))) { functions[typeof(T)].Add(request); } else { functions.Add(typeof(T), new Collection<Delegate>() { request }); }} will become public void Register<T, R>(Func<T, R> request){ if (request == null) { throw new ArgumentNullException(request); } var type = typeof(T); if (functions.ContainsKey(type)) { functions[type].Add(request); return; } functions.Add(type, new Collection<Delegate>() { request });} or this public IEnumerable<R> Request<T, R>(T parameter){ if (functions.ContainsKey(typeof(T))) { var applicableFunctions = functions[typeof(T)].OfType<Func<T, R>>(); foreach (var function in applicableFunctions) { yield return function(parameter); } }} will become public IEnumerable<R> Request<T, R>(T parameter){ var type = typeof(T); if (!functions.ContainsKey(type)) { return Enumerable.Empty<R>(); } var applicableFunctions = functions[type].OfType<Func<T, R>>(); foreach (var function in applicableFunctions) { yield return function(parameter); }}
|
_softwareengineering.333317
|
I've been doing some functional JavaScript. I had thought that Tail-Call Optimization had been implemented, but as it turns out I was wrong. Thus, I've had to teach myself Trampolining. After a bit of reading here and elsewhere, I was able to get the basics down and constructed my first trampoline:/*not the fanciest, it's just meant toreenforce that I know what I'm doing.*/function loopy(x){ if (x<10000000){ return function(){ return loopy(x+1) } }else{ return x; }};function trampoline(foo){ while(foo && typeof foo === 'function'){ foo = foo(); } return foo;/*I've seen trampolines without this,mine wouldn't return anything unlessI had it though. Just goes to show Ionly half know what I'm doing.*/};alert(trampoline(loopy(0)));My biggest issue, is I don't know why this works. I get the idea of rerunning the function in a while loop instead of using a recursive loop. Except, technically my base function already has a recursive loop. I'm not running the base loopy function, but I am running the function inside of it. What's stopping foo = foo() from causing a stack overflow? And isn't foo = foo() technically mutating, or am I missing something? Perhaps it's just a necessary evil. Or some syntax I'm missing.Is there even a way to understand it? Or is it just some hack that somehow works? I've been able to make my way through everything else, but this one has me befuzzled.
|
Why do Trampolines work?
|
javascript;functional programming
|
The reason your brain is rebelling against the function loopy() is that it is of an inconsistent type:function loopy(x){ if (x<10000000){ return function(){ // On this line it returns a function... // (This is not part of loopy(), this is the function we are returning.) return loopy(x+1) } }else{ return x; // ...but on this line it returns an integer! }};Quite a lot of languages don't even let you do things like this, or at least demand a lot more typing to explain just how this is supposed to make any kind of sense. Because it really doesn't. Functions and integers are totally different kinds of objects.So let's go through that while loop, carefully:while(foo && typeof foo === 'function'){ foo = foo();}Initially, foo is equal to loopy(0). What is loopy(0)? Well, it's less than 10000000, so we get function(){return loopy(1)}. That's a truthy value, and it's a function, so the loop keeps going.Now we come to foo = foo(). foo() is the same as loopy(1). Since 1 is still less than 10000000, that returns function(){return loopy(2)}, which we then assign to foo.foo is still a function, so we keep going... until eventually foo is equal to function(){return loopy(10000000)}. That's a function, so we do foo = foo() one more time, but this time, when we call loopy(10000000), x is not less than 10000000 so we just get x back. Since 10000000 is also not a function, this ends the while loop as well.
|
_computergraphics.3868
|
The 99 lines of C path tracer Smallpt renders a 2x2 subpixel grid for each pixel it intends to render and then does a tent filter to combine them.There is an interesting presentation explaining the code here, and it mentions the tent filter but doesn't explain why it's there.Can anyone explain why a tent filter would be preferable in this case over a box blur (just averaging the samples)?Would it be higher quality to go with something better than a tent filter, such as bicubic hermite interpolation?
|
Why use a tent filter in path tracing?
|
pathtracing;filtering
|
The theoretical ideal antialiasing filter for discretely sampled data is a sinc filter, because it perfectly removes all frequencies higher than the Nyquist frequency, while leaving alone all the lower ones. So, to some extent, we can expect antialiasing filters that more closely resemble the sinc filter to produce better-quality images.The tent filter (triangle filter) certainly resembles the central peak of the sinc filter more closely than does the box filter:A bicubic filter (e.g. Mitchell-Netravali) could capture the shape of the sinc even more precisely, including its first two negative lobes.The reality of filter selection is a bit more subtle than approximate sinc as well as possible, since there are different kinds of artifacts that can be generated by non-ideal antialiasing filters, such as aliasing, overblurring, and ringing. Also, different filters may be more or less computationally expensive. So it's a game of trying to trade off the different artifacts against each other and against performance. Different scenes/images may favor one choice or another, and it's also partly an aesthetic judgement.As for why smallpt uses a tent filter in particular, I would guess for a combination of performance (it's a quick filter to evaluate) and brevityit can be done in a couple lines of code, while a bicubic filter would take a bunch more code.Incidentally, smallpt actually uses a 2x2 subpixel grid and places a tent filter at each subpixel, then averages together the results of the four subpixels. So the overall effect is, curiously, that of the sum of four tents, which ends up looking like a pyramid with a flat top:I'm not sure if this was intentional, or just happened to be the way it worked out. My guess is this results in a somewhat sharper image than if a single tent filter per pixel were used (because of the narrower support), but probably also more visible aliasing.
|
_webmaster.103313
|
I am working on a website where some pages link to a pdf. Here is the high-level description of the current set up:Page A - This is a normal web page, lets say, a page that talks about instruction manuals for a particular piece of furniture, how rare they are, etc, and has a link to a PDF of the actual instructions for that piece (or multiple links if there are several versions). The URI of this page might be something like:http://www.example.com/antique-xyz-game-table-manuals...and it would have links to one or more Page BPage B - This is a pdf viewer page... basically has the site's header and footer, and in between is an iframe of the PDF using the google document viewer (the actual pdf is hosted on the main site, it just uses the google viewer to embed it). This page also contains a direct link to the pdf which would either open it in the browser or download it depending on the user and whatever client they use. Example URIs of these pages would be:http://www.example.com/file/view/f?=xyz-assembly.pdfhttp://www.example.com/file/view/f?=xyz-maintenance.pdfhttp://www.example.com/file/view/f?=xyz-parts.pdfPage C - We'll call the direct URI of the PDF Page C. Each Page B would have a link to the direct pdf. Example URIs would be:http://www.example.com/file/xyz-assembly.pdfhttp://www.example.com/file/xyz-maintenance.pdfhttp://www.example.com/file/xyz-parts.pdfA few more assumptions:Page A is original content talking about the manuals, and linking to them. It is NOT a duplicate of the manual. The PDFs themselves have their own entries in the sitemaps.xml and have no issues getting indexed by the search engines.The UI is how it is, and it is how the customer wants it. This is not a question about the UI.The question(s):On the direct link in Page B, to the actual PDF, Should I be using a rel=canonical meta tag, and if so, should it point to the actual PDF or should it point to the page A?On Page A - should there be any rel attribute on the link itself?Any other SEO factors I should consider with this type of set-up?Thanks in advance and let me know if any further clarification is needed.
|
rel=canonical/alternate and PDF documents and SEO
|
seo;iframe;pdf
|
So you have three types of pages of which you want two to appear in the search engine results.Therefore you can use rel=canonical link elements in order to tell the search engine which page of two pages it should index and serve as a result and which one it should skip.The rel=canoncal attribute has to be placed in a <link > element in a HTML document's <head> section:<html> <head> <link rel=canonical http://www.example.com/file/xyz-assembly.pdf > </head> </html>For your setup this means:http://www.example.com/antique-xyz-game-table-manualsThis page should be indexed and ranked. No need to specify duplicates or alternate versions, as long there are none of them. Basically it is a good practice to mark up these page with a rel=canonical to themselves to avoid duplicate content issues with URL variations.http://www.example.com/file/view/f?=xyz-assembly.pdfThis page is a duplicate of http://www.example.com/file/xyz-assembly.pdfAs you only want the PDF file to rank in the SERPs you make use of rel=canonical to the PDF document (despite the reader's menu the documents are identical).To speak more generally:Each overview page has a self referential canonical link element in the <head> section of it's source code.Each viewer page has as canonical link element pointing to the real PDF document in the <head> section of it's source code.The alternate Links are not needed in terms of SEO.For your specific QuestionsOn the direct link in Page B, to the actual PDF, Should I be using a rel=canonical meta tag, and if so, should it point to the actual PDF or should it point to the page A? Specify the rel=canonical link in the <head> section of the viewer page pointing to to the actual PDF. If you cannot access the HTML source of the viewer page you may set up a canonical header for viewer pages pointing to the actual PDF file. (For more detailed information on how to implement canonical headers see: How To: Advanced rel=canonical HTTP Headers (Moz.com)On Page A - should there be any rel attribute on the link itself?Not for SEO reasons.Any other SEO factors I should consider with this type of set-up?Maybe, but it depends on further information to judge this :)As you have direct links to the PDF files you may think of using optimized anchor texts. F.e.: Assembly Guide for Table Type XYZ (PDF) instead of xyz-assembly.pdf. Make sure the PDF link is the first to be crawled by the search engine.Make sure you do not mix noindex and canonical! maybe you think of marking the viewer pages as noindex in order to keep them out of the search engine's index. This would hurt the canonical set-up.In order to save crawling resources you may set up your overview page in a way that it only serves links to the actual PDF files ind leverages Java Script or something alike to enable the viewer mode. This would avoid search engines crawling the viewer pages. But you would stay with the canonicalization of viewer page and PDF file, as users may link to the viewer URL from outside of your page.
|
_unix.92495
|
Is it possible to start many VMs created by different users on the same Linux host?I want to start four virtual machines with my own user name and start four with another user name at the same time on the same host.
|
User-specific virtual machines in VirtualBox
|
virtualbox
|
If you have powerful enough host or low requirements for the virtual machines, then it certainly is possible - the best way to find out is to try it.That said, depending on your needs, OS-level virtualisation like LXC might serve you better.
|
_webapps.10663
|
I saved some bookmarks with proper tags, but these are displayed only when I log in. These are not available in the recent list on the homepage without logging in even though I searched with tag or URL.Where am I going wrong?
|
Bookmarks not visible in Delicious
|
bookmarks;delicious
| null |
_unix.318922
|
vtt files look like this:WEBVTT100:00:00.096 --> 00:00:05.047you're the four functions if you would of management first of all you have the planning200:00:06.002 --> 00:00:10.079the planning stages basically you were choosing appropriate organizational goals and courses300:00:11.018 --> 00:00:13.003action to best achieve those goalsI need just the text, like this:you're the four functions if you would of management first of all you have the planning the planning stages basically you were choosing appropriate organizational goals and courses action to best achieve those goalson ubuntu I tried:cat file.vtt | grep -v [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9][[:space:]][[:punct:]][[:punct:]][[:punct:]][[:space:]][0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]that gives me:WEBVTT1you're the four functions if you would of management first of all you have the planning2the planning stages basically you were choosing appropriate organizational goals and courses3action to best achieve those goalsbut I can't figure out how to do the rest. what I want to replace is\n[0-9]+\n\n with space but I can't figure out how to make sed or grep do that.how do I get with basic / portable (eg generally preinstalled in ubuntu, centos, etc, eg grep, sed, or tr command) to just the raw text with the subtitle timing removed, and all in one line (no newlines)?NOTE: this has to work for other language characters like chinese hindi arabic, so preferably no [a-z] type matches but instead remove the timing lines which are very consistent in format. Also don't blindly remove any numbers as text can contain numbersNOTE 2: ultimate goal is to have the text safe for a json value , so all special chars removed and double quotes escaped, but that's sort of beyond the scope of this question
|
grab text out of vtt file
|
text processing;sed;grep;regular expression;json
|
Since your file appears to consist of a sequence of records separated by one or more blank lines, I'd suggest trying something based on the paragraph modes of either awk or perl.For example, if you always need to strip off the first two lines, like100:00:00.096 --> 00:00:05.047you could split into newline-delimited fields within blank-separated paragraphs and skip the first two fields using eitherawk -vRS= -vORS= -F'\n' '{for(j=3;j<=NF;j++) print $j; print }' file.vttorperl -F'\n' -00ne 'print join(, @F[2..$#F]), ' file.vttIf you can't rely on there being a fixed number of fields (lines) to be removed, then it's fairly easy to add a regular expression test - a little easier in perl since it allows us to grep directly on arrays rather than writing an explicit loop. For example, to split into blank-separated records and then print only those fields (lines) having at least one sequence of at least 3 alphabetic characters, you could useperl -F'\n' -00ane ' print join(, grep { /[[:alpha:]]{3}/ } @F), ' file.vttIf you want to exclude the WEBVTT string you can simply skip the first record, i.e.perl -F'\n' -00ane ' print join(, grep { /[[:alpha:]]{3}/ } @F), if $. > 1 ' file.vttIt will be down to you to choose a suitable regex that capture the wanted lines and excludes the unwanted ones. You can add an END block in either awk or perl if you want to add a final newline to the concatenated output.NOTE: since (based on the discussion in comments) your files appear to have DOS-style CRLF line endings, you will need to deal with those - either by modifying the field and record separators in the above commands accordingly, or by stripping out the CRs first e.g.sed 's/\r$//' file.vtt | perl -F'\n' -00ane ' print join(, grep { /[[:alpha:]]{3}/ } @F), if $. > 1 'you're the four functions if you would of management first of all you have the planning the planning stages basically you were choosing appropriate organizational goals and courses action to best achieve those goals steeldriver@xenial-vm:~/test/$
|
_softwareengineering.310704
|
I am working on a personal project using Python. I have been using version control to the best of my abilities and if you would like to check it out and run the app https://github.com/CodeAmend/old-bull-tools/tree/developIf you prefer Floobits, look at my actual code in a editor here:https://floobits.com/CodeAmend/old-bull-tools/file/app.py:1I have been learning version control with this project and I have been trying to use TDD with the best of my abilities. Currently opening of the Test_Schedule class, it has been hard to write test methods.A short slice of what I am trying to do:I am building an api that handles a scheduling system. This will communicate with the web as well as mobile devices. Users sign in and can check their schedule, change dates to view other scheduled times and also pick the amount of information displayed (i.e. only show servers or kitchen staff, daily view, month view, calendar view).So here is the question:How would one build a schedule object? How should I visualize this? What types of questions should I ask myself to help me move forward? It seems that I need to user information from both user and shift to populate the schedule.Right now I am stuck. And this is because I have two objects: User and Shift. Now I am thinking I should make a schedule object.a User contains _id(user_id), name, email.... a Shift contains a _id, user_id, start_time, stop_timeIn order to display this stuff on the front end, I need to populate a schedule. Kinda like this:# mon tues weds thurs fri sat # user1 4:00 ____ 6:00 4:00 5:00 6:00 # user2 4:00 5:00 6:00 ____ 5:00 6:00This is only an example but from the look of this, I might need Schedule to return something like this (Shift, None, Shift, Shift, None, Shift)This is some test cases in my shift objectdef test_create_shift(self):def test_shift_throws_error_if_time_is_not_int(self):def test_save_shift_to_database(self):def test_get_shifts_by_id(self):def test_get_shifts_within_date_range_by_id(self): def test_get_shifts_on_specific_date_by_id(self):def test_get_shifts_before_end_time_by_id(self):def test_get_shifts_after_start_time_by_id(self):def test_get_shifts_exactly_on_start_date_by_id(self):def test_get_shifts_exactly_on_end_date_by_id(self):def test_get_current_weeks_shifts_by_id(self):Here is my thought process so far:schedule = Schedule(user_id) <---- no range addedtest_no_range_added_returns_this_weeks_shifts_for_user()assertEquals(len(schedule.shifts), 7)test_user_with_no_shifts_returns_none_for_each_day_in_range() for i in range(schedule.shifts): assertEqual(schedule.shifts[i], None)This is the most current for of thinking. A schedule is just one row, so basically one user. Schedule has Shifts and a User. Multiple Schedules are loaded to populate all employees. Perhaps Schedule is not the best name, but I am not sure yet.
|
How to think about a schedule that pulls from a database as objects
|
object oriented;python;unit testing;tdd;flask
| null |
_codereview.61823
|
The purpose of this code is to centralize all error / status messages to present to the user. For example, registering an account and the user email address is already registered. A status code is set then sent off to get a friendly error message to present to the user. All services will have its own set of status code and status messages which is handled by a status handler for filtering. While this is only a basic class I want to make sure that I am going in the right direction before extending.Status codes namespace Services.RegistrationService { public enum StatusCodes { UserAlreadyExists, // more to come } } List of statuses for registrationusing Framework;using System.Collections.Generic;namespace Services.RegistrationService{ public class RegistrationStatusMessages : MessageStatusHandler { public void AddErrors(List<StatusCodes> codes) { foreach(var errorCodes in codes) switch (errorCodes) { case StatusCodes.UserAlreadyExists: { base.add(User already exists, EmailAddress, true); break; } } } }}Message status handlerusing System.Collections.Generic;using System.Linq;namespace Framework{ public class MessageStatusHandler { protected List<MessageStatusHandler> _errorList; private string _friendlyErrorMessage; private bool _isError; private string _propertyName; public MessageStatusHandler() { _errorList = new List<MessageStatusHandler>(); } protected void add(string friendlyErrorMessage, string propertyName, bool isError) { _errorList.Add(new MessageStatusHandler { _friendlyErrorMessage = friendlyErrorMessage, _propertyName = propertyName, _isError = isError }); } public bool HasErrors() { return _errorList.Any(x => x._isError == true); } }}Again, it is a simple class setup that centralizes status codes, error messages for each service. Is there any way to improve on this, or am I going in the right direction?
|
Generic error message factory
|
c#;error handling
|
First a few minor things:Standard naming convention for methods in C# is PascalCase.You should use braces { } for pretty much all blocks. This is asking for maintenance trouble:foreach(var errorCodes in codes)switch (errorCodes){ case StatusCodes.UserAlreadyExists: { base.add(User already exists, EmailAddress, true); break; }}The Enum naming convention suggests to use singular form for enums.Now design:I find it a bit odd that your class represents a descriptor for a status code and acts as a container for all status codes at the same time. This looks to me like an SRP (Single Responsibility Principle) violation. I would split it up and maybe put some generics in the mix (unfortunately enum can't be used as generic type constraint).So something along these lines:public class StatusCodeDescriptor<T>{ public readonly T StatusCode; public readonly string FriendlyErrorMessage; public readonly bool IsError; public readonly string PropertyName; public StatusCodeDescriptor(T statusCode, string friendlyError, string propertyName, bool isError) { StatusCode = statusCode; FriendlyErrorMessage = friendlyError; IsError = isError; PropertyName = propertyName; }}public abstract class StatusCodeHandlerBase<T>{ protected List<StatusCodeDescriptor<T>> _StatusCodes = new List<StatusCodeDescriptor<T>>(); public void AddStatusCodes(IEnumerable<T> statusCodes) { foreach (var code in statusCodes) { _StatusCodes.Add(GetDescriptor(code)); } } protected abstract StatusCodeDescriptor<T> GetDescriptor(T statusCode); public bool HasError() { return _StatusCodes.Any(c => c.IsError); }}public enum RegistrationStatusCode{ UserAlreadyExists, // ...}public class RegistrationStatusCodeHandler : StatusCodeHandlerBase<RegistrationStatusCode>{ protected override StatusCodeDescriptor<RegistrationStatusCode> GetDescriptor(RegistrationStatusCode statusCode) { switch (statusCode) { case RegistrationStatusCode.UserAlreadyExists: return new StatusCodeDescriptor<RegistrationStatusCode>(statusCode, User already exists, EmailAddress, true); } }}
|
_codereview.117277
|
I'm learning Racket and have implemented a mutable stack, which is just a bunch of wrappers around an underlying struct containing a size and buffer list (so it's not optimal, in terms of computational complexity). After consulting #racket and reading the first half of Greg Hendershott's Fear of Macros, I was able to write the syntax transformations I wanted for my implementation.(module stack racket (module stack-implementation racket (struct stack (size buffer) #:mutable) ;; size :: stack -> integer (define (size stack) (stack-size stack)) ;; non-empty-stack? :: stack -> boolean (define (non-empty-stack? stack) (and (stack? stack) (positive? (stack-size stack)))) ;; push! :: stack -> any (new item) -> integer (size) (define (push! stack item) (set-stack-buffer! stack (append (list item) (stack-buffer stack))) (set-stack-size! stack (+ (stack-size stack) 1)) (stack-size stack)) ;; pop! :: (non-empty) stack -> any (head) (define (pop! stack) (let ([head (car (stack-buffer stack))] [tail (cdr (stack-buffer stack))]) (set-stack-buffer! stack tail) (set-stack-size! stack (- (stack-size stack) 1)) head)) ;; make (define-syntax-rule (make name) (define name (stack 0 '()))) (provide make stack? (contract-out [size (-> stack? integer?)] [push! (-> stack? any/c integer?)] [pop! (-> non-empty-stack? any)]))) (require 'stack-implementation (for-syntax racket/syntax)) ;; make-stack ; Defines a stack under the specified symbol <name> ; Plus defines <name>-size, <name>-empty?, <name>-push! and <name>-pop! (define-syntax (make-stack stx) (syntax-case stx () [(_ name) (with-syntax ([(size-fn empty-fn push-fn pop-fn) (map (lambda (fn) (format-id stx ~a-~a #'name fn)) '(size empty? push! pop!))]) #'(begin (make name) (define (size-fn) (size name)) (define (empty-fn) (zero? (size-fn))) (define (push-fn item) (push! name item)) (define (pop-fn) (pop! name))))])) (provide make-stack stack?))I'm completely new to Racket and Lisp, so I'm guessing there are many improvements I can make here (e.g., the duplication in the macro where I define the helper function IDs), besides using a better underlying data structure.
|
Mutable stack in Racket
|
stack;lisp;macros;racket
|
Many Lisp programs use cons cells quite liberally instead of adding aseparate stack structure, in that sense your concerns about complexityare probably a bit less critical. Since the stack is also carrying thelength of the list it actually supports at least the additional sizeoperator quite well. Of course writing more code for an underlying(resizable) vector could make sense, but again I wouldn't count onthat being necessary.For the code I only have minor suggestions, as it's pretty well writtenand clear what each part means; while I'm not that familiar with Racketit's easily readable to me.For the pattern (+/- x 1) there are also the functions add1 andsub1 which could be used.The non-empty-stack? could just check whether the buffer isnull? or empty? instead. positive? sounds like there's somerisk that the stack size might get negative for some reason. For thesame reason the contract can probably also be tightened to check fornon-negative integers.(append (list x) y) is a bit shorter as (cons x y).
|
_softwareengineering.173650
|
I've tried to find a solution for this for hours now, and I'm getting the same results in the end, asking me to install a lot of Azure and other stuff, plus running some example project .sln that I can't open with my 2012 version of Visual Studio.So, I'm pretty much stuck, and have some pretty straight forward questions regarding this:Does TFS 2012 include the Odata service in any way, so that I don't have to install it?If not, how can I install a NATIVE 2012 version of the Odata service for TFS 2012?Is it possible that I'm aiming for the wrong target here? I'm looking for a solution to the following:I have a TFS 2012 Server that I need to be able to create Work Items on programatically, based on data from our Help Desk system. Then I need to query these Work Items for changed status since its creation, and update the Help Desk Database.Am I better off using the regular TFS API? I was kinda thinking that the Odata way was more future proof, but I'm not sure...
|
How to access / query Team Foundation Server 2012 with Odata?
|
team foundation server;visual studio 2012
| null |
_unix.226000
|
I need to a add a column in CSV file from an array using awk.For example,input.csva,10b,11array = (100 200)output.csv should look likea,10,100b,11,200I tried this command but it does not workawk -F, 'BEGIN { OFS = , } {for (x in array) $3=array[x]; print}' input.csv> output.csv
|
adding column in CSV file using awk
|
command line;text processing;awk
| null |
_unix.318248
|
I've got two backup directories that live on the same filesystem on my backup server. The first is called clone - it contains a clone of my laptop that is remotely updated nightly via rsync. The second is called backup, which is a weekly rsync snapshot of only the important parts of clone. To save space, backup is created as hard links to clone instead of copies, using --link-dest:rsync -avum --link-dest=/clone /clone/ /backupNow I want to also use the --backup option to copy the old versions of changed files from backup to a holding area, in case I need them or accidentally delete something important. This works fine without --link-dest:rsync -avumb --backup-dir=/holding/2016_10_22 /clone/ /backupHowever, this creates copies of the changed files in backup, wasting space - I want hard links. But if I add the --link-dest parm back in:rsync -avumb --backup-dir=/holding/2016_10_22 --link-dest=/clone /clone/ /backup...then only deleted files are backed up. Changed files are silently hard linked. The reason (I believe) is that --link-dest shares the logic of --copy-dest. I.e., if the source file is unchanged relative to the copy-dest (or link-dest) file, then it is not transferred, but instead copied/linked from the copy/link-dest dir to the target dir. Because I'm using the source dir as the link-dest dir, all non-deleted files are unchanged, and handled silently.I could do this in two steps: first --backup without --link-dest, then again --link-dest without --backup. (Newer versions of rsync will replace identical files with hard links.) But I'd really prefer to do it all at once.Is there a way of doing --backup while only creating hard links? (Really what I want is regular rsync with hard linking instead of file transfer. My use of --link-dest seems like a bit of a hack, given the intended logic of that option.)Bonus question: the man page seems to indicate that using --link-dest only on empty targets is preferred:This option works best when copying into an empty destination hierarchy, as existing files may get their attributes tweaked, and that can affect alternate destination files via hard-links. Also, itemizing of changes can get a bit muddled.The bit about itemizing getting muddled is a bit vague. Is using --link-dest on a non-empty target really dangerous, assuming I don't care too much about file attributes? Can anyone give an example?
|
how to get rsync to make hard links to the source dir, while also backing up changed files?
|
rsync
| null |
_cogsci.10478
|
I am trying to make a list of the main accepted branches of psychoanalysis to quiz a friend of mine. I don't know much about it and to learn more I need to know the main areas. So far I have Freudian PsychologyObject Relations TheoryRelations Theory Self-psychology Does anyone know of a basic list of the main branches? My friend said these were the main ones, but I couldn't find a source to substantiate that and I want to verify these are indeed considered the main branches. EDIT: By a branch or school, I mean a general umbrella term people use to aggregate related trains of thought. In physics, this might be general relativity or quantum mechanics.
|
What are the different branches of Psychoanalysis?
|
psychoanalysis
|
In the context of the question I think it makes sense to limit the scope to earlier developments in psychoanalysis. Thompson (1957) gives an overview of what can be called psychoanalytic schools. She includes:Freudian psychoanalysisIndividual psychology (Alfred Adler)Analytical psychology (Carl Gustav Jung)Object relations theory (Sndor Ferenczi, Otto Rank)(Wilhelm Reich)Karen Horney (sometimes denoted Culturalist Psychoanaysis)Erich Fromm (sometimes denoted Culturalist Psychoanaysis)Harry Stack Sullivan (sometimes denoted Culturalist Psychoanaysis)On the other hand, several psychoanalytic psychologies can be distinguished. Following a systematization by Gottfried Fischer, there are:Drive theory/drive psychology (psychodynamic theory)Ego psychology (Freudian psychoanalytic psychology/structural theory)Object relations theorySelf psychologyNewer psychoanalytic schools comprise e. g. Lacanian psychoanalysis, interpersonal psychoanalysis and relational psychoanalysis but for a more comprehensive list see Kernberg (2001) and Gabbard (2009).Literature:Frosh, Stephen (2012).A Brief Introduction to Psychoanalytic Theory. London: Palgrave.Gabbard, Glen O. (2009) Textbook of Psychotherapeutic Treatments. American Psychiatric Publishing. (Ch. 1: Theoretical Models of Psychodynamic Psychotherapy)Kernberg, Otto F. (2001). Recent Developments in the Technical Approaches of English-Language Psychoanalytic Schools. The Psychoanalytic Quarterly, Volume LXX, Issue 3, 519547.Thompson, Clara Mabel (1957). The different schools of psychoanalysis. American Journal of Nursing, 57, 13041307.Thompson, Clara Mabel & Mullahy, Patrick (1951). Psychoanalysis: Evolution and Development (3rd ed.). New York: Hermitage House.
|
_softwareengineering.11334
|
Does your company have a written policy about contributing to open-source projects? We've been contributing don't ask don't tell style, but it's time to write something down. I'd appreciate both full written policy text and bits and pieces.Update: we've made some progress since I asked this question and now have such a policy - read this.
|
Does your company have a written policy about contributing to open-source projects?
|
open source;contribution
| null |
_unix.144089
|
I have a couple of nodes ( which are not mine ) running one openvz kernel version -2.6.32-042stab092.2specifications :processor model name : E5-2620 0 @ 2.00GHzNumber of Processors : 24RAM : 48Gnumber of VPSs hosted on each : 23 each vps is assigned 1000 unit of cpu and a cpu limit of 400each vps is assigned 1G of memoryafter some researching i have found that running on el6 kernel that means that each vps can take up to 1000/400 each cpu running intensive processes .. which means a total of 25% if the vps is running on maximum processing , am i right ?now i face a problem with high load , some of the vbs are running forums with plugins enabled and intensive mysql access .problem is whenever a VPS is causing a high load the whole node is also affected by it and the load average raise , which causes other VPSs problems .. slow them downwhy is this happening ? apart from resource management inside the vps it self , how do i prevent one vps causing load to not slow down the whole node and raising it's load average ?Thank you for your time
|
Openvz resource management
|
openvz;resources;load average
| null |
_unix.121318
|
I'm preparing CentOS 6.5 x86_64 system with following mount points/usr/local 10 GB or more ***/var 10 GB or more ***/root 200 MB or more ***/tmp 200 MB or more ***The mount points are created successfully but the system does not allow me to complete installation and issues an error:this mount point is invalid. The /root directory must be on / file systemKindly help in this regard.Regards,Asim
|
this mount point is invalid. The /root directory must be on / file system
|
linux;partition;centos
|
The current version of the Anaconda installer in the Centos 6.5 repository is 13.21.215-1.By checking out that source code, we can see that the installer has sanity checks for the storage configuration (starting at 1008 of storage/__init__.py).Part of those sanity checks assert that the following directories must be on the root filesystem and thus cannot be on separate mountpointsmustbeonroot = ['/bin','/dev','/sbin','/etc','/lib','/root', '/mnt', 'lost+found', '/proc']If you remove the separate mount you have created for /root (perhaps allocate the space to your / pointpoint if possible), the installer will likely allow you to continue.
|
_webapps.103651
|
I'm trying to see forms that I am currently submitting in CommCare via live preview and mobile device. I have the date filter on the Submit History report to today. Is there a reason my forms might not be showing up?
|
Missing forms from Submit History report in CommCare when the filter is set to today
|
commcare
|
The today date filter for this report on CommCare defaults to Eastern Standard Time. Therefore if you are in a time zone that puts you in a different day than the eastern coast of the United States, the default filter of today won't show your form submissions. For instance, if you are submitting forms at 7am in Cape Town and looking for them to show up in your Submit History report filtered to today, you won't see those submissions because the filter for today is technically referring to yesterday for your timezone.
|
_webmaster.63263
|
I always make a footer and a header and include them in my php pages but I am not sure the impact of doing this for SEO.The header has only a main banner and the navigation menu, all the metatags including page description are unique to each page.So if I made just one header file and one footer file to php include on all pages , does it affect SEO?
|
SEO impact when using php include
|
seo;php
|
No, this will not affect you. PHP is processed on the server side and then it sends out HTML to the user agent. In this case the user agent is Google. So all Google sees is the HTML of your pages. It doesn't know nor care how you generate your pages.
|
_unix.284961
|
If I print a png file to a cups-pdf printer, using lp, the pic is adjusted to the page size (i'm assuming), even though fitplot is false.lp ~/Pictures/tux-db.pngHere is output of lpoptions:copies=1 device-uri=cups-pdf:/ finishings=3 fitplot=false job-hold-until=no-hold job-priority=50 job-sheets=none,none marker-change-time=0 mirror=false number-up=1 orientation-requested=3 ppd-timestamp=* printer-commands=AutoConfigure,Clean,PrintSelfTestPage printer-info=PDF printer-is-accepting-jobs=true printer-is-colormanaged=true printer-make-and-model='Generic CUPS-PDF Printer' printer-state=3 printer-state-change-time=1464004024 printer-state-reasons=none printer-type=8450124 printer-uri-supported=ipp://localhost:631/printers/PDF scaling=100The generated pdf is here.If I open the png file with Image Viewer, and print it, I get a correct size pdf (small picture), so the printer is capable of printing the correct size. Pdf file here.What is the right option to use?Using ubuntu 14.04.Just to clear, the final goal is to use cups API in my own sw, with the correct option, so I can print images without rescaling (to avoid resizing small images to large sizes).
|
Print image to cups-pdf without rescaling
|
printing;cups
|
It turns out that the answer is the scaling parameter. I thought the parameter was relative to the image, but turns out it is relative to the page.So setting scaling=0 will print the image on its native size. It is possible to also manipulate it using the ppi (pixel per inch), and the natural-scaling parameter. More info here.
|
_unix.237090
|
lrwxrwxrwx. 1 tomcat tomcat 27 Oct 17 00:23 workThis is my file(link) I want to go inside a directory within it to rm a file and then copy the new one. But it says permission denied and does not show any link. How can I do what I want.
|
file with permission lrwxrwxrwx does not show any link on ls -l command
|
files;permissions;symlink
| null |
_unix.11217
|
So, basicallyTHIS LINE WOULD BE DELETEDand(THIS LINE WOULD ALSO BE DELETED)butIndeed, THIS LINE WOULD NOT
|
sed one-liner to delete any line that does not contain lowercase letters
|
sed;awk
|
Quite a few ways. Think negatively:sed '/[a-z]/!d' # !x runs x if the pattern doesn't matchgrep -v '[a-z]' # -v means print if the regexp doesn't matchawk '!/[a-z]/' # !expr negates expr
|
_unix.31254
|
I want to download the contents of this page for study purposes. How can I download only this directory?
|
How to download an entire directory from a webserver?
|
web;download
|
This should work:wget -r --no-parent --reject index.html* http://lxr.post-tech.com/source/?v=iphone-u-boot-2010-0512
|
_softwareengineering.351060
|
If you look at the source code of a website such as Facebook, you'll see many classes as such:<div class=_cy6 _2s24><div class=_4kny><div class=uiToggle _8-a _1kj2 _4d1i _-57 _5-sk id=u_0_8><a data-hover=tooltip data-tooltip-content=Quick Help data-onclick=[["HelpLiteFlyoutBootloader","loadFlyout"]] class=_59fc href=# rel=toggle role=button data-tooltip-delay=500 aria-haspopup=true aria-controls=u_0_7 aria-label=Help Center data-testid=contextual_help_jewel_button><div class=_59fb _tmz></div></a><div id=u_0_7 class=__tw _8-b _tdb toggleTargetClosed uiToggleFlyout><div class=beeperNub></div><div id=fbHelpLiteFlyout><div id=fbHelpLiteFlyoutLoading class=_5uco><img class=_26y2 img src=https://www.facebook.com/rsrc.php/v3/yb/r/GsNJNwuI-UM.gif alt= width=16 height=11 /></div></div>To the naked eye, they appear to be gibberishly named classes. However, I am unsure as to why they are obfuscated. I don't see a class named something as post with any meaningful classes on child elements. Is there a reason for this practice? I see many large websites such as Facebook conducting this pattern, and am unsure if there is a reason.
|
Why does Facebook obfuscate the names of CSS classes?
|
javascript;programming practices;web applications;css;patterns and practices
|
It's called minification. It makes the CSS files (and potentially Javascript files too) smaller, requiring less bandwidth to download. This can make a significant difference in performance, especially for wireless devices.
|
_webapps.41894
|
Since I cannot restrict the Empty Trash option in Google Drive for my Google Apps users would creating one account that is only used to setup as shared folders in drive work? Can I then give all users an edit option to prevent them from accidentally or maliciously deleting files? This account would always have the file in its trash, correct? Is there any other way?
|
Google Drive only apps account prevents emptying the trash
|
google drive
| null |
_codereview.19141
|
I have 3 nested NSEnumeration loops, which are used to get the textfields of a custom cell, in a custom table in a custom view in a controller.How can I make this code more readable and more optimizated?- (void) textfieldsOperations:(APOperation)op{ __block int Valid = 0; __block NSArray *sub = _Table.subviews; __block MyCell *cell = nil; __block UIView *view = nil; __block NSMutableArray *ret = [NSMutableArray arrayWithCapacity:5]; [sub enumerateObjectsUsingBlock:^(id c, NSUInteger index, BOOL *stop) { if ( [c isKindOfClass:[MyCell class]] ) { cell = c; [cell.subviews enumerateObjectsUsingBlock:^(id v, NSUInteger index, BOOL *stop) { if ( [v isKindOfClass:[UIView class]] ) { view = v; [view.subviews enumerateObjectsUsingBlock:^(id t, NSUInteger index, BOOL *stop) { if ( [t isKindOfClass:[MyTextField class]] ) { MyTextField *txt = t; switch ( op ) { case APOperationClear: // something with txt break; case APOperationEnableSearch: // something with valid break; case APOperationGetText: // something with txt break; case APOperationPos: { // something with txt break; } } } }]; } }]; } }]; //[...] }
|
Optimize nested enumerate blocks?
|
performance;array;objective c
| null |
_codereview.27421
|
Is this a good implementation for Equals and GetHashCode for a base class in C#? If it's not good enough, can you suggest improvements for it, please?public abstract class Entity<TKey> //TKey = Type of the Key{ private string FullClassName; private bool KeyIsNullable; private Type BaseClassType; private bool KeyIsComplex; public abstract TKey Key { get; } //Key of the object, which determine it's uniqueness public Entity() { FullClassName = GetType().FullName + #; KeyIsNullable = typeof(TKey).IsAssignableFrom(typeof(Nullable)); BaseClassType = typeof(Entity<TKey>); KeyIsComplex= !typeof(TKey).IsPrimitive; } public override bool Equals(object obj) { bool result = BaseClassType.IsAssignableFrom(obj.GetType()); result = result && ( ( ( !KeyIsNullable || (Key != null && ((Entity<TKey>)obj).Key != null ) ) && Key.Equals(((Entity<TKey>)obj).Key ) ) // The key is not nullable, or (it's nullable but) both aren't null, and also equal || ( KeyIsNullable && Key == null && ((Entity<TKey>)obj).Key == null ) ); // Or the key is nullable, and both are null return result; } public override int GetHashCode() { if ((KeyIsNullable&& Key == null) || (!KeyIsNullable&& Key .Equals(default(TKey)))) { return base.GetHashCode(); } string stringRepresentation = FullClassName + ((KeyIsComplex)? Key.GetHashCode().ToString() : Key.ToString()); return stringRepresentation.GetHashCode(); }}Example of a derived class:public class Foo : Entity<int>{ public virtual int FooId { set; get; } public virtual string FooDescription { set; get; } public override int Key { get { return FooId; } }}Specific and special details to the proposal:Any instance of a derived class is considered equal to a instance of the base class if they have the same key.The key could be null.If the key of the current class and the key of the comparing object are both null, the two objects are considered equal. This is because I am planning to handle just one new object at a time, and if the key is nullable, it will be null for the new object. So if I have two instances with a null key, I will consider them as the same entity.
|
Implementation of Equals and GetHashCode for base class
|
c#;inheritance;null
|
//TKey = Type of the Key//Key of the object, which determine it's uniquenessIf you're going to use comments like these, it's useful to use XML documentation comments instead, so that you can see them in IntelliSense.Also, you should try to keep your comments grammatically correct, though I understand that's not always easy, especially if you're not a native speaker.public Entity(){ FullClassName = GetType().FullName + #; KeyIsNullable = typeof(TKey).IsAssignableFrom(typeof(Nullable)); BaseClassType = typeof(Entity<TKey>); KeyIsComplex = !typeof(TKey).IsPrimitive;}I think it doesn't make much sense to store these in each instance. If your profiling shows that retrieving these values on each call slows down your code, store at least the last three values in static fields (you could initialize them from a static constructor).Also, KeyIsNullable will be always false, because Nullable is a static class that's distinct from Nullable<T>. (But it doesn't matter anyway, see below.)bool result = BaseClassType.IsAssignableFrom(obj.GetType());According to ReSharper, you could instead use BaseClassType.IsInstanceOfType(obj). (I had no idea such method existed.)But this check means that for example two different types deriving from Entity<int> with the same key will compare as equal. I don't think that's what you want, you should compare the type against GetType() and you should make sure that the types are exactly equal. This is especially true since in such case, the two objects will compare as equal, but will have different hash codes, which makes your code wrong.Also, your code will throw an exception when obj is null, you should add a check against that.result = result && ( This monstrous expression doesn't make much sense to me (and that's not just because it's hard to understand). For nullable value types, Equals() works fine, you don't need all this gymnastics.if ((KeyIsNullable&& Key == null) || (!KeyIsNullable&& Key .Equals(default(TKey)))){ return base.GetHashCode();}This code indicates that if the Key has its default value, you want to use reference equality. But there is no indication of that in your Equals(). You have to decide what exactly does equal mean for your type and keep that definition consistent across Equals() and GetHashCode().Also, again, you don't need special code for nullable value types.string stringRepresentation = FullClassName + ((KeyIsComplex)? Key.GetHashCode().ToString() : Key.ToString());return stringRepresentation.GetHashCode();I haven't seen hash code include the type before. It could make sense if you're using hash-based collections that can contain different types with the same key values, though doing that is not very common, I think.Though if you want to do that, I would use the hash code of GetType() instead of dealing with type name.Also, there is no reason to use strings here, simply combining the hash codes (e.g. using XOR) is enough.With all these changes, your code will look like this:/// <typeparam name=TKey>Type of the Key</typeparam>public abstract class Entity<TKey>{ /// <summary> /// Key of the object, which determines its uniqueness /// </summary> public abstract TKey Key { get; } public override bool Equals(object obj) { if (obj == null) return false; if (obj.GetType() != GetType()) return false; bool sameKey = Key.Equals(((Entity<TKey>)obj).Key); if (sameKey && Key.Equals(default(TKey))) return ReferenceEquals(this, obj); return sameKey; } public override int GetHashCode() { if (Key.Equals(default(TKey))) return base.GetHashCode(); return GetType().GetHashCode() ^ Key.GetHashCode(); }}
|
_webapps.50990
|
When I open draw.io, it does not connect to my Google Drive, and when I click on the button Connect to Google Drive, a pop-up window appears for a fraction of a second and then disappears.The result is that I cannot access all my drawings.I have tried with both Firefox and Windows IE, and experienced the same thing in both. I then logged-in to Google Drive and tried to open one of my drawings with draw.io, but it does not work (stuck loading)Is this a wider issue than just with my account?
|
Connecting to Google Drive using Draw.io
|
google drive;draw.io
| null |
_unix.15153
|
Are there any solutions similar to AIX smit for Linux based OSes?Basically this would be some kind of 'terminal menu-driver' script collection perhaps using ncurses for doing things that system administrators regurarly do.
|
Smitty like solution under Linux or BSD?
|
linux;software rec;administration
|
This would be a per-distro thing. For example, Debian used to have lots of ncurses based wizards for various administration tasks particularly setting up new software. I'm not sure how much they do that any more.However in general this does not fit the linux model of development where all the software pieces are developed independently. Any central admin interface would require constantly keeping in sync with the options being developed on all possible related software projects. In the AIX, Unix or even BSD worlds much more of the system software is developed together as part of the main distro project. this makes writing central administration systems make more sense. In the Linux world any attempt to do so is far more likely to break things than fix them. It's generally better to administer each piece of software in the way that software was designed to be used.
|
_datascience.9195
|
Are there any papers published which show differences of the regularization methods for neural networks, preferably on different domains (or at least different datasets)?I am asking because I currently have the feeling that most people seem to use only dropout for regularization in computer vision. I would like to check if there would be a reason (not) to use different ways of regularization.
|
Are there studies which examine dropout vs other regularizations?
|
neural network;computer vision;convnet;regularization;dropout
| null |
_webapps.73803
|
Named ranges are duplicated when their sheet is duplicated. However, protected ranges are not.I have 40 protected ranges on a sheet that I need to replicate 6 times, so I'm not really looking forward to defining 240 ranges. Is there a way to keep the protected ranges when you replicate a sheet, or otherwise import them to the replicated sheet?
|
How to copy permissions across sheets?
|
google spreadsheets
| null |
_webmaster.5577
|
If I override default link href with onclick and ajax, for example link <a href=/mypage>, so onclick I load mypage through ajax, if javascript is disabled, or its a text browser or bot, I let go to /mypage, is this good enough for SEO as having regulat /mypage link with no javascript and ajax?What I want is to have same content as without ajax, but to load it via ajax for better user expirience. Wonder if that can be achieved with same SEO effect?I assume for google bot it will be the same, but this page /mypage will not appear in analytics, no referers...maybe that is the weakness of this approach?
|
Overriding link action with ajax - SEO
|
javascript;ajax;seo;hyperlink;page
| null |
_webmaster.35426
|
I've got my URL however some of the strings would contain &. Obviously I can't use them as best practice so I've replaced them with +.However if I encoded my & instead it would become %26. How would a search engine see that? Would it see %26 as a & so still bring back the URL or would it just see it as a %26? ie.Would www.example.com/sweet?m&m show as that, or would they see it as www.example.com/sweet?m%26m
|
How would a search engine see url encoded characters?
|
seo;google;search engines
| null |
_unix.11451
|
I'm using Debian Mint and my internet has worked everywhere on earth (Home, Mcdonalds, other peoples homes) except at school where I really need it. It will always see the networks and will 'try' to connect but will never be able to do so.Occasionally it will work if I reboot, and disconnect networking, and reconnect, but only occasionally. It works perfectly if I dual boot to Windows so it's kinda frustrating.Power management is off, and Tx power is at 15db.
|
Cannot connect to wireless at School
|
wifi;linux mint;networking
| null |
_codereview.46492
|
I was eventually going to add another computer and more options to this (i.e., Rock-paper-scissors-lizard-Spock) but I wanted to make sure I was using the best practice for this type of game. Any help would be appreciated. # The traditional paper scissors rock gameimport osdef clear(): os.system(clear)clear()print (\n\nPaper, Rock, Scissors Game -(Best of five games))x = 0 ; l = 0 ; w = 0 ; d = 0 ; lt = 0 ; wt = 0 ; dt = 0while x < 5: x = x + 1 import random class Computer: pass comp_is = Computer() comp_is.opt = ('r','p','s') comp_is.rand = random.choice(comp_is.opt) if comp_is.rand == 'r': comp = 'rock' elif comp_is.rand == 'p': comp = 'paper' else: comp = 'scissors' class Human: pass human_is = Human print human_is.player = raw_input(' Enter your choice of\n r\ for rock\n p for paper or\n s for scissors ... ') print class Result: pass Result_is = Result if comp_is.rand == human_is.player: print (draw - computer chose , comp) print d = d + 1 dt = dt + 1 elif comp_is.rand == 'r' and human_is.player == 'p': print ( player beats computer -computer chose , comp) print w = w + 1 wt = wt + 1 elif comp_is.rand == 'p' and human_is.player == 's': print ( computer chose , comp) print ( player beats computer-because scissors cuts paper) print () w = w + 1 wt = wt + 1 elif comp_is.rand == 's' and human_is.player == 'r': print ( computer chose , comp) print ( player beats computer-because rock breaks scissors) w = w + 1 wt = wt + 1 else : print ( computer wins - computer chose , comp) print l = l + 1 lt = lt + 1 if x == 5: print () print () print ( games won ... , w) print ( games lost ... , l) print ( games drawn ... , d) print () print ( Running total overall of games won ... , wt) print ( Running total overall of games lost ... , lt) print ( Running total overall of games drawn ... , dt) print () w = 0 ; l = 0 ; d = 0 again = input('Do you want to play again y for yes, n for no .. ') if again == 'y': x = 0 else: print if lt > wt: print (You are a miserable loser,\nYou have lost more than you have won,\nPoor show indeed ) print ('finish')
|
Rock, Paper, Scissors in Python
|
python;beginner;game;rock paper scissors
|
There is much to improve. I recommend you read PEP 8, the official Python style guide. It includes many important tips like:Use consistent 4-space indentationMultiple statements on the same line are discouragedFurthermore:You should use words instead of single letters for your variable names. All those variables like x, l, w, d, lt, wt, dt aren't self-explaining. What is their purpose? Instead: count_rounds, count_losses, count_wins, count_draws, .Your usage of object oriented features is extremely weird. Get rid of all classes for now.Instead of x = x + 1 write x += 1.Your code is really complicated because it munges together the user interface (prompting the user for choices, displaying results) with the actual logic of your program. Put the logic into separate functions, e.g.def beats(choice_a, choice_b): if choice_a == 'rock' and choice_b == 'scissors': return 'smashes' if choice_a == 'scissors' and choice_b == 'paper': return 'cuts' if choice_a == 'paper' and choice_b == 'rock': return 'wraps' else: return NoneThis could be used asdef result_string(computer, player): verb = beats(computer, player) if verb: return computer beats player because %s %s %s % (computer, verb, player) verb = beats(player, computer) if verb: return player beats computer because %s %s %s % (player, verb, computer) return drawwhich in turn could be used as print(result_string(computer_choice, player_choice)).Please try to fix these issues and to clean up your code, then come back and ask a new question for a second round of review.
|
_cogsci.15274
|
Different areas of the inner ear (the cochlea) are sensitive to different acoustic frequencies. Hence, the cochlea basically performs a fast Fourier transform on the audio signal. This spectral information is subsequently sent to the auditory cortex. But how does the cochlea encodes the intensity of an acoustic stimulus?
|
How does the inner ear encode sound intensity?
|
neurobiology;perception;sensation;neurophysiology;hearing
| null |
_codereview.114374
|
I have a code here that counts the number of fruits from Column B to Column AF (31 days).I used a switch with cases from 1 to 31. I'd like my code to be simpler. 31 case statements is just too long. private void button1_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel.Application OfficeExcel; Microsoft.Office.Interop.Excel._Workbook OfficeWorkBook; Microsoft.Office.Interop.Excel._Worksheet OfficeSheet; var dtpMonth = dateTimePicker1.Value.ToString(MMMM); var dtpYear = dateTimePicker1.Value.Year; var MonthYear = dtpMonth + - + dtpYear; var dtpDay = dateTimePicker1.Value.Day; try { OfficeExcel = new Microsoft.Office.Interop.Excel.Application(); OfficeExcel.Visible = true; int appletotal = Convert.ToInt32(lblappletotal.Text); int bananatotal = Convert.ToInt32(lblbananatotal.Text); int orangetotal = Convert.ToInt32(lblorangetotal.Text); int grapestotal = Convert.ToInt32(lblgrapestotal.Text); switch (dateTimePicker1.Value.Day.ToString()) { case 1: OfficeWorkBook = (Microsoft.Office.Interop.Excel._Workbook)(OfficeExcel.Workbooks.Add()); OfficeSheet = (Microsoft.Office.Interop.Excel._Worksheet)OfficeWorkBook.ActiveSheet; OfficeSheet.Cells[3,1] = apple; OfficeSheet.Cells[4,1] = banana; OfficeSheet.Cells[5,1] = orange; OfficeSheet.Cells[6,1] = grapes; OfficeSheet.Cells[2, 2] = dtpDay + dtpMonth ; OfficeSheet.Cells[3, 2] = appletotal; // variable OfficeSheet.Cells[4, 2] = bananatotal; OfficeSheet.Cells[5, 2] = orangetotal; OfficeSheet.Cells[6, 2] = grapestotal; OfficeExcel.Visible = true; OfficeWorkBook.SaveAs(D:\\fruits\\ + MonthYear + .xls, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); break; case 2: OfficeWorkBook = OfficeExcel.Workbooks.Open(D:\\fruits\\ + MonthYear + .xls); OfficeSheet = (Excel.Worksheet)OfficeWorkBook.Worksheets.get_Item(1); OfficeSheet.Cells[2, 3] = dtpDay + dtpMonth; OfficeSheet.Cells[3, 3] = appletotal; OfficeSheet.Cells[4, 3] = bananatotal; OfficeSheet.Cells[5, 3] = orangetotal; OfficeSheet.Cells[6, 3] = grapestotal; OfficeExcel.Visible = true; OfficeWorkBook.Save(); case 3: OfficeWorkBook = OfficeExcel.Workbooks.Open(D:\\fruits\\ + MonthYear + .xls); OfficeSheet = (Excel.Worksheet)OfficeWorkBook.Worksheets.get_Item(1); OfficeSheet.Cells[2, 4] = dtpDay + dtpMonth; OfficeSheet.Cells[3, 4] = appletotal; OfficeSheet.Cells[4, 4] = bananatotal; OfficeSheet.Cells[5, 4] = orangetotal; OfficeSheet.Cells[6, 4] = grapestotal; OfficeExcel.Visible = true; OfficeWorkBook.Save(); break; case 4: OfficeWorkBook = OfficeExcel.Workbooks.Open(D:\\fruits\\ + MonthYear + .xls); OfficeSheet = (Excel.Worksheet)OfficeWorkBook.Worksheets.get_Item(1); OfficeSheet.Cells[2, 5] = dtpDay + dtpMonth; OfficeSheet.Cells[3, 5] = appletotal; OfficeSheet.Cells[4, 5] = bananatotal; OfficeSheet.Cells[5, 5] = orangetotal; OfficeSheet.Cells[6, 5] = grapestotal; OfficeExcel.Visible = true; OfficeWorkBook.Save(); break; . . . so On..... }
|
short or simple solution for putting values from label to column in excel
|
c#;excel;winforms
| null |
_softwareengineering.43347
|
I have a class that will read from Excel (C# and .Net 4) and in that class I have a background worker that will load the data from Excel while the UI can remain responsive. My question is as follows: Is it bad design to have a background worker in a class? Should I create my class without it and use a background worker to operate on that class? I can't see any issues really of creating my class this way but then again I am a newbie so I figured I would make sure before I continue on.I hope that this question is relevant here as I don't think it should be on stackoverflow as my code works, this just a design issue.
|
Is It Wrong/Bad Design To Put A Thread/Background Worker In A Class?
|
c#;design;multithreading;class design
|
Should I create my class without it and use a background worker to operate on that class?Yes, you should. And I will tell you why - you are violating the Single Responsibility Principle. By tightly coupling the class that accesses the excel doc with how it accesses the excel doc, you eliminate the ability for the controller code (any code that uses this) to do it a different way. How different, you may ask? What if the controller code has two operations that take a long time but wants them to be sequential? If you allowed the controller the ability to handle the threading, it can do both long-running tasks together in one thread. What if you want to access the excel doc from a non-UI context and don't need it to be threaded? By moving the responsibility of threading out to the caller, you allow more flexibility of your code, making it more reusable.
|
_unix.307875
|
There are about 10000 files under a given directory. Are there any command that can help me randomly pick 1000 files from it and put them into another directory. The picked files should be removed from the original directory.
|
Randomly select a proportion of files from a given directory
|
linux;command line;files;mv
|
If you have shuf, it will easily let you do what you want, provided that no filename has a newline character in it, and there are no subdirectories:mapfile -t sample < <(shuf -n 1000 -e given_directory/*)mv ${sample[@]} other_directoryIf there are subdirectories, you could get the list of files by using find instead of the glob. Or you could oversample and filter. find will also help you deal with files which could have newlines in their names (which is really a bad idea, but that doesn't necessarily mean that you can ignore the possibility), since you can use the -print0 action combined with the -z flag to shuf. For example,find given_directory -type f -print0 |shuf -z -n 1000 |xargs -0 mv -t other_directorymv -t is a (very useful) Gnu extension which lets you provide the destination directory at the beginning of the command line, which works nicely with the xargs/find -exec model of putting multiple arguments at the end of the command line.
|
_unix.350659
|
I would like to know why 6 is the number/code/signal associated with the reboot command in init 6. I mean the history/stories/legend reasons, not in a technical way... If it was a list related reason or maybe a graphic thing about recursivity/circle-ouroboros/101 alike number. I'm starting reading Design of the UNIX Operating System by Maurice Bach, but didn't find yet a reason or idea.
|
Why is 'init 6' the reboot command? (historic reasons)
|
signals;history;init;documentation
| null |
_datascience.15526
|
if I have a training data set and I'll train a Naive Bayes Classifier on it and I got an attribute value which has the probability zero. How to handle this if I later want to predict the classification on new data. The problem is, if there is a zero in the calculation the whole product becomes zero, no matter how many other values I got which maybe would find another solution.Example:$P(x|spam=yes) = P(TimeZone = US | spam=yes) \cdot P(GeoLocation = EU | spam = yes) \cdot ~ ... ~ = 0,004 $$P(x|spam=no) = P(TimeZone = US | spam=no) \cdot P(GeoLocation = EU | spam = no) \cdot ~ ... ~ = 0 $ The whole product becomes $0$ because in the training data the attribute TimeZone US is always Yes in our small trainings data set. How can I handle this? Should I use a bigger set of training data or is there another possibility to overcome this problem?
|
How to handle a zero factor in Naive Bayes Classifier calculation?
|
classification;naive bayes classifier
|
An approach to overcome this 'zero frequency problem' in a Bayesian setting is to add one to the count for every attribute value-class combination when an attribute value doesnt occur with every class value. So, for example, say your training data looked like this:$$\begin{array}{c|c|c|} & \text{Spam} = yes & \text{Spam} = no \\ \hline\text{TimeZone} = US & 10 & 5 \\ \hline\text{TimeZone} = EU & 0 & 0 \\ \hline\end{array}$$$ P(\text{TimeZone} = US | \text{Spam} = yes) = \frac{10}{10} = 1$$P(\text{TimeZone} = EU | \text{Spam} = yes) = \frac{0}{10} = 0$Then you should add one to every value in this table when you're using it to calculate probabilities:$$\begin{array}{c|c|c|} & \text{Spam} = yes & \text{Spam} = no \\ \hline\text{TimeZone} = US & 11 & 6 \\ \hline\text{TimeZone} = EU & 1 & 1 \\ \hline\end{array}$$$ P(\text{TimeZone} = US | \text{Spam} = yes) = \frac{11}{12}$$P(\text{TimeZone} = EU | \text{Spam} = yes) = \frac{1}{12}$
|
_softwareengineering.246225
|
Having a larger WinForms application with several classes I currently pass references to several central objects around to function calls.This leads to more method parameters.Example:public static class Program{ private static MyCentral _central; ...}...public class SomeController{ public object SomeFunction(MyCentral central) { // Do something with the MyCentral instance. }}Now I'm asking myself whether I should ditch this approach and instead use singletons for those central objects so that everyone can always access these objects and I do not need to pass them around anymore.Example:public static class Program{ public static MyCentral Central { get; private set; } ...}...public class SomeController{ public object SomeFunction() { // Do something with the Program.Central singleton. }}My question:Are there any rules-of-thumb whether the singleton approach or the passing objects around approach should be prefered?
|
Passing central objects around or having global instances?
|
design;class design;singleton
|
The rule of thumb is: Always pass around, never use the traditional singleton pattern approach.The problem kind of solves itself if you use a dependency injection framework.Using public statics will make testing harder, strongly couple your components, and make dependencies between your classes harder to see.
|
_unix.178811
|
I recently migrated a RAID1 from a CentOS 5 system to a CentOS 6 system and ever since when I attempt to perform a check I get the following:$ echo 'check' > /sys/block/md127/md/sync_action-bash: /sys/block/md127/md/sync_action: Read-only file systemThis actually shows up from a CRON too, specifically, /etc/cron.d/raid-check. this is included in the mdadm RPM:$ rpm -ql mdadm | head -5/etc/cron.d/raid-check/etc/rc.d/init.d/mdmonitor/etc/sysconfig/raid-check/lib/udev/rules.d/63-md-raid-arrays.rules/lib/udev/rules.d/65-md-incremental.rulesHere I'm running the same command that's used by the CRON:$ raid-check/usr/sbin/raid-check: line 96: /sys/block/md127/md/sync_action: Read-only file systemThis typically runs once a week and sends an email which is what originally alerted me to the issue. But at any rate I'm at a loss why this RAID seems to be unable to be checked.The RAID seems fine on inspection though.$ cat /proc/mdstat Personalities : [raid1] md127 : active raid1 sda1[0] sdb1[1] 976759936 blocks [2/2] [UU]unused devices: <none>I point this out only because while googling I found this thread regarding a bug in mdadm but this was for a older version of mdadm.Debian Bug report logs - #380746checkarray: E: /sys/block/md_d1/md/sync_action not writeable.Version info$ lsb_release -dDescription: CentOS release 6.6 (Final)$ rpm -q mdadmmdadm-3.3-6.el6_6.1.x86_64$ mdadm --versionmdadm - v3.3 - 3rd September 2013
|
Unable to check a mdadm RAID1 array, says the file system's read only?
|
mdadm;software raid
|
Thanks to @frostschutz's comment the issue appears to be due to /sys being mounted as readonly (ro). This was evident through this command:$ cat /proc/mounts |grep syssysfs /sys sysfs ro,seclabel,relatime 0 0none /proc/sys/fs/binfmt_misc binfmt_misc rw,relatime 0 0This appears to be an issue with docker. I found this issue titled: sysfs goes into readonly mode with host networking #7101. A workaround to the issue is to remount /sys read-write (rw) like so:$ mount -o remount,rw /sysLooking through the issues in docker's issue tracker it's unclear to me whether this is intentionally being left this way or not. The workaround is good enough for me for the time being but this seems like a bug to me.
|
_codereview.119873
|
I'm currently populating before and after arrays with indexes, based on a number provided. If the input going in is an int, there will be three indexes (left, middle and right). If it is a decimal, there will just be two (left, right). There will me a maximum of three indexes to sort into a maximum of two arrays (before and after). To understand, here is some expected input/output:input: 1output: before [] after [0, 1, 2]input: 1.5output: before [] after [1, 2]input: -3.4output: before [3, 4] after []input: 0output: before [1] after [0, 1]Essentially, the input index gets floored and ceiling'd (or, in the case of a whole number, their next/previous integers are used along with the original input). If any of the resulting integers are below 0, they get put in the before array, but their index is made absolute, otherwise they go into the after array. If they do get put into the before array, then they are put in to reverse order, such that they remain sorted in numerical order.I have the below working code. But I feel like I could do much better. How would the community go about optimising this?var input = document.getElementById('input');var button = document.getElementById('button');var ouput = document.getElementById('output');function getOutput(input) { var left = Math.floor(input); var right = Math.ceil(input); var middle; var before = []; var after = []; if (right == left) left--, middle = left + 1, right = left + 2; if (left < 0) before.unshift(Math.abs(left)); else after.push(left); if (middle < 0) before.unshift(Math.abs(middle)); else if (typeof middle == 'number') after.push(middle); if (right < 0) before.unshift(Math.abs(right)); else after.push(right); return {before: before, after: after}; }function buttonPressed () { var i = parseFloat(input.value); var msg = 'not a number'; if (!isNaN(i)) { var o = getOutput(i); msg = 'before [' + o.before.toString() + '] ahead [' + o.after.toString() + ']'; } ouput.innerHTML = msg; }<input id=input type=text><input id=button type=button value=get onclick=javascript:buttonPressed();><br><br><div id=output style=font-family: monospace;></div>My interest is in the getOutput method. The other stuff is for demonstration purposes.UpdateI have adjusted the expected output and the code from the original question, after being prompted to rethink from the comments.
|
Creating indexes from a theoretical decimal/int, splitting into before and after arrays
|
javascript;sorting;floating point
|
The code in the question seems to have adequate complexity for the getOutput function. Some small hints may be given, like:do not use comma-expressions and decrement,initialize middle with null and check for it with !== instead of typeof,also, I do not like comparing undefined middle with 0.The current code is more or less readable.As for optimizations, one observation is that apart from [-1, 1] range, all other inputs always use the same alternative, making unnecessary to check left, right and middle individually. (eg, if right < 0, then so are middle and lift). How much optimization it really brings is hard to tell. If input numbers are almost always large, then making separate branch and constructing an array directly [left, middle, right] may make the code more efficient.The near-zero case may need more conditions, of course (or just some kind of lookup for ready arrays - as the number of cases is small).If you want a more compact code, maybe something like this can be done: tmparray = ((right == left) ? [left-1, left, left+1] : [left, left+1]);And after that push/unshift in a loop for each tmparray element. Not sure this will be faster though, but at least may be more readable. (left may be renamed to lower, and right calculated inline only in the condition).
|
_unix.366311
|
I use CentOS. I have ATI card that the website says supports RHEL 7.0 and 7.1. Currently it works in CentOS 7.2 as well but not in CentOS 7.3. Is it possible to use kernel of 7.2 (excluding from update via yum.conf) with other packages of 7.3? When I did that last time it did not work, the system did not boot so I am cautious about attempting to do that once again.
|
CentOS minor update with previous kernel
|
centos;upgrade;ati
| null |
_codereview.150864
|
I've created a little text based game in the console. the game randomly chooses two primitive data types and the user is asked to pick which has the larger memory allocation. I've tried to use TDD to create this application however I have noticed places where I may have tried to do too much at once. I've tried to refactor as much as possible and to extract methods/classes out to keep things clear and also keep to the SRP. But i'd like to know if there is anything you think I missed out or any tips on how to improve.Specifically I found it difficult to test the UserInputFromConsole Class as it takes input through System.in.UserInputFromConsole:package org.FaneFonseka.LearningGames2;import java.io.InputStream;import java.util.InputMismatchException;import java.util.Scanner;/** * Created by Fane on 09/12/2016. */public class UserInputFromConsole implements UserInput { private Scanner reader; UserInputFromConsole(InputStream in) { reader = new Scanner(in); } @Override public int getUserInputInt() throws InputMismatchException { //todo not sure how to test this return reader.nextInt(); } @Override public String getUserInputString() { //todo not sure how to test this return reader.nextLine(); }}I had it implement a UserInput interface so that I could swap it out when testing other classes which are dependent on it, such as the GameRunner Class.GameRunner:package org.FaneFonseka.LearningGames2;import java.io.InputStream;import java.util.InputMismatchException;/** * Created by Fane on 03/12/2016. */class GameRunner { private final Picks picks; private int numberOfQuestions; private User user; GameRunner(User user, Picker randomPrimitivePicker) { this.user = user; picks = new Picks(randomPrimitivePicker); } void askAllQuestions(UserInput userInput) { setNumberOfQuestions(userInput); System.out.println(Let's Begin!); System.out.println(); System.out.println(Enter your answer as a number); //questionsAskedCount+=; for (int i = 0; i <= numberOfQuestions - 1; i++) { getAnswer(userInput); } } private void getAnswer(UserInput answerAsInt) { picks.setPicks(); int answerNumber = 0; boolean isValidNumber = true; while (isValidNumber) { whichPickIsBiggerPrompt(); try { answerNumber = answerAsInt.getUserInputInt(); isValidNumber = false; } catch (InputMismatchException e) { System.out.println(Not valid number); } } switch (answerNumber) { case 1: user.addAnswerToList(picks.firstPickGreaterThanSecondPick()); break; case 2: user.addAnswerToList(picks.secondPickGreaterThanFirstPick()); break; case 3: user.addAnswerToList(picks.firstPickIsSameSizeAsSecondPick()); break; default: System.out.println(false); user.addAnswerToList(false); break; } } void setNumberOfQuestions(UserInput userInput) { System.out.println(How many questions would you like?); this.numberOfQuestions = userInput.getUserInputInt(); System.out.println(ok); } int getNumberOfQuestions() { return this.numberOfQuestions; } private void whichPickIsBiggerPrompt() { System.out.println(Which is bigger?); System.out.println(1. + picks.getFirstPick().name + ?); System.out.println(2. + picks.getSecondPick().name + ?); System.out.println(3. + Both the same?); } public static void main(String args[]) { System.out.println(Welcome to the Java primitive data types quiz!); InputStream in = System.in; UserInput userInput = new UserInputFromConsole(in); User user = new User(); user.setName(userInput); Picker randomPrimitivePicker = new RandomPrimitivePicker(); GameRunner game1 = new GameRunner(user, randomPrimitivePicker); game1.askAllQuestions(userInput); System.out.println(Your score is + user.getScore(game1.getNumberOfQuestions())); System.out.println(Thanks For playing!); }}GameRunnerTest:package org.FaneFonseka.LearningGames2;import org.junit.Before;import org.junit.Test;import java.util.Stack;/** * Created by Fane on 03/12/2016. */public class GameRunnerTest { private GameRunner gameRunner; private Picker fixedPrimitivePicker; private PrimitiveDataType primitive1; private PrimitiveDataType primitive2; private PrimitiveDataType primitive3; private Stack<PrimitiveDataType> primitiveDataTypeStack; private PrimitiveDataType primitive5; private PrimitiveDataType primitive4; private PrimitiveDataType primitive6; private User user; @Before public void setup() { user = new User(); primitiveDataTypeStack = new Stack<PrimitiveDataType>(); primitiveDataTypeStack.push(primitive6 = new PrimitiveDataType(float, 64)); primitiveDataTypeStack.push(primitive6 = new PrimitiveDataType(char, 8)); primitiveDataTypeStack.push(primitive5 = new PrimitiveDataType(char, 8)); primitiveDataTypeStack.push(primitive4 = new PrimitiveDataType(long, 64)); primitiveDataTypeStack.push(primitive3 = new PrimitiveDataType(int, 32)); primitiveDataTypeStack.push(primitive2 = new PrimitiveDataType(boolean, 1)); primitiveDataTypeStack.push(primitive1 = new PrimitiveDataType(boolean, 1)); fixedPrimitivePicker = new Picker() { public PrimitiveDataType pick() { return primitiveDataTypeStack.pop(); } }; gameRunner = new GameRunner(user, fixedPrimitivePicker); } @Test public void setNumberOfQuestionsTest() { UserInput fakeUserInput = new UserInput() { @Override public int getUserInputInt() { return 1; } @Override public String getUserInputString() { return null; } }; gameRunner.setNumberOfQuestions(fakeUserInput); assert gameRunner.getNumberOfQuestions() == 1; } @Test public void whenUserIsAskedWhichDataTypeIsBiggerLargerDataTypeIsChosenReturnsTrueTest() { UserInput fakeUserAnswers = new UserInput() { @Override public int getUserInputInt() { return 2; } @Override public String getUserInputString() { return null; } }; gameRunner.askAllQuestions(fakeUserAnswers); assert user.getAnswersList().get(0); } @Test public void whenUserIsAskedWhichDataTypeIsBiggerSmallerDataTypeIsChosenReturnsFalseTest() { UserInput fakeUserInput1 = new UserInput() { @Override public int getUserInputInt() { return 1; } @Override public String getUserInputString() { return null; } }; gameRunner.askAllQuestions(fakeUserInput1); assert !user.getAnswersList().get(0); }}I had an idea to use a stack as the InputStream (similar to what I did in the GameRunnerTest) to get fixed output, but i'm finding it difficult to find a way to do this.EDIT: decided to focus on one main problem I'm facing in the code.
|
Java primitive data types quiz
|
java;quiz
| null |
_computerscience.3742
|
tl;dr: Math problem in projective geometry: How does one find some 4x4 camera matrix that gives a projection as illustrated below, such that points A,B,C,D are somewhere on the edges of the unit box (e.g. OpenGL normalized device coordinates), and the corners of the unit box fall somewhere reasonable along the rays EA, EB, EC, ED?( extra tags: dlt direct-linear-transform projections opengl homography projective-space perspectivity collineation ndc normalized-device-coordinates matrix svd singular-value-decomposition least-squares camera camera-matrix projective-geometry projective-space homogeneous-coordinates )elaboration:Given a quadrilateral ABCD within the the viewport, I think there exists a unique(?) transformation that maps it back to a rectangle. As seen in the image below: the quadrilateral ABCD in the viewport acts as a physical 'window', and if we map it back to a rectangle it will appear distorted.(the box on the right represents NDC, which I talk about later)The goal is to quickly obtain the image on the right. We could raytrace every point to obtain the image (which I've done), but I would prefer to use OpenGL or other projective techniques because I wanted to take advantage of things like blending, primitives, etc.first attempt (hover to show): I believe I can solve the problem of finding the 3x4 camera matrix that makes the 3+1-dimensional homogeneous coordinate in 3-space (on the left) and projects it down to the 2+1 dimensional homogeneous coordinates in 2-space (on the right). One can solve this using the direct linear transformation to get a system of equations Ba=0 for the unknown entries a of the camera matrix, and solving the system using singular value decomposition (SVD). I would take the vectors EA, EB, EC, ED (where E is your physical eye or the camera in world-space) as points in the pre-image, and (0,0), (1,0), (1,1), (0,1) or something as the points in the post-image, and each pair of points would give a few linear equations to plug into the SVD. The resulting matrix would map EA->(0,0) etc. (assuming there are enough degrees of freedom i.e. if the solution is unique, which I'm not sure about, see note[a].)But to my chagrin this is not how OpenGL works. OpenGL does not directly project 3d to 2d with a 3x4 matrix. OpenGL requires normalized device coordinates (NDC), which are three-dimensional points. After projecting into NDC, everything in the 'unit' box from (-1,-1,-1,1) to (1,1,1,1) is drawn; everything outside is clipped (since we're dealing with homogenerous coordinates: any point (x,y,z,w) will appear only on-screen only if the first three coordinates of (x/w,y/w,z/w,1) are within the unit box from -1 to 1).So the question becomes: does there exist some reasonable transformation that maps some weird-looking cuboid in homogeneous coordinates (specifically the cuboid drawn on the left, with ABCD (front points) and A'B'C'D' (back points, hidden behind front points)) to the unit cube, e.g. using a 4x4 matrix? How does one do it?what I've tried: I've tried something stronger: I made ABCD and A'B'C'D' look like a regular pyramidal frustrum (e.g. gl frustrum) (i.e. in this hypothetical setup, the image on the left would just have a black rectangle superposed on it, not a quadrilateral), and then used the DLT/direct linear transformation to solve for the alleged 4x4 matrix. However when I tried it, there did not seem to be enough degrees of freedom... the resulting 4x4 matrix did not map every input vector to every output vector. While using A,B,C,D,A' (5 pairs of pre-transform and post-transform vectors), I /almost/ get the result I want... the vectors are mapped correctly, but for example B',C',D' are mapping to (3,3,1,1) instead of (-1,-1,1,1) and are clipped away by OpenGL. If I try adding a sixth point (6 pairs of points for the 4x4 matrix to project), my solution seems degenerate (zeroes, infinites). How many degrees of freedom am I dealing with here, and is this possible with a 4x4 matrix mapping the usual 4vectors (3+1-dimensional homogeneous-coordinate vectors) that we know and love?random minor thoughts: (I'm guessing that it's not possible to map any arbitrary cuboid to any arbitrary cuboid with a 4x4 matrix, though I'm confused because I thought it was possible to map any convex quadrilateral to any other convex quadrilateral in 2d with some matrix like in, say, Photoshop?... can/can't this not be done with a projective transform? And how does it generalize to 3d? ...... Also given the failed attempt to find a 4x4 matrix, linear algebra says we should not expect an NxN matrix to map more than N linearly independent points to N target points in the best case, but I feel that somehow homogeneous coordinates cheat this because there is some hidden colinearity going on? I guess not?)another solution?: I guess one could also maybe do the following ugly thing, where you use a typical frustrum camera projection matrix, find the 2d points corresponding to the corners, then perform a 2d perspective distort homography, but if that were to happen after the pixels were rendered (e.g. photoshop) then there would be problems with resolution... maybe hypothetically one could figure out a matrix to perform this transformation on the XY-plane within NDC-space, then compose it with the normal frustrum-based matrix?(note [a]: Degree of freedom: ABCD can be further constrained to be the post-image of a projective transformation acting on a rectangle, if that is necessary... that is the black rectangle on the left could be said to be the result of projecting a picture frame clipart model)
|
How to unproject quadrilateral into rectangle?
|
opengl;projections;matrix
| null |
_softwareengineering.304438
|
I've recently worked on a reusable network service class for a service-aggregator iOS app. This class should retry a failed request if it was caused by expired user token. Plus, this class will be used between multiple contractors, who will create the aggregated services.Since the contractors might use different authentication methods, I create a interface / protocol for the class that will manage user's authentication. Here's a sample of my work (in Swift):BaseNetworkService.swiftclass BaseNetworkService {/**Request headers that will be used by this instance.*/internal var requestHeaders = [Content-Type: application/json]/**Request GET method to `URL` with passed `parameters`. Will send success responsein `next` and failure in `error` event of returned `RACSignal` instance.*/internal func GET(URL: String, parameters: [String: AnyObject]) -> RACSignal { // method implementation here}// Rest of HTTP methods here}AuthenticatedNetworkService.swiftclass AuthenticatedNetworkService: BaseNetworkService {/**Used to retrieve authentication-related request headersand refresh expired user token.*/private var authService: AuthenticationProtocolinit(authService: AuthenticationProtocol) { self.authService = authService}/**Request GET method to `URL` with passed `parameters`. Will send success responsein `next` and failure in `error` event of returned `RACSignal` instance.- note: If the request fails because of expired user token, this instance willrefresh current user token, and retry it once again.*/override func GET(URL: String, parameters: [String: AnyObject]) -> RACSignal { // method implementation here}// Rest of HTTP methods here }AuthenticationProtocol.swiftprotocol AuthenticationProtocol {/**Stores authentication header name in the `key`, and its value in itscorresponding `value`.*/internal var authenticationHeaders: [String: String] { get }/**Checks whether passed `error` caused by expired user token or not.*/func isErrorCausedByExpiredToken(error: NSError) -> Bool/**Refresh this instance's `authenticationHeaders`. It send `next:` event from returned `RACSignal` if the process succeeds, and `error:` otherwise.*/func refreshAuthenticatioHeaders() -> RACSignal}I was reading about Design Patterns while working on this, and created a Factory-like class for creating the AuthenticatedNetworkService for the aggregated services. Something around this:class AuthenticatedNetworkServiceFactory {/**Returns network service for Pizza Delivery service.*/class func PizzaDeliveryNetworkService() -> AuthenticatedNetworkService { let authService = PizzaDeliveryAuthenticationService() return AuthenticatedNetworkService(authService: authService)}/**Returns network service for Quick Laundry service.*/class func QuickLaundryNetworkService() -> AuthenticatedNetworkService { let authService = QuickLaundryAuthenticationService() return AuthenticatedNetworkService(authService: authService)}/**Returns network service for Cab Finder service.*/class func CabFinderNetworkService() -> AuthenticatedNetworkService { let authService = CabFinderAuthenticationService() return AuthenticatedNetworkService(authService: authService)}}Yet, after revisiting the GoF book, I found that Factory pattern was meant to return subclasses instead of a the main class. Since I was returning the main class (AuthenticatedNetworkService), is the AuthenticatedNetworkServiceFactory could be considered as a Factory? Or was it just a Helper class?
|
Could this class be considered as a Factory class?
|
design patterns;ios;swift language;factory
|
There is no clear answer to your question, because the definition of a factory is not cast in stone.Many people consider a factory to be anything that creates something for you so that you don't have to new it yourself. This is dumb in my opinion, but who am I to say that your factories are not true factories ?The real benefits of using a factory come when:The factory decides which particular subclass to instantiate (as Kilian Foth mentioned) so that you don't have to know the actual class of the object created.The factory is an abstract class itself, so not only you don't have to know the actual class of the object created, but you don't even know the actual class of the factory that you are invoking.So, according to these real benefits your factory is in fact a helper, but if you still go ahead and call it a factory I do not think anybody can blame you. By calling it a factory you are simply advertising the fact that this thang instantiates stuff.
|
_unix.316542
|
I'm using CentOS 7 and x11vnc version 0.9.13 (release 11.el7) for arch x86_64.I create Xvfb with two screens (:10.0 and :10.1) like this:sudo Xvfb :10 -screen 0 1366x768x24+32 -screen 1 1066x768x24+32 -br +bs -ac &I launch one x11vnc for the first screen:sudo x11vnc -display :10.0 -ncache 0 -rfbport 9999 -shared -forever -debug_ncache &I can use a VNC server to use that screen: it works: I open a Firefox on it, for instance.I kill that x11vnc and start another one, but for the second screen:sudo x11vnc -display :10.1 -ncache 0 -rfbport 10000 -shared -forever -debug_ncache &I can use a VNC server to use that screen: it works: I open a Chrome on it, for instance.Now, I kill x11vnc again, and then I start both servers, starting by the first screen and then the second:sudo x11vnc -display :10.0 -ncache 0 -rfbport 9999 -shared -forever -debug_ncache &sudo x11vnc -display :10.1 -ncache 0 -rfbport 10000 -shared -forever -debug_ncache &I can use a VNC server to use the first screen: it works and I see the Firefox window.BUT, trying to connect to the second VNC, brings a crash with the following trace:*** buffer overflow detected ***: x11vnc terminated======= Backtrace: =========/lib64/libc.so.6(__fortify_fail+0x37)[0x7fd434365597]/lib64/libc.so.6(+0x10c750)[0x7fd434363750]/lib64/libc.so.6(+0x10e507)[0x7fd434365507]/lib64/libvncserver.so.0(rfbProcessNewConnection+0x114)[0x7fd436d01764]/lib64/libvncserver.so.0(rfbCheckFds+0x3f8)[0x7fd436d01c98]/lib64/libvncserver.so.0(rfbProcessEvents+0x1d)[0x7fd436cf8c3d]x11vnc[0x4a0951]x11vnc[0x463d8a]x11vnc[0x410c0a]/lib64/libc.so.6(__libc_start_main+0xf5)[0x7fd434278b15]x11vnc[0x41b201]======= Memory map: ========00400000-00542000 r-xp 00000000 fd:00 14735 /usr/bin/x11vnc00741000-00742000 r--p 00141000 fd:00 14735 /usr/bin/x11vnc00742000-00788000 rw-p 00142000 fd:00 14735 /usr/bin/x11vnc00788000-00ad0000 rw-p 00000000 00:00 0 [heap]7fd42f627000-7fd42f63c000 r-xp 00000000 fd:00 38 /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f63c000-7fd42f83b000 ---p 00015000 fd:00 38 /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f83b000-7fd42f83c000 r--p 00014000 fd:00 38 /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f83c000-7fd42f83d000 rw-p 00015000 fd:00 38 /usr/lib64/libgcc_s-4.8.5-20150702.so.17fd42f83d000-7fd42f868000 rw-s 00000000 00:04 913866832 /SYSV00000000 (deleted)7fd42f868000-7fd42f892000 rw-s 00000000 00:04 913834063 /SYSV00000000 (deleted)7fd42f892000-7fd42f8bb000 rw-s 00000000 00:04 913801294 /SYSV00000000 (deleted)7fd42f8bb000-7fd42f8e3000 rw-s 00000000 00:04 913768525 /SYSV00000000 (deleted)7fd42f8e3000-7fd42f90a000 rw-s 00000000 00:04 913735756 /SYSV00000000 (deleted)7fd42f90a000-7fd42f930000 rw-s 00000000 00:04 913702987 /SYSV00000000 (deleted)7fd42f930000-7fd42f955000 rw-s 00000000 00:04 913670218 /SYSV00000000 (deleted)7fd42f955000-7fd42f979000 rw-s 00000000 00:04 913637449 /SYSV00000000 (deleted)7fd42f979000-7fd42f99c000 rw-s 00000000 00:04 913604680 /SYSV00000000 (deleted)7fd42f99c000-7fd42f9be000 rw-s 00000000 00:04 913571911 /SYSV00000000 (deleted)7fd42f9be000-7fd42f9df000 rw-s 00000000 00:04 913539142 /SYSV00000000 (deleted)7fd42f9df000-7fd42f9ff000 rw-s 00000000 00:04 913506373 /SYSV00000000 (deleted)7fd42f9ff000-7fd42fa1e000 rw-s 00000000 00:04 913473604 /SYSV00000000 (deleted)7fd42fa1e000-7fd42fe1f000 rw-p 00000000 00:00 07fd42fe1f000-7fd430220000 rw-s 00000000 00:04 912457765 /SYSV00000000 (deleted)7fd430220000-7fd430244000 r-xp 00000000 fd:00 4260 /usr/lib64/liblzma.so.5.0.997fd430244000-7fd430443000 ---p 00024000 fd:00 4260 /usr/lib64/liblzma.so.5.0.997fd430443000-7fd430444000 r--p 00023000 fd:00 4260 /usr/lib64/liblzma.so.5.0.997fd430444000-7fd430445000 rw-p 00024000 fd:00 4260 /usr/lib64/liblzma.so.5.0.997fd430445000-7fd4304a5000 r-xp 00000000 fd:00 4288 /usr/lib64/libpcre.so.1.2.07fd4304a5000-7fd4306a4000 ---p 00060000 fd:00 4288 /usr/lib64/libpcre.so.1.2.07fd4306a4000-7fd4306a5000 r--p 0005f000 fd:00 4288 /usr/lib64/libpcre.so.1.2.07fd4306a5000-7fd4306a6000 rw-p 00060000 fd:00 4288 /usr/lib64/libpcre.so.1.2.07fd4306a6000-7fd4306c7000 r-xp 00000000 fd:00 4383 /usr/lib64/libselinux.so.17fd4306c7000-7fd4308c7000 ---p 00021000 fd:00 4383 /usr/lib64/libselinux.so.17fd4308c7000-7fd4308c8000 r--p 00021000 fd:00 4383 /usr/lib64/libselinux.so.17fd4308c8000-7fd4308c9000 rw-p 00022000 fd:00 4383 /usr/lib64/libselinux.so.17fd4308c9000-7fd4308cb000 rw-p 00000000 00:00 07fd4308cb000-7fd4308d2000 r-xp 00000000 fd:00 4597 /usr/lib64/libffi.so.6.0.17fd4308d2000-7fd430ad1000 ---p 00007000 fd:00 4597 /usr/lib64/libffi.so.6.0.17fd430ad1000-7fd430ad2000 r--p 00006000 fd:00 4597 /usr/lib64/libffi.so.6.0.17fd430ad2000-7fd430ad3000 rw-p 00007000 fd:00 4597 /usr/lib64/libffi.so.6.0.17fd430ad3000-7fd430ada000 r-xp 00000000 fd:00 11023 /usr/lib64/librt-2.17.so7fd430ada000-7fd430cd9000 ---p 00007000 fd:00 11023 /usr/lib64/librt-2.17.so7fd430cd9000-7fd430cda000 r--p 00006000 fd:00 11023 /usr/lib64/librt-2.17.so7fd430cda000-7fd430cdb000 rw-p 00007000 fd:00 11023 /usr/lib64/librt-2.17.so7fd430cdb000-7fd430cdd000 r-xp 00000000 fd:00 13338 /usr/lib64/libXau.so.6.0.07fd430cdd000-7fd430edd000 ---p 00002000 fd:00 13338 /usr/lib64/libXau.so.6.0.07fd430edd000-7fd430ede000 r--p 00002000 fd:00 13338 /usr/lib64/libXau.so.6.0.07fd430ede000-7fd430edf000 rw-p 00003000 fd:00 13338 /usr/lib64/libXau.so.6.0.07fd430edf000-7fd430ee2000 r-xp 00000000 fd:00 4978 /usr/lib64/libkeyutils.so.1.57fd430ee2000-7fd4310e1000 ---p 00003000 fd:00 4978 /usr/lib64/libkeyutils.so.1.57fd4310e1000-7fd4310e2000 r--p 00002000 fd:00 4978 /usr/lib64/libkeyutils.so.1.57fd4310e2000-7fd4310e3000 rw-p 00003000 fd:00 4978 /usr/lib64/libkeyutils.so.1.57fd4310e3000-7fd4310f0000 r-xp 00000000 fd:00 5356 /usr/lib64/libkrb5support.so.0.17fd4310f0000-7fd4312f0000 ---p 0000d000 fd:00 5356 /usr/lib64/libkrb5support.so.0.17fd4312f0000-7fd4312f1000 r--p 0000d000 fd:00 5356 /usr/lib64/libkrb5support.so.0.17fd4312f1000-7fd4312f2000 rw-p 0000e000 fd:00 5356 /usr/lib64/libkrb5support.so.0.17fd4312f2000-7fd431368000 r-xp 00000000 fd:00 4770 /usr/lib64/libgmp.so.10.2.07fd431368000-7fd431567000 ---p 00076000 fd:00 4770 /usr/lib64/libgmp.so.10.2.0caught signal: 611/10/2016 17:24:00 deleted 43 tile_row polling images.Now, let's start x11vnc servers in reverse order: the second screen first and then the first screen:sudo x11vnc -display :10.1 -ncache 0 -rfbport 10000 -shared -forever -debug_ncache &sudo x11vnc -display :10.0 -ncache 0 -rfbport 9999 -shared -forever -debug_ncache &When I try to use VNC to reach the screen :10.1 (the second screen, but the first x11vnc launched), it works: I see the Chrome window.BUT, trying to connect to the screen :10.0 (last x11vnc launched), x11vnc crashes with the same trace as above (the first x11vnc server is still intact, running well).Note: I used RealVNC and TightVNC on Windows as clients.They both crash the second server.Note 2: running two separate Xvfb on displays :10 and :11 with only one screen (0) each, and pointing the two x11vnc servers to :10 and :11 leads to the same crash.Note 3: I ran both Xvfb and x11vnc as root. Running them as regular users also leads to the same crash.What did I wrong?Is there a way to start only one x11vnc server with two ports for both X11 screens?Is it a bug from x11vnc?
|
Xvfb with 2 screens and Two x11vnc servers (one for each screen): only the first one work
|
x11;vnc;xvfb;x11vnc
| null |
_softwareengineering.255426
|
I have a MyObject which has an x and y coordinate. as far as I can see, I can store it in three ways:class MyObject: def __init__(self, x, y): self.x = x self.y = yclass MyObject: def __init__(self, x, y): self.position = [x, y]class MyObject: def __init__(self, x, y): self.position = Coord(x,y) #Coord class created elsewhereIs there a best practise either way for this ?Where I'm thinking this is relevant, is when passing these coordinates into other methods:eg.myObj = MyObject(0,0)searchLocation(myObj.x, myObj.y)searchLocation2(myObj.position)
|
Should I store x,y coordinates as an array, a class object, or two variables?
|
python;variables
| null |
_unix.35864
|
I have a simple install with Debian as a guest in Virtualbox. I installed the resolvconf package.The resolv.conf file is this:# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTENnameserver 8.8.8.8nameserver 10.3.x.xnameserver 10.219.x.xI added nameservers through GUI (Applications/System Tools/Network Tools).The 8.8.8.8 is Google's DNS, and I want to use it to resolve internet addresses.The 10.3.x.x and 10.219.x.x are needed to resolve internal domains like teleportal.company.intra.When I have these nameservers in resolv.conf(and 8.8.8.8 is the first) I get an error when querying internal an address:> host teleportal.company.intra Host teleportal.company.intra not found: 3(NXDOMAIN)However if I explicitly set the second nameserver's address as a nameserver for nslookup, it works: nslookup teleportal.company.intra 10.3.x.xServer: 10.3.x.xAddress: 10.3.x.x#53teleportal.company.intra canonical name = proxy.dummy1.dummy2.private.Name: proxy.dummy1.dummy2.privateAddress: 172.27.x.xName: proxy.dummy1.dummy2.privateAddress: 172.27.x.xThe resolv.conf documentation states that the nameserver entries will be tried in order, if one of them cannot resolve the query. However if I turn debug on when using nslookup I see that nslookup does not even try other entries, only the first.If I change the order of the nameservers, then internal addresses will be resolved properly (nslookup still uses only the first entry).How can I set up 3 nameservers so that utilities will use all of them in order?
|
Domain resolve problem with stock Debian
|
debian;networking;dns
|
The resolv.conf list of nameservers is contacted one after the other only in case of timeout. Not when one nameserver authoritively says there is no such domain (NXDOMAIN). In your case the DNS 8.8.8.8 apparently does not know about teleportal.company.intra and the resolver stopped when it got the NXDOMAIN.If possible you should configure one DNS server and use it for all your resolution and let the DNS server decide how to resolve the name. If 10.3.x.x is your intranet DNS server it would likely be able to resolve the internet hostnames as well.Having said that, if you really want to relay the requests to different DNS servers based on the names you could try pdnsd. Its a caching DNS proxy program that one would run locally. Install it (apt-get install pdnsd) and add your localhost (127.0.0.1) to resolv.conf. In the pdnsd.conf configuration file you can specify which DNS servers to contact based on name matching. An example paragraph for your /etc/pdnsd.conf:server { label= google; exclude = .company.intra; ip = 8.8.8.8;}server { label= intra; include = .company.intra; ip = 10.3.x.x;}I've snipped out many other parameters in the above file. You should follow the documentation and the example config file that ships with debian package to setup your pdnsd.conf.
|
_webapps.89712
|
I am trying to pull the data from sheet 1, using the following formula:=query(Sheet1!A1:V1850,select I,A,D,E,F,H,R,S,L, M,O where I = 'TODAY()')So I do not have to enter todays date every time. How can it get it to pull that information?Here is the sheet.
|
Using a query to pull data for today
|
google spreadsheets
| null |
_unix.209665
|
A web page provides web-based ssh access to a linux machine. I'm using it one a Windows7 machine.While editing a file in vi, I want to repeadetly enter the following:j0nhd0This (1) goes to the next line, then (2) goes to the beginning of the line, then (3) goes to the next occurrence of the search term, then (4) moves one space to the left, then (5) deletes everything on the line to the left of that point. The 0 is just because I'm being really cautious.I thought what I'd do is write the followingj0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0j0nhd0and then copy that and paste it (while not in insert mode, of course) and it would do that operation on 15 lines, and then I could stare at it for a few seconds to make sure it didn't do anything wrong, before doing it the next time. Doing this a couple of hundred times would finish the job in minutes.But the interface won't let me copy and paste.So:Is there some way I can copy and paste?Should I do something intelligent instead? If so, what?
|
How (and whether) to copy and paste on an ssh web interface?
|
ssh;vi;clipboard
| null |
_softwareengineering.324179
|
I have a list of numbers (let's call it L) and I need to split this list into three groups (A, B, and C) such that the sum of the numbers in each group (sum(A), sum(B), sum(C)) is as close as possible to the sum(L) / 3.I'm sure it is an old problem, but I couldn't find a solution. The closest I got is to sort L, then put every third number starting from the first element into A, then put every third number starting from the second element into B, and put the rest into C. But it doesn't always work, especially if numbers in L are not uniformly distributed.
|
Sort numbers into three groups s.t. their sums are close to a certain value
|
algorithms
| null |
_unix.191319
|
I recently dist-upgraded my jessie box and several new packages were installed. It looks like there were no packages that depend on the new packages, as I could autoremove them flawlessly.An example is ruby, which was not installed before and got pulled in during the last upgrade. It is marked as auto.Is there something in apt that I don't understand? I don't want new, non-critical packages installed, unless I specify it.
|
Debian installs new, non depended on packages
|
debian;apt;package management
| null |
_computergraphics.5319
|
I'm rendering clouds by applying a texture map on the inside of an ellipsoid. From a distance (at the center of the cloud ellipsoid) the texture looks quite nice and reasonably realistic. See image below:The problem is that as I fly close to the boundary of the ellipsoid (into the cloud) I see the boundaries of each of the quads that make up the ellipsoid. See image below:Any suggestions on how to get around this artifact would be appreciated. I'm using 50 grid segments in both the azimuthal and polar directions of the ellipsoid which is actually truncated 10 degrees below the poles. The texture map uses GL_MODULATE with GL_LINEAR and GL_LINEAR_MIPMAP_LINEAR for the Min and Mag filters. The ellipsoid base colour is white, so that there are no shading issues involved. I have also verified that the texture coordinates are correctly applied and the normals are oriented correctly.Thanks in advance.I could cheat and use a lot of fog which would mimic actually flying into a cloud, but I'd really like to implement an elegant robust solution.
|
Hiding Boundaries with the Eye close to a set of adjacent textured quads
|
opengl;texture
| null |
_unix.123074
|
If I configure the swappiness value to another, from ex.: 60 to 0, then I always need to reboot the machine to the changes to take effect? Even when modifying with:sysctl -w vm.swappiness=0
|
Does changing of the swappiness need a reboot?
|
swap
|
Everything is well explained in the Wikipedia page you gave.# Set the swappiness value as rootecho 10 > /proc/sys/vm/swappiness# Alternatively, run this as a non-root user# This does the same as the previous commandsudo sysctl -w vm.swappiness=10# Verify the changecat /proc/sys/vm/swappiness10At this point, the system will manage the swap like you just configured it, BUT if you reboot NOW, your change will be forgotten and the system will work with the default value (assuming 60, meaning than it will start to swap at 40% occupation of RAM).You have to add the line below in /etc/sysctl.conf to keep your change permanently:vm.swappiness = 10Hope its more clear for you now!
|
_unix.303023
|
I have set up Raspbian Jessie on my RPi 3 Model B. I am using mobaXterm as a remote client. To start the Pi's GUI, when I type startx, the following output is returned:
|
startx command not working in MobaXterm
|
raspbian;gui;startx
| null |
_cstheory.7224
|
Are there any good examples of branching efficiency / prediction in quantum algorihms? Specifically suppose I have a set of CNOT gates one after the other that have the control line on the same line as the output of the CNOT gate?
|
Branch prediction in quantum algorithms
|
reference request;quantum computing
|
I agree with Artem, but perhaps this paper on a quantum circuit model for constructing conditional statements may be of some relevance to what you are trying to figure out.
|
_vi.2129
|
One way to select a buffer in vim could be to browse the buffers list, using standard commands as :ls, or with some external plugin / vimscript code to browse a list in a window.Let's say I want to jump to a buffer directly, as fast as possible.To traverse the buffer list in sequential mode, I now use <C-J> <C-K> shortcuts, having set in my .vimrc: move among buffers with CTRLmap <C-J> :bnext<CR>map <C-K> :bprev<CR>Another way (direct access) could be switching by number: knowing the buffer number, it is possible to switch directly by entering the buffer number followed by <C-^>. So if I want to switch to buffer number 5, I would press 5<C-^>.But this seem not working for me (I use vim 7.4 on ubuntu box, from a Windows guest, with Italian keyboard). I suspect that's because the ^ character is in the upper case key ^ in the Italian keyboard, so in fact to got ^ I need to press SHIFT-^ Any ideas?
|
Fastest way to switch to a buffer in vim?
|
vimrc;buffers
| null |
_bioinformatics.687
|
I have a gene expression count matrix produced from bulk RNA-seq data. I'd like to find genes that were not expressed in a group of samples and were expressed in another group.The problem of course is that not all effectively non-expressed genes will have 0 counts due to sequencing errors, or because they were expressed in a small subset of cells.I'm interested in solutions using R.
|
What methods are available to find a cutoff value for non-expressed genes in RNA-seq?
|
rna seq;r
| null |
_unix.123394
|
I want to using crontab to synchronize two directory between my linux partion and windows partion like this: 24 9 * * * cp -r /home/fan/Data /media/T/DataBut it would create a directory named Data in the origin Data directory, instead of copy the missing file from the source directory. I can't find a proper option at the cp manual to perfectly solve this. How can i copy the missing file(they do exist at the destination directory) from the src to dir. And by the way, seems it need the T disk have been mounted to run the copy command, how to automatically mount the disk when i need to run the command(the mount command should run as root). And how can i get the error message if the command have an exception?
|
how to synchronize two directory?
|
mount;file copy;synchronization
|
To address the error-message portion of the question, you might choose to run a script from cron instead of the system command.24 9 * * * /usr/local/sbin/sync_data.shCreate the file as /usr/local/sbin/sync_data.sh, giving root ownership and execute permission: chown root:root /usr/local/sbin/sync_data.sh && chmod 0700 /usr/local/sbin/sync_data.sh. The contents of the script are below. #!/usr/bin/env bashif [[ $EUID -ne 0 ]]; then echo This script must be run as root. 1>&2 exit 1fi# [ ] vs [[ ]] : http://mywiki.wooledge.org/BashFAQ/031DIR_SRC=/home/fan/Data/DIR_DST=/media/T/# A Boolean to know if running interactively or notB_INTERACTIVE=1if [[ -v PS1 ]] ; then # The -v PS1 method is for BASH 4.2+ $B_INTERACTIVE=0 # Could also use [[ -z $PS1 ]]fi# Send messages to console or syslog.function notify() { MESSAGE=$1 if [[ $B_INTERACTIVE -eq 1 ]] ; then echo $MESSAGE else # eval combines args into a single string for execution... eval $CMD_LOGGER -p err $0: $MESSAGE fi}# If the mount point if not currently mounted...if [[ $(grep $DIR_DST /proc/mounts) = ]] ; then # Try to mount the directory. mount $DIR_DST # Send a message to console or syslog. if [[ $? -ne 0 ]] ; then notify($0 failed to mount $DIR_DST) exit 1; fifi# Create a backup directory if it does not existif [[ -d $DIR_DST ]] ; then mkdir -p $DIR_DST 2>/dev/nullfi# A one-way sync to DIR_DST, deleting files that no longer exist in DIR_SRC...rsync -a --delete $DIR_SRC $DIR_DST &> /dev/null# Check the return status of last command...if [ $? -eq 0 ]; then notify($0: the rsync process succeeded.);else notify($0: the rsync process failed.);fi
|
_unix.91638
|
I am trying to execute the following:exec &>filenameAfter this I am not able to see anything including what I typed, alright.I frantically try , exec 1>&1 and exec 2>&2 , but nothing happens.Now , without killing the shell , how do I get back the output redirected to the stdout and error redirected to stderr respectively?Are the file descriptors the only way to refer standard [in|out]put and stderr?
|
Restoring output to the terminal after having issued exec &>filename
|
io redirection
|
After you run exec &>filename, the standard output and standard error of the shell go to filename. Standard input is file descriptor 0 by definition, and standard output is fd 1 and standard error is fd 2.A file descriptor isn't either redirected or non-redirected: it always go somewhere (assuming that the process has this descriptor open). To redirect a file descriptor means to change where it goes. When you ran exec &>filename, stdout and stderr were formerly connected to the terminal, and became connected to filename.There is always a way to refer to the current terminal: /dev/tty. When a process opens this file, it always means the process's controlling terminal, whichever it is. So if you want to get back that shell's original stdout and stderr, you can do it because the file they were connected to is still around.exec &>/dev/tty
|
_codereview.48308
|
Can you please verify my approach?using System; /* * In Factory pattern, we create object without exposing the creation logic. * In this pattern, an interface is used for creating an object, * but let subclass decide which class to instantiate. * */namespace FactoryMethod{Product (abstract) /* * Faza Class ITree * * */ public interface ITree { string GetTreeName(); }Products (concrete) /* * The Concrete class which implements ITree * * */ public class BananaTree : ITree { public string GetTreeName() { return My Name Is Banana Tree; } } /* * The Concrete class which implements ITree * * */ public class CoconutTree : ITree { public string GetTreeName() { return My Name Is Coconut Tree; } }Factory (abstract) /* * Faza Class TreeType * If you want you can add abstract class instad of faza class * * */ public interface TreeType { ITree GetTree(string tree); }Factory (concrete) /* * Concrete class which implements faza or concrete class * * */ public class ConcreteTreeType : TreeType { public ITree GetTree(string tree) { if (tree == COCONUT) return new CoconutTree(); else return new BananaTree(); } }Client code /* * main app. * * */ class Program { static void Main(string[] args) { TreeType oTreeType = new ConcreteTreeType(); ITree banana = oTreeType.GetTree(COCONUT); Console.WriteLine(banana.GetTreeName()); Console.ReadKey(); } }}
|
Factory Method implementation
|
c#;factory method
|
I personally would not rely on using magic strings.Magic strings are where you have taken something like a class/method/variable name and written it within a string, which is then used to identify the appropriate class/method/variableThis makes it hard to refactor later on if you change a class name, it is too easy to miss instances etc. Furthermore, the code that you currently have is case-sensitive. This might be by design, however, consider the following:var actuallyABananaTree = oTreeType.GetTree(Coconut);Even though the developer is specifying a coconut tree, he actually gets a banana tree. If the construction logic was changed to:if (tree.Equals(coconut, StringComparison.OrdinalIgnoreCase))You would then get the right tree type back. See StringComparison Enum for the comparison options.In that same construction logic, you are also not checking to see whether or not the parameter tree is a null reference. This might be something that you wish to consider adding, especially if you use the approach suggested above.Use of EnumsA better approach would be to use enums instead of magic strings. For example:enum MyTreeTypes { Coconut, Banana}Then in your construction logic, you can have: public ITree GetTree(MyTreeTypes tree){ switch (tree) { case MyTreeTypes.Coconut: return new CoconutTree(); default: return new BananaTree(); }}Using this approach ensures type safety and prevents problems of magic strings when refactoring etc. Also, you will compile time errors if you spell the tree type incorrectly
|
_unix.286277
|
I am pxe installing Ubuntu over a network, unattended. I want Ldap installed as well, but I need to provide the ldap db root password in the seed:ldap-auth-config ldap-auth-config/rootbindpw passwordHow can I keep this secure? I don't want to provide the plain text password on this line.
|
How to provide password in a secure way to LDAP seed?
|
openldap;pxe;preseed
|
AFAIK, it's not possible.You can preseed a pre-encrypted password for the root and the first user accounts. You can even do it with the grub password (and a few others too). e.g.d-i passwd/root-password-crypted password [MD5 hash]d-i passwd/user-password-crypted password [MD5 hash]d-i grub-installer/password-crypted password [MD5 hash]but that won't work for ldap-auth-config/rootbindpw because you need the unencrypted password in your LDAP config to connect to the LDAP server.The only thing I can suggest is to use a dummy password in the pre-seed, and script an ssh connection TO the freshly-built new machine, to set the real rootbindpw. This has to be a 'push' operation rather than a 'pull' otherwise you're just shifting the problem from preseed to somewhere else.
|
_codereview.41298
|
Is it possible to write this in fewer lines of code?If you input an integer it will output it as an ordinal number if it is less than 100. The below code works perfectly, but I'm wondering if it could be written more succinctly.def ordinal(self, num): Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc. self.num = num n = int(self.num) if 4 <= n <= 20: suffix = 'th' elif n == 1 or (n % 10) == 1: suffix = 'st' elif n == 2 or (n % 10) == 2: suffix = 'nd' elif n == 3 or (n % 10) == 3: suffix = 'rd' elif n < 100: suffix = 'th' ord_num = str(n) + suffix return ord_num
|
Producing ordinal numbers
|
python
|
def ordinal(self, num): Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc. Its suspicious that this seems to be a method rather than a free standing function. self.num = numWhy are you storing the input here? Given the purpose of this function that seems odd. n = int(self.num)Its doubtful that this is a good idea. What are you converting from? Converting to int should be really be done closer to whether this number came from. if 4 <= n <= 20:You've made this case larger than necessary, many of those would be correct even with out this test, and its not clear what so special about the range 4-20. suffix = 'th' elif n == 1 or (n % 10) == 1:You don't need the or. If n == 1, then that the second condition will be true anyways. suffix = 'st' elif n == 2 or (n % 10) == 2: suffix = 'nd' elif n == 3 or (n % 10) == 3: suffix = 'rd' elif n < 100: suffix = 'th'What happens if suffix is >= 100? You'll get an error. ord_num = str(n) + suffix return ord_numYou don't need to split this across two lines.Here is my version:# much code can be improved by using a datastructe.SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}def ordinal(num): # I'm checking for 10-20 because those are the digits that # don't follow the normal counting scheme. if 10 <= num % 100 <= 20: suffix = 'th' else: # the second parameter is a default. suffix = SUFFIXES.get(num % 10, 'th') return str(num) + suffix
|
_softwareengineering.354774
|
I've decided to write two methods, one providing general functionality, and one doing something more specific and narrow that can be done with the more complex method, though maybe with worse performance than a dedicated implementation.As an example, say that I want to write the methods map and iterate, with the former going over every element in a list and projecting it with a function, and the latter just going over every element in the list.map<T, S>(list : List<T>, f : T => S) : List<S>iterate<T>(list : List<T>, f : T => void) : voidI can either write the more complex method first and then call it using specific parameters in the simpler method (if that makes sense in terms of performance etc), or else write the simpler method first and do extra things in the more complex one (if that's possible).Which is the better option?
|
I've decided to write two methods, one doing a subset of the other. Which should I write first?
|
programming practices;api
| null |
_codereview.146534
|
I am learning the concepts of pattern matching in Scala. Following is an exercise for the same. The task is to define a show function that outputs an expression as a String. Following are the definitions involved:object Test { trait Expr case class Number(n: Int) extends Expr case class Sum(e1: Expr, e2: Expr) extends Expr case class Prod(e1: Expr, e2: Expr) extends Expr case class Var(name: String) extends Expr def nestOperations(e1: Expr, e2: Expr): String = { val l = e1 match { case Number(n) => n.toString case Prod(x, y) => nestOperations(x, y) case Var(s) => s case Sum(x, y) => ( + show(x) + + + show(y) + ) } val r = e2 match { case Number(n) => n.toString case Prod(x, y) => nestOperations(x, y) case Var(s) => s case Sum(x, y) => ( + show(x) + + + show(y) + ) } l + * + r } def show(e: Expr): String = e match { case Number(n) => n.toString case Sum(e1, e2) => show(e1) + + + show(e2)` case Prod(e1, e2) => nestOperations(e1, e2) case Var(s) => s } show(Sum(Number(1), Number(2))) show(Sum(Prod(Number(2), Var(x)), Var(y))) show(Prod(Sum(Number(2), Var(x)), Var(y)))}The expectation is that:show(Sum(Number(1), Number(2))) outputs 1 + 2show(Sum(Prod(Number(2), Var(x)), Var(y))) outputs 2 * x + yshow(Prod(Sum(Number(2), Var(x)), Var(y))) outputs (2 + x) * y The program achieves all of the above. I want to know if the nestOperations method can be simplified? Looks like a lot of repetitive code in there.
|
Displaying nested arithmetic expressions as a string using Scala pattern matching
|
beginner;scala;formatting
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.