source
sequence
text
stringlengths
99
98.5k
[ "serverfault", "0000786717.txt" ]
Q: Centos7 Fresh install boots into black screen I installed Centos7 onto a box we have here for testing, I am using a Bootable HDD to install it on the System, I have used the same HDD to install Centos7 on a Dell Powerblade Server & a HP Z640 System but it will not install on this Tyan Box for some reason. Box Specs Previous Operating System Windows 10 Pro 64-bit CPU CPU 1 Intel Xeon E5 v3 @ 2.40GHz Haswell-E/EP 22nm Technology CPU 2 Intel Xeon E5 v3 @ 2.40GHz Haswell-E/EP 22nm Technology RAM 64.0GB Unknown @ 931MHz Motherboard TYAN FT77C-B7079 (SOCKET 0) Graphics Standard Monitor (1024x768@60Hz) ASPEED Technology Microsoft Basic Display Adapter (ASPEED Technology) 8x NVIDIA GeForce GTX 980 Ti 2047MB (PNY) ForceWare version: 361.91 SLI Disabled Storage 238GB Samsung SSD 850 PRO 256GB (SSD) 25 °C The install appeared fine, went through the usual steps and rebooted. after reboot it runs through POST and gives me two options I have multiple options in the BIOS under Boot options. I have swapped the order of each one multiple times, Booting form UEFI OS:, SATA0 PO:, and CentOS Linux (PO: SSD...... Each one has the same outcome, i get to this screen below. Choosing EITHER of the above options results in the same outcome, a black screen and nothing comes from it, no errors, no cursor, nothing. Edit - Picture of the exciting black screen. I have SecureBoot Disabled already. I cannot get a terminal, I have tried Alt+F1, Alt+f2, Ctrl-Alt+F1, Ctrl-Alt+F2, ESC etc.. I have also re-installed twice, I also tried using the "Troubleshoot" option and install with basic GUI but had the same result. I have seen multiple questions similiar to this on here but the difference is they could all access the Terminal, I unfortunately can't, or at least if I can, I'm not sure on how. A: I've found the solution. note this post is based on this thread from this debian forums thread. I've had the same problem (except I couldn't even install initially). My install problem was that Nouveau prevented me from continuing past a certain point in the install. I fixed this, and then wasn't able to boot up. In my situation it would mostly black screen, but some times it would just freeze at the four penguins logo. This problem was also caused by Nouveau. I fixed this via the following steps: press e before entering any centos boot. navigate to the linuxefi /images/pxeboot/vmlinuz... line or what ever line is your linux boot command (usually ends in quiet to supress debug info) enter in the following additional arguments to your boot args list: rdblacklist=nouveau nouveau.modeset=0 these arguments will stop nouveau from starting for the next boot, press ctrl-x or f10 to boot into Centos 7 uninstall nouveau and install non nouveau drivers, other wise you will have to do this process every boot
[ "unix.stackexchange", "0000056638.txt" ]
Q: Linux + Solaris how to verify the last execute process from list of process I need advice: How to verify which is the last scan_sys.sh process that run in my linux or solaris ? my target is to kill all scan_sys.sh process , except the latest scan_sys.sh ( the last execute /usr/scan_sys.sh script ) ps -ef | grep scan_sys.sh . root 367 1 0 Nov 08 ? 0:21 /usr/scan_sys.sh root 27517 27515 0 17:27:18 ? 0:01 /usr/scan_sys.sh root 18939 367 0 Nov 15 ? 0:00 /usr/scan_sys.sh root 18940 18939 0 Nov 15 ? 0:01 /usr/scan_sys.sh root 27515 367 0 17:27:18 ? 0:00 /usr/scan_sys.sh A: Use ps option -o to select fields you want to display to show process pid, start time and command name, optionally selecting the processes you're interested in right away (-C), sort on start time, kill all but the last one. Since ps is notoriously known to be a command line options hell, you'll have to check the man page for your implementation. For me the equivalent of the following works on linux (to list the appropriate PIDs): ps -C scan_sys.sh -o pid --sort start | sed '$d' Remember to quote the $ in sed script with single quotes (at least in bash) as otherwise it will be expanded to environment variable d. You can send the PIDs to kill e.g. via xargs or by command substitution (`` or $() in bash).
[ "russian.stackexchange", "0000008243.txt" ]
Q: Is it temperature or something else? Does the sentence on the T-shirt, После 40° жизнь только начинается! , refer to the temperature, i e does it mean Beyond 40 degrees life just starts! or is there another meaning? A: In this context the degree (градус) means volume fraction of ethanol (alcohol) in a beverage. One percent of ethanol by volume corresponds to one degree on Tralles hydrometer, so historically alcohol proof was measured in degrees rather than in percent in Russia. Minimum proof of 40% ABV (or 40°) had been a standard for Russian vodka since late XIX century, and "40°" (сорок градусов) is popular metaphor for vodka. The t-shirt quote is actually a pun on the famous quote from the 1979 Soviet film "Moscow Does Not Believe in Tears" ("Москва слезам не верит"), told by the protagonist, a woman in her early forties: После сорока жизнь только начинается. Это я уже теперь точно знаю. // Life just begins after 40. Now I know this for a fact. A: No, it is about vodka. In Russian, there is a well known sentence "после сорока жизнь только начинается" (it is about age). They humorously changed it to "после сорока градусов", referring to the percentage of alcohol in vodka. The volume percent of alcohol is called градус (i.e. крепость водки 40 градусов). A: "Expedition"(logo seen on T-shirt) is a trade mark. They sell goods for travellers, fishermen etc. So their slogan "После 40 жизнь только начинается" is a bit of wordplay, but not just "vodka". See, for example, the flask with less ambiguous text directly mentioning those "40 degrees/percent" - http://www.ozon.ru/context/detail/id/5023509
[ "stackoverflow", "0045178207.txt" ]
Q: get firebase keys from snapshot not working I have this in my firebase DB: { "vehicles" : { "fz20tqpxUChOM98fNUYGQhtZ83" : { "amount" : 31, "timeStamp" : "2017-07-18T20:31:34Z" }, "sw30tqpxUChOM98fNUrGQhtk33" : { "amount" : 45, "timeStamp" : "2017-07-18T20:31:34Z" } } I am using .on to get a snapshot of the data: var ref = database.ref('vehicles'); ref.on('value', function(snapshot) { var obj = snapshot.val(); for (var key in obj){ console.log(obj);//prints my obj console.log(obj.key);//prints 'undefind' both times (why??) console.log(obj.fz20tqpxUChOM98fNUYGQhtZ83);//prints data if ('fz20tqpxUChOM98fNUYGQhtZ83' === key) {//Just for testing console.log("IT IS ==="); //my 'key' is equal to //the hardcoded key } else { console.log("NOT ==="); } } }); When I console.log(obj.key); I get undefined for both keys. However when I run console.log(obj.fz20tqpxUChOM98fNUYGQhtZ83); I get my data, obviously I can't hard code my key in there, so WHY is it not printing when I ask it too??? A: obj.key would only work if there were a key in the object literally called key, like this: { key: "foo" } What you want is obj[key], which will look up the value of the key based on a dictionary lookup of the variable value instead of a literal reference.
[ "ell.stackexchange", "0000215246.txt" ]
Q: "execute": to run or to kill The verb execute has 2 different but somewhat opposite meanings: to run and to kill. Plus, there are at least 3 words derived from this verb: executive: a person who runs an organization; executor: a person who executes a will; executioner: a person who kills criminals; I'm having a hard time remembering which is which. I'd like to understand where it means "to run" and where "to kill". To be specific, my questions are: Is it always true that executor means "runner" and executioner means "killer"? What can be run by an executor? Can we say command executor, law executor, plan executor, etc.? Can we say business executor instead of business executive? Does executable mean "can be run", "can be killed", or either depending on context? I think we can say executable programs, but can we say executable criminals? Same but for executive (when used as adjective). For example, in these sentences: His executive skills will be very useful. The executive process went smoothly. Is it clear if executive here means "running a business" or "killing someone"? When someone mentions "the power of execution", are we sure it's about leadership but not a firing squad? A: The basic meaning is "follow out" (from Latin ex-sequor) in the sense of "follow instructions to completion". From this come the general meaning "carry out a procedure", implicit in "executive" and "executor". It has also acquired a more specific meaning of "carry out the procedure of killing as a legal punishment", and "executioner" is specific to this sense. (This is occasionally extended to non-legal killing). Neither "executive" nor "executor" is used in this sense. The verb "execute" and the noun "execution" can be used in either sense: only context will distinguish them. Ambiguity is possible, but rare because there is usually enough context to clarify.
[ "askubuntu", "0000418704.txt" ]
Q: Will Steam work as good in other desktop flavors as it runs on Ubuntu? It's great news that Steam supports Linux, and will surely help with gaming on Linux. I've heard that Ubuntu is the distro that Steam officially supports, so it follows that you'd have the best Steam experience on Ubuntu. My question is this: Would any of the differences that make Lubuntu what it is and not Ubuntu, affect the quality of experience I would get with Steam? A: The desktop environment that you use does not affect the usage of Steam. In fact, you do not even need a desktop at all to run steam. An example of that is that a Steam session can be added to LightDM or any other login managers to run Steam in big picture mode instead of the actual desktop. And by the way: SteamOS is built on top of the stable release branch of Debian, not Ubuntu, Ubuntu is as well officially supported as any other Linux distribution. Not that it matters, most of the popular Linux distribution will run Steam without any issues.
[ "stackoverflow", "0016086819.txt" ]
Q: Running LAN WCF service I'm trying to create a client-server app where the server runs on the user's machine. I'm looking into either using WCF or Sockets but I have a couple of questions. I'd like to use WCF but it seems that the user needs admin rights in order to launch the service. Would the user need admin rights if the WCF service was running within a managed application (e.g. a Windows Service)? With sockets it seems that admin rights isn't required to open the relevant port. How would HTTPS security work in WCF? Since this is a LAN program (user talking from client to their own machine), do I need to purchase a certificate and install it on their machines? I'd rather avoid this if possible as the data being transferred isn't sensitive. Would this be the same if I use SSLStream for sockets? A: There are a lot of questions, :), so very short answer on part of them: You can host WCF even in console application. Windows Services may not require admin properties to be installed on pc. For HTTPS - you does not have to buy certificate, you can crate your own - there are a lot of examples in the net. But - if your data is not sensitive - you can probably use simple http.
[ "stackoverflow", "0024035354.txt" ]
Q: Combobox inside DataGrid not displaying SelectedItem I'm trying to learn Silverlight with MVVM pattern. I've stumbled across a problem that's puzzling me for quite few hours I've a Combobox inside a Datagrid. When the combobox is opened, the item corresponding to the SelectedItem of Datagrid isn't being selected in the Combobox options. This is my Model public class Address : ViewModelBase { private string streetName; public string StreetName{...} private City city; public City City {...} } public class City : ViewModelBase { private string cityName; public string CityName{...} private string code; public string Code{...} } This is my ViewModel public class MainPageViewModel : ViewModelBase { #region Fields private Address selectedAddress; #endregion #region Properties public ObservableCollection<Address> Addresses { get; set; } public ObservableCollection<City> Cities { get; set; } public Address SelectedAddress {...} #endregion public MainPageViewModel() { InitializeProperties(); } #region Methods private void InitializeProperties() { InitializeAddresses(...); InitializeCities(...); } #endregion } And my XAML <sdk:DataGrid ItemsSource="{Binding Path=Addresses, Mode=TwoWay}" SelectedItem="{Binding Path=SelectedAddress, Mode=TwoWay}" AutoGenerateColumns="False" RowHeight="25" ColumnWidth="*"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="Street Name" Binding="{Binding Path=StreetName, Mode=TwoWay}"/> <sdk:DataGridTemplateColumn Header="City Name"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Path=City.CityName, Mode=TwoWay}"/> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> <sdk:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <ComboBox DisplayMemberPath="CityName" ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=sdk:DataGrid}, Path=DataContext.Cities, Mode=OneWay}" SelectedItem="{Binding Path=City, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> </DataTemplate> </sdk:DataGridTemplateColumn.CellEditingTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTextColumn Header="City Code" Binding="{Binding Path=City.Code, Mode=TwoWay}" IsReadOnly="True"/> </sdk:DataGrid.Columns> </sdk:DataGrid> Then if I make a selection from combobox dropdown menu, next time I open the combobx it will be selected. When the combobox is opened What I'm looking for when the combobox is opend Also when the user selects an item from combobox, it should be binded to the Datagrid's SelectedItem's City property. Thanks in advance for any suggestions or links to a solution. A: [Edit] I have an idea what might be going wrong... How do you initialize the list of available cities and the addresses? Because if you are not using the same instances you created to populate the available city list for initializing the addresses, then the SelectedItem you have bound is not found in the ItemsSource (think: object identity). so you should do it like this: var cities = InitializeCities(...); InitializeAddresses( cities ); ... private void InitializeAddresses(... cities) { ... var address = new Address {City = cities[42] }; [Original Post] Try removing the explicit UpdateSource trigger, it is not needed for the ComboBox and may interfere in a way. SelectedItem="{Binding Path=City, Mode=TwoWay}"
[ "stackoverflow", "0020746023.txt" ]
Q: Function that needs to putt limited length strings doesn't work well I've got this function i created: void getWords(int words){ int remaining, error=0; char word[WORD_MAX+1], def[DEF_MAX+1]; for(remaining = words;remaining > 0;remaining--){ do{ printf("Enter definition #%d out of %d:\n",((words+1) - remaining),words); gets(word); if(strlen(word) > WORD_MAX){ error = 1; printf("\nError! '%s' contains %d characters | Maximum allowed: %d | Please try again...\n\n",word,strlen(word),WORD_MAX); } }while(error); } } It does what it should do basically, checks if the string length is at most 'WORD_MAX' characters long and if not asks the user to do it again, My problem is this: when i tested it with WORD_MAX of 3 and tried to write a 6 characters long string it works perfectly, but when i tried to write a really long string, for example 20 chars long, it wrote only some of the word, with some weird ascii smiley on the end, and the 'remaining' variable which contains the number of words i ask the function to input get some garbage value and it ruins the whole program, why does it do that? Thank you! A: As you've noticed, there is no way to avoid buffer overflow with gets. As an alternative, you could use fgets fgets(word, WORD_MAX+1, stdin); From its man page char *fgets(char *s, int size, FILE *stream); fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.
[ "stackoverflow", "0043938707.txt" ]
Q: PHP RegEx pattern for repeating within the string I am trying to make regex for this string : This is some string <select> this is another string <select var1> another string which can contain special characters <select var2> another variable string <select var1,var2> I need to select all the strings not in select tag. Select all string not within <select> tag Can anyone help ? using PHP preg_match A: by using preg_split: $str = 'This is some string <select> this is another string <select var1> another string which can contain special characters <select var2> another variable string <select var1,var2>'; $arr = preg_split('/\<.*?\>/',$str); print_r($arr);
[ "stackoverflow", "0052113666.txt" ]
Q: Service Broker message flow I have two different servers in two locations. I need to use asynchronous exchange of data. Server A is our data server, we store customer info here. Server B is our proccesing server, we process production. Each production operation on server B has a production group. What I need to do is: A to send a message to B with a question: What operations are planned for today in this group(GUID). B has to answer with an XML list of operations scheduled for today. A has to answer with an XML list of operations to cancel B has to cancel operations and end conversation My question is: What is the right way to go about this? Can I do this in just a single dialog using one contract? Should I? With a contract like this: CREATE CONTRACT [GetScheduledContract] AUTHORIZATION [xxx] (GetScheduledOutCalls SENT BY INITIATOR, ReturnScheduledOutCalls SENT BY TARGET, DeleteScheduledOutCalls SENT BY INITIATOR) Or should I separate the tasks to different contracts and dialogs? A: What you have seems good to me as an MVP (i.e. if things go right, it'll work). A couple of things: Consider adding one more reply from the target saying "operation completed successfully" before closing the conversation. Upon receipt, the initiator can also close their end of it. What happens if any of those operations is explicitly not able to be completed (e.g. in your step 4, the request is to delete something that's not present or that delete causes a foreign key violation)? I'd add in some sort of error message type (sent by any) that allows either side to tell the other "hey… something went wrong". What happens if any of those operations is implicitly not able to be completed (e.g. the message never gets delivered)? The other side may not respond for some reason. Build in some way to at least detect and alert on that.
[ "ux.stackexchange", "0000084838.txt" ]
Q: Is it important to display HTTP error codes to users? On a 404 or 403 page, should we include the error code or can the page be written and designed better for UX without it? A: While I don't think you need to explicitly display the exact error code, it won't harm to have it. Even those pages using creative "page not found" messages tend to use the error code, especially when this error is 404, because anyone surfing the web for some time has found this error many times, so a lot of people know what a 404 error code is (even if they don't know it's a response code). On a technical side, it's good to display the error code, because it provides a hint on what to do after getting this error. Obviously, if you 're using just plain Unix messages, this is extremely needed. See the list of HTTP response codes. It's really easy to see not all messages are the same. Even if the outcome may look similar (such as a page not found), some errors offer alternatives, while other errors are definitive. With the above being said, I think you'll realize something basic: more important than displaying error codes is to explain users what are their options. Finally, here’s some additional info on error messages: http://www.sitepoint.com/error-message-ux/ http://www.uxmatters.com/mt/archives/2010/08/avoid-being-embarrassed-by-your-error-messages.php http://blog.hubspot.com/blog/tabid/6307/bid/33766/10-Clever-Website-Error-Messages-From-Creative-Companies.aspx A: I always approached this problem similarly to a search that returns no results. Imagine that you are in a clothing store: You: "Do you have this sweater in teal?" Bad salesperson: "No, we don't. Sorry." Good salesperson: "I'm sorry, we don't have it in teal, but we do have it in Aqua, or this gorgeous blue that I think would really look great with your eyes." Similarly, if a search returns no results or a page is missing, try to offer them the next best thing to show that you're interested in satisfying them. Note that the "Good salesperson" doesn't just say "We have it in Aqua, etc." because that would be rude: It ignores the fact that the store doesn't have it in teal. Similarly, a good UI would acknowledge the 404 (or other error), going as far as to show the error number, especially if the page invites feedback from the user. It lets them be specific: "I got a 404 error on your page just now …." [Edited to add last paragraph on recommendation of commenter.]
[ "stackoverflow", "0006922018.txt" ]
Q: How can I serialize wpf user control with xaml and code behind I want to serialize wpf user control xaml and codebehind. XamlWriter.Save() only serialize's xaml so what can I do in this situation? My situtation is I have a usercontrol which include custom methods, subscribed events (ex: button click) When I deserialize usercontrol (for create usercontrol at runtime) I want to run that events and methods. Sorry my english isn't very good. A: Just an idea, you can use MEF to built up a plugin structure for your user control. You want to create a user control on the fly but the event handler still should be hardcoded somewhere else in your project; with the plugin structure, you can just collect the plugin and reuse it; the events can be handled by a command something. Maybe giving a scenario and we can figure out more detail. Plus, ISerializable provides a way for custom binary serialization for field, not for methods or events. Here is a related question: What is the point of the ISerializable interface? ; on the other hand, you can still try some pattern like how the web control save its view state; for example two virtual methods: public virtual byte[] SaveState(); // it saves the states for your custom control public virtual void LoadState(byte[] state) // it restore your state back to the control. The custom code should be like: byte[] state = controlA.SaveState(); // this method saves its own state. YourControl controlB = new YourControl(); controlB.LoadState(state); // this method load the save state from A to B itself. For the event, every event has a handler name, you can also serialize its handler name to the state and find it back by the saved name from its naming container alike. I don't have any experience to save the method. If you still want to save and load state including fields, events and method, maybe serialization is not the proper way you are looking for I think.
[ "askubuntu", "0000498539.txt" ]
Q: SSH remote command execute stays without disconnect when finished execute? I am trying to build a script/command that will restart our Asterisk/Elastix service on our PBX. The script is basically using simple command with auto log-in public key that run from Ubuntu 14.04LTS: The command script is: ssh user@iphost 'service asterisk restart' But after the command finished and service restarted, the ssh stays and only after ctrlc its breaks out. My question, is how can I terminate the session after the command completes? A: Try redirecting stdin, stdout, and stderr to /dev/null. For an explanation, see https://serverfault.com/questions/36419/using-ssh-to-remotely-start-a-process.
[ "stackoverflow", "0020414504.txt" ]
Q: How do I replicate a \t tab space in HTML? How can I use the common \t escape character in html ? Is it possible? I need a code that has the same function as the /t escape character A: You can enter the tab character (U+0009 CHARACTER TABULATION, commonly known as TAB or HT) using the character reference &#9;. It is equivalent to the tab character as such. Thus, from the HTML viewpoint, there is no need to “escape” it using the character reference; but you may do so e.g. if your editing program does not let you enter the character conveniently. On the other hand, the tab character is in most contexts equivalent to a normal space in HTML. It does not “tabulate”, it’s just a word space. The tab character has, however, special handling in pre elements and (although this not that well described in specifications) in textarea and xmp element (in the latter, character references cannot be used, only the tab character as such). This is described somewhat misleadingly in HTML specifications, e.g. in HTML 4.01: “[Inside the pre element, ] the horizontal tab character (decimal 9 in [ISO10646] and [ISO88591] ) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. We strongly discourage using horizontal tabs in preformatted text since it is common practice, when editing, to set the tab-spacing to other values, leading to misaligned documents.” The warnings are unnecessary except as regards to the potential mismatch of tabbing in your authoring software and HTML rendering in browsers. The real reason for avoiding horizontal tab is that it a coarse and simplistic tool as compared with tables for presenting tabular material. And in displaying computer source programs, it is better to use just spaces inside pre, since the default tab stops at every 8 characters are quite unsuitable for any normal code indentation style. In addition, in CSS, you can specify white-space: pre (or, with slightly more limited browser support, white-space: pre-wrap) to make a normal HTML element, like div or p, rendered like pre, so that all whitespace is preserved and horizontal tab has the “tabbing” effect. In CSS Text Module Level 3 (Last Call working draft, i.e. proceeding towards maturity), there is also the tab-size property, which can be used to set the distance between tab stops, e.g. tab-size: 3. It’s supported by newest versions of most browsers, but not IE (not even IE 11). A: &nbsp;&nbsp;&nbsp;&nbsp; would be a work around if you're only after the spacing. A: HTML doesn't have escape characters (as it doesn't use escape-semantics for reserved characters, instead you use SGML entities: &amp;, &lt;, &gt; and &quot;). SGML does not have a named-entity for the tab character as it exists in most character sets (i.e. 0x09 in ASCII and UTF-8), rendering it completely unnecessary (i.e. simply press the Tab key on your keyboard). If you're working with code that generates HTML (e.g. a server-side application, e.g. ASP.NET, PHP or Perl, then you might need to escape it then, but only because the server-side language demands it - it has nothing to do with HTML, like so: echo "<pre>\t\tTABS!\t\t</pre>"; But, you can use SGML entities to represent any ISO-8859-1 character by hexadecimal value, e.g. &#09; for a tab character.
[ "stackoverflow", "0014088313.txt" ]
Q: Template Partials in Symfony 2 Are there such things as partials in Symfony 2, reusable templates from anywhere, effectively? I have found include http://twig.sensiolabs.org/doc/tags/include.html but this only allows the rendering of a template in a specific directory structure. What I really want a folder that contains all my partial templates, rather than lumping them into my main views? So I want to be able to do something like {% include "Bundle:Default:Partials:view.html.twig" %} Update I do not want to use the enforced structure of Bundle:Controller:Template structure. I do not want to use this as it means putting all my template partials in with my main view templates. I need something that lets me do Bundle:Controller:PartialDir:Template A: You can already do that. The symfony2 docs has a section describing how to do this. http://symfony.com/doc/current/book/templating.html#including-other-templates
[ "anime.stackexchange", "0000056871.txt" ]
Q: If All for One can pass quirks on to others, can he pass debilitating quirks to people that don't want them? Since All for One can transfer quirks, can he pass along quirks to people that don't want them? A: Of course. All for One has the power to pass quirks regardless of the wishes of the receiving person. About One For All from fandom : Long ago, a man with a Quirk that could steal other Quirks and give them away forcibly gave his seemingly Quirkless younger brother a Quirk that allowed him to stockpile power within his body. This is the story of how One for All was born. The brother of the original All for One rejected any desire of having a quirk but his brother gave one to him regardless. So it is possible to give Quirks to people who don't want them.
[ "stackoverflow", "0062634466.txt" ]
Q: Facing issues 'An error occured while initializing MyFaces' in WAS 8.5.5.16 with Myfaces 2.3 I am trying to deploy Myfaces 2.3 base application in WAS 8.5.5.16 with Java 8 but facing below mention error. 0000005c AbstractFaces E An error occured while initializing MyFaces: Class com.ibm.ws.jsf.config.annotation.WASMyFacesAnnotationProvider is no org.apache.myfaces.spi.AnnotationProvider java.lang.IllegalArgumentException: Class com.ibm.ws.jsf.config.annotation.WASMyFacesAnnotationProvider is no org.apache.myfaces.spi.AnnotationProvider at org.apache.myfaces.shared.util.ClassUtils.buildApplicationObject(ClassUtils.java:567) at org.apache.myfaces.shared.util.ClassUtils.buildApplicationObject(ClassUtils.java:534) at org.apache.myfaces.spi.impl.DefaultAnnotationProviderFactory.resolveAnnotationProviderFromService(DefaultAnnotationProviderFactory.java:138) at org.apache.myfaces.spi.impl.DefaultAnnotationProviderFactory.createAnnotationProvider(DefaultAnnotationProviderFactory.java:93) at org.apache.myfaces.spi.impl.DefaultAnnotationProviderFactory.getAnnotationProvider(DefaultAnnotationProviderFactory.java:62) at org.apache.myfaces.config.annotation.AnnotationConfigurator.createFacesConfig(AnnotationConfigurator.java:90) at org.apache.myfaces.config.DefaultFacesConfigurationProvider.getAnnotationsFacesConfig(DefaultFacesConfigurationProvider.java:201) at org.apache.myfaces.config.DefaultFacesConfigurationMerger.getFacesConfigData(DefaultFacesConfigurationMerger.java:92) at org.apache.myfaces.config.FacesConfigurator.configure(FacesConfigurator.java:603) at org.apache.myfaces.webapp.AbstractFacesInitializer.buildConfiguration(AbstractFacesInitializer.java:456) at org.apache.myfaces.webapp.Jsp21FacesInitializer.initContainerIntegration(Jsp21FacesInitializer.java:70) at org.apache.myfaces.webapp.AbstractFacesInitializer.initFaces(AbstractFacesInitializer.java:190) at org.apache.myfaces.webapp.StartupServletContextListener.contextInitialized(StartupServletContextListener.java:103) at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:1736) at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:415) at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88) at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:171) at com.ibm.ws.webcontainer.WSWebContainer.addWebApp(WSWebContainer.java:904) at com.ibm.ws.webcontainer.WSWebContainer.addWebApplication(WSWebContainer.java:789) at com.ibm.ws.webcontainer.component.WebContainerImpl.install(WebContainerImpl.java:427) at com.ibm.ws.webcontainer.component.WebContainerImpl.start(WebContainerImpl.java:719) at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1211) at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1462) at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:641) at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:1040) at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:795) at com.ibm.ws.runtime.component.ApplicationMgrImpl$5.run(ApplicationMgrImpl.java:2279) at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5482) at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5698) at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255) at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2284) at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:436) at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123) at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:379) at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:127) at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$CUInitializer.run(CompositionUnitMgrImpl.java:985) at com.ibm.wsspi.runtime.component.WsComponentImpl$_AsynchInitializer.run(WsComponentImpl.java:524) at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892) A: WebSphere 8.5.5 by default provides the MyFaces JSF 2.0 implementation. This IllegalArgumentException suggests that the WAS-provided JSF implementation is still enabled, and that the MyFaces 2.3 implementation you're providing with your app is conflicting with it. You need to follow IBM's instructions[1] for using a "third-party JSF implementation": configure the server to use Sun RI 1.2 for JSF instead of "default" or "MyFaces", and provide your MyFaces 2.3 implementation and its dependencies as an isolated shared library. [1] https://www.ibm.com/support/knowledgecenter/en/SSAW57_8.5.5/com.ibm.websphere.nd.multiplatform.doc/ae/tweb_jsf.html
[ "stackoverflow", "0047903602.txt" ]
Q: Bootstrap styles not applying to my angular 2 project I added bootstrap css in angular-cli.json - styles. Not applying bootstrap styles to my project. I added in package.json and did npm install. How to resolve this? angular-cli.json "styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.css" ] package.json "dependencies": { "bootstrap": "^4.0.0-beta.2" } A: No need to update or reinstall your bootstrap just do below mentioned step it will work for you open angular-cli.json inside styles array and specifying the path of bootstrap like this: Angular-cli.json: "styles": [ "./node_modules/bootstrap/dist/css/bootstrap.min.css", "styles.css" ], Open your style.css and paste this at the top: @import url("../node_modules/bootstrap/dist/css/bootstrap.min.css") A: In your style.css add following line of code on top and let us know. @import url("../node_modules/bootstrap/dist/css/bootstrap.min.css") Also check with following line too @import url("./node_modules/bootstrap/dist/css/bootstrap.min.css") Hope it will help. A: There is two styles declaration in angular.json file. One in Builder section and other one test's builder section. Make sure you are putting it in the right section. "builder" : { ..... "styles" : [ // It should go here. Around line no. 27 "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css" ], ..... }, "test": { ..... "styles" : [ // Not here! "src/styles.css", ], ..... }
[ "stackoverflow", "0057717813.txt" ]
Q: BeautifulSoup Not Finding All 'th' I'm currently trying to scrape a statistics site in Python 3.7 using BeautifulSoup. I'm trying to grab all of the headers from a table as my column headers, but for some reason BeautifulSoup isn't grabbing all of the headers that are located within the 'th' tags. Here is my code: url = 'https://www.eliteprospects.com/team/552/guelph-storm/2005-2006?tab=stats' html = urlopen(url) scraper = BeautifulSoup(html,'html.parser') column_headers = [th.getText() for th in scraper.findAll('tr', limit=1)[0].findAll('th')] # Find Column Headers. print(column_headers) Here is the output I am getting: ['#', 'Player', 'GP', 'G', 'A', 'TP'] Here is the output I should be getting: ['#', 'Player', 'GP', 'G', 'A', 'TP', 'PIM', '+/-', 'GP', 'G', 'A', 'TP', 'PIM', '+/-'] For Reference here is what the table source html looks like: <table class="table table-striped table-sortable skater-stats highlight-stats" data-sort-url="https://www.eliteprospects.com/team/552/guelph-storm/2005-2006?tab=stats" data-sort-ajax-container="#players" data-sort-ajax-url="https://www.eliteprospects.com/ajax/team.player-stats?teamId=552&amp;season=2005-2006&amp;position="> <thead style="background-color: #fff"> <tr style="background-color: #fff"> <th class="position">#</th> <th class="player sorted" data-sort="player">Player<i class="fa fa-caret-down"></i></th> <th class="gp" data-sort="gp">GP</th> <th class="g" data-sort="g">G</th> <th class="a" data-sort="a">A</th> <th class="tp" data-sort="tp">TP</th> <th class="pim" data-sort="pim">PIM</th> <th class="pm" data-sort="pm">+/-</th> <th class="separator">&nbsp;</th> <th class="playoffs gp" data-sort="playoffs-gp">GP</th> <th class="playoffs g" data-sort="playoffs-g">G</th> <th class="playoffs a" data-sort="playoffs-a">A</th> <th class="playoffs tp" data-sort="playoffs-tp">TP</th> <th class="playoffs pim" data-sort="playoffs-pim">PIM</th> <th class="playoffs pm" data-sort="playoffs-pm">+/-</th> </tr> </thead> <tbody> Any help would be greatly appreciated! A: Looking at the source of the page you are trying to scrape, this is exactly what the data looks like: <div class="table-wizard"> <table class="table table-striped"> <thead> <tr> <th class="position">#</th> <th class="player">Player</th> <th class="gp">GP</th> <th class="g">G</th> <th class="a">A</th> <th class="sorted tp">TP</th> </tr> </thead> <tbody> That is why that is the only data you get. It's not even a case where JavaScript alters it after the fact. If I perform a querySelector in the browser console, I get the same thing: > document.querySelector('tr') > <tr> <th class="position">#</th> <th class="player">Player</th> <th class="gp">GP</th> <th class="g">G</th> <th class="a">A</th> <th class="sorted tp">TP</th> </tr> In short, Beautiful Soup is giving you exactly all the th tags in the first tr tag. If you try and grab the second tr tag that has th tags using the CSS selector tr:has(th), you will see you get more th tags: column_headers = [th.getText() for th in scraper.select('tr:has(th)', limit=2)[1].findAll('th')] Output ['#', 'Player', 'GP', 'G', 'A', 'TP', 'PIM', '+/-', '\xa0', 'GP', 'G', 'A', 'TP', 'PIM', '+/-']
[ "puzzling.stackexchange", "0000027737.txt" ]
Q: The game of Shafiqa and Habibi Shafiqa chose a positive integer number $X\le100$, and Habibi is trying to guess the number. Habibi can select two natural numbers $M$ and $N$ less than $100$ and ask about the greatest common divisor $\gcd(X+M,N)$ of $x+M$ and $N$. Can Habibi always determine Shafiqa's number with at most seven questions? A: Yes. Why: He first asks the values from $gcd(X+0,30)$ to $gcd(X+3,30)$. Two of $X,X+1,X+2,X+3$ are bound to be divisible by 2, and at least one is a multiple of 3. If none of them are divisible by 5, $X+4$ is, but whether it's the case or not he can then determine the $mod 2,3$ and $5$ values of $X$. Thus, there are 3 or 4 possible $X$ solutions in the form of $n, n+30, n+60$, with $n+90$ in the mix if possible. If he asks the GCDs of $X$ and these values starting from the last, he can either find the solution directly (the first answer equal to the number he picked) or by eliminating the rest after 3 more questions at most. An alternative solution: He first asks the values from $gcd(X+0,70)$ to $gcd(X+5,70)$, which allows him to determine the $mod 2,5$ and $7$ values of $X$. Thus, there are 1 or 2 possible $X$ solutions in the form of $n$ and $n+70$ if possible. If $n>29$, there's only one solution. Otherwise he asks the GCD of $X$ and $n+70$, after which he can either find the solution directly or by eliminating the rest.
[ "stackoverflow", "0061889543.txt" ]
Q: How do I change the style of an element through another element selector with withStyle from materialUI I have an input and I would like to change the border of the parent div when I focus on the input. https://codesandbox.io/s/jolly-fermat-e2tyo?file=/src/App.js import React from "react"; import ReactDOM from "react-dom"; import { withStyles } from "@material-ui/core/styles"; const InputComponent = ({ value, classes }) => ( <div className={classes.inputContainer}> <input value={value} className={classes.input} /> </div> ); const styles = { input: { fontSize: 14, padding: 15, "&:focus": { backgroundColor: "#F8F8F8", $inputContainer: { //I know this won't work border: "1px solid #006CFF" } } }, inputContainer: { border: "1px solid black", backgroundColor: "white" } }; const InputWithStyles = withStyles(styles)(InputComponent); export default function App() { return ( <div className="App"> <h1>Hello CodeSandbox</h1> <InputWithStyles /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, rootElement ); Currently using withStyles HOC from material-ui, and using the classes props on the component Version used: "@material-ui/core": "^3.9.2" A: The short answer is that this isn't possible in CSS (see Is there a CSS parent selector?). The way to achieve the desired result is to change the parent (e.g. add/remove a "focused" class) via JavaScript in response to focus/blur events. This is the approach Material-UI uses internally to change the styles of input containers (see https://github.com/mui-org/material-ui/blob/v4.9.14/packages/material-ui/src/InputBase/InputBase.js#L414). Here is a modified version of your sandbox using this approach: import React from "react"; import ReactDOM from "react-dom"; import { withStyles } from "@material-ui/core/styles"; import classnames from "classnames"; const InputComponent = ({ value, classes }) => { const [focused, setFocused] = React.useState(false); return ( <div className={classnames(classes.inputContainer, { [classes.focused]: focused })} > <input onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} value={value} className={classes.input} /> </div> ); }; const styles = { input: { fontSize: 14, padding: 15, "&:focus": { backgroundColor: "#F8F8F8" } }, inputContainer: { border: "1px solid black", backgroundColor: "white", "&$focused": { border: "1px solid #006CFF" } }, focused: {} }; const InputWithStyles = withStyles(styles)(InputComponent); export default function App() { return ( <div className="App"> <h1>Hello CodeSandbox</h1> <InputWithStyles /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); I was expecting to see your example using one of the Material-UI input components. If you are actually using one of those and removed it for the sake of simplicity in your example, then let me know. The way to handle this for Material-UI inputs would be a bit different -- Material-UI is already managing knowledge of the focused state, so it generally wouldn't be necessary to repeat that work. Instead, you would just leverage the class that Material-UI is already adding to the input container.
[ "stackoverflow", "0053557056.txt" ]
Q: How can I code this Cellular Automata project more efficiently? I am new to programming and I have an interest in cellular automata, so I decided to try to script one using JavaScript both for coding practice and so that I could make a personalised one. The cellular automata project I created is for a simple binary (black and white) 2D table CA which looks at the colours of the 8 nearest neighbors of a cell and the colour of the cell itself and updates its colour depending on the rules given in the 'ruleset' table below the CA table. Only problem is the code that I wrote takes forever to process each iteration, clearly because of all the large loops it needs. In fact as I am writing this I realise that I can reduce the processing power needed by stopping the comparison search between the current neighbour colour configuration and the set of all possible configurations when the if statement finds the correct configuration, but this will probably not reduce the processing power needed by the amount that I would prefer and I am sure that there are more ways to make it faster. If anybody could give me some advice on how to reduce the processing power even more I would really appreciate it. Also, please explain your answers in laymans terms. Thank you! Here is the code: <!DOCTYPE html> <html> <head> <title></title> <style> table {border-collapse: collapse;} table, td, th {border: 1px solid black;} td {width:1px; height:1px;} </style> </head> <body> <button onclick="Toggle()">Toggle</button> <!-- Toggle runs the Iterate function with a setInterval --> <button onclick="Iterate()">Iterate</button> <br> <script> document.write("<table>") for (row=0; row<100; row++) { document.write("<tr>") for (col=0; col<100; col++) {document.write("<td id = 'R" + row + "C" + col + "' style='background-color: white' ondblclick='MouseDown(this)' onmousedown='MouseDown(this)' onmouseover='MouseUp(this)'>" + "</td>")} document.write("</tr>")} document.write("</table>") // This is the cellular automata table document.write("<br>") document.write("<table>") for (row=0; row<16; row++) { document.write("<tr>") for (col=0; col<32; col++) {document.write("<td id = 'id" + (col+32*row) + "' style='background-color: white' ondblclick='MouseDown(this)' onmousedown='MouseDown(this)' onmouseover='MouseUp(this)'>" + "</td>")} document.write("</tr>")} document.write("</table>") // This is the 'ruleset' table let determiner = 0 function MouseDown(cell) {determiner = 1 if (cell.style.backgroundColor == "white") {cell.style.backgroundColor = "black"} else {cell.style.backgroundColor = "white"}} window.addEventListener('mouseup', function(event){determiner = 0}) function MouseUp(cell) {if (determiner == 1) { if (cell.style.backgroundColor == "white") {cell.style.backgroundColor = "black"} else {cell.style.backgroundColor = "white"}}} // This section provides the click & drag cell colour changing functions for (i=0; i<512; i++) { if (i % 512 < 256){this["j1"] = "white"} else {this["j1"] = "black"} if (i % 256 < 128){this["j2"] = "white"} else {this["j2"] = "black"} if (i % 128 < 64){this["j3"] = "white"} else {this["j3"] = "black"} if (i % 64 < 32){this["j4"] = "white"} else {this["j4"] = "black"} if (i % 32 < 16){this["j5"] = "white"} else {this["j5"] = "black"} if (i % 16 < 8){this["j6"] = "white"} else {this["j6"] = "black"} if (i % 8 < 4){this["j7"] = "white"} else {this["j7"] = "black"} if (i % 4 < 2){this["j8"] = "white"} else {this["j8"] = "black"} if (i % 2 < 1){this["j9"] = "white"} else {this["j9"] = "black"} this["compare"+i] = {unit00: j1,unit01: j2,unit02: j3,unit10: j4,unit11: j5,unit12: j6,unit20: j7,unit21: j8,unit22: j9} } // This creates an object for each possible block of 9 cells to compare with the actual blocks of cells around each cell in the Iterate() function function Iterate() { this["groupvec"] = [] for (i=0; i<100; i++) { for (j=0; j<100; j++) { if (i !== 0 && i !== 99) {rownum = [i-1, i, i+1]} else if (i == 0) {rownum = [99, 0, 1]} else if (i == 99) {rownum = [98, 99, 0]} if (j !== 0 && j !== 99) {colnum = [j-1, j, j+1]} else if (j == 0) {colnum = [99, 0, 1]} else if (j == 99) {colnum = [98, 99, 0]} this["group"+"R"+i+"C"+j] = {} for (r in rownum) { for (c in colnum) { this["group"+"R"+i+"C"+j]['unit'+r.toString()+c.toString()] = document.getElementById("R" + rownum[r] + "C" + colnum[c]).style.backgroundColor }} this["groupvec"].push( JSON.stringify(this["group"+"R"+i+"C"+j]) ) }} for (i=0; i<100; i++) { for (j=0; j<100; j++) { for (k=0; k<512; k++) { if (groupvec[j+(100*i)] == JSON.stringify(window["compare"+k.toString()])) { document.getElementById("R"+i+"C"+j).style.backgroundColor = document.getElementById("id"+k).style.backgroundColor }}}}} // This function finds the colours of the cells in a block of 9 cells around each cell, compares them with the 'compare' objects and then changes their colour to the colour of the 'ruleset' table with the same index as the 'compare' object. let toggler = null function Toggle() { if (toggler == null) {toggler = setInterval(Iterate.bind(null), 1000)} else {clearInterval(toggler); toggler = null} } // This provides an automated run function for the CA </script> </body> </html> A: Your code loops 5 210 000 times for every iteration (100 rows * 100 columns * 3 cells * 3 cells + 100 rows * 100 columns * 512 ruleset cells). That's quite a lot of work for every iteration, and it is exacerbated by your use of an HTML <table>, from and to which you are constantly reading and writing styles. If you want a more tenable solution, try using a Canvas for displaying your CA's state, and JavaScript arrays for handling the state. You could still perhaps use a table to set the ruleset at the start, and then store it in an array, so that when you check it you are checking an in-memory array of data. Your code then might look something like this, which loops 80 000 times (although it might be more if you incorporate your rulesets): const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const width = 100; const height = 100; const cellWidth = 4; const cellHeight = 4; // Access cells with automaton[row][column] let automaton = Array(height).fill(Array(width).fill(0))); // Initialise your automaton somehow // ... function iterate() { // Create the next automaton state to write updates to let nextAutomaton = Array(height).fill(Array(width).fill(0))); for (let y = 0; y < height; ++y) { for (let x = 0; x < width; ++x) { // Get the surrounding 8 cells // (n + MAX + 1) % MAX will wrap around // (n + MAX - 1) % MAX will wrap around const surroundingIndices = [ { x: x, y: (y + height - 1) % height }, // above { x: (x + width + 1) % width, y: (y + height - 1) % height }, // above right { x: (x + width + 1) % width, y: y }, // right { x: (x + width + 1) % width, y: (y + height + 1) % height }, // below right { x: x, y: (y + height + 1) % height }, // below { x: (x + width - 1) % width, y: (y + height + 1) % height }, // below left { x: (x + width - 1) % width, y: y }, // left { x: (x + width - 1) % width, y: (y + height - 1) % height } // above left ]; for (int i = 0; i < 8; ++i) { const cell = automaton[surroundingIndices.y][surroundingIndices.x]; // Do something based on the value of this surrounding cell // This could depend on your ruleset // ... } // Set this cell's value in the next state nextAutomaton[y][x] = 1; // Render the cell context.fillStyle = 'red'; context.fillRect(x, y, cellWidth, cellHeight); } } // Overwrite the old automaton state automaton = nextAutomaton; } For animating your automaton, you will want to use window.requestAnimationFrame, which must call itself recursively with the iterate function, and which you can start or stop with your toggle button (see window.cancelAnimationFrame).
[ "stackoverflow", "0016950731.txt" ]
Q: Create a list from another list Let's say I have: class Plus5 { Plus5(int i) { i+5; } } List<int> initialList = [0,1,2,3] How I can create, from initialList, another list calling Plus5() constructor for each element of initialList. Is here something better than the following? List<Plus5> newList = new List<Plus5>(); initialList.ForEach( i => newList.Add(Plus5(int))); A: How i can create, from initialList, another list calling Plus5() constructor for each element of initialList? So the result is List<Plus5> newList and you want to create a new Plus5 for every int in initialList: List<Plus5> newList = initialList.Select(i => new Plus5(i)).ToList(); If you want to micro-optimize(save memory): List<Plus5> newList = new List<Plus5>(initialList.Count); newList.AddRange(initialList.Select(i => new Plus5(i))); A: Use LINQ to add 5 to each number in your list. var result = initialList.Select(x => x + 5);
[ "stackoverflow", "0024020779.txt" ]
Q: Finding a point along an imaginary line between two other points Im working on a game and i have a problem. I hope someone helps me : There are 3 specified points on the screen P0 , P1, P2 P3 = Target point we need to find (X3 and Y3), if we have P1 and P2 positions. What information we have : 1-P0 position (X,Y) is known. 2- Distance between P0 and P1 is known 3- Distance between P0 and P2 is known 4-The angle between Red line and Blue line is known How can i find position of P1 and P2 (x1,y1 and x2,y2) ? Second problem is more important : 2- If i have positions of P1 and P2 , How can i find P3 which is on the imaginary line passes through P1 and P2 and distance between P3 from P2 is an specific number? (40 in this example) A: You can solve the second problem with a little vector arithmetic. The length of the vector P1->P2 is d = sqrt((x2-x1)^2 + (y2-y1)^2) The unit vector in the direction P1->P2 is therefore ((x2-x1)/d, (y2-y1)/d) Multiply this by 40 to get P2->P3 (40*(x2-x1)/d, 40*(y2-y1)/d) Finally, add P2->P3 to P2 to get P3 (x2 + 40*(x2-x1)/d, y2 + 40*(y2-y1)/d)
[ "stackoverflow", "0001047773.txt" ]
Q: how to play .mp3 songs randomly by searching for them recursively in a directory and its sub directories? Once I am in the directory containing .mp3 files, I can play songs randomly using mpg123 -Z *.mp3 But if I want to recursively search a directory and its subfolders for .mp3 files and play them randomly, i tried following command, but it does not work. mpg123 -Z <(find /media -name *.mp3) (find /media -name *.mp3), when executed gives all .mp3 files present in /media and its sub directories. A: mpg123 -Z $(find -name "*.mp3") The $(...) means execute the command and paste the output here. Also, to bypass the command-line length limit laalto mentioned, try: mpg123 -Z $(find -name "*.mp3" | sort --random-sort| head -n 100) EDIT: Sorry, try: find -name "*.mp3" | sort --random-sort| head -n 100|xargs -d '\n' mpg123 That should cope with the spaces correctly, presuming you don't have filenames with embedded newlines. It will semi-randomly permute your list of MP3s, then pick the first 100 of the random list, then pass those to mpg123.
[ "codereview.stackexchange", "0000114760.txt" ]
Q: Student registration form Problem statement Create one form having registration and student login fields for course using HTML5 elements and CSS3 styling. Expected Output Solution <style type="text/css"> .div{ height: 20px; background-color: #2A646C; width: 60%; margin: auto; } .form{ background-color: #C4D8E2; height: 350px; width: 50%; margin: auto; padding-left: 10px; padding-right: 10px; position: relative; } .para1{ height:20px; color: #5D8AA8; font-family: sans-serif; font-size: 12px; } .para2{ width:50%; } .para3{ width: 100%; margin-top: 0px; } .span1{ font-weight: bold; font-family: "Times New Roman"; font-size: 16px; color: #5D8AA8; margin-right: 5px; } .span2{ color: #5072A7; font-weight: bold; font-family: "Times New Roman"; font-size: 16px; } .span3, .span4{ font-weight: bold; font-family: "Times New Roman"; font-size: 14px; color: white; } .span3{ margin-right: 5px; } .span4{ color: white; font-style: underline; font-size: 10px; position: absolute; right: 10px; bottom: 20px; } .register{ margin: 5px; width: 50%; position: relative; } .login{ margin: 5px; width: 40%; height: 230px; position: absolute; right: 10px; top: 80px; background-color: #5072A7; padding-left: 10px; padding-right: 10px; } .submitbutton{ border: 1px solid black; width: 20%; height: 30px; position: absolute; right: 70px; } .loginbutton{ border: 1px solid orange; background-color: #5072A7; width: 20%; height: 30px; position: absolute; right: 10px; bottom: 40px; } .checkbox{ color: white; } </style> <div class="div"></div><br><br> <form class="form" method="POST" action="javascript:void(0)" enctype="multipart/form-data"> <h3>Enter the system</h3> <p class="para1"><span>It is necessary to login in Your account in order to sign up for a course.</span></p> <p class="para2"><span class="span1">ARE YOU NEW?</span><span class="span2">REGISTER</span></p> <div class="register"> <input type="text" name="username" required placeholder="User name" autocompleter="off" pattern="^[A-Za-z0-9._-]{6,10}$" size="40" maxlength="10"> <br><br> <input type="email" name="emailid" required placeholder="Email" autocompleter="off" pattern="^[A-Za-z0-9 _.-]+@[A-Za-z.-]+\.[A-Za-z]{3,4}$" size="40" maxlength="30"> <br><br> <input type="password" name="password" required placeholder="Password" autocompleter="off" pattern="^[A-Za-z0-9 _.-]{8,15}$" size="40" maxlength="15"> <br><br> <input type="password" name="confirmpassword" required placeholder="Confirm Password" pattern="^[A-Za-z0-9 _.-]{8,15}$" size="40" maxlength="15" autocompleter="off"> <br><br> <input type="submit" name="register" value="Register" class="submitbutton"> </div> <div class="login"> <p class="para3"><span class="span3">ALREADY A STUDENT?</span><span class="span4">LOGIN</span></p> <br><br> <input type="text" name="loginname" required placeholder="User name" autocompleter="off" pattern="^[A-Za-z0-9._-]{6,10}$" size="40" maxlength="10"> <br><br> <input type="password" name="loginpassword" required placeholder="Password" autocompleter="off" pattern="^[A-Za-z0-9 _.-]{8,15}$" size="40" maxlength="15"> <br><br> <input type="checkbox" name="remember" value="yes"><span class="checkbox">Remember me?</span> <br><br> <input type="submit" name="register" value="Login" class="loginbutton"> <span class="span4">Forgot Password?</span> </div> </form> 1) How do you review the usage of position attribute? Can it be avoided for login div container, register button and loginbutton? 2) Can we improvise this code to be responsive? 3) Can the regex pattern be improved? A: Styling and readability You are using classes as id's, both by not using a class twice or more and by naming them after the specific element you are using the class for. You do not use css-selectors to their full extent. You can select elements that appear as children of an other element for example, and you can select elements based on (part) of the value of an attribute. Consider using input[type=checkbox] span instead of .checkbox for example. Another part is that you do not select groups of elements based on what you want them to be. Want elements in the right box to have white text? Do not set the text color for each idclass that appears in there, but select #login and set the text color there. The headers appear with different sizes, and one of the elements with class span4 appears below the form through the other element with class span4. You should make the layout consistent. Validation, semantics and correctness You should validate your code on the site of w3. Validation shows that you use an attribute autocompleter for your input elements. This is a non-existing attribute. You likely meant to use autocomplete (without an 'r'). You use the pattern attribute without the title attribute. When the user enters an invalid value, it is not made clear to the user how to improve this. Add a title attribute to tell what input is expected. Your login button and register button both have the name "register". You can use a <label> element to better specify that the text in that element explains what a checkbox is for. Either make the checkbox input element a child of the label, or use the for attribute of the label to link the checkbox and label. In either case this has the added benefit that you can check and uncheck the checkbox by clicking the label. You are using one form. This means that all input fields in that form that are marked as required must be filled in. Except that this means that you have to fill in both the registration part and the login part to be able to pass the form. Responsiveness and use of position There are various ways of making two boxes appear next to each other. Other ways of accomplishing this is by using float, or preferably flex boxes. The latter one will make it easier to create a responsive layout that displays well on other screen sizes. Your over-usage of ids-disguised-as-classes might make it difficult to create a responsive layout, as you are thinking of elements as individual components, rather than of elements in relation to each other and what certain group of elements have in common. Since you have control over both the html and the css, there is no real reason why you shouldn't be able to create a responsive layout using @media queries. See mdn for more information about usage of flexboxes.
[ "stackoverflow", "0015626415.txt" ]
Q: Cocos2d removing objects in distance (java) Hi i have sprite which is granade ^^ Problem is when it exploding. It should kill all targets in distance (in this case all on screen) but it kills them randomly. public void Explode(Object sender) { ArrayList<Enemy> targetsToBlow = new ArrayList<Enemy>(); targetsToBlow.addAll(targets); Bullet bullet = (Bullet)sender; float x = bullet.getPosition().x; float y = bullet.getPosition().y; // Log.i("Explode", "boom"); // Log.i("Target",String.valueOf(y)); for (int i=0;i<targetsToBlow.size();i++) { Enemy enemy = targetsToBlow.get(i); float xd = enemy.getPosition().x - x; float yd = enemy.getPosition().y - y; float distance = (float) Math.sqrt(xd*xd + yd*yd); Log.i("Distance", String.valueOf(distance)); if(distance<20000/2) { enemy.setHp(bullet.dmg); Log.i("Explode", "boomed1"); } else if(distance<=20000) { enemy.setHp(bullet.dmg/2); Log.i("Explode", "boomed2"); } if(enemy.getHp()<=0) { targets.remove(enemy); removeChild(enemy, true); money++; moneyLabel.setString("GOLD: "+money); } targetsToBlow.remove(i); } projectiles.remove(bullet); removeChild(bullet, true); } I tried to do it from last index, but then it's not killing and granade stays on screen. I have no idea what is wrong :/ Please help A: The problem was in arraylist items index after removing them. I think that was reason why some of them stays on scene. I made it same like in simple shoot: public void Explode(Object sender) { ArrayList<Enemy> targetsToDelete = new ArrayList<Enemy>(); Bullet bullet = (Bullet)sender; for (Enemy enemy : targets){ if(isEnemyInRange(bullet, enemy, 100)) { enemy.setHp(bullet.dmg); if(enemy.getHp()<=0) { targetsToDelete.add(enemy); } } } for (Enemy target : targetsToDelete){ targets.remove(target); removeChild(target, true); } projectiles.remove(bullet); removeChild(bullet, true); } So items index isn't changed and after first loop i can destroy and remove all items that i need :)
[ "stackoverflow", "0061117361.txt" ]
Q: How to use custom torch.autograd.Function in nn.Sequential model Is there any way that I can use custom torch.autograd.Function in a nn.Sequential object or should I use explicitly an nn.Module object with forward function. Specifically I am trying to implement a sparse autoencoder and I need to add L1 distance of the code(hidden representation) to the loss. I have defined custom torch.autograd.Function L1Penalty below then tried to use it inside a nn.Sequential object as below. However when I run I got the error TypeError: __main__.L1Penalty is not a Module subclass How can I solve this issue? class L1Penalty(torch.autograd.Function): @staticmethod def forward(ctx, input, l1weight = 0.1): ctx.save_for_backward(input) ctx.l1weight = l1weight return input, None @staticmethod def backward(ctx, grad_output): input, = ctx.saved_variables grad_input = input.clone().sign().mul(ctx.l1weight) grad_input+=grad_output return grad_input model = nn.Sequential( nn.Linear(10, 10), nn.ReLU(), nn.Linear(10, 6), nn.ReLU(), # sparsity L1Penalty(), nn.Linear(6, 10), nn.ReLU(), nn.Linear(10, 10), nn.ReLU() ).to(device) A: The nn.Module API seems to work fine but you should not return None in your L1Penalty forward method. import torch, torch.nn as nn class L1Penalty(torch.autograd.Function): @staticmethod def forward(ctx, input, l1weight = 0.1): ctx.save_for_backward(input) ctx.l1weight = l1weight return input @staticmethod def backward(ctx, grad_output): input, = ctx.saved_variables grad_input = input.clone().sign().mul(ctx.l1weight) grad_input+=grad_output return grad_input class Model(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(10,10) self.fc2 = nn.Linear(10,6) self.fc3 = nn.Linear(6,10) self.fc4 = nn.Linear(10,10) self.relu = nn.ReLU(inplace=True) self.penalty = L1Penalty() def forward(self, x): x = self.fc1(x) x = self.relu(x) x = self.fc2(x) x = self.relu(x) x = self.penalty.apply(x) x = self.fc3(x) x = self.relu(x) x = self.fc4(x) x = self.relu(x) return x model = Model() a = torch.rand(50,10) b = model(a) print(b.shape)
[ "stackoverflow", "0027746680.txt" ]
Q: How do I properly select a certain part of an image inside a picture box in C# and highlight it? I have been trying to write a program, to be able to load an image on a form and select a rectangle on it, then load that rectangle onto another picture box (pictureBox2), and I also want to be able to highlight what I have selected on the original picture, in pictureBox1, as I move my mouse. So far I have this code, but it doesn't properly respond to the mouseMove event, the rectangle that I highlight isn't selected properly. What is the problem? public partial class Form1 : Form { Bitmap original; bool isSelecting; int x0, y0, x1, y1; public Form1() { InitializeComponent(); pictureBox1.MouseDown += new MouseEventHandler(picOriginal_MouseDown); pictureBox1.MouseMove += new MouseEventHandler(picOriginal_MouseMove); pictureBox1.MouseUp += new MouseEventHandler(picOriginal_MouseUp); } #region helpder methods // Start selecting the rectangle. private void picOriginal_MouseDown(object sender, MouseEventArgs e) { if(original != null) { isSelecting = true; // Save the start point. x0 = e.X; y0 = e.Y; } } // Continue selecting. private void picOriginal_MouseMove(object sender, MouseEventArgs e) { if(original != null) { // Do nothing it we're not selecting an area. if(!isSelecting) return; // Save the new point. x1 = e.X; y1 = e.Y; // Make a Bitmap to display the selection rectangle. Bitmap bm = new Bitmap(original); // Draw the rectangle. using(Graphics gr = Graphics.FromImage(bm)) { gr.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x0 - x1), Math.Abs(y0 - y1) ); } // Display the temporary bitmap. pictureBox1.Image = new Bitmap(bm, new Size(pictureBox1.Width, pictureBox1.Height)); } } // Finish selecting the area. private void picOriginal_MouseUp(object sender, MouseEventArgs e) { if(original != null) { // Do nothing it we're not selecting an area. if(!isSelecting) return; isSelecting = false; // Display the original image. pictureBox1.Image = original; // Copy the selected part of the image. int wid = Math.Abs(x0 - x1); int hgt = Math.Abs(y0 - y1); if((wid < 1) || (hgt < 1)) return; Bitmap area = new Bitmap(wid, hgt); using(Graphics gr = Graphics.FromImage(area)) { Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt); Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt); gr.DrawImage(original, dest_rectangle, source_rectangle, GraphicsUnit.Pixel); } // Display the result. pictureBox2.Image = area; } } #endregion private void button1_Click(object sender, EventArgs e) { if(original != null) { } } private void button2_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "jpg files (*.jpg)|*.jpg|All files(*.*)|*.*"; if(dialog.ShowDialog() == DialogResult.OK) { original = new Bitmap(dialog.FileName); pictureBox1.Image = new Bitmap(original, new Size(pictureBox1.Width, pictureBox1.Height)); } dialog.Dispose(); } } A: I think your problem is the 'original' image size which is not the same as the picturebox size. Try this code to compensate for the zoom ratio between your 'original' image and the picturebox size: // Draw the rectangle. float zoomX = (float)original.Size.Width / pictureBox1.Width; float zoomY = (float)original.Size.Height / pictureBox1.Height; using (Graphics gr = Graphics.FromImage(bm)) { gr.DrawRectangle(Pens.Red, Math.Min(x0, x1) * zoomX, Math.Min(y0, y1) * zoomY, Math.Abs(x0 - x1) * zoomX, Math.Abs(y0 - y1) * zoomY ); } This fixes the red rectangle in my case. But the copied part in picturebox2 is still not correct... And this fixes the copy to the second picturebox: // Copy the selected part of the image. float zoomX = (float)original.Size.Width / pictureBox1.Width; float zoomY = (float)original.Size.Height / pictureBox1.Height; int wid = (int)(zoomX * Math.Abs(x0 - x1)); int hgt = (int)(zoomY * Math.Abs(y0 - y1)); if ((wid < 1) || (hgt < 1)) return; Bitmap area = new Bitmap(wid, hgt); using (Graphics gr = Graphics.FromImage(area)) { Rectangle source_rectangle = new Rectangle((int)(zoomX * Math.Min(x0, x1)), (int)(zoomY * Math.Min(y0, y1)), wid, hgt); Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt); gr.DrawImage(original, dest_rectangle, source_rectangle, GraphicsUnit.Pixel); }
[ "stackoverflow", "0004057728.txt" ]
Q: Is there a convention for maintaining both a free and pro app version from the same codebase in Eclipse? I am releasing two versions of an app--free and paid. The differences between the two are few, and I would like to release both using the same codebase (maybe a different constant defined for the other build?). Has anyone done this? Can someone point me in the right direction? Thanks! A: Use an Android library project, which was specifically designed for your free/paid scenario.
[ "stackoverflow", "0032898192.txt" ]
Q: Java Swing adding mouse Listener (inner class) for an array of buttons leads to malfunction Ok, so the program I want to build is simple. There are five buttons named from 0 to 4. If any of the buttons are pressed, then the number 0 to 4 is printed in console. I have used a GridLayout to place the buttons in the frame. And to set up each button I have created a method, inicializarIG(). This inicializarIG() method creates an array of 5 buttons and inside a for loop it does: Create an instance of a button for each cell in the array of buttons. Set up a mouseListener for each button. The value to print in each Listener is different, it is determined by the index of the loop (AND I WANT TO DO IT BY USING THE INDEX!). Add The button to the main frame. Surprisingly, This simple program doesn´t work properly. It always print the number "5" no matter what button is pressed: NOTE: I had to put the index var outside the inicializarIG() method in order to fulfill the var scope for the Listeners. I don't know if the problem is related, just saying in cause it might help. THE CODE: import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JFrame; public class IGrafica { private JFrame frame; public int index=0; public IGrafica(){ frame = new JFrame(); configureFrame(); inicializarIG(); } public void configureFrame(){ frame.setBounds(100,100,400,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new GridLayout(1,5)); // } public void inicializarIG(){ //Buttons JButton [] botones = new JButton [5]; //Loop to set up buttons and add the mouseListener for (index = 0; index < botones.length; index++) { botones[index] = new JButton(Integer.toString(index)); //Set up each listener botones[index].addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { System.out.println(index); //texto.setBackground(colores[index]); } }); //Add the button frame.getContentPane().add(botones[index]); } } public void visualizate(){ frame.setVisible(true); } public static void main(String[] args) { IGrafica window = new IGrafica(); EventQueue.invokeLater(new Runnable() { public void run() { window.visualizate(); } }); } } Thank you in advance. Any idea will be welcomed. Jesús A: First of all, don't use a MouseListener for this, but rather use an ActionListener, since this works best for buttons. Next of all, you need to remember that your listener is a class of its own, and it needs a variable of its own to store its own index, else it uses the final value of the loop index which is not what you want. Either this or use the ActionEvent's actionCommand property, a value which will match the text of the button. So: botones[index].addActionListener(new MyActionListener(index)); and // a private inner class private class MyActionListener implements ActionListener { private int index; public MyActionListener(int index) { this.index = index; } @Override public void actionPerformed(ActionEvent e) { System.out.println("index is: " + index); System.out.println("Action Command is: " + e.getActionCommand()); } } Or if you want to use an anonymous inner class: botones[index].addActionListener(new ActionListener() { private int myIndex; { this.myIndex = index; } @Override public void actionPerformed(ActionEvent e) { System.out.println("index is: " + myIndex); } });
[ "math.stackexchange", "0001171328.txt" ]
Q: normal distribution word problem Suppose the amount of heating oil used annually by households is normally distributed, with a mean of 760 liters per household per year and a standard deviation of 150 liters of heating oil per year. If the members of a particular household were scard into using a fue conservation measures by newspaper acounts of the probably price of heating oil next year, and they decide they wanted to use less oil than 97.5% of all households, what is maximum amount of oil they can use and stil accomplish their objective? A: The normal distribution is defined as $$P(X)=\frac{1}{\sigma \sqrt{2\pi}}e^{-\frac{(X-\mu)^{2}}{2\sigma^{2}}}$$ Where X is the amount of oil for wich you want the probability, $\mu$ is the mean and $\sigma$ is the standard deviation. What you want is to take the 97.5% of companies that use the most amount of oil, and find out how much oil is used by the most economic of those, therefore $$\int_{X_1}^{\infty}P(X)dX=\int_{X_1}^{\infty}\frac{1}{\sigma \sqrt{2\pi}}e^{-\frac{(X-\mu)^{2}}{2\sigma^{2}}}dX=0.975$$ and solve the equation for $X_1$. The logic behind this, is that this integral will give you the probability that the amount of oil used will be less than that used by 97.5% of the companies. This integral I believe can only be calculated numerically, so making the integration start at infinity in the program and progressing until it reaches the value of 0.975 is probably the way to go, I don't know if there are more efficient methods of solving this.
[ "stackoverflow", "0028058651.txt" ]
Q: AFNetworking POST Value Here's my question: NSDictionary *parameters = @{@"type": @"5", @"xq": @"a", @"apid": @"b", @"apsecret": @"c", @"astoken": @"d"}; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setValue:[NSString stringWithFormat:@"text/plain; charset=UTF-8"] forHTTPHeaderField:@"Content-Type"]; if i use GET : [manager GET:@"http://127.0.0.1/123.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"responseObject : %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error : %@", error); }]; i can get $_GET['parameters'] value but when i use POST : [manager POST:@"http://127.0.0.1/123.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"responseObject : %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error : %@", error); }]; i always get $_POST['parameters'] value is null..... am i doing something wrong in the setting? A: sorry for all, i found it's can work AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://127.0.0.1/123.php"]]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; [manager POST:@"123.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) { NSLog(@"responseObject : %@", responseObject); } failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"error : %@", error); }];
[ "stackoverflow", "0018653287.txt" ]
Q: How to update Drools Plugin in Eclipse? I am using drools older version 5.4.0 in my project by using this version I got one issue which we can not pass more than 255 arguments but this bug is resolved in drools latest version 5.5.0 and 6.0.0. So Now: Can anyone explain how can I update my drools version to 5.5.0 ? If can I update to latest version will it effect to presently working code ? A: Assuming you are using a Drools library in your projects, you should create a new runtime with the version of Drools you want to use (download the bin artefact, unzip and create a runtime based on that folder), and use that for your project. If you are using maven to define your dependencies, simply update the version of Drools you want to use in your pom.xml. Upgrading from 5.4 to 5.5 shouldn't really impact working code. Upgrading to 6.0 should also be backwards compatible if you have the right jars in your classpath, but might be slightly more tricky (as that is a mayor upgrade). You can also update your Eclipse plugin (for example using an update site like the JBossTools update site for Eclipse Kepler: http://download.jboss.org/jbosstools/updates/integration/kepler/integration-stack/aggregate/ ) but I don't think that is absolutely necessary. Kris
[ "stackoverflow", "0018946842.txt" ]
Q: why I can't show arabic language on HTML I have a website and this is the meta in the head tag <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> but all arabic text shows like in the picture.. but when I change the browser unicode to arabic it shows correctly, but I have to to it every refresh so it is not a solution at all. A: For solve that problem, You only have to save all your PHP files in UTF-8 too... Check that! :P A only meta charset in UTf-8 doesn't works... Rembember it forever :P It happens to me every time.. :P If you use Sublime Text, you can save it like that: if you not, I recommend you you to use sublime text: http://www.sublimetext.com/ it will give you some life years.. xD
[ "stackoverflow", "0008130608.txt" ]
Q: python smtplib - non-blocking mailing I'm using smtplib sending out mails, rather frequently. I'm using my own SMTP server as a relay. The problem is every time a connection is issued smtplib.SMTP(...) the whole process is blocked. I'm new to python(v3), and is wondering if smtplib already support asynchronous mailing. I also tried to delegate the blocking work load to a MTA such as sendmail and then issue separate processes in python code so that it doesn't block the flow. I'm not sure if it's good practice. What would be a good solution for my case? A: You can do that with a message queue (like rabbit MQ for example). Instead of sending an email directly, you leave the message to the queue. Posting into the queue returns immediately. Then, in the background, some process is emptying the queue and sending emails. More info here: http://www.rabbitmq.com/
[ "stackoverflow", "0026501050.txt" ]
Q: Set proxy for terminal in linux In CentOS 7 how can i connect terminal through a "proxy with username and password" and use some command like: yum update For now when i use this command i got this error: Loaded plugins: fastestmirror, langpacks Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os error was 14: curl#7 - "Failed to connect to 2a02:2498:1:3d:5054:ff:fed3:e91a: Network is unreachable" One of the configured repositories failed (Unknown), and yum doesn't have enough cached data to continue. At this point the only safe thing yum can do is fail. There are a few ways to work "fix" this: 1. Contact the upstream for the repository and get them to fix the problem. 2. Reconfigure the baseurl/etc. for the repository, to point to a working upstream. This is most often useful if you are using a newer distribution release than is supported by the repository (and the packages for the previous distribution release still work). 3. Disable the repository, so yum won't use it by default. Yum will then just ignore the repository until you permanently enable it again or use --enablerepo for temporary usage: yum-config-manager --disable <repoid> 4. Configure the failing repository to be skipped, if it is unavailable. Note that yum will try to contact the repo. when it runs most commands, so will have to try and fail each time (and thus. yum will be be much slower). If it is a very temporary problem though, this is often a nice compromise: yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true Cannot find a valid baseurl for repo: base/7/x86_64 A: yum uses HTTP so you need to set a http proxy for your environment. Check this out: https://www.centos.org/docs/5/html/yum/sn-yum-proxy-server.html
[ "stackoverflow", "0039582859.txt" ]
Q: Python Regex remove numbers and numbers with punctaution I have the following string line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)" I would like to remove the numbers 1234567 7852853427.111 using regular expresisions I have this re nline = re.sub("^\d+\s|\s\d+\s|\s\d\w\d|\s\d+$", " ", line) but it is not doing what i hoped it would be doing. Can anyone point me in the right direction? A: You can use: >>> line = "1234567 7852853427.111 https://en.wikipedia.org/wiki/Dictionary_(disambiguation)" >>> print re.sub(r'\b\d+(?:\.\d+)?\s+', '', line) https://en.wikipedia.org/wiki/Dictionary_(disambiguation) Regex \b\d+(?:\.\d+)?\s+ will match an integer or decimal number followed by 1 or more spaces. \b is for word boundary.
[ "stackoverflow", "0015394910.txt" ]
Q: JUnit Testing Java EE web-service endpoint methods How is a Java EE web-service endpoint method tested using JUnit? I'm using Spring and MyBatis frameworks and the standard Maven directory structure in Eclipse. I know I could simply test each method by creating a JUnit test-case for it. But, I'm wondering how I can make use of the @WebService, @WebMethod, @WebResult tags for the testing. @WebService(endpointInterface = "com.ws.BrowserService", name = "BrowserService", targetNamespace = "http://abc.def.com") public interface BrowserService { /** * Runs the provided SQL query and returns the result. * @param queryText is the SQL query text. * @return The query result is returned in the form of List<Object>. */ @WebMethod @WebResult(name = "Object") public List<Object> runQuery( @WebParam(name = "QueryText") String queryText); } Edit Implementation @WebService(targetNamespace = "http://abc.def.com", portName = "BrowserPort", serviceName = "BrowserService") public class BrowserServiceImpl implements BrowserService { @Autowired private QueryMapper queryMapper; public List<Object> runQuery(String queryText) { List<Object> queryResult= new ArrayList<Object>(); queryResult = queryMapper.runQuery(queryText); return queryResult; } } A: Turns out, what I was looking for in fact was Integration Testing.
[ "stackoverflow", "0020523136.txt" ]
Q: My username input is redirecting to about page <?php ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="css/global.css"> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lusitana" </head> <body> <div id="header"> <h1>Lorem ipsum dolor sit amet.</h1> <a href = "index.php"</href><h2>Home</h2> <a href = "news.php"</href><h2>News</h2> <a href = "login.php"</href><h2>Login</h2> <a href = "about.php"</href><h2>About</h2> </div> <div id="login"> <label for="username">Type the username:</label> <input type = "text" name="username" id="username"/> </div> </body> </html> When I click on the input for typing the username I get redirected to other page of my website (about.php) Can anyone explain why is this happening and give instructions on how to fix? EDIT: Everything is redirecting to about.php minus the other links from the header A: <a href = "index.php"</href><h2>Home</h2> Should be <a href = "index.php"><h2>Home</h2></a> Closing the anchor tag incorrectly link not closed <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lusitana" <a href = "index.php"><h2>Home</h2></a> <a href = "news.php"><h2>News</h2></a> <a href = "login.php"><h2>Login</h2></a> <a href = "about.php"><h2>About</h2></a>
[ "stackoverflow", "0013607192.txt" ]
Q: Check if value in 3 different date ranges in Mysql query I have a table wp_posts which contains post_date and author_id columns I need to find the author_id from wp_posts where has posts in (all) 3 time ranges: wp_posts.post_date BETWEEN '2012-11-05 00:00:00' AND '2012-11-10 23:59:59' wp_posts.post_date BETWEEN '2012-11-12 00:00:00' AND '2012-11-17 23:59:59' wp_posts.post_date BETWEEN '2012-11-19 00:00:00' AND '2012-11-25 23:59:59' Looks simple, but I can't figure out. If I put AND between every date range, will always return 0. Any ideas? A: Why don't you put OR: (wp_posts.post_date BETWEEN '2012-11-05 00:00:00' AND '2012-11-10 23:59:59') OR (wp_posts.post_date BETWEEN '2012-11-12 00:00:00' AND '2012-11-17 23:59:59') OR (wp_posts.post_date BETWEEN '2012-11-19 00:00:00' AND '2012-11-25 23:59:59') EDIT: SELECT author_id FROM wp_posts WHERE author_id IN ( SELECT author_id FROM wp_posts WHERE post_date BETWEEN '2012-11-05 00:00:00' AND '2012-11-10 23:59:59' ) AND author_id IN ( SELECT author_id FROM wp_posts WHERE post_date BETWEEN '2012-11-12 00:00:00' AND '2012-11-17 23:59:59' ) AND author_id IN ( SELECT author_id FROM wp_posts WHERE post_date BETWEEN '2012-11-19 00:00:00' AND '2012-11-25 23:59:59' ) Is this what you need?
[ "stackoverflow", "0013462842.txt" ]
Q: PhoneGap app for Symbian | "Application closed : WidgetUi KERN-EXEC 3" I develop phonegap app for symbian (cordova for symbian I'm get from here) After 3-5 seconds when my app begin execute ajax request, I get error: Maybe someone faced with this issue? Update1: I make cross-domain ajax request with jquery mobile 1.8.1 $.ajax({ type: 'GET', url: "http://example.org/some/path", dataType: "json", mimeType: "application/json", headers: { "TOKEN": "%SOME_TOKEN%" } }).done(function (data) { // success processing }).fail(function (xhr, textStatus) { // fail processing }); A: It could be as simple as the fact that you're missing " from the url line of your AJAX creation, but I suspect it isn't. I'm guessing that's a copying typo. This error message means your getting an uncaught exception which is bringing your app down. Other people have reported JQuery for mobile being buggy, and having problems with certain HTTP Response statuses. I suggest bypassing it altogether, and making your own AJAX request, as a workaround (plenty of examples on the internet; I would alert the response status just so you can see what you're getting).. If that works, you can investigate whether other version of JQuery suffer from the same bugs. Example AJAX without JQuery: <script type="text/javascript"> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { // do stuff with xmlhttp.responseText; } } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); </script>
[ "stackoverflow", "0029968241.txt" ]
Q: Why apply() converts date objects to numeric objects? Why apply() converts my date objects to numeric before calling the user function? apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"), 1)), 1, function(x) { return(class(x)) }) [1] "numeric" "numeric" "numeric" "numeric" "numeric" And why as.Date() doesn't have the origin parameter set to "1970-01-01" by default? > as.Date(apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"), 1)), 1, function(x) { return(x) })) Error in as.Date.numeric(apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"), : 'origin' must be supplied > as.Date(apply(matrix(seq(as.Date("2010-01-01"), as.Date("2010-01-05"), 1)), 1, function(x) { return(x) }), origin="1970-01-01") [1] "2010-01-01" "2010-01-02" "2010-01-03" "2010-01-04" "2010-01-05" A: There is a function seq.Date in the base package that will allow you to make a sequence for a Date object. But a matrix will still only take atomic vectors, so you will either just have to call as.Date() again whenever you need to use the Date, or just store it in a dataframe because that can hold "Date" class values. As far as the default parameter for as.Date, I don't think it makes sense to have 1970 set as the default. What if people are analyzing data from before that date for whatever possible reason?
[ "stackoverflow", "0026431457.txt" ]
Q: VBA Excel: Delete worksheet when it has a certain name For my workbook, when a user wants to delete tabs for a project, they put the PRJNumber in cell T14 of the program tab. There are various other tabs with that project number as the last 6 digits of the name (e.g., A_PRJNumber, B_PRJNumber, etc). All PRJNumbers are 6 digits long. The code below should work, the two msgboxes indicate that it is reading both the 6 digits in cell T14 and in the tab name correctly, but it does not delete the tab or give me any errors. Ideas? Sub Delete_Project() Dim wks As Worksheet Dim PRJNumber PRJNumber = Sheets("Program").Range("T14").Value MsgBox (PRJNumber) For Each wks In ActiveWorkbook.Worksheets MsgBox (Right(wks.Name, 6)) If Right(wks.Name, 6) = PRJNumber Then wks.Delete End If Next wks End Sub A: What I'm suspecting is that T14 contains some extra spaces/etc. For example: Dim str1 as String, str2 as String str1 = "123456 " str2 = "123456" '## These two message boxes should look the same, you would not be able to tell the difference: MsgBox str1 MsgBox str2 '## But by comparing their inputs, you can see they are NOT the same MsgBox str1 = str2 If this is the case, then you can use the TRIM function which will take care of user-error if they inadvertently enter spaces (often these are result of copy/paste from other applications, etc.): PRJNumber = Trim(Sheets("Program").Range("T14"))
[ "stackoverflow", "0018769007.txt" ]
Q: How to get revision date time using sharpsvn (working copy) I need to get the date/time when the revision was commited, Now I can get last revision but not finding how to get the date and time when this revision created. This is my code now. Int32 LastRevision; var workingCopyClient = new SvnWorkingCopyClient(); SvnWorkingCopyVersion version; workingCopyClient.GetVersion(RootFolder, out version); LastRevision = version.End; workingCopyClient.Dispose(); A: Have you tried using the SvnClient class? There's a couple of options you have with that: Firstly: How to get latest revision number from SharpSVN? or this: using (SvnClient client = new SvnClient()) { Collection<SvnLogEventArgs> logEventArgs; SvnLogArgs logArgs = new SvnLogArgs { Limit = 1 }; client.GetLog(target, logArgs, out logEventArgs); DateTime revisionTime = logEventArgs[0].Time; }
[ "opensource.stackexchange", "0000009254.txt" ]
Q: What's the correct way to include licence for part of the code from another project Let's say I have an open source project (Apache2) And I only take one function from another project which is also open sourced under MIT/Apache2 license, and put it together with my code in a single file. Where do I put original license from the function author? How to attribute author for just that one single function? A: For clarity, it is easiest if you can put the third-party source code in a separate source file. Then you can put the copyright and license notices without any issue at the normal place (the top) in the file. If you can't use a separate source file and both projects use the same license (or the third party code uses a dual license with the license of your project among the choices), then you should add the copyright of the third party code next to your copyright. You don't have to copy over the license, because that should match the already existing license statement for your own code. I once had a situation where I included third-party code with a different license into a source file, and I solved that by stating at the top of the file (next to the copyright/license applying to the bulk of the file) that some functions are subject to a different license. Then, in a comment block directly next to the relevant functions, I included the license that applied to that function.
[ "stackoverflow", "0042737060.txt" ]
Q: C++ - How to override child class methods using base pointers So. I am working on a small game project for school and I got collision and stuff working for my objects, and the idea is to check if an object collides with another and then have the specific logic for each type have a bunch of overloaded functions depending on the object being sent in. For instance, if the object is a player-controlled object, enemies will hurt it, but if it is a powerup colliding with an enemy, things will be fine. So, I was hoping I could do something like (everything inherits from Obj obviously): std::vector<Obj*> list; list.push_back(new Powerup()); list.push_back(new Enemy()); list.push_back(new Player()); for (auto i: list) { for (auto j: list) { if (collision(i,j)) { i->doStuff(*j); } } } But I'm having trouble finding a way to send in the proper type. I made a test program demonstrating the problem: #include <iostream> class A { public: virtual void doStuff(A& T) { std::cout << "A->A!" << std::endl; } }; class B : public A { public: virtual void doStuff(A& T) { std::cout << "B->A!" << std::endl; } }; class C : public A { public: virtual void doStuff(A& T) { std::cout << "C->A!" << std::endl; } virtual void doStuff(B& T) { std::cout << "C->B!" << std::endl; } }; int main() { A* base; A a; B b; C c; c.doStuff(a); c.doStuff(b); base = &a; c.doStuff(*base); base = &b; c.doStuff(*base); return 0; } And running it I get this: C->A! C->B! C->A! C->A! When I was expecting: C->A! C->B! C->A! C->B! Any idea how to make this work? A: What you are attempting here is called double dispatch - making a function virtual with respect to two arguments. C++, like most programming languages with virtual functions, does not support this natively. Consider the c.doStuff(*base); call. It really has two arguments under the hood: c (which ends up as *this inside of the function) and *base. Now the problem is that doStuff is virtual only with respect to the first argument. That's why the call would end up in one of C's doStuff functions even if c had a static base-class type. The second argument, however, is not handled in a polymorphic way. The static type of base is an A*, even it currently points to a subclass object, so *base yields an A, and that matches the A& overload. While it's true that C++ does not support double dispatch, there are ways to simulate it. The Visitor Design Pattern is often cited as a way to do that. For example, see Difference betwen Visitor pattern & Double Dispatch. P.S.: Mixing overriding with overloading is rarely a good idea, as it can become extremely confusing to find out, as a human reader of the code, which function will be called.
[ "opendata.stackexchange", "0000004092.txt" ]
Q: Is it okay to download all datasets from a government open data portal? I'm thinking of making a copy of all my country's open data portal datasets. I will be rate limiting my downloads. Is that okay or is it bad manners to get a full data dump? I am asking of the ethical/moral considerations. A: Bad manners have nothing to do with it. As a taxpayer, it's your data, and they're making it available for you to download. Your country also benefits from having backups of their dataset floating around out there. You could take the public service angle of it to the next level by uploading a copy of the full archive to the Internet Archive using their S3-compatible interface: https://archive.org/help/abouts3.txt If you think their system is creaky and might strain at giving you the full dataset, or you think there's a more efficient way for them to give you a full dump -- then you can always email or call and ask them. But do it after you've got your first complete copy downloaded, just in case. A: The Philippine Government has published (Jan. 2014) on the government website (gov.ph) the 2014-2106 action plan for open data. In Section 8, Appendix F (Creative Commons Attribution 3.0 Philippines) describes how the data is licensed to the public. From my reading of it, you are free to create derivative works (e.g., your own archive), including for commercial purposes - but most provide attribution back to data.gov.ph. http://www.gov.ph/downloads/2014/01jan/Open-Data-Philippines-Action-Plan-2014-2016.pdf
[ "stackoverflow", "0034512810.txt" ]
Q: How many times const subquery in select is executed? I have query: SELECT id, (SELECT `name` from `config` WHERE id = 1) AS 'config' FROM customers How many times is the subquery executed? Does MySql cache this subquery constant or does it execute it for every row? A: For a simple question here is your simple answer: The subquery is only executed once, and the result is indeed held in a cache. It does NOT get executed for each row. That is, of course, unless you add a modifier such as SQL_NO_CACHE to it.
[ "stackoverflow", "0001075603.txt" ]
Q: How do I sort a string array alphabetically by length? By alphabetically by length I mean as follows: given: { "=", "==>>", "=>>", "=>", "!>" } I want to get out: !> = => =>> ==>> I'm currently just using OrderBy(x => x.Length).ToArray() anyone got a better lambda? Is this reasonably possible? lol, I'm not sure what the rule conventions here would be :-( A: Writing your own string comparer you can do this, which meets both set of requirements you've posted. public class MyStringComparer : IComparer<string> { #region IComparer<string> Members public int Compare(string x, string y) { if (x[0] == y[0]) { return x.Length.CompareTo(y.Length); } else return x[0].CompareTo(y[0]); } #endregion } a bcde bcd b bced cb would yield: a b bcd bcde bced cb and { "=", "==>>", "=>>", "=>", "!>" } yields: !> = => =>> ==>> by calling: myStringCollection.OrderBy(x=>x, new MyStringComparer).ToArray(); A: I don't think the sorting you're trying to do is any different than a standard dictionary sort, unless I'm missing something.
[ "stackoverflow", "0044726818.txt" ]
Q: Win32 process creation order I would like to enumerate all the instances of an application and determine which instance was created first (oldest). Given a list of HWNDs that belong to the process instances, can I sort the list to determine the order of creation? If not, is there another way? EDIT 1 : the windows being enumerated are not created by my process, they were created long before my process started execution. EDIT 2: As mentioned in the comments, I am interested in the creation time of the processed. I need the HWND of he main window of the oldest instance of the application. Not sure how to get the HWND from the process ID. A: There are two different ways you can approach this: Start with the windows Use EnumWindows(), or a FindWindow/Ex() loop, to find the candidate app windows you are interested in. In the case of EnumWindows(), you can use things like GetClassName() and GetWindowText() in the callback. Use GetWindowThreadProcessId() to get each window's PID. Use OpenProcess() to open each PID, and GetProcessTimes() to get its creation time. Now you can sort the times to get the oldest, and you will know the window(s) that go with the corresponding process. Start with the processes Use EnumProcesses(), or a Process32(First|Next)() loop, to find the PIDs of each instance of the app path+filename you are interested in. Use OpenProcess() and GetProcessTimes() to get their creation times, and then sort them. Then, with the oldest PID, you can enumerate windows looking for the one(s) that belong to that PID. You can either: enumerate all windows as above, using GetWindowThreadProcessId() to look for the PID. use EnumThreadWindows() on each thread of the process. To get the process's thread IDs, you can use a Thread32(First|Next)() loop. Optionally, assuming the process's main thread is the one creating the window(s) you want, you can limit the window enumeration to just that thread. Enumerate the pricess's threads, using OpenThread() and GetThreadTimes() to find the oldest thread ID, which will be the main thread.
[ "stackoverflow", "0047883784.txt" ]
Q: Maven cucumber reporting from eclipse not generating the reports as per this plugin Trying to generate the reports as per the maven cucumber reporting Link to maven cucumber reporting Made the necessary changes in the pom.xml file as explained here tutorial on configuring reports But the reports are getting generated in the simple html file but not as per the cucumber reports. pom.xml <pluginManagement> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.${java.version}</source> <target>1.${java.version}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.20</version> <configuration> <!-- <testFailureIgnore>true</testFailureIgnore> --> <includes> <exclude>**/*RunCukesTest.java</exclude> <!-- <include>**/*RunCukesTest.java</include> --> </includes> <!-- <excludes> <exclude>**/*RunCukesTest.java</exclude> </excludes> --> </configuration> </plugin> <!-- This is for Cucumber Custom Report plug in we specify the configuration details under configuration tag. --> <!-- http://startingwithseleniumwebdriver.blogspot.com/2016/05/custom-cucumber-reporting-using-maven.html --> <plugin> <groupId>net.masterthought</groupId> <artifactId>maven-cucumber-reporting</artifactId> <version>3.11.0</version> <executions> <execution> <id>execution</id> <phase>verify</phase> <goals> <goal>generate</goal> </goals> <configuration> <projectName>CucumberReport</projectName> <outputDirectory>${project.build.directory}/site/cucumber-reports</outputDirectory> <!-- <cucumberOutput>${project.build.directory}/cucumber.json</cucumberOutput> --> <jsonFiles> <param>${project.build.directory}/cucumber.json</param> </jsonFiles> <!-- <parallelTesting>false</parallelTesting> --> <buildNumber>1</buildNumber> <checkBuildResult>false</checkBuildResult> </configuration> </execution> </executions> </plugin> </plugins> </pluginManagement> RunCukesTest.java @RunWith(Cucumber.class) @CucumberOptions( features = {"classpath:features"}, plugin = {"html:target/site/cucumber-pretty","json:target/cucumber.json"}, tags = {"@currentTest"}, glue={"helpers","stepDefinitions"}, monochrome = true ) public class RunCukesTest{ } Reports are generated like this which are different from expected A: all configuration was good, made two changes. removed pluginManagement tag in pom Used cucumberOutput output directory instead of jsonFiles. For some reason jsonFiles was generating duplicate reports. pom file, <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.${java.version}</source> <target>1.${java.version}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.20</version> <configuration> <includes> <exclude>**/*RunCukesTest.java</exclude> </includes> <testFailureIgnore>true</testFailureIgnore> </configuration> </plugin> <plugin> <groupId>net.masterthought</groupId> <artifactId>maven-cucumber-reporting</artifactId> <version>3.13.0</version> <executions> <execution> <id>execution</id> <phase>verify</phase> <goals> <goal>generate</goal> </goals> <configuration> <projectName>Simplify360 Automation Test Report</projectName> <outputDirectory>${project.build.directory}/site/cucumber-reports</outputDirectory> <cucumberOutput>${project.build.directory}/cucumber.json</cucumberOutput> <buildNumber>8.4.1.2</buildNumber> </configuration> </execution> </executions> </plugin> </plugins> </build>
[ "magento.stackexchange", "0000085851.txt" ]
Q: How to load custom module js file in magento 2? I have created banner slider module for magento 2. I have called JS file using following ways and its working fine. In block class I created following function public function getBaseJs($fileName){ return $this->_storeManager->getStore()->getBaseUrl( \Magento\Framework\UrlInterface::URL_TYPE_MEDIA ).'bannerslider/js/'.$fileName; } and this function is called in bannerslider.phtml file as following manner. <script type="text/javascript" src="<?php echo $this->getBaseJs('jquery-1.7.min.js') ?>"></script> <script type="text/javascript" src="<?php echo $this->getBaseJs('jquery.flexslider.js') ?>"></script> But, according to jQuery dependency mechanism of require.js How I can do it ? A: Finally, I got the solution for my query. I would like to share it in details as below. Step 1: Add your module js file under <Vendor>/<Module_Name>/view/<area>/web/js/ e.g. <Vendor>/<Module_Name>/view/<area>/web/js/flexslider.js Step 2: Create requirejs-config.js file under <Vendor>/<Module_Name>/view/<area>/ e.g. <Vendor>/<Module_Name>/view/<frontend>/requirejs-config.js Add following code to requirejs-config.js var config = { map: { '*': { bannerslider: 'VendorName_ModuleName/js/flexslider' } } }; Note: you may set your object name as per your choice. In my case I have set as bannerslider and do not add the .js extension to file name in VendorName_ModuleName/js/flexslider Step 3: Call the function of your module js in .phtml file as following manner. <script type="text/javascript"> require(['jquery','bannerslider'],function($){ $(window).load(function() { $('.flexslider-8').flexslider({ animation: "fade", controlNav: "thumbnails", slideshowSpeed: 2000, minItems: 2, maxItems: 4 }); }); }); </script> Its working fine for me. Trace : Use Net tab to see requested URL of js file loaded or not. A: My way is: Step 1 Include an extension's base javascript file using layout instructions. Step 2 Require the extension's other javascript files from the base file with RequireJS: require( [ 'jquery', '{VendorName}_{ModuleName}{path_to_js_file/relative_to/view/web/no_js_at_end}' // ex. Magento/Ui/view/base/web/js/grid/sticky/sticky.js // became Magento_Ui/js/grid/sticky/stick ], function($, someOtherLibrary) { // custom code here... ); });
[ "stackoverflow", "0059810995.txt" ]
Q: How to print "key" value of a list of key:value pairs? I have a list of key:value pairs. How do I print each one of them separately? NetworkCommands = [ (target + '/network/vlan' , {"vlan": 30, "tagged_ports": [1,2], "ip": "172.0.10.1/16"}), (target + '/network/vlan' , {"vlan": 51, "tagged_ports": [1,2], "ip": "10.0.0.1/16"}), (target + '/network/apply' , {}), (target + '/network/sr/routing/static' , {"vlan": 51, "dest_ip": "100.0.0.0/8", "gateway": "10.0.0.2"}), (target + '/network/apply' , {}), ] This prints both: for i in NetworkCommands: print(i) ('https://sonia:443/network/vlan', {'ip': '172.0.10.1/16', 'vlan': 30, 'tagged_ports': [1, 2]}) ('https://sonia:443/network/vlan', {'ip': '10.0.0.1/16', 'vlan': 51, 'tagged_ports': [1, 2]}) ('https://sonia:443/network/apply', {}) ('https://sonia:443/network/sr/routing/static', {'vlan': 51, 'gateway': '10.0.0.2', 'dest_ip': '100.0.0.0/8'}) ('https://sonia:443/network/apply', {}) A: You can use argument unpacking to assign each of the two elements in each tuple to their own variable. for first, second in NetworkCommands: print('The first element is', first) print('The second element is ', second) Alternatively, just index the tuple as required. for i in NetworkCommands: print('The first element is', i[0]) print('The second element is', i[1])
[ "stackoverflow", "0019722919.txt" ]
Q: Optimizing the rounding of all elements in a 2-dimensional array I have a 2 dimensional numpy array, and I would like each element to be rounded to the closest number in a sequence. The array has shape (28000, 24). The sequence, for instance, would be [0, 0.05, 0.2, 0.33, 0.5]. E.g. an original 0.27 would be rounded to 0.33, and 0.42 would be rounded to 0.5 This is what I use so far, but it is of course really slow with a double loop. MWE: arr = np.array([[0.14, 0.18], [0.20, 0.27]]) new = [] sequence = np.array([0, 0.05, 0.2, 0.33, 0.5]) for i in range(len(arr)): row = [] for j in range(len(arr[0])): temp = (arr[i][j] - sequence)**2 row.append(list(sequence[np.where(temp == min(temp))])[0]) new.append(row) Result: [[0.2000001, 0.2000001], [0.2000001, 0.33000001]] Motivation: In machine learning, I am making predictions. Since the outcomes are reflections of confidence by experts, it could be that 2/3 gave a 1 (thus 0.66). So, in this data, relatively many 0, 0.1, 0.2, 0.33, 0.66, 0.75 etc. would occur. My predictions are however something like 0.1724. I would remove a lot of prediction error by rounding in this case to 0.2. How to optimize rounding all elements? Update: I now pre-allocated memory, so there doesn't have to be constant appending. # new = [[0]*len(arr[0])] * len(arr), then unloading into new[i][j], # instead of appending Timings: Original problem: 36.62 seconds Pre-allocated array: 15.52 seconds shx2 SOLUTION 1 (extra dimension): 0.47 seconds shx2 SOLUTION 2 (better for big arrays): 4.39 seconds Jaime's np.digitize: 0.02 seconds A: Another truly vectorized solution with intermediate storage not larger than the array to be processed could be built around np.digitize. >>> def round_to_sequence(arr, seq): ... rnd_thresholds = np.add(seq[:-1], seq[1:]) / 2 ... arr = np.asarray(arr) ... idx = np.digitize(arr.ravel(), rnd_thresholds).reshape(arr.shape) ... return np.take(seq, idx) ... >>> round_to_sequence([[0.14, 0.18], [0.20, 0.27]], ... [0, 0.05, 0.2, 0.33, 0.5]) array([[ 0.2 , 0.2 ], [ 0.2 , 0.33]]) UPDATE So what's going on... The first line in the function figures out what the mid points between the items in the sequence are. This values are the thresholds for rounding: below it, you have to round down, above it, you have to round up. I use np.add, instead of the more clear seq[:-1] + seq[1:] so that it accepts a list or tuple without needing to explicitly convert it to a numpy array. >>> seq = [0, 0.05, 0.2, 0.33, 0.5] >>> rnd_threshold = np.add(seq[:-1], seq[1:]) / 2 >>> rnd_threshold array([ 0.025, 0.125, 0.265, 0.415]) Next we use np.digitize to find out in what bin, as delimited by those threshold values, each item in the array is. np.digitize only takes 1D arrays, so we have to do the .ravel plus .reshape thing to keep the original shape of the array. As is, it uses the standard convention that items on the limit are rounded up, you could reverse this behavior by using the right keyword argument. >>> arr = np.array([[0.14, 0.18], [0.20, 0.27]]) >>> idx = np.digitize(arr.ravel(), seq).reshape(arr.shape) >>> idx array([[2, 2], [3, 3]], dtype=int64) Now all we need to do is create an array the shape of idx, using its entries to index the sequence of values to round to. This could be achieved with seq[idx], but it is often (always?) faster (see here) to use np.take. >>> np.take(seq, idx) array([[ 0.2 , 0.2 ], [ 0.33, 0.33]])
[ "stackoverflow", "0019507087.txt" ]
Q: Reloading a route's model with server json data and need ember-related opinion I’m building a map with a search function. Basically, I’d like to store objects from the server within my ember app so that whenever I search for something that collection updates itself with the results from the server so the related view updates itself. It’s all on one page. So far I have an Application Controller, and a Results ArrayController. Data is shown from the Results Controller. Now I’d need that when a search is requested, it gets JSON from the server and updates the results collection. First question would be: How would you build that? I did a v1 with jQuery only and started a new one with Ember but I’m lost as of how structure-wise should I build it. I built a small jsbin based on what I have here: http://emberjs.jsbin.com/IYuSIXE/1/ Second question: How would I change a route's model content? Am I going in the wrong direction? Thanks a lot A: What I was looking for is a way to change the model on-the-fly. So basically if I have this: App.ResultsRoute = Ember.Route.extend({ model: function() { // empty array that will contain results return []; } }); I can do this to set the content of the model: this.get('model').setObjects([{}, {}, {}]); That way I can dynamically play with the models, load them with objects coming from almost anywhere.
[ "stackoverflow", "0018648123.txt" ]
Q: JSON string that contains double quotes for a value is being sent to the controller as NULL I make this AJAX call: function CreateProjectTree(sc) { debugger; $.ajax({ type: "POST", url: "../api/projects/SearchProjects", data: sc, contentType: "application/json; charset=utf-8", dataType: "json" }).done(function(data) { buildTree(data); }).fail(function(jqXHR, status, error) { console.log("Error: " + error); }); } If the variable sc does not have any double quotes for any of the values, (e.g. "Person": "Jack"), it works fine. However, if the object contains double quotes as such: "Person": ""Jack"", it'll send the object as NULL to the controller. I'm not sure why this is happening. Do I have to do anything special in this case? A: "Person": ""Jack"" doesn't work because the second quote on ""Jack"" is an end quote (two quotation marks make a string: ""). The JSON is bad because of this, and is therefore being treated as null. You can fix it by either one of two methods: 1) Change from using " to ' in your JSON: 'Person': '"Jack"' 2) Use an escape to use a quote inside a quote: "Person": "\"Jack\""
[ "stackoverflow", "0052107018.txt" ]
Q: How to change Modal state from outside the React class? I am trying to call my modal by changing the state from outside the react class. But so far no luck. I tried the following: I have a method named Portfolio which needs to activate the modal once user click on the Image const Portfolio = (props) => <div className="col-sm-4"> <div className="mb-2"> <img onClick={this.toggle} className="card-img-top" src={"/assets/imgs/project/"+props.portfolio.img_thumb} alt="" /> </div> </div> Here is the Class that contain the state and the modal. But I cannot change state to activate the modal. class Project extends React.Component { constructor(props, context) { super(props, context); this.state = { modal: false, } this.toggle = this.toggle.bind(this); } toggle() { this.setState({ modal: !this.state.modal }); } render(){ return ( <div className="row portfolioWrap"> // here resides our modal which activate once modal state changed <div> <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}> <ModalHeader toggle={this.toggle}>Modal title</ModalHeader> <ModalBody> {this.state.gallery.map(gallery => <img className="card-img-top" src={"/assets/imgs/project/"+gallery} alt="" />) } </ModalBody> <ModalFooter></ModalFooter> </Modal> </div> // calling portfolio method inside the loop {currentTodos.map(item => <Portfolio key={item.title} portfolio={item} />)} </div> ) } } I am trying to activate the modal from Portfolio function. But since its outside the class scope i cannot access the state. Is there any way to accomplish this? A: You can pass the toggle method to your Portfolio component then use it from the props. <Portfolio key={item.title} toggle={this.toggle} portfolio={item} /> Then in Portfolio: const Portfolio = (props) => <div className="col-sm-4"> <div className="mb-2"> <img onClick={props.toggle} className="card-img-top" src={"/assets/imgs/project/"+props.portfolio.img_thumb} alt="" /> </div> </div>
[ "cooking.stackexchange", "0000037469.txt" ]
Q: Small turkey for practice Thanksgiving is getting closer and I want to cook a turkey. However, I want to cook a test turkey first. Problem is, the turkeys in the grocery stores will be massive, and I just want to practice on a small turkey. I was wondering if I can just use a chicken for practice? What do you do when you want to practice something before serving it to guests? A: I like to practice too if it's something I've never made before. Roasting a chicken will give you an opportunity to practice the all-important skill of correctly placing the thermometer, but chicken has a different flavor than turkey. One option is to get the smallest turkey you can find, experiment with a brine (which I highly recommend for roasted turkey) and perhaps go into Thanksgiving with a bit more confidence. You can always cut up the turkey meat and freeze it for sometime after Thanksgiving when you're no longer sick of turkey. Leftover turkey makes great tamales or enchiladas.
[ "stackoverflow", "0052337851.txt" ]
Q: How to define BuildConfig object with Jenkins and openshift I am using Jenkins and OpenShift to create the build and trigger the deployment. The following is my YAML file : apiVersion: v1 kind: List metadata: {} items: - apiVersion: v1 kind: BuildConfig metadata: name: petclinic-pipeline spec: source: git: uri: <<git url>> type: Git strategy: type: JenkinsPipeline jenkinsPipelineStrategy: jenkinsfilePath: Jenkinsfile triggers: - generic: secret: FiArdDBH type: Generic The Jenkins config is as follows: node { stage('Source Checkout') { git url: "git url" } stage('Build') { git url: "git url" sh "/var/lib/jenkins/apache-maven-3.5.4/bin/mvn clean package -Dorg.jenkinsci.plugins.durabletask.BourneShellScript.HEARTBEAT_CHECK_INTERVAL=300 -DskipTests=true" stash name:"jar", includes:"target/a.jar" } stage('Build Image') { unstash name:"jar" sh "oc start-build petclinic-pipeline --from-file=target/a.jar --follow" } } Now, if I apply this, I'm getting the following error : $ oc start-build petclinic-pipeline --from-file=target/a.jar --follow Uploading file "target/a.jar" as binary input for the build ... The Build "petclinic-pipeline-20" is invalid: spec.source.git: Invalid value: "": must be set when using Jenkins Pipeline strategy with Jenkinsfile from a git repo My expectation is that the image should be built and I am not able to understand where the issue is. Is it something like, spec source git should not be used in YAML file when using Jenkins strategy? A: Personally, I think you had better use the OpenShift Pipeline Jebkins Plugin instead of executing commands for oc start-build. For example, simple build and deploy description using OpenShift Pipeline Jenkins Plugin. For more details, refer here apiVersion: v1 kind: BuildConfig metadata: labels: name: your-pipeline name: your-pipeline spec: runPolicy: Serial strategy: jenkinsPipelineStrategy: jenkinsfile: |- node(''){ stage 'Build using your-yourconfig' openshiftBuild(namespace: 'your-project', bldCfg: 'your-buildconfig', showBuildLogs: 'true') stage 'Deployment using your-deploymentconfig' openshiftDeploy(namespace: 'your-project', depCfg: 'your-deploymentconfig') } type: JenkinsPipeline triggers: - github: secret: gitsecret type: GitHub - generic: secret: genericsecret type: Generic I hope it help you.
[ "stackoverflow", "0004540190.txt" ]
Q: jQuery element width update problem I want to get element width using jQuery. The problem is when I change html inside this element. I want to get its width and width() returns its parent width instead, it looks like html() doesn't update element width at all. But... It works perfectly when no DOCTYPE is specified. I'm using IE in WebBrowser control. css: p { margin: 0; padding: 0; } .name { font-weight: bold; } .description { color: #444; width: 190px; white-space: nowrap; overflow: hidden; } #container { } html looks like this: <div id="container"> <div id="friend0"><p class="name">Name</p><div class="description"><p>Description</p></div> </div> js: var x1 = GetFriend(id).children('.description').width(); var x2 = GetFriend(id).children('.description').children('p').width(); (some jQuery animation code) and after that: GetFriend(id).children('.description').children('p').html('some now text here...'); var x3 = GetFriend(id).children('.description').children('p').width(); and x3 is the same as .description with value of 190 but when I don't declare DOCTYPE at the beginning of html it returns correctly updated value. I need to have DOCTYPE declared because some animation code causes flickering of scrollbars. Anyone know how to do it correctly? A: You already are doing it correctly. Block elements like <p> will use the width of their parent; that's the way the standard box model works. It changes when you drop the DOCTYPE because you're toggling the browser in and out of quirks mode. (Comment posted as answer ...)
[ "stackoverflow", "0028743428.txt" ]
Q: Unable to getting the results from concurrent CompletionService I am very new to the Java concurrent package. I am using the java.util.concurrent.CompletionService class for getting the results from the pool without any waiting for the other threads to complete the task. But I was unable to get the tasks even after 10 min of code execution. I am just printing the thread name in the task. Here is my code. public class CompletionService { public void execute(ThreadPoolExecutor argThreadPoolExecutor) throws InterruptedException, ExecutionException { java.util.concurrent.CompletionService<String> completionService = new ExecutorCompletionService<String>(argThreadPoolExecutor); int counter = 0; for (int i = 0; i < 4; i++) { Task task = new Task(); completionService.submit(task); ++counter; } print(counter, completionService); } private void print(int argCounter, java.util.concurrent.CompletionService<String> argCompletionService) throws InterruptedException, ExecutionException { String s = argCompletionService.take().get(); if (s != null && !s.isEmpty()) { System.out.println(s); } } public static void main(String[] args) throws InterruptedException, ExecutionException { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(8, 8, 3000, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); CompletionService completionService = new CompletionService(); completionService.execute(threadPoolExecutor); threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); } } Task class: public class Task implements Callable<String> { @Override public String call() throws Exception { String name = Thread.currentThread().getName(); return name; } } Result: pool-1-thread-1 I am getting only one thread information. I waited 10-15 min still I am not getting the results. Am I wrong anywhere.? Can any one help me on this.? Thanq. A: completionService.execute(threadPoolExecutor); threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); You will block here forever because you have not asked the ThreadPoolExecutor to shutdown.
[ "security.stackexchange", "0000171106.txt" ]
Q: Security questions - SSL secured payment iframe on an SSL secured site Sorry if this has been answered before, I couldn't really find this exact example and I wanted to get a clearer answer for a client. I understand that an iframe with a https payment portal on a http (non secure) embedding site isn't safe. If the site with the embed is https, and the payment portal embedded with an iframe is https, is that secure or would it be better to just forgo the iframe and link directly to the portal off site? And if so, why? Thanks in advance :) A: Embedding and SSL frame in and HTTP page is only unsafe if the host page is MITM’d and replaced with a phishing host and phishing frame. This is the only danger. The same origin policy protects everything else so long as they are on different origins (I assume they are because why else would you not have SSL on this page?). Against a passive attacker, this is safe. If they are actively modifying your traffic and change the frame SRC URL all bets are off. The content of the original page is of course safe still but it’s very hard to know what the actual location of an iframe is as a user.
[ "electronics.stackexchange", "0000430442.txt" ]
Q: How to interpret MAX7219 timing diagram? I'm trying to connect this module to atmega32u4 (16 MHz): Everything seems mostly working, but I have a question: how much time is needed for the latch to take effect? I.e., is a delay needed between SLAVE_DESELECT and SLAVE_SELECT in the following example? #define SLAVE_SELECT PORTB &= ~(1 << PB0) #define SLAVE_DESELECT PORTB |= 1 << PB0 ... DDRB |= 1 << PB0; PORTB |= 1 << PB0; // begin high (unselected) .... SLAVE_SELECT; for (int i = 0; i < NUM_DEVICES; i++) writeWord(0x0A, 0x0F); // brightness SLAVE_DESELECT; SLAVE_SELECT; for (int i = 0; i < NUM_DEVICES; i++) writeWord(0x0C, 0x01); SLAVE_DESELECT; (SCK frequency is 4MHz in my configuration.) Also, I do not understand how to interpret the timing diagram from datasheet: A: No, no delay is needed. I have used MAX7219 with Arduinos at 8 MHz SPI clock, back to back writes were not an issue. The timing diagram just shows chip select (Load) going low, 16 bits going out with the clock, and chip select going high. I use SPI.transfer, with port manipulation like you did, but as an example here with digitalWrite: digitalWrite (ssPin, LOW); SPI.transfer(address); // from 1 to 15, or 0 if using NOP SPI.transfer(dataToSend); // varies by register. 1 to 8 are data display, 9+ are command registers digitalWrite (ssPin, HIGH); Replace the digitalWrite with your SLAVE_SELECT; & SLAVE_DESELECT; commands. For a single MAX7219, I would have 5 of these in setup() to configure the intensity, Normal mode, # of digits (scan limit), not Mode B, and display test. Others might do that as 5 function calls. Or 1 function call to do all 5. SLAVE_SELECT; SPI.transfer(address); SPI.transfer(dataToSend); SLAVE_SELECT; // no delay needed here,even with 8 MHz SPI clock SLAVE_SELECT; SPI.transfer(address); SPI.transfer(dataToSend); SLAVE_SELECT; And if you are bit-banging this, the transfer will be even slower: writeWord(0x0A, 0x0F); // brightness
[ "chinese.stackexchange", "0000035738.txt" ]
Q: What does 老得 mean? 我老得麻烦同事。 What does 老得 means in here? Does it mean I'm too old and have to bother colleagues constantly. I find an example, 我老得不能养猫了。 I'm too old to have a cat. A: You should take 老得 separately in this case. 老: always; constantly 得(dei3): need; have to 我老得麻烦同事 means I have to bother colleagues constantly. In 我老得不能养猫了(I'm too old to have a cat), 得 is pronounced as de and 老 means old. It relies on context to determine whether 得 is pronounced de or dei3, which reflects different meanings.
[ "stackoverflow", "0035006499.txt" ]
Q: Time differences in Apache Pig? In a Big Data context I have a time series S1=(t1, t2, t3 ...) sorted in an ascending order. I would like to produce a series of time differences: S2=(t2-t1, t3-t2 ...) Is there a way to do this in Apache Pig? Short of a very inefficient self-join, I do not see one. If not, what would be an good way to do this suitable for large amounts of data? A: S1 = Generate Id,Timestamp i.e. from t1...tn S2 = Generate Id,Timestamp i.e. from t2...tn S3 = Join S1 by Id,S2 by Id S4 = Extract S1.Timestamp,S2.Timestamp,(S2.TimeStamp - S1.TimeStamp) Edit Sample Data 2014-02-19T01:03:37 2014-02-26T01:03:39 2014-02-28T01:03:45 2014-04-01T01:04:22 2014-05-11T01:06:02 2014-06-30T01:08:56 Script s1 = LOAD 'test2.txt' USING PigStorage() AS (t:chararray); s11 = foreach s1 generate ToDate(t) as t1; s1_new = rank s11; s2 = LOAD 'test2.txt' USING PigStorage() AS (t:chararray); s22 = foreach s2 generate ToDate(t) as t1; s2_new = rank s22; -- Filter records by excluding the 1 ranked row and rank the new data ss = FILTER s2_new by (rank_s22 > 1); ss_new = rank ss; s3 = join s1_new by rank_s11,ss_new by rank_ss; s4 = foreach s3 generate DaysBetween(ss_new::t1,s1_new::t1) as time_diff; DUMP s4;
[ "stackoverflow", "0057897844.txt" ]
Q: Professor indicates I missed 2 tag styles, but cannot figure out what I had a homework assignment a couple weeks ago, and on my assignment I was to recreate a very simple website. It was done quickly and it looked like an exact replica. However, she said I only did 2 tag styles out of the 4 that were required. She indicated I missed the h2 and h3 tags styles. What does this mean? Or am I just stupid. I would ask her, but I have another assignment due tonight (which I have already done), and its too late to shoot her an email. The website was supposed to look like this: [][1] <!DOCTYPE html> <!-- CTI 110 - Evan Wright --> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Dog Breeds </title> <style> body { background-color: lightblue; } ol li { color: blue; } .dog-breed { color: green; } .dog-breed-info { background-color: lightyellow; } .dog-breed-variations { color: blue; } /* Colors */ #yellow { color: yellow; } #chocolate { color: chocolate; } #white { color: white; } #brindle { color: rgb(189, 118, 92); /* kind of brownish tan I guess */ } #fawn { color: tan; } #red { color: red; } #blue { color: grey; } </style> </head> <body> <h1> Dogs </h1> <p> Information on dog breeds. </p> <h2 class="dog-breed"> Labradors </h2> <p class="dog-breed-info"> Labradors are one of the most popular breeds of dog.</p> <h3 class="dog-breed-variations"> Colors </h3> <ul> <li> Black </li> <li id="yellow"> Yellow </li> <li id="chocolate"> Chocolate </li> </ul> <h2 class="dog-breed"> Chihuahuas </h2> <p class="dog-breed-info"> Chihuahuas are the smallest breed of dogs and come in any variety of colors.</p> <h3 class="dog-breed-variations"> Varieties </h3> <ol> <li> Long-Haired </li> <li> Short-Haired </li> </ol> <h2 class="dog-breed"> Greyhounds </h2> <p class="dog-breed-info"> Greyhounds are any breed of tall, slender, smooth-coated dogs.</p> <h3 class="dog-breed-variations"> Colors </h3> <ul> <li id="white"> White </li> <li id="brindle"> Brindle </li> <li id="fawn"> Fawn </li> <li> Black </li> <li id="red"> Red </li> <li id="blue"> Blue(Grey) </li> </ul> </body> </html> ``` [1]: https://i.stack.imgur.com/2VgCO.png A: That's super hard to know, but it sounds like it might have been something simple like literally not styling the h2/h3 tags? I know you styled them using class="..." on the h2/h3 tags, but perhaps she wanted you to apply styles to the HTML tags themselves? You already achieved this here: <style> body { background-color: lightblue; } </style> You can do this using something like that for the h2 / h3 tags as well: <style> h2 { font-weight: bold; } h3 { font-weight: bolder; } </style> The easiest thing to do would be to ask the teacher for clarification though! :)
[ "stackoverflow", "0012645738.txt" ]
Q: Calling C function from Objective-C loses passed in values I'm trying to keep a float[] of my table row heights. I found a nice class for doing so here: http://forums.macnn.com/t/224809/nsmutablearray-vs-a-plain-c-array-for-storing-floats. The problem is that once the C function (located in another file) gets called, the float that I passed in becomes 0. This happens every single time, regardless of the float value. C function: typedef struct { float *array; int count; } floatArray; BOOL AddFloatToArray ( floatArray *farray, float newFloat ) { if ( farray->count > 0 ) { // The array is already allocated, just enlarge it by one farray->array = realloc ( farray->array, ((farray->count + 1) * sizeof (float)) ); // If there was an error, return NO if (farray->array == NULL) return NO; } else { // Allocate new array with the capacity for one float farray->array = (float *)malloc ( sizeof (float) ); // If there was an error, return NO if (farray->array == NULL) return NO; } printf("Adding float to array %f\n", newFloat); farray->array[farray->count] = newFloat; farray->count += 1; printArrayContents(farray); return YES; } int printArrayContents( floatArray* farray) { printf("Printing array contents\n"); for(int j=0; j < farray->count; j++) printf("%f\n", farray->array[j]); return 0; } Called from: NSDictionary* review = [self.reviews objectAtIndex:indexPath.row]; returnHeight = [ReviewCell cellHeightForReview:review]; NSLog(@"Adding height to array: %0.0f", returnHeight); AddFloatToArray(heights, returnHeight); Here's what gets logged: 2012-09-28 11:46:12.787 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 101 Adding float to array 0.000000 Printing array contents 0.000000 2012-09-28 11:46:12.788 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 138 Adding float to array 0.000000 Printing array contents 0.000000 0.000000 2012-09-28 11:46:12.788 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 122 Adding float to array 0.000000 Printing array contents 0.000000 0.000000 0.000000 2012-09-28 11:46:12.789 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 139 Adding float to array 0.000000 Printing array contents 0.000000 0.000000 0.000000 How can I ensure that the correct value is actually inserted into the float[]? A: I didn't declare the functions in the .h I was #importing. So everything compiled and ran, but the classes weren't communicating correctly. You'd think that would raise a warning or error.
[ "stackoverflow", "0036602022.txt" ]
Q: Memory overflow List<int> pal=new List<int>(); List<int> nums = new List<int>(); var thdigit1 = 1; var thdigit2 = 999; while (thdigit2>=1) { var holder=thdigit1* thdigit2; nums.Add(holder); thdigit2 -= 1; if (thdigit2==0) { thdigit2 = 999; thdigit1 += 1; } } I am getting a memory overload problem for too much in the list. Is there a certain limit that my computor can handle? Thanks A: The problem is when thdigit2 is 1, it is still continuing the while loop, while (thdigit2>=1) reduced by 1 and then becomes 0 thdigit2 -= 1; and... reseted back to 999. if (thdigit2==0) { thdigit2 = 999; thdigit1 += 1; } Thus you get memory overflow as you never gets out of the while loop. To fix it, you probably need to add another termination condition in your while loop: while(thdigit2 >= 1 && thdigit1 <= 10) //example
[ "stackoverflow", "0025028860.txt" ]
Q: Can I use type of a variable to declare another variable in Java? Can I do something like this in Java? HashMap<String, Child> childMap=new HashMap<String, Child>(); HashMap<String, childMap.typeName> parentMap=new HashMap<String, childMap.typeName>(); //instead of HashMap<String, HashMap<String, Child>> parentMap=new HashMap<String, HashMap<String, Child>>(); or something like this HashMap<String, HashMap<String, Child>> parent1=new HashMap<String, HashMap<String, Child>>(); parent1.typeName parent2=new parent1.typeName; Because some time, if the map level is too deep or too complex, it is very hard to write and read. A: Abbreviations are possible by defining a subclass: class Str2Child extends HashMap<String, Child>>{} class Str2Map extends HashMap<String,Str2Child>{} Str2Map parent1 = new Str2Map(); A: No but you could shorten it if you're using Java 7 or higher. The compiler can infer the type parameters from the left side of the assignment and you can skip them altogether while creating the object HashMap<String, HashMap<String, Child>> parentMap = new HashMap<>(); In older versions of Java, you could resord to Guava's Maps class and its newHashMap method. HashMap<String, HashMap<String, Child>> parentMap = Maps.newHashMap(); Another thing you could possibly do is create a type that implements a certain specification of the generic HashMap. public class HashMapStringChild extends HashMap<String, Child> { } and then use it as a type parameter HashMap<String, HashMapStringChild> parent2 = new HashMap<>(); but personally, I find this a bit of a stretch. I certainly wouldn't overuse it and I'd be careful extending the collection classes. Addendum You should also note that you're effectively binding your API to a specific implementation of the Map interface (HashMap), or even worse, in case of introducing the new class (HashMapStringChild), to a specific, non-standard implementation. What if at some point, you decide to keep your Child objects sorted at all times? You could do this by switching to a TreeMap but that would mean a big deal of refactoring. You would be better off basing your API on a more general interface. This way you could switch from Map<String, Map<String, Child>> map = new HashMap<String, HashMap<String, Child>>(); to Map<String, Map<String, Child>> map = new HashMap<String, TreeMap<String, Child>>(); or Map<String, Map<String, Child>> map = new TreeMap<String, TreeMap<String, Child>>(); or any other implementation without a hassle. If you really want to make the map of String to Child a specific type, you could introduce an interface public interface MapStringToChild extends Map<String, Child> { } Then you could keep your reference types general and use HashMap<String, Child>, TreeMap<String, Child>, HashMapStringChild or literally any other implementation mapping a String to a Child interchangeably, while keeping the code short.
[ "electronics.stackexchange", "0000416170.txt" ]
Q: custom solenoid trigger circuit I have a custom made solenoid that is required to work at 60V to actuate with enough force. I have tried two circuits shown in the figure below but both don't work. In the first circuit, the voltage across the coils is just 3V whereas in the second one, the voltage across the coil is zero although the opto isolator does work. I can't figure out what is going wrong. I used IRFZ44N for mosfets at 30V source-drain voltage for testing. A: For the first circuit remove the top mosfet and connect the diode and solenoid to the 60V supply. Make sure the MOSFET you use is fully saturated by the output voltage of the arduino, otherwise you'll find they die. You may also want to add more snubbing circuitry. In the second circuit you've read the schematic wrongly, the component isn't a opto isolator, but an opto-isolated solid state relay.
[ "stackoverflow", "0013723750.txt" ]
Q: Web Service fails to start: Could not load file or assembly I have a problem with a web service that will not run anymore. It previously had the 64-bit version installed, but now the 32-bit is installed. However, it seems that it is looking for a 64-bit version of the ChilkatDotNet2.dll, which is strange. The version that was installed by the MSI-package is X86. C:\Program Files (x86)\Sipp\Market Server\bin>asminfo.exe ChilkatDotNet2.dll ChilkatDotNet2, Version=9.3.0.0, Culture=neutral, PublicKeyToken=eb5fc1fc52ef09b d | X86 I enabled FusionLog and it gave the following output: Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.BadImageFormatException: Could not load file or assembly 'ChilkatDotNet2' or one of its dependencies. An attempt was made to load a program with an incorrect format. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Assembly Load Trace: The following information can be helpful to determine why the assembly 'ChilkatDotNet2' could not be loaded. === Pre-bind state information === LOG: User = SF\sonsupport LOG: DisplayName = ChilkatDotNet2 (Partial) LOG: Appbase = file:///C:/Program Files (x86)/Sipp/Market Server/ LOG: Initial PrivatePath = C:\Program Files (x86)\Sipp\Market Server\bin Calling assembly : (Unknown). === LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Program Files (x86)\Sipp\Market Server\web.config LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Aspnet.config LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/Temporary ASP.NET Files/server/b8e4736f/d41d574d/ChilkatDotNet2.DLL. LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/Temporary ASP.NET Files/server/b8e4736f/d41d574d/ChilkatDotNet2/ChilkatDotNet2.DLL. LOG: Attempting download of new URL file:///C:/Program Files (x86)/Sipp/Market Server/bin/ChilkatDotNet2.DLL. ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated. Stack Trace: [BadImageFormatException: Could not load file or assembly 'ChilkatDotNet2' or one of its dependencies. An attempt was made to load a program with an incorrect format.] System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0 System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +416 System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +166 System.Reflection.Assembly.Load(String assemblyString) +35 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +190 [ConfigurationErrorsException: Could not load file or assembly 'ChilkatDotNet2' or one of its dependencies. An attempt was made to load a program with an incorrect format.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +11241896 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +388 System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +232 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +48 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +210 System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir) +191 System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory vdir, Boolean ignoreErrors) +54 System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +295 System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +476 System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +116 System.Web.Compilation.BuildManager.GetCompiledCustomString(String virtualPath) +39 System.ServiceModel.HostingManager.GetCompiledCustomString(String normalizedVirtualPath) +202 System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +33 System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +46 System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +654 [ServiceActivationException: The service '/server/service.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'ChilkatDotNet2' or one of its dependencies. An attempt was made to load a program with an incorrect format..] System.ServiceModel.AsyncResult.End(IAsyncResult result) +15778592 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +15698937 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +265 System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +227 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171 A: IIS > Application pools > your application pool > Advanced settings > set Enable 32bit application to true.
[ "stackoverflow", "0005332346.txt" ]
Q: Javascript trouble I am trying to make a calculator with Javascript, and I'm having a few problems... The code is at http://jsfiddle.net/NwkQW/10/. Try adding some values, and you'll see that the box that says TOTAL will change according to the values you enter. However, you'll also see that if you click CLEAR FORM, the value will not go back to TOTAL. How do I do that? I want to link to the javascript (e.g. <script type="text/javascript" src="mydomain.com/calculate.js></script>), but if I try, it doesn't work right! HELP!!! Thanks! A: add a onClick to your clear form button like: onClick="document.getElementById('totalDiv').innerHTML='';" reset won't clear anything that's not a form element see http://jsfiddle.net/NwkQW/16/
[ "stackoverflow", "0056165578.txt" ]
Q: Optimize Conditional while loop I have a huge dataframe in python +7mil rows. My general problem is that I need to run over a column and make a new 'numer' every time I see a '#' in that column. So the first time I see a # I overwrite it with 1 and drop this row, then I continue in the next row with the same number until I see again a '#' and i procede that. I already have some code in place, but at it is a loop it is super slow! i=0 j=0 while i <len(data): if data.iloc[i][0] == '#': j=j+1 data = data.drop(data.index[i]) else: data.iloc[i][0] = j i=i+1 return data A: Try with something like this: m = (data.iloc[:, 0] == '#') data.iloc[:, 0] = m.cumsum() data.drop(m.index[m], inplace=True)
[ "stackoverflow", "0007238967.txt" ]
Q: how to get the key name from app settings with associated with value in app settings can anyone tell me how to get the key name associated with a value in <app settings> A: Not entirely clear what you want to achieve here, but you could always just iterate over all appSettings and compare their values. If you find the one you're looking for take it's key. foreach (string key in Configuration.AppSettings.Settings.AllKeys) { string value = appSettings.Settings[key].Value; if (value.Equals(myValue)) { Console.WriteLine("Found Key: " + key); break; } } NOTE: The reverse mapping from value to key is of course not necessarily unique, i.e. you would have to deal with the fact, that the value you're using a search predicate matches more than one key.
[ "judaism.stackexchange", "0000109404.txt" ]
Q: Is part of the Mediterranean sea considered Eretz Israel? I heard that the Gemmorah discusses some islands in the Mediterranean sea as belonging to the Biblical Eretz Israel. Is the sea considered a part of Eretz Israel and what are practical ramifications of that: what are those islands - is it Cyprus? if the sea is dried - who does the land belong to? seaweeds or fruits - do they need Terumah or Maaser, etc? A: Source Gittin 8a which is regarding what part of the mediteranien sea is obligated in Maaser (see 7b-8a) (Bold is translation everything else is Research) הנסין שבים רואין אותן כאילו חוט מתוח עליהם מטורי אמנון עד נחל מצרים מן החוט ולפנים א"י מן החוט ולחוץ חו"ל רבי יהודה אומר כל שכנגד ארץ ישראל הרי הוא כא"י The Islands in the Mediteranean sea within the imaginary line between the Turei Amnon (or Hor Hahar mountain as Rashi Translates) { - According to Rav Estori Haparchi (14th Century Traveller written in Kaftor vapherach) brought down in LÀ GÉOGRAPHIE DU TALMUD (press ctrl-f search "endroit du nom de kaplaria if you understand french) by Adolphe neubauer, this is Jebel Akrra which has many ancient sites identified with Hitites part of the ancient Canaanites by archeoligists of Mount Kilic see reviews below Antioch (antakya in modern day turkey) where the border of Israel is supposed to pass below, as the Targum Yerushalmi Translates Numbers 34,8: מֵהֹ֣ר הָהָ֔ר תְּתָא֖וּ לְבֹ֣א חֲמָ֑ת as מִטַוְורוֹס מָנוֹס תְּכַוְונוּן לְכוֹן לְמַעֲלֵי אַנְטוּכְיָיא וִיהוֹן מַפְקָנוֹי תְּחוּמָא. This mountain slopes right into the sea. - According to Historian Dean Philip Bechard in Paul Outside the Walls: A Study of Luke's Socio-geographical Universalism in Acts 14:8-20 Turei Amnon (gemora)= Turus amunus (the Targum Yerushalmi could also be refering to this as טַוְורוֹס מָנוֹס), a range of Mountains that reach from the Northern medetaranean till the Euphrates river just north east of Antakya even further north then Mount Kilic. - Alternatively according to Rashi Makkos 9b who says the land is divided into 4 equal parts from north to south the 3rd of which is Shechem (Nablus) to Chevron which is 49 miles, Hor Hahar (98 miles north of Shechem) could be identified with Jabal Baiquon which slopes down to the town of Remaile on the cost just north of Sidon} till the valley of Mitzrayim { - Most seem to think this is Wadi el Arish like Rabbi Saadia Gaon (in fact he lived in Arish). - Rashi seems to think its the Nile in Joshua 13,3 (Rambam in Cairo could have been living in Israel on the Eastern front of the Nile)} are part of Israel to obligate Maaser. Rabbi Yehuda says parralel lines from top and bottommost border of Israel till the Ocean i.e the islands (i.e not mainland see Tosfos דלא איירי ביבשה שעד אוקיינוס אלא בנסין שבים הגדול דווקא) require Maaser. Bearing in mind Tosfos quoted says only Islands are included not sea bed or mainland (It dseems if the islands expanded more would be part of Israel but if mainland e.g Africa expanded this would not be part od Israel, These Islands seem to be Chayav Maaser according to both opinions of Rashi and Rav Ishtori Haparchi are part of Israel: Zireh Island (Moder day Lebanon next to Sidon), Adam rock off Bat yam beach, Rosh Hanikra Islands and Achziv Islands near the border of Israel with Lebanon. If the line goes from Mount killic (Rav Istori Haparchi opinion) then also the inhabited island Arwad, uninhabited Al Abbas, Jasirat basira, islands of Abu al faris (all part of modern day Syria), the Palm Islands nature reserve (includin 9 islands next to Trippoli, Lebanon) are within the line according to Chachamim and also Rabbi Yehuda If Hor Hahar is as far north as mount kilic in Turkey or the Taurus Amunus range, Major Islands of Cyprus, Crete (Greece) and Sicily (Italy), Malta among many others are parrallel to Eretz Yisrael and are part of it to require Maaser according to Rabbi Yehuda. But even if Hor hahar is lower down like near Sidon the island of Djerba (Tunisia) is certainly aligned with Israel according to Rabbi Yehuda (but not Rabbannan) see map
[ "tex.stackexchange", "0000343458.txt" ]
Q: todonotes package - how to underline a single word instead of the complete line? The todonotes package typically underlines the whole line. I would like to have more control over this. Is there an easy way? For instance, how do I write a todo that underlines just the word 'first' in the second paragraph? \documentclass[11pt,a4paper]{scrartcl} \usepackage{todonotes} \begin{document} \todo{note 1. full line} First paragraph. This is the first sentence of the first paragraph. Second paragraph. This is the \todo{note 2. single word} first sentence of the second paragraph. \end{document} At the moment, the second note underlines from 'first' to the end of the line. Using \todo[noline]{note 2. single word} results in: and the word in not underlined at all. A: Edit: Added a macro to do highlighting and the note together, with both disabled when the disable option is given to todonotes. This solution comes from section 1.8.13 of the todonotes documentation, but is slightly improved (doesn't eat the following space). \documentclass[11pt,a4paper]{scrartcl} \usepackage{todonotes} \usepackage{soul} \makeatletter \if@todonotes@disabled \newcommand{\hlnote}[2]{#1} \else \newcommand{\hlnote}[2]{\todo{#2}\texthl{#1}} \fi \makeatother \begin{document} \todo{note 1. full line} First paragraph. This is the first sentence of the first paragraph. Second paragraph. This is the \hlnote{first}{note 2. single word} sentence of the second paragraph. \end{document}
[ "stackoverflow", "0011016481.txt" ]
Q: WPF find control under mouse without modifying the application I'm creating a log system ('outside' the application) that logs all the click on the application. I have setup a PreFilterMessage function wich detects a click from the mouse, but I can't find the control/element that was clicked. I've tried with Mouse.DirectlyOverbut the element is always null. I've tried also with VisualTreeHelper.HitTest but I don't have a Visualto make the search from. I don't have access to the inside of the application: only to the Main method (with the Application.Run(new MainForm()); and my Application.AddMessageFilter(new Logger());). Does anyone have an idea (or a walk around) on how to get the clicked control in the application (in .Net 3.5)? A: I've been using an amazing little application called Snoop for some time now that I think does exactly what you're after, it's open source (C#) and may be of use to you if you can find out how it works. (All WPF developers should get this and no I don't work on Snoop lol) http://snoopwpf.codeplex.com/
[ "stackoverflow", "0033945402.txt" ]
Q: Format a string with uppercase I have to format a string. So I would like that my string is automatic format well. For example: I have this string : "hello, my name is Michael. can you help me?i have a problem" I would like that using JavaScript, the string becomes : "Hello, my name is Michael. Can you help me? I have a problem" So the function for do that have to check the first letter (in this case "h") is capitalize, if there is a space after dots (and add space and capitalize first letter after dot) and in case there is a space check if the first letter is capitalize. Anyone know how to do that? A: You can use replace() with regex to do that function formatSentence(sentence) { return sentence .replace(/^\w/g, function(m) { return m.toUpperCase(); }).replace(/(\.|\?)\s?(\w)/g, function(_, m1, m2) { return m1 + ' ' + m2.toUpperCase(); }) } document.write(formatSentence("hello, my name is Michael. can you help me?i have a problem"));
[ "stackoverflow", "0023025891.txt" ]
Q: Flask - Pass Variables From Redirect to render_template I have a question regarding redirecting to a function that renders a template. I have two functions: @user.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'GET': return render_template('register.html') email = request.form['email'] if User.query.filter(User.email == email).first() is not None: flash('Account already exists for this email address!') return redirect(url_for('user.login')) and @user.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') return "Hello" In the first function, with the line return redirect(url_for('user.login')), I want to pass the email variable with that redirect, so I can have render_template in the second function display that variable on an HTML page. I tried the following: return redirect(url_for('user.login', defaultEmail=email)) in the first function and return render_template('login.html', defaultEmail=email)) but it gives me NameError: global name 'email' is not defined. How would I go about doing this? A: The url_for should pass email through the query string. It can by accessed by login as part of request.args. email = request.args.get('defaultEmail')
[ "wordpress.stackexchange", "0000371658.txt" ]
Q: advanced custom fields and contact form 7 I want to use contact form 7 shortcode in advanced custom fields I created field called shortcode with advanced custom fields and put the contact form 7 shortcode in it. it displayed the form as frontend but no functionality. I am using the free version of advanced custom fields. also I choose the type of the field as wysewig then here is the code <?php echo get_field('shortcode'); ?> I used the shortcode of contact form 7 on another page and the form worked well without using advanced custom fields. so what is the wrong, please? ********* after updating ********* <form class="getin_form wow fadeInUp" data-wow-delay="400ms" onsubmit="return false;"> <?php echo do_shortcode(get_field('shortcode')); ?> </form> unfortunately can not send the link because it is on localhost. I am using xampp but this is the picture of the advanced custom fields shortcode field A: You almost got it. You are missing the do_shortcode function. <?php echo do_shortcode(get_field('shorcode')); ?>
[ "stackoverflow", "0049924190.txt" ]
Q: Tableau Calc field syntax - inches to feet Can anybody help me with the tableau syntax to create a calculated field? I have a list of height data in inches, I would like to convert that to feet and inches. So for example, 72 inches translates to 6 feet. 73 to 6.08 feet(or rounded to 6.1). Any help is much appreciated! A: Assuming your current field is called height, then the calculation would be: [height] / 12 To set default format (round to 1 decimal place), right click on the field and select Default Properties -> Number Format -> Number (Custom) -> 1 decimal place. Review this documentation for getting started with calculated fields. https://onlinehelp.tableau.com/current/pro/desktop/en-us/calculations_calculatedfields_create.html
[ "stackoverflow", "0024341163.txt" ]
Q: Showing record count in DevExpress XtraGrid v12.2 Below is part of my base EntityList class which contains a grid. The grid will be filled with columns and rows depending on child entities later. I need to show the number of rows on the grid's footer, and thus I am using TotalSummary. <dx:ASPxGridView runat="server" ID="grdMain" ClientInstanceName="grid" KeyFieldName="ID" AutoGenerateColumns="false"> <settings showfooter="True"/> <TotalSummary> <dx:ASPxSummaryItem FieldName="ID" SummaryType="Count"/> </TotalSummary> </dx:ASPxGridView> The problem is, in different entities that use this base class, I have different names for the ID column, such as InvoiceID, CustomerID, etc. So, how to tell the grid what Count I want it to show? Even if I had the same name for the specified column, that column would not be visible in the grid, thus it's TotalSummaryItem showing the count of that column, would not be seen on the grid. Is there any way to tell the grid I need it to show the Count of rows, not a specified column with a fixed name? Any ideas how to solve this problem??? Many thanks! P.S. if it helps, I am implementing IListServer in a DataObject class A: The documentation for FieldName property does not tell anything about this, but it says something important that can help solve the problem. By using Custom for the value of SummaryType property and handling CustomSummaryCalculate event, you have complete control over how the summary item is being calculated. Handle the event and count the rows, however you want. Another option is to add the summary item in code, where you know the name of the columns. I guess when you are creating the grid and supplying its data, you can find the name of the desired column.
[ "stackoverflow", "0030308032.txt" ]
Q: Markdown no break (nobr)? I've got a phone number in my markdown that tends to break over the end of the line. In HTML I could wrap it in a <nobr> tag to have it keep together properly. What is the correct way to do this in markdown? A: You can use non-break hyphen character ( &#x2011; ) 1&#x2011;111&#x2011;111&#x2011;1111 for 1-111-111-1111 Or you could need the phone number format with spaces in between, then use no-break space character ( &#160; ) 1&#160;111&#160;111&#160;1111 for 1 111 111 1111 A: Apparently I didn't realize you could just embed html in markdown. <nobr>[1-111-111-1111](tel:11111111)</nobr> works fine
[ "stackoverflow", "0051989200.txt" ]
Q: Vimeo Channel and Videos not showing I'm working with Vimeo API to access a channel using axios and react. I have the code set up correctly, but I am getting this error after I compile: TypeError: Cannot read property 'map' of undefined regarding this particular line: {this.state.videos.map(video => Here is the entire piece of code for reference: import React, { Component } from 'react'; import axios from 'axios'; class Apicall extends Component { componentWillMount() { this.getChannel(); } getChannel() { axios.get(`https://api.vimeo.com/channels/collegehumorbackstage/page:1`) .then(res => { const videos = res.data.data.children.map(obj => obj.data); this.setState({videos}); }); } constructor(props) { super(props); this.state = { channel_id: 'collegehumorbackstage', data: [], per_page: '5', paging: { first: '/channels/collegehumorbackstage/videos?page=1', last: '/channels/collegehumorbackstage/videos?page=2' } } this.getChannel = this.getChannel.bind(this); } render() { return ( <div className="container"> <ul> {this.state.videos.map(video => <li key={video.uri}></li> )} </ul> </div> ); } } export default Apicall; As far as I know everything else is fine, also a 2nd pair of eyes always helps. Am I missing something? A: That is because initially you don't have videos in your state. So it is undefined. You should provide default value for it, for example an empty array: this.state = { channel_id: 'collegehumorbackstage', data: [], per_page: '5', paging: { first: '/channels/collegehumorbackstage/videos?page=1', last: '/channels/collegehumorbackstage/videos?page=2' }, videos: [], }
[ "stackoverflow", "0008873381.txt" ]
Q: UITextView Interface Builder MultiLine Issue I am using a UITextView in Interface Builder and have typed a hunk of text into it and there are lots of lines breaks in it, blank lines. I did this by typing into it and alt-returning to get a new line. However when built and run on my device none of these line breaks are seen. Any tips? Anyone heard of this? Thanks. A: This works for me: In the header file: IBOutlet UITextView * textview; In the implementation file: textview.text = @"First line\nSecond line\n\nThere is a blank line above\n\tTabbed line"; Don't forget to link the UITextView with the element in the Interface Builder.
[ "stackoverflow", "0053207360.txt" ]
Q: custom thingsboard widget for device control (REST) I'm creating a controller for lights using thingsboard. I need to change device's telemetry data (thingsboard) using rest put request $.post("http://<ip_here>:8080/api/v1/<device_accesscode_here>/telemetry",{ selectedPreset:2 }); REST calls work using swagger.io and postman, but when calling from widget or any other web page, request returns 400. Can't seem to find solution to this and url is correct. i have tried both $.post and $.ajax styles. A: YAY! i got it working! for some reason, only XHR approach worked.. var data = "{\"selectedPreset\":\"2\"}"; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { console.log(this.responseText); } }); xhr.open("POST", "IP HERE"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.setRequestHeader("postman-token", "33c35ded-140d-e016-fa35-ee8185d7bd44"); xhr.send(mydata); i ripped this right out of postman.
[ "stackoverflow", "0052002899.txt" ]
Q: Jquery add autofocus to field on click I have multiple Modals with forms, I want that when I click on one it will give the attribute autofocus to the first visible input field. As there are also hidden input fields in the form. I work with MaterializeCSS to generate the Modals. I have this set up already: $('#modal-entry').modal({ onOpenEnd: function () { alert('The autofocus needs to be added in this line'); }, // Callback for Modal open }); A: Replace your alert with this, you of course need the selector for your form or the container containing your form. Use not to avoid focusing on a hidden input. Use first to get the first input in the selector list of inputs $('#form input').not(":hidden").first().focus(); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="form"> <input type="hidden"/> <input type="text" placeholder="name"/> <input type="text" placeholder="lastname"/> </form>
[ "cogsci.stackexchange", "0000008393.txt" ]
Q: Are some facial features more important than others in human facial recognition? I'm often surprised by the human ability to correctly identify other individuals despite significant modifications due to ageing, hairstyle, injury etc. But, sometimes the addition of a beard and a hat can radically increase the identification error. Are all facial regions equally important when we try to recognise human faces? Do we focus more on some regions than others? A: In a study by Pelphrey et al., 2002 the authors show that when people are asked to scan a face, they spend about 80% of the time looking at the eyes, about 10% on the nose region, and a few percents on the mouth (the remaining few percentages were spent on other non-core features such as ears, forehead etc). Hence, the eyes by far draw the most attention and represent the most important feature when it comes to facial processing. A typical example of a visual scan by a human subject as examined by eye tracking is the following (taken from Pelphrey et al., 2002), which shows that the subject scanned the core features of the facial image (eyes, nose, mouth): Nonetheless, the presence of a complete face makes recognition more efficient than when looking at incomplete faces (Tanaka & Farah, 1993)
[ "stackoverflow", "0027649166.txt" ]
Q: Slicing using negative index range a = 'blueberry' print a[-1:-3] Can some explain why this prints ''. Is it not possible to select a range using negative indexing. A: That is because you are asking it to read from -1 (the last character) to -3 in forward direction and nothing lies beyond last character hence ''. The way it works is a[begin:end:step]
[ "stackoverflow", "0007121682.txt" ]
Q: PHP how to import all classes from another namespace I'm implementing namespaces in my existing project. I found that you can use the keyword 'use' to import classes into your namespace. My question is, can I also import all the classes from 1 namespace into another. Example: namespace foo { class bar { public static $a = 'foobar'; } } namespace { use \foo; //This doesn't work! echo bar::$a; } Update for PHP 7+ A new feature in PHP 7 is grouped declarations. This doesn't make it as easy as using 1 'use statement' for all the classes in a given namespace, but makes it somewhat easier... Example code: <?php // Pre PHP 7 code use some\namespace\ClassA; use some\namespace\ClassB; use some\namespace\ClassC as C; // PHP 7+ code use some\namespace\{ClassA, ClassB, ClassC as C}; ?> See also: https://secure.php.net/manual/en/migration70.new-features.php#migration70.new-features.group-use-declarations A: This is not possible in PHP. All you can do is: namespace Foo; use Bar; $obj = new Bar\SomeClassFromBar();
[ "askubuntu", "0000642417.txt" ]
Q: Unable to Disable Power Button | Ubuntu 14.04.2 running Xfce 4.10 This is my first question here, so if I goof on a convention kindly let me know. Configuration: Ubuntu 14.04.2 with Xfce 4.10 using crouton on an Acer c720 Chromebook Issue: The default behavior of the power button (located directly above the backspace key) is to abruptly power off linux with no delay, warning, or confirmation. Steps Taken: I have already uncommented the appropriate lines in /etc/systemd/logind.conf to no effect. See the file's excerpted contents below. I have also changed the appropriate lines in ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml, also to no effect. See the file's contents below. I attempted to locate the powerbtn.sh script discussed in other threads. This file is known to live in /etc/acpi/something-else... but I have no /etc/acpi directory. I attempted to find this script, but that yielded no results. Referenced Files: cat /etc/systemd/logind.conf [Login] #NAutoVTs=6 #ReserveVT=6 #KillUserProcesses=no #KillOnlyUsers= #KillExcludeUsers=root Controllers=blkio cpu cpuacct cpuset devices freezer hugetlb memory perf_event net_cls net_prio ResetControllers= #InhibitDelayMaxSec=5 HandlePowerKey=ignore HandleSuspendKey=ignore HandleHibernateKey=ignore HandleLidSwitch=ignore #PowerKeyIgnoreInhibited=no #SuspendKeyIgnoreInhibited=no #HibernateKeyIgnoreInhibited=no #LidSwitchIgnoreInhibited=yes #IdleAction=ignore #IdleActionSec=30min cat .config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml <channel name="xfce4-power-manager" version="1.0"> <property name="xfce4-power-manager" type="empty"> <property name="power-button-action" type="uint" value="3"/> <property name="hibernate-button-action" type="uint" value="3"/> <property name="sleep-button-action" type="uint" value="3"/> <property name="critical-power-action" type="uint" value="3"/> </property> </channel> Any help would be greatly appreciated as this is quite the nuisance. A: Alright, so I stumbled upon the answer to my own question quite by accident. I probably should've mentioned this before, but I also tried to find out what keycode and keysym the power key was attached to through xev, but it registered nothing when the key was pressed. Anyhow, I just recently changed over from using the Xmonad window manager to the i3 window manager (great switch btw, i3 is awesome!). As I was configuring i3, it crossed my mind to check and see if the power key would behave the same way as it had under Xfce/Xmonad. I pressed it and, nothing! After letting out an emotionally charged cry of victory over this nuisance, I immediately started xev and discovered that (at least on this model chromebook) the power key is registered to keycode 124. I then altered my ~/.Xmodmap file to include the line: keycode 124 = F11 F11 F11 F11 Finally, I restarted Ubuntu and lo and behold, xev now appropriately registers the "F11" key being pressed and the system doesn't abruptly shut down. I hope that this is helpful to anyone who was suffering the same frustrations. Peace be with you!
[ "bicycles.stackexchange", "0000068908.txt" ]
Q: Will an Shimano M8000 brake lever blade fit a M8100? Will an Shimano M8000 brake lever blade fit a M8100? I broke my left blade, it's a Shimano XT M8100. I can only seem to find the replacement M8000 part. I don't want to replace the whole unit, seems like a waste. Thank you! EDIT, pics make everything better: Here's the original M8100 lever blade: and the M8000 lever blade: A: Ok this is exciting, I called around locally bikes owned bikes shops and asked if they had some scrap parts laying around. One of them had a Shimano SLX m7000 left brake assembly. I paid for the part and disassembled the lever. It is an exact fit. So, you can take a blade from the m7000 hydraulic series and put it on the newest m8100 hydraulic series! Fits like a glove. KEEP all the parts from the existing brake handle! Use the existing spring, newer pin, newer retention screw, and newer rubber plug/bung! Reassembling is tricky. I made a temporary paper pin to hold the assembling together. Then I put the assembly into place, then used the real metal pin to push out the paper pin.
[ "italian.meta.stackexchange", "0000001232.txt" ]
Q: Best practice for suggested edits On bigger (non-beta) communities, the best practice to suggest an edit includes the rule: "make it substantial" (in fact 2K+ users should have a reject reason titled "No improvement whatsoever"). I'd like to know if the practice it's the same here, or if being the site still in beta and the activity much lower it is tolerated to submit an edit which e.g. just improves the formatting (the question arises from this question, which as of now uses a bulleted list to list a single statement, which IMO would be better formatted using backticks). A: The best practice of all SE sites, including Italian SE, is "the edit should improve the original question/answer." When willing to edit, one should ask oneself: Does "wrong" formatting/spelling/grammar/phrasing make the text difficult to understand, or low quality, or not perfectly correct? If it does, then you should edit it, however minor the edit would appear to be. But if it does not, then don't touch it to merely satisfy your sense of style or righteousnesses. If the better formatting doesn't particularly address any issues or problems with the question, then there's no point in editing. For example, what would be improved in that question by changing from a single bullet point to another type of highlighting, such as citation or code style? Nothing, wouldn't it?
[ "stackoverflow", "0010708199.txt" ]
Q: Should a "==" implementation in Ruby check the type? I want to implement == for a ruby class. I can do def ==(o) o.respond_to?(:id) && self.id == o.id end or def ==(o) o.is_a?(Foo) && self.id == o.id end According to this article, it seems that the former would make more sense. If I was implementing eql? then I would do the latter. Is this correct? A: It depends if you're comparing to an arbitrary object or one of a specific type. The second form is specific, the first generic. In your case you're probably fine with the specific form. Generic comparisons are only relevant when the object you're comparing with can be converted or interpreted as something that can match. Using id seems way too open ended. This would imply that Foo 10 and Bar 10 are equivalent when they might be drawn from completely different sources.
[ "stackoverflow", "0062542693.txt" ]
Q: Kafka streams shuts down if sink node/topic not reachable? I want to test scenario when Kafka Streams using Processor API is reading from a source and writing to list of topics and one or two topics are not reachable ( failure test: trying to simulate it by adding 1/2 topics which do not exist in the cluster). topology.addSource("mysource","source_topic"); topology.addProcessor("STREAM_PROCESSOR",()->new SourceProcessor(),"mysource"); topology.addSink("SINK_1","TOPIC_1","STREAM_PROCESSOR"); topology.addSink("SINK_2","TOPIC_2","STREAM_PROCESSOR"); topology.addSink("SINK_3","TOPIC_3","STREAM_PROCESSOR"); // This topic is not present in cluster sourceContext.forward(eventName,eventMessage,To.child("sink1 or sink2 or sink3")); My understanding is kafkaStreams should give error for the topic which is not present and continue forwarding records to topic1 and 2 which exists. But the behavior I see is it gives the following error : Exception in thread "StreamProcessor-56da56e4-4ab3-4ca3-bf48-b059558b689f-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: task [0_0] Abort sending since an error caught with a previous record (timestamp 1592940025090) to topic "TOPIC_X" due to org.apache.kafka.common.errors.TimeoutException: Topic "TOPIC_X" not present in metadata after 60000 ms. Timeout exception caught when sending record to topic "TOPIC_X". This might happen if the producer cannot send data to the Kafka cluster and thus, its internal buffer fills up. This can also happen if the broker is slow to respond, if the network connection to the broker was interrupted, or if similar circumstances arise. You can increase producer parameter `max.block.ms` to increase this timeout. Is this the correct way of simulating non-reachable topics or topic not present issues ? also why does the Kafka streams shuts down with the above error even when we are handling Streams and topology exceptions . kafka streams should not shutdown if one of the sink topics is not available or reachable for some reason right ? . Kindly suggest On the above error I want to forward the error when catching the StreamsException to Error topic , however kafkastreams stops prematurely. catch(StreamsException e) { context.forward("","",Error_Topic) } Is this an expected behavior ? Refer : https://docs.confluent.io/current/streams/developer-guide/manage-topics.html#user-topics does this mean that a non-existent topic is not allowed in kafkastreams topology as a sink node . Please confirm. A: It's by design that Kafka Streams shuts downs if it cannot write into a sink topic. The reason is that by default, Kafka Streams guarantees at-least-once processing semantics and if it cannot write data to one sink topic but would continues, at-least-once processing would be violated as there would be data loss in the sink topic. There is a production.exception.handler configuration that might help. It allows you to swallow certain exception when writing data into an output topic. However, note, that this implies that you have data loss on the corresponding topic.
[ "stackoverflow", "0033468041.txt" ]
Q: Increment decimal place by 0.05 in Word VBA I'll start off by saying i have jut started teaching myself VBA about a week ago, so I may not be asking the right question, but... I am attempting to write a loop in Word VBA that will increment a number calculated partially from text retrieved from bookmarks. I want it to round up to the nearest .05, so .87 becomes .90 and .21 becomes .25. The module that I have written follows: A = ActiveDocument.Bookmarks("SRebateIncome").Range.Text B = ActiveDocument.Bookmarks("RebateDefault").Range.Text C = ((A - 6000) * 0.15) D = B - C E = B + D F = (18200 + ((445 + E) / 0.19)) + 1 G = (0.19 * 18200) + 445 + E + (37000 * (0.015 + 0.325 - 0.19)) H = (G / (0.015 + 0.325)) + 1 I = ActiveDocument.Bookmarks("TRebateIncome").Range.Text If F < 37000 = True Then J = (0.125 * (I - F)) Else J = (0.125 * (I - H)) End If K = E - J K = Format(Round(K, 2), "###,##0.00") 'round K up to the nearest .00 or .05 If K <> "###,###.#0" = False or K <> "###,###.#5") = False Then Do K = K + 0.01 Loop Until K = "###,###.#0" = True or K <> "###,###.#5") = True End If Set RebateOutput = ActiveDocument.Bookmarks("RebateOutput").Range RebateOutput.Text = K Now assuming that the value input for bookmarks "SRebateIncome", "RebateDefault" and "TRebateIncome" are 10175, 1602 and 43046 respectively, I expected the output to be 1460.80, but instead "K" is returned as 1460.78. At this stage I don't know anything about using Excel within word (except copy/paste a spreadsheet into a document and I don't want to do that with this). Any help would be appreciated Thanks! A: You can do it with an excel object and the Ceiling function Option Explicit Sub RoundText() Dim dblSRebateIncome As Double Dim dblRebateDefault As Double Dim dblTRebateIncome As Double Dim dblFinal As Double Dim rngOutput As Range Dim oExcel As Object ' Load the variables Set oExcel = CreateObject("Excel.Application") Set rngOutput = ActiveDocument.Bookmarks("RebateOutput").Range dblSRebateIncome = CDbl(ActiveDocument.Bookmarks("SRebateIncome").Range.Text) dblRebateDefault = CDbl(ActiveDocument.Bookmarks("RebateDefault").Range.Text) dblSRebateIncome = CDbl(ActiveDocument.Bookmarks("TRebateIncome").Range.Text) dblFinal = GetCalculatedValue(dblSRebateIncome, dblRebateDefault, dblTRebateIncome) dblFinal = oExcel.worksheetfunction.Ceiling(dblFinal, 0.05) rngOutput.Text = Format$(dblFinal, "###,##0.00") End Sub Function GetCalculatedValue(ByVal dblSIncome As Double, _ ByVal dblDefault As Double, _ ByVal dblTIncome) As Double ' Declare all the intermediate variables. Dim c As Double, d As Double, e As Double Dim f As Double, g As Double, h As Double Dim j As Double, ret As Double ' Perform the complicated calculation c = ((dblSIncome - 6000) * 0.15) d = dblDefault - c e = dblDefault + d f = (18200 + ((445 + e) / 0.19)) + 1 g = (0.19 * 18200) + 445 + e + (37000 * (0.015 + 0.325 - 0.19)) h = (g / (0.015 + 0.325)) + 1 If f < 37000 Then j = (0.125 * (dblTIncome - f)) Else j = (0.125 * (dblTIncome - h)) End If ret = e - j ' Return the value of the fucntion GetCalculatedValue = ret End Function Hope this helps. :)
[ "pt.stackoverflow", "0000064070.txt" ]
Q: Imagem de background da activity distorce quando abre o teclado Estou desenvolvendo um aplicativo em que tem uma imagem de plano de fundo da imagem. Mas toda vez que eu abro o teclado virtual para preencher um campo, essa imagem fica achatada. Como faço para que isso não aconteça? A: Achei um tópico muito semelhante no stack overflow em Inglês. Segundo ele, basta adicionar isso para a Activity no seu manifest: android:windowSoftInputMode="stateVisible|adjustPan" Parece que o problema é causado por haver uma ScrollView dentro da Activity.
[ "stackoverflow", "0045852034.txt" ]
Q: Scraping table data from a list of URLs (each containing a unique table) for the purposes of appending it all to a single list/dataframe? I am scraping data from a list of hundreds of URLs, each one containing a table with statistical baseball data. Within each unique URL in the list, there is a table for all of the seasons of a single baseball player's career, like this: https://www.baseball-reference.com/players/k/killeha01.shtml I have successfully created a script to append the data from a single URL into a single list/dataframe. However, here is my question: How should I adjust my code to scrape a full list of hundreds of URLs from this domain and then append all of the table rows from all of the URLs into a single list/dataframe? My general format for scraping a single URL is as follows: import pandas as pd from urllib.request import urlopen from bs4 import BeautifulSoup url_baseball_players = ['https://www.baseball-reference.com/players/k/killeha01.shtml'] def scrape_baseball_data(url_parameter): html = urlopen(url_parameter) # create the BeautifulSoup object soup = BeautifulSoup(html, "lxml") column_headers = [SCRAPING COMMAND WITH CSS SELECTOR GADGET FOR GETTING COLUMN HEADERS] table_rows = soup.select(SCRAPING COMMAND WITH CSS SELECTOR GADGET FOR GETTING ALL OF THE DATA FROM THE TABLES INCLUDING HTML CHARACTERS) player_data = [] for row in table_rows: player_list = [COMMANDS FOR SCRAPING HTML DATA FROM THE TABLES INTO AN ORGANIZED LIST] if not player_list: continue player_data.append(player_list) return player_data list_baseball_player_data = scrape_baseball_data(url_baseball_players) df_baseball_player_data = pd.DataFrame(list_baseball_player_data) A: If url_baseball_players is a list of all the URLs you want to scrape, and your expected output is one data frame (where you append, row-wise, each new URL's data), then just keep adding with concat() as you iterate over URLs: df = pd.DataFrame() for url in url_baseball_players: df = pd.concat([df, pd.DataFrame(scrape_baseball_data(url))])