id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.337907
I have a file in the following format: s1,23,789 s2,25,689and I would like to transform it into a file in the following format: s1 23 789 s2 25 689i.e 6 white spaces between the 1st and 2nd column and only 3 white spaces between the 2nd and 3rd column? Is there a quick way of pulling this off using sed or awk?
How to replace commas with white spaces in a csv, but inserting a different number of space after each column?
text processing;command line;awk;sed;csv
null
_unix.123482
Typically on a server, automatic updates of security-related patches are configured. Therefore, if I'm running MySQL 5.5 and a new security patch comes out, Ubuntu Server will apply the upgrade and restart MySQL to keep me protected in an automated way. Obviously, this can be disabled, but it's helpful for those of us who are a bit lazy ;)Does such a concept exist inside of a Docker container? If I'm running MySQL in a Docker container, do I need to constantly stop the container, open a shell in it, then update and upgrade MySQL?
Application updates inside of Docker containers?
lxc;docker
TL;DR: If you don't build it in yourself, it's not going to happen.The effective way to do this is to simply write a custom start script for your container specified by CMD in your Dockerfile. In this file, run an apt-get update && apt-get upgrade -qqy before starting whatever you're running.You then have a couple way of ensuring updates get to the container:Define a cron job in your host OS to restart the container on a schedule, thus having it update and upgrade on a schedule.Subscribe to security updates to the pieces of software, then on update of an affected package, restart the container. It's not the easiest thing to optimize and automate, but it's possible.
_softwareengineering.298576
It is good programming style to include all necessary dependencies in a header that references them. Often this includes declarations that are placed in the STD & global namespaces (like cstdio). However, this creates problems when a second programmer wants to wrap such an include file in a new namespace to encapsulate the first one. With this scenario in mind, is there a way to force declarations into the global name space? As a conceptual example (this won't actually compile):foo.h --> original definition// force global namespace, this is redundant when foo is in the global space// but could be important if foo included into another namespace.namespace :: { #include <cstdio>}namespace foo { FILE *somefile;}bar.h --> New file, by a new programmer, encapsulating foo.namespace bar { # include foo.h FILE *somefile; // bar:somefile, as opposed to bar::foo::somefile}Without the putative namespace ::{} we end up with declarations like foo::FILE, and foo::printf(), when we just want ::FILE and ::printf().Popular libraries like boost resolve this by defining an explicit hierarchy. That would require that foo know it will be part of bar, and place global namespace includes outside of the local namespace definition. However, good extensibility requires that we be able to use foo directly, OR wrap foo in a new namespace, without having to change foo or its includes.Does anyone know how to accomplish this?
C++ Extensible namespaces - how to force declarations back into global namespace
c++;namespace;extensibility;globals
null
_webapps.61016
I posted:Is there anyway to edit the post to change the title of the SoundCloud track sp1n DJs - Mix MIT GSC Boat Cruise - 23 - 05 - 2014 to something else?
How can I edit the information of a SoundCloud attachment in a Facebook post?
facebook;soundcloud
You cannot edit the information of a SoundCloud attachment in a Facebook post.
_cs.4659
I have a number of related questions about these two topics.First, most complexity texts only gloss over the class $\mathbb{NC}$. Is there a good resource that covers the research more in depth? For example, something that discusses all of my questions below. Also, I'm assuming that $\mathbb{NC}$ still sees a fair amount of research due to its link to parallelization, but I could be wrong. The section in the complexity zoo isn't much help.Second, computation over a semigroup is in $\mathbb{NC}^1$ if we assume the semigroup operation takes constant time. But what if the operation does not take constant time, as is the case for unbounded integers? Are there any known $\mathbb{NC}^i$-complete problems?Third, since $\mathbb{L} \subseteq \mathbb{NC}^2$, is there an algorithm to convert any logspace algorithm into a parallel version?Fourth, it sounds like most people assume that $\mathbb{NC} \ne \mathbb{P}$ in the same way that $\mathbb{P} \ne \mathbb{NP}$. What is the intuition behind this?Fifth, every text I've read mentions the class $\mathbb{RNC}$ but gives no examples of problems it contains. Are there any?Finally, this answer mentions problems in $\mathbb{P}$ with sublinear parallel execution time. What are some examples of these problems? Are there other complexity classes that contain parallel algorithms that are not known to be in $\mathbb{NC}$?
Some questions on parallel computing and the class NC
complexity theory;reference request;parallel computing;complexity classes
null
_codereview.21491
After I found the Change Tracking feature in SQL Server, I thought that I would love to have this information in a stream. That lead me to RX, and Hot Observables. I did some reading and came up with this. I'm wondering if it could be improved.First is how I would use it, followed by the class that implements it: var test = new MonitorDB.Server.PollChangeEvents(ConfigurationManager.ConnectionStrings[MonitorDB.Properties.Settings.db].ToString()); test.IntervalDuration = 1; test.SubscribeToChangeTracking(MessageQueueStatus, MessageQueueStatusID); test.StartMonitorChangesAcrossAllTables(); var subject = Guid.NewGuid(); var observer = test.Listen(subject.ToString()); var sub1 = observer.Subscribe(msg => Console.WriteLine(string.Format(Table {0} Operation {1} Key {2} Value {3}, msg.TableName, msg.Operation, msg.KeyName, msg.KeyValue))); Console.ReadLine(); test.StopMonitoringChangesAcrossAllTables(); Console.ReadLine();using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Timers;using System.Data.SqlClient;using System.Collections.Concurrent;using System.Collections.ObjectModel;using System.Reactive.Linq;using System.Reactive.Disposables;namespace MonitorDB.Server{ public class PollChangeEvents { Timer _timer; string _connectionString; private readonly IDictionary<string, IObservable<ChangeTrackingEvent>> observers = new Dictionary<string, IObservable<ChangeTrackingEvent>>(); public PollChangeEvents(string pConnectionString) { _timer = new Timer(); GC.KeepAlive(_timer); //prevents attempts at garbadge collection _timer.Elapsed += _timer_Elapsed; _ChangeTrackingEvents = new ConcurrentDictionary<string, IChangeTrackingSubscription>(); _connectionString = pConnectionString; } void _timer_Elapsed(object sender, ElapsedEventArgs e) { TableMonitoring.AsParallel().ForAll(pTableSubscription => { using (SqlConnection conn = new SqlConnection(_connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { string CmdString = string.Format(select *, CHANGE_TRACKING_CURRENT_VERSION() from Changetable(changes {0},{1}) as T, pTableSubscription.Key, pTableSubscription.Value.LastChangeVersion); cmd.CommandText = CmdString; cmd.Connection = conn; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { var newEvent = new ChangeTrackingEvent(pTableSubscription.Key, reader.GetName(5)); newEvent.Operation = reader[2].ToString(); newEvent.KeyValue = reader[newEvent.KeyName].ToString(); newEvent.LastChangeVersion = Int64.Parse(reader[6].ToString()); FIFOQueue.Enqueue(newEvent); pTableSubscription.Value.LastChangeVersion = newEvent.LastChangeVersion; } } conn.Close(); } }); } //Taken mostly from here //http://awkwardcoder.blogspot.ca/2012/06/understanding-refcount-in-reactive.html#!/2012/06/understanding-refcount-in-reactive.html // public IObservable<ChangeTrackingEvent> Listen(string subject) { IObservable<ChangeTrackingEvent> value; if (observers.TryGetValue(subject, out value)) return value; IObservable<ChangeTrackingEvent> observable = Observable.Create<ChangeTrackingEvent>(o => { var disposable = Observable.Timer(TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(1)) .Timestamp() .Subscribe(ts => { ChangeTrackingEvent dequeuedEvent = null; FIFOQueue.TryDequeue(out dequeuedEvent); if (dequeuedEvent != null) o.OnNext(dequeuedEvent); } ); return new CompositeDisposable(disposable, Disposable.Create(() => observers.Remove(subject))); }) .Publish() //this makes it a hot observable, throw events without a subscription .RefCount(); observers.Add(subject, observable); return observable; } private ConcurrentQueue<ChangeTrackingEvent> FIFOQueue = new ConcurrentQueue<ChangeTrackingEvent>(); private int _IntervalDuration; public int IntervalDuration { get { return _IntervalDuration; } set { _IntervalDuration = value; } } ConcurrentDictionary<string, IChangeTrackingSubscription> _ChangeTrackingEvents; private ConcurrentDictionary<string, IChangeTrackingSubscription> TableMonitoring { get { return _ChangeTrackingEvents; } } public bool SubscribeToChangeTracking(string pTableName, string pKeyName) { var ChangeTrackingEvent = new ChangeTrackingEvent(pTableName, pKeyName); return _ChangeTrackingEvents.TryAdd(pTableName, ChangeTrackingEvent); } public void StartMonitorChangesAcrossAllTables() { _timer.Interval = this.IntervalDuration * 1000; _timer.Start(); } public void StopMonitoringChangesAcrossAllTables() { _timer.Stop(); } }}
Hot Observable of Change Tracking Events from SQL Server 2008 R2
c#;system.reactive
null
_codereview.21532
I have written a piece of code that finds common patterns in two strings. These patterns have to be in the same order, so for example I am a person and A person I am would only match person. The code is crude, all characters, including whitespace and punctuation marks, receive the same treatment. The longest patterns are matched first.The main function then returns two lists (one per string) of tuples with two elements. The first element is 1 if a substring has been matched, else 0. The second element is the substring.So the format of returned lists will be like this:[(1, 'I '), (0, 'am a person\n')][(1, 'I '), (0, 'can see\n')]Now to the question -- what do you think about my code? I somehow feel that it's not quite top-notch, and I'm not an experienced coder. Any suggestions on coding style or the algorithms? I hope the code is reasonably clear.The find_raw_patterns function returns lists with alternating integers and strings, so the only thing find_common_patterns does in addition to calling find_raw_patterns, is to arrange the lists' elements in two-element-tuples.The function longest_common_substring is copied directly from Wikibooks, and I'm not very concerned about that function.Code:def longest_common_substring(S1, S2): M = [[0]*(1+len(S2)) for i in range(1+len(S1))] longest, x_longest = 0, 0 for x in range(1,1+len(S1)): for y in range(1,1+len(S2)): if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1] + 1 if M[x][y]>longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 return S1[x_longest-longest: x_longest]def find_common_patterns(s1, s2): arranged1 = [] arranged2 = [] (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern for i in range(len(ptr1) - 1): if type(ptr1[i]) == int: arranged1.append((ptr1[i], ptr1[i+1])) for i in range(len(ptr2) - 1): if type(ptr2[i]) == int: arranged2.append((ptr2[i], ptr2[i+1])) return (arranged1, arranged2)def find_raw_patterns(s1, s2): # used recursively one = [] # used to reassemble strings, but with patterns and integer showing whether it's been matched or not two = [] # same, but for the second string com = longest_common_substring(s1, s2) if len(com) < 2: return ((0, s1), (0, s2)) elif len(com) >= 2: i1 = s1.index(com) i2 = s2.index(com) s1_bef = s1[:i1] #part of string before the matched pattern s1_aft = s1[i1 + len(com) : ] # -//- after matched pattern s2_bef = s2[:i2] s2_aft = s2[i2 + len(com) : ] if len(s1_bef) > 0 and len(s2_bef) > 0: # find patterns in first parts of strings res = find_raw_patterns(s1_bef, s2_bef) one.extend(res[0]) two.extend(res[1]) one.extend((1, com)) # add current pattern two.extend((1, com)) if len(s1_aft) > 0 and len(s2_aft) > 0: # find patterns from second parts res = find_raw_patterns(s1_aft, s2_aft) one.extend(res[0]) two.extend(res[1]) return (one, two)
Python 3: Finding common patterns in pairs of strings
python;strings
You can simplify the two functions quite a bit. For find_raw_patterns you can use partition instead of manually splitting the strings up, and simplify the formation of the list.def find_raw_patterns(s1, s2): # used recursively if s1 == '' or s2 == '': return [], [] com = longest_common_substring(s1, s2) if len(com) < 2: return ([0, s1], [0, s2]) s1_bef, _, s1_aft = s1.partition(com) s2_bef, _, s2_aft = s2.partition(com) before = find_raw_patterns(s1_bef, s2_bef) after = find_raw_patterns(s1_aft, s2_aft) return (before[0] + [1, com] + after[0], before[1] + [1, com] + after[1])For find_common_patterns, you can use list indices to get the even and odd values rather than checking the type of each value, and use zip to get a list of pair tuples.def find_common_patterns(s1, s2): (ptr1, ptr2) = find_raw_patterns(s1, s2) #ptr - pattern return (zip(ptr1[::2], ptr1[1::2]), zip(ptr2[::2], ptr2[1::2]))But I think you can also combine the two functions with a minor adjustment to put the found values into paired tuples.def find_common_patterns(s1, s2): # used recursively if s1 == '' or s2 == '': return [], [] com = longest_common_substring(s1, s2) if len(com) < 2: return ([(0, s1)], [(0, s2)]) s1_bef, _, s1_aft = s1.partition(com) s2_bef, _, s2_aft = s2.partition(com) before = find_common_patterns(s1_bef, s2_bef) after = find_common_patterns(s1_aft, s2_aft) return (before[0] + [(1, com)] + after[0], before[1] + [(1, com)] + after[1])
_codereview.42001
public class Office{ private Int32 _SyncID; private string _OfficeName; #region Properties public Int32 SyncID { get { return _SyncID; } set { _SyncID = value; } } public string OfficeName { get { return _OfficeName; } set { _OfficeName = value; } } #endregion public void GetOffice(int syncID) { List<Office> results = new List<Office>(); var sql = @Select so.SyncID, so.titleFrom Offices oLeft Outer Join SyncOffices so On so.id = o.SyncIDWhere o.SyncID = @syncID; using (var connection = new SqlConnection(Settings.ConnectionString)) using (var command = new SqlCommand(sql, connection)) { command.CommandType = CommandType.Text; command.Parameters.AddWithValue(@syncID, syncID); connection.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var office = new Office(); office.SyncID = reader.GetInt32(0); office.OfficeName = reader.GetString(1); results.Add(office); } } } this.SyncID = results.FirstOrDefault().SyncID; this.OfficeName = results.FirstOrDefault().OfficeName; }}
Class for Managing Office Details
c#;sql server;asp.net mvc 4
The current code will ensure that the list has only one entry (i.e. the last one) ...results = new List<Office>();results.Add(office);... because invoking results = new List<Office>() will discard any previous list elements.If you expect your SQL join where to produce exactly one (or, zero or one but not more than one) element then you can assert that; perhaps something like ...if (reader.Read()) ... get the data ...if (reader.Read()) throw new Exception(Too many rows);... or ...string rc = null;while (reader.Read()){ if (rc != null) throw new Exception(Too many rows); rc = reader.GetString(1);}Perhaps your GetOffice method could be the Office constructor; or be a static factory method of Office.
_unix.196447
I need to do it without using the ' character.I could do it like this:awk '{sum+=$5} END { print Average = ,sum/NR}'except this contains a '.
How to average a column in a text file without using ' character?
linux;bash;sed;awk;perl
You don't need '' (strong quotes), you can use the weaker form , except you then need to escape the s.awk {sum+=\$5} END { print \Average = \,sum/NR}But why?
_cs.63847
Lexical Analyzer mostly deletes comments and white-spaces. One example where I think Lexical Analyzer might not be discarding white-spaces is in Python language, as indentation has a important role in python. But I can't think of practical example where comments are/should be kept by Lexical Analyzer? Is there any such example you can think of?
White-space and comment by lexical analyzer
compilers;parsers;lexical analysis
White-space and comments can contain valuable information.For white-space, you can look at layout sensitive languages, like Python or Haskell. I'm not sure how their lexers work, but off the top of my head I would store an indentation level, not the actual white-space.For comments, it can be useful to store these if you want to generate documentation from Javadoc-style comments. For Javadoc, the parameter types do not have to be specified in the docblock (unlike PHPDoc, for instance). This means that a documentation generator would have to look at both the comments and the method header (everything before {). For the latter the lexer can be used, for the former it cannot (presuming the lexer removes comments).I'm note sure how Javadoc-based documentation generators work, so perhaps the above is inaccurate, but the general idea is correct. I'm working on the Cloogle project, a Clean function search engine similar to Haskell's Hoogle. We hook into the Clean compiler to parse function types from all standard libraries. It would be nice if we could show comments around the definition as well, but the lexer removes this information. So, if we want to display comments, we have to adapt the compiler's frontend, or write a simplistic program that finds comments around some function, without lexing everything. If the lexer and parser would store comments, we would have a much more elegant solution.
_codereview.74042
I've read somewhere on Stack Overflow that doing queries in a loop is very inefficient. It will hammer your SQL server and make your script very slow.Sample code:// Connect to SQL Server 1$query = SELECT * FROMarticles;$resource = mysql_query($query);$articles = array();while $record = mysql_fetch_assoc($resource) { $articles[] = $record;}// The part that bothers me:// (Note: this is executed on a different sql server)foreach ($articles as $article) { // Connect to SQL server 2 $sQuery = SELECT artcode FROM articles WHERE id='.$article['id'].'; $sResource = mysql_query($query); if (mysql_num_rows($sResource) == 1) { $data = mysql_fetch_assoc($sResource); // Connect to SQL Server 1 again ... // This will be executed on the first sql server again $uQuery = UPDATE articles SET artcode='.$data['artcode'].' WHERE id='.$article['id'].' LIMIT 1; $uResource = mysql_query($query); }}How would I go and make this code more efficient. (In best case scenario avoiding doing the query in a loop.)
Looping to update article codes on one server based on queries on another server
php;performance;sql;mysql
The problem: there is a query being performed inside a for-loop.foreach ($articles as $article) { // Connect to SQL server 2 $sQuery = SELECT artcode FROM articles WHERE id='.$article['id'].';}The solution: move the query outside of the for-loopforeach ($articles as $article) { $articleIds[] = $article['id'];}$sQuery = SELECT artcode FROM articles WHERE id IN '.implode(',',$articleIds).';Then loop over the result of that query and peform the update query. Again, this update query be moved outside the loop. Check this for more info.
_unix.141598
I have a focusrite scarlett 8i6 soundcard and I would like to make many sounds with it. Currently it's deadly silent and I want to crack on with some programming whilst listening to music!I usually go for a very standard Ubuntu install, but thought I would give Linux Mint a try, but the soundcard doesn't seem to work currently.After some fiddling with Linux Mint I've actually made it recognise the soundcard.cat /proc/asound/cards: 1 [USB ]: USB-Audio - Scarlett 8i6 USB Focusrite Scarlett 8i6 USB at usb-0000:00:14.0-1, high speedI've blacklisted the onboard soundcard, but now I'm not sure how to use this one. It isn't picked up in sound preferences, by default that just has a dummy output now. I've got pulseaudio, alsa and jack installed, but have no idea how to actually get any or all of those working together.Some other info:# /sbin/lsmod | grep sndsnd_usb_audio 149200 0 snd_usbmidi_lib 25070 1 snd_usb_audiosnd_hwdep 13602 1 snd_usb_audiosnd_seq_midi 13324 0 snd_seq_midi_event 14899 1 snd_seq_midisnd_rawmidi 30095 2 snd_usbmidi_lib,snd_seq_midisnd_seq 61560 2 snd_seq_midi_event,snd_seq_midisnd_pcm 102033 1 snd_usb_audiosnd_seq_device 14497 3 snd_seq,snd_rawmidi,snd_seq_midisnd_page_alloc 18710 1 snd_pcmsnd_timer 29433 2 snd_pcm,snd_seqsnd 69141 9 snd_usb_audio,snd_hwdep,snd_timer,snd_pcm,snd_seq,snd_rawmidi,snd_usbmidi_lib,snd_seq_device,snd_seq_midisoundcore 12680 1 sndI've also updated /etc/modprobe.d/alsa-base.conf:options snd-usb-audio index=0aplay --list-devices: **** List of PLAYBACK Hardware Devices **** card 1: USB [Scarlett 8i6 USB], device 0: USB Audio [USB Audio] Subdevices: 1/1 Subdevice #0: subdevice #0I don't really know much about pulseaudio, other than the basic of what it does.But the soundcard doesn't seem to be picked up by it.pacmd list-cardsWelcome to PulseAudio! Use help for usage information.>>> 0 card(s) available.For completeness the output of speaker testspeaker-test 1.0.27.1Playback device is defaultStream parameters are 48000Hz, S16_LE, 1 channelsUsing 16 octaves of pink noiseRate set to 48000Hz (requested 48000Hz)Buffer size range from 192 to 2097152Period size range from 64 to 699051Using max buffer size 2097152Periods = 4was set period_size = 524288was set buffer_size = 20971520 - Front LeftTime per period = 12.425529But still no sound.Any suggestions?*******UPDATE***********Command: amixer -c 0 contentsnumid=1,iface=MIXER,name='Scarlett 8i6 USB-Sync' ; type=ENUMERATED,access=rw------,values=1,items=2 ; Item #0 'Internal' ; Item #1 'S/PDIF' : values=0
Focusrite Scarlett 8i6 With linux mint
linux;linux mint;audio;alsa;pulseaudio
null
_codereview.112202
I've been trying to learn Java and one way I've been teaching myself is by tackling programming challenge questions.One such question is reverse the character order of words in a string.For example, I have a hat => I evah a tah (note the spaces). In my implementation, I don't deal with punctuation, so I have a hat! => I evah a !tah.I've written an implementation and I'd like some feedback, particularly regarding the readability and efficiency of the code (basically, is there a slicker implementation of what I'm trying to accomplish - to me, the answer is yes, especially the last part of my implementation).The implementation is basically doing the following:Create a one element-sized String array called candidateReversedWordsString and initialize it with the input StringCreate a StringBuilder that will build all the reversed words.Iterate through the characters in the stringIf the character is not a space and the StringBuilder is empty, note the character index value in the wordStartIndex variable and add the character to the StringBuilder.If the character is not a space and the StringBuilder is not empty, add the character to the StringBuilderIf the character is a space and the StringBuilder is not empty, take the only element in the candidateReversedWordsString array and basically concatenate the element with the reversed word from the StringBuilder using substrings.If at the final character and the StringBuilder is not empty, slight adjustment to the concatenationpublic String reverseWordsInString(final String string) { final String[] candidateReversedWordsString = new String[1]; candidateReversedWordsString[0] = string; int stringCharacterIndex = 0; int wordStartIndex = 0; final StringBuilder reverseWordStringBuilder = new StringBuilder(); while (stringCharacterIndex < string.length()) { if (' ' != string.charAt(stringCharacterIndex)) { if (reverseWordStringBuilder.length() == 0) { wordStartIndex = stringCharacterIndex; } reverseWordStringBuilder.append(string.charAt(stringCharacterIndex)); } if (' ' == string.charAt(stringCharacterIndex) && reverseWordStringBuilder.length() > 0) { candidateReversedWordsString[0] = new StringBuilder(). append(candidateReversedWordsString[0].substring(0, wordStartIndex)). append(reverseWordStringBuilder.reverse().toString()). append(candidateReversedWordsString[0].substring(stringCharacterIndex)).toString(); reverseWordStringBuilder.setLength(0); } if (stringCharacterIndex == string.length() - 1 && reverseWordStringBuilder.length() > 0) { candidateReversedWordsString[0] = new StringBuilder(). append(candidateReversedWordsString[0].substring(0, wordStartIndex)). append(reverseWordStringBuilder.reverse().toString()).toString(); } stringCharacterIndex++; } return candidateReversedWordsString[0];}
Reverse the character order of the words in a string
java;strings;programming challenge
I like the effort that you put into naming your variables. You may have gone a bit overboard, though. For example, instead of candidateReversedWordsString, how about result?A few mechanical issues:This could be a static method, since it relies on no instance state.It's pretty funny that you defined a final String[] of length 1 to store one String with the ability to change its only element. Why not just use a regular String variable?You have int stringCharacterIndex = 0; while (stringCharacterIndex < string.length()) { stringCharacterIndex++; }That pattern would be easier to understand if written asfor (int i; i < string.length(); i++) { }Here, I would opt for a short variable name i, which has the connotation of being a loop counter that is an index. string[i] is easy enough to understand.This statement summarizes your strategic error:candidateReversedWordsString[0] = new StringBuilder(). append(candidateReversedWordsString[0].substring(0, wordStartIndex)). append(reverseWordStringBuilder.reverse().toString()). append(candidateReversedWordsString[0].substring(stringCharacterIndex)).toString();Basically, you are rebuilding the entire tentative result string every time you want to reverse a word. That's bad for performance, and also complicates your code.I think that you would be better off without using any StringBuilder, and just using a char[] instead, especially since you know that the result will be exactly the same length as the input.Consider this solution instead:public static String reverseWords(String string) { char[] c = string.toCharArray(); int wordStartIndex = -1; for (int i = 0; i < c.length; i++) { if (c[i] == ' ') { // Ignore spaces continue; } if (wordStartIndex < 0) { // Mark start of word wordStartIndex = i; } if (i + 1 == c.length || c[i + 1] == ' ') { // Word ends here; reverse it for (int a = wordStartIndex, b = i; a < b; a++, b--) { char swap = c[a]; c[a] = c[b]; c[b] = swap; } wordStartIndex = -1; } } return new String(c);}
_codereview.77264
I started out practicing on implementing the builder pattern and somehow ended it up with this 2 hours later. It isn't really much, but it works and I'm hoping review should bring about a lot of insight.I'm curious in pinpointing:Which part(s) are well executed? I've never done anything 'game' like so I have no idea what's a good idea and what isn't.Which part(s) could be considered poorly executed? I wanted to standardize the outputs and decreased repetition as best I could through method calls but I still get the feeling that a few things are redundant.General feedback on efficiency of the program. Particularly, little things, I'm wondering if it would make more sense to makeStringbuilder and use append instead of using string concatenation.The Dragon class:class Dragon { int atk, def, hp, hpMax, mp, mpMax, exp, lvl; String name; Element element; Race race = Race.DRAGON; Dragon(Builder d) { atk = d.atk; def = d.def; hp = d.hp; hpMax = d.hp; mp = d.mp; mpMax = d.mp; lvl = d.lvl; name = d.name; element = d.element; } static class Builder { int atk = 0, def = 0, hp = 1, mp = 0, lvl = 1; String name; Element element = Element.NEUTRAL; Builder(String name){ this.name = name; } public Builder atk(int val){ atk = val; return this; } public Builder def(int val){ def = val; return this; } public Builder hp(int val){ hp = val; return this; } public Builder mp(int val){ mp = val; return this; } public Builder element(Element e){ element = e; return this;} //You can't generate a dragon. A dragon is born! public Dragon born(){ return new Dragon(this); } } public void addExperience(int exp){ this.exp += exp; } public String getStatus() { return this.name + has + this.atk + attack + this.def + defense + this.mp + / + this.mpMax + mana and + this.hp + / + this.hpMax + health. ; }}Element enum: public enum Element { LIGHT, DARK, FIRE, WATER, AIR, EARTH, NEUTRAL; @Override public String toString() { return super.toString().substring(0, 1).toUpperCase() + super.toString().substring(1).toLowerCase(); }}Race enum:public enum Race { DRAGON; @Override public String toString() { return super.toString().substring(0, 1).toUpperCase() + super.toString().substring(1).toLowerCase(); }}I haven't yet really implemented these two yet but I included them for the sake of completion.Main: import java.util.Scanner;public class BattleSim { static Scanner input = new Scanner(System.in); public static void main(String[] args) { System.out.print(What is your name? ); String name = input.nextLine(); Dragon player = new Dragon.Builder(name) .atk(5).def(2).hp(25).mp(7).born(); Dragon challenger = new Dragon.Builder(Glaurung) .atk(6).hp(15).born(); System.out.println(You are a Dragon.\n + Not the order your underlings around 'big bad' that barely + ever shows up kind + but bonafide sky soaring, loot hoarding, city scorching Dragon. ); System.out.println(\nWhile you were out being awesome another dragon + stole your princess.\nYour damsel's in distress. + You 'gonna take that? ); battle(player, challenger); System.out.println(Thanks for checking this out fellow CRers.); } public static int printBattleMenu() { System.out.print(\nBattle menu\n1: Attack\n2: Defend + \n3: Abilities\n4: Status\n5: Enemy Status\nEnter a choice: ); int selection = input.nextInt(); while (selection > 5 || selection < 1) { System.out.print(Out of range. Enter a choice (1-5): ); selection = input.nextInt(); } return selection; } public static int printAbilityMenu() { System.out.print(\nAbility menu\n1: Rage Claw - 2 mp + \n2: Meditate - gain 3 mp\n3: Healing breath - 3 mp + \n4: Back\nEnter a choice: ); int selection = input.nextInt(); while (selection > 5 || selection < 1) { System.out.print(Out of range. Enter a choice (1-4): ); selection = input.nextInt(); } return selection; } public static void printBattleStatus(Dragon x, Dragon y) { System.out.println(x.name + has + Math.max(0, x.hp) + health and the opposing + y.name + has + Math.max(0, y.hp) + health remaining. ); } public static void battle(Dragon x, Dragon y){ int damageDealt, damageTaken, recoveryValue; System.out.println(\t\t\tVS. + y.name); do { switch(printBattleMenu()) { case 1: damageDealt = Math.max(0, x.atk - y.def); damageTaken = Math.max(0, y.atk - x.def); System.out.println(x.name + deals + damageDealt + damage and takes + damageTaken + damage. ); x.hp -= damageTaken; y.hp -= damageDealt; // Print current status printBattleStatus(x, y); break; case 2: damageTaken = Math.max(0, y.atk - x.def * 2); System.out.println(x.name + takes a defensive stance and + takes + damageTaken + damage. ); printBattleStatus(x, y); break; case 3: switch(printAbilityMenu()) { case 1: damageTaken = Math.max(0, y.atk - x.def); if (x.mp < 2) { System.out.println(Insufficient mana. + \nOpposing + y.name + took advantage of your + foolishness to attack. ); } else { damageDealt = Math.max(0, x.atk * 2 - y.def); x.mp -= 2; System.out.println(x.name + 's claws are infused with mana! ); System.out.println(x.name + deals + damageDealt + damage and takes + damageTaken + damage. ); y.hp -= damageDealt; } x.hp -= damageTaken; printBattleStatus(x, y); break; case 2: damageTaken = Math.max(0, y.atk - x.def); System.out.println(x.name + absorbs the mana of the land. ); x.mp = Math.min(x.mpMax, x.mp + 3); System.out.println(x.name + takes + damageTaken + damage. ); x.hp -= damageTaken; printBattleStatus(x, y); break; case 3: damageTaken = Math.max(0, y.atk - x.def); if (x.mp < 3) { System.out.println(Insufficient mana. + \nOpposing + y.name + took advantage + of your foolishness to attack. ); } else { recoveryValue = (int)Math.floor(x.hpMax * 0.3); x.hp = Math.min(x.hpMax , x.hp + recoveryValue); x.mp -= 3; System.out.println(x.name + recovers + recoveryValue + health! ); } x.hp -= damageTaken; System.out.println(x.name + takes + damageTaken + damage. ); printBattleStatus(x, y); break; case 4: // do nothing break; } // End of Ability Switch break; case 4: System.out.println(x.getStatus()); break; case 5: System.out.println(Opposing + y.getStatus()); break; } // End of Selection Switch } while(x.hp > 0 && y.hp > 0); if (x.hp == y.hp){ System.out.println(It is a double K.O.); } else if (x.hp > y.hp){ System.out.println(x.name + is the victor!); } else { System.out.println(y.name + has slain you!); } // setting values back to full x.mp = x.mpMax; x.hp = x.hpMax; }}
How to Train Your Dragon
java;object oriented;design patterns;game;adventure game
This is smelly:class Dragon { Race race = Race.DRAGON;You see, why does a Dragon need an enum field to re-state that it is a Dragon.This is error-prone:Dragon(Builder d) { atk = d.atk; def = d.def; hp = d.hp; hpMax = d.hp; mp = d.mp; mpMax = d.mp; lvl = d.lvl; name = d.name; element = d.element;}It's pretty hard to read which values from the builder get assigned.It's easy to get lost in the middle of those lines and possibly forget to assign something very important.The common writing style is to have all assignments on their own lines.It's also good to stop here for a second about naming...Why name a Builder variable d? How about builder?The field names seem unnecessarily shortened.For example attack and defense are not that long,and immediately more natural than atk and def. //You can't generate a dragon. A dragon is born! public Dragon born(){ return new Dragon(this); }To be precise, a dragon is born... from a Dragon.Builder? That's interesting :PThis, used in both Element and Race is very tedious:@Overridepublic String toString() { return super.toString().substring(0, 1).toUpperCase() + super.toString().substring(1).toLowerCase();}A simpler way would be to name the enum constants already Capitalized,and omit completely the custom toString implementation,for example:public enum Race { Dragon}Or, if you really prefer enum constants as all-caps,at least move the common capitalization logic to a utility class to eliminate duplicated code, for example:public class StringUtils { private StringUtils() { // utility class, forbidden constructor } public static String toCapitalized(String label) { return label.substring(0, 1).toUpperCase() + label.substring(1).toLowerCase(); }}public enum Element { LIGHT, DARK, FIRE, WATER, AIR, EARTH, NEUTRAL; @Override public String toString() { return StringUtils.toCapitalized(super.toString()); }}The BattleSim.battle method is awfully long.It would be good to try to break it into smaller pieces.In terms of OOP,there isn't much to see here.Although you called the main class Dragon, it's not very Dragon-like.It might as well be a Human Wizard:it has attributes like attack, defend, mana,but it doesn't have features like breath attack, paralyzing terror, flying.It's not clear how to extend the existing classes to add such and more features,it seems that thorough thinking would be needed.
_cs.69625
I have been reading up on the NeuronEvolution of Augmented Topologies and there's this little thing that's been bothering me. While reading Kenneth Stanley's Paper on NEAT I came on this figure here:The innovation numbers go from 1,2,3,4,5,6 to 1,2,3,4,5,6,7 on the first mutation.On the second one it goes from 1,2,3,4,5,6 to 1,2,3,4,5,6,8,9. My question is why does it skip number 7 and goes straight up to 8 instead? I didn't find anything related to deleting innovation numbers.Same thing on this second figure, how did Parent 1 lose 6,7 and where did the 8th gene go to in Parent 2?
NeuroEvolution: NEAT algorithm innovation numbers
machine learning;neural networks;genetic algorithms;neural computing
Here is what I gathered from skimming the paper for just the figure.Your first figure, which is the figure 3 in the paper, already has the answer in its caption:Figure 3: The two types of structural mutation in NEAT. Both types, adding a connection and adding a node, are illustrated with the connection genes of a network shown above their phenotypes. The top number in each genome is the innovation number of that gene. The innovation numbers are historical markers that identify the original historical ancestor of each gene. New genes are assigned new increasingly higher numbers. In adding a connection, a single new connection gene is added to the end of the genome and given the next available innovation number. In adding a new node, the connection gene being split is disabled, and two new connection genes are added to the end the genome. The new node is between the two new connections. A new node gene (not depicted) representing this new node is added to the genome as well.In figure 3, it could be deduced that the add connection mutation (top half) occur preceding the add node mutation (buttom half).When the add connection mutation occurred, the lowest free innovation number was 7. And so the gene created at that moment was assigned the marker of 7.Later, when the add node mutation occurred, 2 new genes were created. And so they were assign the lowest free innovation number at the time which is 8 and 9.The innovation number is not the indices of each gene inside the array representing a genome.The innovation number is just a number permanently branded to each gene, telling us when the gene first occur. As if the year number when human first evolved a gene for hairless body were written down on the gene itself.The uses of innovation is then explained around your latter figure, which is figure 4:The historical markings give NEAT a powerful new capability. The system now knows exactly which genes match up with which (Figure 4). When crossing over, the genes in both genomes with the same innovation numbers are lined up. [...] This way, historical markings allow NEAT to perform crossover using linear genomes with out the need for expensive topological analysis.From this I assumed that innovation number are always ordered increasingly within a genome, but gaps in innovation numbers are allowed to occur within genome.The order is probably ensured simply by the fact that all operations done on genome was designed to not violate this within-genome ordering.This makes sense because each gene can be thought of as an instruction to construct a graph.By keeping the instruction ordered by when it was introduced, it makes sure that reading instruction on genome from left to right makes sense chronologically.
_webapps.82935
I tweeted something via Twitter and then tried to search for it. The tweet is https://twitter.com/bgoodr2/status/638042917056065536 so I searched for:Allow Intra-PDF document link navigationAnd that gave nothing (URL was https://twitter.com/search?f=tweets&q=Allow%20Intra-PDF%20document%20link%20navigation&src=typd)I tried searching forIntra-PDFAnd gave some results (URL was https://twitter.com/search?q=Intra-PDF&src=typd). I then tried to include the to: operator:Intra-PDF to:dochubappwhich gave https://twitter.com/search?f=tweets&q=%22Intra-PDF%22%20to%3Adochubapp&src=typd but my tweet did not show up there.Is this the same situation as described in the answer to Why is my tweet not appearing, and when might it appear? ? If so, then that is puzzling: I would have expected it to show me my own outbound tweets even if they aren't showing up in the feed of the recipient.
Why is twitter search not finding results
twitter
null
_webapps.40363
Currently I'm trying to search through my rather large email archive on Gmail.Unfortunately the words I like to find also occur in almost any email footer as the signature text.While I understand that there is no entity type signature in a plain email body, it seems that Gmail is still (limited) capable of detecting signatures (and collapsing them with those ... buttons).My question:Is there a search operator to tell Gmail to search for text but omit the signature?
Is it possible to exclude the email signatures when searching in Gmail?
gmail;gmail search;email signature
Kinda, there is a work around to do what you want, while doing the search, you can specify that results should not have some text, by using the field Doesn't have, and include in this field some text from the signatures.or if you can also specify to search for whole sentences only, by using double quotes like this:my one long sentenceso it will match the whole sentence only, and not single words.
_opensource.2655
I know this question is utterly silly for a developer, but apparently the legal dept. is getting paid to have a common sense that's ... different from ours.So here is my question: What license governs the files that are automatically generated by Visual Studio?And I don't refer here to things that are added as Nuget packages. Those have a (relatively) clear license.I refer to the trivial files, like:web.[debug|release].config files for web projectsglobal.asax(.cs)?AssemblyInfo.csXxxForm.designer.cs (for Winforms projects)For some context: I have to comply with a tool called Protex that scans source files and finds pieces that may be part of OSS projects. The general idea is sane - we do want to comply with the requirements of the OSS libraries we use, and this tool helps check if there's anything we missed. The problem is, it also finds positives in (unmodified) files like web.debug.config, probably because there are a zillion OSS projects out there that have used the same VS Web Project template containing the same scaffolded files.
What is the license of the scaffolding files Visual Studio generates automatically?
licensing;development environment
null
_unix.2048
Currently I need to have a program running all the time, but when the server is rebooted I need to manually run the program. And sometimes I'm not available when that happens.I can't use a normal configuration to restart my program when the server is starting because I don't have root access and the administrator don't want to install it.
how to ensure a program is always running but without root access?
process;boot;monitoring;cron
I posted this on a similar questionIf you have a cron daemon, one of the predefined cron time hooks is @reboot, which naturally runs when the system starts. Run crontab -e to edit your crontab file, and add a line:@reboot /your/command/hereI'm told this isn't defined for all cron daemons, so you'll have to check to see if it works on your particular one
_unix.236235
I installed a newer version of tcpdump via MacPorts and would like to make it the default binary.$ which -a tcpdump/usr/sbin/tcpdump/opt/local/sbin/tcpdumpFor now I set an alias, but that of course doesn't prevent man to show the older documentation.
How to set binary installed by package manager as default?
osx;package management;binary
In OS X 10.8.5, bash 3.2.53(1), MacPorts 2.3.4 you should actually do nothing.I don't know though why it didn't work at first. PATH's value might have somehow been stored and not updated (more on this below).I tried MANPATH as suggested by thrig, but that didn't work. From man's man page:It overrides the configuration file and the automatic search path. exporting the PATH from my (global) profile with the directories of the package manager first. That prefixed them thrice and suffixed them once and it did set the newer binaries/man pages as default, but I was curious about this new longer composition of PATH (the old value had all directories just once but in a different order, OS's defaults first, then package manager's).For this topic check over at SU, Where does $PATH get set in OS X 10.6 Snow Leopard?.It turns out MacPorts installer adds the directories in ~/.profile.# MacPorts Installer addition on 2015-10-10_at_20:55:20: adding an appropriate PATH variable for use with MacPorts.export PATH=/opt/local/bin:/opt/local/sbin:$PATH# Finished adapting your PATH environment variable for use with MacPorts.I had this multiple times, so I proceeded to comment all, except the last one. That resulted in a clean PATH.But how does man actually get the newer documentation?From the SEARCH PATH FOR MANUAL PAGES section:In addition, for each directory in the command search path (we'll call it a commanddirectory) for which you do not have a MANPATH_MAP statement, man automatically looks fora manual page directory nearby namely as a subdirectory in the command directory itself orin the parent directory of the command directory.You can disable the automatic nearby searches by including a NOAUTOPATH statement in/private/etc/man.conf.I corroborated this by temporarily enabling NOAUTOPATH.Example$ type tcpdumptcpdump is /opt/local/sbin/tcpdump$ ll -d /opt/local/manlrwxr-xr-x 1 root admin 9 Oct 10 20:55:20 2015 /opt/local/man -> share/manFor other package managers YMMV, but not much I suppose.
_cs.13874
I need to keep a collection on integers in the range 0 to 65535 so that I can quickly do the following:Insert a new integerInsert a range of contiguous integersRemove an integerRemove all integers below an integerTest if an integer is presentMy data has the property that it often contains runs of integers in the collection. For example, the collection might at one point in time be:{ 121, 122, 123, 124, 3201, 3202, 5897, 8912, 8913, 8914, 18823, 18824, 40891 }The simplest approach is just to use a balanced binary tree like the C++ std::set, however, using that, I am not leveraging the fact that I often have runs of numbers. Perhaps it would be better to store a collection of ranges? But that means a range needs to be able to be broken up if an integer in its middle is removed, or joined together if the space between two ranges in filled in.Are there any existing data structures that would be well suited for this problem?
What data structure would efficiently store integer ranges?
data structures;efficiency;search trees;integers
I suggest you use a binary search tree, augmented so that leaves can contain an interval (a run of consecutive integers). Maintain the invariant that the intervals do not overlap and are in order (following the search tree invariant). (This can be considered a special case of an interval tree or a segment tree, for the special case where the intervals do not overlap.)This data structure you can support all of your operations in $O(\lg n)$ time, where $n$ is the number of intervals. Since we're guaranteed $n\le 65535$, I would expect this to be quite efficient. (In particular, yes, you can split an interval into two pieces or merge two adjacent intervals into a single interval in $O(\lg n)$ time.)
_unix.150917
I used the following command to redirect 80 to 3000. All the requests that come, from any domain, are redirected to 3000:sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3000Having to processes: one that listens on 80001 and another one that listens on 8002 how can I link two domains to the two ports?Is it possible to have a JSON configuration like below?[ { port: 8001, domains: [example.com, example2.com] }, { port: 8002, domains: [domain.com, domain2.com] }]So, domain.com, domain2.com will send their requests to the process that listens on 8002 and the other two domains on 8001?
Redirect domains to different ports on same machine
iptables;port forwarding;json
Usually you would have to setup your web server with virtual hosts and maybe mod_proxy (for Apache).However, I would suggest that you use a reverse proxy such as haproxy to take care of that. Setup Haproxy so that it listens to port 80 and direct your traffic to your webservers using ACLs on the domain name. Setup your webserver with virtual hosts that listen to 127.0.0.1:8002 and 127.0.0.1:80001 (if haproxy runs on the same server).Pretty simple setup. Look at this example. It's for putting haproxy in front of Docker containers, but you can adapt the configuration to suit your needs.
_unix.208607
When running this script, I run into an error on this line (relevant snippet below):..._NEW_PATH=$($_THIS_DIR/conda ..activate $@)if (( $? == 0 )); then export PATH=$_NEW_PATH # If the string contains / it's a path if [[ $@ == */* ]]; then export CONDA_DEFAULT_ENV=$(get_abs_filename $@) else export CONDA_DEFAULT_ENV=$@ fi # ==== The next line returns an error # ==== with the message: export: not valid in this context /Users/avazquez/anaconda3 export CONDA_ENV_PATH=$(get_dirname $_THIS_DIR) if (( $($_THIS_DIR/conda ..changeps1) )); then CONDA_OLD_PS1=$PS1 PS1=($CONDA_DEFAULT_ENV)$PS1 fielse return $?fi...Why is that? I found this ticket, but I don't have that syntax error.I found reports of the same problem in GitHub threads (e.g. here) and mailing lists (e.g. here)
Zsh: export: not valid in this context
zsh;environment variables;command substitution;assignment
In zsh, Command Substitution result was performed word splitting if was not enclosed in double quotes. So if your command substitution result contain any whitespace, tab, or newline, the export command will be broken into parts:$ export a=$(echo 1 -2)export: not valid in this context: -2You need to double quote command substitution to make it work, or using the safer syntax:PATH=$_NEW_PATH; export PATHor even:PATH=$_NEW_PATH export PATH
_softwareengineering.168494
Is it important to point out the good parts of the code during a code review and the reasons why it is good? Positive feedback might be just as useful for the developer being reviewed and for the others that participate in the review.We are doing reviews using an online tool, so developers can open reviews for their committed code and others can review their code within a given time period (e.g. 1 week). Others can comment on the code or other reviewer's comments. Should there be a balance between positive and negative feedback?
How important is positive feedback in code reviews?
code reviews
Improve Quality and Morale Using Peer Code Reviews http://www.slideshare.net/SmartBear_Software/improve-quality-and-morale-using-peer-code-reviewsThings Everyone Should Do: Code Review http://scientopia.org/blogs/goodmath/2011/07/06/things-everyone-should-do-code-review/Both of these articles state that one of the purposes of code review is to share knowledge about good development techniques, not just find errors.So I'd say it's very important. Who wants to go to a meeting and only be criticized?
_unix.34933
I can connect to Linux machines from Windows using PuTTY/SSH. I want to do the other way round - connect to a Windows machine from Linux. Is this possible?
Can I connect to Windows machine from Linux shell?
linux;ssh;windows
null
_unix.191265
I'm managing a lot of drupal sites, and trying to automate some stuff using drush. Drush run locally calls drush on the remote host via ssh using options specified in the config for the site alias. I'm making quite a lot of these calls, so to speed it up I use persistent ssh connections with ssh config like so:Host * # see http://www.revsys.com/writings/quicktips/ssh-faster-connections.html ControlMaster auto ControlPath ~/tmp/%r@%h:%p ControlPersist 3600I get a speed-up, but I also get messages like so:$ drush @alias drupal-directory webform /var/local/www/example.com/htdocs/sites/all/modules/contrib/webformShared connection to 12.34.56.78 closed.The message about the shared connection is on stdout, along with the output I want (seriously? why not stderr?), so it's causing problems when I try to capture the output in my scripts:directory=$(drush @$alias drupal-directory $module)I expect the master connection to be one I already had open though, and it doesn't look like that closed. So maybe drush is explicitly making this new connection a master one and closing it? In any case, is there a way to suppress the message about the connection closing?[This issue is in a drupal / drush context, but I think it's fundamentally about ssh. Is this the right site then?]EDIT:It looks like the problem is specific to where the -t option to ssh is in use. I'm using this because svn passwords need to be entered at various points, and without -t, the password prompts don't get displayed. Maybe there's another way to stop those prompts being lost?
Avoid Shared connection to closed messages
shell script;ssh;drupal
null
_webapps.79266
Can Google Apps mail support MULTIPLE geographical email subdomains? Such as:[email protected]@[email protected] so, how can this be implemented?Is it also possible to lock down these subdomains so that they can only be accessed from certain IP addresses?The reason we need it is that we need to demonstrate that users are in specific offices for a variety of boring but important regulatory compliance reasons.
How to set up geographical email subdomains on Google Apps
google apps email
null
_unix.295292
The CPU is a [email protected]. It has 4 cores and each core has 2 threads. Here is the dmidecode output:# dmidecode -t 4# dmidecode 2.9SMBIOS 2.7 present.Handle 0x0042, DMI type 4, 42 bytesProcessor Information Socket Designation: SOCKET 0 Type: Central Processor Family: <OUT OF SPEC> Manufacturer: Intel(R) Corporation ID: A9 06 03 00 FF FB EB BF Version: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz Voltage: 1.1 V External Clock: 100 MHz Max Speed: 3800 MHz Current Speed: 3400 MHz Status: Populated, Enabled Upgrade: <OUT OF SPEC> L1 Cache Handle: 0x003F L2 Cache Handle: 0x003E L3 Cache Handle: 0x0040 Serial Number: Not Specified Asset Tag: Fill By OEM Part Number: Fill By OEM Core Count: 4 Core Enabled: 4 Thread Count: 8 Characteristics: 64-bit capableIt will be 8 logic core in a system, like what shows in /proc/cpuinfo. But can any one tell why the cpu MHz of a core is 1600MHz? I guess there is 2 threads in a core, so a hw thread freq may be about the half of the core's? How this number is calculated?processor : 7vendor_id : GenuineIntelcpu family : 6model : 58model name : Intel(R) Core(TM) i7-3770 CPU @ 3.40GHzstepping : 9cpu MHz : 1600.000cache size : 8192 KBphysical id : 0siblings : 8core id : 3cpu cores : 4apicid : 7initial apicid : 7fpu : yesfpu_exception : yescpuid level : 13wp : yesflags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp lm constant_tsc arch_perfmon pebs bts rep_good xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 x2apic popcnt aes xsave avx lahf_lm ida arat tpr_shadow vnmi flexpriority ept vpidbogomips : 7013.49clflush size : 64cache_alignment : 64address sizes : 36 bits physical, 48 bits virtualpower management:Also, here is the output of lshw and lscpu command. There are also 1600MHz mentioned. lshw info:#lshw -class processor *-cpu description: CPU product: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz vendor: Intel Corp. physical id: 42 bus info: cpu@0 version: Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz slot: SOCKET 0 size: 1600MHz capacity: 3800MHz width: 64 bits clock: 100MHz capabilities: fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx rdtscp x86-64 constant_tsc arch_perfmon pebs bts rep_good xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm sse4_1 sse4_2 x2apic popcnt aes xsave avx lahf_lm ida arat tpr_shadow vnmi flexpriority ept vpid cpufreqlscpu info:#lscpuArchitecture: x86_64CPU op-mode(s): 32-bit, 64-bitCPU(s): 8Thread(s) per core: 2Core(s) per socket: 4CPU socket(s): 1NUMA node(s): 1Vendor ID: GenuineIntelCPU family: 6Model: 58Stepping: 9CPU MHz: 1600.000Virtualization: VT-xL1d cache: 32KL1i cache: 32KL2 cache: 256KL3 cache: 8192K
What does cpu MHz field mean in the /proc/cpuinfo of a hyper-threading cpu?
linux;cpu;multiprocessor;hyperthreading
Modern cpu's can operate at several different frequencies changing dynamicallyunder the load requirements (see wikipedia). Intel call this SpeedStep. When a cpu has little to do it will run at a lower frequency to reduce power (and therefore heat and fan noise). So the 1600Mhz you see is probably because all the cpus are not doing much, but it can rise to some maximum like 3400 Mhz determined by cpu and motherboard architecture, and temperature.I'm not sure where /proc/cpuinfo gets its single value from, butyou can see individual cpu info in files /sys/devices/system/cpu/cpu*/cpufreq/, eg for the current frequency:cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freqand read more about Linux cpu frequency scaling software in archlinux.
_unix.84283
I'd like to have TLSv1.2 support in Apache on my Scientific Linux 6 (RHEL6 rebuild) server.Is there some semi-supported pathway to getting this working? Preferably with minimal custom rebuilding. Right now I'm using mod_ssl with open_ssl, as provided in the SL6 repositories.Edit: Once TLSv1.2 support is available, the Apache configuration is well-documented and not too difficult. The problem is that RHEL6 ships with OpenSSL 1.0.0, which only supports TLS through 1.0 or 1.1.
How can I get TLSv1.2 support in Apache on RHEL6/CentOS/SL6?
rhel;openssl;apache httpd;scientific linux
I've written a quick guide on backporting the OpenSSL 1.0.1 RPM from Fedora Core to support RHEL6 and variants by replacing the bundled 1.0.0 version to add TLSv1.2 and ECC support. Built and tested against CentOS 6.4 in September of 2013:Guide to OpenSSL 1.0.1 RPM for CentOS 6Please note: That's the place where I keep my own copy of OpenSSL and OpenSSH up-to-date. Improvements in CentOS 6.5 have largely mitigated the demand for TLS1.2 and flaws like Heartbleed are addressed there, while this answer will forever be stuck in 2013. Don't follow the steps below verbatim, it is imperative you run 1.0.1g or newer.Now with github: github/ptudor/centos6-opensslI've made a patch available that I will reference in this guide: openssl-spec-patricktudor-latest.diffFirst, prepare your build environment. (If you've installed EPEL, use mock. Keeping it simple here...)yum -y groupinstall Development tools yum -y install rpm-build zlib-devel krb5-develmkdir -p $HOME/redhat/{BUILD,RPMS,SOURCES,SPECS,SRPMS}echo %_topdir $HOME/redhat/ > ~/.rpmmacrosNext, grab the Fedora Core 20 SRPM for OpenSSL and the full OpenSSL source.rpm -Uvh http://dl.fedoraproject.org/pub/fedora/linux/development/rawhide/source/SRPMS/o/openssl-1.0.1e-42.fc21.src.rpmcd ~/redhat/SOURCES/wget http://www.openssl.org/source/openssl-1.0.1g.tar.gzwget http://www.openssl.org/source/openssl-1.0.1g.tar.gz.sha1openssl dgst -sha1 openssl-1.0.1g.tar.gz ; cat openssl-1.0.1g.tar.gz.sha1Now apply the old secure_getenv syntax and apply the patch:cd ~/redhat/SOURCES/sed -i -e s/secure_getenv/__secure_getenv/g openssl-1.0.1e-env-zlib.patchcd ~/redhat/SPECS/wget http://www.ptudor.net/linux/openssl/resources/openssl-spec-patricktudor-fc20-19.diffpatch -p1 < openssl-spec-patricktudor-latest.diffRun the build:time rpmbuild -ba openssl.specEverything went well hopefully, so let's install the new RPMs:cd ~/redhat/RPMS/x86_64/sudo rpm -Fvh openssl-1.0.1g-*.rpm openssl-libs-1.0.1g-*.rpm openssl-devel-1.0.1g-*.rpmMake sure it actually worked:openssl ciphers -v 'TLSv1.2' | head -4The link above at my website has more details but this should be a good starting point.Thanks, enjoy.20130819: Rawhide revision bumped from 14 to 15.20130831: fc20 revision bumped from 15 to 18.20130906: fc20 revision bumped from 18 to 19.20140408: just go to my website for anything after 1.0.1g.
_unix.205226
How can I map Ctrl+Backspace to behave as Delete key with xkb? I can remap a single key on /usr/share/X11/xkb/symbols/pc but can't figure out how to do the combination. My OS is Ubuntu 15.04
xkb: make ctrl+backspace behave as delete
keyboard shortcuts;keyboard;keyboard layout;xkb
As Gilles pointed out in a comment, you can do it with xkb if you change the type of BKSP key to control-modifiable. Example: if I edit /usr/share/X11/xkb/symbols/pc and under: include pc(editing) include keypad(x11)change this line: key <BKSP> { [ BackSpace, BackSpace ] };to: key <BKSP> { type=PC_CONTROL_LEVEL2, symbols[Group1]= [ BackSpace, Delete ] };then Ctrl+Backspace behaves as Delete.
_webapps.85286
i have a hotmail account and have recently discovered that there is a Gmail account with the same name i use for my hotmail account? does this mean they have access to my hotmail/outlook/google/youtube/facebook accounts and if so how can i remove the gmail account as i have noticed unusal activity within my hotmail account, things deleted, emails not coming thru to my hotmail, its not right, ive changed my password a million times, removed devices associated with my google account, updated my backup recovery info, and put in 2step verification, but im always bypassed by code generator, and within facebook it keeps being reactivated, and will bypass a tx to my ph?Please advise if anyone has any info much appreciatedShannonPlease read belowSorry Im just as confused too, but what im asking is, is it possible a gmail account using the same username as your hotmail email account and google account link up together in anyway because they share the same user name? where they are all accessible by logging into one of these accounts? As i know google has the ability to link/sync all your accounts together so you can access them on any device from anywhere?I hope that is more understandable?.. RegardsShan
removing email accounts that have the same user name as mine
gmail;google contacts
null
_codereview.147845
I am learning redux by doing a small project. Everything is working fine, but I need to know how I can refactor such code. For this situation, it might be good to use if conditions like I have done, but what if I need to handle 7-8 languages? It won't be viable to use else if for 7 times. What is the proper way to handle such situation?import { FRENCH } from '../../public/messages/fr';import { ENGLISH } from '../../public/messages/en';const initialState = { lang: FRENCH.lang, messages: FRENCH.messages};export const localeReducer = (state = initialState, action) => { switch (action.type) { case 'LOCALE_SELECTED': if (action.locale === 'fr') { return { ...initialState, lang: FRENCH.lang, messages: FRENCH.messages }; } else if (action.locale === 'en') { return { ...initialState, lang: ENGLISH.lang, messages: ENGLISH.messages }; } break; default: return state; }};
Locale language reducer
javascript;ecmascript 6;react.js;i18n
null
_codereview.138616
I wrote a method that calculates the average and standard deviation of sell currency exchange-course (ASK). But I think that it isn't the easiest way to define such behavior.In my opinion there is too much creating of BigDecimal values.I have also doubts about using an ArrayList to get values in order to count standard deviation, maybe there is a better data structure to achieve that goal.The method contains also counting average of buy currency exchange-course (BID in parsed file) but don't focus on it please.package pl.parser.nbp;import java.math.BigDecimal;import java.math.RoundingMode;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class Counting {public void countAverageAndStandartDeviaton(String address){ try { DocumentBuilderFactory df = DocumentBuilderFactory.newInstance(); DocumentBuilder db = df.newDocumentBuilder(); Document doc = db.parse(address); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(Rate); List<BigDecimal> listForStandartDeviation = new ArrayList<>(); BigDecimal averageOfBid = new BigDecimal(0); BigDecimal averageOfAsk = new BigDecimal(0); BigDecimal divisor = new BigDecimal(nList.getLength()); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; BigDecimal valueForBidAverage = new BigDecimal(eElement.getElementsByTagName(Bid).item(0).getTextContent()); BigDecimal valueForStandartDeviation = new BigDecimal(eElement.getElementsByTagName(Ask).item(0).getTextContent()); averageOfBid = averageOfBid.add(valueForBidAverage); averageOfAsk = averageOfAsk.add(valueForStandartDeviation); listForStandartDeviation.add(valueForStandartDeviation); } } averageOfBid = new BigDecimal(averageOfBid.divide(divisor).toString()).setScale(4, RoundingMode.HALF_UP); averageOfAsk = new BigDecimal(averageOfAsk.divide(divisor).toString()); System.out.println(averageOfBid + - BID Average); BigDecimal sumStandartDeviation = new BigDecimal(0); for(int i = 0 ; i<listForStandartDeviation.size(); i++){ BigDecimal valueFromList = new BigDecimal(listForStandartDeviation.get(i).toString()); sumStandartDeviation = sumStandartDeviation.add((valueFromList.subtract(averageOfAsk)).pow(2)); } sumStandartDeviation = sumStandartDeviation.divide(divisor); sumStandartDeviation = new BigDecimal(Math.sqrt(sumStandartDeviation.doubleValue())) .setScale(4, RoundingMode.HALF_UP); System.out.println(sumStandartDeviation + - ASK Standart Deviation); } catch (Exception e) { e.printStackTrace(); }}}
Counting standard deviation from parsed XML file
java;xml;statistics
null
_unix.352074
In what way does the final value of number being assigned by read var number (and we enter 5) and number=5 differ? I was making this for loop: read var number#number=5factorial=1i=1for i in `seq 1 $number`do let factorial=factorial*idoneecho $factorialwhen I noticed that if the number has the value assigned by the read, rather than direct assigning, it doesn't enter my for. I'm guessing it's because of the data type.
For with read value
shell script;command line;scripting;variable;read
If you change the first line toread numberyoull get the behaviour youre looking for.read var numberreads two values and stores them in variables named var and number. If you only input one value, seq 1 $number expands to seq 1 which is just 1.
_webmaster.16846
I've a product page ranking well for a keyword which I duplicated from the company itself which contained faq about it's product.Now the website has removed that page so mine is the only one existing now.Does anyone have any idea if still duplicate content penalty will be applied to my page?Should I go ahead and remove it?
Penalty issue for a duplicate page in site but original page doesn't exist anymore
seo;duplicate content
null
_softwareengineering.202991
Microsoft employees commonly describe Windows 8 as having both a Render thread and UI thread.Typically they say the Render thread performs animations and the UI thread handles most other operations: parsing, layout, applying templates, data binding, input processing, most app callbacks, etc.Animations can be calculated from beginning to end when they are created. Sometimes the changes to the property being animated dont affect rest of the objects in a scene. These are called independent animations and they are run on the composition thread instead of the UI thread. This guarantees that they remain smooth because the composition thread is updated at a consistent cadence...Is this a common architecture or unique to Windows 8? What about Windows Phone 8? Android? iOS?
What operating systems use both a Render thread and a UI thread?
architecture;multithreading
null
_unix.109723
Lets suppose a file is being owned by a user named mrxyz with UID and GID 1000, and has RW permissions for the file (esp. in ext file-systems). Now if the file is brought to my system will my user hash with UID 1000 inherit the permissions or will I have to make changes to fit my context? So basically, I want to know how changing ownership and permission with chown and chmod work from portability point of view?PS. It was a curiosity raised in this comment ...would there be issues with permissions/ownership if I plugged the disk into another box? that I posted this Q. (So, it would be great to have answers covering portability of files as well as filesystem.)
How portable are the works chmod and chown commands?
permissions
null
_cstheory.31037
In the seminal paper of Polishchuk and Spielman where they give a construction of nearly linear sized $PCP$ for an $NP$ problem, one of the key ingredients is a low-degree test for bivariate polynomials. Essentially, to test if the function values on a set of evaluation points correspond to a bivariate polynomial of maximum degrees $(d,d)$, we check whether the restriction of this to axis parallel lines (i.e. rows and columns) are all degree $d$ univariate polynomials (This is an equivalence condition in the absolute case, which is easy to verify. The interesting part is the robustness of the test: that is, if the function values on the restrictions to axis parallel lines agree with low-degree polynomials on most points (that is, close to Reed-Solomon codewords), then there is a bivariate low degree polynomial (a Reed-Muller codeword) which also agrees with the function on most evaluation points). The proof of robustness uses the notion of error-corrector polynomial to capture the bad evaluation points, polynomial interpolation and then uses resultants. For more details check out sections 2,3,4,5 in http://cs.yale.edu/homes/spielman/PAPERS/holographic.pdfIn a follow-up paper by Sudan and Ben-Sasson (lemma 6.13 and section 6.6 in http://people.csail.mit.edu/madhu/papers/2005/rspcpp-full.pdf) they extend the basic argument of Polishchuk-Spielman to obtain a universal constant relating the distances of the function from row, column polynomials and the Reed-Muller polynomial. They claim a basic proof using the constant taken to be 128, without optimization.Then in a follow-up paper (by Ben Sasson et al here http://eccc.hpi-web.de/report/2012/045/, in section 10 (more precisely section 10.3)) they again talk about optimizing this universal constant and get it down to 10.24.My question is, Where did the universal constant exactly come into the picture at all, and how did they use the value of 128 in the first place? It seems to me (and I am sure I'm wrong here but not clear why) that one could have proved that same result without assuming anything about the size of the constant? It would be very helpful if someone could make that (simple and short) proof more explicit so that one sees how the constant and its assumed value enters the proof. Thanks in advance.
Universal constant for bivariate testing
coding theory;polynomials;pcp;property testing
null
_webapps.69468
Is there a way to see all of the shared files in my Dropbox account? I'd like to see which folders I've shared with people either by inviting them or just by sharing a link to that folder/file.
See all of the shared files in a Dropbox account
dropbox;sharing
Clicking links in the sidebar worked
_codereview.98778
I'm using a one-dimensional array with length \$W(\text{weight capacity})\$. Is this is any better than the solutions with a two-dimensional array \$W, n\$ where \$n\$ is the number of items? I'm looking for code review, optimizations and best practices.class Thieves: def __init__(self, details, items): self.details = details self.items = items self.index = [None] * (self.details[1] + 1) def valuable(self): ind = 0 while ind < len(self.items): to_be_added = set() for i in range(1, len(self.index)): if self.items[ind][0] <= self.details[1]: if self.index[i] == self.items[ind][1] and i == self.items[ind][0]: if self.index[i * 2] != None: if self.index[i * 2] < self.index[i] * 2: self.index[i * 2] = self.index[i] * 2 else: self.index[i * 2] = self.index[i] * 2 if i == self.items[ind][0]: if self.index[i] != None and self.index[i] < self.items[ind][1]: self.index[i] = self.items[ind][1] elif self.index[i] == None: self.index[i] = self.items[ind][1] if i - self.items[ind][0] > 0 and i - self.items[ind][0] != self.items[ind][0]: #and self.index[self.items[ind][0]] == self.items[ind] #and self.index[self.items[ind][0]] == self.items[ind][0]: if self.index[i - self.items[ind][0]] != None and self.index[i] == None: value = self.index[i - self.items[ind][0]] + self.items[ind][1] to_be_added.add((i, value)) elif self.index[i - self.items[ind][0]] != None and self.index[i] != None: if self.index[i] < self.index[i - self.items[ind][0]] + self.items[ind][1]: to_be_added.add((i,self.index[i - self.items[ind][0]] + self.items[ind][1])) #print to_be_added for i in to_be_added: self.index[i[0]] = i[1] to_be_added = set() ind += 1 print self.index[self.details[1]]def main(): t = Thieves((5, 5), [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3]]) t.valuable() z = Thieves((12, 5), [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3], [3, 10], [2, 11], [1, 4], [1, 7], [5, 20], [1, 10], [2, 15]]) z.valuable() k = Thieves((4, 10), [[6, 30], [3, 14], [4, 16], [2, 9]]) k.valuable()
Solution to the 0-1 knapsack
python;performance;programming challenge
Your code is very hard to follow. Your variable names tell very little about what they are supposed to be, and there are mysterious things, like why details is a 2-tuple, when only the second value in it is used. The very long lines make it hard to follow as well. It is also not obvious to figure out which of the values in every item is the weight and which the value.So while I am not really sure of what that code is doing, you only need to keep the full 2D array in memory if you want to backtrack over it to find out which items you should take with you. If you are only interested in knowing how much value can fit in the knapsack, you only need to have two rows of the array in memory. And that can be implemented much, much more compactly than what you have come up with:def knapsack_01(capacity, items): # items is sequence of (weight, value) tuples prev_row = [0] * (capacity + 1) for weight, value in items: this_row = prev_row[:weight] for idx in range(weight, capacity+1): this_row.append(max(prev_row[idx], prev_row[idx-weight] + value)) prev_row = this_row return prev_row[-1]if __name__ == '__main__': items1 = [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3]] items2 = [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3], [3, 10], [2, 11], [1, 4], [1, 7], [5, 20], [1, 10], [2, 15]] items3 = [[6, 30], [3, 14], [4, 16], [2, 9]] assert knapsack_01(5, items1) == 8 assert knapsack_01(5, items2) == 36 assert knapsack_01(10, items3) == 46Note that the tests, which all pass, run your test samples against the values returned by your code. So both this and your implementation agree, which is a good thing.
_webapps.56723
As I write this, I'm in EST (GMT - 5), and I'm trying to add an event for a couple of months from now when I will be in EDT (GMT - 4). Say the event is at 12:00 noon. When I add the event, it adds at noon, but this is incorrect because after the time change, the event will move an hour earlier on the calendar.I'm adding like this (and even specifying EDT):But the event is created like this:I could remember this trap and mentally correct for it, but what I really want is to be able to specify a time like 3/20/2014 at 12:00 in Eastern time, and have the app determine that this actually means EDT and NOT EST, and place the event correctly.That might be asking a bit too much, but what's the closest I can get to this without writing a custom app?
How can I specify daylight timezome status when adding an event?
google calendar
null
_cs.67203
BackgroundI have a setup where I need to make an API call to a partner to initiate a financial transaction. I have multiple partners, and I need to choose which one to use each time a transaction needs to happen. The characteristics differentiating two partners are: if the transaction is accepted or not (acceptance)the cost of the transaction (fee charged by the partner, assumed to be constant over time)the speed of the transaction (assumed to be constant over timefor each partner)The characteristics of a transaction are especially:amountcurrency(several other factors such as the user's country, the payment method he chose, etc)Additional info: the acceptance rate of a partner is subject to change arbitrarily over time..AlgorithmAs you probably guessed, I am currently thinking about solutions and algorithms that could be used to solve the following problem.Inputs:a transaction (with all its characteristics)the database of all transactions having ever happened, containing for each transaction the partner usedthe fee chargedif the transaction was accepted or notOutput: the best partner to use to execute the transaction.Obviously, the first step is to define best. Do we value speed more than cost? Do we value the expected acceptance rate more than both the cost and speed? etc.Another important aspect I mentioned earlier is that the acceptance of the same transaction by the same partner might change over time. This means that the algorithm should sometimes try a partner that is believed not to be currently the best just to be able to, for instance, check if a partner's acceptance rate has improved over time.My questionI'm obviously not asking someone to write a magic algorithm solving that. I have a background of CS, but I am unsure about what algorithms and types of algorithms are usually used to solve this kind of problem. I would be grateful to be given some extra terminology (e.g. if this is a typical problem with a particular name in the domain) and resources to be able to dig into the problem.Please don't hesitate to ask if something is unclear.Thank you![Edit] After searching a bit more on the web, it seems that this problem has a lot in common with the multi-armed bandit problem. However I believe that the algorithms presented to solve this problem (e.g. UCB1) could be suboptimal in this context, because they wouldn't take into account the characteristics of a transaction and act as if the partner didn't take them into account.
A decision algorithm to choose what partner to use
algorithms;data mining
null
_codereview.79078
There are 3 search fields, and at least one must be filled out. When the search button is clicked the search fields are checked, if none are filled in show the error window with the error message for this error. If at least one field is filled in get a code based on the search criteria. If the code was not successfully retrieved show same error window but with the error message for this error.The code I have works fine for this except that it looks verbose and I am repeated the code in the else statements except for the unique error messages. How can this be improved?private void searchButton_Click(object sender, RoutedEventArgs e){ searchCriteria.Clear(); searchCriteria.Add(townSearchTextbox.Text); searchCriteria.Add(countySearchTextbox.Text); searchCriteria.Add(postcodeSearchTextbox.Text); if (isValidSearchCriteria(searchCriteria)) { formatSearchCriteria(searchCriteria); set.updateWOEID(searchCriteria); if (set.WOEID.Length > 0) { // continue } else { // display any errors in the error window Error errorWindow = new Error(); errorWindow.Show(); errorWindow.errorMessage.Text = Error: Could not retrieve WOEID, please try again.; } } else { // display any errors in the error window Error errorWindow = new Error(); errorWindow.Show(); errorWindow.errorMessage.Text = Error: Please provide one or more search criteria.; }}
Checking search buttons on click
c#
Create a method:private void DisplayError(String errorMessage) { // display any errors in the error window Error errorWindow = new Error(); errorWindow.Show(); errorWindow.errorMessage.Text = errorMessage;}Then you can doprivate void searchButton_Click(object sender, RoutedEventArgs e){ searchCriteria.Clear(); searchCriteria.Add(townSearchTextbox.Text); searchCriteria.Add(countySearchTextbox.Text); searchCriteria.Add(postcodeSearchTextbox.Text); if (isValidSearchCriteria(searchCriteria)) { formatSearchCriteria(searchCriteria); set.updateWOEID(searchCriteria); if (set.WOEID.Length > 0) { // continue } else { DisplayError(Error: Could not retrieve WOEID, please try again.); } } else { DisplayError(Error: Please provide one or more search criteria.); }}Of course, the next step if you need it would be to use Exceptions instead. Yes, I know this is for Java, but it shows why.
_cs.57841
After researching concurrency I am unable to discern if it is either of these specifically or it encapsulates both?I was also wondering if someone could provide some programming applications/real world examples I am struggling to grasp the concepts entirely and it feels like every where I look people have different understandings.Just two re-define the two concepts I believe it to be:Order independent: There is 3 Tasks A, B and C they need to be completed for the application to finalize, and are able to be completed in any order.Interruptible: Tasks are able to be halted mid processing in order to complete part of one of the other tasks.Point 2 I am most uncertain about how is this advantageous for a serial application? I am guessing it would be to do with user input/bypassing locks or waits caused by requiring further information so other tasks can be completed.NOTE: I am trying to apply these in a context outside of parallelism.
Concurrency: Is it order-independability or interruptibility of tasks?
concurrency
Concurrency is working with tasks that may run simultaneously. In my experience, when this term is used, the main focus is on correctness: making sure a system works as intended.One way of doing that is to impose additional constraints on the system and ensure that they are always met. Order independence and interruptability are examples of two such constraints. You may want them to hold for your concurrent system. But they are not required properties of concurrent systems in general: for many concurrent systems, they do not hold and do not need to hold. For instance, in MySQL, you can configure to what extent you want your transactions to be isolated, with full serializability (order independence) as the highest level.
_unix.200237
I can't get less --quit-if-one-screen (-F) working without --no-init (-X).less --quit-if-one-screen /proc/uptimeI see no output.This works:less --quit-if-one-screen --no-init /proc/uptimeWhat I am doing wrong?
pager less: --quit-if-one-screen without --no-init
terminal;less;ncurses
null
_webapps.95437
Subscribing to a blog is possible via RSS and/or Atom. But when I search for it on Google, the results show how to do this for the author. I mean how can an author of a blog provide a facility to allow subscribing via email?I want to receive new posts by email.
How to subscribe to a blog on Blogspot via email?
blogger
null
_webapps.17276
I want to allow friends of friends to see my wall posts. However there is a certain friend who I have that I want to block access to for his friends. I want to block his friends without blocking him. Is this possible?
How to allow access to friends of friends except for a certain friend
facebook
null
_reverseengineering.15744
I have this pseudo code:v5 = serial[6] + serial[0] - serial[7] - serial[2];LOBYTE(v5) = serial[1];v8 = serial[3] + v5 - serial[4];if ( v8 != serial[5] ) goto FAIL;The variable serial[] is an array representing the bytes of the key abcdefgh. Dor example, serial[0] = 0x61. If we assume that serial[5] is 0x66 (the letter 'f'), how can I calculate the needed key to get a 0x66 in v8 as you can see some calculations are done to decide the possible values of v8.
Generating a key for a simple algorithm
cryptography;math
null
_unix.350823
What is the correct way to install Linux (LMDE2 in my case) to a new drive (SSD) and correctly copy over /home files?Partition Scheme on both harddrives was the same:- /dev/sda1 linux-swap- /dev/sda2 /- /dev/sda3 /homeI think I went about it the wrong way. I used nemo to simply copy the contents of my /home/andrew folder to two external harddrives(for redundancy). I then installed the new LMDE2 on a new 250gb SSD. I then moved the /home/andrew folder from the external harddrive to my new OS and deleted the /home/andrew that the installer had created. This created all sorts of problems because of file permisions. I tried to change file permisions with sudo chown -R andrew:andrew /home/andrewwhich sort of worked, but I still had problems. For example, I couldn't open gedit from terminal for example. sudo geditSome error to do with .Xauthority in my /home/andrew folder. I then tried this approach. I booted into a live usb and:sudo rsync -aXS --progress /media/mint/250GbStorage/andrew /media/mint/(long uuid)/homeThen I ran the installer again mounting/dev/sda2 as / /dev/sda3 as /homeThe installer simply created a default /home/andrew folder and all my files just appeared in /home/home/andrew. Deleting /home/andrew and renaming /home/home/andrew to /home/andrew just creates the same problem as before. My final approach was to install the OS then simply copy my documents, desktop, music etc individually from /home/home/andrew to home/andrew using nemo and everything works just fine. (I didn't copy the configuration files. Is my mistake that I did not correctly back up my home files?If I did mess up by incorrectly backing up my home files, how do I recover from this? I have already deleted my original partion?I have tried searching for this in many permutations in google but can't find a solution which I understand. There are lots of people who say that you should have your files in a separate /home partition but no definitive guide which explains an easy way to install a new operating system on a new drive and how to migrate your files. Thanks
New LMDE2 install and correctly move /home partition
linux;linux mint;system installation;home
null
_unix.148613
Ok so I am student, about to get my degree in computer science. I have been programming for couple of years now on my Macbook pro on OS X and I havent had any problems. On the other hand, everyone around is telling me to install linux OS because its better, developers use it, programmers use it, etc. But no one told me why is linux better than OS X? What's the big deal about having programming and developing on Linux?
Why should I get linux?
linux;ubuntu;osx
null
_codereview.71119
I'm currently studying C and I'm trying to just print the contents of a string array. I'm using pNames to point to the first char pointer and iterating from there.A more proper approach would use this pointer, get a char* each time and use printf(%s, pNames[i]) to print a whole string. However, I thought I would try to print it character-by-character inside each string, as follows: #include <stdio.h>int main(int argc, char *argv[]){char *names[] = { John, Mona, Lisa, Frank};char **pNames = names;char *pArr;int i = 0;while(i < 4) { pArr = pNames[i]; while(*pArr != '\0') { printf(%c\n, *(pArr++)); } printf(\n); i++;}return 0;} This code kind of works (prints each letter and then new line). How would you make it better?
Printing the contents of a string array using pointers
c;array;pointers
Given that the code is really simple, I see mostly coding style issues with it.Instead of this:char *names[] = { John, Mona, Lisa, Frank};I would prefer either of these writing styles:char *names[] = { John, Mona, Lisa, Frank };// orchar *names[] = { John, Mona, Lisa, Frank};The pNames variable is pointless. You could just use names.Instead of the while loop, a for loop would be more natural.This maybe a matter of taste,but I don't think the Hungarian notation like *pArr is great.And in any case you are using this pointer to step over character by character,so Arr is hardly a good name.I'd for go for pos instead. Or even just p.You should declare variables in the smallest scope where they are used.For example *pos would be best declared inside the for loop.In C99 and above, the loop variable can be declared directly in the for statement.The last return statement is unnecessary.The compiler will insert it automatically and make the main method return with 0 (= success).Putting it together:int main(int argc, char *argv[]){ char *names[] = { John, Mona, Lisa, Frank }; for (int i = 0; i < 4; ++i) { char *pos = names[i]; while (*pos != '\0') { printf(%c\n, *(pos++)); } printf(\n); }} Actually it would be more interesting to use argc and argv for something:int main(int argc, char *argv[]){ for (int i = 1; i < argc; ++i) { char *pos = argv[i]; while (*pos != '\0') { printf(%c\n, *(pos++)); } printf(\n); }}
_webmaster.99793
Given the following code:<section id=about-us> <div class=Employee> <h2>Lorem</h2> </div> <div class=Employee> <h2>Lorem</h2> </div></section><section id=contact> <form> <input> </form></section>With the following navigation<nav> <ul> <li><a href=/about-us>About us</a></li> <li><a href=/contact>Contact</a></li> </ul></nav>If a user would click on a link I would catch that with JavaScript and scroll to the corresponding section, but would Google understand my logic and index the pages /about-us and /contact as two separate pages? Or would I be better off to structure the navigation as:<nav> <ul> <li><a href=#about-us>About us</a></li> <li><a href=#contact>Contact</a></li> </ul></nav>
Google bot and navigation on a one page website
google;googlebot;navigation
null
_unix.353933
When tmux's mouse support is enabled (via set -g mouse on), clicking in a window pane will trigger tmux's copy mode, which is not what you always need. To select the text as you'd usually do in rxvt-unicode, one can temporarily disable mouse reporting by holding down the shift key before clicking using the left mouse button. After upgrading to Ubuntu 16.04, which has rxvt-unicode v9.21 and tmux v2.1, it seems like disabling mouse reporting is broken. Even after pressing down the shift key, mouse events are being sent to tmux and tmux's copy mode and a conventional rxvt-unicode selection are both triggered simultaneously (in response, the selection flickers a bit). I tried several things (including patching rxvt-unicode using this patch), but I'm not able to get the expected behavior. I believe this problem is rxvt-unicode centric since other terminal emulators (xterm, xfce4-terminal, gnome-terminal, etc.) work as expected. Is there a way to get around this issue in rxvt-unicode?EDIT On further investigation, I found that this is no longer an issue with the rxvt-unicode package(v9.22) shipped with Ubuntu 16.10. So this was either fixed betweenversions 9.21 and 9.22 or there is some problem with the version in Ubuntu 16.04.
Selecting text in rxvt-unicode and tmux with mouse reporting disabled
terminal;tmux;mouse;rxvt
null
_webapps.88035
I'm considering the migration of my entire project planning (and life planning) from e-kalender.de to Google Keep.I have about 5000 entries there, sometimes consisting of a few pages of text, but no images, audios or similar. Apart from that, these entries are organized in about a dozen groups (similar to Keep's Labels).Does anyone have a similar amount of data in Google Keep, and does it work / sync flawlessly and across devices (iPhone, iPad, Web version)?
How scalable is Google Keep?
google keep
null
_unix.118333
I have a file in the format as follows:$ cat file.txt27.33.65.227.33.65.258.161.137.7121.50.198.5184.173.187.1184.173.187.1184.173.187.1What's the best way to parse the file file.txt into a format like:27.33.65.2: 258.161.137.7: 1121.50.198.5: 1184.173.187.1: 3In other words, I want to loop through the file and count the number of times each IP address appears. I've already run it through sort so all the IP addresses are in order and directly after each other.
Counting number of times each IP address appears in log file
awk;sort
You're looking for uniq -cIf the output of that is not to your liking, it can be parsed and reformatted readily.For example:$ uniq -c logfile.txt | awk '{print $2: $1}'27.33.65.2: 258.161.137.7: 1121.50.198.5: 1184.173.187.1: 3
_softwareengineering.35639
Just out of curiosity, I started wondering whether a language which doesn't allow comments would yield more readable code as you would have be forced to write self-commenting code.Then again, you could write just as bad code as before because you just don't care. But what's your opinion?
Would a language which doesn't allow comments yield more readable code?
comments
null
_reverseengineering.6867
I'm in the process of trying to reverse engineer a GPS-watch firmware image in purpose of adding a new feature to the watch. Here's what I got so farI have the firmware image (.gcd file). AFAIK it's no common image, I couldn't find any information about it from googlingHere's the binwalk output:DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------344446 0x5417E Zlib compressed data, default compression548342 0x85DF6 Zlib compressed data, default compression548698 0x85F5A Zlib compressed data, default compression548849 0x85FF1 Zlib compressed data, compressed549789 0x8639D Zlib compressed data, compressed550677 0x86715 Zlib compressed data, compressed550878 0x867DE Zlib compressed data, default compression551849 0x86BA9 Zlib compressed data, default compression551871 0x86BBF Zlib compressed data, best compression552002 0x86C42 Zlib compressed data, default compression552145 0x86CD1 Zlib compressed data, compressed552274 0x86D52 Zlib compressed data, default compression552425 0x86DE9 Zlib compressed data, compressed552778 0x86F4A Zlib compressed data, default compression553056 0x87060 Zlib compressed data, default compression553199 0x870EF Zlib compressed data, compressed554875 0x8777B Zlib compressed data, compressed555202 0x878C2 Zlib compressed data, default compression555341 0x8794D Zlib compressed data, compressed555600 0x87A50 Zlib compressed data, default compression555778 0x87B02 Zlib compressed data, default compression555928 0x87B98 Zlib compressed data, default compression556221 0x87CBD Zlib compressed data, compressed556502 0x87DD6 Zlib compressed data, default compression556612 0x87E44 Zlib compressed data, default compression556953 0x87F99 Zlib compressed data, compressed559176 0x88848 Zlib compressed data, default compression559922 0x88B32 Zlib compressed data, default compression560116 0x88BF4 Zlib compressed data, default compression560292 0x88CA4 Zlib compressed data, default compression560417 0x88D21 Zlib compressed data, compressed560774 0x88E86 Zlib compressed data, default compression561567 0x8919F Zlib compressed data, default compression562207 0x8941F Zlib compressed data, best compression670601 0xA3B89 Zlib compressed data, best compression673859 0xA4843 Zlib compressed data, compressed678389 0xA59F5 Zlib compressed data, default compression797326 0xC2A8E Zlib compressed data, default compression811248 0xC60F0 Zlib compressed data, compressed850955 0xCFC0B Zlib compressed data, best compression1023917 0xF9FAD Zlib compressed data, best compression1079306 0x10780A Zlib compressed data, default compression1278786 0x138342 Zlib compressed data, default compression1278986 0x13840A Zlib compressed data, default compression1279066 0x13845A Zlib compressed data, default compression1279106 0x138482 Zlib compressed data, default compression1279186 0x1384D2 Zlib compressed data, default compression1279226 0x1384FA Zlib compressed data, default compression1281321 0x138D29 Copyright string: 2002-2009n1284386 0x139922 XML document, version: 1.01294150 0x13BF46 LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 754974720 bytes1294166 0x13BF56 LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1294182 0x13BF66 LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1294206 0x13BF7E LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1294222 0x13BF8E LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes1370193 0x14E851 Zlib compressed data, default compressionIt all seems like a false positive because when I run binwalk -e I get these files as output:All files without file suffixes are empty and the zip files give an error. ( I can't unzip the zlib files)From hexdump output I see quite a lot of ascii which I guess indicates it's not encrypted. Especially I've found that there seems to be some sort of language files between 0x10780A and 0x138342I've included the hexdump as hex2.outAll the files can be found hereMy question is: Where do I go from here? Please help, I've no idea.
Trying to reverse GPS Watch firmware image with binwalk
firmware;embedded
The Garmin GCD file format is documented here, with some additional information here and here.Furthermore, it looks like somebody already wrote a tool (mirrored here) for handling and manipulating Garmin GCD files:
_unix.34526
I have a recent problem with my sound configuration. Basically, it's way too loud until I set the volume below 10%. And then it's very quickly too silent. Using the alsa mixer, I can set the headphone volume and PCM volume to about 50% and then obtain a reasonable range on the master. But any application using pulse will reset all the non-master channels to max and kill my ears instantly.Is there a way to force pulse to NOT change the other channels? I tried to look for information, and it seems that I need to change the channels from mixin to ignore in the configuration file, but there are so many configuration files, and I haven't found which ones are actually used by my system. So in the end, I am not even sure that what I think is correct.Can someone tell me: how to find the exact configuration files I need to change, or how to override the global configuration with some local one? and what I need to actually change?Thanks.
How to change mixing of channels by pulse audio / alsa
debian;configuration;alsa;pulseaudio
So in the end, I figured out that my profile was called analog-output-headphones. And the relevant configuration file is there:/usr/share/pulseaudio/alsa-mixer/paths/analog-output-headphones.confFor some reason, the configuration of my alsa card is such that the master volume doesn't do anything and I haven't found how to change that. But I can ignore the master and only act on the headphones ... This is not ideal, but currently works.
_webmaster.107986
I've a news website included in Google News. I've used to use hEntry schema to give my news articles the structured data of articles.Now I want to remove my structured data tags/attributes and rely on the meta tags only.For example, instead of the structured data for date:<time class=entry-date published updated datetime=2017-07-20T04:40:19+00:00></time>I want to rely on this meta tag:<meta property=article:published_time content=2017-07-20T04:40:19+00:00 />Are they the same for Google bot?
Can meta tags replace structured data for Google News articles?
meta tags;structured data;google news
null
_codereview.48146
When it come to security I try to be to better as possible but I don't have the knowledge.According to what I read on-line my following code should be good but I could use some of your comment/critic/fixesHere is a simple class just to example how I would do a login. Does it look secure enough?class UserClass{private $dbCon = null;public $Error = '';public function __construct(PDO $dbCon){ $this->dbCon = $dbCon;}public function login($Email,$Password,$RegisterCustomerSession = FALSE){ $GetSalt = $this->dbCon->prepare('SELECT id,salt,hashPass FROM `customer` WHERE `email` = :Email'); $GetSalt -> bindValue(':Email',$Email); $GetSalt -> execute(); if($GetSalt -> rowCount() == 0) { $this->Error = No customer is registered with that email; return false; } elseif($GetSalt->rowCount()>0) { $CustomerInfo = $GetSalt->fetch(PDO::FETCH_ASSOC); if(sha1($Password.$CustomerInfo['salt'])==$CustomerInfo['hashPass']) { if($RegisterCustomerSession) self::RegisterAllCustomerSession($CustomerInfo['id']); return true; } else { $this->Error = Invalid Password; return false; } }}public function SetPassword($CustomerId,$Password){ $Salt = self::CreateSalt(16); $HashPass = sha1($Password.$Salt); $SetPasswordAndSalt = $this->dbCon->prepare('UPDATE `customer` SET `hashPass` = :HashPass,`salt` = :Salt WHERE `id` = :CustomerId;'); $SetPasswordAndSalt -> bindValue(':CustomerId',$CustomerId); $SetPasswordAndSalt -> bindValue(':Salt',$Salt); $SetPasswordAndSalt -> bindValue(':HashPass',$HashPass); try{ $SetPasswordAndSalt ->execute(); return true; }catch(PDOException $e){echo $e->getMessage(); return false; }}private function CreateSalt($HowLong = 16){ $CharStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-=+_<>'; $ReturnStr = ''; for($i = 0;$i<$HowLong;$i++) { $ReturnStr .= $CharStr{mt_rand(0,77)}; } return $ReturnStr;}private function RegisterAllCustomerSession($CustomerId){ // some code.}}
Is this user login secure?
php;mysql;security
I'm not sufficiently familiar with PDO to say more on your database access than that you don't seem to have any injection vulnerabilities. However, there are a few things which I would do differently.Salt entropyThere are two things which strike me as odd about your salt generation. Firstly, using a base-77 encoding. If you configure your database correctly then you can use the full 8 bits of each byte of salt. That's more efficient, avoids possible bugs with generating a number in the wrong range (how sure are you that strlen($CharStr) === 78?), and is closer to the assumptions made when analysing salted hashing.Secondly, while mt_rand is better than rand it's not a cryptographic PRNG. The best portable secure PRNG in PHP is openssl_random_pseudo_bytes; if you're not planning to deploy to Windows then you could also get good entropy from /dev/random.HashSHA is not generally recommended as a hash for passwords. The current conventional wisdom is that you want password hashing to be slow, and should use either bcrypt or scrypt. If you insist on SHA then you should use it as a component of PBKDF2.Account existence oracleThere are two schools of thought on telling people That username doesn't exist. The usability argument is that it's preferable to tell someone that they got their username wrong. The security argument is that you should always say Either your username doesn't exist or you got your password wrong to prevent people identifying accounts which do exist and then trying to brute-force their passwords. (Anti-brute-forcing techniques is a separate issue which I'm not going to address in detail).If you favour the security argument over the usability argument then you need to avoid telling people indirectly that the username doesn't exist. That means that if $GetSalt -> rowCount() === 0 you should still do a hashing operation to avoid a quicker page load which leaks information.Minor style pointsif($GetSalt -> rowCount() == 0) ...elseif($GetSalt->rowCount()>0)I see three things wrong here:What other possibilities are there? Shouldn't that elseif just be an else?Why == instead of ===?Pick a style for use of whitespace and stick with it.
_webapps.27828
I am a student at Smith College trying to make a Google Docs presentation visible to anyone in the world with a link.However, the options that surface when I click Share only let me share within Smith College. This document is also shared with some other students at Smith College.Why can't I share this presentation with the rest of the world?In fact, I can't even publish it on the web to everyone.
Why can't I share my Google Docs presentation outside of my college network?
google drive;google apps
It's because you don't have permissions to do so. The administrator of the Google Apps account has disabled this ability. There is a setting in the admin that scopes out the permissions and share abilities. They've selected the option that restricts other users from being able to see or edit the document unless they are within the organisation, in this case, the school.Users cannot share documents outside this organization In order to be able to share from Google Docs, you will need to have the administrator's account change the settings permission to allow you to do so.
_codereview.58420
I have a statistics query I'm trying to run against the below table:CREATE TABLE *****.RUN_D ( WHSE_CODE CHAR(12 BYTE), RUN_NUM NUMBER(*,0), SHEET_NUM NUMBER(*,0), SHEET_SEQ NUMBER(*,0), COUNT_DATE DATE, COUNTED CHAR(1 BYTE), ITEM_NUM CHAR(30 BYTE), BIN_CODE CHAR(10 BYTE), STOCK_UOM CHAR(10 BYTE), ON_HAND NUMBER(12,3), SNAP_COST NUMBER(15,5), COUNTED_OH NUMBER(12,3), COUNTER_NAME CHAR(20 BYTE), USER_CODE CHAR(30 BYTE), COUNT_VARIANCE CHAR(1 BYTE), ORG_CODE CHAR(2 BYTE), DIV_CODE CHAR(8 BYTE), LOT_CODE CHAR(20 BYTE), UPDATED CHAR(1 BYTE))I have the following query which works correctly but EXPLAIN PLAN is telling me that it requires a double table scan, which I'm trying to avoid.Query:SELECT tot.run_num, tot.whse_code, TRUNC(tot.count_date) AS Count_Date, CAST((vary.Variance_Count / COUNT(tot.item_num) * 100) AS DECIMAL(10,2)) AS Percentage_Count_Variance, CAST((vary.Variance_Cost / SUM(tot.snap_cost * tot.on_hand) * 100) AS DECIMAL(10,2)) AS Variance_Percentage, CAST(vary.Variance_Cost AS DECIMAL(10,2)) AS Total_Value_VarianceFROM run_d totJOIN (SELECT run_num, COUNT(item_num) AS Variance_Count, SUM(snap_cost * (counted_oh - on_hand)) AS Variance_Cost FROM run_d WHERE counted_oh - on_hand != 0 GROUP BY run_num) vary ON tot.run_num = vary.run_num WHERE TRUNC(tot.count_date) BETWEEN TO_DATE('07/01/2014','MM/DD/YYYY') AND TO_DATE('07/21/2014','MM/DD/YYYY')GROUP BY tot.run_num, tot.whse_code, vary.Variance_Count, vary.Variance_Cost, TRUNC(tot.count_date)ORDER BY tot.whse_code, tot.run_numIs there a more efficient way that I can write this query, most specifically to avoid the double table scan?
Trying to avoid a double full scan with aggregates in query
sql;oracle
No, I cannot see a better way. The group-by constraints are different for the selects, so there is no way to merge them in to one.The remainder of your code looks good, except I am concerned about your % calculations.... are they accurate?(vary.Variance_Count / COUNT(tot.item_num) * 100) AS DECIMAL(10,2)That looks like it will be integer arithmetic all the way through, I would instead write it as:(100.0 * vary.Variance_Count / COUNT(tot.item_num)) AS DECIMAL(10,2)
_webapps.89363
Whenever I type something resembling a URL (for example asp.net) at twitter.com, it automatically converts it into a real link. Is there a way to 'escape' this conversion if I want it to remain plain text?
How to NOT create a link in a tweet
twitter
The only practical way I've found is to munge the URL in some way. Enclosing in single-quotes, double-quotes, parentheses, brackets, braces, backticks, etc., has no effect.The classic way is to escape the dot character: asp[dot]net.Adding a couple of extra spaces around the dot would also do the trick: asp . net.If you can manage to insert a zero-length character (such as U+200B) in the string, that should do the trick as well. (Alt+08203 seems to work on Windows.)The only other way I can see to make this happen is to use a third-party Twitter client. Then again, the API may convert the URL-like strings to URLs on the server side anyway.
_unix.235737
AUR is said the largest repository out there but sometimes, when trying to build and install, and also to build and install dependencies, the outcome is not always a success. What a medium user can do at that point?Normally (that is, for a ubuntu user) , the idea is to build and install from source. That is temerary enough endeavour for me - but how can I try to fix what the automated Pamac/pacman could not?
AUR package cannot be built and installed - what to do?
arch linux;compiling;pacman;manjaro;aur
The AUR is an unsupported repository: the quality of the PKGBUILDS varies from the very good through to the abominably bad or outright negligent.You should always read the PKGBUILD before attempting to install anything and look at the comments on the package page to satisfy yourself that there won't be any unforseen surprises when running makepkg.You should also not get in the habit of relying on an AUR helper to automate the build process for you and thereby blur the distinction between the officially supported repositories and the AUR.If a particular PKGBUILD does not build successfully, the first step is to try and build it manually: makepkg will provide meaningful error messages that should provide sufficient information to identify the issue.Arch Linux is not like Ubuntu: users are expected to be able to read PKGBUILDs (basic bash scripts, essentially) and the man page for makepkg and understand the build process sufficiently to responsibly maintain their installations.If the fault lies with the PKGBUILD, leave a comment to that effect on the package's AUR page to alert the maintainer and anyone else who may want to install the same package. If the issue goes unaddressed, you can always ask to have the package orphaned, then adopt it and fix the PKGBUILD so that it works as expected.There are guidelines for maintaining packages on the Arch Wiki.
_webmaster.24593
I have a website where users register domain.com/user/username. I'd like to add a feature where users can search for and purchase a domain name that maps back to that URL.I'm not sure how big of a task this is - can anyone provide an explanation of what's involved?
Process of automating domain registration?
domains;dns;url
You'd have to either resell domain registrations, hook into a registrar's API, or become ICANN-accredited (which costs thousands of dollars I believe) - the most practical option would be to find a good, ICANN-accredited registrar (such as name.com or Namecheap or Enom) and use an API.For example, Namecheap.com has a developer's API that will let you register and manage domains:http://www.namecheap.com/support/api/api.aspx?sflang=enI should point out that APIs like this will register domains to YOUR account, not your customer's individual accounts. So if you secure payment from the customer first, you can register the domain to your (business?) account on a registrar automatically via an API. Then, you can use the same API to manage the domain's settings, such as pointing to their URL on your site.For billing and payment, I'd look into Google Wallet or PayPal (or better yet, both). You just have to write code that receives some data from their checkout endpoints and do your own processing (save to a database, send confirmation emails, register the domain, etc).So, it's not too far-fetched. If you have some time and a little financial means (mostly to cover labor/coding costs) it should be fairly straightforward. Just find a developer who really knows what they're doing that you can trust (as always).
_unix.163101
Trying to install packages, and keep getting dependency errors.Already installed EPEL, IUS, REMI repos.Example:yum install gccand I get Error: Package: devtoolset-2-gcc-4.8.2-15.1.el6.x86_64 (slc6-devtoolset) requires: glibc-devel >= 2.2.90-12 (and other dependencies)and when I try to install glibc (or the other dependencies)yum install glibc-devel*I get no package glibc-devel* available. Nothing to do.yum list installed |grep glibc* does not show any glibc-devel installedRHEL Version = 2.6.32-358.el6.x86_64[root@localhost yum.repos.d]# yum repolist allLoaded plugins: product-id, refresh-packagekit, replace, security, subscription- : managerThis system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.repo id repo name statusInstallMedia Red Hat Enterprise Linux 6.4 disabledepel Extra Packages for Enterprise Linu enabled: 11,141epel-debuginfo Extra Packages for Enterprise Linu disabledepel-source Extra Packages for Enterprise Linu disabledepel-testing Extra Packages for Enterprise Linu disabledepel-testing-debuginfo Extra Packages for Enterprise Linu disabledepel-testing-source Extra Packages for Enterprise Linu disabledius IUS Community Packages for Enterpr enabled: 232ius-archive IUS Community Packages for Enterpr disabledius-archive-debuginfo IUS Community Packages for Enterpr disabledius-archive-source IUS Community Packages for Enterpr disabledius-debuginfo IUS Community Packages for Enterpr disabledius-dev IUS Community Packages for Enterpr enabled: 25ius-dev-debuginfo IUS Community Packages for Enterpr disabledius-dev-source IUS Community Packages for Enterpr disabledius-source IUS Community Packages for Enterpr disabledius-testing IUS Community Packages for Enterpr disabledius-testing-debuginfo IUS Community Packages for Enterpr disabledius-testing-source IUS Community Packages for Enterpr disabledpgdg93 PostgreSQL 9.3 6Server - x86_64 enabled: 256pgdg93-source PostgreSQL 9.3 6Server - x86_64 - disabledremi Les RPM de remi pour Enterprise Li disabledremi-debuginfo Les RPM de remi pour Enterprise Li disabledremi-php55 Les RPM de remi de PHP 5.5 pour En disabledremi-php55-debuginfo Les RPM de remi de PHP 5.5 pour En disabledremi-php56 Les RPM de remi de PHP 5.6 pour En disabledremi-php56-debuginfo Les RPM de remi de PHP 5.6 pour En disabledremi-test Les RPM de remi en test pour Enter disabledremi-test-debuginfo Les RPM de remi en test pour Enter disabledrhel-source Red Hat Enterprise Linux 6Server - disabledrhel-source-beta Red Hat Enterprise Linux 6Server B disabledrpmforge RHEL 6Server - RPMforge.net - dag enabled: 4,718rpmforge-extras RHEL 6Server - RPMforge.net - extr disabledrpmforge-testing RHEL 6Server - RPMforge.net - test disabledslc6-devtoolset Scientific Linux CERN 6 (SLC6) - D enabled: 458slc6-devtoolset-debug Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-source Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-testing Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-testing-debug Scientific Linux CERN 6 (SLC6) - D disabledslc6-devtoolset-testing-source Scientific Linux CERN 6 (SLC6) - D disabledslc6-os Scientific Linux CERN 6 (SLC6) bas disabledwebtatic Webtatic Repository 6Server - x86_ enabled: 383webtatic-debuginfo Webtatic Repository 6Server - x86_ disabledwebtatic-source Webtatic Repository 6Server - x86_ disabledrepolist: 17,213
Can't install any packages on RHEL because of dependancies
rhel
You should be installing the gcc package from slc6-os.repo or slc6-updates.repo Then the dependancies will be provided from there too rather than using the devtoolset version.Yum Repositories Entries/etc/yum.repos.d/slc6-os.repo/etc/yum.repos.d/slc6-updates.repo/etc/yum.repos.d/slc6-extras.repoInstallation instructionsLocation:slc6-os.reposlc6-updates.reposlc6-extras.repoImport the GPG key:rpm --import http://linuxsoft.cern.ch/cern/slc6X/x86_64/RPM-GPG-KEY-cern
_cs.16744
Let $S$ be a set of $n$ integers. Consider the following weighted permutations problem.Let $m<n$ be an integer. What is an efficient algorithm to enumerate all subsets of $m$ integers of $S$ such that they are listed in order of the sum of the integers in each subset?Each subset is a permutation, and each permutation has a total weight that is the sum of the integers in the permutation.The idea is to come up with an algorithm that is not the trivial algorithm of enumerating all subsets, and then sorting them, i.e. more of a streaming type algorithm. That is, efficiency in terms not so much of time but of small space.Maybe this is published somewhere in the literature although I have not seen it.
Enumerating weighted permutations in sorted order problem
algorithms;reference request;sorting;efficiency;enumeration
null
_softwareengineering.66389
I wasn't sure if this was more suited to here or StackOverflow. I've always resisted doing web development because the technology stack just seemed a mess. It seems the web has become quite popular so I'm actually going to embrace web development, at least for a little project I'm thinking about.I'm a Microsoft developer, so I'm going to use ASP.NET. I'm familiar with how the web technologies work at a high level, I sort of understand what Javascript can do, I get AJAX (conceptually). CSS and HTML seem ugly but I get what they're for.As an ASP.NET developer do you find yourself working directly with Javascript or HTML? Does AJAX get abstracted away neatly or do you find yourself doing that stuff by hand? Are there any other technologies you use?And on a related note, I don't quite see where HTML 5 fits in with ASP.NET, yet. There seems to be a lot of noises from Microsoft that HTML 5 is actually the future of the web as opposed to Silverlight, so do any pro ASP.NET developers understand or use HTML 5 features?I appreciate that's kinda vague, I think a lot of it will become clearer as I get started, but I'd feel more secure if I had some soothing words and pointers from people who have already been through that.
If you develop with ASP.NET, which other technologies do you use?
asp.net
First thing to understand is that ASP.Net is a server-side programming API. When you develop with ASP.Net you are writing a .Net program that runs on a server and ultimately serves HTML/CSS/Javascript code over the internet to a web browser. Then the web browser parses that code and displays the output.That being the case, I don't think you should look at HTML/CSS/Javascript as something to be abstracted away from you. The ASP.Net Web Forms model was originally designed with this goal in mind, but in practice it does not work well because the output is bloated, ugly code which is difficult to maintain and does not conform well to web standards.This is why there has been a shift away from that model with the ASP.Net MVC Framework, where you are encouraged more than ever to write that code by hand. This is so you can have full control over the HTML/CSS/Javascript that is sent to the browser. Also, with this understanding, HTML 5 fits into the picture perfectly fine.
_codereview.153291
I have some coordinates looking likeN47 15' 36.75,E011 20' 38.28,+001906.00and I've created a class to parse and convert them to Double:struct PLNWaypointCoordinate { var latitude: Double = 0.0 var longitude: Double = 0.0 init(coordinateString: String) { self.latitude = convertCoordinate(string: coordinateString.components(separatedBy: ,)[0]) self.longitude = convertCoordinate(string: coordinateString.components(separatedBy: ,)[1]) } private func convertCoordinate(string: String) -> Double { var separatedCoordinate = string.characters.split(separator: ).map(String.init) let direction = separatedCoordinate[0].components(separatedBy: CharacterSet.letters.inverted).first let degrees = Double(separatedCoordinate[0].components(separatedBy: CharacterSet.decimalDigits.inverted)[1]) let minutes = Double(separatedCoordinate[1].components(separatedBy: CharacterSet.decimalDigits.inverted)[0]) let seconds = Double(separatedCoordinate[2].components(separatedBy: CharacterSet.decimalDigits.inverted)[0]) return convert(degrees: degrees!, minutes: minutes!, seconds: seconds!, direction: direction!)} private func convert(degrees: Double, minutes: Double, seconds: Double, direction: String) -> Double { let sign = (direction == W || direction == S) ? -1.0 : 1.0 return (degrees + (minutes + seconds/60.0)/60.0) * sign }}Is there a better and safer way to perform this conversion?Last method I've picked up here. Sorry, but I can't find the link to reference it.
Parsing and converting DMS Coordinates from String to Double
swift;unit conversion
You have defined a value type (struct) and not a class, which is good. Invar latitude: Double = 0.0var longitude: Double = 0.0you can omit the type annotations because the compiler can infer thetype automatically:var latitude = 0.0var longitude = 0.0But actually I would go the other way around and replace the initialvalues by an init() method. The reason is that since you definedyour own init method there is no default memberwise initializer anymore.Therefore I would start withstruct PLNWaypointCoordinate { var latitude: Double var longitude: Double init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude } // ...}which allows you to create a value not only from a string, butalso from a given latitude and longitude:let c = PLNWaypointCoordinate(latitude: ..., longitude: ...)Your init(coordinateString: String) method assumes that the givenstring is in a valid format and can crash otherwise (by accesssingout-of-bounds array elements or unwrapping nils). As@Ashley already said in his answer, you should define a failable initializer instead, which returns nil if the input isinvalid:init?(coordinateString: String) { ... }Alternatively, define a throwing initializer:init(coordinateString: String) throws { ... }which throws an error for invalid input. Your helper methods convertCoordinate and convert are private,which is good. They do not use any properties of the value, which meansthat they can be made static.The conversion helper function is very lenient, it will for exampleaccept X47 15 36.75 instead of N47 15' 36.75 as latitude. It does not check that the coordinate starts witha valid direction, or that the proper separators are used.I don't know what the final part +001906.00 stands for, but thatis ignored completely in your code.There is also a flaw in your conversion, the fractional partof the seconds is ignored, e.g. 36.75 is taken as 36 seconds.I would suggest to use Scanner instead, which makes it relativelyeasy to check for a valid input and simultaneouslyparse the values into variables. To distinguish between latitude and longitude, two arguments for the positiveand the negative direction are passed to the helper method.The complete code then looks like this:struct PLNWaypointCoordinate { var latitude: Double var longitude: Double init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude } init?(coordinateString: String) { let components = coordinateString.components(separatedBy: ,) guard components.count >= 2, let latitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[0], positiveDirection: N, negativeDirection: S), let longitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[1], positiveDirection: E, negativeDirection: W) else { return nil } self.init(latitude: latitude, longitude: longitude) } private static func convertCoordinate(coordinate: String, positiveDirection: String, negativeDirection: String) -> Double? { // Determine the sign from the first character: let sign: Double let scanner = Scanner(string: coordinate) if scanner.scanString(positiveDirection, into: nil) { sign = 1.0 } else if scanner.scanString(negativeDirection, into: nil) { sign = -1.0 } else { return nil } // Parse degrees, minutes, seconds: var degrees = 0 var minutes = 0 var seconds = 0.0 guard scanner.scanInt(&degrees), // Degrees (integer), scanner.scanString(, into: nil), // followed by , scanner.scanInt(&minutes), // minutes (integer) scanner.scanString(', into: nil), // followed by ' scanner.scanDouble(&seconds), // seconds (floating point), scanner.scanString(\, into: nil), // followed by , scanner.isAtEnd // and nothing else. else { return nil } return sign * (Double(degrees) + Double(minutes)/60.0 + seconds/3600.0) }}
_unix.204241
I recall that X11 provided a number of fun programs accessible via unix. For instance, if you use the command xeyes, an interface will pop up of cartoon-like eyes which follow your cursor everywhere. This still works on my most update version of X11. But I remember so many more of these fun little commands. For instance, there is:(A) xsnow which causes snow to fall on your desktop, with the santa option(B) xsol which would begin a solitaire GUI you could interact with (C) xmille was something similar, and allow you to play the game Mille Borne(D) xroach caused cockroaches to crawl all over your screen, with the squish option allow you to click/squish these buggers(E) xphoon would show the moon as it appears today(F) xpenguins has penguins appear(G) oneke had something to do with cats and dogsQuestion 1: Does anyone else still use these? The only command which still works for me is xeyes. Which updates do I need to use the others? Question 2: Have I forgotten any of these types of X11 commands?
X Windows special programs: do some of these still exist?
linux;x11
If you are using a debian-derivative (debian, ubuntu, linux mint), you can use the commandapt-cache search xmilleto search for any of these. Then, useapt-get install xmille(or the given package name). This works with xpenguins, too, but for example not with oneke.
_softwareengineering.332751
I've moved this from Stack Overflow and this was the suggested place to ask. This has been marked as a possible duplicate of a question about the merits of composition over inheritance. I'm not asking that question, I'm looking for strategies to manage development given the code we have. The context of the question is a set of applications written in C++ with Qt. We work in a pseudo agile manner, i.e. we have 2 week sprints but don't have frequent releases.They are all variations of a theme but each modifies the one before it.This is not an ideal scenario but what I have to work with.So application A uses Alib. application B uses Blib and Alib; most of the classes in Blib are descendents of those in Alib. Similarly application C uses Alib Blib and Clib, which subclasses from Blib primarily but also occasionally Alib.We use CVS and it is a proper pain in the neck to branch our builds as the MSVC projects never merge correctly.What currently happens is a developer working on Alib can cause unforeseen issues in both Blib and Clib unless we adopt some strategy for review or rules on development.We are under a lot of time pressure and don't currently have the time to reorganise the code, so I am looking for things we can do within the current framework.If we were using git it would be easier to branch the code for each dev but again we're not currently there just yet (it is in the pipeline).I'm thinking along the lines of requiring all new developments which alter (as opposed to add) functionality in ALib to subclass that behaviour.Other options I've read about include fail often i.e. being brash about committing/changing the stuff in Alib and make sure that Blib and Clib are review often enough to keep up with the changes.Similar to this is frequent code reviewing (one developer (me) has good knowledge of all three libs so should be able to spot potential downstream effects early), which begs the question pre or post commit.Edit: Thanks for the broad range of solutions, I wish I could mark a couple of these as answers, but have gone with John W'us answer. He's articulated my dilemma quite well in the third point - trying to reduce repeating ourselves (i.e. don't violate DRY) while having some isolation for each lib. Ultimately a code refactor is in order, but more (some!) unit tests should highlight broken code. One issue we've had is that the developer in Alib would see their changes affecting Blib and Clib and go and change those in ways the developers of Blib and Clib didn't exactly appreciate. So a rule about keeping code closed (extend but don't modify) is also very pertinent.
How to prevent downstream problems due to inheritance
c++;agile;inheritance;maintainability
Three options for youFollow the Open/Closed PrincipleFrom a code and process management perspective, getting a teamwide agreement to adhere to the Open/Closed Principle should help resolve the problem.If you are able to get everyone to follow this principle pretty strictly then it may be all that you need to do.Continuous integration builds with automated unit testsDevelop an automated continuous build process in which ALib, BLib, and CLib are built whenever any of them change.Develop a suite of automated unit tests that execute as part of the build. If any of the tests fail, the build should fail.Publicly shame anyone who breaks the build..Use interfaces insteadIf you cannot help yourself and ALib needs to be able to be modified all the time, then perhaps you should move away from implementation inheritance and stick strictly with interface inheritance, as follows:Develop a new lib, call it ILib. This library should contain zero implementation code and should only contain interface definitions.Remove the inheritance relationship between ALib, BLib, and CLibAdd an interface relationship between ALib->ILib, BLib->ILib, and CLib->ILibFreeze ILibThat way, any implementation changes in ALib will have zero impact on BLib and CLib.The drawback is that you may end up duplicating a lot of code, i.e. violate DRY.
_webmaster.47885
I want to set up a Google Analytic's Experiment to test variations of product page. Parts of the URL changes depending on what product you are viewing - here are some examples...domain.com/products/shirt/100domain.com/products/pants/200domain.com/products/hat/300I want to experiment on everything that comes after /products/.How can I set this up as an experiment? Do I just input domain.com/products/? Or do I add some fancy regular expression magic?... Is this at all possible, or do Experiments only apply to static pages? If that's the case; what alternatives are there out there?
Google Experiments & dynamic URLs
google analytics
null
_webapps.50047
Im using importdata to retrieve Yahoo stock information, which works fine on individual rows, but when combined with arrayformula to fill down the page when additional symbols are added does not initiate continue. The formula I'm using is:=arrayformula(ImportData(http://finance.yahoo.com/d/quotes.csv?s=&CONCAT(A2:A,B2:B)&&f=snk2l1jkm3m4))A2:A contains the stock codesB2:B contains the exchange code, e.g., .ax for Australia
Use of importdata with arrayformula
google spreadsheets;formulas
null
_unix.260409
For my i3 window-manager settings, I am looking for a command line tool, similar to xbacklight, but to control the brightness of the leds which are in the keyboard.Basically, I can set up the leds through a command line, but it requires to be root:# Light off the ledsecho 0 > /sys/class/leds/smc::kbd_backlight/brightness# Light on the leds (full power)echo 100 > /sys/class/leds/smc::kbd_backlight/brightnessI know that it is possible because Gnome3 has support for that, but I do not know exactly how they proceed...For now, my ~/.config/i3/config looks like this:# screen brightness controlsbindsym XF86MonBrightnessUp exec xbacklight -inc 10bindsym XF86MonBrightnessDown exec xbacklight -dec 10# keyboard backlight controls#TODO# XF86KbdBrightnessUp# XF86KbdBrightnessDownSo, is there a tool, similar to xbacklight to do the same than screen brightness with keyboard backlight? It would be even better if this tool would have the control on both (screen and keyboard).
Set bindings in i3 to control keyboard backlight
i3;backlight;keyboard backlight
You could write your own pretty easily.Create two shell scripts containing the echo lines above somewhere in your path (/usr/local is the normal place). Set the permissions 755 owned by root. Then either edit your sudoers file to allow them to be run as root, or use chmod +s to set them SUID.This sort of thing is considered a security risk, BTW, so make absolutely sure the permissions are set appropriately. You don't want anyone without root permissions to be able to edit the scripts, and you don't want the scripts to use any input.It would be trivial to add support for a brightness level flag, but unless you're an accomplished shell scripter I'd recommend against it as a bug in your code would be a security hole.
_unix.315243
I have a LENOVO Ideapad 300-14IBR 80M2.The basic debian install failed on me. (many problems : wifi, suspend, gpu, various crashes...)I randomly used jessie-backport and non-free, compiling and installing some linux kernels as well.#dpkg --list | grep linux-imageii linux-image-3.16.0-4-amd64 3.16.36-1+deb8u1 amd64 Linux 3.16 for 64-bit PCsii linux-image-4.2.1-040201-generic 4.2.1-040201.201509211431 amd64 Linux kernel image for version 4.2.1 on 64 bit x86 SMPii linux-image-4.4.13 1.0.NAS amd64 Linux kernel binary image for version 4.4.13ii linux-image-4.5.0-0.bpo.2-amd64 4.5.4-1~bpo8+1 amd64 Linux 4.5 for 64-bit PCsii linux-image-4.6.0 1.0.NAS amd64 Linux kernel binary image for version 4.6.0ii linux-image-4.6.0-0.bpo.1-amd64 4.6.3-1~bpo8+1 amd64 Linux 4.6 for 64-bit PCsii linux-image-amd64 3.16+63 amd64 Linux for 64-bit PCs (meta-package)With linux-image-4.2.1-040201-generic the GPU is working a little. (less charge on cpu on video play... but suspend, hibernate just crash the computer)I obviously have no idea what I am doing, but it's a good time for me to learn.My main problem is with my GPU : #lspci -vnn | grep VGA 00:02.0 VGA compatible controller [0300]: Intel Corporation Atom/Celeron/Pentium Processor x5-E8000/J3xxx/N3xxx Integrated Graphics Controller [8086:22b1] (rev 21) (prog-if 00 [VGA controller])How can i find the best kernel for my system based on a specific hardware ?Do I need to compile it myself or is there a trustable kernel source with a gpu/driver inside ?now my /etc/apt/sources.list :deb ftp://ftp.debian.org/debian stable main contrib non-freedeb http://httpredir.debian.org/debian/ jessie main contrib non-freedeb http://ftp.debian.org/debian jessie-backports main contrib non-freeThanks.
Looking for match between my laptop and linux kernel
debian;linux kernel
null
_codereview.104804
I have this array within array which contains a lot of values: 183 => array (size=3) 0 => string 'DE' (length=2) 1 => string '2015-06-09' (length=10) 2 => string 'GK' (length=2) 184 => array (size=3) 0 => string 'DE' (length=2) 1 => string '2015-06-08' (length=10) 2 => string 'GL' (length=2) 185 => array (size=3) 0 => string 'FR' (length=2) 1 => string '2015-06-09' (length=10) 2 => string 'GN' (length=2) 186 => array (size=3) 0 => string 'FR' (length=2) 1 => string '2015-09-08' (length=10) 2 => string 'GO' (length=2)0 is the country code. 1 is a date. 2 is a column on an Excel file. I want to organize it in this way: 2015-06-09 => array (size=3) DE => array (size=2) column => GK download => 666 FR => array (size=2) column => GN download => 777 2015-06-08 => array (size=3) DE => array (size=2) column => GL download => 666 FR => array (size=2) column => GO download => 777 So the same date can show up more than once. if it gets to an array value with the same date - it inserts in it the country code with and its' column. if it has more than 1 country - it adds a new country. (with the 'download' and column values). I have this function: function get_cols_to_array_by_date($array) { $mainarr = array(); $last_in_arr = count($array); for ($i=0; $i<$last_in_arr; $i++){ $mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) ); } return $mainarr;}which outputs an array that runs over the country when it gets to the same date and doesn't give me an array of countries. What part am I missing in my code? Is there a simpler way to do it? ( PHP syntax shortcuts ;) )
Reorganizing a PHP array structure (arrays within arrays)
php;array;php5
WhyYou're replacing the indexed item for the date when you declare a new array in the line:$mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) );See it as $array[$index] = array(...) -- running it again over the same index would replace the value at that index.Quick FixYou could simply replace that line with (considering that there'll not be more than one line for a given country, for the same date, as in: no two DE for 2015-06-08):if (!isset($mainarr[$array[$i][1]])) { $mainarr[$array[$i][1]] = array(); }$mainarr[$array[$i][1]][$array[$i][0]] = array('downloads'=> 666, 'col'=>$array[$i][2]);Note that $array[$i][0] (aka the country) moved to the left site of =, and the outer array on the right side of it was removed.How would I doI refactored the code to be more legible and easier to understand, and also use better practices IMHO:function get_cols_to_array_by_date($array) { // set the name of the variable to a more meaningful one $result = array(); foreach ($array as $i => $data) { // shortcuts to prevent having to remember which index they are (you could change them for constants) $country = $data[0]; $date = $data[1]; $col = $data[2]; $download = 123; // don't know where 'download' value comes from, put it here // you need to check if the date index already exists // if not, create the empty array for the date if (!isset($result[$date])) { $result[$date] = array(); } // considering that country will NOT repeat for a given date $result[$date][$country] = array( 'column' => $col, 'download' => $download, ); } return $result;}
_unix.193314
I installed Linux Mint 17.1 on VMWare Player 7.1.0 but when I try to reboot the system, it saysModemManager is shut downand in the next line, it saysnm-dispatcher.action: Could not get the system bus. Make sure the message bus dameon is running! Message: Failed to connect to socket /var/run/dbus/system_bus_socket: No such file or directoryBefore this I renamed the file org.freedesktop.ModemManager1.service to thisfilebreaksmycomputer.service from /usr/share/dbus-1/system-services following this link Ubuntu 14.04 wont shutdown or reboot.I tried with different commands like sudo init 6, sudo reboot now, sudo shutdown now but all the same.Any suggestions please?
Unable to reboot or shutdown Linux Mint 17.1 on VMWare Player
linux mint;reboot
null
_webmaster.76510
On my side, I use bootstrap modals (aka dialogs / overlays) with remote content to display the detail view of some things (for example for detail view of user reviews/comments).The code looks like this:<a data-toggle=modal href=/detail-12.html data-target=#myModal>Detail of this comment 12</a>Basically, when a user clicks on the link, bootstrap loads the content of the href and inserts it as an overlay to the page. Google and other SE follow the link, because its a normal link for them and they index the page. The problem:Since I only load the modal content (basically without <html><head>...etc.) without any site structure like header, navigation or sidebar, I have a useless page indexed. Since the aim of my question, wasn't clear enought, I had to change the question a little bit:At the moment, a normal user clicks on the link and sees a modal with the content <h1>Detail of Product 12</h1>. Thats fine and what I want!A non JavaScript User or Google Crawler would follow the link to /deatil-12.html and see a white, unstyled page without any navigation or footer, just with the content <h1>Detail of Product 12</h1>. This ugly page would be indexed by google. Thats bad, since if a user enters this page, he sees an ugly page and has no chance to reach other pages (since lack of navigation urls).What I wantI want, that a normal User sees the content inside a modal (like know). And a non JS User (incl. Google) sees the content inside my normal page structure <html><head>...</head><body><nav>My cool navigation</nav><h1>Detail 12</h1><p>Some content...</p><footer>My cool footer</footer></body></html>.I know, how to reach this technically (by adding a param on-click to the url. If this param is set, I will return the modal content only. If this param is not set (No JS = No Click-Event), I will return the complete HTML page including header, footer, navi, etcMy questionWill Google punish me for that or is it OK for Google?
URLs for dialogs from Bootstrap modals popups are getting indexed in search engines, but without nav they aren't good landing pages
google;googlebot;bootstrap
null
_datascience.11413
How do we calculate monthly rolling average? I have monthly 2 years of data . I know that if it is 2 months rolling average ,we need to take the average of every 2 months . But since I need monthly rolling average,I am assuming that it would just be the mean of each month and prepare a chart having means of each month . Please correct me if I am wrong..I need to show this in R.
Time series_Calculation of monthly rolling average
r;time series
null
_unix.159686
I want to replace now within my working directories the word -> with $\to$ if the word is not within verbatim environment.PseudocodeReplace all entriens of -> with $\to$ everywhere else but not within \begin{verbatim}...\end{verbatim}.My perl pseudocode based on this excellent answer#!/usr/bin/env perl## The target directoriesmy @directories=(Cardiology, Pathophysiology, Patology and Biopsy, Physiology, Propedeutics, Radiology, Rheumatology, Surgery);## Iterate over the directoriesforeach my $dir (@directories) { my $dd=0; ## Read the current directory opendir (my $DIR, $path/$dir); ## Find all files in this directory while (my $file = readdir($DIR)) { ## Skip any files that aren't .tex next unless $file =~ /\.tex$/; ## Open the file open(my $fh,$path/$dir/$file); while (<$fh>) { if (/\\begin{verbatim}/) { # Skip the Verbatim environment # TODO how this? # Need to tell it that you one line by one until \end{verbatim} is met, after which go normally forward. while (!/\\end{verbatim}/) { $dd++; } $dd++; } else { if ($dd==0) { $dd++; # I think we need this here to go one line after another } $string =~ s/->/$\to$/g; } } print \n; }where I am not sure about the innermost pseudocode in while -loop: while (<$fh>) { if (/\\begin{verbatim}/) { # Skip the Verbatim environment # TODO how this? # Need to tell it that you one line by one until \end{verbatim} is met, after which go normally forward. while (!/\\end{verbatim}/) { $dd++; } $dd++; } else { if ($dd==0) { $dd++; # I think we need this here to go one line after another } $string =~ s/->/$\to$/g; } }How can you write such a pseudocode with condition?
How to write this replacement with condition
text processing;scripting;perl;latex
Assuming your shell is bash, this can be a one-liner:perl -i.bak -pe ' /\\begin\{verbatim\}/../\\end\{verbatim\}/ or s/->/\$\\to\$/g' {Cardiology,Pathophysiology,Patology and Biopsy,Physiology,Propedeutics,Radiology,Rheumatology,Surgery}/*.texNote that {...} is a regex quantifier, so the braces need to be escaped.I'd write your code as:my @directories=( Cardiology, Pathophysiology, Patology and Biopsy, Physiology, Propedeutics, Radiology, Rheumatology, Surgery);chdir $path or die cannot chdir '$path';foreach my $dir (@directories) { opendir my $DIR, $dir or die cannot opendir '$dir'; while (my $file = readdir($DIR)) { my $filepath = $dir/$file; next unless -f $filepath and $filepath =~ /\.tex$/; open my $f_in, <, $filepath or die cannot open '$filepath' for reading; open my $f_out, >, $filepath.new or die cannot open '$filepath.new' for writing; while (<$fh>) { if (not /\\begin\{verbatim\}/ .. /\\end\{verbatim\}/) { s/->/\$\\to\$/g; } print $f_out; } close $f_in or die cannot close '$filepath'; close $f_out or die cannot close '$filepath.new'; rename $filepath, $filepath.bak or die cannot rename '$filepath' to '$filepath.bak'; rename $filepath.new, $filepath or die cannot rename '$filepath.new' to '$filepath'; } closedir $DIR or die cannot closedir '$dir';}I'd continue to make it more OO:use autodie qw(:io);use Path::Class;foreach my $dir ( Cardiology, Pathophysiology, Patology and Biopsy, Physiology, Propedeutics, Radiology, Rheumatology, Surgery) { my $directory = dir($path, $dir); while (my $file = $directory->next) { next unless -f $file and $file =~ /\.tex$/; my $f_out = file($file.new)->open('w'); for ($file->slurp) { /\\begin\{verbatim\}/ .. /\\end\{verbatim\}/ or s/->/\$\\to\$/g; $f_out->print; } $f_out->close; rename $file, $file.bak; rename $file.new, $file; }}
_softwareengineering.304168
I'm currently working on a project which only uses its database for data storage. This means there are no triggers or stored procedure in it, just tables and data to put into it. In this scenario I'm building the application using Spring 4. The Spring container allows you to have profiles, which basically decide which beans get loaded in your project. You can make sure an embedded in-memory database or a full-fledged oracle database is used for data storage, without having to change a single thing in your code.This is obviously using for unit and integration testing. Not having to rely on a database is great for your tests. I was wondering if the same doesn't count during development. In this specific project I'm not entirely sure about what my final data model will look like, and because I don't feel like writing SQL over and over to move columns I'd prefer to use some kind of in-memory database. Of course one with pre-filled development data, so I can mimic a system that's been filled with all kinds of data, and I can easily add more for small tests during development.Is this a recommended practice or inherently bad in a way?
Is it a good practice to have a pre-filled embedded database for development?
database;database design;development process;database development
null
_unix.256083
On a CentOS 7 server, I have installed PHP from remi repository. I need to connect to Oracle 9.2 on a remote machine. Installing oci8 via yum install oci8 results OCI8 Version 2.1.0 which is not compatible with Oracle 9.2. The following is from the phpinfo output. OCI8 Support enabledOCI8 DTrace Support enabledOCI8 Version 2.1.0Revision $Id: 8e84657b6fdeaa913819689ef327ad2808110ed4 $Oracle Run-time Client Library Version 12.1.0.2.0Oracle Compile-time Instant Client Version 12.1Trying to install an earlier version using pecl install oci8-1.4.10 fails as well: In file included from /var/tmp/oci8/oci8.c:58:0:/var/tmp/oci8/php_oci8_int.h:56:17: fatal error: oci.h: No such file or directory #include <oci.h> ^compilation terminated.make: *** [oci8.lo] Error 1ERROR: `make' failedWhat should I do to install oci8 version 1.*?
Installing oci8 php extension
centos;php
null
_unix.81858
I have a 16 GB USB flash drive that I would like to install CentOS 6 on so that I can boot into it on other computers. The reason for this is because I am going to be upgrading to VPS hosting and I would like to recreate the environment so that I can have a production website and simply sync it to live site. However, for various reasons, I don't want to be tied to one computer.I have tried using LinuxLive USB Creator, which worked absolutely perfectly, apart from even though I set the persistent file to the maximum when I installed packages they weren't there after a reboot.I did install CentOS on an old laptop, if that will allow me to install CentOS on the flash drive somehow? Alternatively, would it install on an external hard drive? Do computers boot from external harddrives?
Run CentOS 6 from a USB flash drive
centos;usb;flash memory
Passing expert on the installer command line will tell it to enable installing to devices other than internal drives.
_cs.35944
I'm reading about a Turing Machine $M$ and it says the problem of deciding whether M accepts a string is $\Sigma^0_2$-hard and $\Pi^0_2$-hard.I haven't seen this kind of notation before and haven't found a good answer from searching. Is this a more specific form of saying NP-hard?
What does $\Sigma^0_2$-hard and $\Pi^0_2$-hard for a TM's Acceptance Problem mean?
turing machines;np complete;np hard
No, it's unrelated to NP-hardness. $\Sigma_n^0$ and $\Pi_n^0$ are the levels of the arithmetical hierarchy. $\Sigma_2^0$ is the class of problems that can be decide by Turing machines that have an oracle for the halting problem and $\Pi_2^0$ is the class of problems whose complement is in $\Sigma_2^0$.There is the corresponding notion of the polynomial hierarchy, in which $\Sigma_1^\mathrm{P}$ is NP and $\Pi_1^\mathrm{P}$ is co-NP.
_cs.18757
There seems to be a classification of processes in IT. For example, business process refers to the collection of tasks done by organization members / software systems to achieve a goal.If a process is completely automated and carried out by software (no people involved) what is the process called? Say we have a Web service A and service B online and we have a process that automatically uses both in achieving a goal.I googled for Software process but the results are not what I am looking for (e.g waterfall)My apologies if this is not the correct forum to ask this question.Thanks in advance
Process Types and names
software engineering
Business process can also be applied. Or you could call it automated process or automated business process or software processing or service or any of a number of other things.In other words: these terms do not have a precise mathematical/technical definition. So, define your terms, and use them consistently. This is not a technical question (and this site is better-suited for technical questions, not terminology questions).
_unix.295607
I've noticed that some graphical file manages such as Thunar allow you to remove any directory as long as you are the owner of this directory -- even if this directory contains a sub directory which you do not have write access to. On the other hand, rm -rf won't allow you to delete such a directory (Permission denied).Example:dirOwnedByUserdirOwnedByRoot$ rm -rf dirOwnedByUser rm: cannot remove 'dirOwnedByUser/dirOwnedByRoot: Permission deniedCould some explain this to me?Is there a way to delete such a directory in Shell?
Removing directories: Shell vs. File Manager
shell;rm;file manager;thunar
null
_cs.33580
Let $k > 0$ be an integer.Define $A_n$ as follows:$$ A_n = \begin{cases} n & \text{if } n < k, \\ \sum_{i=0}^{k-1} i & \text{if } n = k \\ \sum_{i=1}^k A_{n-i} & \text{if } n > k. \end{cases} $$This looks much like Fibonacci, except it's linear up until the k-th term (so the G formula does not work). I am 99% sure there is a closed formula for this one, but can't seem to figure it out at the moment.Any pointers will be appreciated!
Is there a closed-form formula for this recursive sequence?
recurrence relation
null
_webapps.25041
When viewing a map, how can I remove the pink pointers? This is just for viewing the map in my browser, and not having them removed from Google Maps.
When viewing a map, how can I remove the pink pointers?
google maps
Mouse over the controls on the upper right of the map - it says satellite and possibly traffic. Other controls will roll out once you mouse over this area. You'll see a control that allows you to remove the search result from the map by 'unchecking' next to the business name or search term.
_softwareengineering.111380
When I previously asked what's responsible for slow software, a few answers I've received suggested it was a social and management problem:This isn't a technical problem, it's a marketing and management problem.... Utimately, the product mangers are responsible to write the specs for what the user is supposed to get. Lots of things can go wrong: The product manager fails to put button response in the spec ... The QA folks do a mediocre job of testing against the spec ... if the product management and QA staff are all asleep at the wheel, we programmers can't make up for that. Bob MurphyPeople work on good-size apps. As they work, performance problems creep in, just like bugs. The difference is - bugs are bad - they cry out find me, and fix me. Performance problems just sit there and get worse. Programmers often think Well, my code wouldn't have a performance problem. Rather, management needs to buy me a newer/bigger/faster machine. The fact is, if developers periodically just hunt for performance problems (which is actually very easy) they could simply clean them out. Mike DunlaveySo, if this is a social problem, what social mechanisms can an organization put into place to avoid shipping slow software to its customers?
How can dev teams prevent slow performance in consumer apps?
performance;ui
null
_unix.346600
Working on Red Hat Enterprise Linux Server release 7.3 (Maipo)yum list installed | grep sambasamba-client-libs.x86_64 4.4.4-9.el7 @rhel-7-server-rpmssamba-common.noarch 4.4.4-9.el7 @rhel-7-server-rpmssamba-common-libs.x86_64 4.4.4-9.el7 @rhel-7-server-rpmssamba-common-tools.x86_64 4.4.4-9.el7 @rhel-7-server-rpmssamba-libs.x86_64 4.4.4-9.el7 @rhel-7-server-rpmsHowever:$ service smb status$ Redirecting to /bin/systemctl status smb.service Unit smb.service could not be found.$ which samba$ /usr/bin/which: no samba in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)$ which smbd $ /usr/bin/which: no smbd in (/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin)Is samba installed or not on my system?Does the system not beeing activated (through subscription manager) have anything to do with samba not loading (although the pacakages seem to be installed)?
Samba on Red Hat 7.3 installation
rhel;yum;samba
In my installation i have this : yum list installed | grep sambasamba.x86_64 4.4.4-9.el7 samba-client-libs.x86_64 4.4.4-9.el7 samba-common.noarch 4.4.4-9.el7 samba-common-libs.x86_64 4.4.4-9.el7 samba-common-tools.x86_64 4.4.4-9.el7 samba-libs.x86_64 4.4.4-9.el7 I think you need to install samba.x86_64.
_cstheory.14648
I don't exactly know if this is the place to ask it, but I'm looking for the original paper of the Moore Neighborhood algorithm. I need to make a reference to it (or whoever came up with it). I can't seem to find the origin, just other people using it. Does anyone have an idea what I need to cite for this ?
Initial paper of the Moore Neighborhood algorithm
graph algorithms
null
_softwareengineering.312875
I'm designing a NoSQL database schema - MongoDB in particular - and I'm wondering if it's a good idea not to embed certain one-to-one relationships.For one example, I have an accounts collection, which stores all the account information. The account balance requires some calculation to compute, and I see two options:Have a cached_balance field on the accounts collection, which starts off as null. Whenever the balance is recomputed, the field for the relevant account is updated.Have an account_balances_cache collection with a one-to-one relationship with accounts. Whenever the balance is recomputed, the relevant field in this collection is updated.The benefit of the embedded document is that I get all the information in one join. A separate collection would require an application-level join which is not as wieldy. However, the reason I thought of having a separate collection is because I like the conceptual separation of it. There is one collection for all the important data that must not be lost, and there's another with data that could be recomputed at any time, where the entire collection could be dropped and nothing of ultimate value will have been lost. Or it could even be in another database which could be kept on a different server, etc. Is this sound reasoning or am I just making it unnecessarily difficult for myself?(Note that this is a simplified example. In actuality the things in these caches may be hard/computationally expensive to compute, which is why I'm putting them in the database as well instead of something like redis or memcached.)
Is it a good idea not to embed certain one-to-one relationships in a Mongo database?
database design;language agnostic;mongodb
null
_codereview.162709
This class looks ugly as hell to me. I feel like there is a better way but can't really think for a good one. Too many instanceofs and else ifs. What OOP practices or design patterns would you suggest to change and improve the code?Any tips, advises and recommended resources are welcome!What does the code do: Basically, public method accepts event object and every event object contains user/player object in some form. The reason we are getting user object from the event is to check whether that particular user will receive notification about the event. Which of course depends on user's notification settings which is inside user object.I've added ENUM class, maybe there is a way to modify it for a better code quality.@Servicepublic class NotificationSettingsCheckServiceImpl implements NotificationSettingsCheckService {@Overridepublic Boolean checkIfEventCanPass(ApplicationEvent event) { if (SYSTEM_EVENTS.getListOfClasses().contains(event.getClass())) { return true; } Boolean eventPasses = false; LotteryUser user; user = event instanceof NotificationApplicationEvent ? getUserBasedOnNotificationEvent(event) : getUserBasedOnEmailEvent(event); if (CAMPAIGN_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getCampaignEvents()) { eventPasses = true; } else if (DRAW_RESULT_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getDrawResultEvents()) { eventPasses = true; } else if (TRANSACTION_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getTransactionEvents()) { eventPasses = true; } else if (USER_WON_EVENTS.getListOfClasses().contains(event.getClass()) && user.getNotificationSettings().getTransactionEvents()) { eventPasses = true; } return eventPasses;}private LotteryUser getUserBasedOnEmailEvent(EventObject event) { LotteryUser user = null; if (event instanceof UserThanksEvent) { user = ((UserThanksEvent) event).getUser(); } else if (event instanceof UserOrderCanceledEvent) { user = ((UserOrderCanceledEvent) event).getUser(); } else if (event instanceof DrawResultEvent) { user = ((DrawResultEvent) event).getPlayer(); } else if (event instanceof UserWinCongratulationEvent) { user = ((UserWinCongratulationEvent) event).getPlayer(); } else if (event instanceof UserAddedToCampaignEvent) { user = ((UserAddedToCampaignEvent) event).getLotteryUser(); } return user;}private LotteryUser getUserBasedOnNotificationEvent(EventObject event) { LotteryUser user = null; if (event instanceof UserReceivedBonusMoneyEvent) { user = ((UserReceivedBonusMoneyEvent) event).getLotteryUser(); } else if (event instanceof UserReceivedBonusInNonDepositCampaignEvent) { user = ((UserReceivedBonusInNonDepositCampaignEvent) event).getLotteryUser(); } else if (event instanceof UserReceivedBonusInDepositCampaignEvent) { user = ((UserReceivedBonusInDepositCampaignEvent) event).getLotteryUser(); } else if (event instanceof UserTakesPartInDepositCampaignEvent) { user = ((UserTakesPartInDepositCampaignEvent) event).getUser(); } else if (event instanceof UserTakesPartInNonDepositCampaignEvent) { user = ((UserTakesPartInNonDepositCampaignEvent) event).getUser(); } else if (event instanceof DrawResultNotificationEvent) { user = ((DrawResultNotificationEvent) event).getPlayer(); } return user; }}Here is the ENUM class I'm using. public enum NotificationSettingsType {SYSTEM_EVENTS(Arrays.asList(OnRegistrationCompleteEvent.class, ResetPasswordEvent.class, ManagerRegistrationEvent.class, DrawResultNotFoundEvent.class, CurrencyUpdatedEvent.class, WalletLockedEvent.class, UserWonBigPrizeEvent.class)),CAMPAIGN_EVENTS(Arrays.asList(UserReceivedBonusInDepositCampaignEvent.class, UserReceivedBonusInNonDepositCampaignEvent.class, UserReceivedBonusMoneyEvent.class, UserTakesPartInDepositCampaignEvent.class, UserTakesPartInNonDepositCampaignEvent.class, UserAddedToCampaignEvent.class)),DRAW_RESULT_EVENTS(Arrays.asList(DrawResultNotificationEvent.class, DrawResultEvent.class)),TRANSACTION_EVENTS(Arrays.asList(UserThanksEvent.class, UserOrderCanceledEvent.class)),USER_WON_EVENTS(Collections.singletonList(UserWinCongratulationEvent.class));private List<Class> listOfClasses;NotificationSettingsType(List<Class> listOfClasses) { this.listOfClasses = listOfClasses;}public List<Class> getListOfClasses() { return listOfClasses; } }Here are the Event Object example and the class that it extends. I have several of these depending on the event they notify. This is just an example. Using Lombok plugin for Getter/Setter annotations if that confuses anyone. @Getter @Setter public class UserReceivedBonusMoneyEvent extends NotificationApplicationEvent {private final LotteryUser lotteryUser;private final BigDecimal bonusAmount;private final String currency;public UserReceivedBonusMoneyEvent( LotteryUser lotteryUser, BigDecimal bonusAmount, String currency) { super(bonusAmount); this.lotteryUser = lotteryUser; this.bonusAmount = bonusAmount; this.currency = currency;}@Overridepublic void accept(NotificationEventVisitor visitor) { visitor.visit(this); } }And here is the NotificationApplicationEvent, which extends Spring framework's Application Event. public abstract class NotificationApplicationEvent extends ApplicationEvent {/** * Create a new ApplicationEvent. * * @param source the object on which the event initially occurred (never {@code null}) */public NotificationApplicationEvent(Object source) { super(source);}public abstract void accept(NotificationEventVisitor visitor);}And This is NotificationEventListener class where checkIfEventCanPass method is placed.@Component@Slf4jpublic class NotificationEventListener implements ApplicationListener<NotificationApplicationEvent> {@Autowiredprivate NotificationEventVisitor notificationEventVisitor;@Autowiredprivate NotificationSettingsCheckService notificationSettingsCheckService;@Overridepublic void onApplicationEvent(NotificationApplicationEvent event) { if (notificationSettingsCheckService.checkIfEventCanPass(event)) { event.accept(notificationEventVisitor); } }}
Notifying players about certain events
java;performance;object oriented;event handling
Boolean vs booleanPrefer to use the primitive type boolean instead of Boolean (The difference is, simply put, that Boolean can also be null).Varargs, defensive copyYou're passing a list of classes to your enum constructor. You could instead use varargs and pass Class... (or possibly Class<?>... although that might give you a warning, if so just ignore it). Then you can get rid of wrapping in Arrays.asList when calling the constructor and instead do it in the constructor itself.Also, don't return the list as it is, return a copy of it. Otherwise some calling code can do getListOfClasses().clear(); and screw up everything. In fact, all you really need is the contains method of the list, so skip the getListOfClasses method and make a contains method on your enum instead.Also, make listOfClasses final.Improved code:private final List<Class<?>> listOfClasses;NotificationSettingsType(Class<?>... classes) { this.listOfClasses = Arrays.asList(classes);}public boolean contains(Class<?> clazz) { return listOfClasses.contains(clazz);}Getting a user...Let the EventObject itself know how to get a user. Make a method somewhere, depending on your class heirarchy for your events, that returns a LotteryUser based on email or based on notification event. Then you can simply call this:private LotteryUser getUserBasedOnEmailEvent(EventObject event) { return event.getUserByEmail();}private LotteryUser getUserBasedOnNotificationEvent(EventObject event) { return event.getUserByNotification();}This removes the need for these methods completely. Depending on whether or not each EventObject really has multiple users, you could even do return event.getUser();
_codereview.45406
I want users to enter their code into my blog and keep original styling tags intact. So I had to develop a function that extracts user's code (between two tags) and convert special characters to HTML entities, then remove unwanted tags using purifyHTML.I want to know if it is safe to use it like that, and if there are any bad issues with this function.public function extracter($string, $start, $end){ function get_string_between($string, $start, $end){ $delimiters = array(); $ini = strpos($string,$start); if ($ini == 0) return FALSE; $delimiters['start'] = substr($string, 0, $ini); $ini += strlen($start); $last = strpos($string,$end,$ini); $len = $last - $ini; $delimiters['inside'] = substr($string,$ini,$len); $delimiters['end'] = substr($string, $last+strlen($end)); return $delimiters; } function reconstruct($strings = array(), $filter){ if( count($strings) == 0 || !$strings ) return false; $count = count($strings); $i = 0; $str = ''; $code = array(); $uniq = uniqid();//i create a unique key to prevent confusion if users insert the same token i'm using foreach ($strings as $key => $val) { $i++; foreach ($val as $k => $v) { if( $k == 'start' ) $str .= $v; if( $k == 'inside' ){ $str .= '['.$uniq.$i.']'; //creat a token in the string $code[$i] = htmlspecialchars($v); } if( $i == $count ) if( $k == 'end' ) $str .= $v; } } $purify = $filter->purifyHtml($str);//i'm using purifyhtml to remove undesirable tags and leave TinyMce tags for ($j=1; $j <= $i; $j++) { $purify = str_replace('['.$uniq.$j.']', $code[$j], $purify); //replace the token with the escaped code } return $purify; } /* main */ $string = .$string; $components = array(); $exists = TRUE; while ( $exists ) { $st = get_string_between($string, $start, $end);//decompose if token found if( !$st ) return $string;// return the original string if nothing found $string = $st['end']; $components[] = $st; $exists = strpos($st['end'], $start) !== FALSE;//check if another code exists in the string } return reconstruct($components, $this->InputFilter);}
Extract code and convert special characters to HTML entities
php;algorithm;strings;security
null
_unix.206349
Context:Remotely located machine with desktop ubuntu 12.04, 2 data drives, 1 OS drive, all specified in /etc/fstab.Issue:During boot one SATA data drive does not respond,and machine will not boot, waits indefinitely for manual input, S for Skip, R for repair, required by Ubuntu.Question:The goal is to have Ubuntu always boot as long as the OS drive is fine,not halting on failed data drives. How to reach this goal ?
ignore failing, non-OS drives?
ubuntu;boot
Try to login as root then comment out all /etc/fstab entries pointing to partitions from the failed data drive. It might be necessary to remount the / partition in read-write mode (if it's mounted read-only and you can't save the file the 1st time, re-try after remounting).When you log out the system will automatically reboot and should come up normally (minus the failed drive mounts).To avoid future non-essential drive failures from preventing the system from booting you could take them out from fstab and mount them when needed, either: manuallyusing autofs (automatically mount them when attempts to accessthem are made and unmount them after some idle time): http://www.golinuxhub.com/2014/09/how-to-configure-autofs-in-linux-and.html (many other references out there).I find autofs very useful for cases like yours, but especially for NFS partitions.
_webapps.98307
In Messenger it states I have 9 groups in common with someone. Two are listed but the remaining 7 aren't. I don't have access to the groups tab of this someone. Is there anyway to find out mutual groups?
Mutual Facebook Groups in common
facebook;facebook groups
null
_webmaster.41108
As I'm building my business website, I'm using service/price tables at the bottom of each service page to demonstrate to customers/potential clients my other offerings. Of course, given that there are 7 or 8 service pages, each with (according to Google) the same service descriptions below the original content for that service, would this be counting as duplicate content? If so, what could I do about it?
Is the structure of my site's navigation (via price/service tables) considered 'Duplicate Content' by Google?
seo;google
null
_softwareengineering.336291
In a web application, we create an email provider, which in turn creates an SMTP client: my question is whether we should create an SMTP client per request or create only one client and have it service all requests?Which is the best way to use an SMTP client? We are only sending (not receiving) email.
Is SMTP client created in singleton scope or request scope?
c#;networking;tcp
null
_unix.167222
On an ext3 (or ext2/4, pick your flavor) filesystem, how would one extract raw byte data that corresponds to a particular inode directly from the hard drive? Is it possible given, say, an inode number to determine its location on disk (perhaps as an offset from the start of the partition, or some other LBA offset) and then use some utility such as dd or a system call (something like lseek except operating on the filesystem?) to read that data without having to reference it as a file? I'm assuming this can be done, perhaps with some sort of driver-level utility ....
How to extract raw ext3 inode data from disk?
ext4;ext3;ext2
null
_unix.100751
So here's a quick overview of my setup:I purchased a new Mac Mini server and I am hosting it with a Mac Mini co-lo facility. At first I had them keep OSX installed and I was using VirtualBox to place CentOS 6.4 (minimal) in a VM. I have 5 public IP's assigned to my Mac Mini (one physical NIC). All are on the same subnet and IP block thus have the same gateway. I ran into an issue with running the VM in VirtualBox where only one of the IP addresses setup in CentOS would work from the outside (public) BUT all of them would work if accessed from the host system (using the public IP). I figured OSX was doing something weird so I had the host install ESXi 5.5 on the Mac Mini (had contemplated doing that anyway).So now I have ESXi 5.5 installed and a single VM (CentOS 6.4 minimal) running on it. I proceeded to setup my IP addresses for CentOS and now I'm running into the same exact issue. I can ping (and obviously access) the main ESXi IP, and I can ping and access the IP for eth0 in CentOS, but any additional IP's aren't accessible.Here are pertinent files and their current setup:/etc/sysconfig/network:NETWORKING=yesHOSTNAME=my.hostname.comGATEWAY=208.x.x.1/etc/sysconfig/network-scripts/ifcfg-eth0:DEVICE=eth0HWADDR=00:0C:29:78:42:C4TYPE=EthernetUUID=1eeafa3a-87b1-4080-9de0-8e4dd9420ba3ONBOOT=yesNM_CONTROLLED=noBOOTPROTO=staticIPADDR=208.x.x.12NETMASK=255.255.255.0/etc/sysconfig/network-scripts/ifcfg-eth0:DEVICE=eth1HWADDR=00:0C:29:78:42:CETYPE=EthernetUUID=be671894-6044-4870-b1e1-2a9c1758c551ONBOOT=yesNM_CONTROLLED=noBOOTPROTO=staticIPADDR=208.x.x.13NETMASK=255.255.255.0ip addr:1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host valid_lft forever preferred_lft forever2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 00:0c:29:78:42:c4 brd ff:ff:ff:ff:ff:ff inet 208.x.x.12/24 brd 208.x.x.255 scope global eth0 inet6 fe80::20c:29ff:fe78:42c4/64 scope link valid_lft forever preferred_lft forever3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 00:0c:29:78:42:ce brd ff:ff:ff:ff:ff:ff inet 208.x.x.13/24 brd 208.x.x.255 scope global eth1 inet6 fe80::20c:29ff:fe78:42ce/64 scope link valid_lft forever preferred_lft forever4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 00:0c:29:78:42:d8 brd ff:ff:ff:ff:ff:ff inet 208.x.x.14/24 brd 208.x.x.255 scope global eth2 inet6 fe80::20c:29ff:fe78:42d8/64 scope link valid_lft forever preferred_lft forever5: eth3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether 00:0c:29:78:42:e2 brd ff:ff:ff:ff:ff:ff inet 208.x.x.15/24 brd 208.x.x.255 scope global eth3 inet6 fe80::20c:29ff:fe78:42e2/64 scope link valid_lft forever preferred_lft foreverip route:208.x.x.0/24 dev eth0 proto kernel scope link src 208.x.x.12 208.x.x.0/24 dev eth1 proto kernel scope link src 208.x.x.13 208.x.x.0/24 dev eth2 proto kernel scope link src 208.x.x.14 208.x.x.0/24 dev eth3 proto kernel scope link src 208.x.x.15 169.254.0.0/16 dev eth0 scope link metric 1002 169.254.0.0/16 dev eth1 scope link metric 1003 169.254.0.0/16 dev eth2 scope link metric 1004 169.254.0.0/16 dev eth3 scope link metric 1005 default via 208.x.x.1 dev eth0 ifconfig -a:eth0 Link encap:Ethernet HWaddr 00:0C:29:78:42:C4 inet addr:208.x.x.12 Bcast:208.x.x.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fe78:42c4/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3549 errors:0 dropped:0 overruns:0 frame:0 TX packets:1188 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:256360 (250.3 KiB) TX bytes:120840 (118.0 KiB)eth1 Link encap:Ethernet HWaddr 00:0C:29:78:42:CE inet addr:208.x.x.13 Bcast:208.x.x.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fe78:42ce/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3160 errors:0 dropped:0 overruns:0 frame:0 TX packets:17 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:223374 (218.1 KiB) TX bytes:1238 (1.2 KiB)eth2 Link encap:Ethernet HWaddr 00:0C:29:78:42:D8 inet addr:208.x.x.14 Bcast:208.x.x.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fe78:42d8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2266 errors:0 dropped:0 overruns:0 frame:0 TX packets:17 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:136142 (132.9 KiB) TX bytes:1238 (1.2 KiB)eth3 Link encap:Ethernet HWaddr 00:0C:29:78:42:E2 inet addr:208.x.x.15 Bcast:208.x.x.255 Mask:255.255.255.0 inet6 addr: fe80::20c:29ff:fe78:42e2/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2260 errors:0 dropped:0 overruns:0 frame:0 TX packets:17 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:135782 (132.5 KiB) TX bytes:1238 (1.2 KiB)lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:937 errors:0 dropped:0 overruns:0 frame:0 TX packets:937 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:123340 (120.4 KiB) TX bytes:123340 (120.4 KiB)I'm only including the setup for eth0 and eth1 since eth2/3 are setup the same way. Again, I can only access one at a time. What am I missing?
Can only get one network to be accessible from outside
networking;centos
null