id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_datascience.22386 | I have generated a common Sklearn model for text classification which I want to make accessible in the cloud (there is no provider preference) as an API.So far the closest solution that I managed to find is in this tutorial but it seems quite complex (getting the venv.zip dependencies package at the beginning is unclear, for instance) and specific (in my case NLTK and an external Stanford segmenter is involved for preprocessing and I cannot figure out where to put all these modules and how to invoke them).Is there a decent and robust way to solve this challenge? | How to Deploy a Scikit-learn Model into the Cloud? | scikit learn;cloud;model deployment | null |
_datascience.13677 | I have a set of user transactions with a service and I suspect that there is a strong correlation between how users rate the service and how likely they are to use the service again.I have chosen to represent user ratings - for each user in the dataset - as a number [1-5] which is the average of all ratings the given user has given in the past. There is more to it in regards to how to represent trends etc, but this is not in context for the problem at hand.My issue is that there is a high number of users that have never left any ratings at all and I am not sure how to deal with these users, in terms of finding the right value for the rating-related features for them.What I have tried so far is to represent ratings in a different way, shown below:UID rating_high rating_medium rating_low A 2 0 1 B 0 0 0where each of the predictors represent the count of ratings - in each rating category - by each of the users in the dataset.In the above case, user A has left a good rating in 2 occasions, a low rating in one occasion and has never left a 'medium' rating. User B has never left any ratings for the service at all, therefore, he is assigned a count of 0 for all 'rating categories'.on the 1-5 rating scale, I class all ratings below 3 as rating_low, all those equal to 3 as rating_medium and the ones above 3 as rating_high.I have not managed to find any other way to represent this data, but I would very much rather not drop this part of the dataset as I believe it caries valuable semantics for my problem.Any ideas on how to best deal with this issue are most appreciated! | User ratings and conditional values | machine learning;dataset | null |
_unix.116594 | I'm building a shutdown button for my Raspberry pi, and for that I have a python script that needs to change a GPIO pin on my Raspberry Pi just before the system runs the halt script. Now Raspbian uses LSB headers to determine the order in which scripts are run at shutdown, but I can't for the life of me figure out what to put in the header so that the script will run AFTER everything except /etc/init.d/halt has run. The problem right now is that the script runs too soon (it always installs at K01xx), thus cutting the power before all other services have shut down properly. I tried setting a custom priority as described in the guide here: http://www.debuntu.org/how-to-managing-services-with-update-rc-d/, but that does nothing as the command just says using dependency based boot sequencing, with the end result being the same as before. I tried manually renaming the K01xx script in /etc/rc0.d to K09xx, so that it would be the last one before the halt command in the directory. But that had no effect either. Any suggestions?My init.d script:#! /bin/sh### BEGIN INIT INFO# Provides: shutdown# Required-Start: # Required-Stop:# Default-Start: 2 3 4 5# Default-Stop: 0# Short-Description: Detect shutdown button### END INIT INFOPATH=/sbin:/usr/sbin:/bin:/usr/bin. /lib/init/vars.sh. /lib/lsb/init-functionsdo_start() { if [ -x /home/pi/bin/shutdown.py ]; then [ $VERBOSE != no ] && log_begin_msg Starting listening for shutdown button python /home/pi/bin/shutdown.py & ES=$? [ $VERBOSE != no ] && log_end_msg $ES return $ES fi}do_stop() { if [ -x /home/pi/bin/shutdown_pin.py ]; then [ $VERBOSE != no ] && log_begin_msg Lowering pin for complete shutdown python /home/pi/bin/shutdown_pin.py ES=$? [ $VERBOSE != no ] && log_end_msg $ES fi}case $1 in start) do_start ;; restart|reload|force-reload) echo Error: argument '$1' not supported >&2 exit 3 ;; stop) do_stop ;; *) echo Usage: $0 start|stop >&2 exit 3 ;;esac | How do I run a script just before halt using LSB headers on Raspbian | shutdown;raspbian;lsb | null |
_codereview.34075 | I have a script that separates the date from a datepicker into day, month, and year. It works fine when there is one form on the page but not when there is a second one (presumably due to the id being the same). How can I add a value to my id and name so that they are unique values if the script runs twice on the same page? var now = new Date();var date = jQuery('.form-date');var day = (0 + now.getDate()).slice(-2);var month = (0 + (now.getMonth() + 1)).slice(-2);var today = now.getFullYear()+-+(month)+-+(day) ;date.val(today);jQuery('form').on('submit', function() { var newVal = date.val().split('-'), dateParts = { year: parseInt(newVal[0], 10), month: parseInt(newVal[1], 10), day: parseInt(newVal[2], 10) }; jQuery('.anchor').append(jQuery.map(dateParts, function (index, key) { var name = 'date_' + key; return jQuery('<input>', { type: 'hidden', name: name, id: name, value: dateParts[key] }); }));});Here is the form that isn't posting the correct date:<form id=modal_res action=http://www.site.com/search.php method=get name=disponibilita target=_blank class=custom> <ul> <li> <label for=modal_date class=anchor1><?php _e('Date:', 'hostel_mama' )?></label><input type=date name=date id=modal_date class=form-date datepicker> </li> <li> <label for=modal_nights><?php _e('Nights:', 'hostel_mama' )?></label><input type=number name=nights id=modal_nights value=2> </li> <li><label for=modal_people><?php _e('Guests:', 'hostel_mama' )?></label><input type=number name=people id=modal_people value=1> </li> <input name=ref type=hidden id=modal_ref value=558 /> <input name=langClient type=hidden id=modal_langClient value=eng /> <li class=select-container> <label for=modal_expr><?php _e('Currency:', 'hostel_mama' )?></label> <select name=expr id=modal_expr> <option value=EUR selected=selected><?php _e('EURO', 'hostel_mama' )?></option> <option value=USD><?php _e('US Dollar', 'hostel_mama' )?></option> <option value=GBP><?php _e('British Pound', 'hostel_mama' )?></option> </select> </li> </ul> <input type=submit name=submit class=button radius text-center value=Click to Book> </form> | Refactor to provide for multiple instances on a single page | javascript;php;jquery | Use a closure, so everything will be only inside it's scope. Additionally you can use $ now!(function ($) { var now = new Date(); var date = $('.form-date'); var day = (0 + now.getDate()).slice(-2); var month = (0 + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear() + - + (month) + - + (day); date.val(today); var form = $('form'); form.on('submit', function (e) { var currentForm = $(this); var newVal = currentForm.find('.form-date').val().split('-'), dateParts = { year: parseInt(newVal[0], 10), month: parseInt(newVal[1], 10), day: parseInt(newVal[2], 10) }; currentForm.find('.anchor').append($.map(dateParts, function (index, key) { console.log(['date', form.index(currentForm), key].join('_')); return $('<input>', { type: 'hidden', name: ['date', key].join('_'), id: ['date', form.index(currentForm), key].join('_'), value: dateParts[key] }); })); });})(jQuery);Also change class=anchor1 to class=anchorEdit: Whoops, looks like I'm wrong. You have to scope your selectors as $('.anchor').append will work on all .anchor elements. I'm assuming that it's the child of form now. |
_unix.191748 | While surfing web I've discovered nice one-liner that suits my needs wellexpac -s %-30n %m | sort -hk 2 | awk '{print $1, $2/1024/1024}' | column -t|However all the functional needed I got used to wrap in functions and there is problem in making function from this one-liner.So I tried to insert this into my .bashrc file:size(){ expac -s %-30n %m | sort -hk 2 | awk '{print $1, $2/1024/1024}' | column -t}and got this error:[user@srv ~]$ size: a.out: No such fileSo my question is: what's wrong about this function and how to fix it? | Sort packages by size one-liner as function | bash;command;function | null |
_codereview.144788 | The following code displays a Timetable, but the code needs too long finish the whole process. <?phpclass showTimeTableModel { static $home = false; static $type = NULL; static $c_id = NULL; static $class = NULL; static $subjects = NULL; static $kn; static $year; static $kw; static $TimeTableArray = array(); static $SubejctArray = array(); static $EventArray = array(); static $TypeArray = array(); public static function show($type, $home = false) { self::$type = $type; self::$home = $home; self::$c_id = ClassModel::user()->u_c_id; self::$class = ClassModel::infos(self::$c_id); foreach(SubjectModel::getSubjects() as $value) { self::$SubejctArray[$value->s_id] = $value; //Get all Subjects } foreach(ClassModel::getEventTypes() as $key => $value) { self::$TypeArray[$key] = $value; //Get all 'Events' in this week } self::getWeekNumber(); self::getYearNumber(); $start = new DateTime(); $end = new DateTime(); $start->setISODate(self::$year, self::$kn, 1); $end->setISODate(self::$year, self::$kn, 7); foreach(EventModel::getEventSpan($start->format('Y-m-d'),$end->format('Y-m-d')) as $value) { self::$EventArray[$value->e_s_id] = array($value->e_day => array(e_id => $value->e_id,e_title => $value->e_title,e_type => $value->e_type)); } if(!self::getTimeTableJSON()) { echo ' <div class=row> <div class=col s12 center> <h4>No Timetable</h4> </div> </div> '; return; } self::showHeader(); self::generateTableHead(); self::generateTableRows(); echo '</tbody></table>'; } private static function getWeekNumber() { if(Request::get(kw) == NULL) { $options = self::$class->c_options; $json = json_decode($options); if($options != NULL && !empty($json) && json_decode($options)->nextweek <= date(N)) { self::$kn = (date(W)+1); } else { self::$kn = date(W); } } else { self::$kn = $_GET[kw]; } } private static function getYearNumber() { if(Request::get(year) == NULL) { self::$year = date(Y); } else { self::$year = $_GET[year]; } } private static function getTimeTableJSON() { $tt = TimetableModel::getTimeTables(self::$c_id); if(!$tt) return false; $weeks = ; $i = 0; foreach($tt as $value) { $weeks .= $value->tt_week; $i++; } self::$kw = TimetableModel::getWeek(self::$kn, $i, $weeks); $row = TimetableModel::getTimeTableWeek(self::$c_id, self::$kw); $json = $row->tt_json; $array = json_decode($json); self::$TimeTableArray = $array; return true; } private static function showHeader() { if(self::$home) return; else if(self::$type == personal) $link = /personal; else if(self::$type == class) $link = /class; $date_show_lastweek = new DateTime(); $date_show_lastweek->setISODate(self::$year, (self::$kn-1)); $date_show_nextweek = new DateTime(); $date_show_nextweek->setISODate(self::$year, (self::$kn+1)); echo ' <div class=row> <div class=col s12 center> <a class=btn primary href='.strtok($_SERVER[REQUEST_URI], ?).'?kw='.$date_show_lastweek->format('W').'&year='.$date_show_lastweek->format('Y').'><i class=fa fa-chevron-left aria-hidden=true></i> Letze Woche</a> <a class=btn primary href='.strtok($_SERVER[REQUEST_URI], ?).'?kw='.$date_show_nextweek->format('W').'&year='.$date_show_nextweek->format('Y').'>Nchste Woche <i class=fa fa-chevron-right aria-hidden=true></i></a> </div> </div> '; } private static function generateTableHead() { $THeaderString = self::THeaderString(); if(!self::$home) $time = '<th>Zeit</th>'; else $time = ; echo ' <table width=100% id=TimeTable class=bordered> <thead> <th>Stunde</th> '.$time.' '.$THeaderString.' </thead> <tbody> '; } private static function THeaderString() { $weekday = Data::getGermanDays(); $THeaderString = ; $date_show = new DateTime(); for ($wd = 0; $wd < 7; $wd++) { if(in_array($wd,json_decode(self::$class->c_options)->daysnotshown)) { continue; } $date_show->setISODate(self::$year, self::$kn, ($wd+1)); $iscurrent = ($date_show->format('Y-m-d') == date(Y-m-d)) ? 'class=info lighten-5' : ; $THeaderString .= '<th '.$iscurrent.'>'.$weekday[$wd].' '.$date_show->format('d.m').'</th>'; } return $THeaderString; } private static function generateTableRows() { $next_hour = true; $s = 1; $max = count((array) self::$TimeTableArray); while($s <= $max) { if($next_hour || self::$TimeTableArray->{$s-1}->to == self::$TimeTableArray->{$s}->from) { echo '<tr>'; self::TableRowsLession($s); $s++; $next_hour = false; } else { echo '<tr id=pause>'; self::TableRowsPause($s); $next_hour = true; } echo '</tr>'; } } private static function TableRowsPause($s) { echo '<td></td>'; if(!self::$home) echo '<td></td>'; for($i = 0; $i < 7; $i++) { if(in_array($i,json_decode(self::$class->c_options)->daysnotshown)) { continue; } echo '<td></td>'; } } private static function TableRowsLession($s) { $from = self::$TimeTableArray->{$s}->from; $to = self::$TimeTableArray->{$s}->to; $curr = date(H:i,time()); if($curr >= $from && $curr < $to && self::$kn == date(W)) $iscurrent = 'class=info lighten-5'; else $iscurrent = ; echo '<th '.$iscurrent.' style=padding-top:0px;padding-bottom:0px;>'.$s.'</th>'; if(!self::$home) echo '<td '.$iscurrent.' style=padding-top:0px;padding-bottom:0px;>'.$from.' - '.$to.'</td>'; for($i = 0; $i < 7; $i++) { if(in_array($i,json_decode(self::$class->c_options)->daysnotshown)) { continue; } self::TableCellLession($s,$i); } } private static function TableCellLession($s,$i) { $day = self::$TimeTableArray->{$s}->{$i}; $rowspan = self::getRowspan($s,$i); $show = self::isShown($s,$i); if(empty($day)) { echo <td></td>; } else { if($show) { self::getSubjectInfos($day,$s,$rowspan,$i); } } } private static function getRowspan($s, $i) { $result = true; $span = 0; $rowspan = 1; $day = self::$TimeTableArray->{$s}->{$i}; do { if(self::$TimeTableArray->{$s+$span}->{to} != self::$TimeTableArray->{$s+($span+1)}->{from}) { $result = false; } if(!empty($day) && $day == self::$TimeTableArray->{$s+$span}->{$i} && $result) { $rowspan = $rowspan+$span+1; } $span++; } while ($span < (count((array) $arr)-1) && $result); return $rowspan; } private static function isShown($stunde_key, $day_key) { $day = self::$TimeTableArray->{$stunde_key}->{$day_key}; $show = true; if(!empty($day) && $day == self::$TimeTableArray->{$stunde_key-1}->{$day_key}) { $show = false; } if(self::$TimeTableArray->{$stunde_key-1}->{to} != self::$TimeTableArray->{$stunde_key}->{from}) { $show = true; } return $show; } private static function getSubjectInfos($subjects,$stunde_key,$rowspan,$day_key) { $array = self::$TimeTableArray; if(self::$type == personal) { self::privateTimeTable($subjects,$rowspan,$stunde_key,$day_key); } else if(self::$type == class) { self::classTimeTable($subjects,$rowspan,$stunde_key,$day_key); } } private static function privateTimeTable($subjects,$rowspan,$s,$day_key) { $date_show = new DateTime(); $date_show->setISODate(self::$year, self::$kn, ($day_key+1)); $from = self::$TimeTableArray->{$s}->from; $to = self::$TimeTableArray->{$s+($rowspan-1)}->to; $curr = date(H:i,time()); if($curr >= $from && $curr < $to && $date_show->format('Y-m-d') == date(Y-m-d)) $iscurrent = 'info lighten-5'; else $iscurrent = ; if(count($subjects) != 1) { echo <td class='.$iscurrent.' rowspan='.$rowspan.' style='padding:0px;'><table width='100%'><tr id='Group' style='border-style:none;'>; foreach($subjects as $group_key => $group) { $subject = ; $show_td = false; foreach(UserModel::getGroups() as $groupl => $grouvpv) { if(!in_array(Session::get(u_id),json_decode($grouvpv->g_users,true))) continue; $json = $grouvpv->g_timetable; $arr = json_decode($json, true); $week = $arr[$s][$day_key][self::$kw]; $dayname = Data::getGermanDays(); foreach($arr as $key => $week_value) { if($key == $s && key($arr[$s]) == $day_key && in_array($group,$arr[$s][key($arr[$s])][self::$kw])) { $subject = $subject; $show_td = true; } } } if($group == $subject && !empty($subject) || $show_td) { self::displayCell($date_show, $group, $iscurrent, $rowspan, false); } } echo </tr></table></td>; } else { self::displayCell($date_show, $subjects[0], $iscurrent, $rowspan); } } private static function classTimeTable($subjects,$rowspan,$s,$day_key) { $date_show = new DateTime(); $date_show->setISODate(self::$year, self::$kn, ($day_key+1)); $curr = date(H:i,time()); $from = self::$TimeTableArray->{$s}->from; $to = self::$TimeTableArray->{$s+($rowspan-1)}->to; if($curr >= $from && $curr < $to && $date_show->format('Y-m-d') == date(Y-m-d)) $iscurrent = 'info lighten-5'; else $iscurrent = ; if(count($subjects) != 1) { echo <td .$iscurrent. rowspan='.$rowspan.' style='padding:0px;'><table width='100%'><tr style='border-style:none;'>; foreach($subjects as $group_key => $group) { self::displayCell($date_show, $group, $iscurrent, $rowspan, false); } echo </tr></table></td>; } else { self::displayCell($date_show, $subjects[0], $iscurrent, $rowspan); } } private static function displayCell($date_show, $subject, $iscurrent, $rowspan, $border = true) { $isEvent = self::$EventArray[$subject][$date_show->format('Y-m-d')]; $event_exist = ($isEvent != NULL) ? true : false; $color = ($event_exist ? 'color:'.self::$TypeArray[$isEvent[e_type]][color].';' : ''); $class = ($event_exist ? 'tooltipped' : ''); $html = '<td '; $html .= 'class='.$iscurrent.' '.$class.' '; $html .= 'data-tooltip='.$isEvent[e_title].' '; $html .= 'day='.$date_show->format('Y-m-d').' '; $html .= 'rowspan='.$rowspan.' '; $html .= 'style=text-align:center;font-size:2rem;'.($border ? '' : 'border-style:none;').''.($event_exist ? 'padding:0px;' : 'padding:15px 5px;').'>'; if($event_exist) $html .= '<a href=/event/infos/'.$isEvent[e_id].' style=display:block;height:100%;width:100%;padding:15px 5px;'.$color.'>'; $html .= self::$SubejctArray[$subject]->s_short; $html .= '<p style=font-size:1rem;>'; $html .= self::$SubejctArray[$subject]->s_room; $html .= </p>; if($event_exist) $html .= </a>; $html .= </td>; echo $html; }}Do you have suggestions? | Displaying a timetable | performance;php;datetime;json;formatting | As mentioned in comment, there is really not enough context to be able to speak to performance issues (or areas where you may want to investigate performance). Utimately, you should familiarize yourself with PHP debugging tools such that you can learn to pinpoint performance bottlenecks in an effective manner.I will give some high-level thoughts on the code. I haven't really gone into detail in thinking about the underlying logic, because frankly, at this point, this code needs some refactoring to get to the point where you can expect a more fully thought-out review.Some thoughts:This code is hard to read. You should seek out examples of good professional code as well as PHP code standard resources like the PHP-FIG coding standards.Consider using a style checking tool to enforce these standards.Styling problems include:no comments.extremely long lines of code. Strive to keep under 80 characters.an overabundance of loose comparisons. This is actually more than style consideration. People who use loose comparisons by default in PHP are probably going to be writing buggy code. You should consider always using strict comparisons except for those relatively rare cases where a loose comparison makes sense.inconsistent casing around method names. Typical standards would have lowercase first character. Also, consider upper case for first character in class name.intermingling of snake_case and camelCase. Be consistent in your code (though I know PHP as a language is not consistent).variable names are often not meaningful. What is the purpose of $c_id, $kn, $kw for example? Without comments and without meaningful variable names (which can sometimes eliminate need for comments), the reader would have to dive into the code itself to understand what these class properties might mean. That is really poor for someone writing code that is using this class.you should explicitly specify the visibility of your class properties.Your class does way too much. Right now this class:directly reads user input. (Your code even does this in private methods which should ideally not be operating on data that is not already properly validated elsewhere);instantiates numerous objects of different classes;generates content for display in view;hold logic for assembling time tables;holds HTML view template;contains CSS styling logic;orchestrates output of the view based on content.You REALLY need to think about decoupling these types of concerns when you are designing your classes.Just to think about this. If someone wanted to make a simple change for a CSS style for this element, they have to go into a PHP class (not even a template) to make this change. That is a questionable design.I am not sure that you are using static properties/methods appropriately, though I am not 100% certain without better understanding how this class fits in the overall application.It seems to me that an object in your system that is tasked with rendering a TimeTable might have separate instances. You spend a lot of time constructing the various data you store on static properties. This seems more like instance behavior rather than behavior that should be setting globally-accessible static property values. Is there more than one time table on a page? If so, why would you be resetting these static values for another instance.If this class is truly intended to have a common set up across the whole application (i.e. really be used statically), then I would think you would best be served by getting the vast majority of logic out of this class, either into configuration which is read into static properties, or into separate object dependencies that could be passed to this class. This class should not need to know how to set up the the time table to be rendered. Tt should be given a properly set up time table (and other dependencies) and do one thing, render it.Also, if this class is truly expected to be set up only once, I would expect to not have to recalculate/reset the values in show() every time a time table needs to be rendered based on this configuration. You could perhaps have an initialize() constructor-like method to set the class up and then calls to show() could just focus on rendering. Again, though, this is really almost instance behavior as this would have the same effect as instantiating a single object of this class and operating against it across the application.Looking at the ways you are accessing your other classes, I wonder if this is a wider consideration, as you seem to be taking an almost exclusively static approach to interacting with other objects in the application.Think about dependency injection over static methods for instantiation, as you can really bloat your classes if they all need to hold understanding for how to instantiate all their dependencies (and perhaps handle errors/ exceptions that could potentially arise during dependency set up).In your one public method, you do nothing to validate that the parameters passed are reasonable for use with this function. You should validate and fail out (ideally with some sort of exception) if proper dependencies are not provided.You should definitely not be setting up dependencies in your private methods as you are often doing (reading user input, instantiating related objects, etc.) Your public methods are your contract with the caller. Your caller needs to give you all the dependencies you need. You need to validate those dependencies within the public methods such that the private methods that might be called from there know with 100% certainty that their dependencies are set up exactly the way they need to be. Otherwise, you get into having to have validation code sprinkled all across your class methods.I don't agree with your approach of setting/getting JSON-serialized data to class properties. JSON is a serialization format, suitable only to represent a datagram for interchange between application components, services, etc. There is no reason that in a class property (static or concrete instance) you should be storing JSON for items you are going to be working with in your code. Why introduce the need to serialize/deserialize just to work with your properties? Store the actual data structure, not the JSON. If the class gets JSON handed to it from dependency, that is fine, but it should deserialize it before setting on the property, such that a) you can validate the JSON is valid and can be deserialized and b) other methods in your class that need to work with this data do not have to deserialize it first. |
_reverseengineering.12448 | While analyzing root cause analysis of a vulnerability using windbg we use to put a command kb to view the stack trace.But after viewing the stack trace how to analyze or confirm the presence of vulnerability.Below is the some few listing after kb command0:000> kChildEBP RetAddr **0012fb88 008bee28 libwireshark!snmp_usm_password_to_key_sha1**0012fba8 008c07af libwireshark!set_ue_keys+0x580012fbc0 008c060a libwireshark!ue_se_dup+0x10f0012fbdc 006e017a libwireshark!renew_ue_cache+0x5a0012fbe8 006d19a3 libwireshark!uat_load+0x18a0012fc04 0069faad libwireshark!uat_load_all+0x530012fc44 0069ff59 libwireshark!init_prefs+0x6d0012fc58 00420673 libwireshark!read_prefs+0x190012fcb4 0041e5c8 wireshark!read_configuration_files+0x230012ff18 00420a81 wireshark!main+0x6b80012ff30 00521bae wireshark!WinMain+0x610012ffc0 7c817067 wireshark!__tmainCRTStartup+0x1400012fff0 00000000 kernel32!BaseProcessStart+0x23if we see the first line by stack trace which is the actual crash 0012fb88 008bee28 libwireshark!snmp_usm_password_to_key_sha1but how to determine which type of bug is?If you see above we saw the stack trace.so how to reach the actual point where vulnerability is triggered, like from where to start looking for vulnerability? | Analyzing stack trace for vulnerability analysis using WIndbg | windbg;vulnerability analysis | null |
_webmaster.17515 | I am trying to implement Google Apps for a new domain of mine, and although Google says it can take up to 48 hours, it is normally much quicker than that, and other DNS changes, such as creating the domain alias, normally take less than 1 hour to propogate. The domain I'm trying to set up Google Apps for is an alias of an existing domain - let me explain:I have mainDomain.com, and this is the name of my domain account on my host, which I cannot change. However, that domain name has expired and is no longer available, so I create a domain alias on the host called aliasDomain.co.za, and choose not to use the main domain DNS. I then set all the MX records, as documented by Google, on aliasDomain.co.za, but it's been about 12 hours with no joy yet. I suppose I should wait the 48 hours, but if my DNS is wrong, it could be another 48 hours to see if I did fix it. Should what I'm doing work normally, or should I be doing something else? | MX changes for domain alias not propogating | dns;google apps | I have resolved this matter, here are the details:When I created the domain alias on my host's control panel, I removed all existing CNAME and MX records, leaving only the NS and A records. Then I followed Google's instructions for setting up new MX records. This worked, but I was under the impression it didn't work, because the URL mail.aliasDomain.co.za still pointed to my host, not to Google. I suspected I was missing a CNAME, but when I tried to create a new CNAME pointing mail.aliasDomain.co.za to ghs.google.com, I got an error that such CNAME 'already exists for the zone'.It turns out that I created all the MX records with the mail prefix, so I couldn't create another record to that same name. After removing the mail prefix from my MX records, I was finally able to create one required CNAME, to gsh.google.com, for the mail prefixed zone. |
_unix.94317 | I am an Archlinux user and I ve had problems with alsamixer which didn't play sound in google-chrome. So I 1st tried to uninstall it using:sudo pacman -Rns alsa-plugins alsa-tools alsa-ossAfter removing the alsa (so I ve thought) I could still call it using command alsamixer which is bizarre. So i tried ti completely remove it by changing my pwd into the /bin and using command: sudo rm alsa*which did seem to remove the alsa and the command alsamixer wasnt reckognized any more (file .asoundrc in my home folder was also removed by me): [ziga@ziga-cq56 ~]$ alsamixerbash: alsamixer: command not foundThen I tried to reinstall the same packets that I deleted and now I get:[ziga@ziga-cq56 ~]$ alsamixerbash: alsamixer: command not foundIt is weird that Amarok music player still plays music. Can anyone help me recover alsa? | ALSAMIXER - deleted the alsa* from /bin - need to recover | alsa | You probably had alsa-utils and alsa-lib still installed. Remove them and then reinstall with 'alsa-plugins alsa-tools alsa-oss alsa-utils'. Alsa-lib should install automatically as a dependency of the others. |
_unix.354881 | STOP! Before you tell me this package has been removed, please use package-name:i386 read what I have to say!I need to use the compression formats of the PAQ-family. The executables were made in the ia32-libs era and they don't accept any replacement for those libs.After a lot of unsuccessful research I decided to go through dependency hell and install all ia32-libs dependencies manually, so I can get this package finally to work on my system. First it went well, but now I caught a broken dependency/package error and it seems like this dependency will stay unresolved, which means I can't use the ia32libs package.What else can I do to make these formats work on my system? | Literal ia32-libs in 2017 | 64bit | Youre obviously not going to like this answer, but I have the PAQ binaries running fine with libgcc1:i386, libc6:i386, and libstdc++6:i386 installed, no ia32-libs in sight. For example:$ ldd paq7 linux-gate.so.1 (0xf77e8000) libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xf762d000) libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xf75d8000) libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xf75ba000) libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf7403000) /lib/ld-linux.so.2 (0x56634000)$ ./paq7paq7 compressor/archiver (C) 2005, Matt Mahoney.Free under GPL, http://www.gnu.org/licenses/gpl.txtTo compress: paq7 [-option] archive files... (archive will be created)Or (Windows): dir/b | paq7 archive (file names read from input)To decompress/compare: paq7 archive [files...] (defaults to stored names)To view contents: more < archiveOptions are -1 to -5 (use 62, 96, 163, 296, 525 MB memory), default -3You can't add/extract single files. Max total file size is 2GBTime 0.00 sec, memory 8463616 bytes |
_softwareengineering.160560 | I know what a Web API is.I've written API's in multiple languages (including in MVC3).I'm also well practiced in ASP.Net.I just discovered that MVC4 has Web API and without going through the video examples I can't find a good explanation of what exactly it IS.From my past experience, Microsoft technologies (especially ASP.Net) have a tendency to take a simple concept and wrap it in a bunch of useless overhead that is meant to make everything easier.Can someone please explain to me what Web API in MVC4 is exactly? Why do I need it? Why can't I just write my own API? | What exactly is Web API in ASP.Net MVC4? | asp.net;asp.net mvc 4 | ASP.NET Web API is a non-opinionated framework to build HTTP Service regardless of REST or RPC. It is Microsoft's best implementation of RFC 2616 (HTTP Spec).Certainly you can build your own API but ASP.NET Web API:Built based on the Russian Doll model which allows for lego-like modules to be added to the HTTP pipelineMakes HTTP first class citizen so all common headers are strongly typed (not just name value) and helps with parsing themAllows for both ASP.NET (IIS) hosting or self-hostingsupports content negotiation, media types, ...Is Async from top to bottomUses a similar approach for clients with HttpClient |
_codereview.155566 | Following is the objective C code snippet to check that the 6-digit number is not repeated and not in sequence/reverse-sequence. I have just printed the proper messages in NSLog that user should be allowed or not: NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@(?!(\\d)\\1+$|(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)|9(?=0)){5}\\d$|(?:0(?=9)|1(?=0)|2(?=1)|3(?=2)|4(?=3)|5(?=4)|6(?=5)|7(?=6)|8(?=7)|9(?=8)){5}\\d$)\\d{6}$ options:NSRegularExpressionCaseInsensitive error:&error]; NSRange matchRange = [regex rangeOfFirstMatchInString:text options:NSMatchingReportCompletion range:NSMakeRange(0, text.length)]; BOOL didValidate = NO; if(matchRange.location != NSNotFound){ didValidate = YES; } if(didValidate){ NSLog(@Allowed); }else{ NSLog(@Not Allowed); }I just want to know if this regex has an effect on performance, and if yes, then what should be optimal solution for it. It would be great if anyone can provide their inputs for the same. | Checking that a 6-digit number is not repeated and not in sequence | regex;objective c;ios | null |
_unix.62595 | Are configuration files with ~ ending (emacs backup files) interpreted when they are in conf.d directory ? | Are *.conf files with ~ ending (emacs backup files) interpreted? | linux;debian | null |
_scicomp.26819 | This question is based upon a research article which I am trying to reproduce. One of the main result of this paper is the condition on transverse confinement of the Bose-Einstein Condensate(BEC) to make the black soliton solution stable. The equation governing BEC is the Gross-Pitaevskii(GP) equation, given by$i\hbar \frac{\partial\psi}{\partial t}=-\frac{\hbar^{2}}{2m}\frac{\partial^{2}\psi}{\partial x^{2}}+g\psi|\psi|^{2}+V_{ext}\: \psi$Here, $|\psi|^{2}$ gives the density of the condensate. We can see when $V_{ext}=0$, the above equation has a solution, in one dimension(say z), of the form $\psi(z,t)=\tanh{cz} \:e^{-i\mu t}$, where $c$ accounts for the constants.Suppose now that we are working in a cylindrical geometry, such that the $V_{ext}=\omega_{z}z^{2}+\omega_{r}r^{2}$ and $\omega_{z}<\omega_{r}$, meaning the radial confinement is stronger than the axial confinement. In such a case, one can obtain a solitonic solution with a nodal plane perpendicular to the axial direction. This can be done by using the split operator method and imaginary time evolution.Now, comes the question of stability of the solitonic solution. One can perturb $\psi$ with a perturbation of the form $\psi\rightarrow\psi+\delta\psi$, where $\delta\psi = u(z)e^{iq.r-i\epsilon t}+v(z)e^{-iq.r+i\epsilon t}$. So, basically, we are looking for small amplitude oscillations where the soliton, whose nodal plane is perpendicular to the axial(z) direction, gives out energy in the radial direction. Putting the form of $\delta\psi$ in the GP equation, we get the following set of equations for $f_{\pm}(z)=u(z)\pm v(z)$, where $\psi_{0}(z)$ is the density profile of the soliton in the z-direction(axial direction) in the presence of the trap($V_{ext}$)$\epsilon f_{-}(z)=\Big[-\frac{\hbar^{2}}{2m}\big(\frac{\partial^{2}}{\partial z^{2}}-q^{2}\big)-\mu+V_{ext}+3g\psi_{0}^{2}(z) \Big]f_{+}(z)$$\epsilon f_{+}(z)=\Big[-\frac{\hbar^{2}}{2m}\big(\frac{\partial^{2}}{\partial z^{2}}-q^{2}\big)-\mu+V_{ext}+g\psi_{0}^{2}(z) \Big]f_{-}(z)$To obtain a stability condition, we need a dispersion relation between $\epsilon$ and $q$. However, as you can see in the above set of equations, there are a lot of terms with $z$ dependences, including a derivative in the $z$ direction. The authors of the paper say that they have numerically solved these set of equations to obtain a dispersion relation. How does one do that? | Stability of dark solitons in a harmonic trap | ode;eigensystem;quantum mechanics;operator splitting;differential equations | As short answer, you need to:Sweep over your wavenumber $q\in [q_\min, q_\max]$;Approximate your differential equation$$\mathcal{L}_q \mathbf{f} = \epsilon \mathbf{f}$$to obtain a discrete problem$$[H(k)]\lbrace U \rbrace = E[S]\lbrace U \rbrace\, ;$$Solve the generalized eigenvalue problem to obtain the admissible frequencies $\epsilon$ for that particular $q$.Regarding point 2 and 3, there are several methods. Some of the most popular ones are discussed in this answer [1]:Finite Difference Methods; Finite Element Methods; andDirect Variational methods.Let's rewrite the equation as above, $\mathcal{L}_q \mathbf{f} = \epsilon \mathbf{f}$, with$$\mathcal{L}_q =\begin{bmatrix}0 &-\frac{1}{2}\nabla^2 + \hat{V}(q) + 3\psi^2_0\\-\frac{1}{2}\nabla^2 + \hat{V}(q) + \psi^2_0 &0\\end{bmatrix}\, ,\quad\mathbf{f} =\begin{Bmatrix} f_{-}\\ f_{+}\end{Bmatrix}\, ;$$and $\hat{V(q)} = V_\text{ext} - \mu - q^2$, where I re-scaled some variables for convenience. The operator $\mathcal{L}$ does not seem to be self-adjoint, if that's the case, the resulting matrices might not be Hermitian (depending on the scheme).If one uses a weighted residual approach, the resulting functional is of the form (I would double-check, it's easy to make silly mistakes)$$\Pi_q[\mathbf{f}, \mathbf{w}] =\frac{1}{2}\int_\mathbb{R} \nabla w_1 \nabla f_{+}\, dz +\frac{1}{2}\int_\mathbb{R} \nabla w_2 \nabla f_{-}\, dz +\\\int_\mathbb{R} |\psi_0|^2[3 w_1 f_{+} + w_2 f_{-}]\, dz +\int_\mathbb{R} \hat{V}(q)[w_1 f_{+} + w_2 f_{-}]\, dz -\epsilon\left[\int_\mathbb{R} w_1 f_{-}\, dz +\int_\mathbb{R} w_2 f_{+}\, dz\right]$$ |
_softwareengineering.245461 | We all know sometimes a e.g. merge can go wrong.If our [unit / integration] tests are in the same repository as the merge, is there then a weakness there that if the tests have merged incorrectly and do not appear in the final code then we don't know what we don't know.Should the unit test project then instead be a complete separate item?In many ways I'd say no as it could litter a master branch with feature tests which are not yet relevant.In compiled languages then the compilation will fail if the test's reliant code is missing, so will help to a certain degree. But perhaps a non-compiled language is better as it would highly specific missing items when running the test.Does anyone have a workflow which it is possible to know which features may of merged incorrectly? | Should tests be kept out of the main merge pipeline? | unit testing;scm | null |
_webapps.104287 | How can I filter all the messages sent to *@domain.com except for those sent exclusively to [email protected]?I tried to:domain.com AND -to:[email protected] and to:(domain.com [email protected]) but it shows all the messages sent to *@domain.com that do not have [email protected] as the recipient. | Filter all mails sent to domain except for specific recipient | gmail;gmail filters | null |
_softwareengineering.287023 | I am making a website that requires logins, and would like to know what a good approach is. Right now, I am thinking of the following:User sends username and password to server, where it is validated.If its valid, then session_start(); is called, and session_id() is stored in my database, which will be used as an access token for the rest of data fetching. If user logs out, that session_id() will be destroyed in the database. I would like to know how to delete the session_ids() , if the user DIDNT log out, and just closed the browser. I would like to know how popular websites like facebook handle sessions. | The correct way to use Sessions (PHP)? | php;database | You're in the right neighborhood.Most PHP applications will have active sessions for all page views, regardless of whether a user is logged in. It would essentially do a session start() at the beginning of the script, and a save() at the end. That session would exist for the entire visit to the site, or longer, depending on how you have PHP set to expire cookies.When a user submits a login form and successfully logs in, you can then store the user information as a session variable. For example, at the most basic, you can store the user id associated with the session:$_SESSION['user_id'] = 1234;When the session is saved, that value is stored with the session. Session variables are not sent to the client - they are stored on the web server (where exactly it is stored is configurable, but ideally in a database).Now, on the next page load, you can check the value of $_SESSION['user_id'] to get the user id of the logged in user, if any. This is because when the session loads at the top of the script, it has access to the session variables you assigned on other pages in that session. When a user logs out, you set the $_SESSION['user_id'] back to 0. On the next page load, the user is no longer associated with that session.If you want the user to get logged out when the browser is closed, you need to set the cookie lifetime to 0. If you want the session to persist, you want to set the cookie lifetime to the maximum number of seconds you want the session to exist (for example, 60 * 60 * 24 * 30 would be 30 days).This is just a conceptual overview. There's some security issues involved with sessions, so make sure you learn about them as well before you make a site live. |
_codereview.93923 | I created a Pandas dataframe from a MongoDB query.c = db.runs.find().limit(limit)df = pd.DataFrame(list(c))Right now one column of the dataframe corresponds to a document nested within the original MongoDB document, now typed as a dictionary. The dictionary is in the run_info column. I would like to extract some of the dictionary's values to make new columns of the data frame. Is there a general way to do this? If not, what is the best brute force method specific to my data?Here is my brute force approach, and it's horrendous. Even for a dataframe of only 200 rows, this is taking several minutes:run_info = df['run_info']# want to extra values from dictionary stored in column df['run_info']# some values are within dictionaries nested within top dictionary# these are 'author' and 'weather'for i in range(len(df['run'])): g = run_info[i] if g.get('weather'): for name in weather_list: if g.get('weather').get(name): try: df.set_value(i, name, g['weather'][name]) except: pass if g.get('author'): for name in author_list: if g.get('author').get(name): try: df.set_value(i, name, g['author'][name]) except: pass for name in name_list: if g.get(name): try: if name is 'local_start_time': df.set_value(i, name, g[name][0:19]) else: df.set_value(i, name, g[name]) except: passI'd appreciate any and all suggestions for how to improve the speed here. Also I am using the try...except because once in a while the encoding on some funky character is causing a ValueError. | Extracting contents of dictionary contained in Pandas dataframe to make new dataframe columns | python;pandas | I suspect the try-except in the loops are the main cause of the slowness. It's not clear at which point you get ValueError due to funky data. It would be good to clean that up, get rid of the try-catch, and I think your solution will get noticeably faster.Another small thing, that might not make a noticeable difference at all, you have some repeated lookups, like in this snippet:if g.get('weather'): for name in weather_list: if g.get('weather').get(name):Here, the g.get('weather') bit is executed twice. It would be better to save the result of the first call, and then reuse that. Apply this logic to other similar places. Although it might not make a practical difference, avoiding duplicated logic is a good practice. |
_webapps.870 | I know of IMDB top 250: http://www.imdb.com/chart/topAre there other places worth visiting ? | Where can I find (free) recommendations for movies? | webapp rec;movies | MovieLens is a research project at the University of Minnesota that gives movie recommendations based on your ratings of other movies.I believe it was one of the first collaborative filtering systems, created over 10 years ago.Here's its Wikipedia page: http://en.wikipedia.org/wiki/MovieLens |
_codereview.150749 | I made a Monte Carlo pi approximation program, that makes use of multithreading and a pseudorandom number generator I wrote (the one from big_wheel.hpp, which I tested using TestU01).Code:monte_carlo_pi.cpp:#include <iostream>#include <iomanip>#include <cstdlib>#include <cstdint>#include <cmath>#include <thread>#include <mutex>#include <random>#include <vector>#include <chrono>#include big_wheel.hpptypedef struct{ double x, y, z;} point_t;static const double PI = 3.1415926535897932384626433832795;static const std::uint32_t prng_max_value = big_wheel_engine<>::max();double approximate_pi(std::uint32_t pc,std::uint32_t tp){ return 4.0*(double(pc)/double(tp));}double pi_error(double x){ return 100.0*((x-PI)/PI);}std::mutex mtx;// Points within circlestd::uint32_t pcnt = 0;template <class RandEng>void calculate_pi(std::uint32_t nppt,RandEng rgen){ std::lock_guard<std::mutex> guard(mtx); point_t rpt; for (std::uint32_t i=0;i<nppt;i++) { rpt.x = double(rgen())/static_cast<double>(prng_max_value); rpt.y = double(rgen())/static_cast<double>(prng_max_value); rpt.z = (rpt.x*rpt.x)+(rpt.y*rpt.y); if (rpt.z <= 1.0) pcnt++; }}int main(int argc,char **argv){ // Check number of cores std::size_t num_cores = std::thread::hardware_concurrency() ? std::thread::hardware_concurrency() : 1; // Thread set std::vector<std::thread> thread_set; // Generate seeds std::random_device rd; std::uint32_t seed[16] = {0x0}; for (int i=0;i<16;i++) seed[i] = rd(); // Initialize PRNG big_wheel_engine<> rnd( seed[ 0],seed[ 1],seed[ 2],seed[ 3], seed[ 4],seed[ 5],seed[ 6],seed[ 7], seed[ 8],seed[ 9],seed[10],seed[11], seed[12],seed[13],seed[14],seed[15] ); std::uint32_t num_points = 3221225472; std::uint32_t num_points_per_thread = num_points/num_cores; for (std::size_t i=0;i<num_cores;i++) thread_set.push_back( std::thread( calculate_pi<big_wheel_engine<>>, num_points_per_thread, rnd ) ); // Calculated Pi value double gen_pi = 0; // Calculation error double pi_err = 0; // Duration double dur = 0; // Print info std::cout << Seeds:\n; for (int iy=0;iy<4;iy++) { std::cout << ; for (int ix=0;ix<4;ix++) std::cout << std::setw(11) << std::setfill(' ') << seed[4*iy+ix] << ; std::cout << \n; } std::cout << Number of points: << num_points << \n; std::cout << Number of cores: << num_cores << \n; std::cout << ==> Number of points per thread: << num_points_per_thread << \n\n; std::cout << Generating random points...\n; std::chrono::high_resolution_clock::time_point tpa = std::chrono::high_resolution_clock::now(); for (std::size_t i=0;i<num_cores;i++) thread_set[i].join(); std::chrono::high_resolution_clock::time_point tpb = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> tm = std::chrono::duration_cast<std::chrono::duration<double>>(tpb-tpa); dur = tm.count(); // Approximate pi and calculate error gen_pi = approximate_pi(pcnt,num_points); pi_err = pi_error(gen_pi); std::cout << \nResults:\n; std::cout << Number of points within circle: << pcnt << \n; std::cout << Pi approximation: << std::setprecision(32) << gen_pi << \n; std::cout << Error: << std::setprecision(10) << pi_err << %\n; std::cout << Time elapsed: << std::setprecision(10) << dur << seconds\n;}big_wheel.hpp:#ifndef BIG_WHEEL_HPP#define BIG_WHEEL_HPP#include <iostream>#include <cstdlib>#include <cstdint>#include <climits>#include <limits>template < std::uint32_t m = 0x3655accc, std::size_t rs1 = 11,std::size_t rs2 = 20,std::size_t rs3 = 14,std::size_t rs4 = 18, std::size_t rm1 = 16,std::size_t rm2 = 16, std::size_t rf = 7>class big_wheel_engine{ public: typedef std::uint32_t result_type; static constexpr std::size_t state_size = 4096; static constexpr std::uint32_t mix_mask = m; static constexpr std::size_t rot_sel1 = rs1; static constexpr std::size_t rot_sel2 = rs2; static constexpr std::size_t rot_sel3 = rs3; static constexpr std::size_t rot_sel4 = rs4; static constexpr std::size_t rot_mix1 = rm1; static constexpr std::size_t rot_mix2 = rm2; static constexpr std::size_t rot_final = rf; big_wheel_engine( const result_type& s01 = 0x0,const result_type& s02 = 0x0,const result_type& s03 = 0x0,const result_type& s04 = 0x0, const result_type& s05 = 0x0,const result_type& s06 = 0x0,const result_type& s07 = 0x0,const result_type& s08 = 0x0, const result_type& s09 = 0x0,const result_type& s10 = 0x0,const result_type& s11 = 0x0,const result_type& s12 = 0x0, const result_type& s13 = 0x0,const result_type& s14 = 0x0,const result_type& s15 = 0x0,const result_type& s16 = 0x0) { // Inverse mask m_i = ~m; seed(s01,s02,s03,s04, s05,s06,s07,s08, s09,s10,s11,s12, s13,s14,s15,s16); } big_wheel_engine(const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& x) { for (std::size_t i=0;i<state_size;i++) state[i] = x.state[i]; counter = x.counter; } big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& operator=(const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& x) { for (std::size_t i=0;i<state_size;i++) state[i] = x.state[i]; counter = x.counter; return *this; } void seed( const result_type& s01 = 0x0,const result_type& s02 = 0x0,const result_type& s03 = 0x0,const result_type& s04 = 0x0, const result_type& s05 = 0x0,const result_type& s06 = 0x0,const result_type& s07 = 0x0,const result_type& s08 = 0x0, const result_type& s09 = 0x0,const result_type& s10 = 0x0,const result_type& s11 = 0x0,const result_type& s12 = 0x0, const result_type& s13 = 0x0,const result_type& s14 = 0x0,const result_type& s15 = 0x0,const result_type& s16 = 0x0) { counter = 0; p1 = (counter+ 0)%4096; p2 = (counter+ 8)%4096; p3 = (counter+ 18)%4096; p4 = (counter+ 30)%4096; p5 = (counter+ 44)%4096; p6 = (counter+ 60)%4096; p7 = (counter+ 78)%4096; p8 = (counter+ 98)%4096; p9 = (counter+120)%4096; // Based on decimal part of sqrt(61/19) result_type off1[16] = { 0xcab305ab,0x22132737,0xbda768dd,0x2438d3ab, 0x00f4ca5a,0xd4681d61,0xc6420bc7,0x2828bdba, 0x64806a32,0x2fa2391f,0xbc61cbca,0xcc6eb7a0, 0xfa01a2cd,0xb766ce25,0x5499507a,0x19c839a0 }; // Based on decimal part of sqrt(73/29) result_type off2[16] = { 0x962a374b,0x0fc75efe,0x86dfdeff,0xddb14a03, 0xf61361c6,0xc908fde9,0x27df3b7d,0x04ae7492, 0x5ee38142,0xfb21ee51,0x56fae74d,0x4f688f90, 0x7889f34c,0x44e4aa33,0x547e3778,0xb6201d7b }; // Based on decimal part of sqrt(79/31) result_type off3[16] = { 0x98ab7f56,0x38ca9f10,0xa2f3d406,0x322c4113, 0xb8d42dd6,0xe6490633,0x4c5bdcf7,0x454c3122, 0x7b22e315,0x1a205e44,0xc6d1b31b,0x06eb7dea, 0x875f1cf1,0xbe9bec2a,0x0350aa26,0x8b3d5aed }; result_type sset[16] = { s01,s02,s03,s04, s05,s06,s07,s08, s09,s10,s11,s12, s13,s14,s15,s16 }; result_type st_a[16] = {0x0}; result_type st_b[256] = {0x0}; result_type st_c[4096] = {0x0}; result_type rn_1[4096] = {0x0}; result_type rn_2[4096] = {0x0}; result_type rn_3[4096] = {0x0}; result_type rn_4[4096] = {0x0}; // Expansion for (std::size_t i=0;i<16;i++) { st_a[i] = sset[i]+off1[i]; st_a[i] = smix(st_a[i],sbox_i1); } for (std::size_t i=0;i<16;i++) { for (std::size_t j=0;j<16;j++) { st_b[16*i+j] = st_a[i]+off2[j]; st_b[16*i+j] = smix(st_b[16*i+j],sbox_i2); } } for (std::size_t i=0;i<256;i++) { for (std::size_t j=0;j<16;j++) { st_c[16*i+j] = st_b[i]+off3[j]; st_c[16*i+j] = smix(st_c[16*i+j],sbox_i3); } } // Mixing for (std::size_t i=0;i<4096;i++) { rn_1[i] = (st_c[(i+ 0)%4096] << 13) | (st_c[(i+ 4)%4096] >> 19); rn_1[i] = smix(rn_1[i],sbox_i4); } for (std::size_t i=0;i<4096;i++) { rn_2[i] = (rn_1[(i+10)%4096] << 11) | (rn_1[(i+18)%4096] >> 21); rn_2[i] = smix(rn_2[i],sbox_i4); } for (std::size_t i=0;i<4096;i++) { rn_3[i] = (rn_2[(i+28)%4096] << 17) | (rn_2[(i+40)%4096] >> 15); rn_3[i] = smix(rn_3[i],sbox_i4); } for (std::size_t i=0;i<4096;i++) { rn_4[i] = (rn_3[(i+54)%4096] << 10) | (rn_3[(i+70)%4096] >> 22); rn_4[i] = smix(rn_4[i],sbox_i4); } for (std::size_t i=0;i<4096;i++) { state[i] = (rn_4[(i+88)%4096] << 16) | (rn_4[(i+108)%4096] >> 16); state[i] = smix(state[i],sbox_i5); } } // Get next random number result_type operator()() { // Elements from state to mix p1 = (counter+ 0)%4096; p2 = (counter+ 8)%4096; p3 = (counter+ 18)%4096; p4 = (counter+ 30)%4096; p5 = (counter+ 44)%4096; p6 = (counter+ 60)%4096; p7 = (counter+ 78)%4096; p8 = (counter+ 98)%4096; p9 = (counter+120)%4096; // Start mixing tmp_11 = (state[p1] << rs1) | (state[p2] >> (32-rs1)); tmp_12 = (state[p3] << rs2) | (state[p4] >> (32-rs2)); tmp_13 = (state[p5] << rs3) | (state[p6] >> (32-rs3)); tmp_14 = (state[p7] << rs4) | (state[p8] >> (32-rs4)); tmp_21 = ((tmp_11 << rm1) | (tmp_12 >> (32-rm1))); tmp_22 = ((tmp_13 << rm2) | (tmp_14 >> (32-rm2))); tmp_3 = (tmp_21 & m) | (tmp_22 & m_i); tmp_4 = rot_r(state[p9] ^ tmp_3,rf); state[p9] = smix(tmp_4,sbox_r); // For jumping to next elements counter++; return state[p9]; } // Discard z elements void discard(unsigned long long z) { for (unsigned long long i=0;i<z;i++) (*this)(); } // Minimum and maximum static constexpr result_type min() { return std::numeric_limits<result_type>::min(); } static constexpr result_type max() { return std::numeric_limits<result_type>::max(); } // Comparision friend bool operator==( const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& lhs, const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& rhs) { if (lhs.counter != rhs.counter) return false; for (std::size_t i=0;i<state_size;i++) { if (lhs.state[i] != rhs.state[i]) return false; else continue; } return true; } friend bool operator!=( const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& lhs, const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& rhs) { return !(lhs == rhs); } // Stream ops template <class CharT,class Traits> friend std::basic_ostream<CharT,Traits>& operator<<( std::basic_ostream<CharT,Traits>& os, const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& bw) { os << bw.counter; for (std::size_t i=0;i<bw.state_size;i++) os << ' ' << bw.state[i]; return os; } template <class CharT,class Traits> friend std::basic_istream<CharT,Traits>& operator>>( std::basic_istream<CharT,Traits>& is, const big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>& bw) { is >> bw.counter >> std::ws; for (std::size_t i=0;i<bw.state_size;i++) is >> bw.state[i] >> std::ws; return is; } private: // State result_type state[4096]; // Reverse mask result_type m_i; // Temporal variables result_type tmp_11, tmp_12, tmp_13, tmp_14; result_type tmp_21, tmp_22; result_type tmp_3; result_type tmp_4; // For picking elements from state std::size_t counter; // Counter std::size_t p1, p2, p3, p4, p5, p6, p7, p8, p9; // Positions // S-boxes: // - sbox_i{1,2,3,4,5}: For initialization // -- i{1,2,3}: Seed expansion // -- i{4,5}: Mixing // - sbox_r: For generating the next random number static std::uint32_t sbox_i1[256]; static std::uint32_t sbox_i2[256]; static std::uint32_t sbox_i3[256]; static std::uint32_t sbox_i4[256]; static std::uint32_t sbox_i5[256]; static std::uint32_t sbox_r[256]; // Left/right bit rotation template <typename D> D rot_l(D x,unsigned r) { return ((x << r) | (x >> (CHAR_BIT*sizeof(D)-r))); } template <typename D> D rot_r(D x,unsigned r) { return ((x >> r) | (x << (CHAR_BIT*sizeof(D)-r))); } // Mix x with an S-box sb result_type smix(result_type x,std::uint32_t *sb) { return result_type( (sb[(x >> 24)&0xff] << 24)| (sb[(x >> 16)&0xff] << 16)| (sb[(x >> 8)&0xff] << 8)| (sb[(x >> 0)&0xff] << 0) ); }};// The S-boxes (randomly generated)template < std::uint32_t m, std::size_t rs1,std::size_t rs2,std::size_t rs3,std::size_t rs4, std::size_t rm1,std::size_t rm2, std::size_t rf>std::uint32_t big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>::sbox_i1[256] = { 0x36,0x09,0x2d,0x7f,0x28,0x8a,0x51,0x81,0x2b,0x69,0x90,0x58,0xaf,0x21,0xda,0x71, 0x8d,0x4f,0xb9,0xa4,0x91,0xbc,0xde,0x3f,0xad,0x6e,0xbd,0x5a,0xbb,0x92,0x1a,0x5d, 0x49,0x6a,0x94,0x0a,0xaa,0x30,0xf3,0x73,0x37,0xfa,0xcf,0x7e,0x76,0xdf,0xb1,0x56, 0xd5,0x78,0x12,0x08,0xe3,0xf1,0x07,0x9d,0x98,0xc5,0xe6,0xcd,0x34,0xf8,0xfd,0xd0, 0x2f,0x84,0x66,0x4b,0x3c,0x4e,0xc6,0x63,0x99,0x57,0x60,0x54,0x97,0x9f,0x39,0xf0, 0x59,0xa1,0xcb,0x18,0xed,0x0b,0xd1,0xdb,0x44,0x1e,0x0f,0x72,0x2c,0x5b,0x27,0xc9, 0x55,0x1c,0x41,0xfc,0x11,0x50,0x4d,0x9b,0x88,0xea,0xd6,0xc8,0x45,0xa2,0xcc,0x8c, 0xa6,0x61,0xb5,0x01,0xb4,0x6d,0x93,0xc3,0xab,0xdd,0x9e,0x6c,0x38,0xe7,0x47,0xe9, 0x70,0x31,0xe8,0x03,0x52,0x75,0xe0,0xb6,0x53,0x40,0x46,0x0e,0x3a,0x5e,0x79,0x5c, 0xc2,0x7c,0x7a,0x6f,0xe1,0xd4,0xb8,0x85,0xee,0x22,0xb0,0x80,0x42,0xf6,0xec,0x24, 0xe2,0x9a,0x14,0x8f,0xac,0x15,0x10,0x82,0xa3,0x20,0x3b,0xf2,0x68,0x4c,0xd3,0x9c, 0xca,0x48,0xfe,0x00,0x04,0xc0,0x0c,0xba,0xb7,0xc7,0x3e,0xff,0xd8,0xfb,0x6b,0x65, 0x26,0x17,0x8b,0xf9,0x02,0xb2,0xe4,0xbf,0x8e,0xc1,0x62,0xd7,0x1d,0x77,0x2e,0x96, 0x25,0x33,0x5f,0xef,0x35,0x43,0xf5,0xf7,0xa0,0x64,0x05,0xc4,0x1b,0xd2,0x0d,0x16, 0xdc,0x86,0x7d,0xeb,0x87,0xa5,0x83,0xf4,0x23,0xd9,0x4a,0x95,0x1f,0x7b,0x74,0xa9, 0x2a,0x13,0x06,0x29,0xae,0xce,0x89,0xa7,0x3d,0x19,0x67,0xa8,0x32,0xb3,0xbe,0xe5};template < std::uint32_t m, std::size_t rs1,std::size_t rs2,std::size_t rs3,std::size_t rs4, std::size_t rm1,std::size_t rm2, std::size_t rf>std::uint32_t big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>::sbox_i2[256] = { 0x2d,0xa9,0x38,0x42,0x24,0xd1,0x55,0x8a,0x3c,0x22,0x84,0x7a,0xd6,0xbc,0x2a,0xb7, 0x99,0xd7,0xe6,0x2f,0x9e,0x1f,0x1e,0x0a,0xd0,0x97,0x45,0xe9,0x90,0x8f,0xe7,0x35, 0x40,0x6e,0x9a,0xeb,0x28,0x75,0x03,0x5a,0x29,0x34,0x6b,0x17,0xaa,0x4a,0x6d,0x00, 0x36,0xd8,0x71,0x9b,0xf1,0x25,0x5b,0x46,0x12,0x69,0x9d,0xb9,0x66,0xf7,0x74,0x95, 0x61,0x48,0x1a,0x23,0xcb,0x5c,0xcd,0x70,0x18,0xb3,0x76,0x0e,0x37,0xc8,0x3a,0x92, 0x59,0xdd,0x26,0xaf,0xb0,0x8e,0x44,0xce,0xe3,0xcf,0x4f,0x0d,0x4c,0x19,0x49,0xca, 0x07,0xc7,0xd2,0x72,0x7b,0x3e,0xc5,0xc1,0xc2,0x91,0x86,0x4b,0x57,0xe0,0x02,0xb6, 0xf4,0x7e,0x39,0xd9,0x20,0x65,0xac,0x87,0xb8,0x33,0xe5,0xb2,0xa1,0x96,0x64,0xa6, 0x2b,0x01,0x85,0x50,0xed,0x27,0xff,0x62,0x30,0x80,0xc9,0xa4,0x31,0xde,0x21,0x7c, 0xdc,0xf6,0xae,0x52,0x8c,0x51,0x32,0xbf,0x0c,0xa8,0xb4,0xe2,0xe8,0x94,0x14,0x43, 0xd3,0xdf,0x58,0x77,0x15,0x0b,0xad,0xab,0x7f,0xbd,0xbb,0xf5,0xf9,0x1c,0x5d,0x04, 0xdb,0x54,0xa3,0x47,0x2e,0xfd,0x67,0x53,0x60,0xee,0x6a,0xa2,0xd4,0xfe,0x8b,0x82, 0x4e,0xc6,0xc4,0x98,0xb5,0xbe,0x06,0x3d,0x13,0xf8,0xe1,0x3b,0x81,0xa7,0x79,0x8d, 0xf2,0xb1,0xd5,0x2c,0xc3,0x1d,0x1b,0x73,0x9f,0x6f,0xba,0xcc,0xfc,0xea,0x09,0xa0, 0xec,0x10,0xc0,0x4d,0x11,0x0f,0x88,0x08,0x5f,0x56,0xf0,0x5e,0x63,0xfa,0x05,0x78, 0x3f,0x7d,0x41,0xfb,0x68,0xa5,0x89,0xf3,0xef,0x83,0x6c,0x16,0xe4,0xda,0x9c,0x93};template < std::uint32_t m, std::size_t rs1,std::size_t rs2,std::size_t rs3,std::size_t rs4, std::size_t rm1,std::size_t rm2, std::size_t rf>std::uint32_t big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>::sbox_i3[256] = { 0x06,0x38,0x28,0x6a,0x51,0xb1,0x0a,0x55,0xf9,0xa3,0x73,0x11,0xed,0x3a,0x43,0x83, 0x54,0x74,0x89,0xe0,0x85,0x10,0xcc,0x6f,0x64,0x2b,0x71,0xc1,0xa4,0x5b,0x42,0x92, 0xc8,0x99,0x4a,0x8f,0xda,0xbc,0xb7,0x5c,0x81,0x16,0x52,0x50,0x82,0x61,0x3f,0xf5, 0x1b,0x12,0x90,0x98,0x02,0x05,0x8d,0xa6,0x5a,0xbf,0xe9,0xa7,0x24,0x56,0xfd,0x40, 0x33,0xe6,0x17,0x72,0xf8,0x18,0xd1,0xac,0xa2,0xfe,0x0f,0x88,0x39,0x09,0x6c,0x0e, 0x67,0x7c,0x84,0xeb,0x8a,0xba,0x63,0x03,0x75,0xcd,0x93,0x97,0xab,0x6d,0x76,0xdc, 0xad,0x53,0xb9,0x8e,0xd2,0x4b,0xf2,0xa5,0x4f,0x77,0x7b,0xd7,0x91,0x9f,0x20,0x70, 0xcb,0xc3,0xb4,0x9c,0xa9,0xd8,0x9d,0xb5,0xca,0x7a,0x1a,0xc4,0x0d,0x19,0xc6,0x30, 0xf0,0x5d,0x65,0x79,0x7e,0x2c,0x31,0x13,0x9e,0xbd,0x44,0xbe,0x57,0xb2,0xc5,0x80, 0xe3,0x27,0xd0,0xec,0x48,0x4e,0xae,0x86,0x8c,0xf4,0x3b,0xfb,0xb3,0xa8,0x69,0xb8, 0x1f,0x0b,0xcf,0x4c,0x45,0xaa,0xdf,0xf7,0xe8,0x68,0xef,0x58,0x34,0x7d,0xbb,0xf6, 0x2e,0x22,0xdb,0x35,0xd6,0x6b,0x1d,0x5e,0xc0,0xa1,0x3d,0xfa,0xb0,0xff,0x60,0x2a, 0x41,0x5f,0xc7,0xd5,0x4d,0x1e,0x2f,0x01,0xea,0x49,0xdd,0x26,0xb6,0x78,0xde,0x25, 0x36,0xf1,0x0c,0xe1,0x04,0x32,0x14,0x3e,0x87,0x6e,0x96,0xe5,0xce,0x95,0xe2,0xaf, 0xf3,0xa0,0x46,0x37,0x15,0x1c,0x00,0x2d,0x7f,0xe4,0x62,0xee,0x3c,0x08,0x47,0x9b, 0x66,0xfc,0x21,0xd3,0x94,0x59,0x8b,0x07,0xd4,0x29,0xc9,0x23,0xc2,0x9a,0xe7,0xd9};template < std::uint32_t m, std::size_t rs1,std::size_t rs2,std::size_t rs3,std::size_t rs4, std::size_t rm1,std::size_t rm2, std::size_t rf>std::uint32_t big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>::sbox_i4[256] = { 0x1a,0x6b,0xfd,0xd0,0x0d,0x11,0x50,0x9e,0x1f,0xd3,0x95,0xca,0xbc,0x0c,0x80,0x29, 0x47,0xa4,0x3f,0x3c,0x2c,0x76,0x3a,0x91,0x60,0x8d,0x39,0x9b,0x7e,0x6d,0x1b,0x12, 0x7f,0xf3,0xab,0xb6,0x63,0x7b,0x53,0x31,0xd6,0x4d,0xbb,0xcb,0x56,0xda,0x15,0xbe, 0x67,0xfb,0xa9,0xdb,0x69,0x97,0x42,0xf1,0x5c,0xc5,0xb3,0x34,0xa3,0x6f,0x51,0x4f, 0xc2,0x70,0xf8,0x52,0x92,0x81,0xd1,0x0f,0xba,0x3d,0x4c,0xb0,0x48,0xff,0xd2,0x7d, 0xaf,0x1c,0x65,0xe8,0x4b,0x5f,0x94,0xcc,0x84,0x09,0x64,0x2e,0xb1,0x77,0x96,0xea, 0x79,0x24,0xb8,0x0e,0x90,0x33,0xf9,0xb2,0x57,0x28,0xe9,0x04,0x03,0xa1,0x17,0xe7, 0x82,0xaa,0x19,0x83,0x43,0x9a,0xfe,0xfc,0xc6,0xef,0x1e,0xa6,0x5b,0xbd,0xdd,0x08, 0xb9,0x16,0x9d,0xf2,0x20,0x78,0x06,0xae,0xf0,0xc3,0x59,0x45,0xb7,0xcd,0xa8,0x05, 0xeb,0x26,0x02,0xf6,0x6e,0x8a,0x14,0x98,0x0b,0x25,0xdc,0x7c,0xc1,0x6a,0x86,0x71, 0xed,0x68,0xec,0x85,0x35,0x87,0x18,0x93,0x46,0x23,0xd8,0x6c,0xbf,0x61,0x4a,0xac, 0xcf,0xe3,0x1d,0xb5,0x5e,0xa0,0x9c,0xf7,0x55,0x73,0x2a,0xad,0x00,0xc8,0x75,0xf5, 0xb4,0x8f,0xc7,0x36,0xe5,0x41,0xde,0xee,0xa7,0x9f,0xce,0xd5,0x21,0x8e,0xa5,0x32, 0x2b,0x54,0x99,0x7a,0xe0,0x58,0xfa,0x30,0x5d,0x44,0x8b,0x8c,0x4e,0x72,0x66,0xc4, 0x40,0x2f,0xe6,0x5a,0x2d,0x37,0x01,0x27,0xa2,0xe1,0x22,0x10,0xd7,0x3e,0x89,0x74, 0xc0,0x38,0x88,0xd9,0x62,0x49,0xdf,0x3b,0xd4,0x0a,0x13,0xf4,0xe4,0x07,0xe2,0xc9};template < std::uint32_t m, std::size_t rs1,std::size_t rs2,std::size_t rs3,std::size_t rs4, std::size_t rm1,std::size_t rm2, std::size_t rf>std::uint32_t big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>::sbox_i5[256] = { 0x28,0x21,0xde,0xd7,0x8f,0x86,0xba,0xb3,0xeb,0xe2,0x7c,0x75,0x2d,0x24,0x18,0x11, 0x49,0x40,0x46,0x4f,0x17,0x1e,0x22,0x2b,0x73,0x7a,0xe4,0xed,0xb5,0xbc,0x80,0x89, 0xd1,0xd8,0x4b,0x42,0x1a,0x13,0x2f,0x26,0x7e,0x77,0xe9,0xe0,0xb8,0xb1,0x8d,0x84, 0xdc,0xd5,0xd3,0xda,0x82,0x8b,0xb7,0xbe,0xe6,0xef,0x71,0x78,0x20,0x29,0x15,0x1c, 0x44,0x4d,0x98,0x91,0xc9,0xc0,0xfc,0xf5,0xad,0xa4,0x3a,0x33,0x6b,0x62,0x5e,0x57, 0x0f,0x06,0x00,0x09,0x51,0x58,0x64,0x6d,0x35,0x3c,0xa2,0xab,0xf3,0xfa,0xc6,0xcf, 0x97,0x9e,0x0d,0x04,0x5c,0x55,0x69,0x60,0x38,0x31,0xaf,0xa6,0xfe,0xf7,0xcb,0xc2, 0x9a,0x93,0x95,0x9c,0xc4,0xcd,0xf1,0xf8,0xa0,0xa9,0x37,0x3e,0x66,0x6f,0x53,0x5a, 0x02,0x0b,0xf4,0xfd,0xa5,0xac,0x90,0x99,0xc1,0xc8,0x56,0x5f,0x07,0x0e,0x32,0x3b, 0x63,0x6a,0x6c,0x65,0x3d,0x34,0x08,0x01,0x59,0x50,0xce,0xc7,0x9f,0x96,0xaa,0xa3, 0xfb,0xf2,0x61,0x68,0x30,0x39,0x05,0x0c,0x54,0x5d,0xc3,0xca,0x92,0x9b,0xa7,0xae, 0xf6,0xff,0xf9,0xf0,0xa8,0xa1,0x9d,0x94,0xcc,0xc5,0x5b,0x52,0x0a,0x03,0x3f,0x36, 0x6e,0x67,0xb2,0xbb,0xe3,0xea,0xd6,0xdf,0x87,0x8e,0x10,0x19,0x41,0x48,0x74,0x7d, 0x25,0x2c,0x2a,0x23,0x7b,0x72,0x4e,0x47,0x1f,0x16,0x88,0x81,0xd9,0xd0,0xec,0xe5, 0xbd,0xb4,0x27,0x2e,0x76,0x7f,0x43,0x4a,0x12,0x1b,0x85,0x8c,0xd4,0xdd,0xe1,0xe8, 0xb0,0xb9,0xbf,0xb6,0xee,0xe7,0xdb,0xd2,0x8a,0x83,0x1d,0x14,0x4c,0x45,0x79,0x70};template < std::uint32_t m, std::size_t rs1,std::size_t rs2,std::size_t rs3,std::size_t rs4, std::size_t rm1,std::size_t rm2, std::size_t rf>std::uint32_t big_wheel_engine<m,rs1,rs2,rs3,rs4,rm1,rm2,rf>::sbox_r[256] = { 0xe9,0xe0,0xdc,0xd5,0x8d,0x84,0x1a,0x13,0x4b,0x42,0x7e,0x77,0x2f,0x26,0x20,0x29, 0x71,0x78,0x44,0x4d,0x15,0x1c,0x82,0x8b,0xd3,0xda,0xe6,0xef,0xb7,0xbe,0x6b,0x62, 0x3a,0x33,0x0f,0x06,0x5e,0x57,0xc9,0xc0,0x98,0x91,0xad,0xa4,0xfc,0xf5,0xf3,0xfa, 0xa2,0xab,0x97,0x9e,0xc6,0xcf,0x51,0x58,0x00,0x09,0x35,0x3c,0x64,0x6d,0xfe,0xf7, 0xaf,0xa6,0x9a,0x93,0xcb,0xc2,0x5c,0x55,0x0d,0x04,0x38,0x31,0x69,0x60,0x66,0x6f, 0x37,0x3e,0x02,0x0b,0x53,0x5a,0xc4,0xcd,0x95,0x9c,0xa0,0xa9,0xf1,0xf8,0x07,0x0e, 0x56,0x5f,0x63,0x6a,0x32,0x3b,0xa5,0xac,0xf4,0xfd,0xc1,0xc8,0x90,0x99,0x9f,0x96, 0xce,0xc7,0xfb,0xf2,0xaa,0xa3,0x3d,0x34,0x6c,0x65,0x59,0x50,0x08,0x01,0x92,0x9b, 0xc3,0xca,0xf6,0xff,0xa7,0xae,0x30,0x39,0x61,0x68,0x54,0x5d,0x05,0x0c,0x0a,0x03, 0x5b,0x52,0x6e,0x67,0x3f,0x36,0xa8,0xa1,0xf9,0xf0,0xcc,0xc5,0x9d,0x94,0x41,0x48, 0x10,0x19,0x25,0x2c,0x74,0x7d,0xe3,0xea,0xb2,0xbb,0x87,0x8e,0xd6,0xdf,0xd9,0xd0, 0x88,0x81,0xbd,0xb4,0xec,0xe5,0x7b,0x72,0x2a,0x23,0x1f,0x16,0x4e,0x47,0xd4,0xdd, 0x85,0x8c,0xb0,0xb9,0xe1,0xe8,0x76,0x7f,0x27,0x2e,0x12,0x1b,0x43,0x4a,0x4c,0x45, 0x1d,0x14,0x28,0x21,0x79,0x70,0xee,0xe7,0xbf,0xb6,0x8a,0x83,0xdb,0xd2,0x2d,0x24, 0x7c,0x75,0x49,0x40,0x18,0x11,0x8f,0x86,0xde,0xd7,0xeb,0xe2,0xba,0xb3,0xb5,0xbc, 0xe4,0xed,0xd1,0xd8,0x80,0x89,0x17,0x1e,0x46,0x4f,0x73,0x7a,0x22,0x2b,0xb8,0xb1};#endifSo, I have some specific questions about it:How can I improve the performance of the program?How can the use of multithreading be improved? | Multithreaded Monte Carlo pi approximation with own pseudorandom number generator | c++;multithreading;random;c++14;numerical methods | Parallelism:There are two major problems with your codeYour code doesn't run in parallel at all! Locking the mutex at the beginning of calculate_pi means you are always only run one instance of calculate_pi at the same time.You are passing a copy of the same random number engine to each thread. As this is only a pseudo rando number generator, all threads will operate on the same sequence of numbers (you are doing the same work multiple times).Solution: The only thing you share among the codes is pcnt just define it as an atomic (std::atomic<std::uint32_t>). Even Better: Don't share anything: Let each task use it's own hit counter and sum them up at the end (easiest way to do this would be to use std::async). Create and seed a separate random number engine for each threadOn my 4 Core machine with VS2015U3, this reduced the execution time from 120 to 20 Seconds and reduced the error roughly by a factor of two.Small style tips: Don't define variables before you use them. e.g.:gen_pi should be defined (as a constant) just when you need to store the result of approximate_pi. p1..9 and tmp_x should be (constant) function local variablesConst correctness: A lot of variables are only initialized and never changed afterwards - make them constrange based for: You could use more range based for loops (e.g. when joining the threads, creating the seed, or some loops that go over the state array of the random number engine. |
_softwareengineering.40202 | I was motivated by the Compiler Construction As A Subject question and thought I would ask this one.I have heard from a few people that they have a good compiler team (don't ask where I heard it, I can't remember), so that led me to wonder, how does one get a job on such a team?I know there are classes at in the Undergrad programs and such, but is that something that a graduate degree would be the minimum (such as a Masters at the least)?I am starting my Masters in Computer Science in two months and the school I am going to has two compiler classes, would that be enough to get a job doing compiler development or would more time need to be invested in it? | Compiler Jobs - How Much Education Is Needed | education;compiler | Well, compiler development is ultra hardcore which means that it requires lots of patience, passion and solid knowledge. Don't confuse patience, passion and solid knowledge with having any kind of degree. We've seen several applicants with Masters degree who couldn't even recognize strlen() in four lines of C code.Definitely attend those classes and gain practical knowledge. Maybe you won't even like compiler development, but experience you gain will help you get some other very interesting development job. |
_cogsci.13466 | Is it true that people handle bad news better if they got told good news first, or do they 'forget' the good news if the bad news is told after?Is it better to save the good news for last so the person who gets the news will have a better average feeling about the conversation? | Good news or bad news first | social psychology | My suggestion is to look to prospect theory here. In general, people feel losses 2.5x more than gains (Kahneman + Tversky). There's also an inversion curve: more good has diminishing returns, more bad has diminishing returns too.Basically we 'acclimate'This is a very crude way to think about it. Good news first:In this situation, we could go up the curve, then 2.5X down for the bad news, or the other way around.Bad news first:In this situation, you go down the curve first, but coming back the curve you erase the curve of the bad news, which is 2.5x steeper, so you're actually net gaining in positive utility, because the same amount of good news brings you up the curve more.This is called the silver lining effect in the literature.So all in all, deliver the bad news first: you'll gain more 'upside' on reversing bad news than following up good news with bad (silver lining effect) + people will remember the good news at the end of the conversation (recency effect). |
_webmaster.69798 | I have a main hosting registered with the domain example.com. The hosting allows me to park another domain. I want that any person that access to example2.com be redirected to sub.example.com. In this way:the user access to: example2.com/something/a.htmlThe user sees the content of: sub.example.com/something/a.htmlAnd the browser displays: example2.com/something/a.htmlI tried to do a CNAME from example2.com to sub.example.com but the pages go to example.com. I think that is because the domain is parked at that hosting.When I get that done, how I ensure that Google displays example2.com and not the other subdomain? | How to redirect parked domain to main domain but still show the parked domain in address bar | redirects;subdomain | You could look into doing a frame redirect. It is also sometimes called web forwarding or masked redirect. In that case the redirect server issues content like this:<html><frameset rows=100%,* border=0><frame src=http://www.example.com/my-page.html noresize frameborder=0></frameset></html>This causes the browser to show the contents of your main site, but the URL will show the redirect domain.This type of redirect is not ideal:The URL doesn't change as the user browses around the siteIt breaks bookmarking functionalityThe other option is to fully duplicate the content and fully host two different domains that have all the same pages on them. |
_codereview.98962 | I'm working on a script that focuses on faster mousing. It has hotkeys to:snap the cursor to hard-coded locations,swap the cursor to the location where it was last swapped from, andsave and snap to custom locations.I've been steadily refactoring with an eye to DRY and other principles. For example, the script used to manually define several variables, but now it uses an array. However, I'm coming from a Python background and still getting used to AHK, so the mix between traditional variables vs expressions, commands vs functions, etc. is kind of confusing.MoveLocation used to also send a click if the cursor was within 10 pixels of that saved location, but I ran into some problems:The click was being sent while the hotkey modifiers were held down. I bypassed this by checking whether the key was physically held down... sometimes (I'm calling these hotkeys with extra mouse buttons mapped to the various defined hotkeys), which mostly worked, but it would still include Control while clicking File Explorer in the taskbar with multiple windows open. Thus, instead of popping the row of window previews, it would swap between each window, which is what happens if you Control-click that. To avoid this, I used...The Sleep command, which, while solving the problem, also introduced a noticeable delay. It only handled Control reliably with a delay of 50ms or more, which was bugging me.Here's the removed code:; if Ctrl isn't physically held down, stop sending itif GetKeyState(Ctrl, P) { Send {Ctrl Up} Sleep, 50}MouseGetPos, tempx, tempy; if the current position is close to the save point, click itif (Abs(tempx-x)<10 && Abs(tempy-y)<10) { MouseMove, x, y Click} ; is clicking a good idea? might be cleaner to remove that logic; otherwise, move to the save pointelse {Removing that made the script more reliable and consistent. It's not much of a hassle to just use the ordinary mouse button to click saved hotspots. However, I now feel that maybe there's some other useful thing I could have the script do if I click the go to hotspot hotkey while the cursor is already on it.The current version of the script that I'm actively practicing with is shown below:#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.; #Warn ; Enable warnings to assist with detecting common errors.SendMode Input ; Recommended for new scripts due to its superior speed and reliability.SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.CoordMode, Mouse, ScreenSetDefaultMouseSpeed, 0SysGet, TotalWidth, 78SysGet, TotalHeight, 79SysGet, monitors, MonitorCountoffset := TotalWidth // monitorsstart := offset // 2x1 := start + offset * 0x2 := start + offset * 1y := TotalHeight // 2rx1 := x1ry1 := yrx2 := x2ry1 := ycount := 0locations := []Loop 11 { locations.Push([0,0])}; shift-pause to snap to left monitor, alt-pause to right+Pause::MouseMove, x1, y!Pause::MouseMove, x2, y; swap to last swapped locationPause:: if (count) { MouseGetPos, rx1, ry1 MouseMove, rx2, ry2 count-- } else { MouseGetPos, rx2, ry2 MouseMove, rx1, ry1 count++ } return; Ctrl+Shift+NumpadNumber to save a hotspot; Ctrl+NumpadNumber to go to or click a hotspotMoveLocation(ID) { global locations MouseMove, locations[ID][1], locations[ID][2]}SaveLocation(ID) { MouseGetPos, x, y global locations locations[ID] := [x, y]}^NumpadEnd::SaveLocation(1)^Numpad1::MoveLocation(1)^NumpadDown::SaveLocation(2)^Numpad2::MoveLocation(2)^NumpadPgDn::SaveLocation(3)^Numpad3::MoveLocation(3)^NumpadLeft::SaveLocation(4)^Numpad4::MoveLocation(4)^NumpadClear::SaveLocation(5)^Numpad5::MoveLocation(5)^NumpadRight::SaveLocation(6)^Numpad6::MoveLocation(6)^NumpadHome::SaveLocation(7)^Numpad7::MoveLocation(7)^NumpadUp::SaveLocation(8)^Numpad8::MoveLocation(8)^NumpadPgUp::SaveLocation(9)^Numpad9::MoveLocation(9)^NumpadIns::SaveLocation(10)^Numpad0::MoveLocation(10)^NumpadDel::SaveLocation(11)^NumpadDot::MoveLocation(11); mousewheel version for basic mice~MButton & WheelUp:: Send {Esc} MouseMove, x1, y return~MButton & WheelDown:: Send {Esc} MouseMove, x2, y returnThere's still some code smell from that big block of SaveLocation/MoveLocation hotkey definitions near the bottom. Unfortunately, I couldn't figure out the Hotkey command, and using Shift as a modifier with the number pad requires different key names (e.g. ^NumpadEnd instead of ^+Numpad1), so I don't even know if Hotkey would work.I welcome answers related to refactoring or to the actual utility of the script. | Mouse movement function | autohotkey | null |
_vi.10239 | When I set makeprg using:set makeprg=gcc\ -Wall\ -g\ %\ -o\ %and then invoke :make Vim does not pass proper filenames, because this command is translated as:gcc -Wall -g file.c -o file.cand executed. The compiler is then complaining that input and output files are the same, which is in fact dangerous. My question is how to change the second % in makeprg to have it without .c extension. The command exectuted should be like this:gcc -Wall -g file.c -o fileI don't know what to put instead the second %. | How to customize % symbol in makeprg command | command line;replace;makeprg | Unless you're using a non-properly configured version of gnumake (Solaris OS, or mingw distribution of gcc under windows), you don't need to modify &makeprg. Its default value is already perfect for GNU compilation tools.All you need to do is to set $CFLAGS with :let $CFLAGS=-g -Wall, and compile with :make %<. |
_softwareengineering.214530 | I have an old habit of avoiding calling references multiple times, both for easier to read/maintain code, and for possible efficiency. But I'm wondering which is more efficient (memory, performance, both?).For example when working with XML using a VTD parserif( vn.toString( vn.getCurrentIndex() ).equalsIgnoreCase( broken-label ) == false ) { do { if( parentNode != null ) { currentNode = parentNode.addChildNode( vn.toString( vn.getCurrentIndex() ) ); } else { currentNode = new xmlNode( vn.toString(vn.getCurrentIndex()), null ); treeNodes.add( 0, currentNode ); }Does not store the value, perhaps saving some overhead for creating space to save a local variable and also lowering the burden on the garbage collector (assuming this section of code is repeated thousands of times in quick succession.My habit of cleaner/efficient code would be to replace the above with the simple change ofString label = vn.toString( vn.getCurrentIndex();if( label ).equalsIgnoreCase( vsled-image ) == false ) { do { if( parentNode != null ) { currentNode = parentNode.addChildNode( label ) ); } else { currentNode = new xmlNode( label, null ); treeNodes.add( 0, currentNode ); }While this is obviously easier to read and maintain. Are there any non-human benefits? | Storing a value vs calling reference for repeated use in Java | java;performance;readability;efficiency | Function calls are expensive. In this example, by using that variable, you have eliminated four separate function calls. Each call puts stuff on the call stack, jumps the instruction pointer around, creates the rough equivalent of brand new variables anyway, etc. On many occasions, functions you call will create what really are new variables within their definitions as well.So, yeah, in cases like this, it's better to just go ahead and make that extra variable up at the top. And if you're worried to death about it, and you're willing to sacrifice modularity and maintainability, you might set up the variable outside of the function's body, before the function is called, and then just reference it within the function. |
_webmaster.87097 | Website is being indexed by Google twice.Both indexes have the right SEO information for the home page, such as title and description. However for the sublinks there are two versions, one version of the indexed site that has the correct sublinks and sublink information, and the other version that has all sublinks pointing to the home page with the format of these wrong sublinks being http://example.com/#random%20textI have gone into webmasters and chosen my prefered domain, I have tried removing these wrong sublink pages, but due to redirecting to home, it stops home from being indexed, so I reverted this change, I have tried demoting the sublinks, it did not work, I've tried adding <meta name=fragment content=!> to my header, it did not work, I have tried disabling all plugins on WordPress to see if that was the reason, it was not.I've everything I can think of and would really appreciate some help as to how I can stop Google indexing one version of my website with all the wrong sublinks.If it's of any help, when I search for the business website name on Google as businessexample it shows the broken link index version, and when I search as business example it shows the correct version. | Website being indexed twice by Google | seo;google search console;google search;wordpress;google index | null |
_cs.56672 | Given the grammar $s \to aSb \mid bSb \mid a \mid b$; what is the language generated by the grammar over the alphabet $\{a,b\}$?When I was solving this question I was a bit confused about the language generated by this grammar. Would be set of all palindromes?Or would the language generated by the above grammar be that of all odd length palindromes?Is it possible that a palindrome generated by above grammar be of odd length only as there is no rule for $S \to \varepsilon$? | What is the language generated by a given grammar | formal languages;context free;formal grammars | The language of this grammar is all strings of the form $wb^n$ where $w\in \{a,b\}^*$, and $|w| = n+1$. If I abuse the notation a bit, it is $\Sigma^{n+1}b^n$.If perchance you mean $S \rightarrow aSa \ | \ bSb \ | \ a\ | \ b$, then the language contains all palindromic strings of odd length. |
_hardwarecs.4136 | So far, it appears the only thing I can get if I want a device that's even remotely modern is the Blackberry Priv, but I could be wrong, hence the question.My hard requirements (it's a dealbreaker without them):The keyboard, as mentioned in the topic.Decent app ecosystem (this eliminates all other BB devices)OS that still gets security updatesGood performance (the UI should not hitch and stutter under daily use)Supported on the Verizon networkSecondary concerns (nice to haves):Can be rooted/jailbrokenAt least a 1080p screenBattery life should last a full day under light useOS still gets feature updatesPrice no object; nearly any phone can be had via carrier discounts or secondhand. | Modern smartphone with a physical keyboard | keyboards;smartphones | The new Blackberry Priv runs Android and has a physical keyboard, 4K display, Snapdragon 808 and 3GB of ram (so it should not be slow).Its the closest thing from what you are looking for I guess. |
_unix.213616 | I am creating a password protected file using 7za, command: 7za a /usr/test/loc/file.del.7za /usr/test/loc/file.del -p.... Creating archive /usr/test/loc/file.del.7za Enter password (will not be echoed) : Verify password (will not be echoed) : Everything is OkHowever, while extracting the files using the command: 7za e /usr/test/loc/file.del.7za, it won't prompt me to enter the password and would extract the file. Looking at the documentation, this is not the expected working. Where am I going wrong? | 7za with password not working while extraction | rhel;7z | null |
_codereview.132349 | I'm making a hotkey program to aid me using PC faster. By saying hotkey here, I mean any combination of two or more keys in the keyboard.For example, if I press G, hold it then press M, I have hotkey GM. Then I can launch Gmail from the default browser.The idea is same with the famous AutoHotkey software, but with a slight difference (note that this program I make for myself so I will make it best suite for me).That is, based on my typing, I see that when I type fast, I often press next key before I release the previous key. For example, when typing GMAIL.COM, after press G, I press M, before release G.I see that the time between I press G and M is less than 100 milliseconds. But if I intend to press a hotkey, I will press G, hold it for 200 milliseconds before press M. To determine if a combination of 2+ keys is a hotkey or not, I check to make sure the press time between these keys are greater than 200 milliseconds.Here is the definition:void gh_Both(int vkCode); // This function is check if keys is a valid hotkeystd::map<int, int> src; // Store [keyCode, Tickcount] for keys // src: [keyCode, tickcount]Low level keyboard hook:LRESULT CALLBACK k_Callback(int nCode, WPARAM wparam, LPARAM lparam){ if (nCode >= 0) { int kCode=((KBDLLHOOKSTRUCT*)lparam)->vkCode; switch (wparam) { case WM_KEYDOWN: case WM_SYSKEYDOWN: // if the key is not repeated key, add it and tickcount to src if (src.find(kCode) == src.end()) src[kCode] = GetTickCount(); gh_Both(kCode); break; case WM_KEYUP: case WM_SYSKEYUP: // clear kCode in src src.erase(kCode); break; } } return CallNextHookEx(_k_hook, nCode, wparam, lparam);}The same for low level mouse hook:LRESULT CALLBACK m_Callback(int nCode, WPARAM wparam, LPARAM lparam){ switch (wparam) { case 513: // left mouse down case 516: // right mouse down case 519: // middle mouse down if (src.find(wparam) == src.end()) src[wparam] = GetTickCount(); gh_Both(wparam); break; case 514: // left mouse up case 517: // right mouse up case 520: // middle mouse up src.erase(wparam - 1); break; case 522: // mouse wheel gh_Both((short)HIWORD(((MSLLHOOKSTRUCT*)lparam)->mouseData) > 0 ? 522 : -522); break; } return CallNextHookEx(_k_hook, nCode, wparam, lparam);}gh_Both function:void gh_Both(int vkCode){ // Sort pressed key by Tickcount, save to dst // dst: [tickcount, keyCode] std::map<int, int> dst; for each (auto& i in src) { dst[i.second] = i.first; } int time = 0; // Store key's tickcount int keys = 0; // Store hotkey bool modifier = false; // If have any modifier key (Ctrl/Shift/Alt) or key have keyCode > 90 // or second key is press after first key 200 miliseconds // then they are considered a valid hotkey combination for each (auto i in dst) { if (i.second > 90) modifier = true; if (i.first - time > 200 || modifier || keys > 1000) { // if hotkey is GM with keycode 71 and 77 then keys = 71 * 1000 + 77 = 71077 // all my hotkeys are combination of less than 4 keys keys = keys * 1000 + i.second; time = i.first; // Save Tickcount of key to time } } switch (keys) { case 71077: // 071: G, 077: M cr(http://mail.google.com, ); // Launch Gmail break; case 66067: // 066: B, 067: C cr(http://www.bbc.co.uk/, ); break; case 70066: cr(http://www.facebook.com/, ); break; case 516: case 519: if (vkCode == 522) sms(APPCOMMAND_VOLUME_UP, false); // VOLUME + else if (vkCode == -522) sms(APPCOMMAND_VOLUME_DOWN, false); // VOLUME - break; default: break; }}My target OS: Windows XP and later. The programe is working as I intend. But I post here to check if there are any errors in my code.Questions:Can I improve the way I store [key, tickcount] and gh_Both function?Are there any bugs/errors in my code? | Custom hotkey like AutoHotkey | c++ | null |
_unix.266472 | After booting into live USB after several seconds everything freezes I can't even open the terminal (CTR+ALT+F1),Looked for a solution and found out that putting acpi=off on the boot menu should make it work,It actually helped and I was able to use the live USB and install but the problem is that now I have to boot again using acpi=off in grub and it make the OS work only with one CPU thread, it doesn't recognizes my multi threaded CPU.I use HP Laptop with i7 quadcore CPU and Quadro GPU (ZBook 15 G2)What should I do? | Linux Mint 17.3 and Ubuntu 15.10 Both freeze after USB live boot | ubuntu;linux mint;acpi | null |
_unix.184957 | I am looking for instructions on how to install Keepass2 on CentOS 7 unfortunately no luck so far. Is there any rpm available anywhere? Any info will be much appreciated! | How to install keepass2 on CentOS 7? | centos | null |
_unix.362612 | I do the following:rsync --recursive --delete --delete-excluded --exclude-from=$HOME/etc/rsync_exclude.txt --relative --safe-links --executability . /path/to/savedirNote that the source directory is the working directory (specified as .)Inside the working directory, I have a directory ./repository and a file ./Vagrantfile.The file rsync_exclude.txt contains, among others, the lines/repository//VagrantfileI would have expected that these entries would exceed my repository and Vagrantfile, becausethe leading slash expresses that the names are to be anchored at the root directory for saving, which is the working directory, andthe trailing slash on repository explicitly states that this is a directory, not a fileHowever, both entries are copied.What did I do wrong?(This is rsync 2.6.9 running on MacOS Sierra (but I don't think this matters in this case)).UPDATE: When debugging rsync (using -vv and --dry-run) I can clearly see that all non-anchored rules are accepted (for instance, rsync tells me hiding directory vp5/.git because of pattern .git/), but none of the anchored rules work. I also tried to replace the source directory (.) by ./ or $PWD, but this too did not have any effect.Furthermore, when I remove the leading / (for instance, turning /repository/ into repository/), the directory is excluded. Of course this directory would now be excluded anywhere in the tree, which doesn't harm in this particular case, but is not what I want in general). | rsync ignores anchored exclude pattern | rsync | null |
_unix.213120 | I have big text-data without spaces and without other rows in one line.In reality, the streams are 0.2 Gb/s, similar situation here, but in this task, counting occurrences which is more challenging computationally than just counting empty lines. The match is 585e0000fe5a1eda480000000d00030007000000cd010000Example data subset is here called 30.6.2015_data.txt and its full binary data here called 0002.raw. The match occurs 1 time in 30.6.2015_data.txt but 10 times in the full data 0002.raw in one line. I prepared the txt data by xxd -ps 0002.raw > /tmp/1 && fold -w2 /tmp/1 > /tmp/2 && gsed ':a;N;$!ba;s/\n//g' /tmp/2 > /tmp/3. The faster implementation, the better. To prepare the mega string in column, you can use this xxd -ps 0002.raw > /tmp/1 && fold -w2 /tmp/1 > /tmp/2. My current rate is 0.0012 s per match i.e. 0.012 s per ten matches in the full data file, which is slow. Grep does this in rows so not possible in counting. In Vim, %s/veryLongThing//gn is insufficient for the task. The command wc is giving only character, byte and lines so not correct tool but probably by combining it to something else. Possibly GNU Find and Sed combination but all implementations seems to be too complicated. Outputs of Mikeserv's answer$ cat 1.7.2015.sh time \ ( export ggrep=$(printf '^ \376Z\36\332H \r \3 \a \315\1') \ gtr='\1\3\a\r\36HZ^\315\332\376' LC_ALL=C gtr -cs $gtr ' [\n*]' | gcut -sd\ -f1-6 | ggrep -xFc $ggrep ) <0002.raw$ sh 1.7.2015.sh 1real 0m0.009suser 0m0.006ssys 0m0.007s-----------$ cat 1.7.2015.sh time \ ( set x58 x5e x20 x20 xfe x5a x1e xda \ x48 x20 x20 x20 x0d x20 x03 x20 \ x07 x20 x20 x20 xcd x01 x20 x20 export ggrep=$(shift;IFS=\\;printf \\$*) \ gtr='\0\1\3\a\r\36HXZ^\315\332\376' \ LC_ALL=C i=0 while [ $((i+=1)) -lt 1000 ] do gcat 0002.raw; done | gtr -cd $gtr |gtr 'X\0' '\n ' | gcut -c-23 |ggrep -xFc $ggrep ) $ sh 1.7.2015.sh 9990real 0m4.371suser 0m1.548ssys 0m2.167swhere all tools are GNU coreutils and they have all options you provide in the code. They may however differ with GNU devtools. Mikeserv runs his code 990 times and there are 10 events so total 9990 events is correct. How can you count the number of matches in a megastring efficiently? | To count number of matches in a mega string quickly | shell script;sed;find | The GNU implementation of grep (also found in most modern BSDs though the latest versions are a complete (mostly compatible) rewrite) supports a -o option to output all the matched portions.LC_ALL=C grep -ao CDA | wc -lwould then count all the occurrences.LC_ALL=C grep -abo CDAto locate them with their byte offset.LC_ALL=C makes sure grep doesn't try and do some expensive UTF-8 parsing (though here, with a fixed ASCII string search, grep should be able to optimise away the UTF-8 parsing by itself). -a is another GNUism to tell grep to consider binary files. |
_unix.356652 | Is git diff related to diff?Is git diff implemented based on diff?Is the command line syntax of git diff similar to that of diff? Does learning one help using the other much?are their output files following the same format? Can they be both used by git patch and patch? (Is there git patch? How is it related to patch?)Thanks. | Is `git diff` related to `diff`? | git;diff | null |
_softwareengineering.294445 | We're designing a rest endpoint for retreiving name autocompletion suggestions for hotel names.Currently it's defined like this: GET /suggest/:term, so that if you queried `/suggest/hil' you would get responses like Hilton Paris, Hilton New York, etc.One of our colleagues argues that this is against REST API design best practices, and that the search term should instead be a query parameter, i.e. /suggest?term=hilt.Looking around other famous APIs, it seems that they all use a query parameter:https://developers.google.com/places/webservice/autocompletehttps://swiftype.com/documentation/autocompletebut I'd like to know why; whether the former is actually bad design and what guidelines would get me to make it a query parameter in the first place. | REST autocomplete endpoint design | rest | null |
_codereview.55001 | I spent a lot of time doing Go Horse Extreme programming, but now I want to be a better person.How can I make this method smaller, better, more OOP? /** * @return \Illuminate\Http\RedirectResponse */public function store(){ if (!User::is_valid(Input::all())) { Flash::error(User::$errors->first()); return Redirect::back()->withInput(); } $existing_user = User::where('email', Input::get('email'))->first(); if (is_null($existing_user)) // The user does not exists. { // Prepare user data $user_input = Input::only( 'firstName', 'lastName', 'email', 'password'); $confirmation_token = str_random(60); $user_data = array_merge($user_input, ['confirmation_token' => $confirmation_token]); // Store user $new_user = User::create($user_data); // Prepare email $data['name'] = Input::get('firstName') . ' ' . Input::get('lastName'); $data['confirmation_token'] = $confirmation_token; $mail_subject = 'Confirmao de e-mail'; // Send email Mail::send('emails.auth.email_confirmation', $data, function ($message) use ($mail_subject) { $message->to(Input::get('email'))->subject($mail_subject); }); // Log the new user in Auth::login($new_user); $flash_message = sprintf( 'Enviamos um email para <strong>%s</strong>. Confirme sua identidade', Input::get('email') ); Flash::warning($flash_message); return Redirect::route('admin.dashboard'); } else { if ($existing_user->is_active()) { //Try to validate $stored = $existing_user->password; $typed = Input::get('password'); $match = Hash::check($typed, $stored); if (!$match) { Flash::warning( 'Voc j possui uma conta. Faa login para continuar.' ); return Redirect::route('login'); } else { Auth::login($existing_user); Flash::message( 'Voc j possui uma conta. Bem vindo de volta!' ); return Redirect::route('admin.dashboard'); } } else { Auth::login($existing_user); $flash_message = sprintf( 'Enviamos um email para <strong>%s</strong>. Confirme sua identidade [Reenviar]', $existing_user->email ); Flash::warning($flash_message); return Redirect::route('admin.dashboard'); } }}It just handles user registration. Everything seems to be working when I run my Behat tests, but I feel (deep in my soul) that things could be a lot better. | Controller for handling user registration | php;beginner;object oriented;mvc;laravel | There are many ways you can refactor this method but since you are using Laravel things are pretty easy. Here is my attempt on refactoring (I'd rather call it re-writing) this method.First of all, this controller is overloaded with so many responsibilities, a controllers sole job should only be to accept an HTTP Request, defer the execution to responsible object and deliver an HTTP Response, that is all a controller need to do. so lets refactor it first.Defer execution to service classI'd create a service class with name AccountService and inject it into AccountController (or whatever you call it in your case), then on AccountService I'd create a method named createNewAcocunt($firstName, $lastName, $email, $password)which will validate the data and create new account. Take care of responsibilitiesThe else part of controller method store() defeats the purpose of REST thingy, I'd just issue a redirect to login page with an appropriate message instead of trying to log them in. all of login stuff and account activation status checking should be performed over login route so it clearly does not belongs to the account creator (or signup) route. with these 2 things in place the controller method store() would look like thispublic function store(){ $details = Input::only('firstName', 'lastName', 'email', 'password'); try { $user = $this->accountService->createNewAccount($details['firstName'], $details['lastName'], $details['email'], $details['password']); Auth::login($user->id); return Redirect::route('admin.dashboard'); } catch (ValidationException $validationEx) { return Redirect::back()->withError($validationEx->getErrors()); // assuming you set errors on exception object before throwing it }}Now over to the AccountService class.The method createNewAcocunt($firstName, $lastName, $email, $password), by its name, should create an account with data fed to it. In case there is an error it should throw an exception. Take advantage of events as they happenNow, you need to take care of responsibilities once again, do not overload this method with mail sending, user login or stuff like that, the only responsibility of this method is to create an account. To handle the mail sending and other tasks you need to perform after creating an account you can use laravel's EventDispatcher class or Event facade (Documentation here).My method would look like thispublic function createNewAcocunt($firstName, $lastName, $email, $password){ $validation = $this->accountValidator->validate( compact('firstName', 'lastName', 'email', 'password') ); if($validation->fails()) { $up = new ValidationException('Invalid data for new account'); // set error messages on exception to communicate them to upper layer $up->setErrors($validation->errors); throw $up; } $token = str_random(60) // if you use a repository then $user = $this->repository->createNewAccount($firstName, $lastName, $email, $password, $token); // or do it in whatever way you prefer // Now that the user is created fire suitable event Event::fire('account.created', [$user]); return $user;}Most of it has already sorted out, now you can catch the event account.created and perform whatever action you want.My advice for sending out emails would be to queue emails instead of sending them in real time, this will decrease the response time since the codes will no longer poll for email to be dispatchedMail::queue('emails.auth.email_confirmation', $data, function ($message) use ($mail_subject){ $message->to(Input::get('email'))->subject($mail_subject);});read more about email queue hereand at last, you can customize the validation error message for email:unique rule and make that include a link to login page. check out the custom error message section over here. basically you can just pass in an associative array to Validator like this:$messages = [ 'email.unique' => 'Looks like you already have an account, please <a href=' . route('login') . '>Log in here</a>'];$validation = Validator::make($data, $rules, $messages);$validation->errors->get('email'); // should display the message as defined aboveI hope this will give you at least an idea to get started with. I, for one, am really happy about your decision to go pro. |
_unix.378387 | Everything was working just fine on office wifi, but suddenly I can't seem to browse any site. I can ping 8.8.8.8 just fine, but ping google.com returns ping: unknown host google.com. Also my browser can't seem to connect to any site.I can browse just fine on other network tho.Have tried solutions offered inI can ping IPs but can't resolve domainscan ping google dns, but not google.de -> unknown host // worked in another networkbut still can't work it out. I'm running Ubuntu 16.04nslookup google.com returned;; connection timed out; no servers could be reachedcat /etc/resolvconf returned# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTENnameserver 8.8.8.8nameserver 8.8.4.4 | Can ping 8.8.8.8 but can't browse internet | ubuntu;networking;wifi;dns | Your DNS resolving doesn't work.Check your firewall for an open port UDP/53 to 8.8.8.8# iptables -L -n -vCheck with your ISP for DNS server provided. They are probably blocking UDP/53 somewhere on the way out to force you to use internal DNS server.If you are on DHCP, renew the lease.Depends on distro (most probably networkmanager, ifdown/ifup combination may work as well).This happens quite often with resolvconfd and dnsmasq. You may need to restart the NetworkManager thenAgain - command depends on distro, usually with systemd# systemctl restart NetworkManagerIf you are on static IP and have noone to ask or check their config, you may sniff (tcpdump -nnvv -i <interface> udp port 53). |
_unix.346017 | Sometimes after I turn on the desktop PC, randomly one of the 4 cores goes to 100% and the machine freezes.Well, I have htop running on it from a remote connection and I can see that all processes are still working.An interesting thing that happens is ex.: a youtube video will continue playing its audio but the screen becomes all frozen, even the mouse won't change its position.At the top of the list at htop, this time was kworker with 100% cpu usage, but other times there was no process at 100%. The cpu 1 (core index 0) was at 100%. So, the core 0 was being actively used by about 10% and the remaining bar was all red, filling 'til 100%. I think that red filling indicator is IO wait right?Then the load average will not stop increasing.So I guess it is related to some kind of IO, I would guess video IO? What commands I could use to test it?In this case, I can't even create a new remote connection, it won't accept, will just freeze the attempt. So I will start such command on a loop and monitor its output whenever the next freeze happens. | how to determine the origin of: one core to be at 100% and freeze the machine? | io;freeze | null |
_webmaster.104715 | I am migrating to a new domain, the previous domain that I had it was really just used for me to learn how to develop websites, so the traffic, if any, of the old website is not important for me, the problem here is that now I am concern about the new website SEO, I do care about this new domain and since the new website is going to have the same information as the old one, I was wondering if google is going to penalize my new domain for having essentially the same content of the old website. I did implement a sitemap, link it to search console and even had analytics, just for testing idk if this information is relevant for the issue, but just to point it out.I am also using a default header file for every page in the website, so since SEO takes into account the title and the description of the page, should I stop using this default header? or there is a way to overwrite the information for each page. I am using php require for header and footer files. | New domain SEO and default header file | seo;domains;html;php | null |
_webmaster.33968 | This is the question I asked on SO site earlier, but didn't get satisfactory replies. hoping to find a solution here..https://stackoverflow.com/questions/12136796/how-can-i-detect-and-correct-these-errors-on-my-blog/12136829#comment16235061_12136829In web master tools, apart from the errors in the question link above, it is showing a site map error too as in the screenshot below:-Need guidance please...thanks :)Edit -1 EDIT 2I had 2 SEO plugins on my blog and I would put meta description for each of my article in both plugins that are All in One SEO and Yoast's Wordpress SEO. Now I removed all article's meta descriptions from All in one SEO the other day but STILL web master tool is showing duplicate meta tags and descriptions. Why?? | How do I remove these errors from my blog so as to get adsense approved? | wordpress;google adsense;sitemap;blog | null |
_cs.77110 | Consider a standard LP minimization problem of the form$$\begin{array}{ll} \text{minimize} & c^\top x\\ \text{subject to} & A x = b\\ & x \geq 0\end{array}$$Should I expect, on average, an improvement in the number of iterations needed to achieve optimality if adding a (tight enough) constraint of the form $c^\top x \leq m + \varepsilon$ to it? By tight enough I mean that $m$ is the optimal value of the problem and $\varepsilon$ is small in some sense. | Adding linear constraint to continuos LP to improve performance | optimization;linear programming | null |
_codereview.61171 | I have created this program and it works fine. It's just that its too wonky and huge so I was wondering if anyone knew how I could shorten the program so I didn't have to put all of these into each buttonif(guess == number){ l1.setText(You have won the number was + number);}if(guess > number){ l1.setText(Too high);}if(guess < number){ l1.setText(Too low);}Here is the full programpublic class Main { public static int number, guess; public static Random rand; public static Scanner scan; public static JButton b1 = new JButton(1); public static JButton b2 = new JButton(2); public static JButton b3 = new JButton(3); public static JButton b4 = new JButton(4); public static JButton b5 = new JButton(5); public static JButton b6 = new JButton(6); public static JButton b7 = new JButton(7); public static JButton b8 = new JButton(8); public static JButton b9 = new JButton(9); public static JButton b10 = new JButton(10); public static JLabel l1 = new JLabel(Guess a number between 1 and 10!); public Main(){ frame(); } public void frame(){ rand = new Random(); number = rand.nextInt(10); JFrame f = new JFrame(); f.setResizable(false); f.setSize(500,500); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); JPanel p = new JPanel(); f.add(p); p.add(b1); p.add(b2); p.add(b3); p.add(b4); p.add(b5); p.add(b6); p.add(b7); p.add(b8); p.add(b9); p.add(b10); p.add(l1); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 1; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 2; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b3.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 3; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b4.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 4; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b5.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 5; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b6.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 6; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b7.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 7; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b8.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 8; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b9.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 9; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); b10.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ guess = 10; if(guess == number){ l1.setText(You have won the number was + number); } if(guess > number){ l1.setText(Too high); } if(guess < number){ l1.setText(Too low); } } }); } public static void main(String[] args){ new Main(); }} | Too-high / too-low guessing game in Swing | java;random;swing;event handling | null |
_codereview.67420 | I've written a function which can get the environment variable's value. The input parameter would one of the following:${machine}/bin${machine/bin}${machine}/bin${path${OS}}/pathI would need to check the values which start with ${} I've written a function which is recursive in nature, and I would appreciate it if anyone can review the code for me and tell me what can be done better:private String replaceWithEnvironmentVariables(String specialChars) { String result=; boolean flag=true; try{ result = specialChars; String temp = ; char loopBreaker = '}'; char dollarCheck = '$'; char slashCheck = '/'; int index = result.indexOf({); if (index == -1){ result = result.replaceAll([{},$], ); return result; } for (int i = index; i < result.length(); i++) { if(slashCheck==result.charAt(i)) break; temp += result.charAt(i); if(dollarCheck==result.charAt(i) || loopBreaker==result.charAt(i)){ break; } } String sub = temp.replaceAll([{},$/], ); if(sub==null || sub.length()==0){ sub=; flag=false; result = result.replace(temp, sub); } if(flag){ String returnSub = getEnvironmentVariableValue(sub); result = result.replace(temp, returnSub); } }catch(NullPointerException nullPointer){ nullPointer.printStackTrace(); }catch(Exception except){ except.printStackTrace(); } return replaceWithEnvironmentVariables(result);} | Get the environment variable's value | java;recursion | I really have a hard time figuring out what you want to archive. Maybe a working example would help me; especially one containing /.So this is what I would suggest so far/* * These variables always have the same value. Make constants of them. */public static final char LOOP_BREAKER = '}';public static final char DOLLAR_CHECK = '$';public static final char SLASH_CHECK = '/';private static String replaceWithEnvironmentVariables(String specialChars) { // This is the only time a NullPointerException can occur inside this function - prevent it! if(null == specialChars) { return null; } // Why should result be first assigned ? Up to the point where specialChars is assigned to result, no Exception can occur. String result = specialChars; // We need to include the $ if you are only interested in things starting with ${ final int index = result.indexOf(${); if (index == -1){ // No need to update result - just return it return result.replaceAll([{},$], ); } // declare outside loop, so we can use it outside loop int groupEnd; // start at index + 2 as we know that ${ is at index for (groupEnd = index + 1; groupEnd < result.length(); groupEnd++) { // cache char, so we don't have the overhead of a function-call each check final char c = result.charAt(groupEnd); if(SLASH_CHECK == c){ // Don't include '/' break; } if(DOLLAR_CHECK == c || LOOP_BREAKER == c) { // Include '$' or '}' then break groupEnd++; break; } } // Creating temp like this will utilize array-copying-mechanics, which should be faster than appending single characters final String temp = result.substring(index, groupEnd); // [{},$/] is searching for too many characters as we stop, when we hit '/' final String sub = temp.replaceAll([{},$], ); // sub can not be null if(sub.length() == 0){ // no need for flag. It is either this block or the next // also no need to assign to sub as it is never again used outside this block result = result.replace(temp, ); } else { // As I do not know what getEnvironmentVariableValue does, you may need your catch-clauses here. Also I would assume, that you need a return-statement in both catch-clauses as otherwise you are going to call the function with the same parameter over and over again as result is equal to specialChars at this point try{ String returnSub = getEnvironmentVariableValue(sub); // replace will throw a NullPointerException when we try to replace with null if(null == returnSub) { result = result.replace(temp, ); } else { result = result.replace(temp, returnSub); } }catch(NullPointerException nullPointer){ nullPointer.printStackTrace(); }catch(Exception except){ except.printStackTrace(); } } return replaceWithEnvironmentVariables(result);} |
_unix.154557 | In the following makeffile one macro process it's arguments to call another macro. I expect that makefile below will generate two targets and correct list of the targets in $TARGETS. But in fact it only generates one target with correct list. How to do such macro call in correct way?all: $TARGETSdefine f2.PHONY: target$(1)target$(1): echo We are in $(1)TARGETS+=target$(1)endefdefine f1VAR$(1)=ValueWith$(1)$(eval $(call f2,$$(VAR$(1))))endef$(eval $(call f1,CallOne))$(eval $(call f1,CallTwo))$(warning Warning: $(TARGETS))output of make:test.mk:16: warning: overriding recipe for target `target'test.mk:15: warning: ignoring old recipe for target `target'test.mk:18: Warning: targetValueWithCallOne targetValueWithCallTwogmake: Nothing to be done for `all'. | Gmake macro expansion: macro calls macro with variable in arguments | make;macro | Let's add some more debugging code.all: $TARGETSdefine f2$$(info f2 called on $(1)).PHONY: target$(1)target$(1): echo We are in $(1)TARGETS+=target$(1)endefdefine f1VAR$(1)=ValueWith$(1)$(info too early: VAR$(1) is $$(VAR$(1)))$$(info right time: VAR$(1) is $$(VAR$(1)))$(eval $(call f2,$(VAR$(1))))endef$(eval $(call f1,CallOne))$(eval $(call f1,CallTwo))$(warning Warning: $(TARGETS))Output:too early: VARCallOne is $(VARCallOne)f2 called on right time: VARCallOne is ValueWithCallOnetoo early: VARCallTwo is $(VARCallTwo)f2 called on debug.mk:18: warning: overriding commands for target `target'debug.mk:17: warning: ignoring old commands for target `target'right time: VARCallTwo is ValueWithCallTwodebug.mk:20: Warning: target targetmake: *** No rule to make target `ARGETS', needed by `all'. Stop.The problem is that the eval call is made before the definition of VAR, at the time the function f1 is expanded, instead of at the time the result of that expansion is processed. You need to delay the eval.Also there is a typo in line 1; if you fix it, you'll find that the target all builds nothing since TARGETS is not defined at the time it's used. You need to declare the dependencies later.all: # default target, declare it firstdefine f2.PHONY: target$(1)target$(1): echo We are in $(1)TARGETS+=target$(1)endefdefine f1VAR$(1)=ValueWith$(1)$$(eval $$(call f2,$$(VAR$(1))))endef$(eval $(call f1,CallOne))$(eval $(call f1,CallTwo))$(warning Warning: $(TARGETS))all: $(TARGETS) |
_webmaster.90505 | Is there a way to identify that someone is scraping my website? | How can I find out if my website is being scraped? And how do I stop it? | web development;web crawlers;security | null |
_vi.6448 | Is there a way to run tests of the current opened file and get output in other window like vim-QuickRun does?Right now I'm running tests by the command in command line:/vagrant/my_project/app/Console/cake test app Console/Command/FeedParseShell+++UPDATE+++I'm calling cake command in the project folder by absolute path, because I have several projects on my virtual machine. I'm still not aware how to make vim to know where is the root folder of the project It's currently in.And then I tell CakePHP console what command I want it to run by specifying the option test and write the path to the test file.It looks like this:/vagrant/my_project/app/Console/cake test app Console/Command/FeedParseShell(app is not necessary - we can specify the absolute path to the test file without app like:/vagrant/my_project/app/Console/cake test /vagrant/my_project/app/Test/Case/Console/Command/FeedParseShell)Test files are locatedy in different folders. Here is the structure of Test/Case folder:Console Controller Lib Model View allTest.php | How do I run Cakephp's tests (PHPUnit) and output it to QuickRun or other window? | quickfix;filetype php | I'm not familiar with CakePHP, but you could use :make for it:set makeprg=/vagrant/my_project/app/Console/cake\ test\ app\ Console/Command/FeedParseShellThen, if you run :make, the output of this command will be used to populate the quickfix list (which can be useful if the output identifies offending line numbers). |
_unix.388130 | I want to login to a weblogic server in an enterprise environment via an ssh session. My session drops immediately when I key in password, with the following error:'Write failed: Broken pipe'.The control tab of the admin console of that weblogic server keeps rolling and doesn't load either.What could be wrong, and how can I debug this? | Issues with weblogic server | linux;rhel;weblogic | null |
_softwareengineering.125258 | I have a requirement to create a donation software for a project.Does anyone know how KickStarter designed theirs? What are the security elements involved? How do I create the credit card transactions-processing part? Is there some common library/service used for that?I am still in research phases for this, so any ideas appreciated! | How to create donation software? | security;web design | There are a lot of issues for handling credit cards. The easiest solution is using a service like Paypal's service to process the credit cards. That way, all you have to do is store the amount and a PayPal Transaction ID.You can then start moving up to more complicated solutions, directly using gateways such as Verisign (yes, that's part of PayPal) or Authorize.net or any of a lot more.Things that you will need to think about, especially if you start to go towards using merchant account APIsPCI ComplianceFraud protectionDispute handlingAuditingGetting an Internet Merchant AccountStoring/ Not storing/ encrypting personal identifiable informationIt's a really broad topic, and there are a lot of answers out there. This is a bit of a start of things you'll have to think about. |
_webapps.45246 | That is, I have created a Twitter list with some 100 members and would like to search for a particular word within all users of the list. | How do I search within a Twitter list? | twitter | null |
_webmaster.29820 | I'm using jQuery .load to load content in from other pages into my homepage, so that Google can still see whats going on I've made the <a> tags go to the pages but over ride them in the JavaScript so instead of going the that page it just loads in the content from that page to the main page.Normaly I would just make the page /contact.html a goal.Can I still get it to work as a goal if the content is being loaded in? Can I do something like when the user clicks <a href=contact.html id=load-contact>contact</a> it logs the clicking of the <a> tag as a goal, rather than the actaul page being visited? | Setting up page goals in Analytics when using progressive enhancement to load content using jquery .load | google analytics;goal tracking;goals | null |
_softwareengineering.271766 | I'm creating a web application with a front end client written in angular as well as a back end that I'm writing in Django (there are reasons I picked the frameworks but they are irrelevant to my question).I have my front end planned out down to every page that will be available. I currently am only going to implement the angular cient but in the future I plan on implementing a native android and iOS app for learning purposes.My question is how coupled should my back end design be with my front end client? Should I design my endpoints on a per view basis?This seems like back end will need work when I create another client.Or should my endpoints be more focused around exposing CRUD functionality for my models?This seems like it would leave room for creativity and make the back end more flexible.These are a few of the questions I have been asking myself and I provided them to add a little more scope to my question.Even if I went with the crud approach it seems like I will still be implementing specialized endpoints for handling common application features.Thanks in advance. | RESTful Backend - How coupled should my back end and front end be? | web development;web applications;rest;web services;web api | If each client you intend to service requires different output from your back end. Then write your back-end in a way where is can serve each type.Do some abstraction. Ask yourself, what things will all clients need the same way, and what things will each client need in a specific different way.Put all the stuff that is the same for all clients together, and then write an interface for each client that handles the differences for that client. These interfaces will get all content from the same module, but adapt serving that content to the specific clients needs. |
_reverseengineering.4792 | I'm trying to decompile the windows photo viewer DLL files to try to tweak them, such as editing speed etc. Since this wasn't possible in the registry.When opening the files in a program such as ILSpy or dotPeek, I get a message that looks like this: This file does not contain a managed assembly.I'm rather new to reverse engineering things so could anyone tell me what I'm doing wrong here since the programs say it's a .NET Framework 4.5 application. | Decompiling windows photo viewer | dll;.net | null |
_webmaster.107455 | Back in the 90's books would always talk about using body and head tags. Do those tags even matter anymore?I've added scripts and style tags and the browsers accept them without any tags. | Do , and tags even matter anymore? | html;web development;development | If you don't use proper HTML, including , , , you can't validate a page, so no easy way to spot problems with the actual page coding. I'm going to guess that invalid HTML also significantly affects SEO, to the extent that matters. |
_cstheory.18233 | Lambda Calculus is very simple. Are there even simpler turing-complete systems? Which is the simplest of them all? | What are the simplest turing-complete systems? | fl.formal languages;turing machines;lambda calculus;functional programming | null |
_softwareengineering.36588 | I'm looking for an open source license which grants me additional privileges.Features:Anyone can freely modify, fork, use the code, as long as they make their source changes publicly available. They can use it in other open source projects, but not in closed-source projects. (similar to, say, GPL v3, with strong emphasis on contributing back)Only I and entities I specifically designate can use the code as part of a closed-source application. I am also exempt from the duty to publish the source code changes. (exemption from GPL duties).In return for my work, I do want the freedom to benefit from other's contributions (by using the project in my closed-source work), even if they fork the code.I'm not trying to forbid the commercial use, just to allow myself more flexibility to use the code, while still contributing to open source. I don't want to burn myself by being legally forbidden from using the libraries I wrote in my commercial projects.Large companies use such dual licenses to maintain an open source project, while also selling the premium version.Which licenses of this type are available? What caveats or obstacles exist?Is there any read-made license for this situation? Consulting lawyers is not an acceptable option at this point in development. | OpenSource license with commerial-use exemptions for the owner | open source;licensing | null |
_datascience.10058 | I'm totally new to the topic of real-time bidding in which I know Machine Learning algorithms are used pretty often.Can somebody explain me the system in a plain language i.e. a language for a non-technical person?What is the bidding? Who bids on what? Where does Machine Learning get involve?What is cookie matching mainly about? | Analysis of Real-Time Bidding | data stream mining | A simplified example: suppose two companies: the webpage owner and a book store. And a customer named Jane, interested in reading.The web page owner has some free space on its page, which can be sold for advertisement. The book store wants to place an advertisement on the same web page, in order to increase sales. Both companies meet eachother at an auction, where the web space is sold to the highest bidder in real-time.So, the book store is bidding on the right to show an advertisement to Jane, who is visiting the page of the webpage owner.The machine learning is done on the part of the book store, who receives information about the web page visitor. This can be all sort of information that the web page owner wants to release, and that could be of any use to the bookstore. Based on this information, it is decided weather to make a bidding for the advertisement space or not, and the amount up to which the book store will want to make a bidding. Without cookie matching, the webpage visitor Jane will probably not be identifiable by the bookstore, so the store must decide on bidding, based on parameters like geographical location of the customer, browser version (just to name a few ).With cookie matching, each visitor/customer gets a unique identifier at the book store. Based on this identifier, the book store has more information of the visitor, like: what ads have been served before, and how long ago ? This visit to the web page can be linked to earlier visits and this information will likely ease the decision making process for doing the bidding on the advertisement space.( There is more to it as there can be two more intermediary companies: one that holds the auction and one that delivers the ad ) |
_unix.292027 | I am currently using various live Linux versions.In most cases I have the choice between a 64 bit and 32 bit versions.Does 32 bit have any disadvantages other than slightly lower performance?What about available software, drivers etc?Which versions are generally best supported?One of the machines I might use them on is a 32bit, so those distros are a bit more flexible for me.Also, if footprint is a bit smaller on a 32bit, there is less data to move from a Live USB etc.Mainly Mint and Ubuntu for now, but availability of packages are quite important. (Especially system tools) | 32 bit versions vs 64 versions of Linux | 64bit;32bit;distributions | null |
_webapps.43296 | I have a Gmail account with my own person email address like [email protected] . This all works fine. Backed up in my Gmail account I had other email ids with other characters/names before the @myemailid.com . I know that these emails are backed up in my Gmail account but I have forgotten what names I used. How can I do a search for a backed up email that starts with 2 characters, as in **@myemailid.com ?Is it possible to search for an email address that only has 2 character before the @? | Search Gmail for emails from specific address using single character wildcard | gmail search | null |
_unix.272618 | I'm looking for a permanently-running monitor which can emit a monthly (or daily, etc) bandwidth report, in a per-program manner.Example desired output:Bandwidth consumption: last 30 days==============Program Downloaded Uploaded/usr/bin/ssh 30MB 100MB/usr/bin/java 9000MB 3000MB(it also could be per-process instead of per-program, but then I'd have to consolidate entries manually)After significative research (including many similar questions over Stack Exchange), I still haven't found such a monitor. Maybe this is not possible under Linux. Or maybe this is bit of an unusual need. | Measure network consumption per program and month | linux;networking;bandwidth | null |
_unix.350996 | I set up a simple asterisk server on Fedora. My goal is to make two android phones call each other. Actually they are connected via wifi, and I use Zoiper and Jitsi softphone. Fedora is on a virtualbox machine with bridged network mode (ip: 192.168.1.13)sip.conf:[general]bindaddr=0.0.0.0svrlookup=noautokill=yes[myTemplate](!)type=friendhost=dynamiccontext=myLocalPhonesdisallow=allallow=ulawallow=alawallow=gsm[5001](myTemplate)secret=5001mailbox=5001@default[5002](myTemplate)[email protected]:[myLocalPhones]exten => 222,1,Dial(SIP/5001)exten => 123,1,Answer()exten => 123,2,Playback(hello-world)exten => 123,3,Hangup()I can make a call and answer but there is no voice ! neither the hello-world message! | Asterisk: Can call but can't hear voice | fedora;asterisk;voip | null |
_unix.227697 | I'm in the process of setting up a Hadoop cluster and have so farbeen unable to find a good answer for how to configure CPU powerin the BIOS for Linux.My BIOS give a variety of options with regards to CPU power,the main categories are:DisableEnergy EfficientCustomMaximum Performance There are a slew of other settings (Long duration power limit, short duration, etc..) But lets just talk about the broad strokes and best practices.My impulse is to either disable power management entirely or to enable maximum performance - but of course the downside to that is paying for the watts when I'm not using them. Is Linux CPU power management good enough at this point that an earth and datacenter cooling/power friendly BIOS will still let me get the maximum potential out of my Hadoop cluster?Or should I just play it old-school and disable power management? | Optimal BIOS CPU power config for performant Hadoop? | linux;cpu;bios;hadoop | I can't give an authoritative answer for this one (nor one specifically regarding Hadoop), but I'll give you what I consider to be best practice.This question seems more hardware-directed than Hadoop-specific, I have to say.Frankly, if you are going to have fluctuating load, I would disable BIOS power management, and set it to always stay at stock clock, relying on Linux's cpupower CPU frequency scaling in order to reduce power usage (but only not under load). I would then set the cpupower governor to 'ondemand'.This means that it scales up to regular stock clock when required, but lowers the CPU frequency (and therefore power consumption) when not under load.This is because cpupower, being a kernel-integrated software utility, can make better decisions than the BIOS scaling, as it has access to more information streams. The firmware can only read what is going on at the hardware level, whereas cpupower can poll information from said firmware in addition to reading info from the kernel. |
_webmaster.77858 | Should I block dnsmadeeasy.com due to bad bots/sites using their dns service?Would this be a scenario of throwing the baby out with the bathwater? | Block dnsmadeeasy.com due to bad bots? | htaccess | null |
_softwareengineering.304016 | Why would I ever throw exceptions in code? (except for one specific scenario where I am developing a class library which the consumers of it, will not want / be able to change).To be more specific, is there any reason to do this:class EmailSender{ public void SendEmail(string recipient, string subject, string content) { if (string.IsNullOrEmpty(recipient)) { throw new ArgumentNullException(exception text...); } // Send the email }}Instead of this:class EmailSender{ public bool SendEmail(string recipient, string subject, string content) { bool result = false; try { if (string.IsNullOrEmpty(recipient)) { logger.Error(Error text...); } else { // Send the email result = true; } } catch (Exception ex) { logger.Error(ex); } return result; }}Take into account that this class is in-house code and not something I am going to ship as a DLL or an open source project. | Why ever use exception throw (in C#) except for Class Library development? | coding style;code quality;exceptions;clean code;error handling | null |
_webapps.12537 | I setup Feedburner on my Wordpress blogs. I want to retrieve the email addresses of my subscribers. But I couldn't find a way to get these addresses from Feedburner. I made some googling before asking. There are some tutorials to retrieve email addresses but on my Feedburner account there is no Manage your list of email subscribers link.Should I better use Mailpress instead of Feedburner? | How to Get Email Addresses of Feedburner Subscribers | feedburner | null |
_datascience.17996 | I've improved my text classification to topic module, from simple word2vec to piped tfidf and OneVsRestClassifier (using sklearn). It does improve the classification but with word2vec I was able to calculate the match percentage for each topic and with OneVsRestClassifier i get a match or no match to a specific topic. Is there a way to see with OneVsRestClassifier what was the percentage of the classification?P.S.I am not talking about evaluating the performance of the training but the actual real time matching percentage. | How to detect the match precision of OneVsRestClassifier | classification;nlp;scikit learn;multiclass classification | Yes, of course. Assuming that you have used sklearn's OneVsRestClassifier and so you have a decision function for example a Support Vector Classifier with say linear kernel. Use set_params to change probability key to True, default is False. Use this in the OneVsRestClassifier classifier and then go with the inbuilt function predict_proba likefrom sklearn.multiclass import OneVsRestClassifierfrom sklearn.svm import SVCmod = OneVsRestClassifier(SVC(kernel='linear').set_params(probability=True)).fit(samples,classes)print mod.predict_proba(np.array([your_sample_vector]).reshape(1,-1))Edit:You can use your old LinearSVC with decision_function to find the distance from the hyperplane and convert them to probabilities likemod = OneVsRestClassifier(LinearSVC()).fit(sample,clas)proba = (1./(1.+np.exp(-mod.decision_function(np.array(your_test_array).reshape(1,-1)))))proba /= proba.sum(axis=1).reshape((proba.shape[0], -1))\print probaNow you don't need tuning the parameters, I guess. :) |
_webapps.94710 | So I was checking one of my Facebook page's specific post insights. Although Likes/Comments on post and Likes/Comments on shares are pretty explicit, I'm wondering what exactly Shares on shares means when the post hasn't been shared yet (Shares on post is 0)?Here's a screenshot:And here's a screenshot of the whole post:And the same happened with a post from 20 minutes ago:How can a post be shared from a share when no one has shared the said post? | How can a Facebook page's post be shared from a share when no one has shared the said post? | facebook;facebook pages;facebook insights | null |
_cs.71053 | Say, I have the situation where I am looking into all the possibilities to obtain a value of e.g. 20 (exactly) by taking all possible combinations of sums using values from 1 to 5. While doing this, I want to minimize my penalty P. There is no limit to the amount of values I use (I could do 4x5, 20x1 and any other possibility).The penalty is not based on the amount of values I use, but instead on the intermediate values of the summation.In this example, let's assume the penalties are as follows:1 * k for 0 <= S < 22 * k for 2 <= S < 63 * k for 6 <= S < 114 * k for 11 <= S < 20where k is the current value being added to my intermediate sum S.So if I consider e.g. [1,2,3,4,5,5] (in that particular order), my total penalty would be P=1*1+1*2+2*3+3*4+3*5+4*5=56.However, the penalty changes if I permute my array to e.g. [1,5,4,5,2,3] (P=53) or [2,4,5,1,3,5] (P=61).In this simple example, we have 192 different sets of values that can together add up to 20. The number of possible permutations per set (taking into account non-unique values) varies between 1 (in case of 20x1, 10x2 etc) and 15840 (7x1, 3x2, 1x3, 1x4). The naive approach would be to just loop through all sets and their permutations, which is doable for the given example.However, my actual problem has about 2000 possible sets of numbers and the number of permutations goes all the way up to ~1E+8. It is no longer fun to use a naive approach in this case.I do know that I can greatly reduce my number of permutations, as the order of my values does not matter if I stay within the same range (when I'm at S=11, it no longer matters in what way I add the final 9).My question is how I can properly implement this knowledge to improve my naive algorithm such that it disregards those permutations a priori (first generating all permutations and then removing is not really an option, as even 8-bit unsigned integers will generate 15 GB arrays for all permutations). Furthermore, I was wondering whether there are any additional improvements that could be made here. | Optimization problem where penalty is sensitive to permutation | algorithms;optimization;permutations | I will outline two different solution methods. Either one will work -- pick whichever one you find easiest to understand and implement.Dynamic programmingThis can be solved using dynamic programming. We'll fill in a one-dimensional table, so that $T[s]$ stores the penalty of the best (lowest-penalty) way to obtain a sum of exactly $s$. Once we've filled in all of the entries, $T[20]$ will tell you the lowest penalty achievable for any combination that sums to 20.So how do we fill in the table entries? We can fill them in recursively:$$T[s] = \min(T[s-1]+p(s-1,1), T[s-2]+p(s-2,2), \dots, T[s-5]+p(s-5,5))$$where $p(s,k)$ is the penalty for adding the number $k$ when the intermediate sum is $s$. In the question, you tell us that $p(s,k) = k$ for $0 \le s < 2$, $p(s,k) = 2k$ for $2 \le s < 6$, etc.Also, we have the base cases $T[0] = 0$. As a convention, we'll agree that $T[-1]=T[-2]=T[-3]=T[-4]=\infty$. Then you can fill in $T[1],T[2],\dots,T[20]$ in that order, using the recursive formula above.This will give you the penalty of the best way to achieve the sum $20$. If you also want to output the specific combination that achieves that penalty, you can keep track of that with a small modification. Basically, each time you fill in a $T[i]$ entry with some penalty value, on the side keep track of the combination that led to that penalty value.Graph searchConstruct a weighted directed graph, with vertices 0, 1, 2, .., 20. Each vertex corresponds to a possible intermediate sum. From each vertex (intermediate sum) $s$, add five outgoing edges, corresponding to the five possibilities for the number you add. The length of the edge from $s$ to $s+i$ (for $i=1,2,\dots,5$) is the penalty for adding $i$ to an intermediate sum $s$, according to the rules described in your question.Now find the shortest path from vertex 0 to vertex 20 in this graph. That path will correspond to a combination of values that sum to 20, and the total length of that path will correspond to the penalty of that path. The shortest path will correspond to the combination with lowest penalty. You can use any standard algorithm for computing shortest paths in a graph, such as Dijkstra's algorithm. |
_cogsci.16434 | (This question is in relation to this question here)How does fear paralysis occur? What is the mechanism that makes this happen in brain? | How does fear paralysis occur? | fear | Taken from hereThe Fear Paralysis Reflex begins to function very early after conception and should normally be integrated before birth. It can be seen in the womb as movement of the head, neck and body in response to threat. It is sometimes classified as a withdrawal reflex rather than a primitive reflex. If this reflex is retained after birth, it can be characterised by withdrawal, reticence at being involved in anything new, fear of different circumstances, and is often described as the scaredy cat child who bears the brunt of teasing by normally adventurous children.This behaviour appears to be due to the reflexs involvement with the parasympathetic nervous system. Most of us are familiar with the fight or flight adrenalin rush of the sympathetic nervous system, however the FPR taps into the opposing system urging the body to eat and stay. The parasympathetic nervous system is intimately involved with the vagus nerve. This nerve comes directly from the brain to aid the organs. It bypasses the spinal cord, so in the case of spinal injury we are still able to digest our food. The vagus nerve may be mechanically trapped in the skull, chest, abdomen or neck. Release of this nerve entrapment corrects one physical factor that contributes to the retention of the FPR. |
_reverseengineering.6377 | In an application I'm analyzing, there's a global variable whose purpose/role in the program is known to me. I'd like to rename it, but for some reason I cannot.The assembly code:.text:00537E90 mov edx, ds:1C968D8h.text:00537E96 mov [eax], edx.text:00537E98 mov ds:1C968D8h, eaxIf I position the cursor on the address (ds:1C968D8h) and try to jump (using Enter), IDA will complain Command JumpEnter failed. Attempting to rename it with the N hotkey will cause IDA to place a label at that address rather than rename the variable as intended.While I'm doing this for educational purposes, this is a proprietary application, so I don't have the source code.I've checked Chris Eagle's The IDA Pro Book, but there seems to be nothing on the subject in there.Help is greatly appreciated. | IDA - cannot rename or jump to a global variable | ida | One thing that I've failed to notice turned out to be crucial: this file wasn't generated by my copy of IDA, it was given to me by a friend as a helping resource. I've simply disassembled the very same exe with my IDA and the troublesome address is now correct: |
_cstheory.20207 | I am a software engineer and I need a bit of clarification. The practical performance of algorithms is usually compared against models where arithmetic and dereferencing are instantaneous, such as RAM. The assumption is that the primary storage already has the capacity to store and address the input, so it should be feasible to expect rapid performance on the words that encode the address space. This is reasonable, yet I think that the model may give equal footing to algorithms that perform inherently different amounts of work - such as returning a constant and mapping numbers (the latter is obviously more demanding in a non-Neumann architecture). Similarly, on a tangent topic, the development of parallel algorithms assumes infinitely parallel hardware, which does not take into account the spatial factors involved in a circuit design.Furthermore, while contemporary machines provide integer-based addressing and while I see this as an arbitrary beneficial phenomenon, I don't think that there is fundamental need for our addresses to be effective quantities, with the corresponding constant-time arithmetic operations on them. So this may also influence the analysis of algorithms towards disbalance.In view of the above, I have the following questions:Are there operations, to our understanding, that we expect to be implemented efficiently in our fully featured (i.e. for practical evaluation) models of computation and why - arithmetic, or any polylogarithmic complexity operation (assuming the standard encodings), or any function that maps words, even finding the n-th prime number if it fits in a word. Why we choose particular operations, and could we choose others? Can we use a different encoding, not based on positional numerals as the medium of computation and gain some comparative benefits throughout?Is it conceivable that data structures and algorithms may be improved asymptotically if they were implemented directly as VLSI circuit designs? For example, is it theoretically conceivable that sorting and dynamic indexing (single-, multi-dimensional) of sets with variably-sized lexicographically ordered keys can be implemented more efficiently if we don't use RAM as our point of reference? Is there counterproof to that, proof, or conjecture?If improvements appear to be possible under 2, how the relationship between the model and the problem enable such improvements? For example, given a universe of keys for an indexing problem, how can we decide if a given model of computation (restricted by faithful correspondence to the VLSI design economics) is optimal, or a better model of computation exists (again feasible and faithful to VLSI economics, but different operations and implementation)?ThanksPS:A similar issue with lock-free algorithms in my opinion is that they assume the underlying architecture provides atomic operations that scale perfectly with the number of cores and cpus. The interconnects and coherency protocols can not scale perfectly, so essentially the algorithms remain blocking. The algorithmic design optimally solves the problem with the resources provided by the model, but this does not answer which is the most optimal practically feasible hardware architecture for solving the original problem, and whether from this point of view the algorithm is actually optimal. | Fundamental assumptions in complexity analysis | ds.algorithms;circuit complexity;time complexity | null |
_codereview.38413 | I wonder if my script is all right. Please review my code:<!DOCTYPE html><html><head><meta charset=UTF-8><title>Menu</title><style>ul {list-style-type:none; margin:0; padding:0;}li {display:inline;}a.active {background:red;}</style></head><body><ul><li><a href=http://www.example.com/home>Home</a></li><li><a href=http://www.example.com/news>News</a></li><li><a href=http://www.example.com/contact>Contact</a></li><li><a href=http://www.example.com/about>About</a></li></ul><script>for (var i = 0; i < document.links.length; i++) { if (document.links[i].href == document.URL) { document.links[i].className = 'active'; }}</script></body></html>It should highlight the current page link in the navigation bar. | Highlight the active link in a navigation menu | javascript;html;css | querySelectorAllHere's another approach, if you don't mind older browsers. You can use querySelectorAll instead of document.links. That way, you end up with a smaller result set rather than all links, and save you CPU cycles for running the loop.In this case, we get only those links that have the same href value as the current document url:var links = document.querySelectorAll('a[href='+document.URL+']');However, note the browser compatibility and there are quirks across implementations.Not all links need activeNow if you think about it, not all links with the document.URL need to have active. Say you have active set the font to 2em. If you get all links that point to the same page, they'd be 2em in size, regardless of where they are in the page!Most likely, you only need it for the primary navigation. Consider adding a class to further refine the result set.<ul class=navigation> <li><a href=http://www.example.com/home>Home</a></li> <li><a href=http://www.example.com/news>News</a></li> <li><a href=http://www.example.com/contact>Contact</a></li> <li><a href=http://www.example.com/about>About</a></li></ul>// Getting only the links that are in .navigationvar links = document.querySelectorAll('.navigation a[href='+document.URL+']');// More specific CSS.navigation a.active {background:red;}classNameNow you have to note that setting className replaces it with the value, like this example. If the links you have happen to have existing classes (and styles that come with them), your script will unintentionally remove their styles due to the replaced className.What you can do is get the existing className value, split them by spaces (multiple class names are separated by spaces), append your class name, join them back and then change the value, like I did here:var element = document.getElementById('change');var classNames = element.className.split(' ');classNames.push('huge');element.className = classNames.join(' '); |
_vi.10708 | I installed tmux in iTerm 2.(Build 3.0.13) When I execute vim in tmux, syntax highlighting looks like this.But outside tmux, syntax highlighting looks fine.My $TERM inside and outside tmux is xterm-256color. I also added set -g default-terminal screen-256colorin .tmux.conf and added thisset t_Co=256set t_AB=mset t_AF=mif &term =~ '256color' set t_ut=endifin .vimrc.I also tried tmux -2 command and read these questions.lose vim colorscheme in tmux modeIncorrect colors with vim in iTerm2 using SolarizedIs this a problem of tmux, vim, or my configuration?EDIT:My .vimrc in GitHub Gisthttps://gist.github.com/sohnryang/3c63397f332f2e30c7d7b2a83c3c9f52 | No syntax highlighting in tmux | syntax highlighting;tmux | Well, I solved the problem by myself.as @Carpetsmoker commented, I started to suspect that my .vimrc is a problem. I read this question and started vim with this command inside tmux.vim -u NONE -U NONE -N ~/.vimrcAfter starting vim with command above, I ran this command inside vim.:syn on:colorscheme solarized8_darkThese highlighted my .vimrc file. So, I started to debug my .vimrc.Long story short, set termguicolors was the problem. If I ran vim with set termguicolors commented in .vimrc, I could see corrected syntax highlighting in tmux. |
_unix.35236 | I am very new at bash, so forgive me for the novice question.Here is my curl call:curl -d 'username=cdaniels&wallclock=391324502' 'https://www-dev.***.***.edu/clusterusage/rest/update.html';which pulls from a file ~/qacct.monthly with the formatTotal : OWNER WALLCLOCK UTIME STIME CPU MEMORY IO IOWTotal : ==========================================================================================================================Total : cdaniels 391324502 0.195 0.066 0.261 0.000 0.007 0.000Total : jlinger 1 0.039 0.056 0.095 0.000 0.000 0.000Total : lbsome 18707336 18675574.761 21433.535 18697008.296 10604793.658 5527.986 0.000The example only pulls one of the users, but I want it to parse through the information and pull all the usernames and wallclock information from all the users on the cluster for that month.I'm wanting to put this into a script so that it executes every month (obviously through a cron job) | Script using CURL to add information to site every month | bash;curl | Something like the following should work:#!/bin/bashwhile IFS= read -r data; do curl -d ${data} 'https://www-dev.***.***.edu/clusterusage/rest/update.html'done < <(awk 'NR>2 { print username=$3&wallclock=$4 }' users) |
_webmaster.15650 | Is it a good idea to filter our own IP addresses from our own websites in Google Analytics?On the one hand, the data is real but on the other are you losing browny points with Google as your getting less visits?Maybe I'm not understanding the filtering!? | Filtering your own IP's in Google Analytics, good or bad idea? | google analytics | Google does not use traffic to rank web pages.But you should still filter your IP address out of Google Analtyics if your goal is to have accurate statistics as to how many users you have and how they are using your site. You're only fooling yourself if you count your own visits in your site statistics. |
_softwareengineering.199587 | I'm a junior in college majoring in Computer Science. Apart from writing lots of code, I want to start reading source code written by others to improve my coding skills and learn better/different ways of doing stuff. I was thinking I should start reading some of the key parts of the code in C++ compilers. I think this would help me do two things:Learn elegant coding practices because compilers are hard and the code represents solutions to this hard problem.This would also help me learn about how my most used language is compiled, the details, how each error is generated, how code is parsed, and become really good with the specifications of the language.Do you think this is a good idea? | Is it a good idea to read compiler source code? | c++;compiler | null |
_codereview.13545 | Any suggestions how I could simplify this LINQ query?from type in assembly.GetTypes()where type.IsPublic && !type.IsSealed && type.IsClasswhere (from method in type.GetMethods() from typeEvent in type.GetEvents() where method.Name.EndsWith(Async) where typeEvent.Name.EndsWith(Completed) let operationName = method.Name.Substring(0, method.Name.Length - Async.Length) where typeEvent.Name == operationName + Completed select new { method, typeEvent }).Count() > 0select type;assembly is of type System.Reflection.Assembly.If you need more information, just ask. | Simplify a complex LINQ query | c#;linq | You can do a join between the methods and events :from type in assembly.GetTypes()where type.IsPublic && !type.IsSealed && type.IsClasswhere (from method in type.GetMethods() join typeEvent in type.GetEvents() on method.Name.Replace(Async, Completed) equals typeEvent.Name select new { method, typeEvent }).Any()select type; |
_softwareengineering.170668 | Have you had any experience in which a non-IT person works with a programmer during the coding process?It's like pair programming, but one person is a non-IT person that knows a lot about the business, maybe a process engineer with math background who knows how things are calculated and can understand non-idiomatic, procedural code.I've found that some procedural, domain-specific languages like PL/SQL are quite understandable by non-IT engineers. These persons end up being co-authors of the code and guarantee the correctness of formulas, factors, etc.I've found this kind of pair programming quite productive, this kind of engineering-type users feel they are also owners and authors of the code and help minimize misunderstandings in the communication process. They even help design test cases.Is this practice common?Does it have a name? Have you had any similar experiences? | Pair programming business logic with a non-IT person | teamwork;requirements;client relations;business logic;pair programming | Though you are describing this as a shared coding session (I can't call it pair programming, as only one person is driving - in pair programming, both parties take the keyboard and write code), I would call it gathering acceptance criteria.That is, you are validating business rules (correct calculations and processes) with the business user (though one with a very technical role, an engineer).In this case, it translates immediately to written code (SQL), but for many other activities is will not, though there are automated acceptance test tooling for different languages and platforms (I am specifically thinking about the gherkin language and related tooling).This practice is not as common as it should be, but is gaining more and more followers and those who follow it (getting acceptance criteria in a form that can be executed) find it invaluable as both a tool to communicate with the business and to drive development. |
_codereview.101461 | Given a folder typically containing ~250,000 small (20-100kb) files in HTML format (they open as single-sheet workbooks in Excel) and a list of ~ 1 million filenames, I need to open all the files that match the list and Do Stuff.Overview of Main code Loop: Test 1 Start to Test 1 EndOnce we get to the main file loop, I have a 1-D array arrCompanyNumbers with approx. 1 Million 8-digit company numbers (extracted from a 2-d array arrFilteredAddresses where the company number is only one of about 12 columns). There is a folder with a couple hundred thousand files in it named like this. Prod224_0005_00040751_20131231 Prod224_0005_00040789_20130930 ....... That number in the middle is the company number. The number on the end is the file date.The macro loops through the folder using strFilename = dir. For each file, it extracts the company number and tries to match it against the array. If it does, it calls Check_File(). If it doesn't it goes to the next file and repeats.Overview of Check_File()Each file opens as a one-sheet workbook with a corporate accounts filing in it. I want to find the Cash, Assets and Profits in the last year. I have 3 collections of phrases that correspond to those values e.g. Cash at Bank:. The macro searches the first 200 rows of the first 2 columns for those phrases. Then searches 10 cells across the row and returns the first number it finds.Once it has Cash, Assets and Profits (or failed to find them), it filters them against set criteria. If they pass, it copies the results to a second worksheet in the main workbook (which is eventually just one long list of companies, file dates and cash/assets/profits) and closes the file.Optimisation Parameters:I've already optimised it as far as I think I can e.g. Running speed tests on using vlookup instead of iterative searching. Even after all that, it will typically run for 6-24 hours to filter an entire month of data, and comes dangerously close to running out of memory. I would like it to run an order of magnitude faster and with a noticeable reduction in memory usage. Any suggestions on how to achieve that would be much appreciated.Runtime Tests:Code between Test 1 Start and Test 1 End consumes approximately 60% of the runtime.The Check_File() sub is responsible for the other 40%Main Sub:Sub Check_Companies_House_Files()Application.ScreenUpdating = FalseApplication.EnableEvents = FalseApplication.Calculation = xlCalculationManual'/================================================================================================================'/ Author: Zak Michael Armstrong'/ Email: -'/ Date: 07 August 2015'/'/ Summary:'/ Companies House release all the electronic corporate account filings they receive every month, which we download onto our server'/ This spreadsheet takes a list of companies whose registered headquarters are in certain postcodes (The Filtered Addreses)'/ And searches the accounts for these companies' filings (using their company number)'/ It then opens these files (provided in XML or HTML format), and performs a manual search for Cash, Assets and Profits'/ If the level of cash, assets or profits meet set filtering requirements, it copies the spreadsheet into the main book and/or'/ adds the distilled information to a list of account data.'/'/ Speed test results: With the full filtered list (approx. 1M companies), macro can check 5 Companies House Files / second'/=================================================================================================================Dim wbAccountsData As Workbook '/ The main Workbook, containing a filtered list of companies to search for and the eventual output dataDim wsFilteredAddresses As Worksheet '/ Contains the list of filtered companies with supplementary dataDim wsAccountsData As Worksheet '/ Will contain a list of companies and the cash, assets, profits reported on their filingDim arrFilteredAddresses() As Variant '/ An array to hold all the data in the filtered addresses spreadsheetDim arrCompanyNumbers() As Variant '/ An array to hold all the company numbers (1 column of the filtered addresses data)Dim strRightString As String '/ Used to get the company number out of the filenames for comparison with the arrayDim strLeftString As String '/Dim strCompanyNumber As String '/ Unique identifying number with Companies HouseDim strCompanyName As String '/ Company's Registered NameDim strPostcode As String '/ Postcode of their registered addressDim strFileName As String '/ Filename of the company accountsDim strFolderPath As String '/ folder the accounts are stored inDim strDay As String '/ the day of the filedateDim strMonth As String '/ the month of the filedateDim strYear As String '/ the year of the filedateDim strFileDate As String '/ the full filedateDim lngFinalRow As Long '/ used for determining size of arraysDim lngFinalColumn As Long '/Dim lngCounter As Long '/ used for general countingDim lngCounter2 As Long '/Dim lngYear As Long '/ Designates the year to be scanningDim lngMonth As Long '/ Designates the month to be scanning (each folder contains one month)Dim varHolder1 As Variant '/ General variable holderDim I As Long '/ General purpose numbersDim J As Long '/Dim K As Long '/Dim L As Long '/Dim M As Long '/Dim N As Long '/Dim lngFolderLength As Long '/ Counts the number of files in a folder to be scannedDim lngTriggerPoint As Long '/ Used to trigger debug.print operations at set progress intervals'/================================================================================================================='/ Initial Setup'/================================================================================================================= Debug.Print Start: & Now'/ Remove any residual dataApplication.DisplayAlerts = FalseL = Worksheets.Count Do While L > 2 Sheets(L).Delete L = L - 1 LoopApplication.DisplayAlerts = TrueSet wbAccountsData = ActiveWorkbookSet wsFilteredAddresses = Sheets(Filtered Addresses)Set wsAccountsData = Sheets(Accounts Data) wsFilteredAddresses.Activate'/ Create arrayslngFinalRow = Cells(1048576, 1).End(xlUp).RowIf lngFinalRow = 1 Then lngFinalRow = 1048576lngFinalColumn = Cells(1, 10000).End(xlToLeft).Column Debug.Print Start array prep: & Now ReDim arrFilteredAddresses(1 To lngFinalRow, 1 To lngFinalColumn) '/ Done iteratively because excel throws an Out of memory if I try to pass the whole range to the array in one go. Approx. 2 minutes for 1Million length list For L = 1 To lngFinalRow For M = 1 To lngFinalColumn arrFilteredAddresses(L, M) = wsFilteredAddresses.Cells(L, M).Text Next M Next L ReDim arrCompanyNumbers(1 To lngFinalRow) For L = 1 To lngFinalRow arrCompanyNumbers(L) = Right(00000000 & arrFilteredAddresses(L, 2), 8) '/ company numbers in the filenames are always 8 digits long, with 0's filling up any extra digits Next L'/ Currently have data from March 2014 to June 2015'/ Currently starts at the most recent and counts backwardlngYear = 2015lngMonth = 6'/================================================================================================================='/ Begin Main loop'/=================================================================================================================Do While lngMonth >= 1 '/ approx. 1M files, should (hopefully) finish over a weekend lngTriggerPoint = 5000 '/============================================================= '/ Begin Month Loop '/============================================================= Debug.Print lngYear & - & MonthName(lngMonth) & - & Start file checks: & Now strFolderPath = S:\Investments\Data\Companies House\Monthly Companies House Downloads\Accounts_Monthly_Data- & MonthName(lngMonth) & lngYear & \ strFileName = Dir(strFolderPath) lngFolderLength = 0 Do While strFileName <> lngFolderLength = lngFolderLength + 1 strFileName = Dir Loop '/=============================== '/ Test 1 start (not including call check_file) '/=============================== strFileName = Dir(strFolderPath) lngCounter = 0 Do While strFileName <> lngCounter = lngCounter + 1 strRightString = Right(strFileName, 22) strLeftString = Left(strRightString, 8) strCompanyNumber = strLeftString K = 1 '/============================================================= '/ Search arrCompanyNumbers for the current file's company '/============================================================= Do While K <= UBound(arrCompanyNumbers) If strCompanyNumber = arrCompanyNumbers(K) _ Then If lngCounter > lngTriggerPoint _ Then Debug.Print (lngCounter & - & lngFolderLength & - & Now & - & MonthName(lngMonth) & - & lngYear) lngTriggerPoint = lngTriggerPoint + 5000 End If strCompanyName = arrFilteredAddresses(K, 1) strPostcode = arrFilteredAddresses(K, 10) strDay = Left(Right(strFileName, 7), 2) strMonth = Left(Right(strFileName, 9), 2) strYear = Left(Right(strFileName, 13), 4) strFileDate = strDay & . & strMonth & . & strYear '/wsFilteredAddresses.Activate '/ originally introduced to save time by deleting companies from the list as they were found '/wsFilteredAddresses.Rows(K).Delete '/ taken out as not huge time saving, and means only most recent filing is found '/ The subroutine opens the file in question and tries to filter the company against set financial values Call Check_file(strCompanyNumber, strCompanyName, strPostcode, strFileName, strFolderPath, strFileDate, _ wbAccountsData, wsAccountsData) DoEvents K = UBound(arrCompanyNumbers) + 1 End If K = K + 1 Loop strFileName = Dir Loop '/=================================== '/Test 1 End '/=================================== '/============================================================= '/ End Month Loop '/============================================================= Debug.Print lngYear & - & MonthName(lngMonth) & - & Finish: & Now Debug.Print Files: & lngCounter Debug.Print lngMonth = lngMonth - 1 If lngMonth <= 0 _ Then lngMonth = lngMonth + 12 lngYear = lngYear - 1 End If If lngYear = 2014 And lngMonth = 3 Then lngYear = 2000Loop'/================================================================================================================='/ End Main loop'/=================================================================================================================Debug.Print Macro Finish: & NowwsAccountsData.ActivateApplication.Calculation = xlCalculationAutomaticApplication.EnableEvents = TrueApplication.ScreenUpdating = TrueEnd SubCheck_File()Private Sub Check_file(ByVal strCompanyNumber As String, ByVal strCompanyName As String, ByVal strPostcode As String, ByVal strFileName As String, ByVal strFolderPath As String, ByVal strFileDate As String, _ ByRef wbAccountsData As Workbook, ByRef wsAccountsData As Worksheet)'/================================================================================================================'/ Author: Zak Michael Armstrong'/ Email: -'/'/ Summary:'/ Opens the file, searches the first and second columns for phrases that correspond to cash, assets and profit'/ Searches across the row from those terms until it finds a number'/ It assumes that number is the value it's after'/ If the data meet set filtering requirements, copies the data and/or the worksheet into the main AccountsData workbook'/=================================================================================================================Dim wbTempFile As Workbook '/ This workbook, containing the accounts filingDim wsTempFile As Worksheet '/ This worksheet (always just 1), containing the accounts filingDim arrFirstColumn() As Variant '/ The first column of data for text searchDim arrSecondColumn() As Variant '/ The second column of data for text searchDim varCash As Variant '/ pre-formatted cash valueDim curCash As Currency '/ currency-formatted cash valueDim varAssets As Variant '/ pre-formatted assets valueDim curAssets As Currency '/ currency-formatted assets valueDim varProfits As Variant '/ pre-formatted profits valueDim curProfits As Currency '/ currency-formatted profits valueDim colCashPhrases As Collection '/ contains all the phrases I've found that correspond to comapnies' current cashDim colAssetPhrases As Collection '/ contains all the phrases I've found that correspond to comapnies' current assetsDim colProfitPhrases As Collection '/ contains all the phrases I've found that correspond to comapnies' current profitsDim lngCurrentRow As Long '/ General indicatorsDim lngCurrentColumn As Long '/Dim lngFinalRow As Long '/Dim lngFinalColumn As Long '/Dim strPhraseHolder As String '/ will hold a string from a collection for text matchingDim varHolder1 As Variant '/ General variable holdersDim varHolder2 As Variant '/Dim varHolder3 As Variant '/Dim bCashFound As Boolean '/ Checks to see if the program found the valuesDim bAssetsFound As Boolean '/Dim bProfitsFound As Boolean '/Dim bCashFilter As Boolean '/ Is the value going to be used for filteringDim bAssetsFilter As Boolean '/Dim bProfitsFilter As Boolean '/Dim curCashFilterValue As Currency '/ the values to set the filter atDim curAssetsFilterValue As Currency '/Dim curProfitsFilterValue As Currency '/Dim strCashFilterDirection As String '/ whether to filter >= or <=Dim strAssetsFilterDirection As String '/Dim strProfitsFilterDirection As String '/Dim bPassedCashFilter As Boolean '/ Handling the (up to) 3 filters separately so these are to check thatDim bPassedAssetsFilter As Boolean '/ each filter case has been handled correctlyDim bPassedProfitsFilter As Boolean '/Dim I As Long '/ General countersDim J As Long '/Dim K As Long '/Dim L As Long '/Dim M As Long '/Dim N As Long '/'/================================================================================================================='/ Initialise variables, set filter parameters'/=================================================================================================================Workbooks.Open (strFolderPath & strFileName)Set wbTempFile = Workbooks(strFileName)Set wsTempFile = wbTempFile.Sheets(1)bCashFound = FalsebAssetsFound = FalsebProfitsFound = False'/ Column 1 datalngFinalRow = Cells(1048576, 1).End(xlUp).RowReDim Preserve arrFirstColumn(1 To lngFinalRow)For I = 1 To lngFinalRow arrFirstColumn(I) = UCase(Left(Cells(I, 1).Text, 40)) '/ Left(40) is in case of extremely long cell textNext I'/ Column 2 datalngFinalRow = Cells(1048576, 2).End(xlUp).RowReDim Preserve arrSecondColumn(1 To lngFinalRow)For I = 1 To lngFinalRow arrSecondColumn(I) = UCase(Left(Cells(I, 2).Text, 40)) '/ Left(40) is in case of extremely long cell textNext I' Fill CollectionsSet colCashPhrases = New CollectioncolCashPhrases.Add (Cash at bank and in hand)colCashPhrases.Add (Cash at bank)colCashPhrases.Add (Cash in hand)colCashPhrases.Add (Cash at bank and in hand:)colCashPhrases.Add (Cash at bank:)colCashPhrases.Add (Cash in hand:)Set colAssetPhrases = New CollectioncolAssetPhrases.Add (Net Current Assets)colAssetPhrases.Add (Total net assets (liabilities))colAssetPhrases.Add (Net Current Assets (liabilities))colAssetPhrases.Add (Total Assets Less current liabilities)colAssetPhrases.Add (Net Current assets/(liabilities))colAssetPhrases.Add (Net Current Assets:)colAssetPhrases.Add (Total net assets (liabilities):)colAssetPhrases.Add (Net Current Assets (liabilities):)colAssetPhrases.Add (Total Assets Less current liabilities:)colAssetPhrases.Add (Net Current assets/(liabilities):)Set colProfitPhrases = New CollectioncolProfitPhrases.Add (Profit and loss account)colProfitPhrases.Add (Profit and loss account:)bCashFilter = FalsebAssetsFilter = FalsebProfitsFilter = TruecurCashFilterValue = 0curAssetsFilterValue = 0curProfitsFilterValue = 250000strCashFilterDirection = >=strAssetsFilterDirection = >=strProfitsFilterDirection = >='/================================================================================================================='/ Search File for Cash, Assets and Profits'/=================================================================================================================On Error Resume Next'/ Search for Cash ValueI = 1 Do While I <= colCashPhrases.Count strPhraseHolder = UCase(colCashPhrases(I)) varHolder1 = Application.Match(strPhraseHolder, arrFirstColumn, 0) varHolder2 = UCase(Application.Index(arrFirstColumn, varHolder1)) If IsError(varHolder1) _ Then varHolder1 = Application.Match(strPhraseHolder, arrSecondColumn, 0) varHolder2 = UCase(Application.Index(arrSecondColumn, varHolder1)) End If '/ varholder1 holds the index, varholder2 holds the text value (if found) If CStr(varHolder2) = strPhraseHolder _ Then lngCurrentRow = varHolder1 lngCurrentColumn = 1 lngFinalColumn = Cells(lngCurrentRow, 10000).End(xlToLeft).Column Do While lngCurrentColumn <= lngFinalColumn lngCurrentColumn = lngCurrentColumn + 1 varCash = Cells(lngCurrentRow, lngCurrentColumn).Value If IsNumeric(varCash) And CLng(varCash) <> 0 _ Then lngCurrentColumn = lngFinalColumn + 1 curCash = CCur(varCash) bCashFound = True End If Loop End If If bCashFound = False Then I = I + 1 If bCashFound = True Then I = colCashPhrases.Count + 1 Loop'/ Search for Assets valueI = 1 Do While I <= colAssetPhrases.Count strPhraseHolder = UCase(colAssetPhrases(I)) varHolder1 = Application.Match(strPhraseHolder, arrFirstColumn, 0) varHolder2 = UCase(Application.Index(arrFirstColumn, varHolder1)) If IsError(varHolder1) _ Then varHolder1 = Application.Match(strPhraseHolder, arrSecondColumn, 0) varHolder2 = UCase(Application.Index(arrSecondColumn, varHolder1)) End If '/ varholder1 holds the index, varholder2 holds the text value (if found) If CStr(varHolder2) = strPhraseHolder _ Then lngCurrentRow = varHolder1 lngCurrentColumn = 1 lngFinalColumn = Cells(lngCurrentRow, 10000).End(xlToLeft).Column Do While lngCurrentColumn <= lngFinalColumn lngCurrentColumn = lngCurrentColumn + 1 varAssets = Cells(lngCurrentRow, lngCurrentColumn).Value If IsNumeric(varAssets) And CLng(varAssets) <> 0 _ Then lngCurrentColumn = lngFinalColumn + 1 curAssets = CCur(varAssets) bAssetsFound = True End If Loop End If If bAssetsFound = False Then I = I + 1 If bAssetsFound = True Then I = colAssetPhrases.Count + 1 Loop'/ Search for profits valueI = 1 Do While I <= colProfitPhrases.Count strPhraseHolder = UCase(colProfitPhrases(I)) varHolder1 = Application.Match(strPhraseHolder, arrFirstColumn, 0) varHolder2 = UCase(Application.Index(arrFirstColumn, varHolder1)) If IsError(varHolder1) _ Then varHolder1 = Application.Match(strPhraseHolder, arrSecondColumn, 0) varHolder2 = UCase(Application.Index(arrSecondColumn, varHolder1)) End If '/ varholder1 holds the index, varholder2 holds the text value (if found) If CStr(varHolder2) = strPhraseHolder _ Then lngCurrentRow = varHolder1 lngCurrentColumn = 1 lngFinalColumn = Cells(lngCurrentRow, 10000).End(xlToLeft).Column Do While lngCurrentColumn <= lngFinalColumn lngCurrentColumn = lngCurrentColumn + 1 varProfits = Cells(lngCurrentRow, lngCurrentColumn).Value If IsNumeric(varProfits) And CLng(varProfits) <> 0 _ Then lngCurrentColumn = lngFinalColumn + 1 curProfits = CCur(varProfits) bProfitsFound = True End If Loop End If If bProfitsFound = False Then I = I + 1 If bProfitsFound = True Then I = colProfitPhrases.Count + 1 Loop On Error GoTo 0'/================================================================================================================='/ Determine filter outcome'/=================================================================================================================bPassedCashFilter = FalsebPassedAssetsFilter = FalsebPassedProfitsFilter = False'/ Filter CashIf bCashFilter = True _ Then Select Case strCashFilterDirection Case Is = >= If curCash >= curCashFilterValue Then bPassedCashFilter = True Else bPassedCashFilter = False Case Is = <= If curCash <= curCashFilterValue Then bPassedCashFilter = True Else bPassedCashFilter = False Case Else MsgBox (Macro encountered an unexpected error whilst filtering file financial data) Stop End Select Else bPassedCashFilter = TrueEnd If'/ Filter AssetsIf bAssetsFilter = True _ Then Select Case strAssetsFilterDirection Case Is = >= If curAssets >= curAssetsFilterValue Then bPassedAssetsFilter = True Else bPassedAssetsFilter = False Case Is = <= If curAssets <= curAssetsFilterValue Then bPassedAssetsFilter = True Else bPassedAssetsFilter = False Case Else MsgBox (Macro encountered an unexpected error whilst filtering file financial data) Stop End Select Else bPassedAssetsFilter = TrueEnd If'/ Filter ProfitsIf bProfitsFilter = True _ Then Select Case strProfitsFilterDirection Case Is = >= If curProfits >= curProfitsFilterValue Then bPassedProfitsFilter = True Else bPassedProfitsFilter = False Case Is = <= If curProfits <= curProfitsFilterValue Then bPassedProfitsFilter = True Else bPassedProfitsFilter = False Case Else MsgBox (Macro encountered an unexpected error whilst filtering file financial data) Stop End Select Else bPassedProfitsFilter = TrueEnd If'/ The filter might return true against a default value of 0 if real number not found, so fail if real number not foundIf bCashFound = False And bCashFilter = True Then bPassedCashFilter = FalseIf bAssetsFound = False And bAssetsFilter = True Then bPassedAssetsFilter = FalseIf bProfitsFound = False And bProfitsFilter = True Then bPassedProfitsFilter = False'/ if passed all 3 conditions, then print and/or copy to main workbookIf bPassedCashFilter = True And bPassedAssetsFilter = True And bPassedProfitsFilter = True _ Then wbAccountsData.Activate wsAccountsData.Activate lngFinalRow = Cells(1048576, 2).End(xlUp).Row lngCurrentRow = lngFinalRow + 1 Cells(lngCurrentRow, 2) = strCompanyNumber Cells(lngCurrentRow, 3) = strCompanyName Cells(lngCurrentRow, 4) = strPostcode Cells(lngCurrentRow, 5) = curCash Cells(lngCurrentRow, 6) = curAssets Cells(lngCurrentRow, 7) = curProfits Cells(lngCurrentRow, 8) = strFileDate'' '/ copies worksheet to main workbook'''' wbTempFile.Activate'' wsTempFile.Copy After:=wbAccountsData.Worksheets(wbAccountsData.Worksheets.Count)'' wbAccountsData.Activate'' ActiveSheet.Name = strCompanyNumber & - & strFileDateEnd IfwbAccountsData.ActivatewbTempFile.CloseEnd Sub | Matching between files and a list of filenames at scale | performance;file system;vba;excel | Here are a couple of things to look into:In the Check_Companies_House_Files, near the start you have this block of code:ReDim arrFilteredAddresses(1 To lngFinalRow, 1 To lngFinalColumn)'/ Done iteratively because excel throws an Out of memory if I try to pass the whole range to the array in one go. Approx. 2 minutes for 1Million length listFor L = 1 To lngFinalRow For M = 1 To lngFinalColumn arrFilteredAddresses(L, M) = wsFilteredAddresses.Cells(L, M).Text Next MNext LReDim arrCompanyNumbers(1 To lngFinalRow)For L = 1 To lngFinalRow arrCompanyNumbers(L) = Right(00000000 & arrFilteredAddresses(L, 2), 8) '/ company numbers in the filenames are always 8 digits long, with 0's filling up any extra digitsNext LWhy have two separate loops? You should be able to merge them.ReDim arrFilteredAddresses(1 To lngFinalRow, 1 To lngFinalColumn)ReDim arrCompanyNumbers(1 To lngFinalRow)'/ Done iteratively because excel throws an Out of memory if I try to pass the whole range to the array in one go. Approx. 2 minutes for 1Million length listFor L = 1 To lngFinalRow For M = 1 To lngFinalColumn arrFilteredAddresses(L, M) = wsFilteredAddresses.Cells(L, M).Text Next M arrCompanyNumbers(L) = Right(00000000 & arrFilteredAddresses(L, 2), 8) '/ company numbers in the filenames are always 8 digits long, with 0's filling up any extra digitsNext LWhen you build the arrCompanyNumbers array, you do that text formatting 1 million times. Why not add a column to your Excel sheet with the value already formatted using the TEXT function? You then just read that column into the array.Your code is looping through your array arrCompanyNumbers looking for a matching entry. You might to look into using a Scripting.Dictionary instead because the Exists method is possibly much quicker than a 1 million long array. Presumably your company number values are all unique?If your files are HTML, Excel probably spends a lot of time parsing the HTML code when opening the file. You could try using the Scripting.FileSystemObject and the Scripting.TextStream.ReadAll method. This will load the file into a string variable and you could then use the InStr function to search for your text entries. If the HTML is complicated/fussy it might be too tricky to find the value that goes with your heading.You do this kind of thing a couple of times: varHolder1 = Application.Match(strPhraseHolder, arrFirstColumn, 0) varHolder2 = UCase(Application.Index(arrFirstColumn, varHolder1)) If IsError(varHolder1) _ Then varHolder1 = Application.Match(strPhraseHolder, arrSecondColumn, 0) varHolder2 = UCase(Application.Index(arrSecondColumn, varHolder1)) End IfI've got two issues with this. First, why bother getting the value for varHolder2 before you've checked if varHolder1 is an error? You should check varHolder1 first and then decide what to do. (By the way, why do you put the Then onto a new line and indent it? I would leave it on the same line as the If unless the line is very long.) varHolder1 = Application.Match(strPhraseHolder, arrFirstColumn, 0) If Not IsError(varHolder1) Then varHolder2 = UCase(Application.Index(arrFirstColumn, varHolder1)) Else varHolder1 = Application.Match(strPhraseHolder, arrSecondColumn, 0) varHolder2 = UCase(Application.Index(arrSecondColumn, varHolder1)) End IfThe second thing, is why use the Index function at all? The Match function has told you the row number/index number of the element. Why not use:varHolder2 = UCase(arrSecondColumn(varHolder1))A minor niggle is you hardcoding the max number of rows in your code, e.g. lngFinalRow = Cells(1048576, 1).End(xlUp).Row. This is fragile and might break if you upgrade Excel. Better to use lngFinalRow = Cells(wsAccountsData.Rows.Count, 1).End(xlUp).Row |
_unix.286506 | The startup I'm working at is setting up some new CentOS 7 servers that will host a mobile application, and some of the data is sensitive, thus, the servers need to be secured to the best of our ability.I installed Snort for an IDS, but I also wanted to install something that would basically audit the settings/configurations on the server for any vulnerabilities or attack vectors. Something similar to Security Advisor or the report generated by CSF, except since we don't use cPanel/WHM, it needs to be able to run as an independent service/application.Does anyone know of a tool like this? I know something like Nexpose can do this, also checking versions and security eratta, but that may be overkill for a couple of servers.Thanks!P.S. Just to clarify, I'm not looking for a firewall or anything to modify the configuration settings, I just need the audit capabilities.P.S.S. Also, I was planning on having the audit/scan automatically run every so often, just to detect if there were any changes. So if there's anything that could send out any critical results, after an audit, then that would be great. I found something called Lynis, and I'm looking at that, but there's probably something better than this. | Looking for a tool similar to the Security Advisor plugin for WHM that can run on CentOS 7 without WHM | security;scanner;vulnerability | null |
_softwareengineering.264860 | some of you should know what a login queue is. You start your game, like world of warcraft, league of legends, ..., type in your username and password, klick log in and then it happens: Login Queue, position: x.What i want to ask is, what actually is a login queue on the serverside? I mean, if you take league of legends and klick log in, the server will first check your logindata and then place you in the loginqueue (or not, if your password is wrong). So what i don't understand is, why is there a queue. If the server had enough time to check your logindata, whats the problem by just setting the is-loggedin flag? Why is there a queue needed? | What is a login-queue? | server side;login | null |
_unix.65171 | Fairly newbie.Fresh Debian install.I need to compile a package but the ./configure command does not work ?Getting the following error : -bash ./configure : No such file or directoryWhere is that script ? Locate did not give something | ./configure command does not work | debian;configure | locate will not work unless you have a up-to-date database.Try find . -type f -name configure instead, or issue a updatedb command first, then do the locate (make sure the current path isn't excluded) |
_softwareengineering.80077 | As a young developer, I would find it useful to get some advice regarding things to think about in order to develop a high-quality application. In my college courses, most teachers emphasized input validation and some talked about security concerns, but no one covered the importance of certain other things, like logging for example.What are some mistakes that inexperienced developers tend to make which could lead to frustration for more experienced developers? | What are the worst things that inexperienced developers forget to think about? | applications;quality;professionalism | null |
_softwareengineering.233335 | What would be the best way to store data in a database for geographical calculations? Say I have an ItemsForSale table paired to a Users table which holds their geo location. I know I can use latitude and longitude to look up items that are within a certain mile radius by using Lambert's formula for long lines or the Haversine formula but I am not sure if there is a better approach for this. | What is a good way to store geographical data for distance calculations | database design;data structures;geospatial | I'm not sure standard databases like MySql provide spacial indexing. You need to put them in a persistent spacial index. Like M-trees. Spacial indexes are efficient data structures that can perform range queries over distance metrics.Wikipedia M treeStack Overflow: Storing coordinates in a smart way to obtain the set of coordinates within a certain range from (lat_,lon_)You might be able to find an implementation of M-tree or other spacial indexing data structures like K-D trees.EDIT: After Martijn Pieters mentioned MySql having spatial indexes, I looked it up. Turns out it does have a R-tree but the support doesn't seem great. I only use innodb because mostly I end up requiring row level locks. MySQL 5.6 implements an additional set of functions that can help create geo-enabled applications with MySQL. Storing polygons boundaries (ZIP code boundaries for example) is efficient and the new spatial functions (st_within, st_contains, etc) will produce correct results and will use spatial (rtree) indexes (for MyISAM tables only). The OpenGIS standard is very common and it is easy to obtain the data in this format or use the standard application which can talk this language. Unfortunately, st_distance function is not very usable for calculating distance between 2 points on Earth and it does not use an index. In this case it is still more feasible to calculate distances manually using the harvesine formula. Hopefully this will be fixed in the next mysql release.Using the new spatial functions in MySQL 5.6 for geo-enabled applications |
_webapps.24063 | I wish to keep both accounts so my colleague doesnt have to assign me permissions again. I wish to do this so I can sync my Google plus with website but it wont let me with the different rights.Thank you. | I have one Google account for analytics, Google and plus, plus another account for adwords can I merge them | google;google analytics;google adsense | null |
_cs.29655 | One way to interpret the (simply typed) lambda calculus is via coherence spaces (Proofs and Types, chapter 8). For example, we can consider the space containing token element ($\mathbf{1}$) and the space containing two incoherent tokens ($\mathbf{Bool}$). These are given as follows:$$ \mathbf{1} = \{\emptyset, \{0\}\}\\ \mathbf{Bool} = \{\emptyset, \{t\}, \{f\}\}$$We can then consider the stable functions from $\mathbf{1}$ to itself:$$ F_1(\emptyset) = \emptyset, F_1(\{0\}) = \emptyset\\ F_2(\emptyset) = \emptyset, F_2(\{0\}) = \{0\}\\ F_3(\emptyset) = \{0\}, F_3(\{0\}) = \{0\}$$The trails of these functions are as follows:$$ \mathcal{Tr}(F_1) = \emptyset\\ \mathcal{Tr}(F_2) = \{(\{0\}, 0)\}\\ \mathcal{Tr}(F_3) = \{(\emptyset, 0)\}$$This again forms a coherence space$$ \mathbf{1 \Rightarrow 1} = \{\emptyset, \{(\{0\}, 0)\}, \{(\emptyset, 0)\}\}$$Which, just like $\mathbf{Bool}$, has two incoherent tokens. As far as I can see, the two should be equivalent, and there exists a stable function of type $\mathbf{(1 \Rightarrow 1) \Rightarrow Bool}$ which maps $F_2$ to $f$ and $F_3$ to $t$.Can this function be expressed in the lambda calculus? If not, why is it part of the interpretation? Can we see $\mathbf{Bool}$ and $\mathbf{1 \Rightarrow 1}$ as the same due to the similarity in coherence space? | How do stable functions 1 => 1 relate to Bool? | lambda calculus;semantics | null |
_cs.71858 | When I read introductory textbooks I get contradictory answers. In some cases efficiency and complexity are treated the same and the big-O notation is used to indicate that (for example) for an O(n) algorithm the time to execute is linearly proportional to the input dataset size.From other sources I have read that efficiency is a measure of the computing resources required to execute an algorithm, but not the same as the complexity of the algorithm. So for example is it possible to have an algorithm (say to multiply two decimal numbers) that is efficient in terms of its resources (it does not need much to execute) but is complex in that as the input dataset increases in size the time to execute is O(n^2) ??? | Definition of efficiency versus complexity of algorithm | algorithm analysis | null |
_scicomp.11819 | Would you know what is the condition for stability for the advection-diffusion equation where we treat the diffusion part using Crank-Nicholson and the advection part using FCTS (forward in time centered in space)? I am applying von Neumann analysis but I am not sure about the final condition for stability. Do you know where I could find the proof for the stability of that scheme? Thank you | advection diffusion equation | advection diffusion;advection;diffusion | null |
_webmaster.79465 | I have a site but I cannot get its URL indexed in search engines like Google, Yahoo, Bing, etc... Please let me know how I can submit my site's URL to Google. | How can I submit my site's URL to search engines? | seo;google;indexing;bing;yahoo | You really don't need to. Crawlers will find you on their own. However, if you would like to help that process a bit then include your domains in Google Webmaster Tools and Bing Webmaster Tools. Both will provide you with a number of helpful stats on your site as well.Also, make sure that you have an XML sitemap on your site. It will assist the crawlers in moving through your website. |
_codereview.152304 | Most importantly which bothers me in the following implementation is the call in BranchAddManager, do I really need to call base.StartAddNewOperation();? How can I get away without making this call?public override void AddNew() { //I would like to avoid calling the base method, if I forget then I may run into bug. base.StartAddNewOperation(); }Please help me to verify whether this approach make sense to you? Am also open to take another approach, if you think it make more sense. I have just noticed, this could be a builder pattern approach too. It will be a bit too much to add the entire code here but I try to demonstrate with relevant code, if you think the explanation is not enough then please let me know.Program (main call)Making a call to add a new Branch Record by setting properties to BranchModel.class Program { static void Main(string[] args) { var model = new BranchModel() { BranchName = Test Branch, Description = The description of a branch, BranchTypeId = 2 }; try { new BranchAddManager(model).AddNew(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }AddManagerBase (abstract)Concrete classes which needs to Add new records into the system should inherit from this base class.abstract class AddManagerBase<T> where T : class{ private TransactionModel _transaction; protected readonly T _model; public AddManagerBase(T model) { _model = model; _transaction = new TransactionModel() { TransactionDate = DateTimeOffset.Now }; } public abstract void AddNew(); protected abstract void RunValidations(); protected abstract void PreDatabaseOperation(); protected abstract void DatabaseOperations(); protected void StartAddNewOperation() { RunValidations(); PreDatabaseOperation(); DatabaseOperations(); LogThisActivity(); } protected void SetTransactionId(int transactionId) { Console.WriteLine(SetTransactionId()); _transaction.TransactionId = transactionId; } private void LogThisActivity() { Logger.AuditLog(AuditType.Add, _transaction.TransactionId, _transaction.TransactionDate); }}BranchAddManager (concrete)This class inherits the base class. The following example is supposed to add a new Branch Record.class BranchAddManager : AddManagerBase<BranchModel>{ public BranchAddManager(BranchModel model) : base(model) { } public override void AddNew() { //I would like to avoid calling the base method, if I forget then I may run into bug. base.StartAddNewOperation(); } protected override void RunValidations() { //In this example ensure the BranchTypeId exists in the DB. Console.WriteLine(RunValidations()); } protected override void PreDatabaseOperation() { //Convert the Model to Pojo/Poco, etc.. Console.WriteLine(PreDatabaseOperation()); } protected override void DatabaseOperations() { //Insert into Branch Table Console.WriteLine(DatabaseOperations()); //manually setting the ID for this example but usually this is given by the Database when the new record gets inserted. int newBranchSqlIdentityId = 9990; base.SetTransactionId(newBranchSqlIdentityId); }}Logger, AuditType, BranchModel and TransactionModel (supporting classes)public enum AuditType { Add, Delete, Update } public class Logger { public static void AuditLog(AuditType auditType, int transactionId, DateTimeOffset date) { Console.WriteLine(string.Format({0} {1} {2}, auditType, transactionId, date)); } }class TransactionModel { public int TransactionId { get; set; } public DateTimeOffset TransactionDate { get; set; } }class BranchModel { public string BranchName { get; set; } public string Description { get; set; } public int BranchTypeId { get; set; } } | Factory Method Pattern - Base implementation to Add New Records | c#;factory method | There is no factory method pattern. Factory method means that a class has a static method (or multiple) for creating an instance of itself usually having a private constructor to prevent creating it in a normal way:class Foo{ private Foo(..) {} public static Foo Create(..) => new Foo(..);}What you do is a simple inheritance that needs a few improvements. You should start by renaming the base class and the models. Classes are objects and should have noun names. How about ModelService? The models don't need the Model suffix and their properties don't need to be prefixed with the model name e.g.:class Transaction{ public int Id { get; set; } public DateTimeOffset Date { get; set; }}Don't you think that currently AddManagerBase is not a very useful class?. You create an instance with a concrete model and all you can do is to repetedly call the AddNew method. Shouldn't the AddNew (or better Add) require a model to add? What happens if you call it again with the same model? Is it still new?You can fix it by changing the Add method to require a model. At the same time you can remove the StartAddNewOperation and put its content inside the Add method. You won't need to override this one any more. It calls the other methods in the right order allowing you to implement them and do something with the model along the way.abstract class ModelService<T> where T : class{ public void Add(T model) { var transaction = new Transaction { Date = DateTimeOffset.Now }; RunValidations(model); PreDatabaseOperation(model); DatabaseOperation(model, transaction); LogActivity(AuditType.Add, transaction); } protected abstract void RunValidations(T model); protected abstract void PreDatabaseOperation(T model); protected abstract void DatabaseOperation(T model, Transaction transaction); private void LogActivity(AuditType auditType, Transaction transaction) { Logger.AuditLog( auditType, transaction.Id, transaction.Date ); }}Implementing the BranchService is now much easier because you no longer have to care about the order of operations and override the Add method. Just do the validation and whatever else it requires by overriding the other methods.The new implementation also no longer needs a custom constructor because the new Add method requires a parameter.class BranchService : ModelService<Branch>{ protected override void RunValidations(Branch branch) { //In this example ensure the BranchTypeId exists in the DB. Console.WriteLine(RunValidations()); } protected override void PreDatabaseOperation(Branch branch) { //Convert the Model to Pojo/Poco, etc.. Console.WriteLine(PreDatabaseOperation()); } protected override void DatabaseOperations(Branch branch, Transaction transaction) { //Insert into Branch Table Console.WriteLine(DatabaseOperations()); //manually setting the ID for this example but usually this is given by the Database when the new record gets inserted. transaction.Id = 9990; }} |
_webapps.59068 | I need help applying this formula to a different sheet:=SUMIF(A2:A6,3,H2:H6)I'm basically trying to discover expenses for the month of March, and hopefully having a year constraint in there too. This is how it looks like:The expense report is separate from the summary report. | Run formula on different sheet | google spreadsheets | If you're in the summary report sheet and you want to sum something in the expense report sheet, then you need to do the following:SUMIF(expenses!A2:A6, 3, expenses!H2:H6)If your sheet name is Expense Sheet, then you need to write the formula like so:SUMIF('Expense Sheet'!A2:A6, 3, 'Expense Sheet'!A2:A6)If you want to search for values only, then I would re-write the 3 into 3. |
_webapps.50339 | How can I view anonymous opinions on sayat.me?I have tried looking around the site but was not able to find out how. I have also ran a few google searches to no avail | How can I view anonymous opinions on sayat.me? | sayat.me | null |
_unix.388279 | i just started shell programming and i can't get the following problem to work.I want that all directorys, from a defined directory (e.g.. /var/www/user), are displayed in dialog checklist. I also want that in the selected folders, get stored a previously defined variable (in every folder the same).Does anyone have a solution for the problem?edit//This is an working example. The problem is, every time i add a folder in the directory (e.g.. folder4) i have to edit the script.while truedoClientens=`dialog --backtitle Script --title Menu \ --checklist Select 0 60 0 \ folder1 off\ folder2 off\ folder3 off 3>&1 1>&2 2>&3`clientsantwort=$?if [ $clientsantwort = 1 ]; then clear exitficase $Clientens in'folder1') echo type=$mtype&text=$message >/var/www/users/folder1/msg/msg.txt break ;;'folder2') echo type=$mtype&text=$message >/var/www/users/folder2/msg/msg.txt break ;;'folder3' ) echo type=$mtype&text=$message >/var/www/users/folder3/msg/msg.txt break ;; *) ;;esac | ls command in a variable to display in dialog checklist and processing of the selected option | shell script;directory;dialog | null |
_unix.91229 | So I'm running a VM somewhere and want to know what hypervisor the host is running. Any way to check whether it's running KVM or in a container?The vm is running Ubuntu | How to check which hypervisor is used from my VM? | linux;ubuntu;virtualization;kvm | null |
_unix.223271 | I have /var on a 10Gb EXT4 partition separate from /. I want to stick /var/cache in RAM using tmpfs. The /etc/fstab entry would be quite simple:tmpgs /var/cache tmpfs size=500M,rw,nodev,nosuid,noexec,noatime 0,0However, I notice that without this entry du -sh shows the size-on-disk as:# du -sh /var/cache215M /var/cacheYet if I apply the above fstab entry, reboot, and run du -sh again I get:# du -sh /var/cache160K /var/cacheWithout the tmpfs entry the folders ldconfig, yum, fontconfig and man are present. When using the tmpfs fstab entry only the latter two are present.I'm curious about this because:I don't understand when to use the bind mount flag.I have /run in a tmpfs mount and now I'm not so sure about the contents of that mount being the same as what would be present if I didn't.Why is this? | Tmpfs mount for directories on another partition | mount;fstab;tmpfs | null |
_scicomp.1648 | I am trying to write computer code which will find the energy and density function for a atom with Z protons and N electrons. I am working in 1D for simplicity and would like to make the overall code as simple as possible (I am using Hartree units aswell). I am using also using the Hartree approximation. This is my overall algorithm:Finds hydrogen like wave-functions (i.e. no electron-election interaction)Works out density function via$n(z) = \sum_i \left | \phi_i(z) \right |^2$Works out Hartree potential$ V_H(r) = \int_0^\infty \frac{n(\vec{s})}{\left | \vec{r}-\vec{s} \right |} d\vec{s} $Uses Kohn-Sham equation to find new individual wavefuncitons$\left (-\tfrac{1}{2}\bigtriangledown^2 + \frac{Z}{\left |r \right |} + V_H(\vec{r}) + V_{EX}(\vec{r}) \right )\phi_i = \varepsilon_i \phi_i$Go back to step 2. and repeatI am having a number of difficulties and would be very grateful for some help with any of my questions.Firstly to compute the Hartree potential I need to turn it into a 1D problem, so we assume even spherical distribution of charge:$ V_H(r) = \int_0^\infty 4\pi s^2 \frac{ n(s)}{\left |r-s\right |} ds $However this blows up when r = s! I have been looking into Gauss's law but had no luck.Any help would be great. | Implementing simple atom model using density functional theory (DFT) | computational chemistry;hartree fock;density functional theory | Use the Poisson equation in its differential form to obtain the Hartree potential. It has a nice form in spherical coordinates. See for example the seminal paper of Becke, in which this problem is solved for the general polyatomic case without relying on spherical symmetry. |
_webapps.35881 | As you know, there was an option available in Google Image Search known as Search image with specific screen resolution, option name as Exactly but recently Google changed the approach and am not happy with the pre-defined sizes available there, any idea how I can hunt for a specific resolution image?Say what if I want to search for an image of 300x300Screen of new Google Image Search Options... | How do I search an image with specific resolution using new Google Image Search | google;google image search | Looks like the option got removed, and Google have even acknowledged it:Thanks for writing in. We're aware of this issue, and we're working on bringing the feature back. I'll let you know as soon as it's back up. Sorry for any inconvenienceAs pointed out in that thread, you can still get an exact size by using the imagesize filter like so:html5 logo imagesize:300x300 |
_cs.66704 | What is a good metric to pick the degree of a B-Tree? I assume this depends on the number of expected elements? Degree 2 gives us a 2-3-4 tree (each node contains 1-3 items and 2-4 children).How can I decide this? I am looking to store a couple of thousand keys in it. | What is a good metric to choose the degree of a B-Tree? | data structures;trees;search trees | null |
_webmaster.15226 | We have had a very long an damaging outage which lasted around 24hrs due to a change in our DNS servers by our registrar. What happened (according to our registrar) was that for some reason their system identified our domain to be due for renewal and changed the authoritative DNS servers to theirs which caused our domain to be forwarded to a temporary holding page. Once we alerted our registrar to the problem it wad already too late as the error had already propagated. Our domain runs out in Jan 2020 so there was absolutely no reason for this change.Now my question is, how do other businesses protect themselves against these types of outages which are both out of their control and take hours to resolve, inevitably causing the service to be unreachable for a long period?Thanks. | Domain registrar changed DNS without warning | web development;dns;domains;dns servers | for some reason their system identified our domain to be due for renewalOur domain runs out in Jan 2020My experience with hosting and registrars are you only find out how good they are when things go wrong and how they help with tidying up the mess, both in terms of fixes and explanations. In this case the explanation at face value seems dubious at best. Ask for a better explanation - if they fail to give one then change registrar. |
Subsets and Splits