id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_softwareengineering.238154
I'm just starting to learn about DDD, and I'm trying to understand how Bounded Contexts can be reconciled with client facing API's like REST/WebServices that use DTO's.For example: your system exposes it's API to the public with a standard WebService, with CRUD style operations for DTO objects with many fields defined via a WSDL. You create a Bounded Context to handle your Domain's business logic, using a non-anemic domain model - so that your domain objects don't simply have a bunch of setters and getters - instead they have methods defined using vocabulary from your ubiqitious language. How would one reconcile the difference between their web service DTO and the Bounded Context? It seems to me this could add a huge amount of complexity, and I'm wondering if there are some well defined ways to solve this.
DDD: How to reconcile a BoundedContext with REST/WebService DTO's?
architecture;domain driven design;enterprise architecture
The domain model is exposing commands and queries that can be used by the application. So the application (more specifically, the anti-corruption component) is responsible for taking the DTOs and re-expressing them in a form that the domain understands.If you are building your application from the domain model out, this is really straight forward: your DTOs just become representations of the commands themselves, and the api becomes a series of endpoints that handle those commands on behalf of the remote client. And the ubiquitous language ripples OUT from the domain model all the way to the clients.Trying to work inwards toward the domain model, from an api that exposes all changes as a CRUD operation... yeah, that's going to suck all the way. Essentially, you end up writing an anti corruption layer that reviews the proposed change, and tries to deduce from it the intent of the operation in the client. Bad news.The good news: if you are following Greg Young's recommendations on when to use DDD (ie: in the parts of your business where you have a competitive advantage), then there's a huge amount of leverage -- the value of improving the process may be high enough to offset the cost of deprecating the CRUD api.Horses for courses.
_opensource.5504
Our application currently has a licence which is not compatible with AGPL. We need to use a library licensed under AGPL (currently the best one for the job and the client would like us to use it).We thought about creating a web service using this library and we would license it under AGPL. Our application would directly depend on it to function properly. We wanted to create two svn repositories, one for the main project and one for the web service AGPL. To install our application, one would need to retrieve the code from both repositories, compile and run the applications.Does that count as a derivative work? Both source codes are open and publicly available. The main project needs to keep its license and cannot be licensed under AGPL.The web service can work as-is. One can just use it without the other project, it is just kind of useless since the web service validates metadata with rules only valid for the main project. The web service has default config files valid only for the main project but they can all be replaced by something completely unrelated. The main problem is that the web service contains default files which make me think that it is potentially a derivative work and if my main project uses this web service, it will be forced to be AGPL to be able to use the web service.Maybe that makes a different but the library AGPL is only used and not changed.Does anybody have an idea if I can use this AGPL web service and keep my license on the main project? If that's not the case, I will need to create another web service with a compatible license and keep the AGPL web service for internal use only.
Web service licensed under AGPL - distribution
derivative works;agpl 3.0
I assume a technical trick (like your web service idea) to avoid the intent of the license wouldn't work. But your assumption about compatibility is wrong.The EUPL (you stated in your answer that that is the licence your project is under) has statements of compatibility that work with the AGPL:EUPL v1.1 states compatibility to CeCILL v2.0, which states compatibility to GPL v2 or later and GPL v3 states compatibility to AGPL v3.EUPL v1.2 states compatibility to AGPL v3.You only need to comply with both licenses, not change your projects license.If both EUPL and AGPL licensed code were distributed together a potential licensee may discard the AGPL code if they wish to only comply with the license of the rest of the code.You may not convert AGPL to EUPL, i.e. you are not allowed to distribute a combination and tell your licensee only about the EUPL. The EUPL states how to do the conversion to other licenses via the compatibility mentioned above. What I called conversion here is an additional step that you don't need to do.
_cogsci.17755
I understood that ethanol increases Golgi cell firing by inhibiting the Na+/K+ ATPase channels, which makes granule cells receive more GABAergic input from the GABA that Golgi cells relase.Some paragraph in this paper are not clear to me. It says that ethanol increased spontaneous firing frequency and depolarized the membrane potential in the perforated-patch configuration, but also that ethanol does not significantly affect firing frequency or membrane potential response to current injection.How does it work?
How does alcohol increase firing rate in Golgi cells?
brain;alcohol
null
_webmaster.55947
example.com is hosted on IP address c.c.c.c at host1, no access any windows server admin at allblog.example.com is on IP a.a.a.a at host2, full access to Linux server admin, using WordPressSo basically, I can fiddle with subdomain all I want.I can't 301 redirect because the content on host 1 is an eCommerce site that I have no server control over. Can't put WordPress on it, can't run scripts, can't do anything on the server period.Is there a method to mask all the URLs on root blog.example.com so they appear as example.com/blog/ folder?They can't actually be sent to example.com/blog/ as that doesn't exist. It just needs to look to the surfer as if they are there.Can this be done with some kind of masking or something?Will this be better for SEO as hopefully search engines will see the blog in a directory on the main domain?
Can domain masking be used to move content from a subdomain to a subdirectory?
seo;url;subdomain;subdirectory
null
_webmaster.28739
Why does this website ranks so high in SERP and also has a PR 3. As the name suggests, it promotes black hat seo and the hits on the website are also very high. Why is it that such websites which openly claim to teach such black hat tactics rank so high?
Why do Blackhat SEO Websites Rank high?
blackhat
null
_codereview.40141
While trying to learn more about arrays in C, I tried to write some code that did the following:Read a stream of numbers from the stdin and store them in an arrayPrint the array in the order the numbers have been stored (i.e. print the original array)Print the array in reversed orderSort and print the arrayGiven an array, search whether an entered value is present in an array. If it is present, print the index otherwise print that the value doesn't exist.It will be great if somebody could review it and let me know how to improve it.#include <stdio.h>#include <stdlib.h>static void printArray(int array[],int startIndex,int endIndex){ if(startIndex < endIndex){ while(startIndex <= endIndex){ printf( %i ,array[startIndex++]); } }else{ while(startIndex >= endIndex){ printf( %i ,array[startIndex--]); } } printf(\n);}static int cmpfunc(const void * a,const void * b){ if(*(int*)a > *(int*)b) return 1; else return -1;}static void sortedArray(int* originalArray){ qsort((void*)originalArray,(sizeof(originalArray)/sizeof(originalArray[0])),sizeof(originalArray[0]),cmpfunc); return;}static int getIndex(int value,int array[],int size){ int i; for(i = 0;i < size;i++){ if(array[i] == value){ return i; } } return -1;}static void identifyTheIndices(int *arbitraryArray,int size){ char buf[10]; printf(Enter the value to search for..enter q to exit\n); while(fgets(buf,sizeof buf,stdin) != NULL){ if(buf[0] == 'q'){ break; } char *end; int value = (int) strtol(buf,&end,0); if(end != buf){ int currentIndex = getIndex(value,arbitraryArray,size); if(currentIndex > -1){ printf(Found the entered value %i at index %i\n,value,currentIndex); }else{ printf(Entered value %i doesn't exist\n,value); } } printf(Enter the value to search for..enter q to exit\n); }}int main(int argc,char **argv){ int counter = 0; if(argc > 1){ int originalArray[argc-1]; while(counter < (argc - 1)){ int currentValue = atoi(argv[counter+1]); printf(Reading input value %i into array \n,currentValue); originalArray[counter] = currentValue; counter++; } int size = sizeof(originalArray)/sizeof(originalArray[0]); printf(Printing out the original array\n); printArray(originalArray,0,size - 1); printf(Printing out the array in reverse\n); printArray(originalArray,size - 1,0); printf(Sorting the array in ascending order\n); qsort((void*)originalArray,size,sizeof(originalArray[0]),cmpfunc); printf(Printing out the sorted array\n); printArray(originalArray,0,size-1); int arr[] = { 47, 71, 5, 58, 95, 22, 61, 0, 47 }; identifyTheIndices(arr,sizeof(arr)/sizeof(arr[0])); } return 0;}
Array manipulation exercise
c;array
I disagree with @vishram0709 about taking values from the command line. Thereis nothing wrong with this. It is often useful to have the option of takingvalues from the command line; you can also prompt for input values if none aregiven on the command line.The fault he pointed out is caused by not validating the input values. Thesame error could occur if the value was input using scanf - and you saw inone of your earlier questions that scanf has its own issues. To check theinput values you can useerrno = 0;char *end;long value = strtol(string, &end, 0);if (errno == ERANGE) { perror(string); exit(EXIT_FAILURE);}The input values above are now long not int because strtol converts tolong and detects ERANGE based upon the size of the maximum possible long.If you wanted to detect over-range int values you could use:char *end;long value = strtol(string, &end, 0);if ((int) value != value) { fprintf(stderr, %s: Result too large\n, string); exit(EXIT_FAILURE);}Some other observations:printArray would be more normal taking a const start point and a length.static void printArray(const int array[], size_t n);and have another printReverseArray to print the reversed array.cmpfunc should return 0 if the items match.sortedArray is unused. It is also wrong in that(sizeof(originalArray)/sizeof(originalArray[0])),gives something meaningless when originalArray is a pointer.sizeof(originalArray) gives the size of the pointer, not the array thatit points to.Later on in main, you do it right, withint size = sizeof(originalArray)/sizeof(originalArray[0]);because here originalArray is a real array, not a pointer. But youalready had the array size (argc - 1), so this was unnecessary.the array parameter to getIndex should be const. But the function isunreliable, as it fails for negative numbers. To make it work you needto separate the return value from the success/failure.static int getIndex(int value, int array[], int size, int *index);add some spaces, eg after if, while, for, ; and , etc.you use the variable names array, originalArray and arbitraryArray toidentify essentially the same thing - an array. Don't use multiple namesfor equivalent things without good reason.Your reading loopint counter = 0;...int originalArray[argc-1];while(counter < (argc - 1)){ int currentValue = atoi(argv[counter+1]); printf(Reading input value %i into array \n,currentValue); originalArray[counter] = currentValue; counter++; }would be neater as:--argc;int array[argc];for (int i = 0; i < argc; ++i) { int v = atoi(argv[i + 1]); printf(Reading input value %i into array \n, v); array[i] = v;}shorter variable names are ok, and indeed preferable, where their scope isrestricted.
_vi.6523
I installed the YouCompleteMe(YCM) plugin and compiled it using the provided instructions, one after the other for all options excluding rust. Below is a reproduction of the commands I ran, the reason for running one after the other is that I got an error running them all together and it was easier to read when doing one by one.cd %USERPROFILE%/vimfiles/bundle/YouCompleteMepython install.py --clang-completer python install.py --omnisharp-completerpython install.py --gocode-completerpython install.py --tern-completer These ran, then I restarted my system due to another issue(was installing driver updates) when I then started GVim it crashed. I can open vim in the shell but it doesn't recognize Vundle and none of the plugins it manages are working there. I don't know if that was the case before, I haven't been using the shell for editing on Windows 10. Please advise!Response to commentsfruglemonkey - It was not configured for use on Windows, it was sourcing the .vimrc while I had opted to use the _vimrc purely for separation of concerns(keep the .vimrc for *nix environments and _ for windows) I copied the _vimrc to .vimrc and Vundle now works, though it doesn't recognise the colour scheme in use. I presume it isn't sourcing from the vim directory that GVim is using is all. Even now that it's sourcing properly it isn't recognizing Gundo or anything. I don't think it's related to the crashing of GVim, but I can provide more information regarding this on request.
gvim on windows - compiled ycm plugin now crashing on start
gvim;microsoft windows;plugin you complete me;crash
null
_cstheory.6713
Greg Egan in his fiction Dark Integers (story about two universes with two different mathematics communicating by means of proving theorems around of inconsistence in arithmetic) claims that it is possible to build general purpose computer solely on existing internet routers using only its basic functionality of packet switching (and checksum correction, to be precise).Is this possible, in principle?Update.To make the question more precise:What is an absolutely minimal set(s) of properties the router network must have that it will be possible to build general purpose computer on top of it?
Dark Integers: General Purpose Computations on Internet Routers
computability;universal computation
This can be helpful:Parasitic computing is an example of a potential technology that could be viewed simultaneously as a threat or healthy addition to the online universe. On the Internet, reliable communication is guaranteed by a standard set of protocols, used by all computers. These protocols can be exploited to compute with the communication infrastructure, transforming the Internet into a distributed computer in which servers unwittingly perform computation on behalf of a remote node. In this model, one machine forces target computers to solve a piece of a complex computational problem merely by engaging them in standard communication.In the parasitic computing site you can detailed information on how you can solve a 3-SAT problem using the checksum of TCP packets.Other useful links:Seminar report on parasitic computing by K.K.MaharanaNature's article on parasitic computing (Aug 2001)
_unix.261872
I am working on an embedded system and it uses udhcpc as its DHCP client. It seems to be running with the following parameters:/usr/share/udhcpc # ps | grep dhcp 5366 root 2432 S udhcpc -R -b -p /var/run/udhcpc.eth0.pid -i eth0I want to change the parameters or run my own DHCP client. I searched and I think it has something to do with ifup and /etc/network/interfaces. iface eth0 inet dhcpBut I don't see a way to modify the DHCP client.I would like to know how to change the parameter to udhcpc, andif it is possible to run my own DHCP client without killing udhcpc Thanks!
How is udhcpc executed and how to change it?
networking;dhcp;udhcpc
Your system seems a lightweight version/variation of Debian, based in busybox. busybox is typically used either for recovery medium, or for embedded systems with limited resources.For modifying the parameters, you can invoke udhcpc automatically. You can change /etc/network/interfaces as:iface eth0 inet manual pre-up /sbin/udhcpc -R -b -p /var/run/udhcpc.eth0.pid -i eth0As for running another DHCP client, you would have to install it; however you would have to switch it with udhcpc unless you have other interfaces.Bear in mind as udhcpc is part of busybox, it is just a link to a global binary that provices you a work environment, and as such, you wont save any space switching DHCP clients.
_unix.58969
How and where can I check what keys have been added with ssh-add to my ssh-agent ?
How to list keys added to ssh-agent with ssh-add?
ssh;key authentication;ssh agent
Use the -l option to ssh-add to list them by fingerprint.$ ssh-add -l2048 72:...:eb /home/gert/.ssh/mykey (RSA)Or with -L to get the full key in OpenSSH format.$ ssh-add -Lssh-rsa AAAAB3NzaC1yc[...]B63SQ== /home/gert/.ssh/id_rsaThe latter format is the same as you would put them in a ~/.ssh/authorized_keys file.
_vi.351
For example, if I have some JavaScript code like this:var widget = library() .chainCall1() .chainCall2() .chainCall3();If I use the = command to auto indent it, it comes out looking this this:var widget = library().chainCall1().chainCall2().chainCall3();Which isn't what I want. I want it to indent the chain calls like it originally was. How can I fix this?
Incorrectly indents JavaScript chain calls
indentation
I had the same problem - for the most part the JavaScript formatting done by vim is not bad, but in examples like the one you give it fails miserably.I've been using the vim-jsbeautify plugin to fix things where the vim indentation fails, and also to clean up ugly code other people have written. It works really well, you can run it on the whole file or just a region, and it's customisable using an EditorConfig file.
_codereview.153030
I'd like feedback on the class below, from the perspective of wanting to write professional code that I would be paid to create. I would appreciate comments on details such as commenting, naming and layout as well as the actual functionality.The code is a class which takes two arguments (directory and extension) and searches the directory for instances of files with the given extension. The context is of me practicing writing PHP with a view to getting a job doing so. There is the possibility of unknown unknowns implied in this question.<?php/** * Filters a directory by file-type */class DirectoryFilter{ /** * Returns a list of files in a given directory, * filtered by the extension of the files * * @param string $dirname * @param string $extension * * @return array */ public function filter(string $dirname, string $extension){ // store results in an array $results = []; // set path $path = __dir__ . /$dirname; // check directory exists if(is_dir(($path))){ foreach(glob($path/*.*) as $filename) { if(pathinfo($filename, PATHINFO_EXTENSION) == $extension){ array_push($results, $filename); } } return $results; } // Directory not found return false; }}$test = new DirectoryFilter();print_r ($test->filter('testdir', 'php'));
Directory Filter Class PHP
php;object oriented;file system
null
_unix.258868
On Debian 8 I cannot do the following command in /lib/systemd/system:root@foo:/lib/systemd/system# grep abc *grep: invalid option -- '.' Usage: grep [OPTION]... PATTERN [FILE]... Try 'grep --help' for more information.Why is that?
cannot grep abc * in /lib/systemd/system on Debian 8 Jessie
linux;debian
grep -- abc *As steeldriver1 mentionned, on my system there is indeed a file called -.slice in that directory.This leads to some unexpected behavior since linux treats such symbols as commands.For example mv - * tab * doesn't auto complete the filename but mv -- '- * tab * does.I figured it out by reading this page which explains it nicely. http://www.cyberciti.biz/faq/linuxunix-move-file-starting-with-a-dash/
_codereview.106860
public static int lastDigit(int a) { a = a % 10; if (a <= 0){ a *= -1; } return a;}This is my solution. The course hasn't taught if else yet, so I'm wondering if there is a way to do it without the if else.public static int lastDigit(int a) {a = a % 10;return a;}The problem with this is that it will not print the last digit of a negative number as a positive.
Return the last digit of a number
java;beginner
Use Math.abs() public static int lastDigit(int x) { return Math.abs(x % 10); }
_unix.156854
I installed CentOS 7, and noticed that I have rsa and ecdsa keys generated. I deleted all of them and rebooted the machine. I got a new pair of rsa and ecdsa keys. How does Linux generate the keys? When is ssh-keygen called..? I couldn't find the configuration for this...
How does Linux generate ssh keys after reboot?
ssh;key authentication
null
_unix.197766
./configure always checks whether the build environment is sane...I can't help but wonder what exactly a insane build environment is. What errors can this check raise?
./configure: What is an insane build environment?
compiling;configure
This comes from automake, specifically from its AM_SANITY_CHECK macro, which is called from AM_INIT_AUTOMAKE, which is normally called early in configure.ac. The gist of this macro is:Check that the path to the source directory doesn't contain certain unsafe characters which can be hard to properly include in shell scripts makefiles.Check that ls appears to work.Check that a new file created in the build directory is newer than the configure file. If it isn't (typically because the clock on the build system is not set correctly), the build process is likely to fail because build processes usually rely on generated files having a more recent timestamp than the source files they are generated from.
_vi.8087
I can't find info in help about whether it should or shouldn't turn on highlighting, but I find it strange that I have to press n or N after * or # to turn on search highlighting.How do I enable this in vim if that's 'normal' behaviour.I've got only these lines in my vimrc related to search highlighting.if !has('nvim') set smartcase set hlsearch highlight search terms set incsearch show search matches as you typeendif
Why doesn't search for word under cursor (* and #) turn on search highlighting and how do I enable it?
search;highlight
You can hook up the hlsearch command like so:nnoremap * :set hlsearch<CR>*nnoremap # :set hlsearch<CR>#And if you want to highlight the current word without moving the cursor you can add the N movement afterwards:nnoremap * :set hlsearch<CR>*Nnnoremap # :set hlsearch<CR>#N
_unix.252530
After an install of centos 7, I can't acces man pages :# man ls-bash: man: command not foundI tried to install it via yum # yum install man-pages... okBut again: # man ls-bash: man: command not foundWhy ?
How to install man pages on centos?
centos;man
In order to use the man command, you must also install the man package before or after the man-pages one# yum install man-pages... ok# yum install man... okNow man is installed# man lsNAME ls - list directory contentsSYNOPSIS ls [OPTION]... [FILE]...DESCRIPTION List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort. Mandatory arguments to long options are mandatory for short options too. ...
_codereview.118763
I've got a service that loads data from a databasr and it performs almost the same operations in all methods. private async Task GetProvenances() { try { var result = await commonRepository.GetProvenances(); if (result != null) { provenanceContainerService.Provenances = result; LogTo.Information(InitCacheMessages.STR_GET_PROVENANCES, result.Count); } else { LogTo.Warning(InitCacheMessages.STR_GET_PROVENANCES_FAILED); } } catch (Exception ex) { exceptionService.HandleException(ex); } } private async Task GetPkInstrumentMarkets() { try { var result = await commonRepository.GetPkInstrumentMarkets(); if (result != null) { pkInstrumentMarketContainerService.PkInstrumentMarkets = result; LogTo.Information(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS, result.Count); } else { LogTo.Warning(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS_FAILED); } } catch (Exception ex) { exceptionService.HandleException(ex); } } private async Task GetPkMotivations() { try { var result = await commonRepository.GetPkMotivations(); if (result != null) { pkMotivationsContainerService.PkMotivations = result; LogTo.Information(InitCacheMessages.STR_GET_PK_MOTIVATIONS, result.Count); } else { LogTo.Warning(InitCacheMessages.STR_GET_PK_MOTIVATIONS_FAILED); } } catch (Exception ex) { exceptionService.HandleException(ex); } }How can I refactor this so I don't have to repeat the same code for about 30 methods?UPDATE 1Hello,I've done this way this night protected async Task PerformInitInternal(string okMessage, string koMessage, Func<Task<IList<T>>> function) { try { var result = await function(); if (result != null) { Items = result; LogTo.Information(okMessage, result.Count); } else { LogTo.Warning(koMessage); } isInitialized = true; } catch (Exception ex) { ExceptionService.HandleException(ex); } }And I call it this way public override Task Init() { return PerformInitInternal(InitCacheMessages.STR_GET_COUNTERPARTS, InitCacheMessages.STR_GET_COUNTERPARTS_FAILED, () => CommonRepository.GetCrossSplitAsync()); }Can this be ok?
A redundant data service
c#;asynchronous
null
_codereview.96293
Is it appropriate for the class to subscribe to its own events like this? Should the class not subscribe, and instead move that code to before the OnEventName(Object args) methods call the EventHandlers? I'm curious if there are any downfalls to this approach.On one hand, with this approach I could remove all the null checks on the event-firing methods. On the other hand, what if another event down the road needs information from the event handling I have already added a subscription to. I.e. in the future a method needs the NetworkServer_Error method to have been guaranteed to have fired before it can work.I'm mostly concerned with the event logic here, not so much the implementations. None of these implementations are concrete, but I want to make sure I have done this part properly first.public class NetworkServer{ NetPeerConfiguration mainServerConfiguration; NetServer mainNetServer; List<NetConnection> connectedClients = new List<NetConnection>(); public NetworkServer() { mainServerConfiguration = new NetPeerConfiguration(SecretKey); mainServerConfiguration.AcceptIncomingConnections = true; mainServerConfiguration.Port = 5501; mainNetServer = new NetServer(mainServerConfiguration); // Wire up our events Error += NetworkServer_Error; DataReceived += NetworkServer_DataReceived; StatusChanged += NetworkServer_StatusChanged; ClientConnected += NetworkServer_ClientConnected; ClientDisconnected += NetworkServer_ClientDisconnected; } void NetworkServer_DataReceived(object sender, NetMessageEventArgs e) { Program.LogLine(Data recieved from: + e.Message.SenderConnection.RemoteEndPoint.ToString() + , Payload size: + e.Message.LengthBytes.ToString(), LoggingType.Information); } void NetworkServer_Error(object sender, MessageEventArgs e) { Program.LogLine(e.Message, LoggingType.Error); } void NetworkServer_ClientConnected(object sender, ConnectionEventArgs e) { if (!connectedClients.Contains(e.Connection)) { connectedClients.Add(e.Connection); Program.LogLine(New client discovered: + e.Connection.RemoteEndPoint.ToString(), LoggingType.Information); } } void NetworkServer_ClientDisconnected(object sender, ConnectionEventArgs e) { if (connectedClients.Contains(e.Connection)) connectedClients.Remove(e.Connection); Program.LogLine(Client lost: + e.Connection.RemoteEndPoint.ToString(), LoggingType.Information); } void NetworkServer_StatusChanged(object sender, StatusChangedEventArgs e) { switch (e.Connection.Status) { case NetConnectionStatus.Disconnected: OnClientDisconnected(new ConnectionEventArgs(e.Connection)); break; case NetConnectionStatus.Connected: OnClientConnected(new ConnectionEventArgs(e.Connection)); break; default: Program.LogLine(Unhandled StatusChanged: + e.Connection.RemoteEndPoint.ToString() + now + e.Connection.Status + ., LoggingType.Warning); break; } } public Task RunServer() { return Task.Run(() => { mainNetServer.Start(); DateTime started = DateTime.UtcNow; Program.LogLine(string.Format(The server was started on {0} at {1}., started.ToString(dd-MM-yyyy), started.ToString(HH:mm:ss.fffffff)), LoggingType.Important); while (true) { NetIncomingMessage msg; while ((msg = mainNetServer.ReadMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: OnError(new MessageEventArgs(msg.ReadString())); break; case NetIncomingMessageType.StatusChanged: OnStatusChanged(new StatusChangedEventArgs(msg.SenderConnection)); break; case NetIncomingMessageType.Data: OnDataReceived(new NetMessageEventArgs(msg)); break; default: Program.LogLine(Unhandled type: + msg.MessageType, LoggingType.Warning); break; } mainNetServer.Recycle(msg); } System.Threading.Thread.Sleep(1); } }); } void OnError(MessageEventArgs args) { if (Error != null) Error(this, args); } void OnStatusChanged(StatusChangedEventArgs args) { if (StatusChanged != null) StatusChanged(this, args); } void OnDataReceived(NetMessageEventArgs args) { if (DataReceived != null) DataReceived(this, args); } void OnClientDisconnected(ConnectionEventArgs args) { if (ClientDisconnected != null) ClientDisconnected(this, args); } void OnClientConnected(ConnectionEventArgs args) { if (ClientConnected != null) ClientConnected(this, args); } public event MessageEventHandler Error; public event NetMessageEventHandler DataReceived; public event StatusChangedEventHandler StatusChanged; public event ConnectionChangedEventHandler ClientConnected; public event ConnectionChangedEventHandler ClientDisconnected;}Here are the EventHandler delegates:public delegate void MessageEventHandler(Object sender, MessageEventArgs e);public delegate void NetMessageEventHandler(Object sender, NetMessageEventArgs e);public delegate void StatusChangedEventHandler(Object sender, StatusChangedEventArgs e);public delegate void ConnectionChangedEventHandler(Object sender, ConnectionEventArgs e);And, lastly, the EventArgs classes:public class ConnectionEventArgs : EventArgs{ private NetConnection _Connection; public NetConnection Connection { get { return _Connection; } } public ConnectionEventArgs(NetConnection client) { this._Connection = client; }}public class MessageEventArgs : EventArgs{ private string _Message; public string Message { get { return _Message; } } public MessageEventArgs(string message) { this._Message = message; }}public class NetMessageEventArgs{ public NetIncomingMessage Message { get; private set; } public NetMessageEventArgs(NetIncomingMessage message) { Message = message; }}public class StatusChangedEventArgs : ConnectionEventArgs{ public StatusChangedEventArgs(NetConnection client) : base(client) { }}Lastly, the Program class calling the NetworkServer:class Program{ static LoggingType logMessageTypes = LoggingType.All; static void Main(string[] args) { NetworkServer ns = new NetworkServer(); Task t = ns.RunServer(); t.Wait(); LogLine(Done!, LoggingType.Information); } public static void LogLine(string line, LoggingType type, ConsoleColor foreColor = ConsoleColor.Gray, ConsoleColor backColor = ConsoleColor.Black) { if (type <= logMessageTypes) { Console.ForegroundColor = foreColor; Console.BackgroundColor = backColor; Console.WriteLine(DateTime.UtcNow.ToString(O) + : + type.ToString() + : + line); } }}
Subscribing an Object to its own Events
c#;object oriented;.net;event handling
Basically the communication between objects is done in two different ways. A parent object is talking to its child object by using the child objects methods and properties.A child object is talking to its parent by using events. So I support @Thomas W with his answer. That beeing said, let us start with the refactoring ideas. The EventArgs classes You should either make the variables you use public readonly omiting the property or use autoimplemented properties with a private setter, because they are only read but never written. The NetMessageEventArgs class is missing the inheriting from EventArgs which should be done.See: https://stackoverflow.com/a/6816889/2655508 it allows people using your classes to use and handle generic *Handler(object sender, EventArgs e) declarations. If you don't inherit from EventArgs, then they have to use explicitly typed I don't see a reason to name the constructors parameter client in the ConnectionEventArgs and StatusChangedEventArgs classes. A more obvious name would be connection. The result of the applied changes (which aren't needed anymore, but posting them nevertheless) public class ConnectionEventArgs : EventArgs{ public NetConnection Connection { get; private set; } public ConnectionEventArgs(NetConnection connection) { Connection = connection; }}public class MessageEventArgs : EventArgs{ public string Message { get; private set; } public MessageEventArgs(string message) { Message = message; }}public class NetMessageEventArgs : EventArgs{ public NetIncomingMessage Message { get; private set; } public NetMessageEventArgs(NetIncomingMessage message) { Message = message; }}public class StatusChangedEventArgs : ConnectionEventArgs{ public StatusChangedEventArgs(NetConnection connection) : base(connection) { }}NetworkServer class mainNetServer and connectedClients should be made readonly so you won't accidently assign some new value to them. You should move the NetPeerConfiguration mainServerConfiguration; inside the constructor, because you only use it there. Or much better you should inject it into the constructor. Your class does not need to know how it is created nor should it need to create it. It only needs to use it. You should declare the NetPeerConfiguration mainServerConfiguration; and NetServer mainNetServer; explicitly private to make this more obvious. Instead of using a List<NetConnection> I would like to encourage you to use a HashSet<NetConnection>. In this way you don't need to check if item is in the set, you can just call Add() and don't have to worry about it beeing already in the set. based on your comments to @Thomas W's answer the only object which is using the provided events is the object itself. So you could use simple methods leaving aside the events. you should use a ILogger interface which should be injected to the constructor instead of using a public static method of the calling object. with using string.Format() you can make the messages easier to read and could make them constant if you want to. The result of the applied changes public class NetworkServer{ private readonly NetServer mainNetServer; private readonly HashSet<NetConnection> connectedClients = new HashSet<NetConnection>(); public NetworkServer(NetPeerConfiguration mainServerConfiguration) { mainNetServer = new NetServer(mainServerConfiguration); } private void ProcessReceivedMessage(NetIncomingMessage message) { string msg = Data recieved from: {0}, Payload size: {1} LogMessage(msg, LoggingType.Information, message.SenderConnection.RemoteEndPoint, message.LengthBytes); } private void LogMessage(string message, LoggingType loggingType, params Object[] par) { message = FormatMessage(message, par); Program.LogLine(message, loggingType); } private String FormatMessage(string message, params Object[] par) { if (par.Length == 0) { return message; } return string.Format(message, par); } private void ProcessErrorMessage(string message) { LogMessage(message, LoggingType.Error); } private void AddClient(NetConnection connection) { if (connectedClients.Add(connection)) { string msg = New client discovered: {0}; LogMessage(msg, LoggingType.Information, connection.RemoteEndPoint) } } private void RemoveClient(NetConnection connection) { connectedClients.Remove(connection); string msg = Client lost: {0}; LogMessage(msg, LoggingType.Information, connection.RemoteEndPoint) } private void ProcessStatusChangedMessage(NetConnection connection) { switch (connection.Status) { case NetConnectionStatus.Disconnected: RemoveClient(e.Connection); break; case NetConnectionStatus.Connected: AddClient(e.Connection); break; default: LogMessage(Unhandled StatusChanged: {0} now {1}., LoggingType.Warning, e.Connection.RemoteEndPoint, e.Connection.Status); break; } } public Task RunServer() { return Task.Run(() => { mainNetServer.Start(); DateTime started = DateTime.UtcNow; LogMessage(The server was started on {0} at {1}., LoggingType.Important, started.ToString(dd-MM-yyyy), started.ToString(HH:mm:ss.fffffff)); while (true) { NetIncomingMessage msg; while ((msg = mainNetServer.ReadMessage()) != null) { switch (msg.MessageType) { case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: case NetIncomingMessageType.WarningMessage: case NetIncomingMessageType.ErrorMessage: ProcessErrorMessage(msg.ReadString()); break; case NetIncomingMessageType.StatusChanged: ProcessStatusChangedMessage(msg.SenderConnection); break; case NetIncomingMessageType.Data: ProcessStatusChangedMessage(msg); break; default: LogMessage(Unhandled type: {0}, LoggingType.Warning, msg.MessageType); break; } mainNetServer.Recycle(msg); } System.Threading.Thread.Sleep(1); } }); }}
_codereview.128303
I am designing a database and I am just wondering if I am doing it correctly. I have tables for things like State with all the states in them and then I reference the ID in other tables. But should I just handle this in my UI and then store it as a string or is this the correct way?The goal of this database is to handle day to day operations of a transportation company. This version of the database is only focused on handling People and contacts. We manage employees, drivers, and there positions in the company. We will be tracking things like accidents, and other incidents drivers have, and gain a better understanding of driver / employee turn over.---- Database: `hrm`---- ------------------------------------------------------------ Table structure for table `address`--CREATE TABLE `address` ( `address_id` int(11) NOT NULL COMMENT 'Primary key for address rows.', `address_line_one` varchar(60) NOT NULL COMMENT 'First street-address line.', `address_line_two` varchar(60) DEFAULT NULL COMMENT 'Second street address line.', `city` varchar(30) NOT NULL COMMENT 'Name of the city.', `state_id` int(11) NOT NULL COMMENT 'Foreign key to state table.', `postal_code` varchar(15) NOT NULL COMMENT 'Postal code for the street address.', `modified_date` datetime NOT NULL COMMENT 'Date and time the row was last updated.') ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `contact`--CREATE TABLE `contact` ( `contact_id` int(11) NOT NULL COMMENT 'Primary key for contact rows.', `title` varchar(8) DEFAULT NULL COMMENT 'A courtesy title. For example, Mr. or Ms.', `first_name` varchar(50) NOT NULL COMMENT 'First name of the person.', `middle_name` varchar(50) DEFAULT NULL COMMENT 'Middle name or middle initial of the person.', `last_name` varchar(50) NOT NULL COMMENT 'Last name of the person.', `suffix` varchar(10) DEFAULT NULL COMMENT 'Surname suffix. For example, Sr. or Jr.', `email_address` varchar(50) DEFAULT NULL COMMENT 'E-mail address for the person.', `phone_number` varchar(25) DEFAULT NULL COMMENT 'Phone number associated with the person.', `address_id` int(11) DEFAULT NULL COMMENT 'Foreign key to address table. ', `modified_date` datetime NOT NULL COMMENT 'Date and time the row was last updated.') ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT=' ';-- ------------------------------------------------------------ Table structure for table `driver`--CREATE TABLE `driver` ( `driver_id` int(11) NOT NULL, `employee_id` int(11) NOT NULL, `driver_type_id` int(11) NOT NULL, `rating_id` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `driver_type`--CREATE TABLE `driver_type` ( `driver_type_id` int(11) NOT NULL, `name` varchar(25) NOT NULL, `abbreviation` varchar(5) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `driver_type`--INSERT INTO `driver_type` (`driver_type_id`, `name`, `abbreviation`) VALUES(1, 'Ambulatory', 'AMB'),(2, 'Wheelchair', 'WC'),(3, 'Bus', 'BUS'),(4, 'Taxi', 'TX');-- ------------------------------------------------------------ Table structure for table `employee`--CREATE TABLE `employee` ( `employee_id` int(11) NOT NULL, `contact_id` int(11) NOT NULL, `status_id` int(11) NOT NULL, `job_title` varchar(50) DEFAULT NULL, `birth_date` date DEFAULT NULL, `interview_date` date DEFAULT NULL, `hire_date` date DEFAULT NULL, `modified_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `employee`--INSERT INTO `employee` (`employee_id`, `contact_id`, `status_id`, `job_title`, `birth_date`, `interview_date`, `hire_date`, `modified_date`) VALUES(1, 1, 2, 'IT Director', '1991-08-10', '2016-02-17', '2016-02-18', '2016-04-25 11:58:00');-- ------------------------------------------------------------ Table structure for table `incident`--CREATE TABLE `incident` ( `incident_id` int(11) NOT NULL, `incident_type_id` int(11) NOT NULL, `driver_id` int(11) NOT NULL, `reported_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `incident_type`--CREATE TABLE `incident_type` ( `incident_type_id` int(11) NOT NULL, `name` varchar(75) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `incident_type`--INSERT INTO `incident_type` (`incident_type_id`, `name`) VALUES(1, 'Tardiness'),(2, 'No Show'),(3, 'Insubordination'),(4, 'Failure to follow protocol'),(5, 'Failure to report incident'),(6, 'Dress code violation');-- ------------------------------------------------------------ Table structure for table `note`--CREATE TABLE `note` ( `note_id` int(11) NOT NULL, `contact_id` int(11) NOT NULL, `note` varchar(255) NOT NULL, `created_date` datetime NOT NULL, `modified_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `rating`--CREATE TABLE `rating` ( `rating_id` int(11) NOT NULL, `name` varchar(50) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `rating`--INSERT INTO `rating` (`rating_id`, `name`) VALUES(1, 'Very Poor'),(2, 'Poor'),(3, 'Fair'),(4, 'Good'),(5, 'Very Good');-- ------------------------------------------------------------ Table structure for table `state`--CREATE TABLE `state` ( `state_id` int(11) NOT NULL COMMENT 'Primary key for state table.', `name` varchar(50) NOT NULL COMMENT 'The name of the state.', `abbreviation` varchar(5) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `state`--INSERT INTO `state` (`state_id`, `name`, `abbreviation`) VALUES(1, 'Alabama', 'AL'),(2, 'Alaska', 'AK'),(3, 'Arizona', 'AZ'),(4, 'Arkansas', 'AR'),(5, 'California', 'CA'),(6, 'Colorado', 'CO'),(7, 'Connecticut', 'CT'),(8, 'Delaware', 'DE'),(9, 'Florida', 'FL'),(10, 'Georgia', 'GA'),(11, 'Hawaii', 'HI'),(12, 'Idaho', 'ID'),(13, 'Illinois', 'IL'),(14, 'Indiana', 'IN'),(15, 'Iowa', 'IA'),(16, 'Kansas', 'KS'),(17, 'Kentucky', 'KY'),(18, 'Louisiana', 'LA'),(19, 'Maine', 'ME'),(20, 'Maryland', 'MD'),(21, 'Massachusetts', 'MA'),(22, 'Michigan', 'MI'),(23, 'Minnesota', 'MN'),(24, 'Mississippi', 'MS'),(25, 'Missouri', 'MO'),(26, 'Montana', 'MT'),(27, 'Nebraska', 'NE'),(28, 'Nevada', 'NV'),(29, 'New Hampshire', 'NH'),(30, 'New Jersey', 'NJ'),(31, 'New Mexico', 'NM'),(32, 'New York', 'NY'),(33, 'North Carolina', 'NC'),(34, 'North Dakota', 'ND'),(35, 'Ohio', 'OH'),(36, 'Oklahoma', 'OK'),(37, 'Oregon', 'OR'),(38, 'Pennsylvania', 'PA'),(39, 'Rhode Island', 'RI'),(40, 'South Carolina', 'SC'),(41, 'South Dakota', 'SD'),(42, 'Tennessee', 'TN'),(43, 'Texas', 'TX'),(44, 'Utah', 'UT'),(45, 'Vermont', 'VT'),(46, 'Virginia', 'VA'),(47, 'Washington', 'WA'),(48, 'West Virginia', 'WV'),(49, 'Wisconsin', 'WI'),(50, 'Wyominng', 'WY');-- ------------------------------------------------------------ Table structure for table `status`--CREATE TABLE `status` ( `status_id` int(11) NOT NULL, `name` varchar(25) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Dumping data for table `status`--INSERT INTO `status` (`status_id`, `name`) VALUES(1, 'Applied'),(2, 'Employed'),(3, 'Disabled'),(4, 'Incarcerated'),(5, 'Deceased'),(6, 'Quit'),(7, 'Terminated'),(8, 'Incompatible');-- ------------------------------------------------------------ Table structure for table `upload`--CREATE TABLE `upload` ( `upload_id` int(11) NOT NULL, `contact_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `name` varchar(200) NOT NULL, `size` varchar(200) NOT NULL, `type` varchar(200) NOT NULL, `url` varchar(200) NOT NULL, `description` varchar(200) DEFAULT NULL, `upload_date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;-- ------------------------------------------------------------ Table structure for table `user`--CREATE TABLE `user` ( `user_id` int(11) NOT NULL, `contact_id` int(11) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `last_login` datetime DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;---- Indexes for dumped tables------ Indexes for table `address`--ALTER TABLE `address` ADD PRIMARY KEY (`address_id`), ADD KEY `state_id` (`state_id`);---- Indexes for table `contact`--ALTER TABLE `contact` ADD PRIMARY KEY (`contact_id`), ADD KEY `address_id` (`address_id`);---- Indexes for table `driver`--ALTER TABLE `driver` ADD PRIMARY KEY (`driver_id`), ADD KEY `employee_id` (`employee_id`), ADD KEY `driver_type_id` (`driver_type_id`), ADD KEY `rating_id` (`rating_id`);---- Indexes for table `driver_type`--ALTER TABLE `driver_type` ADD PRIMARY KEY (`driver_type_id`);---- Indexes for table `employee`--ALTER TABLE `employee` ADD PRIMARY KEY (`employee_id`), ADD UNIQUE KEY `ix_contact_id` (`contact_id`), ADD KEY `idx_status_id` (`status_id`);---- Indexes for table `incident`--ALTER TABLE `incident` ADD PRIMARY KEY (`incident_id`), ADD KEY `incident_type_id` (`incident_type_id`), ADD KEY `driver_id` (`driver_id`);---- Indexes for table `incident_type`--ALTER TABLE `incident_type` ADD PRIMARY KEY (`incident_type_id`);---- Indexes for table `note`--ALTER TABLE `note` ADD PRIMARY KEY (`note_id`), ADD KEY `contact_id` (`contact_id`);---- Indexes for table `rating`--ALTER TABLE `rating` ADD PRIMARY KEY (`rating_id`);---- Indexes for table `state`--ALTER TABLE `state` ADD PRIMARY KEY (`state_id`);---- Indexes for table `status`--ALTER TABLE `status` ADD PRIMARY KEY (`status_id`);---- Indexes for table `upload`--ALTER TABLE `upload` ADD PRIMARY KEY (`upload_id`), ADD KEY `contact_id` (`contact_id`), ADD KEY `user_id` (`user_id`);---- Indexes for table `user`--ALTER TABLE `user` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `contact_id` (`contact_id`);---- AUTO_INCREMENT for dumped tables------ AUTO_INCREMENT for table `address`--ALTER TABLE `address` MODIFY `address_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key for address rows.', AUTO_INCREMENT=22;---- AUTO_INCREMENT for table `contact`--ALTER TABLE `contact` MODIFY `contact_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key for contact rows.', AUTO_INCREMENT=23;---- AUTO_INCREMENT for table `driver`--ALTER TABLE `driver` MODIFY `driver_id` int(11) NOT NULL AUTO_INCREMENT;---- AUTO_INCREMENT for table `driver_type`--ALTER TABLE `driver_type` MODIFY `driver_type_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;---- AUTO_INCREMENT for table `employee`--ALTER TABLE `employee` MODIFY `employee_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;---- AUTO_INCREMENT for table `incident`--ALTER TABLE `incident` MODIFY `incident_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;---- AUTO_INCREMENT for table `incident_type`--ALTER TABLE `incident_type` MODIFY `incident_type_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;---- AUTO_INCREMENT for table `note`--ALTER TABLE `note` MODIFY `note_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;---- AUTO_INCREMENT for table `rating`--ALTER TABLE `rating` MODIFY `rating_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;---- AUTO_INCREMENT for table `state`--ALTER TABLE `state` MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary key for state table.', AUTO_INCREMENT=51;---- AUTO_INCREMENT for table `status`--ALTER TABLE `status` MODIFY `status_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;---- AUTO_INCREMENT for table `upload`--ALTER TABLE `upload` MODIFY `upload_id` int(11) NOT NULL AUTO_INCREMENT;---- AUTO_INCREMENT for table `user`--ALTER TABLE `user` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Database design for a transportation company
sql;mysql;database
latin1 in this day and age? You probably have a plan to deal with names that aren't in that character set? The whole split between first, middle and last name also might conflict with the real world. (I guess the names argument is a bit overkill, but you could possibly also get away with a single generic name field.)A few tables are really hidden enumerations - you could think about using something on the application level rather than requiring yet another join on every operation (or use MySQL enumerations which are rather unwieldy though). Edit: That's basically the answer to your first question, i.e. I'd probably go with the actual string value if you don't need to associate more information with the enumeration.The user table has the column password. That has to be a password hash (meaning the field will have a lower fixed length) and should consequently be named password_hash or something similar.Lacking the exact requirements I still find the upload table a bit weird - why are size and type of type varchar(200)? Both sound way more restricted in scope and size more like it should be an integer type instead.
_codereview.84365
I have written a Rational struct for working with rational numbers, i.e. Rational(int numerator, int denominator).A recent post regarding rational numbers peaked my interest. I particular like the answer by @aush with his RationalNumber class. I am inclined to think of a rational number as just that: a number, akin to { int, double, Decimal }. So it screams for struct rather than a class.Note I am neither a student, nor a teacher. Though I write code for a living, I have no business requirements for Rational, which means I have no constraints or restrictions on the struct design. I am only limited by what I can imagine how a rational number should behave. In fact, I have no foreseen practical need for Rational. I just find that going through such mental exercises helps improve my overall skills. namespace System{ public struct Rational : IComparable, IComparable<Rational>, IEquatable<Rational> { public int Numerator { get; private set; } public int Denominator { get; private set; } // These fields bypass Simplify(). public static readonly Rational MinValue = new Rational { Numerator = int.MinValue, Denominator = 1 }; public static readonly Rational MaxValue = new Rational { Numerator = int.MaxValue, Denominator = 1 }; public static readonly Rational Epsilon = new Rational { Numerator = 1, Denominator = int.MaxValue }; public static readonly Rational Undefined = new Rational { Numerator = 0, Denominator = 0 }; public static readonly Rational Zero = new Rational { Numerator = 0, Denominator = 1 }; public static readonly Rational One = new Rational { Numerator = 1, Denominator = 1 }; public static readonly Rational MinusOne = new Rational { Numerator = -1, Denominator = 1 }; public Rational(int numerator, int denominator = 1) : this() { this.Numerator = numerator; this.Denominator = denominator; // There is a special case where Simplify() could throw an exception: // // new Rational(int.MinValue, certainNegativeIntegers) // // In general, having the contructor throw an exception is bad practice. // However given the extremity of this special case and the fact that Rational // is an immutable struct where its inputs are ONLY validated DURING // construction, I allow the exception to be thrown here. Simplify(); } public static bool TryCreate(int numerator, int denominator, out Rational result) { try { result = new Rational(numerator, denominator); return true; } catch { result = Undefined; } return false; } public static bool TryParse(string s, out Rational result) { try { result = Rational.Parse(s); return true; } catch { result = Undefined; } return false; } public static Rational Parse(string s) { // Note that 3 / -4 would return new Rational(-3, 4). var tokens = s.Split(new char[] { '/' }); var numerator = 0; var denominator = 0; switch (tokens.Length) { case 1: numerator = GetInteger(Numerator, tokens[0]); denominator = 1; break; case 2: numerator = GetInteger(Numerator, tokens[0]); denominator = GetInteger(Denominator, tokens[1]); break; default: throw new ArgumentException(string.Format(Invalid input string: '{0}', s)); } return new Rational(numerator, denominator); } // This is only called by Parse. private static int GetInteger(string desc, string s) { if (string.IsNullOrWhiteSpace(s)) { throw new ArgumentNullException(desc); } var result = 0; // TODO: Decide whether it's good idea to convert - 4 to -4. s = s.Replace( , string.Empty); if (!int.TryParse(s, out result)) { throw new ArgumentException(string.Format(Invalid value for {0}: '{1}', desc, s)); } return result; } //TODO: consider other overloads of ToString(). Perhaps one to always display a division symbol. // For example, new Rational(0, 0).ToString() --> 0/0 instead of Undefined, or // new Rational(5).ToString() --> 5/1 instead of 5 public override string ToString() { switch (Denominator) { case 0: return Undefined; case 1: return Numerator.ToString(); } return string.Format({0}/{1}, Numerator, Denominator); } public int CompareTo(object other) { if (other == null) return 1; if (other is Rational) return CompareTo((Rational)other); throw new ArgumentException(Argument must be Rational); } public int CompareTo(Rational other) { if (IsUndefined) { // While IEEE decrees that floating point NaN's are not equal to each other, // I am not under any decree to adhere to that same specification for Rational. return other.IsUndefined ? 0 : -1; } if (other.IsUndefined) return 1; return this.ToDouble().CompareTo(other.ToDouble()); } public bool Equals(Rational other) { if (IsUndefined) return other.IsUndefined; return (this.Numerator == other.Numerator) && (this.Denominator == other.Denominator); } public override bool Equals(object other) { if (other == null) return false; if (other is Rational) return Equals((Rational)other); throw new ArgumentException(Argument must be Rational); } // Mofified code that was stolen from: // http://www.dotnetframework.org/default.aspx/4@0/4@0/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/clr/src/BCL/System/Double@cs/1305376/Double@cs // The hashcode for a double is the absolute value of the integer representation of that double. [System.Security.SecuritySafeCritical] // auto-generated public unsafe override int GetHashCode() { if (Numerator == 0) { // Ensure that 0 and -0 have the same hash code return 0; } double d = ToDouble(); long value = *(long*)(&d); return unchecked((int)value) ^ ((int)(value >> 32)); } public static bool operator ==(Rational rat1, Rational rat2) { return rat1.Equals(rat2); } public static bool operator !=(Rational rat1, Rational rat2) { return !rat1.Equals(rat2); } public static Rational operator +(Rational rat1, Rational rat2) { if (rat1.IsUndefined || rat2.IsUndefined) { return Undefined; } return new Rational { Numerator = rat1.Numerator * rat2.Denominator + rat1.Denominator * rat2.Numerator, Denominator = rat1.Denominator * rat2.Denominator }.Simplify(); } public static Rational operator -(Rational rat1, Rational rat2) { if (rat1.IsUndefined || rat2.IsUndefined) { return Undefined; } return new Rational { Numerator = rat1.Numerator * rat2.Denominator - rat1.Denominator * rat2.Numerator, Denominator = rat1.Denominator * rat2.Denominator }.Simplify(); } public static Rational operator *(Rational rat1, Rational rat2) { if (rat1.IsUndefined || rat2.IsUndefined) { return Undefined; } return new Rational { Numerator = rat1.Numerator * rat2.Numerator, Denominator = rat1.Denominator * rat2.Denominator }.Simplify(); } public static Rational operator /(Rational rat1, Rational rat2) { if (rat1.IsUndefined || rat2.IsUndefined) { return Undefined; } return new Rational { Numerator = rat1.Numerator * rat2.Denominator, Denominator = rat1.Denominator * rat2.Numerator }.Simplify(); } // The simplified Denominator will always be >= 0 for any Rational. // For a Rational to be negative, the simplified Numerator will be negative. // Thus a Rational(3, -4) would simplify to Rational(-3, 4). private Rational Simplify() { // These corner cases are very quick checks that means slightly longer code. // Yet I feel their explicit handling makes their logic more clear to future maintenance. // More importantly, it bypasses modulus and division when its not absolutely needed. if (IsUndefined) { Numerator = 0; return this; } if (Numerator == 0) { Denominator = 1; return this; } if (IsInteger) { return this; } if (Numerator == Denominator) { Numerator = 1; Denominator = 1; return this; } if (Denominator < 0) { // One special corner case when unsimplified Denominator is < 0 and Numerator equals int.MinValue. if (Numerator == int.MinValue) { return ReduceOrThrow(); } // Simpler and faster than mutiplying by -1 Numerator = -Numerator; Denominator = -Denominator; } // We only perform modulus and division if we absolutely must. Reduce(); return this; } private void Reduce() { var greatestCommonDivisor = GreatestCommonDivisor(Numerator, Denominator); Numerator /= greatestCommonDivisor; Denominator /= greatestCommonDivisor; } // Very special one off case: only called when unsimplified Numerater equals int.MinValue and Denominator is negative. // Some combinations produce a valid Rational, such as Rational(int.MinValue, int.MinValue), equivalent to Rational(1). // Others are not valid, such as Rational(int.MinValue, -1) because the Numerator would need to be (int.MaxValue + 1). private Rational ReduceOrThrow() { try { Reduce(); return this; } catch { throw new ArgumentException(string.Format(Invalid Rational(int.MinValue, {0}), Denominator)); } } public bool IsUndefined { get { return (Denominator == 0); } } public bool IsInteger { get { return (Denominator == 1); } } public double ToDouble() { if (IsUndefined) return double.NaN; return (double)Numerator / (double)Denominator; } // http://en.wikipedia.org/wiki/Euclidean_algorithm private static int GreatestCommonDivisor(int a, int b) { return (b == 0) ? a : GreatestCommonDivisor(b, a % b); } } //end struct} //end namespaceUse of Negatives:The sign of a Rational is determined by the Numerator. Thus a new Rational(3, -4) or Parse(3/-4) would both return Rational(-3, 4). Undefined:There are corner cases where the integer inputs do not return a valid Rational. This would only happen if the Denominator is negative and the Numerator equals int.MinValue. E.g. new Rational(int.MinValue, -2) returns a valid Rational but new Rational(int.MinValue, -1) would not.Convenient Fields and Properties:Like other numbers, Rational has a MinValue and MaxValue. Other convenient fields are Epsilon, Undefined, Zero, One, and MinusOne. Some convenient properties are IsUndefined and IsInteger.Constructor Validation:I imagine the biggest controversy is that I allow the 2 parameter constructor to throw an exception on invalid inputs. Im aware of the argument that this is bad practice. Sure I could replace this constructor with a static Create method, the net effect is the same: anytime you create a new Rational it could possibly throw. So its wrong kill your neighbors but perfectly acceptable to hire someone else to do it?I seriously debated the issue but ultimately decided to let the constructor throw. This keeps the use of Rational similar to other numbers, including Decimal, which also can throw during construction (example: new Decimal(double.NaN)).
My Rational struct, version 1
c#;rational numbers
I like it very much (maybe other reviewers will disagree though).A few things tickle a bit.System namespace is not yoursI wouldn't put anything in the System namespace, whatever the reason is. That namespace belongs to the framework, and as much as your struct looks like it should be part of that framework, it isn't. And the day Microsoft ships a System.Rational, you have a clash.thisThe keyword this is inconsistently being used as a qualifier - sometimes it's there, sometimes it isn't. I'd just remove it, it's perfectly redundant.ToStringThe ToString implementation is switching on a non-enum value, and that switch block doesn't have a default case: public override string ToString() { switch (Denominator) { case 0: return Undefined; case 1: return Numerator.ToString(); } return string.Format({0}/{1}, Numerator, Denominator); }I'd live with the non-enum switch in the name of premature optimisation (does an if block really make a difference?), but move the return string.Format part into it.Double-dipIn several places you're doing this:return new Rational{ Numerator = /*expression*/, Denominator = /*expression*/}.Simplify();That's actually calling the default constructor (a 0/0 / Undefined instance) and accessing the private setters from outside that instance, which is violating the type's immutability and, some would argue, encapsulation. And then Simplify() returns yet another instance.I don't like having public int SomeProperty { get; private set; } auto-properties in an immutable type, exactly for that reason. In my mind, a public property with a private setter should be 100% equivalent to this:private readonly int _numerator;public int Numerator { get { return _numerator; } }But that would blow up your code with the above, because you're accessing the private setter.Why not just do this instead?return new Rational([expression], [expression]);The constructor is calling Simplify anyway!Immutable?Wait a sec... is that struct really immutable?private void Reduce(){ var greatestCommonDivisor = GreatestCommonDivisor(Numerator, Denominator); Numerator /= greatestCommonDivisor; Denominator /= greatestCommonDivisor;}Shouldn't that be private Rational Reduce(), and returning a new instance? You're dealing with a struct here - the two values ought to be considered as a single unit. I'm not sure how much of a violation that is, because the method is private, but it doesn't feel right that a struct internally mutates itself.
_vi.11730
I have a binding in my .vimrc that reads the contents of the system clipboard to a line immediately below my cursornnoremap <silent> <leader>f <esc> :read ! test -f /usr/bin/xsel && /usr/bin/xsel -ob \|\| /usr/bin/pbpaste<cr>I tried to change it to (1)nnoremap <silent> <leader>f <esc> :read ! /usr/bin/xsel -ob \|\| /usr/bin/pbpaste<cr>or (2)nnoremap <silent> <leader>f <esc> :read ! /usr/bin/xsel -ob ; /usr/bin/pbpaste<cr>for the sake of simplicity, even though it's more brittle.When I change it to either of those, however, I get the contents of stderr in my buffer as well, as if vim is reading from both stdout and stderr when executing the command. (this is after echo clipboard_contents | pbcopy)./bin/sh: /usr/bin/xsel: No such file or directoryclipboard_contentsWhy is vim doing that? Is there a way to tell it to silently drop stderr in this case or redirect it to /dev/null?
read from external command captures stderr as well
external command
From :h :r!: :r! :read!:[range]r[ead] [++opt] !{cmd} Execute {cmd} and insert its standard output below the cursor or the specified line. A temporary file is used to store the output of the command which is then read into the buffer. 'shellredir' is used to save the output of the command, which can be set to include stderr or not.And in :h 'shellredir':'shellredir' 'srr' string (default >, >& or >%s 2>&1) global {not in Vi} String to be used to put the output of a filter command in a temporary file. ... The default is >. For Unix, if the 'shell' option is csh, tcsh or zsh during initializations, the default becomes >&. If the 'shell' option is sh, ksh or bash the default becomes >%s 2>&1. This means that stderr is also included.So, just do:set shellredir=>
_unix.155698
I have to compare Linux and Windows machine hardware?In windows system, I can open the My computer properties and see the details like processors, RAM Hard disks etc.Through task manager, I can see how many processors are there ?In the same way, Linux has commands to do that likecat /proc/meminfocat /proc/cpuinfoHow to check hard disk types and number of processors in my linux machine?
Comparing Windows and Linux machine hardware
linux;process;hard disk;cpu;oracle linux
null
_webmaster.107233
I am looking for a way to connect asset download goals early in the buying cycle with signups at the end of the cycle.My website has complex buying cycle that happens over the course of months, for which we have top, mid, and bottom of marketing funnel goals. The top of funnel goals include downloads of white papers and ebooks, whereas the middle and bottom of funnel are downloads of solution assets and sign ups for free trials, demos, etc. I am hoping to find a way to see in Google Analytics see how many mid and bottom of funnel goals were tied to a user conversion on top of funnel resources.Is there a way in Google Analytics to connect multiple goals to a user?
Connecting different goal types to see correlations in Google Analytics
google analytics;analytics;conversions;universal analytics;goal tracking
null
_cogsci.1034
QuestionsIs it true that people 'like' those who are similar to them?Why is it so? Is there an evolutionary explanation?
Do people like those who are similar to them and why?
social psychology;evolution
Since you mentioned that you want an evolutionary explanation, there is one available. In biology the effect of providing benefit towards potential non-kin based on an arbitrary marker is known as the green-beard or armpit effect. In a social human setting, if the marker is arbitrary social construct it is usually known as ethnocentrism. This sort of behavior is studied in game theory in the context of cooperate-defect games (typical example: Prisoner's dilemma) and usually called conditional altruism.It has been shown that conditional altruism evolves in a simple spatial agent-based model and promotes cooperative behavior (Hammond & Axelrod, 2006a 2006b). The effect does not create cooperation, but if there is another mechanism for creation of cooperation (say spatial factors in the H&A model) then ethnocentrism helps maintain it and extend the range of parameters under which cooperation can occur (Kaznatcheev & Shultz, 2011). In humans, this ability to cooperate only with others of similar culture is believed to require a significant amount of cognitive ability. In fact, some even suppose that it could have been one of the factors that drove towards the increasing complexity of our brains. Unfortunately, Kaznatcheev (2010a) shows that the ethnocentrism of the sort present in the H&A models is not robust to increase in the cost of cognition. Thus, in humans (or simpler organisms) the mechanism allowing discrimination has to have been in place already (and not co-evolved) or be very inexpensive.The above examples dealt with the prisoner's dilemma (PD) which is a typical model of a competitive environment. In the PD cooperation is irrational, so there conditional altruism allowed the agents to cooperate irrationally (thus moving over to the better social payoff), while still treating those of a different culture rationally and defection from them. This doesn't seem as bad, but Kaznatcheev (2010b) shows that the mechanism of ethnocentrism is robust across different games (not just PD) including ones where cooperation is rational. In those games conditional altruism produces an irrational defection from the out-group. Thus, from an evolutionary stand-point this is a two-edged sword: it can cause unexpected cooperative behavior, but also irrational hostility.ReferencesHammond, R., & Axelrod, R. (2006a). Evolution of contingent altruism when cooperation is expensive. Theoretical Population Biology, 69, 333-338.Hammond, R., & Axelrod, R. (2006b). The evolution of ethnocentrism. Journal of Conflict Resolution, 50, 926-936. (pdf)Kaznatcheev, A. (2010a). The cognitive cost of ethnocentrism. In S. Ohlsson & R. Catrambone (Eds.), Proceedings of the 32nd annual conference of the cognitive science society. (pdf)Kaznatcheev, A. (2010b). Robustness of ethnocentrism to changes in inter-personal interactions. Complex Adaptive Systems - AAAI Fall Symposium. (pdf)Kaznatcheev, A., & Shultz, T.R. (2011). Ethnocentrism Maintains Cooperation, but Keeping One's Children Close Fuels It. In L. Carlson, C, Hoelscher, & T.F. Shipley (Eds), Proceedings of the 33rd annual conference of the cognitive science society. (pdf)
_unix.332259
When the GRUB bootloader boots Linux, it pass the name of the root partition (where /sbin/init is) to the kernel through the root= kernel parameter in order for the initrd to be able to mount the real root filesystem later.When we use the grub-install tool, we pass as arguments only the block device where the MBR should be installed and the place where the GRUB image and configuration files should be placed, we do not specify the root partirion with what the kernel will be booted.How exactly GRUB determines the root partition of the system when it's installed? How is that implemented?
How GRUB determines the Linux root partition that it pass to the kernel with root=?
boot;partition;root;grub
null
_unix.387277
My first encounters with a CLI (and computers generally), involved booting to a command prompt, usually inserting a disc, and loading a full screen GUI program that was not windowed in what we commonly see today as GUI based OS.It went something like this. Boot >> Prompt>> Load Rocky's Boots >>Launch Rocky's Boots >> Quit >> PromptI've never seen that happen with a Unix / Linux based system, loading directly to a graphical program not in a windowed OS environment - only ascii based programs like Space Invaders, or VIM. Does the ability exist to do the aforementioned DOS-like loading of 8-bit graphical programs (I stress, not windowed in OSX or Unity or whatever)? If not, why is it different?
Can a Unix (Linux) System Launch a GUI from CLI Like (Apple/Microsoft) DOS?
linux;terminal;graphics
null
_softwareengineering.234482
I have a RESTful API, built in NODE.js that does what you would expect it to: consumes data and then makes it accessible. Currently, data being submitted to my server is nested form data:data[0][username]=...data[0][email]=...data[0][phone]=......data[12][username]=...data[12][email]=...data[12][phone]=...or as a query stringdata[0][username]=...&data[0][email]=...&data[0][phone]=...SO when I parse it on the server, I get a JS array of objects with those particular fields. What I am wondering is, is it safe for me accept a string that I can JSON.parse and the process it?data=(some stringified json object)I am unsure if it's possible for malicious code or anything to be included in the JSON object that would blow up my server once run through a parserThanks.
Is parsing a submitted JSON object safe?
javascript;node.js;json;code security;malicious code
null
_unix.174609
I am trying to replace multiple words in file by using sed -i #expression1 #expression2fileSomething 123 item1Something 456 item2Something 768 item3Something 353 item4Output (Desired)anything 123 stuff1anything 456 stuff2anything 768 stuff3anything 353 stuff4Try-outsI can get the following output by using sed -i for 2 times. sed -i 's/Some/any/g' file sed -i 's/item/stuff/g' fileCan I have any possible way of making this as single in-place command like sed -i 's/Some/any/g' -i 's/item/stuff/g' fileWhen I tried above code it takes s/item/stuff/g as a file and try working on it..
sed with multiple expression for in-place arguement
shell;shell script;text processing;sed
Depending on the version of sed on your system you may be able to dosed -i 's/Some/any/; s/item/stuff/' fileYou don't need the g after the final slash in the s command here, since you're only doing one replacement per line.Alternatively:sed -i -e 's/Some/any/' -e 's/item/stuff/' fileThe -i option tells sed to edit files in place; if there are characters immediately after the -i then sed makes a backup of the original file and uses those characters as the backup file's extension. Eg,sed -i.bak 's/Some/any/; s/item/stuff/' fileorsed -i'.bak' 's/Some/any/; s/item/stuff/' filewill modify file, saving the original to file.bak.Of course, on a Unix (or Unix-like) system, we normally use '~' rather than '.bak', sosed -i~ 's/Some/any/;s/item/stuff/' file
_cs.6718
I try to understand if someone can apply a NTM to recognize coNP language.From the definition we know that:NP - set of languages that can be recognized by NTM in polynomial time.coNP - set of all languages that are complement to NP language.as with P versus NP question, we have NP versus coNP question.Unfortunately, is not defined explicitly if can one recognize coNP language with NTM.However, if we take a look at few examples from the set of coNP languages, few questions emerge.TAUTOLOGY = {$\varphi$:$\varphi$ is satisfied by every assingment}$\bar{SAT}$ = {$\varphi$: $\varphi$ is not satisfiable }These languages are known to be coNP language and intuitively it seems like one can construct NTM to recognize these languages. On the other hand, if one can construct NTM to recognize them why them not in NP class (by definition)? Maybe not all language of coNP can be solved by NTM just few of them, if yes, we will have intersection of NP class and coNP class. And if every language from coNP class cannot be solved by NTM, does it mean that limitation of NTM is located in coNP class. Is NTM is limited at all?I am a little bit confused, I will appreciate if someone will shed the light on this topic.
coNP and limitation of NDTM
complexity theory;np complete;complexity classes
null
_reverseengineering.15127
I am working on Lab13-01.exe from Practical Malware Analysis (you can download it from here).When I run it without debuggers in my VMWare it runs without errors.I started to analyze it with OllyDbg 2.01.There is some point in the code that it receives exception and I don't understand why.It has resource that contains encoded string: LLLKIZXORXZWVZWLZI^ZUZWBHRHXTVThis resource is saved at address 0x408060At 0x4011C1 it overwrites the first byte of the string with AL (0x77):MOV BYTE PTR DS:[ECX], ALThen I received:Access violation when writing to [00408060]When I press Shift+Run/Step, it succeed to run.There number of things I don't understand here.If it can't write to [00408060], how come when I press Shift+Run/Step it succeed ?Why it can't write to [00408060] ? Is there some flag that prevent from writing to this aread (if yes, where can I see it?) ?
Why the program can't write to specific memory area
ollydbg;exception
null
_softwareengineering.196407
I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model? I would add that I have other controller methods that will read this session value later. public ActionResult AddFriend(FriendsContext viewModel) { if (!ModelState.IsValid) { return View(viewModel); } // Start - Confused if the code block below belongs in Controller? Friend friend = new Friend(); friend.FirstName = viewModel.FirstName; friend.LastName = viewModel.LastName; friend.Email = viewModel.UserEmail; httpContext.Session[latest-friend] = friend; // End Confusion return RedirectToAction(Home); }I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext){ httpContext.Session[latest-friend] = friend;}public static Friend GetLatestFriend(HttpContextBase httpContext){ return httpContext.Session[latest-friend] as Friend;}
MVC : Does Code to save data in cache or session belongs in controller?
mvc;asp.net mvc;asp.net mvc 3;asp.net mvc 4
null
_cs.14788
I'm searching for a reference of an undecidability proof that is as simple as possible and starts from scratch.With from scratch I mean that it does not use some other undecidable problem to prove some undecidability (which is the usual case), I cannot wrap my mind about how proving undecidability that way (without a previous proof) could be possible.This question may be inspiring: An example of an easy to understand undecidable problemAlso, I know this is probably not very objective, but it is important to me, it should be something as simple as possible, hopefully enough so that even I can understand it.
Reference for an undecidability proof
reference request;proof techniques;undecidability;decision problem
null
_unix.331019
i use this bash script to monitor my bandwidth usage :#!/bin/sh#Get __RequestVerificationTokencc=`curl -s -X GET http://192.168.8.1/api/webserver/SesTokInfo`c=`echo $cc| grep SessionID=| cut -b 10-147`t=`echo $cc| grep TokInfo| cut -b 10-41`while true; do#Exucate Commandmx=$(curl http://192.168.8.1/api/monitoring/traffic-statistics 2>/dev/null \ -H Cookie: $c -H __RequestVerificationToken: $t -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 \ 2>&1 | grep '</CurrentDownload>' #convert byte to megabytete=$(( $mx / 1048576 ))time=$(date)# show Usageecho $te M.B#compare usage from below list if [ $te -ge 1000 ] && [ $te -le 5000 ] || [ $te -ge 8000 ] && [ $te -le 10000 ] || [ $te -ge 11000 ] && [ $te -le 15000 ] || [ $te -ge 17000 ]thenecho Plz Low your Data Usage !!else echo Under Bandwidth Limit .. $timefisleep 20it`s work well at first but during running it gives my error:arithmetic expression: expecting primary: / 1048576 on line that converting byte to megabyte& i try execute it using sh test.sh & bash test.sh Same Error !!output of : sudo sh -x ./test.sh+ curl -s -X GET http://192.168.8.1/api/webserver/SesTokInfo+ cc=<?xml version=1.0 encoding=UTF-8?><response><SesInfo>SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS</SesInfo><TokInfo>92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I</TokInfo></response>+ + + grepechocut SessionID= <?xml version=1.0 encoding=UTF-8?><response><SesInfo>SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS</SesInfo><TokInfo>92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I</TokInfo></response> -b 10-147+ c=SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFu FgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS+ + + grepcut TokInfo -b 10-41echo <?xml version=1.0 encoding=UTF-8?><response><SesInfo>SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS</SesInfo><TokInfo>92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I</TokInfo></response>+ t=92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I+ true+ + + + grepcut </CurrentDownload>cut -d> -f2 -d<curl -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98 3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 2+ IP=628609528+ re=599+ echo 628609528628609528+ date+ time=Sat 17 Dec 12:06:36 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:36 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:36 EET 2016+ echo 628609528628609528+ sleep 2+ true+ + + + grepcurlcut </CurrentDownload>cut http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5I d983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMg CZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -d> -f2 -H -d< __RequestVerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H -f1 Content -Type: application/x-www-form-urlencoded; charset=UTF-8 2+ IP=628610195+ re=599+ echo 628610195628610195+ date+ time=Sat 17 Dec 12:06:39 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:39 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:39 EET 2016+ echo 628610195628610195+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d>curl -f2 -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98 3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 2+ IP=628610687+ re=599+ echo 628610687628610687+ date+ time=Sat 17 Dec 12:06:41 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:41 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:41 EET 2016+ echo 628610687628610687+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2curl -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98 3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 2+ IP=628611179+ re=599+ echo 628611179628611179+ date+ time=Sat 17 Dec 12:06:45 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:45 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:45 EET 2016+ echo 628611179628611179+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d>curl -f2 -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98 3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 2+ IP=628611671+ re=599+ echo 628611671628611671+ date+ time=Sat 17 Dec 12:06:48 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:48 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:48 EET 2016+ echo 628611671628611671+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2curl -d< http://192.168.8.1/api/monitoring/traffic-statistics -f1 -H Cookie: SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __Request VerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application /x-www-form-urlencoded; charset=UTF-8 2+ IP=628619238+ re=599+ echo 628619238628619238+ date+ time=Sat 17 Dec 12:06:50 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:50 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:50 EET 2016+ echo 628619238628619238+ sleep 2+ true+ + + + grepcut </CurrentDownload>cut -d>curl -f2 -d< -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd4 6cClFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __Requ estVerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: applicat ion/x-www-form-urlencoded; charset=UTF-8 2+ IP=628623293+ re=599+ echo 628623293628623293+ date+ time=Sat 17 Dec 12:06:53 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:53 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:53 EET 2016+ echo 628623293628623293+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2 -d<curl -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98 3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 2+ IP=628630547+ re=599+ echo 628630547628630547+ date+ time=Sat 17 Dec 12:06:55 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:55 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:55 EET 2016+ echo 628630547628630547+ sleep 2+ true+ + + + grepcutcurlcut -d> http://192.168.8.1/api/monitoring/traffic-statistics -f2 -H </CurrentDownload> Cookie: SessionID=5Id983frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cC lFxFuFgEzZf8h5ACq7cMgCZsabMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -d< -f1 -H __RequestVerificationToken: 92iFXKTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: a pplication/x-www-form-urlencoded; charset=UTF-8 2+ IP=628631670+ re=599+ echo 628631670628631670+ date+ time=Sat 17 Dec 12:06:58 EET 2016+ echo Its Just 599 M.BIts Just 599 M.B+ [ 599 -ge 4000 ]+ echo Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:58 EET 2016Under Bandwidth Limit Until Now .. Sat 17 Dec 12:06:58 EET 2016+ echo 628631670628631670+ sleep 2+ true+ + + + grepcutcut </CurrentDownload> -d> -f2 -d<curl -f1 http://192.168.8.1/api/monitoring/traffic-statistics -H Cookie: SessionID=5Id98 3frqqUaL3VhtspvHHEah/lbS0BvOuhWUYQYaPMhSDMhMAs1yrxHd46cClFxFuFgEzZf8h5ACq7cMgCZs abMhBXTwuBEykKNcvvThdoSm93C8YHwShh797oQ8lDS -H __RequestVerificationToken: 92iFX KTfY7pRK+DhUFa2mFLLNWgwPV+I -H Content-Type: application/x-www-form-urlencoded; charset=UTF-8 2+ IP=./test.sh: 11: ./test.sh: arithmetic expression: expecting primary: / 104 8576
error with bash script arithmetic expression: expecting primary
bash;shell script;router;api
null
_unix.71533
I'd like the footer of a Mailman list to include an image. Is this possible? If yes, how?I tried the obvious path of just typing <img...>, but that didn't work.
How can I include an image in a Mailman footer?
mailman
null
_cs.68550
I need to generate/enumerate isomorphism classes of vertex-rooted graphs with the following properties. Let $\Delta$ be the maximal degree (say 3 for subcubic graphs) and $r$ the maximal distance of a vertex from the root (something like radius, even though the formal definition of radius of a graph is different). Note that the requirement also means the graphs are connected. Note that rooted graphs are isomorphic if there exists an isomorphism that respects the root, i.e., sends root to root.It is clear that for fixed $\Delta$ and $r$ there exist only finitely many such graphs. The number of them will be huge, but still drastically smaller than the number of all graphs or all bounded-degree graphs on the same number of vertices.Example: For $\Delta=2$ and $r=1$ we would get exactly $4$ graphs: (1) just the root, (2) an edge with one vertex the root, (3) a cherry with the root in the middle and (4) a triangle with one vertex the root.The case I am mostly interested in is $\Delta=3$ but if possible I would like to be more general.Question: Is there some software or a collection that provides this? If possible, I would like to avoid coding the whole thing myself as this seems to be a rather complex task (generating non-isomorphic graphs in a reasonable efficient way). I am aware of nauty, which can check isomorphism and also generates certain types of graphs. But after reading the manual, I think there is no option to generate rooted graphs (there is option to generate bounded-degree graphs, though).Does anyone have an idea how to do this without spending a lot of time writing my own generator?
Generate all non-isomorphic bounded-degree rooted graphs of bounded radius
graphs;graph isomorphism;mathematical software
null
_softwareengineering.172927
I started as the analyst, talking to the client and jotting down requirements and all that jazz. Ended as the sole developer of the project.The schedule is OK, but not OK for someone that don't know nothing about how to develop a WPF application, IMHO.What can I do about it, tell program manager that she made a huge mistake by choosing someone with no skills(she had no choice, I was the only one not allocated), or slit my wrists? Do I have other choices?P.S.: Really trying to learn it, can't get how to structure the project MVVM, IoC, Logging. The concept count is too damn high.
Assigned to a new WPF project, know nothing about it
wpf
I'd start with the basics first and add the design patterns and AOP concerns once those are nailed down. Trying to learn all of that in one shot is just going to confuse you, as you seem to be aware.I would suggest that you talk to the PM not in terms of I can't do it, but rather in terms of this is going to be a relatively simple implementation. I'm not sure where the MVVM/Logging/etc requirements are coming from, but I'd fix those if I were you as being unfeasible, given your skill set with the framework. The main thing is to manage expectations. The app will have to be relatively simple and it might not be the most maintainable thing in the world since this is your first crack at it.Edit to clarify about MVVM: My intent here was to suggest that MVVM is not a specific requirement of WPF projects rather than to question its validity as a pattern or its usefulness. Similar concept of the AOP techniques as well.
_unix.67492
I have a python application that uses pygame to access the framebuffer directly without using X. I want to start this application on startup instead of showing the console login prompt. I haven't found any good resources which explains how I would do it.Just the same way gdm is started instead of showing a console login prompt. Bonus question: What would happen if said application crashed? Would the console login prompt be shown?Edit: I have been reading up on runlevels and startup. More specific question below Will it be enough to create a /etc/init.d script which starts my python program, update rc.d with update-rc.d and setting priority to 99 so that it runs last and setting it to run under runlevel 5 (Which is for gui applications I heard). Then changing the default runlevel 5 in /etc/inittab?Or do I have to do something special since the program uses framebuffer?
How do I start a gui framebuffer (no X) application on startup instead of console login prompt?
debian;gui;startup;raspberry pi;framebuffer
You can try to run directy on the inittab... try to edit the /etc/inittab and replace the 1:2345:respawn:/sbin/getty 38400 tty1with1:2345:respawn:/usr/bin/python /srv/game/game.pyIf the game crashes, init will restart it again. The game probably needs to know that is should open tty1 (or any other at your choice)if you need the console, the other terminals should be normal, so ctrl+alt+F2 should jump to a login consoleIf you want to try with the runlevel, you are on good track... you probably need to define a TTY (probably export TTY=/dev/tty1) so the app knows where it should connect (as inittab and rc script run without any TTY defined). As i don't know python nor framebuffer consoles, dont know how to do that in python and what else is needed (maybe a more framebuffed or python direct question on stackoverflow is needed)
_codereview.12303
Summary:I've implemented what I think is a complete Java implementation of the Scala Option class. Could you please review and let me know if I have correctly and completely implemented it? And if not, could you please indicate where I have security, multi-threading, persistence, etc. defects?Details:I'm learning Scala, but still not able to use it in my projects at work. However, I have fallen in love with Scala's Option class. It's the equivalent to Haskell's Maybe. It's a great way to consistently implement the null object pattern; i.e. type safely getting rid of tons of potentially hidden NullPointerExceptions.While working on bringing some legacy Java code forward in time (written by me +10 years ago), I kept wanting to use something like Scala's Option, only written in Java for Java. Thus began my hunt for an effective Java version of Scala's option class.First, I googled and found something simple from Daniel Spiewak written in 2008: The Option Pattern.A comment by Tony Morris on Daniel's blog article (above) lead me to an article by Tony Morris where Daniel's idea was made a bit more complete, also adding to it a bit more complexity (at least to me): Maybe in Java.Then, while doing further research to try and find something already written, rather than my writing it myself, I found this one. Written earlier this year (2012), it seemed quite up-to-date: Another Scala option in Java.However, once I brought this latest code into my project to use, it started putting yellow squigglies under any references to None. Basically, the singleton the author used was leaking raw types into my code generating warnings. That was particularly annoying as I had just finished eliminating all the raw type code warnings from this particular code base the previous week.I was now hooked on getting something working that might resemble a work that could/would appear in the high-quality Java libraries, eliminating raw type leakage, adding things like serialization support, etc.Below is the result as three separate Java class files:Option - public interfaceOptional - factory for safely producing instances of Some and NoneMain - JUnit4 test suite to ensure proper functionalityPlease review and then give me any feedback and/or corrections you are willing to contribute.1. Interface Option - public interfacepackage org.public_domain.option;import java.util.Iterator;import java.io.Serializable;public interface Option<T> extends Iterable<T>, Serializable { @Override Iterator<T> iterator(); T get(); T getOrElse(T value);}2. Class Optional - Option instance factorypackage org.public_domain.option;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;public final class Optional<T> { @SuppressWarnings(rawtypes) private static volatile Option NONE_SINGLETON = new OptionImpl(); public static <T> Option<T> getSome(T value) { if (value == null) { throw new NullPointerException(value must not be null); } return new OptionImpl<T>(value); } @SuppressWarnings({unchecked, cast}) public static <T> Option<T> getNone() { return (Option<T>)getNoneSingleton(); } @SuppressWarnings(unchecked) public static <T> Option<T> getOptionWithNullAsNone(T value) { return (value != null) ? new OptionImpl<T>(value) : (Option<T>)getNoneSingleton() ; } public static <T> Option<T> getOptionWithNullAsValidValue(T value) { return new OptionImpl<T>(value); } @SuppressWarnings(rawtypes) static Option getNoneSingleton() { return NONE_SINGLETON; } private Optional() { //no instances may be created } private static final class OptionImpl<T> implements Option<T> { private static final long serialVersionUID = -5019534835296036482L; private List<T> values; //contains exactly 0 or 1 value protected OptionImpl() { if (getNoneSingleton() != null) { throw new IllegalStateException(NONE_SINGLETON already defined); } this.values = Collections.<T>emptyList(); } protected OptionImpl(T value) { List<T> temp = new ArrayList<T>(1); temp.add(value); //even if it might be a null this.values = temp; } @Override public int hashCode() { return this.values.hashCode(); } @Override public boolean equals(Object o) { boolean result = (o == this); if (!result && (o instanceof OptionImpl<?>)) { result = this.values.equals(((OptionImpl<?>)o).values); } return result; } protected Object readResolve() { Object result = this; if (this.values.isEmpty()) { result = getNoneSingleton(); } return result; } @Override public Iterator<T> iterator() { return (!this.values.isEmpty()) ? Collections.unmodifiableList(new ArrayList<T>(this.values)).iterator() : this.values.iterator() ; } @Override public T get() { if (this.values.isEmpty()) { throw new UnsupportedOperationException(Invalid to attempt to use get() on None); } return this.values.get(0); } @Override public T getOrElse(T valueArg) { return (!this.values.isEmpty()) ? get() : valueArg ; } }}3. Class Main - JUnit4 test suitepackage org.public_domain.option.test;import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertFalse;import static org.junit.Assert.assertNotSame;import static org.junit.Assert.assertSame;import static org.junit.Assert.assertTrue;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.junit.Test;import org.public_domain.option.Option;import org.public_domain.option.Optional;public class Main { @Test public void simpleUseCasesSome() { String value = simpleUseCases; String valueOther = simpleUseCases Other; //Some Option<String> optionSome = Optional.getSome(value); assertEquals(value, optionSome.get()); assertEquals(value, optionSome.getOrElse(valueOther)); assertNotSame(valueOther, optionSome.get()); assertNotSame(valueOther, optionSome.getOrElse(valueOther)); //validate simple iterator state (each call is a newly created iterator) assertTrue(optionSome.iterator().hasNext()); assertEquals(value, optionSome.iterator().next()); assertNotSame(valueOther, optionSome.iterator().next()); //ensure iterator exhausted after single return value (all on the same iterator) Iterator<String> iterator = optionSome.iterator(); assertTrue(iterator.hasNext()); assertEquals(value, iterator.next()); assertFalse(iterator.hasNext()); } @Test public void simpleUseCasesNone() { String value = simpleUseCases; String valueOther = simpleUseCases Other; Option<String> optionNone = Optional.getNone(); assertEquals(valueOther, optionNone.getOrElse(valueOther)); assertNotSame(value, optionNone.getOrElse(valueOther)); //ensure iterator is already exhausted assertFalse(optionNone.iterator().hasNext()); } @Test (expected=NullPointerException.class) public void simpleInvalidUseCaseSomePassedNull() { @SuppressWarnings(unused) Option<String> optionSome = Optional.getSome(null); } @Test (expected=UnsupportedOperationException.class) public void simpleInvalidUseCaseNoneGet() { Option<String> optionNone = Optional.getNone(); @SuppressWarnings(unused) String value = optionNone.get(); } @Test public void simpleUseCaseEquals() { String value = simpleUseCases; String valueSame = value; String valueDifferent = simpleUseCases Other; Option<String> optionSome = Optional.getSome(value); Option<String> optionSomeSame = Optional.getSome(valueSame); Option<String> optionSomeDifferent = Optional.getSome(valueDifferent); Option<String> optionNone = Optional.getNone(); Option<String> optionNoneSame = Optional.getNone(); //Some - self-consistency assertSame(optionSome, optionSome); //identity check assertEquals(optionSome, optionSomeSame); //content check assertEquals(optionSomeSame, optionSome); //symmetry check assertNotSame(optionSome, optionSomeDifferent); //identity and content check assertNotSame(optionSomeDifferent, optionSome); //symmetry check //None - self-consistency assertSame(optionNone, optionNoneSame); //identity check assertSame(optionNoneSame, optionNone); //symmetry check //Some-vs-None consistency assertNotSame(optionSome, optionNone); //identity check assertNotSame(optionNone, optionSome); //symmetry check } @Test public void useCaseSomeWithNullAsNone() { String value = null; String valueSame = value; String valueDifferent = simpleUseCases; Option<String> option = Optional.getOptionWithNullAsNone(value); Option<String> optionSame = Optional.getOptionWithNullAsNone(valueSame); Option<String> optionDifferent = Optional.getOptionWithNullAsNone(valueDifferent); //Some - self-consistency assertSame(option, option); //identity check assertEquals(option, optionSame); //content check assertEquals(optionSame, option); //symmetry check assertNotSame(option, optionDifferent); //identity and content check assertNotSame(optionDifferent, option); //symmetry check //None consistency Option<String> optionNone = Optional.getNone(); assertSame(option, optionNone); assertSame(optionNone, option); //symmetry check } @Test public void useCaseSomeWithNullAsValidValue() { String value = null; String valueSame = value; String valueDifferent = simpleUseCases; Option<String> option = Optional.getOptionWithNullAsValidValue(value); Option<String> optionSame = Optional.getOptionWithNullAsValidValue(valueSame); Option<String> optionDifferent = Optional.getOptionWithNullAsValidValue(valueDifferent); //Some - self-consistency assertSame(option, option); //identity check assertEquals(option, optionSame); //content check assertEquals(optionSame, option); //symmetry check assertNotSame(option, optionDifferent); //identity and content check assertNotSame(optionDifferent, option); //symmetry check //None consistency Option<String> optionNone = Optional.getNone(); assertNotSame(option, optionNone); assertNotSame(optionNone, option); //symmetry check } private byte[] transformToByteArray(Object root) { ByteArrayOutputStream baos = new ByteArrayOutputStream(65536); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(root); } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); } private Object transformFromByteArray(byte[] content) { Object result = null; ByteArrayInputStream bais = new ByteArrayInputStream(content); ObjectInputStream ois; try { ois = new ObjectInputStream(bais); result = ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return result; } @Test public void useCaseSerialzation() { String value = simpleUseCases; String valueSame = value; String valueDifferent = simpleUseCases Other; Option<String> optionSome = Optional.getSome(value); Option<String> optionSomeSame = Optional.getSome(valueSame); Option<String> optionSomeDifferent = Optional.getSome(valueDifferent); Option<String> optionNone = Optional.getNone(); Option<String> optionNoneSame = Optional.getNone(); Map<String, Option<String>> dataIn = new HashMap<String, Option<String>>(); dataIn.put(optionSome, optionSome); dataIn.put(optionSomeSame, optionSomeSame); dataIn.put(optionSomeDifferent, optionSomeDifferent); dataIn.put(optionNone, optionNone); dataIn.put(optionNoneSame, optionNoneSame); byte[] dataInAsByteArray = transformToByteArray(dataIn); @SuppressWarnings(unchecked) Map<String, Option<String>> dataOut = (Map<String, Option<String>>)transformFromByteArray(dataInAsByteArray); assertEquals(optionSome, dataOut.get(optionSome)); assertEquals(optionSomeSame, dataOut.get(optionSomeSame)); assertEquals(optionSomeDifferent, dataOut.get(optionSomeDifferent)); assertSame(optionNone, dataOut.get(optionNone)); assertSame(optionNoneSame, dataOut.get(optionNoneSame)); }}
Scala Option conversion to Java
java;generics
If you want to guarantee serializability, the T type parameter must be Serializable, or your Option won't be:public interface Option<T extends Serializable> extends Iterable<T>, SerializableAlso, the use of a public interface to declare Option allows anybody to create their own implementation. The code will break if it is given another implementation of the Option interface, because it assumes the only implementation is an OptionImpl.Here's an alternate implementation much the same as yours that I'd come up with:package util;import java.util.Collections;import java.util.Iterator;import java.util.NoSuchElementException;public abstract class Option<A> implements Iterable<A> { private Option() {} public abstract A get(); public abstract A getOrElse(A defaultResult); public abstract Iterator<A> iterator(); public abstract boolean match(Option<A> other); @SuppressWarnings(unchecked) public static <A> Option<A> Option(final A a) { return a == null? (Option<A>)None : Some(a); } public static <A> Option<A> Some(final A a) { return new _Some<A>(a); } @SuppressWarnings(unchecked) public static <A> Option<A> None() { return (Option<A>)None; } @SuppressWarnings(rawtypes) public static final Option None = new _None(); private static final class _Some<A> extends Option<A> { private final A value; private _Some(A a) { if (a == null) throw new IllegalArgumentException(argument to Some may not be null); this.value = a; } @Override public A get() { return this.value; } @Override public A getOrElse(final A ignored) { return this.value; } @Override public Iterator<A> iterator() { return Collections.<A>singleton(this.value).iterator(); } @Override public boolean match(final Option<A> other) { return other == None? false : value.equals( ((_Some<A>)other).value ); } @Override @SuppressWarnings(unchecked) public boolean equals(final Object obj) { return obj instanceof Option? match((Option<A>)obj) : false; } @Override public int hashCode() { return this.value.hashCode(); } @Override public String toString() { return Some( + this.value + ); } } private static final class _None<A> extends Option<A> { private _None() {} @Override public A get() { throw new NoSuchElementException(None.get() called); } @Override public A getOrElse(final A result) { return result; } @Override public Iterator<A> iterator() { return Collections.<A>emptyList().iterator(); } @Override @SuppressWarnings(rawtypes) public boolean match(final Option other) { return other == None; } @Override public boolean equals(final Object obj) { return obj == this; } @Override public int hashCode() { return 0; } @Override public String toString() { return None; } }}For usage, I use import static:import util.Option;import static util.Option.*;Option<Boolean> selfDestruct = getSelfDestructSequence();if (selfDestruct.match(Some(true)) { blowUpTheShip();}That way it reads similar to pattern matching and deconstruction, but of course it's really construction and equals(). And you can compare to None using ==.The only thing I don't like about this is that the None singleton does give unchecked warnings on usage unless you use the factory method to return it. If only we had existential types, we could overcome that.
_codereview.61209
I have some php code to style a button and activate it, when a specific variable is true.It's actually a radio button, styled with the bootstrap to a button.As you can see below, this is how it looks when the variable is '1'.Also, the buttons at the bottom are the same, but then with one extra option.The HTML code for this is the following: Navigation bar color: <?php if ($navcolor == '1') { $nav_color_i_active = 'active'; $nav_color_i_checked = 'checked'; $nav_color_n_active = ''; $nav_color_n_checked = ''; } else { $nav_color_i_active = ''; $nav_color_i_checked = ''; $nav_color_n_active = 'active'; $nav_color_n_checked = 'checked'; } ?> <div class=btn-group data-toggle=buttons> <label class=btn btn-primary <?= $nav_color_i_active ?>> <input type=radio name=navcolor value=1 <?= $nav_color_i_checked ?>> Inverted </label> <label class=btn btn-primary <?= $nav_color_n_active ?>> <input type=radio name=navcolor value=0 <?= $nav_color_n_active ?>> Normal </label> </div><div class=form-group><label>Navigation bar position: </label> <?php if ($navpos == '2') { $nav_pos_2_active = 'active'; $nav_pos_2_checked = 'checked'; $nav_pos_1_active = ''; $nav_pos_1_checked = ''; $nav_pos_0_active = ''; $nav_pos_0_checked = ''; } elseif ($navpos == '1') { $nav_pos_2_active = ''; $nav_pos_2_checked = ''; $nav_pos_1_active = 'active'; $nav_pos_1_checked = 'checked'; $nav_pos_0_active = ''; $nav_pos_0_checked = ''; } else { $nav_pos_2_active = ''; $nav_pos_2_checked = ''; $nav_pos_1_active = ''; $nav_pos_1_checked = ''; $nav_pos_0_active = 'active'; $nav_pos_0_checked = 'checked'; } ?> <div class=btn-group data-toggle=buttons> <label class=btn btn-primary <?= $nav_pos_2_active ?>> <input type=radio name=navpos value=2 <?= $nav_pos_2_checked ?>> Floating </label> <label class=btn btn-primary <?= $nav_pos_1_active ?>> <input type=radio name=navpos value=1 <?= $nav_pos_1_active ?>> Sticky to top </label> <label class=btn btn-primary <?= $nav_pos_0_active ?>> <input type=radio name=navpos value=0 <?= $nav_pos_0_active ?>> Dynamic, stick to top </label> </div> </div>As you can see, it's a lot of code for not a lot of buttons. I've used empty variables, because otherwise php would return errors, for unknown variables.Is it possible that this code can look a lot cleaner, and that there can be less code?
Styling and activating radio buttons on condition
php;twitter bootstrap
Firstly, you could shorten the names of the variables e.g from $nav_color_i_active to $i_active and so on.Secondly, there is a problem in your logic. You see else part will run if $navcolorhas any value other than 1. You should use elseif instead of else in both parts of code.
_webapps.45991
I've tried to find a way to enable 2 factor authentication for login to the Google Apps management console (admin.google.com), but can't seem to find it. (I already have 2 factor auth for my users on the domain, so it is not for domain users but for the admin console I want to enable it.)Have googled for it and searched here also, but can't seem to find the answer/way to enable it.Can anyone help, please?
Is 2 factor authentication available for login to the Google Apps management console?
google apps
Based on my own testing, it seems that Google Apps users who have enabled 2-factor authentication for their account will also be required to input a verification code when logging into the management console. This has two key implications:The only way to enforce 2-factor authentication for the management console is by ensuring that all users who can access the console have 2-factor auth enabled. As I understand it, it's not possible to force your users to enable this feature, the only thing you can do is choose to make the feature available to them (or not, obviously) and encourage all users to enable it.Any user who has asked for their device to be 'remembered' when logging in using 2-factor auth will not be required to enter a verification code to log into the management console unless they clear their cookies or use a different device.In summary, 2-factor auth works as expected with the management console, but it must be enabled on a per-user basis.Assuming that you have enabled 2-factor auth for your Google apps account, you can test the above by logging into the console from an Incognito window or an alternative browser. It should then ask you for a verification code as expected.
_scicomp.19279
In the method of weighted residual applied to boundary value problems, is it necessary for the basis function to satisfy all of the boundary conditions? Will it work even if it does not satisfy all of the boundary conditions?
In the method of weighted residual, is it necessary for the basis function to satisfy the boundary conditions?
boundary conditions
null
_vi.9927
I have a command defined in my ftplugin/markdown.vim to maintain a consistent style, and check for any errors:command! Lint !pandoc % -o % --columns=80However, when I run :Lint I then need to hit L<CR> followed by :e.Is there any way of defining this command such that it will reload automatically, with no further keypress?
Automate file reload after command that modifies it?
vimrc;command line
Your command tells pandoc to filter your file (%) instead of your buffer. This is problematic because there's no guarantee that the content of the buffer and the content of the file are identical. What you need is a filter, not something that acts on actual files.The default behavior of pandoc is to act as a filter, which happens to be exactly what you want: take text from stdin and return a filtered version of it to stdout::!pandoc --columns=80But pandoc's default output format for markdown is HTML if you don't specify any so you should use -t markdown to force markdown output:!pandoc -t markdown --columns=80But even that is not enough to make a proper custom command:command! Lint !pandoc -t markdown --columns=80The first problem is that custom commands don't accept a range by default. This is easy to fix with :help :command-range:command! -range=% Lint execute <line1> . , . <line2> . !pandoc -t markdown --columns=80At this stage, you can do :Lint or :24,67Lint or vjjjjj:Lint and get exactly what you want But we still have three problems to address.The second problem is that this command will leave the cursor on the last line of the buffer. This is not really a showstopper but oh well! We can fix it with :help winsaveview() and :help winrestview():command! -range=% Lint let myview = winsaveview() | \ execute <line1> . , . <line2> . !pandoc -t markdown --columns=80 | \ call winrestview(myview)The third problem is that this command will also be available in non-markdown buffers because all custom commands are global by default. This is another easy fix thanks to :help :command-buffer:command! -buffer -range=% Lint let myview = winsaveview() | \ execute <line1> . , . <line2> . !pandoc -t markdown --columns=80 | \ call winrestview(myview)The fourth and last problem is a lot less severe than the others. It's just that ftplugin/markdown.vim is not really the right place for language-specific settings/mappings/commands due to the order in which filetype plugins are sourced:#1 $HOME/.vim/ftplugin/markdown.vim#2 $VIMRUNTIME/ftplugin/markdown.vim#3 $HOME/after/ftplugin/markdown.vimYou should use $HOME/after/ftplugin/foo.vim for all your filetype specific needs.Wow What a ride!
_cs.74073
I am trying to understand the time complexity of the word break problem which uses the backtracking recursive approach. It is O(2^N).Well lets take an example abcd as input with the recursive approach naive, the recursion tree will be something like this abcd /.... \ /\ /\ a bcd..abc d / \ /\ b cd So eventually at the end of the tree, I mean the leaves the count will be (2^N). is that right?
Why is the time complexity of the word break O(2^N)
algorithms
null
_unix.83695
I have some AIX 7 servers that are restricted to what software I can install and wonder if I can get ksh to use the tab key to complete filenames at the shell promot.The man pages are sparse for ksh and I don't see any relevant questions here covering this ground. Due to the majority of users using ksh, I'm hesitant to shift my shell to bash - but I suppose that's an easy out.I log in initially from a PC using putty/ssh and work mostly from xterm once the X11 forwarding brings back the traffic to Hummingbird Exceed on the PC.Can /usr/bin/ksh that ships with bos.rte.shell for AIX 7.1 be configured to trigger filename completion (which is normally triggered by pressing ESC+\ ) by pressing the TAB key?
Can ksh on AIX be configured to use the tab key for filename completion?
ksh;aix
See if /usr/bin/ksh93 is available:ksh93 --versionIf it saysversion sh (AT&T Research)then use that as your interactive shell. It will have the ${.sh.version} and should have the TAB expansion.
_cs.32554
I am trying to classify the Differential Evolution algorithm according to the framework in the book:Introduction to Evolutionary ComputingThe authors classify the field of evolutionary computation into 4 paradigms:Evolutionary programmingGenetic programmingEvolutionary strategiesGenetic algorithmsI have ruled out 1. and 2., since they deal with programs as opposed to abstract optimization problems. I also ruled out 3. since evolutionary strategies maintain an explicit random distribution during the optimization process. That leaves only genetic algorithms. But when you say genetic algorithm, the firs thing that comes to most peoples' minds is the traditional flipping of 0s and 1s. I have personally never heard anybody refer to differential evolution as a genetic algorithm.
Is Differential Evolution a genetic algorithm?
optimization;genetic algorithms;evolutionary computing
If you're asking for a homework assignment, then I can't really help you, because the answer really depends on how your professor interprets the taxonomy. But if you're asking for your own edification, I can give you my view.First, the distinctions between the four classes you list (particularly between 1, 3, and 4) are largely historic. There are still some very real differences of course, but we don't view the lines between them as sharply as we once did. This means, for example, that GAs can be real-valued instead of binary and might rely on mutation more than crossover. You can have an evolution strategy for the traveling salesman problem. Really the description in the book isn't terribly well suited for use as a taxonomy for this reason. I teach from this book, and I like it a lot, so that's not really a criticism. I don't think the authors intended for you to try and use it as a well-defined taxonomy either.If we go with this idea as a rough taxonomy though, then in principle, we have an umbrella term: Evolutionary Computation or Evolutionary Algorithms that covers all four of the cases you list. In practice though, while if someone says evolution strategy or genetic programming, it's because they intentionally want to highlight that that's what they're doing, people sometimes say genetic algorithms when they really mean evolutionary algorithms. So that term is especially hard to interpret.So we might be able to call DE a GA with that understanding and be OK, but it really depends on who's asking the question as to whether that's what they had in mind or not.Looking at the problem another way though, it gets even fuzzier. Right now, you're reading someone else's taxonomy and trying to fit the pieces together. What if you take a step back and try to formally define what a genetic algorithm or evolutionary algorithm is yourself? You might come up with something like an algorithm that maintains a population of one or more candidate solutions, usually generated randomly, and continually selects the better individuals from the population, produces new individuals from the old ones via some type of variation operators, and favors the better of these new individuals for insertion into the population.It's hard to get much narrower than that without excluding some things we think are obviously evolutionary algorithms, but this definition is really very broad. Certainly things like differential evolution and particle swarm optimization meet this definition, but so does, for example, simulated annealing. You can even take a simple next-descent hill-climber and call it a (1+1)-ES.Personally then, my answer to your question is sort of. If I write a paper that proposes a novel DE variant that looks super-awesome, I'd absolutely submit it to a journal like Evolutionary Computation. I know that my algorithm would be viewed as being appropriate for a venue that focused on genetic and evolutionary algorithms. But I probably wouldn't tell people that I used a genetic algorithm either, because that term doesn't feel precise enough to capture what it is that I want to express.I'm not sure this is a particularly helpful answer, but I think it's probably a pretty common view among people in the field.
_cs.41199
I really get confused by all the different complexities you find around. One is $O(n \log n)$, the next $O(n \cdot |\Sigma|)$. Personally I think it's the last one, but I'm really not that confident with it to say so. Well on average we go $\log n$ deep and need at max $|\Sigma|$ steps to find a corresponding node that matches (or not). Thus I would come up with $O(n \cdot |\Sigma| \cdot \log n)$.Repeat the following for all suffixes of the given string, right to left.Scan if its in tree Not in tree -> add it as new nodeIs partly in tree -> fork here, such that the matching part remainsGo back to step 1 until the sequence that was observed equals the source
Suffix Tree algorithm complexity
algorithms;algorithm analysis;data structures;runtime analysis;suffix trees
null
_ai.1423
We, humans, during following multiple processes (e.g. reading while listening to music) memorize information from less focused sources with worse efficiency than we do from our main concentration.Do such things exist in case of artificial intelligences? I doubt, for example that neural networks obtain such features, but I may be wrong.
Is there any artificial intelligence that possesses concentration?
structured data
Douglas Hofstadter's CopyCat architecture for solving letter-string analogy problems was deliberately engineered to maintain a semantically-informed notion of 'salience', i.e. given a variety of competing possibilities, tend to maintain interest in the one that is most compelling. Although the salience value of (part of) a solution is ultimately represented numerically, the means by which it determined is broadly intended to correspond (at least functionally) to the way 'selective attention' might operate in human cognition.
_unix.152756
I've found some anomaly when writing a script.The following examples works as expected:$ echo 123 | awk '{print $1 456}'123456$ sh -c echo 123 | awk '{print $1}'123But the following example, doesn't:$ sh -c echo 123 | awk '{print $1 456}'456I'm expecting to print the 1st column with the additional string, which should return 123456 as it does when running the same command withoutsh -c. But what is happening, the 1st column is ignored for some reason. What's interesting, $1 is printed without problems when not performing string concatenation.Why this is happening and how to do string concatenation within the command which is passed to separate instance of shell?
awk: Columns are not printed when concatenating strings is passed as command string
sed;awk
You must escape $ sign:$ sh -c echo 123 | awk '{print \$1 456}'123456Otherwise, $1 is expanded by current shell.
_scicomp.20060
I am setting up a simple model that uses recursion to iterate between known constraints - relaxation, in other words. I need a spreadsheet that allows:A0 50A1 =(A0+A2)/2A2 =(A1+A3)/2A3 =(A2+A4)/2A4 100It should be simple, but OpenOffice and Apple Numbers specifically forbid this. If you know of configuration setting to override this, that would be great too.
Relaxation - spreadsheet solution to recursive algorithm
numerical modelling
null
_hardwarecs.2620
I'm looking for electromagnetic field reader as demonstrated in the this documentary (shown below):Or some similar device which can do the same (measure EMF fingerprint of the placed object).
EMF reader for USB
usb
I'm finding this hilarious. The pseudoscience is stunning. That device is a pretty standard microphone that was used for attaching to a landline. The proper name escapes me (I'll update) but you can find it as a telephone suction cup microphone for between 5-20 dollars on amazon. I am unable to identify the sound card he is using for the capture, and the software he's using seems to be wavelab. Any good soundcard should work for this I suspectI'd note those things are good fun, and he might be picking up noise off of his power lead. I'm unsure what the seemingly quarter inch connector is leading off of the sound device.
_unix.306286
I have a healthy and working software based RAID1 using 3 HDDs as active on my Debian machine.I want to mark one of the disks as a spare so it ends up being 2 active + 1 spare.Things like:mdadm --manage --raid-devices=2 --spare-devices=1 /dev/md0and similar just fail saying either one of the options is not supported in current option mode or simply fails.Billy@localhost~#: mdadm -G --raid-devices=2 /dev/md0mdadm: failed to set raid disksunfreezeorBilly@localhost~#: mdadm --manage --raid-devices=2 --spare-devices=1 /dev/md0mdadm: :option --raid-devices not valid in manage modeor similar. I have no idea man. please help?
How to mark one of RAID1 disks as a spare? (mdadm)
hard disk;array;raid1
You can check the current state of the array with cat /proc/mdstat. In this example, that's where the data comes from.So let's assume we have md127 with 3 disks in a raid1. Here they're just partitions of one disk, but it doesn't mattermd127 : active raid1 vdb3[2] vdb2[1] vdb1[0] 102272 blocks super 1.2 [3/3] [UUU]We need to offline one of the disks before we can remove it:$ sudo mdadm --manage /dev/md127 --fail /dev/vdb2mdadm: set /dev/vdb2 faulty in /dev/md127And the status now shows it's badmd127 : active raid1 vdb3[2] vdb2[1](F) vdb1[0] 102272 blocks super 1.2 [3/2] [U_U]We can now remove this disk:$ sudo mdadm --manage /dev/md127 --remove /dev/vdb2mdadm: hot removed /dev/vdb2 from /dev/md127md127 : active raid1 vdb3[2] vdb1[0] 102272 blocks super 1.2 [3/2] [U_U]And now resize:$ sudo mdadm --grow /dev/md127 --raid-devices=2raid_disks for /dev/md127 set to 2unfreezeAt this point we have successfully reduced the array down to 2 disks:md127 : active raid1 vdb3[2] vdb1[0] 102272 blocks super 1.2 [2/2] [UU]So now the new disk can be re-added as a hotspare:$ sudo mdadm -a /dev/md127 /dev/vdb2mdadm: added /dev/vdb2md127 : active raid1 vdb2[3](S) vdb3[2] vdb1[0] 102272 blocks super 1.2 [2/2] [UU]The (S) shows it's a hotspare.We can verify this works as expected by failing an existing disk and noticing a rebuild takes place on the spare:$ sudo mdadm --manage /dev/md127 --fail /dev/vdb1mdadm: set /dev/vdb1 faulty in /dev/md127md127 : active raid1 vdb2[3] vdb3[2] vdb1[0](F) 102272 blocks super 1.2 [2/1] [_U] [=======>.............] recovery = 37.5% (38400/102272) finish=0.0min speed=38400K/secvdb2 is no longer marked (S) because it's not a hotspare.After the bad disk has been re-added it is now marked as the hotsparemd127 : active raid1 vdb1[4](S) vdb2[3] vdb3[2] 102272 blocks super 1.2 [2/2] [UU]
_softwareengineering.336915
I currently work on a hobby project which I use to learn more about Android/Java programming and programming in general. Recently, I decided to integrate jUnit into the project. Just getting it in there wasn't much of a problem, but actually using it was. I've read that a unit test should be the definition of what a method (or component) is supposed to do, and that unit tests force you to write good, or at least better code.But the problems started occurring the moment I wrote the first unit test to test some logic. The method I wanted to test does only logical work, nothing with the UI is done and the results are simply saved in variables for later use. But, in the same class, I have a method to display whatever the first method has worked out. And jUnit doesn't seem to like that; for the second method I need (of course) UI imports, and jUnit complains that it doesn't know any Android Context class. Until now, I thought that putting the logical and UI parts of a component in one class but seperated methods would be easily understandable and an acceptable practice. But now, because jUnit forces you to write good code, I'm much less sure about this.So, should I put the UI and logical parts for one component in seperate classes? They depend on each other, the UI method needs the values from the logical method, but the logical method can't do anything with its computed values without the UI method. But because someone else might think different about this... And that someone else is the one who probably has to understand my code somedays afterall.
Should I put UI and logic in separate classes?
class design;ui
UI design patterns like Model-View-Controller, Model-View-Presenter and Model-View-ViewModel routinely provide mechanisms (i.e. separate classes) that allow Separation of Concerns between the surface of the UI and the class that manages it, for the same reasons that you've already cited.
_unix.306741
I am trying to recover all my deleted folders and files The first step I took was Inode Owner Mode Size Blocks Time deleted8391823 0 120777 3 1/ 2 Wed Jul 6 00:21:52 20166816215 0 120777 3 1/ 2 Tue Aug 30 22:23:12 20166816241 0 120777 3 1/ 2 Tue Aug 30 22:23:12 20166816248 0 120777 2 1/ 2 Tue Aug 30 22:23:12 20166816268 0 120777 2 1/ 2 Tue Aug 30 22:23:12 20166816336 0 120777 2 1/ 2 Tue Aug 30 22:23:12 20166816338 0 120777 2 1/ 2 Tue Aug 30 22:23:12 20166816340 0 120777 2 1/ 2 Tue Aug 30 22:23:12 20168 deleted inodes found.root@kali:~# df /rootFilesystem 1K-blocks Used Available Use% Mounted on/dev/sda5 192360020 12389648 170176020 7% /root@kali:~# debugfs -w /dev/sda5debugfs 1.42.12 (29-Aug-2014)debugfs: lsdeldebugfs: logdump -i <8391823>Inode 8391823 is at group 1024, block 33554564, offset 1792Journal starts at block 24819, transaction 1055643No magic number at block 25323: end of journal.debugfs: logdump -i <6816215>Inode 6816215 is at group 832, block 27263022, offset 2816Journal starts at block 24819, transaction 1055643No magic number at block 25628: end of journal.debugfs: logdump -i <6816241>Inode 6816241 is at group 832, block 27263023, offset 2048Journal starts at block 24819, transaction 1055643No magic number at block 25696: end of journal.debugfs: logdump -i <6816248>Inode 6816248 is at group 832, block 27263023, offset 2944Journal starts at block 24819, transaction 1055643........What would be the next step for me to recover all my files and folders
How should I restore my files after I get the following output
kali linux;data recovery
null
_codereview.49550
I am making an application which fetches tweets for a specified amount of time, then inserts those tweets in a database and when the user presses another button the top n words and the hashtags will be shown.This is my Twitter package:[Package]Twitter >[Class]TwitterTools.javaThis is my Analyzing package:[Package]Analyzing >[Class]WordCounting.javaThis is the TwitterTools class:public class TwitterTools { public static List<Status> search(Query query) { } public static void filterTweetsBasedOnCity(List<Status> tweets, final String city) { } public static Query queryMaker(final String keywords, final Date since, final Date until, final int count) { }}search - returns a list of status based on a queryfilterTweetsBasedOnCity - deletes status from a list if they were not made in a certain cityqueryMaker - makes a query based on the parametersThis is the WordCounting class:public class WordCounting { public static String getHtmlTable(final List<String[]> words, final List<String[]> hashtags) { } public static Stream<Map.Entry<String, Long>> getTopWords(final int topX, final Stream<String> words) { } public static String listToHtmlTable(List<Map.Entry<String, Long>> topEntries, final String title) { }}getHtmlTable - returns the html table of the top X wordsgetTopWords - returns a stream of the top wordslistToHtmlTable - converts a list to an html tableMy question is how should I arrange these two packages. Should I merge them since they have only one class each? Should I split them even more by having some of the functions in another class?
Putting in order my two packages and possibly merging them
java;classes
The ideal package structure is one which indicates usage. Classes such as these which exclusively contain static methods are definitely utility classes, which I usually put in a util subpackage of your main application.From what it sounds like, you don't have a main package at the moment which ideally would be your website (in reverse domain order), e.g. com.stackexchange.codereview so that the more specific elements are later, then on top of that you'd have the name of your application which may make it something like com.stackexchange.codereview.tweettrends.This would be the core of your program, and from here you could then add on your extras.The Twitter package in particular doesn't sound helpful: your entire program seems to relate to Twitter so it doesn't really convey what that part of the program does. Frankly, I'd just put all those classes under com.stackexchange.codereview.tweettrends.util and add in more sub-packages if you add more classes.And generally speaking, in Java packages should be exclusively lowercase.
_webmaster.4331
I've got a shared hosting account on GoDaddy, however my domain name is registered at a seperate company. Assuming I already know how to point my domain name to whatever I want, how do I set up GoDaddy to accept the whatever domain name I want, and how do I find the proper address for my GoDaddy hosting so that I can point my domain name to?
GoDaddy shared hosting with domain registed at a different registrar
domains;web hosting;shared hosting
When you sign up for Godaddy shared hosting they usually send you and email afterwards with the server's IP. Once you have the IP address go to the site that is hosting your domain name and change the Host (A)Record within the DNS setting to reflect the new IP address. It will take an hour or an hour and a half based upon what the TTL is set to.
_softwareengineering.313291
I am developing an application which sends certain notifications to the user as read from a read-only external service. The user might dismiss notifications, and those should not appear again.I cannot ask the server to give me only entries newer than than my last query because I am particularly interested in a value that changes over time. I have to give entries a chance for at least a week or so. Because of that, the queries to the service might return data which were already retrieved before, and I need to filter the ones already dismissed. I can do that by looking at the IDs of the received entries, which appear to be SHA hashes.I can save those IDs to the Preferences as id -> boolean pairs, or in a SQLite database, but surely they will reach some limit sooner or later.Also, I do not really need to check the older entries. I could put a hard limit on, say, the 100 latest entries and that should be more than enough.How should I approach the disposal of old entries to ensure I don't go over the limits?EDIT: As requested, more information about the problem which might be useful:My query currently is of the form the latest 1000 entries, from newest to oldest, if they are newer than 2 weeks. 1000 is a number so high that is effectively infinite, for the purposes of my application. 2 weeks is a time interval so long that the user should not want to be notified about that information anymore, as it is highly unlikely to become relevant by that time.All entries have a created timestamp. They also have an updated timestamp, which, if exists, should be treated as the created date for the purposes of my application. I do not expect answers to account for this technicality, though.All entries have an importance coefficient, which is the value I am tracking. I notify the user only of entries with this coefficient higher than a set threshold. Since this value changes over time, I cannot simply ignore entries I have already fetched before and found to not be relevant. Changes in this value do not affect the updated field.If the user dismisses the notification about an entry, its notification should be filtered out the next time a query happens. Comparing the IDs is enough for that.
How to save a list of strings which might grow too large but old data is not useful
design;android
Just an idea, maybe I misunderstood some parameters of the problem. I'll offer my solution anyway, as a start to work towards something functional.At retrieval time:retrieve from read-only database only entries that are either newer than your last query or newer than 1-2 weeksfilter out the entries that have already been dismissed comparing their ID's with the ones you saved in your SQLite databaseIn addition, if you are afraid to run out of space in your SQLite database, or anyway want to forget about the old dismissed notifications:once every week, check which ones of the entries of your SQLite database are older than 2 weeks (either running a cross-check with the read-only database, or just saving their entrance date in your SQLite database), and delete them
_unix.359453
I am trying to deploy an ntp server in my local network, so I followed these steps (i used the tutorial here):apt install chronyAnd I added the following lines:server time.google.com iburstallow 0/0Then I made a :service chrony restartI am suposed to have an output like this:# chronyc sources 210 Number of sources = 2 MS Name/IP address Stratum Poll Reach LastRx Last sample ========================================================================== ^* 192.0.2.12 2 6 177 46 +17us[ -23us] +/- 68ms And this is my output:# chronyc sources210 Number of sources = 1MS Name/IP address Stratum Poll Reach LastRx Last sample ==========================================================================^? time3.google.com 0 8 0 - +0ns[ +0ns] +/- 0nsAs you can see the +0ns[ +0ns] +/- 0ns do not change and the clock does not synchronise with the google server -- where is the problem ?
Chrony does not want to synchronize
linux;ntp;chrony
null
_unix.362839
I have a large .csv file where I need to split a specific column by string length. I'm trying to take the last 6 characters of column 2 and move them into a new column.Current:3102017,90131112,0,7403022017,8903944,90,03092017,127037191,475,0Desired:3102017,90,131112,0,7403022017,8,903944,90,03092017,127,037191,475,0
Use AWK to split substring by last n characters in to a new column
text processing;awk;sed;perl;csv simple
With a POSIX-compliant awk:awk -F, -v OFS=, '{sub(/.{6}$/, OFS &, $2); print}'With a POSIX-compliant sed:sed 's/^\([^,]*,[^,]*\)\([^,]\{6\}\)/\1,\2/'Those modify the lines only if the second field is at least 6 characters long (note that it will happily change 111,123456,333 to 111,,123456,333 leaving the second field empty).
_unix.22114
Is there an easy way to move to the next capital letter with vim? I'm often working with camel-cased variables and it could be useful.
Move to next capital letter
vim
There are a few scripts out there to redefine the word motion commands (b, e, w) to stop at capital letters in CamelCase words; camelcasemotion looks well-established (disclaimer: I've never used it). The Vim wiki has a few examples of simpler scripts if you prefer to do it yourself. Here's a relatively simple way to remap C-Left and C-Right to handle caml-cased words.nnoremap <silent><C-Left> :<C-u>call search('\<\<Bar>\U\@<=\u\<Bar>\u\ze\%(\U\&\>\@!\)\<Bar>\%^','bW')<CR>nnoremap <silent><C-Right> :<C-u>call search('\<\<Bar>\U\@<=\u\<Bar>\u\ze\%(\U\&\>\@!\)\<Bar>\%$','W')<CR>inoremap <silent><C-Left> <C-o>:call search('\<\<Bar>\U\@<=\u\<Bar>\u\ze\%(\U\&\>\@!\)\<Bar>\%^','bW')<CR>inoremap <silent><C-Right> <C-o>:call search('\<\<Bar>\U\@<=\u\<Bar>\u\ze\%(\U\&\>\@!\)\<Bar>\%$','W')<CR>
_softwareengineering.332214
First let me explain what is my understanding of the terms statically typed language and type safety:Statically typed language: a language that does not allow you to change the type of a variable at run-time.Type safety: type safety means that you are not allowed to mix incompatible data types.For example, you cannot assign a float to an int, and you cannot assign an int to a function pointer, and you cannot add a user-defined object to an int (unless you use operator overloading), etc.Back to my question, let's say that there is an interpreted statically typed language, in such a language I can write code that assigns a float to an int, but when this code is executed, a (run-time) type error will occur.Is such a language considered to be type safe, or are type safe languages can only be statically typed and compiled, and so type errors must be caught at the compilation stage?
Can an interpreted statically typed language be considered type safe?
data types;dynamic typing;static typing;type safety
null
_codereview.165045
I am writing a program which downloads a file from a URL. Because the name of the downloaded file depends on the url, there is a risk of duplication if the user downloads the same file twice. For example if the url is : http://www.example.org/myfile.zip The downloaded file name will be myfile.zip. and if the user downloads it again the name will be myfile(1).zipTo achieve this, I wrote the following code : //A file already exist, we use the usual name //but add a number before the extension like Name(X).extension X being a number //Append the number just before the file extension auto pos = name.find_last_of(.); std::string nameWithoutExt = name.substr(0, pos); std::string extension = name.substr(pos); std::ostringstream possibleName; int i = 1; do { //Clear the string stream possibleName.str(); possibleName.clear(); possibleName<< nameWithoutExt << ( << std::to_string(i) << ) << extension; ++i; //Check if a file with the possible name exists } while (std::experimental::filesystem::exists(builder.str())); name = builder.str();This solution does not look optimal to me, because it may require a lot of calls to std::experimental::filesystem::existsfunction. Are there any ways to improve this?
generate a file name with format Name(Number).extension
c++;file;file system;c++14
There are a couple of improvements that I think you might make to this code.Provide complete code to reviewersThis is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.Use standard functions where appropriateSince you're already using the experimental/filesystem routines, why not make better use of them? Here is a function called uniqueName which shows one way to do that using your current strategy:fs::path uniqueName(const std::string &name) { fs::path possibleName{name}; auto stem = possibleName.stem().string(); auto ext = possibleName.extension().string(); for (int i=1; fs::exists(possibleName); ++i) { std::ostringstream fn; fn << stem << ( << i << ) << ext; possibleName.replace_filename(fn.str()); } return possibleName;}As suggested by the name of the function, this routine takes the name of a file and either returns it unaltered if no such file exists in the current directory or returns an altered filename as per your schema. Be aware that after this function is called, some other process could create a file with the same name.Create a list and use itAs shown in the review by @yuri, you could create a list and then use that. It has the same potential problem noted above in that another process could create additional files after the list is created. This version does not require any regex:std::unordered_set<std::string> create_file_list(){ std::unordered_set<std::string> m{}; for (const auto item : fs::directory_iterator{fs::current_path()}) { m.emplace(item.path().filename().string()); } return m;}This creates a list of just the filenames (stripping the path). This can then be used in a minor variation of the routine shown above. Note that only a single line is different.fs::path uniqueName(const std::string &name, const std::unordered_set<std::string> files) { fs::path possibleName{name}; auto stem = possibleName.stem().string(); auto ext = possibleName.extension().string(); for (int i=1; files.find(possibleName.string()) != files.end(); ++i) { std::ostringstream fn; fn << stem << ( << i << ) << ext; possibleName.replace_filename(fn.str()); } return possibleName;}
_webapps.88415
I read that is not possible to delete sent messages in Facebook here:How can I delete Facebook messages sent to other users?, but an answer there says that there's a work around like this: mark the message as Spam or Abuse (in Actions), then delete it from your messages, and disable/deactivate your account.I tried this but there's not a option to mark my own messages as spam, when I go to the all-chats interface, when I select a conversation with a friend there's a action menu that let me mark something as spam (I believe that's the whole conversation that's fine by me) but I don't know if this would work since I believe that I would be marking as spam their messages and not mine, so if I press that button I think that I would be marking their messages as spam so they would be still able to watch and read my messages.So how this work-around works if I can't mark my own messages as spam before deleting them. I know that this trick work since I have a few conversation when a yellow rectangle appears instead of my friend messages saying that the messages was marked as spam even knowing that I didn't marked their messages as spam.
How can you mark your own sent messages in a chat as spam in Facebook
facebook;facebook chat;facebook messages
null
_webmaster.19160
I'm trying to optimize my website and running a few tests using webpagetest.org. I tried the test from Singapore and Hongkong. I saw that while all facebook, quantcast, chitika scripts were loading from singapore/hongkong servers, but jquery (google hosted), plusone.js, twitter etc were loading from the mountain view/palo alto/cambridge servers.Since I'm using cloudflare, I can see that one of the JS files that I host on my server was actually loading from one of cloudfare's singapore servers.So is there a real benifit of using google hosted jquery etc? Sample test results are here 1) For my website's home page (http://www.humbug.in) - Test Location Singaporehttp://www.webpagetest.org/result/110904_89_1G8RF/1/details/2) For the url of this question - Test Location Amsterdamhttp://www.webpagetest.org/result/110904_B6_1G93M/1/details/In both cases jquery is being loaded from mountain view servers
Do Google/Twitter etc actually use distributed servers to serve their resources?
cdn;page speed;geolocation
null
_unix.186418
This works to change the background color for the entire terminal with xterm:printf '\033]10;%s\a\033]11;%s\a' Blue RedIt doesn't work in xfce4-terminal, tho. Is there something that will work? Note, I want a command line solution.
using ansi escape codes to change the background color in xfce4-terminal
colors;escape characters;xfce4 terminal
null
_computergraphics.170
It is no secret that according to the official documentation extensions are not available under OpenGL ES 2.0. Nevertheless, the glext.h file present in the NDK platform-include directories makes me think that extensions are indeed available. I know that working with OpenGL under NDK doesn't differ from working with standalone OpenGL. So, if I make something like a JNI bridge between my java engine interface and these extensions, I could use them.So the question is: what architectural solution should I use if I want to use available OpenGL ES extensions on ES2.0 devices?
Using extensions in Android OpenGL ES 2.0
opengl;android
null
_softwareengineering.216899
In Python we have yield which is very similar to that one which is proposed in ES6 (in fact, pythonic co-routines were the main source of inspiration for implementing co-routines inI wonder what are the reasons for choosing a separate function* () syntax for generators compared to just defining regular functions with yeilds - just like in python by the way? I'm talking strictly of technical issues and peculiarities. Why it had been decided that a separate form will be more appropriate?
Are there any technical obstacles for implementing `function* ()` syntax
javascript
Because code that uses yield normally as variable would change its meaning:function test() { var yield = 3; return yield + 2 //in current javascript this means return 5 //but if yield syntax was enabled for all //functions then it would secretly change meaning}
_codereview.166496
I've to simulate exactly a recursive algorithm with an iterative one.Assuming that I have a binary search tree that contains only a key and two references at his right and left child I want to do this count:CountOddRec(T) ret = 0 if T != NIL then if T->key % 2 = 1 then ret = T->key rsx = CountOddRec(T->sx); rdx = CountOddRec(T->dx); ret = ret + rsx + rdx; return retBasically my idea is to use the general scheme of iterative binary tree visit to do that:VisitIter(T) last = NIL curr = T stk = NULL while (curr != NIL || stk != NIL) do if curr != NIL then //Pre-order visit stk = push(stk, curr) next = curr->sx else curr = Top(stk) if (last != curr-> dx) then //In-order visit if (last != curr-> dx && curr->dx != NULL) then next = curr->dx else //Post-order visit stk = pop(stk) next = NIL last = curr curr = nextNow I know that this one should be in Pre-order block: if T->key % 2 = 1 then ret = T->keyThe rsx = assignment should be in-order, and rdx = assignment and last block should be in post-order.Now here I'm stuck, I ask if someone could help me to understand how finish the algorithm.This is my first attempt that should work:CountOddIter(T) last = NIL curr = T stk = NULL //stack Sret = NULL //stack Srsx = NULL //stack ret = 0 while (curr != NIL || stk != NIL) do ret = 0 if curr != NIL then //Pre-order block if (curr->key % 2 == 1) then ret = curr->key Sret = push(Sret, ret) stk = push(stk, curr) next = curr->sx else curr = Top(stk) if (last != curr-> dx) then //In-order block Srsx = push(Srsx, pop(Sret)) if (last != curr-> dx && curr->dx != NULL) then next = curr->dx else //Post-order block rdx = pop(Sret) rsx = pop(Srsx) r = pop(Sret) ret = rdx + rsx + r Sret = push(Sret, ret) stk = pop(stk) next = NIL last = curr curr = nextThis solutions works if I assume that a pop on an empty stack returns 0.Any other suggestions? Improvements? Is it really correct? Please can I have some feedback?Many thanksWorking code (main.c):#include <stdio.h>#include <stdlib.h>#include stack.h#include stack_int.h#include tree.hint countOddRic(tree_p T){ int ret = 0; if(T != NULL){ if(T->key % 2 == 1){ ret = T->key; } int rsx = countOddRic(T->left); int rdx = countOddRic(T->right); ret = ret + rsx + rdx; } return ret;}int countOddIte(tree_p T){tree_p curr = T;tree_p next = NULL;tree_p last = NULL;stack *S = init_stack(100);stack_int *Sret = init_stackInt(100);stack_int *Srsx = init_stackInt(100);int ret = 0;while(curr != NULL || !isEmptyStack(S)){ ret = 0; if(curr != NULL){ //printf(pre-order: %d\n, curr->key); if(curr->key % 2 == 1){ ret = curr->key; } Sret = pushInt(Sret, ret); S = push(S, curr); next = curr->left; }else{ curr = top(S); if(last != curr->right){ //printf(in-order: %d\n, curr->key); Srsx = pushInt(Srsx, popInt(Sret)); } if(last != curr->right && curr->right != NULL){ next = curr->right; }else{ //printf(post-order: %d\n, curr->key); int rdx = popInt(Sret); int rsx = popInt(Srsx); int r = popInt(Sret); ret = rdx + rsx + r; Sret = pushInt(Sret, ret); pop(S); next = NULL; } } last = curr; curr = next;}printf(\nRet = %d\n, ret);}int main(void){tree_p T = NULL;insert(&T, 54);insert(&T, 12);insert(&T, 46);insert(&T, 78);insert(&T, 6);insert(&T, 434);insert(&T, 44);insert(&T, 4);insert(&T, 552);insert(&T, 216);insert(&T, 47);insert(&T, 892);insert(&T, 74);insert(&T, 62);insert(&T, 414);insert(&T, 4442);insert(&T, 86);insert(&T, 4618);insert(&T, 798);insert(&T, 74);insert(&T, 554);insert(&T, 45);insert(&T, 776);insert(&T, 98);insert(&T, 36);insert(&T, 211);insert(&T, 24);printf(Count: %d\n, countOddRic(T));countOddIte(T);return 0;}stack.c:#include stack.hstack *init_stack(int size) {stack *S = (stack*) malloc(sizeof(stack));if (S == NULL) { exit(-1);}S->size = size;S->array = (tree_p*) malloc(size * sizeof(tree_p));if (S->array == NULL) { exit(-1);}S->last = 0;return S;}int isEmptyStack(stack *S) {return S->last == 0;}int isFullStack(stack *S) {return S->last == S->size - 1;}stack *push(stack *S, tree_p elem) {if (isFullStack(S)) return S;S->last++;S->array[S->last] = elem;return S;}tree_p pop(stack *S) {if (isEmptyStack(S)) return ERR_EMPTY_STACK;S->last--;return S->array[S->last + 1];}tree_p top(stack *S) {if (isEmptyStack(S)) return ERR_EMPTY_STACK;return S->array[S->last];}void freeStack(stack *S){if(S != NULL){ free(S->array); S->array = NULL; free(S);}}void printStack(stack *S) {if (isEmptyStack(S)) return;tree_p e = pop(S);printf(|%d, e->key);printStack(S);push(S, e);}stack.h:#include <stdio.h>#include <stdlib.h>#include <time.h>#include tree.h#ifndef STACK_H_#define STACK_H_#define ERR_EMPTY_STACK NULLtypedef struct { int size; int last; tree_p *array;} stack;stack *init_stack(int size);void fillRandomStack(stack *S, int nElem);int isEmptyStack(stack *S);int isFullStack(stack *S);stack *push(stack *S, tree_p elem);tree_p pop(stack *S);tree_p top(stack *S);void freeStack(stack *S);void printStack(stack *S);#endifstack_int.c:#include stack_int.hstack_int *init_stackInt(int size) { stack_int *S = (stack_int*) malloc(sizeof(stack_int)); if (S == NULL) { exit(-1); } S->size = size; S->array = (int*) calloc(size + 1, sizeof(int)); if (S->array == NULL) { exit(-1); } return S;} void fillRandomStackInt(stack_int *S, int nElem){ while(!isFullStackInt(S) && nElem > 0){ pushInt(S, rand() % 500); nElem--; }} int isEmptyStackInt(stack_int *S) { return S->array[0] == 0;} int isFullStackInt(stack_int *S) { return S->array[0] == S->size - 1;}stack_int *pushInt(stack_int *S, int elem) { if (isFullStackInt(S)) return S; S->array[0]++; S->array[S->array[0]] = elem; return S;}int popInt(stack_int *S) { if (isEmptyStackInt(S)) return ERR_EMPTY_STACK_INT; S->array[0]--; return S->array[S->array[0] + 1];}int topInt(stack_int *S) { if (isEmptyStackInt(S)) return ERR_EMPTY_STACK_INT; return S->array[S->array[0]];}void freeStackInt(stack_int *S){ if(S != NULL){ free(S->array); S->array = NULL; free(S); }}stack_int.h:#include <stdio.h>#include <stdlib.h>#include <time.h>#ifndef STACK_INT_H_#define STACK_INT_H_#define ERR_EMPTY_STACK_INT 0typedef struct { int size; int *array;} stack_int;stack_int *init_stackInt(int size);void fillRandomStackInt(stack_int *S, int nElem);int isEmptyStackInt(stack_int *S);int isFullStackInt(stack_int *S);stack_int *pushInt(stack_int *S, int elem);int popInt(stack_int *S);int topInt(stack_int *S);void freeStackInt(stack_int *S);void printStackInt(stack_int *S);#endiftree.c:#include tree.hvoid insert(tree_p *tree, int val) {tree_p temp = NULL;if(!(*tree)) { temp = (tree_p) malloc(sizeof(tree)); temp->left = temp->right = NULL; temp->key = val; *tree = temp; return;}if(val < (*tree)->key) insert(&(*tree)->left,val);else if(val > (*tree)->key) insert(&(*tree)->right,val);else return;}tree.h#include <stdlib.h>#include <stdio.h>#ifndef TREE_H_#define TREE_H_typedef struct tree { int key; struct tree *left; struct tree *right;} tree, *tree_p;void insert(tree_p *tree, int val);#endif
Counting nodes in a binary tree with odd values, using an iterative algorithm
algorithm;c;tree;iteration
Overthinking itI think when you translated the code from recursive to iterative, you were overthinking the order of operations (i.e. preorder vs inorder vs postorder). For this task, you are simply summing all the key values that are odd. So it actually doesn't matter which traversal order you use. You can just use whatever order is the most convenient.In your iterative solution, you created three stacks. The purpose of the integer stacks was (I believe) so that you could simulate the correct order of the additions. But as mentioned above, additions can be made in any order, as long as you add each odd key exactly once to the return value. So the integer stacks are totally unnecessary.Other thingsYour indentation is off everywhere, but I'm guessing you pasted the code incorrectly.You never free your stacks, so you have a memory leak there.Your header files include headers that aren't needed by the header files themselves. You should move those #includes into the .c files, where they are actually needed.Simplified solutionHere is how you could have written your function, without any of the integer stacks:int countOddIte(tree_p root){ stack *S = init_stack(100); int ret = 0; push(S, root); while (!isEmptyStack(S)) { tree_p curr = pop(S); if (curr == NULL) continue; if (curr->key % 2 == 1) ret += curr->key; push(S, curr->left); push(S, curr->right); } freeStack(S); printf(\nRet = %d\n, ret);}Simulating exact recursionAccording to a comment by the OP, the goal was to simulate the recursion exactly no matter how strange/inefficient the code turned out. So here, I will present a rewrite to accomplish that goal (although the code is quite ugly). A few items to note:I only used one stack, but each stack frame contains the exact information that would be contained in a normal recursive stack frame for a function.I maintain a return address at all times, which determines where in the caller the function should return to. This simulates what really happens when a function returns to its caller. I had to use goto statements to accomplish this.I used a macro on the recursive call site to simplify what the call looked like (since there were two calls almost exactly the same).I combined all your code into one .c file:Here is the code:#include <stdio.h>#include <stdlib.h>typedef struct tree { int key; struct tree *left; struct tree *right;} tree, *tree_p;void insert(tree_p *tree, int val){ tree_p temp = NULL; if(!(*tree)) { temp = (tree_p) malloc(sizeof(tree)); temp->left = temp->right = NULL; temp->key = val; *tree = temp; return; } if(val < (*tree)->key) insert(&(*tree)->left,val); else if(val > (*tree)->key) insert(&(*tree)->right,val); else return;}int countOddRecursive(tree_p T){ int ret = 0; if(T != NULL){ if(T->key % 2 == 1){ ret = T->key; } ret += countOddRecursive(T->left); ret += countOddRecursive(T->right); } return ret;}typedef struct stackNode { tree_p T; int ret; int returnAddr;} stackNode;// This macro simulates a recursive function call by pushing the current// frame onto the stack and setting the variables up as if the function// had just been called.#define countOddSimRecurse(newT, newReturnAddr) \ stack[stackIndex].T = T; \ stack[stackIndex].ret = ret; \ stack[stackIndex++].returnAddr = returnAddr; \ T = newT; \ returnAddr = newReturnAddr; \ goto begin;int countOddIterative(tree_p T){ stackNode stack[100]; int stackIndex = 0; int ret = 0; int funcRet = 0; int returnAddr = 0;begin: ret = 0; if (T != NULL) { if(T->key % 2 == 1){ ret = T->key; } countOddSimRecurse(T->left, 1);ret1: ret += funcRet; countOddSimRecurse(T->right, 2);ret2: ret += funcRet; } // If the stackIndex is 0, we are returning from the initial // function call, so return for real. if (stackIndex == 0) return ret; // Otherwise we are simulating a return to one of the two possible // return addresses, ret1 or ret2. We pop the previous frame from the // stack and return to wherever returnAddr tells us to return to. // Note that the value of ret is copied to funcRet because when // we return from this recursive call, ret will be set to the value // that the caller had for that variable. int returnTo = returnAddr; funcRet = ret; T = stack[--stackIndex].T; ret = stack[ stackIndex].ret; returnAddr = stack[ stackIndex].returnAddr; if (returnTo == 1) goto ret1; else if (returnTo == 2) goto ret2;}int main(void){ tree_p T = NULL; insert(&T, 54); insert(&T, 12); insert(&T, 46); insert(&T, 78); insert(&T, 6); insert(&T, 434); insert(&T, 44); insert(&T, 4); insert(&T, 552); insert(&T, 216); insert(&T, 47); insert(&T, 892); insert(&T, 74); insert(&T, 62); insert(&T, 414); insert(&T, 4442); insert(&T, 86); insert(&T, 4618); insert(&T, 798); insert(&T, 74); insert(&T, 554); insert(&T, 45); insert(&T, 776); insert(&T, 98); insert(&T, 36); insert(&T, 211); insert(&T, 24); printf(Count (recursive): %d\n, countOddRecursive(T)); printf(Count (iterative): %d\n, countOddIterative(T)); return 0;}
_unix.212172
I am running Linux.I have a single process in a mount namespace. I did in this process a mount -t tmpfs tmpfs /mountpoint. What happens if the process exits and there are no more processes in that mount namespace?Will the filesystem be automatically unmounted? Will the mount namespace be destroyed? If the namespaces and the mount are still active how do I access it?What happens to tun/tap/macvtap interfaces if a network namespace has no more processes?
What happens if the last process in a namespace exits?
linux;namespace;network namespaces
null
_unix.57336
Currently on Ubuntu Linux, but I noticed this on other OS's too. Apparently any user can execute the sync command, but why is this? I can only see the disadvantage: system slow down due to unnecessary disk writes.Why can every user execute sync?
Why can an unpriviliged user execute the `sync` command?
hard disk;synchronization
null
_scicomp.27536
Consider one dimensional hyperbolic pde $$u_t+f'(u)u_x=0$$For the above problem ,CFL condition is $\Delta t\leq \dfrac{\Delta x}{|f'(u)|}.$ But if we include the source term $,S(u,t),$ which depend upon $u$ and $t$ in above equation i.e.$$u_t+f'(u)u_x=S(u,t)$$ What is the influence of $S(u, t)$ in the CFL condition ?.
CFL condition of source term
finite difference;cfl
null
_unix.309616
Im using packer to create automated linux golden images. When I try and run a script that requires sudo, I get the following errorsudo: no tty present and no askpass program specifiedThis error has been discussed at length on the internet, the recommended advice is use one of the following: ssh using -tRemove from /etc/sudoers Defaults:username !requirettyexport SUDO_ASKPASS=/usr/libexec/openssh/ssh-askpassAdd user to suoders group %admin ALL=(ALL) NOPASSWD:ALLI've verified that the /etc/sudoers file that ships with ubuntu 16.04 does not contain requiretty. Why does ubuntu still give error sudo: no tty present and no askpass program specifiedhttps://github.com/mitchellh/vagrant/issues/1482 https://askubuntu.com/questions/281742/sudo-no-tty-present-and-no-askpass-program-specified
How to disable requiretty on ubuntu 16.04
sudo;tty;pty
null
_unix.339281
As far as I know, once an inode of a file is found, finding the data is trivial - done by accessing a specific location on the disk, which is stored in the inode. The question however is how exactly are the inodes found, when the system is given a filepath? The purpose of my question is mainly the desire to grasp the way the b-trees are implemented in real life. I understand the general idea of it, I would like to know how exactly it is implemented in Unix filesystem (if at all), though. Does each node of the tree store the inode number, with the leaves additionally storing the address on the disk of the inode itself? Or maybe the consecutive parts of the filepath?Does the implementation vary depending on whether the disk is a hard drive or an SSD?
How exactly are files located under the hood?
filesystems;ssd;inode;tree
null
_codereview.127351
I have a table that name is Store , In Store Table , just one row can IsDefault=true at time . when I insert new Row , I check If user selected IsDefault , I update other row whice isDefault=true . I use this code :public AddStatus Add(AddStoreViewModel storeViewModel) { if (Exists(storeViewModel.Name)) return AddStatus.Exists; var storeModel = Mapper.Map(storeViewModel, new StoreEntity.Store()); if (storeModel.IsDefault) { var defaultStore = GetDefault(); if (defaultStore != null) { defaultStore.IsDefault = false; _uow.MarkAsBaseChanged(defaultStore); // update } } _uow.MarkAsBaseAdded(storeModel); return AddStatus.Successfull; }and in controller I call Above Method like belowe and Call SaveAllChanges : _storeService.Add(storeViewModel); await _uow.SaveChangesAsync();and MarkAsBaseChange like belowe : public void MarkAsBaseChanged<TEntity>(TEntity entity) where TEntity : BaseEntity { Entry(entity).Entity.Action = Enums.AuditAction.Update;}is this code ok ?
disable other default row- Entity framework
c#;linq
null
_vi.13238
I have followingfunction! s:get_visual_selection() let [line_start, column_start] = getpos('<)[1:2] let [line_end, column_end] = getpos('>)[1:2] let lines = getline(line_start, line_end) if len(lines) == 0 return '' endif let lines[-1] = lines[-1][: column_end - 2] let lines[0] = lines[0][column_start - 1:] return join(lines, \n)endfunction dependencies - tpope's surround.vim pluginfunction! s:singleDoubleQuotesToggler() {{{ select between using norm va let doubleq_sel = s:get_visual_selection() echo string(doubleq_sel) let doubleq_sel_length = strlen(doubleq_sel) echo string(doubleq_sel_length) exec norm! \<Esc> if doubleq_sel_length == 0 echo string(single) norm cs' else echo string('double') norm cs' endifendfunction }}}nnoremap <silent> GS :call <SID>singleDoubleQuotesToggler()<CR>problem is that GS work through once and I dont know whyvideo
Help to implement script that toggle single and double quotes
vimscript;visual mode
null
_cstheory.36943
The SOM AlgorithmIn pseudo-code, for M map units represented by a vector $m \in \mathcal{R}^p$ where $p$ is the vector dimension, the on-line version of the SOM algorithm looks like the following:For each iteration $i in I$: For each sample $s \in S$ Find map unit with min distance $m_{bmu} = \argmin_{m \n M}$ Update the Best-Matching Unit (BMU) and neighborhood closer to $m_{bmu}$There does not appear to be controversy about how the algorithm looks between various assessments of complexity.Complexity Analysis in the LiteratureKaski (1997) wrote that the complexity is $O(K^2)$ where $K$ is the number of map units. As each learning step requires $O(K)$ computations, to achieve a sufficient statistical accuracy the number of iterations should be at least some multiple of K. Presumably this means that $I$ and $M$ (in my above notation) will grow together, such that an increase in $M$ implies an increase in $I$, such that the number of distance calculations and updates grows with $K^2$, and that $N$ and $p$ are assumed as constants that can be disregarded in asymptotic analysis. Drigas and Vrettaros (2008) also report complexity as quadratic to the number of inputs, but do not perform any discussion of it, nor list any assumptions.In contrast, Roussinov and Chen (1998) described the complexity as $O(NC)$ where $N$ is the input vector size and $C$ is the number of cycles. (I.e., $p$ and $I$ in my notation, respectively). The authors claimed that this could be expressed as $O(S^2)$ as the vector dimensionality is proportional to the number of documents in a collection (i.e., the number of unique terms). Then, because each document is presented multiple times, C and be represented by $S$, thus $O(S^2)$.Lastly, Maiorana (2008) divided the algorithm into phases, and claimed that, for each iteration, the computation of the winning neuron (ie., the BMU) is $O(N^2 \times no)$ where N is the number of input elements ($S$ in my notation) and $no$ is the number of classes or output neurons, i.e., Map Units. Now this was surprising to me. Why would computing the winning neuron require $N^2 \times no$ computations of distance? For each sample, only one comparison to all Map Units is required.Specification of QuestionTo me, it seems like the time complexity is $O(I\times S\times N\times p)$, as there are two outer loops, and the determination of the BMU requires a visit of all the map units, $M$. Clearly, any increase of either I, S or M will mean that more computations of the distance $d(s, m)$ are required. Furthermore, if the dimension $p$ is increased, an additional flop is required to compute the difference between the corresponding vector elements.Central to my question is how the complexity of this algorithm really should be reported and analyzed. There is, of course, always a chance that such an analysis already exists, but I have not been able to find it this far. There is also a question on Cross-Validated https://stats.stackexchange.com/questions/147313/what-is-the-computational-complexity-of-the-som-algorithm with an answer, but it only provides links, and no real analysis.Since all four factors I have cited above, clearly affect running time, it seems to me that the potential dependence between factors is how complexity can be squared (or cubic) with regard to some term. Unless the premise is made that any of them are fixed, I think the analysis is incomplete.
What is the computational complexity of the on-line Self-Organizing Map (SOM) algorithm?
time complexity
null
_webmaster.14894
So I was developing my PHP application, right? And then all of a sudden, my sessions wont work anymore! So I checked my error log, and here is what it told me (a few times)PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/imagick.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20060613/imagick.so: cannot open shared object file: No such file or directory in UnknownWhats going on? I have a regular webhost with access to cPanel. This just happend all of a sudden, and I have no clue of what to do. Help appreciated. :)
Sessions suddenly not working in PHP, and error log contains a lot of junk now
php;error;session
null
_softwareengineering.250334
This is not a question about how to number versions.We have an application with a certain version numbering scheme. We also have a Jenkins CI server (soon to be replaced with Atlassian's Bamboo) that regularly builds our software. The application displays the version number, so it's written in one of the files in our code base.We don't want to manually change the version number before releasing a version. Our current solution is that we have a Jenkins job that changes the version number in our code base, commits it, tags the repository with the version number, pushes it and then packages the application for distribution. The problem with that is that we have to decide to release a version before the build succeeds or fails. What we want to do is this: have Jenkins regularly build our product and run the unit tests. Afterwards, we want to select a passing build and release it with a certain version number. In summary, this is the process I want:Jenkins builds and tests our product regularly.When we want to release a version, we can select the last passing build from Jenkins and check to release it.The resulting release should include the version number.The commit that was built and released should be tagged with the release number.What is the best practice for releasing product versions? Is there a process that will meet my demands?
Building software with version numbers
continuous integration;versioning
null
_unix.108979
I'm trying to get a ruby script to run via cron. The cron job looks like this:* * * * * /usr/local/rvm/rubies/ruby-2.0.0-p353/bin/ruby /usr/share/adafruit/webide/repositories/shed_watcher/lib/shed_watcher.rb >> /tmp/cron_shed_watcher.log 2>&1I've encountered a couple of problems. The first was that the environment cron runs in could find one of the required gems:require rest_clientThis was solved by setting the GEM_PATH in the crontab:GEM_PATH=/usr/local/rvm/gems/ruby-2.0.0-p353:/usr/local/rvm/gems/ruby-2.0.0-p353@globalThe second problem is that the script, running on Occidentals on a Raspberry Pi, makes use of a temperature probe and needs to call:`modprobe w1-gpio``modprobe w1-therm`i.e. modprobe commands in backticks. Cron cannot execute this, instead I get an operation not permitted message. modprobe is found in /sbin so I added a path entry to my crontab:PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/usr/local/rvm/gems/ruby-2.0.0-p353/bin:/usr/local/rvm/gems/ruby-2.0.0-p353@global/bin:....But I get the same error (not surprising as it was a not permitted message, not a not found message). What do I need to do to get this working?
Giving cron permission to execute command
raspberry pi;ruby;modprobe
You should add your job to the root's crontab, not the user's one. User's crontabs always executed with uid/gid of the user when root crontab can contain additional field:* * * * * username /path/to/the/commandThen command will be executed with username privileges/permissions.
_cstheory.37163
Jerrum,Valiant and Vazirani on their paper Random generation of combinatorial structures from a uniform (http://www.cc.gatech.edu/~vazirani/AppCount.pdf) talk about seeing problems related to relations in a Existence, Construction, Uniform Generation and Counting hierarchy.In the case of the of M being a perfect matching in a bipartite graph G, we know that the problems of existence and construction are easy, and the counting problem is #P-Complete. The uniform generation problem is to generate a perfect matching in such a way that all perfect matching have the same probabilityIs anything know about the problem of uniform generation of perfect matchings?
Complexity of Uniform Generation of Perfect Matchings
cc.complexity theory;reference request;graph theory;counting complexity;matching
The Jerrum-Sinclair-Vigoda algorithm can be used to sample perfect matchings approximately in bipartite graphs. For general graphs, as far as I know, sampling perfect matchings (approximately or exactly) is still open.
_unix.364366
I sometimes see this pattern in installation instructions:sh ./ poky-<...>-2.1.1.shNote the first parameter, ./.How does this method of calling sh compare to the following?sh ./poky-<...>-2.1.1.sh
Shell script call with current dir as first parameter and shell script as second
linux;shell script;shell
This is a typographical error in the instructions that you are reading.sh ./ scriptThis would try to run the script called ./ with the string script as its first command line argument. This will fail (or at least do nothing).If you see this particular typographical error again, just remove any space between the ./ and the name of the actual script.
_cs.18209
Symmetric/Metric TSP can be solved via the Held-Karp algorithm in $\mathcal O(n^2 2^n)$.See A dynamic programming approach to sequencing problems by Michael Held and Richard M. Karp, 1962.In Exact Algorithms for NP-Hard Problems: A Survey (PDF) Woeginger writes:This result was published in 1962, and from nowadays point of view almost looks trivial. Still, it yields the best time complexity that is known today.Thus, this is the best known upper-bound.Question:Are there any better results for Euclidean TSP? Or does that best-known bound apply to Euclidean TSP as well.How is Euclidean TSP different? Well,Euclidean TSP can be encoded into $\mathcal O(n \log m)$ space, where $n$ is the number of cities, and $m$ is the bound on the integer coordinates of the city locations. As opposed to (sym)metric TSP variants, which essentially require a distance matrix of size $\mathcal O(n^2 \log m)$. Thus, it might be easier to solve; for example, perhaps Euclidean TSP can be more easily encoded into k-SAT, because the distance function is implicit.Contrary to popular notion, Euclidean TSP's reduction from k-SAT is quite different from (sym)metric TSP. UHC (undirected Hamiltonian cycle), symmetric TSP, and metric TSP are pretty directly related to each-other. But formulations of reductions from (sym)metric TSP to Euclidean TSP are not easy to come by. Paragraph, from interesting article, The Travelling Salesmans Power by K. W. Regan (bold mine):Now the reductions from 3SAT to TSP, especially Euclidean TSP, are less familiar, and we ascribe this to their being far more expansive. Texts usually reduce 3SAT to Hamiltonian Cycle, then present the latter as a special case of TSP, but this does not apply to Euclidean TSP. The ${\mathsf{NP}}$-completeness of Euclidean TSP took a few years until being shown by Christos Papadimitriou, and a 1981 paper by him with Alon Itai and Jayme Luiz Szwarcfiter advertised a new, relatively simple, proof. This proof uses vertex-induced subgraphs of the grid graph in the plane, for which the shortest possible TSP tour and any Hamiltonian cycle have the same length. Despite this simplification, the gadgets involved are largea diagram of one occupies most of one journal page.Hunting down k-SAT $\rightarrow$ Euclidean TSP reductions is quite an adventure; so far I've found two of them. One $\rm k\text{-}SAT \rightarrow CircuitSAT \rightarrow PlanarCircuitSAT \rightarrow EuclideanTSP$, and another, even tougher one to find, $\rm k\text{-}SAT \rightarrow DHC \rightarrow UHC \rightarrow PlanarUHC \rightarrow EuclideanTSP$. The latter reduction can perhaps be seen to make Euclidean TSP parallel (sym)metric TSP.
Can Euclidean TSP be exactly solved in time better than (sym)metric TSP?
graph theory;reference request;time complexity;np hard;traveling salesman
One can exploit planar separator structures in a geometric setting and thus solve Euclidean TSP exactly in $O(n^{c \sqrt{n}})$ time, where $c$ is some small constant greater than 1. There's at least three simultaneous results for this; Smith's PhD thesis [1], Kann's PhD thesis [2], and Hwang et al. [3]. Each algorithm has a running time of $O^*(c^{\sqrt{n} \log n})$. This is much better than $O(n^2 2^n)$. As far as I know, it is still an open question whether the running time can be improved by say getting rid of the logarithmic term. [1] W.D. Smith, Studies in computational geometry motivated by mesh generation. Ph.D. Thesis, Princeton University, Princeton.[2] V. Kann, On the approximability of NP-complete optimization problems, Ph.D. Thesis, Kungliga Tekniska Hgskolan, Stockholm, 1992.[3] R.Z. Hwang, R.C. Chang, R.C.T. Lee, The searching over separators strategy to solve some NP-hard problems in subexponential time,Algorithmica 9 (1993) 398423.
_codereview.169441
Okay...so I have been self teaching for about seven months, this past week someone in accounting at work said that it'd be nice if she could get reports split up....so I made that my first program because I couldn't ever come up with something useful to try to make...all that said, I got it finished last night, and it does what I was expecting it to do so far, but I'm sure there are things that have a better way of being done. I wanted to get it finished without help first, but now I'd like someone to take a look and tell me what I could have done better, or if there is a better way to go about getting the same results....What this is doing is: it opens a CSV file (the file I've been practicing with has 27K lines of data) and it loops through, creating a separate file for each billing number, using the billing number as the filename, and writing the header as the first line. Each instance is overwriting the file if it is already created, this is an area I'm sure I could have done better. After that, it loops through the data again, appending each line of data into the correct file.import osimport csv#currentdirpath = os.getcwd()#filename = 'argos.csv'#file_path = os.path.join(os.getcwd(), filename) #filepath to opendef get_file_path(filename): ''' - This gets the full path...file and terminal need to be in same directory - ''' file_path = os.path.join(os.getcwd(), filename) return file_pathpathOfFile = get_file_path('argos.csv')''' - Below opens and reads the csv file, then going to try to loop and write the rows out in files sorted by Billing Number - '''with open(pathOfFile, 'rU') as csvfile: reader = csv.reader(csvfile) header = next(reader) for row in reader: new_file_name = row[5][:5] + '.csv' ''' Create file named by billing number, and print the header to each file ''' fb = open(new_file_name, 'w+') fb.write(str(header) + '\n') #fb.close()with open(pathOfFile, 'rU') as csvfile: reader = csv.reader(csvfile) for row in reader: new_file_name = row[5][:5] + '.csv' ab = open(new_file_name, 'a') ab.write(str(row) + '\n')I've left a few of the things in there that I had at one point, but commented out...just thought it might give you a better idea of what I was thinking...any advice is appreciated!
Split data from single CSV file into several CSV files by column value
python;csv
Don't use string literals as comments. PEP 8 explains how to use comments.Docstrings should use rather than ''', as described in PEP 257. Also your docstring doesn't need the -, and should probably be rephrased slightly to fit on one line.Close files, #fb.close() shows you went out of your way to make bad code. Without fb.close or wrapping open in a with, the file is not guaranteed to be closed. I personally prefer with to fb.close, as described here.Personally, rather than over-riding your files \$n\$ times, I'd use collections.defaultdict, to group all your files into their rows.You may want to change get_file_path, to be based of __file__. Or leave your path to be relative, as it'll default to that behavior.import osimport csvfrom collections import defaultdictFILE_DIR = os.path.dirname(os.path.abspath(__file__))def get_file_path(filename): return os.path.join(FILE_DIR, filename)file_path = get_file_path('argos.csv')with open(file_path, 'rU') as csvfile: reader = csv.reader(csvfile) header = next(reader) data = defaultdict(lambda:[header]) _ = data[header[5][:5]] for row in reader: data[row[5][:5]].append(row) for file_name, rows in data.items(): with open(file_name, 'w+') as f: for row in rows: f.write(str(row) + '\n')
_softwareengineering.182034
Obviously, testing methods are language-independent. An integration test stays an integration test no matter what the technology. But platforms implement some kinds of testing support. And the details vary between implementations, so a programmer has to learn how to use the tools of their framework. And platforms evolve, so best practices in one version may become obsolete or at least inefficient in the next version. See for example this StackOverflow question about unit tests for which at least the first three answers seem to be valid: One describing the correct solution for the current version, one describing the solution which used to be best before the .NET framework included an ExpectedException attribute, and one describing a generic solution which is tool-independent. My question is: were there any major testing-related changes between the .NET framework versions 3.5 and 4.5? Something as disruptive to testing as introducing generics was to programming in general, or introducing the Membership framework was to authentication? Or were there only small enhancing changes? I am asking this because I wonder whether learning materials written for 3.5 are still reasonably valid today.
Were there major changes in testing practices in ASP .NET between 3.5 and 4.5?
testing;asp.net;changes
I would say 3.5 testing information is still reasonably valid. Microsoft has added some enhancements, but I wouldn't call them disruptive or assert that the paradigm has shifted.One change is code contracts, though I don't think they affect unit testing so much as provide an additional/improved way to validate parameters, which may change the way code is tested.Most of the changes/improvements are not with the framework but more with the IDE -- Visual Studio 2012 introduces some new tools and features, including support for third-party frameworks, test management, as well as a new isolation framework called Fakes.Fakes is a great addition (if you have the 2012 Ultimate version), but arguably not much different than third-party frameworks that were available previously, most notably Typemock Isolator.
_webmaster.93976
I have recently developed a website that allows users to have a sub-domain creation of our online store: www.USERNAME.example.comI need to offer the user the ability to have their own complete domain. www.USERNAME.com and then using cloaking alone with Path Forwarding replace their subdomain:www.USERNAME.com == SHOWS INSTEAD OF ==>> www.USERNAME.example.comwww.USERNAME.com/contact === SHOWS INSTEAD OF ==>> www.USERNAME.example.com/contactI need to know the best way to do this.. I know that each actual domain I will need to purchase.. but does anyone know what coding to add to the htaccess file..Please include full instructions if possible as I'm not the best at all of this?
Path Forwarding with cloaking or masking
domain forwarding;masking;cloaking;path
null
_unix.120909
U-Boot 2013.07 (Nov 21 2013 - 18:12:40)Memory: ECC disabledDRAM: 1 GiBMMC: zynq_sdhci: 0SF: Detected N25Q128A with page size 64 KiB, total 16 MiBIn: serialOut: serialErr: serialNet: Gem.e000b000Hit any key to stop autoboot: 0SF: Detected N25Q128A with page size 64 KiB, total 16 MiBSF: 11010048 bytes @ 0x520000 Read: OKWrong Image Format for bootm commandERROR: can't get kernel image!U-Boot-PetaLinux>then I would type run sdboot, and it boots from sd card, where I have put an image for sd booting.It shows that by default UBoot is booting from flash. What changes do I need to make in uboot and where so that the default boot device is SD card and not the flash?Is there any environmental variable I have to set for this?
How to make sd card as default boot in uboot?
sd card;u boot
null
_softwareengineering.253421
I'm reading algorithms and I understand most of it, one thing that I can still struggle with a lot is something as simple as running times on different for-loops. Everyone seems to have easy with that, except for me and therefore I search help here.I am currently doing some excercises from my book and I need help completing them in order to figure out the different running times.The title of the exercise is: Give the order of growth(as a function of N) of the running times of each of the following code fragmentsa:int sum = 0;for (int n = N; n > 0; n /= 2) for(int i = 0; i < n; i++) sum++;b:int sum = 0;for (int i = 1; i < N; i *= 2) for(int j = 0; j < i; j++) sum++;c:int sum = 0;for (int i = 1; i < N; i *= 2) for(int j = 0; j < N; j++) sum++;We have learned different kinds of running times/order of growth like n, n^2, n^3, Log N, N Log N etc. But I have hard understanding which to choose when the for loop differs like it does. the n, n^2, n^3 is not a problem though, but I can't tell what these for-loops running time is.Here's an attempt of something.. the y-axis represents N value and the x axis represents times the outer loop has been run. The drawings in the left is: arrow to the right = outer-loop, circle = inner loop and the current N value. I have then drawn some graphs just to look at it but I'm not sure this is right though.. Especially the last one where N remains 16 all the time. Thanks.
Running time of simple for-loops
algorithms;big o;runtime
BackgroundFor an arbitrary for loop such as:for (int p = ; ) do_something(p);it should be clear that the run time of this loop is simply the sum of the run times of the inner computations (i.e. do_something(p) in this case). Note that the run time of the inner computation may depend on the loop variable(s).In the special case where the run time of do_something(p) is independent of the loop variable(s), the run-time is then proportional to the number of times the inner computation is executed.Typically, simple arithmetic such as incrementing (sum++) are constant-time operations.For brevity I will use log to denote the base-2 logarithm. Additionally, I will use pow(x, y) to denote x raised to the power y because ^ is often used for something else in the C-family of languages.The problemsThe interesting coincidence in this set of problems is that the run time of each computation is actually proportional to the final value of the sum (can you see why?) so the question can be simplified to: how does the final value of sum vary with the parameter N?The sum can be calculated algebraically, but we don't need to know the exact result. We just need to make some good estimates.Problem Aint sum = 0;for (int n = N; n > 0; n /= 2) for (int i = 0; i < n; i++) sum++;How many times does the outer loop run? It starts at N and goes down by half each time until it hits zero. This is just (a discrete version of) an exponential decay with a base of 2. Therefore, we can make an educated guess thatn 1 / pow(2, p) [approximately]Here, we define p to be a counter that increases by 1 each time the outer loop is repeated. In fact, this is exactly what your graph plots.Where does p start? We can just pick p_start = 0 for convenience, and this allows us to determine the coefficient of proportionality: n N / pow(2, p)Where does p end? Whenever n reaches zero! Since this is integer division, n can only be zero if N < pow(2, p). From this we can deduce that p_end log(N) (base-2 logarithm). With experience, you can easily skip this entire analysis and jump straight to this conclusion instead.Now we can rewrite the loop using the variable p instead of n (again, approximately). Notice that every instance of n must be substituted:int sum = 0;for (int p = 0; p < log(N); p++) for (int i = 0; i < N / pow(2, p); i++) sum++;The advantage of writing the loop like this is that it becomes obvious how many times the outer loop is repeated. (Keen readers may notice that this is The inner loop consists of only increments to sum and is repeated N / pow(2, p) times, so we can just rewrite the above to:int sum = 0;for (int p = 0; p < log(N); p++) sum += N / pow(2, p);(Note that the run time of this loop may no longer be the same, but the value of sum still reflects the run time of the original problem.)From this code we can write the value of sum as:(As randomA noted, this is just a geometric series so there is a well-known closed-form expression for the sum. Here I use a more general technique based on calculus, however.)This can be simplified further by approximating the summation as an integral:And there you go, the run time of the problem A is linear with respect to N.Problem Bint sum = 0;for (int i = 1; i < N; i *= 2) for (int j = 0; j < i; j++) sum++;The problem here is similar, but I'll omit some of the steps. The variable i grows exponentially, so we can do the transformation:i pow(2, p)with p increasing by one at each iteration, starting from 0, and ending at log(N). After variable substitution, the loop becomes:int sum = 0;for (int p = 0; p < log(N); p++) for (int j = 0; j < pow(2, p); j++) sum++;which reduces to:int sum = 0;for (int p = 0; p < log(N); p++) sum += pow(2, p);You can apply the same tricks again to find a closed-form expression for the sum: it is also O(N).Problem Cint sum = 0;for (int i = 1; i < N; i *= 2) for (int j = 0; j < N; j++) sum++;This one is actually quite a bit easier because the number of repeats of the inner loop doesn't depend on the outer loop variable, so we can go right away and simplify this to:int sum = 0;for (int i = 1; i < N; i *= 2) sum += N;The loop has the same exponential behavior as in Problem B, so it is run only log(N) times, so this can then be simplified to:int sum = 0;sum += log(N) * N;Hence, the run time is O(N log(N)).
_scicomp.19591
When using the SIMPLE method on a mesh with a collocated variable arrangement, the following interpolation is used for the advecting velocities:\begin{equation}u_f = \overline{u}_f - \overline{D}_f\left(\left(\nabla P\right)_f - \overline{\left(\nabla P\right)}_f\right)\end{equation}where the over bar denotes a geometrically interpolated quantity and\begin{equation}D_P = \frac{V_P}{a_P}\end{equation}where $V_P$ is the volume of cell $P$ and $a_P$ is the central coefficient arising from the discretized momentum equation,\begin{equation}a_Pu_P + \sum_{F}a_Fu_F = -V_P\nabla P\end{equation}Anyways, my question is, how do you correctly determine $\overline{D}_f$ at boundaries? I recently wrote a SIMPLE solver for unstructured meshes, but have noticed that the largest continuity errors are always occurring at the boundary cells, leading me to think I may have accounted for this term incorrectly (I simply extrapolate it to the boundary face). This term can be very important in the computations as it also shows up in the pressure correction equation. I also have some difficulty getting the solver to converge when using inlet/outlet boundary conditions.
A Question About the Rhie-Chow Interpolation Used for Solving the Incompressible Navier-Stokes Equations on Unstructured Grids
fluid dynamics;computational physics;numerical;numerical modelling
null
_unix.192599
I've got a server on my LAN which hosts a website. I've also got a router with openWRT serving as gate between the internet (with public IP 1.2.3.4) and LAN and a registered hostname say myhost.com. I could set additional subhost gitlab.myhost.com pointing to 1.2.3.4.The question is: how do I pass connections to LAN (via the openWRT router) using port 80 or 443 only when the request is for gitlab.myhost.com.
access to local web site from internet using hostname
internet;openwrt;lan
null
_softwareengineering.197118
I'm currenetly struggling with choosing how to proceed as a programmer. I mainly programmed games and would like to continue. And for about 5 years or so I just used C++ and OpenGL, so I spent a lot of time on infrastructure, strange bugs, and mostly getting basic things to work.A friend of mine then recommended python and after initially being aversed by it being not as explicit and formal as I was used to I was shocked by how much more productive I could be and how much progress I could actually make in a very small amount of time.So currently I'm working on a multiplayer-shooter and repeatedly I find myself struggling with python being not as fast I might want it to be. I know that that I have to approach writing efficient code in python very differently now, but even with a little help from friends that are more experienced with python there is just too much going on sometimes (and extrapolating this, I know that I will end up stuck).There are a lot of things I really like about my home-language C++, but after knowing how many hours I could be wasting I don't really want to go back.What language can you recommend which offers high-productivy, is memory-safe (I really hated this) and as high-performance as I can get, but is still mature enough to be used for kind of serious projects (games-related) and maybe even mature enough to have people already having spent some time on OpenGL-Bindings or various libraries for Sound and similar (alternatively easy access to shared libraries written in C). Easy cross-plattform is a big plus! So no .NET please. Is this even possible?
Spoiled by Python convenience- and productivity-wise, spoiled by C++ speed-wise. Now unhappy with both
programming languages;c++;python;game development
null
_scicomp.1372
Is there a speedier way to calculate standard errors for linear regression problems, than by inverting $X'X$? Here I assume we have regression:$$y=X\beta+\varepsilon,$$where $X$ is $n\times k$ matrix and $y$ is $n\times 1$ vector.For finding least squares problem solution it is impractical to do anything with $X'X$, you can use QR or SVD decompositions on matrix $X$ directly. Or alternatively you can use gradient methods. But what about standard errors? We really only need the diagonal of $(X'X)^{-1}$ (and naturally LS solution to calculate the estimate of standard error of $\varepsilon$). Are there any specific methods for standard error calculation?
Computing standard errors for linear regression problems without calculating inverse
linear algebra;optimization
Let's suppose that you solved your least squares problem using the singular value decomposition (SVD) of $X$, given by$$X = U\Sigma V',$$where $U$ and $V$ are unitary, and $\Sigma$ is diagonal.Then$$X'X = V \Sigma^2 V'.$$$(X'X)^{-1}$ exists iff $X$ is full rank (or has strictly positive singular values), in which case$$(X'X)^{-1} = V \Sigma^{-2} V'.$$(See an answer I gave to a related question on Math.SE.)If you already have $\Sigma$ and $V$, calculating $(X'X)^{-1}$ requires inverting and squaring a diagonal matrix ($n$ operations for an $n \times n$ matrix), scaling the columns (or rows) of a matrix ($n^2$ operations), and a single matrix multiply (unfortunately $\mathcal{O}(n^{3})$). This method will be well-behaved numerically.There are fast methods for obtaining the diagonal elements of the inverse of a sparse matrix (see work by Yousef Saad's group and work by Lin Lin, et al). However, in your case, $X'X$ is probably not sparse (even if $X$ is), and even if it were, it would likely be ill-conditioned enough that these fast methods would yield inaccurate results.
_cs.9379
I am interested in precise time complexity of distributed algorithm for finding MIS (Maximum Independent Set) of a given graph $G$.I investigate the Slow MIS distributed algorithm (from these lecture notes, page 2).Following is the more detailed version than in lecture notes.Every node sends its UID to it's neighbors.Run procedure joinon event: getting a message decide(1) from a neighbor $w$ doSet $b = 0$ - flag that node terminates and not participating in further phases.Send decide(0) to all neighborson event: getting a message decide(0) from a neighbor $w$ do:Invoke procedure join.Procedure Joinif every neighbor $w$ of $v$ with a larger identifier has decided $b(w) = 0$, then doSet $b = 1$.Send decided(1) to all neighbors.The question is what's time complexity of the algorithm $\Theta(n)$ or $\Theta(D)$, where $D$ is a diameter of $G$.In the lecture notes linked above, they say that time complexity is $O(n)$. I think that in our case it can be expressed as $\Theta(D)$ (simultaneously $O(D)$ and $\Omega(D)$) for special cases.The problem is how to prove that that time complexity in general is $O(D)$ and there are special cases when time complexity is $\Omega(D)$ if it's right at all.Let's take a look at the example I have in mind.$D=1$ and $n=4$, and as I understood the algorithm every vertex will decide to join MIS on the first round.If you have an idea how to show that, please, share it with us.
Slow MIS Distributed Algorithm
algorithms;time complexity;distributed systems
null
_codereview.122411
What is a better way to create this select statement? I tried to just select 'u' and 'us', but the object properties were not accessible when I did this.var userSubmittedRequests = (from u in db.TimeRequests join us in db.UserManagers on u.EmployeeUserID equals us.UserID join ut in db.Users on us.ManagerID equals ut.UserID where (us.ManagerID == userResult.UserID) where(u.User.disabled == false) select new PendingTimeOffViewModel { TimeRequestID = u.TimeRequestID, sDateTime = u.sDateTime, eDateTime = u.eDateTime, EmployeeUserID = u.EmployeeUserID, ManagerID = u.ManagerID, hrID = u.hrID, ApproveDenyReasonID = u.ApproveDenyReasonID, ManagerApproval = u.ManagerApproval, ManagerActionDate = u.ManagerActionDate, ManagerComment = u.ManagerComment, hrApproval = u.hrApproval, hrActionDate = u.hrActionDate, hrComment = u.hrComment, UserSubmitDate = u.UserSubmitDate, Comment = u.Comment, DayTypeID = u.DayTypeID, User = u.User, CompanyDesc = ut.Company.CompanyDesc, User1 = u.User1, User2 = u.User2, DayType = u.DayType, ManagerIDUM = us.ManagerID, ManagerADName = ut.ADUserName, ManagerName = ut.FullName }).ToList();View model: public class PendingTimeOffViewModel { public int TimeRequestID { get; set; } public int CompanyID {get;set;} public System.DateTime sDateTime { get; set; } public System.DateTime eDateTime { get; set; } public int EmployeeUserID { get; set; } public Nullable<int> ManagerID { get; set; } public Nullable<int> hrID { get; set; } public Nullable<int> ApproveDenyReasonID { get; set; } public bool ManagerApproval { get; set; } public Nullable<System.DateTime> ManagerActionDate { get; set; } public string ManagerComment { get; set; } public bool hrApproval { get; set; } public Nullable<System.DateTime> hrActionDate { get; set; } public string hrComment { get; set; } public string Comment { get; set; } public System.DateTime UserSubmitDate { get; set; } public int DayTypeID { get; set; } public Nullable<int> HoursRequested { get; set; } public virtual ApproveDenyReason ApproveDenyReason { get; set; } public virtual DayType DayType { get; set; } public virtual User User { get; set; } public virtual User User1 { get; set; } public virtual User User2 { get; set; } public virtual Company Company { get; set; } public int UserManagerID { get; set; } public Nullable<int> UserID { get; set; } public Nullable<int> ManagerIDUM { get; set; } public string ManagerADName { get; set; } public string ManagerName { get; set; } public string CompanyDesc { get; set; }}
LINQ query for a user's submitted time-off requests
c#;linq
null
_softwareengineering.216597
Can anyone explain me what byte stream actually contains? Does it contain bytes (hex data) or binary data or english letters only? I am also confused about the term raw data. If someone asked me to reverse the 4 byte data, then what should I assume the data is hex code or binary code?
What is a byte stream actually?
stream processing
null
_reverseengineering.15305
I am working to reverse app, this app use zlib library.is there any way I can make IDA to recognize the name of the zlib(lib) functions.I don't want to waste my time to analyze the zlib functions.Thanks
Static lib functions
ida;static analysis
null
_softwareengineering.109646
Recently I've finished learning about multithreaded programming on single shared objects, but was curious about how different things would be in order to successfully program on multiple shared objects?
Multithreaded Programming?
programming practices;multithreading
This is a very hot current research topic. The question of how to properly share data between multiple, concurrent, processing units, doesn't have obviously good answers yet.Some of the issues that change and you should think about:With multiple shared objects, you'll want to have different threads being able to work with different objects at the same time. If two objects are different, but related, you'll need to have a way of deciding whether they can be worked on independently of each otherObjects may end up moving around in memory more, as they get moved closer to where they are being used (physically closer, or logically closer)Multiple related objects may end up cached in multiple, un-related, caches. Those caches are going to want to know when they've become invalid, which they might if one of a set of related objects is changed. Imagine, for example, a thread which draws to the screen, while other threads go about modifying the data that's being drawn. How do you make sure that what you see on the screen makes sense?There are different ways for objects to be accessed, some with side effects, some without. The patterns of access can heavily influence performance - optimization techniques can become intractably complex
_unix.211380
With the update from BasilOS Quad to Pentus, DEVISH became the primary shell(replacing bash)... I am completely unfamiliar with DEVISH, so I need to be able to switch back to bash... I tried chsh but it said it was not a command... Any help would be appreciated...
How to switch to bash on DEVISH?
bash;shell
Simply type sh to switch to an interactive bash shell... It was added as a feature for people who preferred Bash to DEVISH... Also, if you edit your .devishrc (found in ~), then you can add DEVISH-func=false, to permanently disable DEVISH... It is always reversible...
_codereview.40168
Please provide feedback on the correctness of this code. It should handle older versions of IE but how far back it goes I have not determined yet./**************************************************************************************************EVENTS*/ // ... snip Priv.functionNull = function () { return undefined; }; // createEvent Priv.createEvent = function () { if (doc.createEvent) { return function (type) { var event = doc.createEvent(HTMLEvents); event.initEvent(type, true, false); $A.someKey(this, function (val) { val.dispatchEvent(event); }); }; } if (doc.createEventObject) { return function (type) { var event = doc.createEventObject(); event.eventType = type; $A.someKey(this, function (val) { val.fireEvent('on' + type, event); }); }; } return Priv.functionNull; }; Priv.proto.createEvent = function (type) { return Priv.createEvent.call(this, type); }; Pub.createEvent = (function () { return function (element, type) { var temp = []; temp[0] = element; Priv.createEvent.call(temp, type); }; }()); // addEvent Priv.addEvent = (function () { if (win.addEventListener) { return function (type, callback) { $A.someKey(this, function (val) { val.addEventListener(type, callback); }); }; } if (win.attachEvent) { return function (type, callback) { $A.someKey(this, function (val) { val.attachEvent('on' + type, callback); }); }; } return Priv.functionNull; }()); Priv.proto.addEvent = function (type, callback) { return Priv.addEvent.call(this, type, callback); }; Pub.addEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; Priv.addEvent.call(temp, type, callback); }; }()); //remove event Priv.proto.removeEvent = (function () { if (win.removeEventListener) { return function (type, callback) { $A.someKey(this, function (val) { val.removeEventListener(type, callback); }); }; } if (win.detachEvent) { return function (type, callback) { $A.someKey(this, function (val) { val.detachEvent('on' + type, callback); }); }; } return Priv.functionNull; }()); Priv.proto.removeEvent = function (type, callback) { return Priv.removeEvent.call(this, type, callback); }; Pub.removeEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; Priv.removeEvent.call(temp, type, callback); }; }());
A package for the DOM - Events
javascript
null
_codereview.37923
I had a somewhat interesting issue. I had to take an array and turn it into a string with a set of delimiters; then later on take that string and turn it back into an array, splitting at the same delimiters. The twist was the string could be contain anything (including the delimiters).I feel like I over-engineered the solution, and am wondering what you guys can come up with as alternatives.Here is my solution. escapedImplode turns an array into a string, and escapedExplode turns that string back into its corresponding array. The testEscapedIE function is a little test scaffolding to see if your solution works.function escapedImplode ($glue, $array, $escapeChar = '\\'){ $array = array_map(function ($item) use ($escapeChar, $glue) { $item = str_replace($escapeChar, $escapeChar . $escapeChar, $item); $item = str_replace($glue, $escapeChar . $glue, $item); return $item; }, $array); return implode($glue, $array);}function escapedExplode ($delimiter, $string, $escapeChar = '\\'){ $characters = str_split($string); $isEscaped = false; $parts = array(); $buffer = ''; for ($i = 0; $i < count($characters); $i++) { $char = $characters[$i]; // If is escaped, just add to the buffer and continue if ($isEscaped) { $buffer .= $char; $isEscaped = false; continue; } // If is a delimiter, which isn't escaped, set state and continue else if ($char == $escapeChar) { $isEscaped = true; continue; } // If not escaped and is the delimiter, break here if ($char == $delimiter) { $parts[] = $buffer; $buffer = ''; continue; } // Doesn't match another special case, tack onto buffer $buffer .= $char; } // Add whatever is in the buffer to end of parts $parts[] = $buffer; return $parts;}function testEscapedIE (){ $tests = array( array('test', 'cool', 'awesome'), array('some/thing', 'cool', '/isbrewing/'), array('with\\/asdf', '//other//', '\\/collness\\/'), array('////','//\\//','\\//\\//\\','\\\\'), ); foreach ($tests as $test) { $imploded = escapedImplode('/', $test); $exploded = escapedExplode('/', $imploded); echo 'Testing: ' . implode(', ', $test) . ' -- '; echo $imploded . ' -- '; echo implode($exploded, ', ') . ': '; echo $test === $exploded ? '<strong>Pass</strong>' : '<strong>Fail</strong>'; echo <br/>\n; }}testEscapedIE();
Escaped explode/implode function
php;strings
Not bad. I just have a few nitpicks.You can iterate over characters of a string directly without splitting it into an array first:for ($i = 0; $i < strlen($string); $i++) { $char = $string[$i]; ...}I believe that the PHP interpreter isn't smart enough to recognize that strlen($string) is invariant, so you might get better performance with$strlen = strlen($string);for ($i = 0; $i < $strlen; $i++) { $char = $string[$i]; ...}I find the else if in escapedExplode() slightly jarring. Either use if and continue everywhere, or if, else if, else if, else without continue.