text
stringlengths
15
59.8k
meta
dict
Q: mysql query using the wrong indexes I have some optimization problems with some of my queries in a mysql database. After I build my application I am trying to optimize using mysqltuner and explain, to find non indexed queries. This is a query that is running often and reports that is not using the index : SELECT count(*) AS rangedandselling FROM ( SELECT DISTINCT `store_formats`.`Store Name` FROM (`eds_sales` JOIN `store_formats` ON (`eds_sales`.`Store Nbr` = `store_formats`.`Store Nbr`) ) WHERE `eds_sales`.`Prime Item Nbr` = '4' AND `eds_sales`.`Date` BETWEEN CAST('2016-07-14' AS DATETIME) AND CAST('2016-07-21' AS DATETIME) AND `store_formats`.`Format Name` IN ('format1','format2') AND `store_formats`.`Store Name` IN ( SELECT DISTINCT `store_formats`.`Store Name` FROM (`eds_stock` JOIN `store_formats` ON (`eds_stock`.`Store Nbr` = `store_formats`.`Store Nbr`) ) WHERE `eds_stock`.`Prime Item Nbr` = '4' AND `eds_stock`.`Date` BETWEEN CAST('2016-07-14' AS DATETIME) AND CAST('2016-07-21' AS DATETIME) AND `store_formats`.`Format Name` IN ('format1','format2') AND `eds_stock`.`Curr Traited Store/Item Comb.` = '1' ) ) t This is the explain output : https://tools.mariadb.org/ea/pyb3h Although I have indexed the columns involved in the joins and lookups, it looks like it is picking another index. this other index is called uniqness, and is composed of 6 different columns in the source columns that I use for inserts (the combination of those columns is the only thing that makes a row unique, hence the name I gave.). I then made sure I have indexes for the other columns and I can see them in the explain. I am not sure why this happens, can someone help? Any ideas on optimizing this query? Here is the explain for those that the link above does not work : | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +---+---+---+---+---+---+---+---+---+---+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 167048 | | | 2 | DERIVED | eds_sales | ref | uniqness,Prime Item Nbr,Store Nbr | uniqness | 4 | const | 23864 | Using where; Using index; Using temporary | | 2 | DERIVED | store_formats | ref | Store Nbr,Store Name,Format Name | Store Nbr | 5 | equidata.eds_sales.Store Nbr | 1 | Using where | | 2 | DERIVED | <subquery3> | eq_ref | distinct_key | distinct_key | 84 | func | 1 | Distinct | | 3 | MATERIALIZED | store_formats | ALL | Store Nbr,Store Name,Format Name | NULL | NULL | NULL | 634 | Using where; Distinct | | 3 | MATERIALIZED | eds_stock | ref | uniqness,Prime Item Nbr,Store Nbr | uniqness | 8 | const,equidata.store_formats.Store Nbr | 7 | Using where; Distinct | +---+---+---+---+---+---+---+---+---+---+ I am also posting the related tables structure : -- -- Table structure for table `eds_sales` -- CREATE TABLE `eds_sales` ( `id` int(12) NOT NULL, `Prime Item Nbr` int(12) NOT NULL, `Prime Item Desc` varchar(255) NOT NULL, `Prime Size Desc` varchar(255) NOT NULL, `Variety` varchar(255) NOT NULL, `WHPK Qty` int(5) NOT NULL, `SUPPK Qty` int(5) NOT NULL, `Depot Nbr` int(5) NOT NULL, `Depot Name` varchar(255) NOT NULL, `Store Nbr` int(5) NOT NULL, `Store Name` varchar(255) NOT NULL, `EPOS Quantity` int(5) NOT NULL, `EPOS Sales` float(4,2) NOT NULL, `Date` date NOT NULL, `Client` varchar(255) NOT NULL, `Retailer` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `eds_sales` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `uniqness` (`Prime Item Nbr`,`Prime Item Desc`,`Prime Size Desc`,`Variety`,`WHPK Qty`,`SUPPK Qty`,`Depot Nbr`,`Depot Name`,`Store Nbr`,`Store Name`,`Date`,`Client`) USING BTREE, ADD KEY `Prime Item Nbr` (`Prime Item Nbr`), ADD KEY `Store Nbr` (`Store Nbr`); Table structure for table eds_stock CREATE TABLE `eds_stock` ( `Prime Item Nbr` int(12) NOT NULL, `Prime Item Desc` varchar(255) NOT NULL, `Prime Size Desc` varchar(255) NOT NULL, `Variety` varchar(255) NOT NULL, `Curr Valid Store/Item Comb.` int(12) NOT NULL, `Curr Traited Store/Item Comb.` int(12) NOT NULL, `Store Nbr` int(12) NOT NULL, `Store Name` varchar(255) NOT NULL, `Curr Str On Hand Qty` int(12) NOT NULL, `Curr Str In Transit Qty` int(12) NOT NULL, `Curr Str On Order Qty` int(12) NOT NULL, `Curr Str In Depot Qty` int(12) NOT NULL, `Curr Instock %` int(12) NOT NULL, `Max Shelf Qty` int(12) NOT NULL, `On Hand Qty` int(12) NOT NULL, `Date` date NOT NULL, `Client` varchar(255) NOT NULL, `Retailer` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `eds_stock` ADD UNIQUE KEY `uniqness` (`Prime Item Nbr`,`Store Nbr`,`Date`,`Client`,`Retailer`), ADD KEY `Prime Item Nbr` (`Prime Item Nbr`), ADD KEY `Store Nbr` (`Store Nbr`), ADD KEY `Curr Valid Store/Item Comb.` (`Curr Valid Store/Item Comb.`); Table structure for table store_formats CREATE TABLE `store_formats` ( `id` int(12) NOT NULL, `Store Nbr` int(4) DEFAULT NULL, `Store Name` varchar(27) DEFAULT NULL, `City` varchar(19) DEFAULT NULL, `Post Code` varchar(9) DEFAULT NULL, `Region #` int(2) DEFAULT NULL, `Region Name` varchar(10) DEFAULT NULL, `Distr #` int(3) DEFAULT NULL, `Dist Name` varchar(26) DEFAULT NULL, `Square Footage` varchar(7) DEFAULT NULL, `Format` int(1) DEFAULT NULL, `Format Name` varchar(23) DEFAULT NULL, `Store Type` varchar(20) DEFAULT NULL, `TV Region` varchar(12) DEFAULT NULL, `Pharmacy` varchar(3) DEFAULT NULL, `Optician` varchar(3) DEFAULT NULL, `Home Shopping` varchar(3) DEFAULT NULL, `Retailer` varchar(15) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `store_formats` ADD PRIMARY KEY (`id`), ADD KEY `Store Nbr` (`Store Nbr`), ADD KEY `Store Name` (`Store Name`), ADD KEY `Format Name` (`Format Name`); A: CAST('2016-07-14' AS DATETIME) -- the CAST is not needed; '2016-07-14' works fine. (Especially since you are comparing against a DATE.) IN ( SELECT ... ) is inefficient. Change to a JOIN. On eds_stock, instead of INDEX(`Prime Item Nbr`) have these two: INDEX(`Prime Item Nbr`, `Date`) INDEX(`Prime Item Nbr`, `Curr Traited Store/Item Comb.`, `Date`) INT is always a 4-byte number, even if you say int(2). Consider switching to TINYINT UNSIGNED (and other sizes of INT). float(4,2) -- Do not use (m,n); it causes an extra rounding and my cause undesired truncation. Either use DECIMAL(4,2) (for money), or plain FLOAT. Bug?? Did you really want 8 days, not just a week in AND `Date` BETWEEN CAST('2016-07-14' AS DATETIME) AND CAST('2016-07-21' AS DATETIME) I like this pattern: AND `Date` >= '2016-07-14' AND `Date` < '2016-07-14' + INTERVAL 1 WEEK Instead of two selects SELECT count(*) AS rangedandselling FROM ( SELECT DISTINCT `store_formats`.`Store Name` ... One select will probably work (and be faster): SELECT COUNT(DISTINCT `store_formats`.`Store Name`) AS rangedandselling ... Once you have cleaned up most of that, we can get back to your question about 'wrong index', if there is still an issue. (Please start a new Question if you need further help.)
{ "language": "en", "url": "https://stackoverflow.com/questions/38522104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django: Form submission in ajax style without csrf token I am new to django. Suppose I have a form and I would like to submit a file to the server in ajax. I notice that the server has HTTP 403 error when I don't specify the csrf token in the post statement (correct behaviour), but somehow the file can still be able to upload to the server... Here is my sample code: models.py (include model and form): from django.db import models from django.forms import ModelForm # Create your models here. class Dummy(models.Model): myfile = models.FileField(upload_to='temp') class DummyForm(ModelForm): class Meta: model = Dummy fields = ['myfile',] views.py: # Create your views here. class TestFormView(View): def get(self, request): form = DummyForm() context = { 'form' : form } print form return render(request, 'testform.html', context) def post(self, request): print request.FILES form = DummyForm(request.POST, request.FILES) print form.is_valid() print form.errors print form.is_bound if form.is_valid(): form.save() print Dummy.objects.all().count() return render(request, 'testform.html') testform.html: <form id="myForm" action="testform/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input id="id_myfile" type="file" size="60" name="myfile"> <input type="submit" value="Ajax File Upload"> </form> <div id="progress"> <div id="bar"></div> <div id="percent">0%</div > </div> <br/> <div id="message"></div> <script> $(document).ready(function() { var options = { beforeSend: function() { $("#progress").show(); //clear everything $("#bar").width('0%'); $("#message").html(""); $("#percent").html("0%"); }, uploadProgress: function(event, position, total, percentComplete) { $("#bar").width(percentComplete+'%'); $("#percent").html(percentComplete+'%'); }, success: function() { $("#bar").width('100%'); $("#percent").html('100%'); alert("done!"); }, complete: function(response) { $("#message").html("<font color='green'>"+response.responseText+"</font>"); }, error: function() { $("#message").html("<font color='red'> ERROR: unable to upload files</font>"); } }; $("#myForm").ajaxForm(options); $("#myForm").submit(function(event) { event.preventDefault(); var $form = $(this); var url = $form.attr('action'); $.post("testform/", { myfile: $('#myfile').val()}); return false; }); }); </script> Of course if I put the csrf token in the $post function, I get HTTP 200. My concern is that will this create security hole because it looks like anyone can upload files to the server? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/18244567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making Mac shortcuts (e.g. Cmd-C) work on linux Is there a way to map Cmd+C to Copy in linux? (instead of Ctrl+C) Would be nice if I could also have the emacs style ones, like Ctrl+B to move left by one character. A: Is there a way, on Linux/X, to map certain key combos to other key combos? In the tradition of all open source projects, there's not a way, there are several. At the lowest level you've got kernel keybindings, which is probably not what you want. At the X server level you've got xkb with its myriad utilities. And then it seems that every window manager - gnome, kde, xfce or other - also has a keymapping utility. xkb seems to have lots of utils and such around it, and is likely more complete than any random window manager's keymapping utils, so I'd look at that first. A: KDE 3 is probably the most flexible here; there's a pre-defined keyboard shortcut scheme named "Mac Scheme". You can set it through KControl Control Center > Regional & Accessibility > Keyboard Shortcuts or kcmshell keys and it will have effect on almost all KDE applications immediately. You might miss some of those Emacs-like "Ctrl-*" shortcuts that OS X has, but that aside, it works well (as long as your X modifiers are mapped correctly). And if it's not to your liking, it's easily customizable. You can also set Control Center > Desktop > Behavior to enable a Mac OS-like menubar; all KDE applications will then share a menubar at the top of the screen instead of being individually attached to each window. A: Update 02/03/2020 Kinto has now been rewritten in C for Ubuntu/Debian systems using x11. It also uses json config files, making it easier to manage and extend to other applications than just terminals. The app no longer maps to Super in the Terminal apps, it will now properly map to Ctrl+Shift to create the exact same feel as having a Cmd key. Please checkout the latest release. https://github.com/rbreaves/kinto The main change to allow for the Super = Ctrl+Shift change is in this symbols file. default partial xkb_symbols "mac_levelssym" { key <LWIN> { repeat= no, type= "ONE_LEVEL", symbols[Group1]= [ Hyper_L ], actions[group1]=[ SetMods(modifiers=Shift+Control) ] }; key <RWIN> { repeat= no, type= "ONE_LEVEL", symbols[Group1]= [ Hyper_R ], actions[group1]=[ SetMods(modifiers=Shift+Control) ] }; }; Pjz's answer is correct in saying that an xkb solution would be ideal, sadly few have taken that route, most likely due to the difficulty of learning xkb and it seems many have gone the route of using Xmodmap files which is being deprecated while we are on our way to Wayland. This answer may be several years too late, but here it is any ways. Kinto is a tool I recently created that will address this problem and does so by using xkb and by listening to what app you are currently using, as it also changes the keymap while using terminals so the mac like experience can be consistent. https://github.com/rbreaves/kinto https://medium.com/@benreaves/kinto-a-mac-inspired-keyboard-mapping-for-linux-58f731817c0 Here's a Gist as well, if you just want to see what is at the heart of it all, it will not alternate your keymap when needed though. The Gist also does not include custom xkb keymap files that setup macOS style cursors/word-wise manipulations that use Cmd and the arrow keys. https://gist.github.com/rbreaves/f4cf8a991eaeea893999964f5e83eebb Edit: Posting the contents of the gist as well. I cannot realistically post the contents of Kinto. # permanent apple keyboard keyswap echo "options hid_apple swap_opt_cmd=1" | sudo tee -a /etc/modprobe.d/hid_apple.conf update-initramfs -u -k all # Temporary & instant apple keyboard keyswap echo '1' | sudo tee -a /sys/module/hid_apple/parameters/swap_opt_cmd # Windows and Mac keyboards - GUI (Physical Alt is Ctrl, Physical Super is Alt, Physical Ctrl is Super) setxkbmap -option;setxkbmap -option altwin:ctrl_alt_win # Windows and Mac keyboards - Terminal Apps (Physical Alt is Super, Physical Super is Alt, Physical Ctrl is Ctrl) setxkbmap -option;setxkbmap -option altwin:swap_alt_win # # If you want a systemd service and bash script to help toggle between # GUI and Terminal applications then look at project Kinto. # https://github.com/rbreaves/kinto # # Note: The above may not work for Chromebooks running Linux, please look # at project Kinto for that. # # If anyone would like to contribute to the project then please do! # A: You'll get almost all of the way there if you switch Cmd and Ctrl A: xmodmap -e "keycode 63 = Control_L" That way Cmd will be Control. No other keys will be swapped Edited: I forgot the "-e"
{ "language": "en", "url": "https://stackoverflow.com/questions/434083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: TBB error when compiling I have the following piece of code that i am trying to execute #include <iostream> #include <cstring> #include "tbb/tbb.h" using namespace std; using namespace tbb; class Accumulate{ float& arr; float* src; public: Accumulate(float& _arr, float* _src) :arr(_arr), src(_src){} void operator() (int i) const{ arr += src[i]; } }; int main(int argc, const char * argv[]) { float arr[4] = {1,3,9,27}; float sum = 0; parallel_for(0, 4, Accumulate(sum, arr)); cout<< sum << endl; } I am trying to make use of parllel_for to calculate the sum and this requires the tbb library. I downloaded the source tbb directory and pasted it in my xcode project directory. When i try to compile the above code, i seem to get the following error 'tbb/internal/_flow_graph_types_impl.h' file not found I am not sure what i am missing, please advise A: I can see this file in TBB repo: https://github.com/01org/tbb/blob/tbb_2017/include/tbb/internal/_flow_graph_types_impl.h Please make sure that your installation of TBB is not damaged. Off-topic advice, there is a data-race in your program on sum and you can use lambda instead of explicit functor: int main(int argc, const char * argv[]) { float arr[4] = {1,3,9,27}; atomic<float> sum = 0; // fixing data-race. Still, it's not recommended way parallel_for(0, 4, [&](int i){ sum += arr[i]; }); cout<< sum << endl; } See also tbb::parallel_reduce in order to make this code correct, clean, and efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/40138885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIViewControllers not receiving orientation notifications I've spent the last hour or so trying to work out why not all my UIViewControllers are receiving orientation change notifications. I've got a subclassed UIViewController attached to the window, that internally creates a few other UIViewControllers to manage smaller portions of the screen which are re-used elsewhere in the application I'm building. The problem is, only the UIViewController attached to the window is receiving the orientation change notifications. The other UIViewControllers aren't firing their - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration methods. I'm assuming it's expected behaviour, and I can't seem to find anything mentioning it in the docs. Is there a way to make sure all active UIViewControllers are getting orientation changes? Or does the parent view controller have to tell it's children when changes are occurring? Cheers. A: Are all your view controllers returning YES to shouldAutorotateToInterfaceOrientation: ? If so, I suggest to pass the interface orientation messages from the parent to the children viewControllers, as you suggested. I have been doing so before and had no problems with that approach so far.
{ "language": "en", "url": "https://stackoverflow.com/questions/3171083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: applying a class to a div I have a css which has some attribute as follows: .ts{ background-image: url("images/xyz/pb.gif"); background-repeat: no-repeat; padding:0,0,0,20px; display:none; } .ts.visible{ display: inline; } Now i want to apply the this style to a div in my html page.How cna i do it.I dont know css A: Yep, what they said. Also, if you want to assign more than one class, use a space to separate them, like so: <div class="ts visible">. Edit: Also, use spaces to separate the "padding" values, like this: padding: 0 0 0 20px;, or just use padding-left: 20px;. A: You can use it like this: <div class="ts">... </div> But I strongly recommend you take a look at css here, it's not that hard. A: Just give that <div> a class attribute, like this: <div class="ts"></div> If you want it to have both classes, use a space between like this: <div class="ts visible"></div> A: You'd simply do: <div class="ts">Contents of div</div> That said, I very much suspect that's not the answer you're looking for. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/4386399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Storing similar objects in a database I am developing an a house renting/selling application, it will allow users to post rental and houses on sale. My concern is the two objects have some similar and different attributes,for example here is a house on rent can have the following attributes ` public class RentalHouse extends Property{ private int numOfBedrooms; private int payMonthsInAdvance; private double securityDeposit; private double rentals; private String dayOfVacancy; } Whilst a house on sale can have the following attributes public class SaleHouse extends Property{ private int numOfBedrooms; private double price; } public class Property { private long id; private String title; private String description; private ArrayList<String> images; private String province; private String area; } Now here is my question; is it good design to have 2 tables for one for rental houses the other for houses on sale? and what would you advice?
{ "language": "en", "url": "https://stackoverflow.com/questions/47167677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What partition key to choose in cosmos db with little data and one customer per database? We’re developing a personnel management system based on blazor and Cosmos DB serverless. There will be one customer per database and around 30 “docTypes”. The biggest categories by number and data volume are "users" and "employees". When we query we get all data of users and employee at once. So it can be several thousand. The other doctypes are much smaller an less frequently queried. The volume of data per customer will not exceed 5 GByte. The most frequent queries are to 3 docTypes. Would it make more sense to use customerId (so all data is in one partition) or docType as a partition key? thanks A: Based on the information you supplied it sound like docType is a good property to use as partition key, since it can be used to avoid cross partition queries. Especially since you state this will be often be used in your queries. With the max size you stated it will also be unlikely to cause you issues as a single partition can contain up to 20GB of data. One thing to watch out for is Hot Partitioning. You state that your users partition might be a lot bigger than others. That can result into one partition doing all of the lifting while the others sit mostly idle which results and causing inefficiëncy of your total throughput. On the other side it won't really matter for your use case. Since none of the databases will exceed that 5GB you'll always stay within a single partition, but it's always good though to think about it beforehand; As situations may change and you end up with a database that does split into partitions. Lastly I would never use a single partition for all data. It has no benefits. If you have no properties that could serve as partition key then id is the better choice (so a logical partition per document). It won't hit storage limitations and evenly distributes throughput between partitions. A: I would highly recommend you first take a look at this segment of the Data Modelling & Partitioning presentation by Thomas Weiss, Cosmos DB program manager. In my view it's one of the best resources to understand how to think about partitioning. Do agree with David Makogon that you didn't provide enough data. For instance, we know there are 30 doc types per single database - given cosmosdb database uses containers, I actually expect each docType to have its own container - contrary to what you wrote: Would it make more sense to use customerId (so all data is in one partition) or docType as a partition key? Which suggests you want to use a single container for all your data. I wouldn't keep users and employees as documents in the same container. They are separate domains and deserve their own container. See Azure docs page on Partition Strategy and subsequent paragraph about access patterns. The recommendation is to: Choose a partition key that enables access patterns to be evenly spread across logical partitions. In the access patterns section, the good practice mentioned is to separate data into hot, medium and cold data and place it into their own containers. One caveat is, that according to this page the max number of containers per database with shared throughput is 25. If that is not possible, and all data has to end up in a single container, then docType seems to be the right partition key, because your queries will get data by docType if I understood correctly. As 404 wrote, you want to avoid Hot Partitioning i.e. jamming most of documents in a container into a single or a few logical partitions. Therefore you want to choose a partition key based on most frequent operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/70532412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MethodNotAllowedHttpException laravel 4.2 error here is my ContactController.php: public function destroy($id){ $contact = Contact::find($id); $contact->delete(); return Redirect::to('http://localhost:8000/contactsview'); } Here is my rountes.php Route::delete('/contactsview/destroy/{id}', array('uses'=>'ContactController@destroy')); Here is my index.blade.php: {{ Form::open(array('url'=>'/contactsview/delete/'.$contact->id, 'method'=>'DELETE', 'style'=>'display:inline;')) }} <!-- {{ Form::hidden('id', $contact->id) }} --> {{ Form::submit('Delete') }} {{ Form::close() }} What did I do wrong? A: Try the form with this instead, passing in the $contact->id as a param rather than directly in the URL: {{ Form::open(array('method' => 'DELETE', 'action' => array('ContactController@destroy', $contact->id )) }}
{ "language": "en", "url": "https://stackoverflow.com/questions/32584786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java Opencv unsatisfiedLinkError, native Library is loaded I am trying to run some program on opencv, but I am getting this error: Exception in thread "main" java.lang.UnsatisfiedLinkError: org.opencv.objdetect.CascadeClassifier.CascadeClassifier_0(Ljava/lang/String;)J I have already loaded the library, libopencv_java310.so by using this code: System.loadLibrary(Core.NATIVE_LIBRARY_NAME); I have also added the path to the native library. I have searched a lot on the internet, but the only reason this error comes, is due to native library is not loaded. What could be the other reason of getting this error. Can anyone help....! Any help will be appreciated. A: you might move your System.loadLibrary(Core.NATIVE_LIBRARY_NAME); to a static block so the dll gets loaded before any instruction of opencv .
{ "language": "en", "url": "https://stackoverflow.com/questions/36321161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xmlns required for bean component of spring-servlet.xml for spring security application How to determine what xmlns are required for beans component of my spring-servlet.xml(spring configuration file) for spring security application? Is this is the correct code? <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd"> ... </beans> A: I got my answer in the spring framework reference and that is mention below: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd"> ... </beans> In general it should be like this. for reference Spring Security 3.0 Reference
{ "language": "en", "url": "https://stackoverflow.com/questions/9349640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embed a Mobile Emulator on a Website? I'm basically wondering if it was possible to create a functionality similar to this site: http://www.howtogomo.com/en/#gomo-meter I want to add some kind of feature on my website that will allow visitors to check to see how their websites looked on a mobile device like an iPhone or Android phone. A: You could fire up the android emulator from the android sdk , then using android debugging bridge fire up the following command adb shell am start -a android.intent.action.VIEW -d http://stackoverflow.com then follow the following blog http://android.amberfog.com/?p=168 , to take screen shot . A: No. It looks like this site renders the website on the server side, and then sends down an image of this to your browser. If you are interested only in Android and iPhone (and similar smartphones with browsers based on webkit) then you could try a similar approach to http://iphonetester.com. This uses a frame embedded to simulate the size (in pixels) of an iPhone. Note, that even though these browsers may be based on webkit, it doesn't mean their implementation is the same - see http://www.quirksmode.org/webkit.html for variance across different webkit based browsers. This won't work if you want to stray to other non webkit based browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/8232389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Creating artificial data out of data that only contains sentences I am trying to create artificial data. However my current data only contains sentences. Two example rows that I have are the following: Your order is on its way with tracking {imaginary tracking code}. Visit {imaginary random link} for more information. The package has been shipped out with tracking {imaginary tracking code}. Visit {imaginary random link} for more information. Now what I want to do is basically take these sentences and create thousands of them but with randomized tracking codes. I thought about splitting the sentences at two at the tracking code but couldn't figure out a way to split them at the specific tracking code. Like most tracking codes they contains numbers but also sometimes letters(usually at the front). My current method which is bad would be to split the sentence into words. then check each word if it contains numbers. If it does contain a number that is the tracking code and now I have my way of creating artificial version of that sentence by taking everything before the tracking code inserting my artificial tracking code and everything after the tracking code. Repeating this for every row in the dataset and then randomizing the dataset. So my question is, is there a more optimal way? A: I suggest that you use regex to identify the codes to replace with random codes. This example is deliberately simplified, I have used static codes and not randomly generated one and the regex pattern needs to be defined and refined. import re sentences = ('Your order is on its way with tracking 1234567890. Visit 98765432 for more information.', 'The package has been shipped out with tracking 1245789865. Visit 65659865 for more information.') code1='9999999999' code2='11111111' for x in sentences: y = re.findall(r'(\D*)\d+(\D*)\d+(\D*)' ,x) if y[0][2]: z = y[0][0] + code1 + y[0][1] + code2 + y[0][2] print(z) output Your order is on its way with tracking 9999999999. Visit 11111111 for more information. The package has been shipped out with tracking 9999999999. Visit 11111111 for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/71938676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Java Firestore query snapshot returning string rather than boolean I am trying to map my query results from firestore back to a class in my java application. I have saved this as a Boolean on the web console, see the image: And then on the app I use the following function to map this to my class: query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { List<uk.wefix.FirestoreModels.Job> mJobsList = new ArrayList<>(); if(task.isSuccessful()){ for(QueryDocumentSnapshot document : task.getResult()) { uk.wefix.FirestoreModels.Job job = document.toObject(uk.wefix.FirestoreModels.Job.class); mJobsList.add(job); } mjobsAdaptor.clear(); mjobsAdaptor.addAll(mJobsList); } else { Log.d("JobsFragment", "Error getting documents: ", task.getException()); } } }); And the class it maps to: public class Job { public String first_name; public String second_name; public String phone_number; public Boolean complete; public Job() {} public Job(String first_name, String second_name, String phone_number, Boolean complete) { this.first_name = first_name; this.second_name = second_name; this.phone_number = phone_number; this.complete = complete; } /** * @return String */ public String getFirst_name(){ return first_name; } /** * @return String */ public String getSecond_name(){ return second_name; } /** * @return String */ public String getPhone_number(){ return phone_number; } /** * @return Boolean */ public Boolean getComplete(){ return complete; } } It seems like Firestore is returning a String instead of a Boolean which means I get the following error out: java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.String to boolean (found in field 'complete') Obviously I could just do something like this in the Job class, but that seems a bit hacky and I am not sure if this is just a bug or if I am doing something wrong. Potential 'hacky' solution /** * @return Boolean */ public Boolean getComplete(){ if(complete.equals("true")){ return true; }else{ return false; } } Query: CollectionReference jobs = db.collection("jobs"); Query query = jobs.whereEqualTo("technician_id", 10).whereEqualTo("date", "2018-12-12");
{ "language": "en", "url": "https://stackoverflow.com/questions/53883555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Program or script to see hex triplets in their actual color I've got a theme file that looks like following: PRIMARY1_COLOR=#7CACDF PRIMARY2_COLOR=#A5C6E9 PRIMARY3_COLOR=#E2EDF8 SECONDARY1_COLOR=#7CACDF SECONDARY2_COLOR=#A5C6E9 SECONDARY3_COLOR=#B9D3EE Is there any tool which allows editing such file while displaying actual colors? A: You can use Geany. It has "Color chooser" button - select your hex code and click on it and you will see the color and will be able to change it. A: You can create an HTML file with your favorite text editor and simply load it up your browser. Try this: <style> .PRIMARY1 { color: #7CACDF } .PRIMARY2 { color: #A5C6E9 } ... </style> <div class="PRIMARY1">PRIMARY1</div> <div class="PRIMARY2">PRIMARY2</div> ... You can even automatically generate this with some clever find & replace or Excel formulas.
{ "language": "en", "url": "https://stackoverflow.com/questions/4430410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Duplicate code but make the copied slower I build the shooting game by C# and Unity. I use GameController and GameStatus to show the score and time. At first scene, I have no problem. It can run smoothly. But the second scene, I copy scene from first and make new GameController for second scene. It's work but running game slower. I try to make new project by using same code, but it's slow even it's my first scene. I don't know cause of this happen. Below is my code, it's work. using UnityEngine; using System.Collections; public class MyGameController2 : MonoBehaviour private Gun gun; public GUISkin mySkin2; private GameStatus gameStatus; public float countDownTime2; private float scoreTime2; private float menuTime2; // Use this for initialization void Start () { countDownTime2 = 60.0f; scoreTime2 = countDownTime2+3; menuTime2 = countDownTime2+5; gameStatus = (GameStatus)GetComponent(typeof(GameStatus)); } // Update is called once per frame void Update () { countDownTime2 -= Time.deltaTime; if(gameStatus.score >= 300){Application.LoadLevel("MainScene2");} if(countDownTime2 <= 0.0f) {gameStatus.isGameOver = true; countDownTime2 = 0.0f; gameStatus.score +=0; } scoreTime2 -= Time.deltaTime; menuTime2 -= Time.deltaTime; } void OnGUI() { float sw = Screen.width; float sh = Screen.height; GUI.skin = mySkin2; int mScore = gameStatus.score; if(countDownTime2 > 0.0f){ GUI.Label (new Rect(50,0,sw/2,sh/2), "Score : " + mScore.ToString(),"scoreStyle"); GUI.Label (new Rect(400,0,0,0), "Time : " + countDownTime2.ToString("000") ,"timeStyle"); } if(gameStatus.isGameOver) {GUI.Label (new Rect(120,100,sw/2,sh/4),"Game Over","messageStyle");} if (scoreTime2 <= 0.0f) { GUI.Label (new Rect(130,50,0,0), "Your Score is " + mScore.ToString(),"scoreStyle2"); } if(menuTime2 <= 0.0f){ // Make the first button. If it is pressed, Application.Loadlevel (1) will be executed if(GUI.Button(new Rect(100,220,80,20), "Retry")) { Application.LoadLevel("MainScene");} if(GUI.Button(new Rect(300,220,80,20), "Menu")) { Application.LoadLevel("TitleScene");} } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/19998071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF5 Code First Many to Many with Migrations I have done this before, but for some reason cannot get it to work in EF5. Usually it just automatically picks up when I have many to many relationships like this one... public class Beer { public int Id { get; set; } public virtual ICollection<Restaurant> Restaurants { get; set; } } public class Restaurant { public int Id { get; set; } public virtual ICollection<Beer> Beers { get; set; } } I am wanting a RestaurantsBeers table or whatever with just RestaurantId and BeerId. When I create it using the normal Code First way by just running the application it works. Using migrations though, it won't create that table. I ran Enable-Migrations then Add-Migration FirstDb and finally Update-Database... No dice... Also tried this... protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Beer>() .HasMany(b => b.Restaurants) .WithMany(a => a.Beers) .Map(m => m.MapLeftKey("BeerId") .MapRightKey("RestaurantId") .ToTable("BeersRestaurants")); } A: Migrations to create a new M2M relationship are not supported yet in EF5.0RC per my experience trying to track down the same issue. Thus why it will work on standard DB creation but doesn't work with Migration features. You can export the create SQL from the standard code first database initialization and run it manually on the migration for now. This should be resolved when EF5.0 goes RTM but for now we have to wait it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/11043023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Select multiple checkboxes using angularjs but unable to get selected one I am trying to get the list of selected checkboxes using angularjs. But unable to get selected. HTML code Here <div class="item" ng-repeat="x in result"> <div class="item-image"> <input type="checkbox" id="product_{{x.id}}" class="form-control" ng-model="x.Selected"> </div> <div class="item-name"> {{ x.category_name }} </div> </div> script code: .controller('categorieCtrl', function($scope, $http) { $scope.result = [{ id: 1, category_name: 'Apple', Selected: false }, { id: 2, category_name: 'Mango', Selected: false }, { id: 3, category_name: 'Orange', Selected: false }]; $scope.myFunc = function () { debugger; var message = ""; for (var i = 0; i < 3; i++) { if ($scope.result[i].Selected) { var id = $scope.result[i].id; var categoryName = $scope.result[i].category_name; message += "Value: " + id + " Text: " + categoryName + "\n"; } } alert(message); }; }); In the above code i am not getting selected items. Please let me know how can i get selected items using angularjs. A: I've created a plunkr with your code here and it is working fine. I suppose you are not calling myFunc() correctly. And also instead of using for (var i = 0; i < 3; i++) { if ($scope.result[i].Selected) { ... } } You can make use of angular.forEach which will give you the object directly angular.forEach(($scope.result, function(result, index){ if (result.selected){ ... });
{ "language": "en", "url": "https://stackoverflow.com/questions/47905903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flash light not detected I am trying to write an app which turns on flash light when a button is pressed. The problem is the app is not detecting flash light on my phone. I have searched alot on internet. Sure others have faced the problem, I have also applied those solutions but they don't seem to work. I don't know what is causing this problem. Posting the code here: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_starting_point); if(! getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) // checking if flash light is available inn android phone { Toast.makeText(StartingPoint.this, "Sorry this app can't work without flash light", Toast.LENGTH_LONG).show(); finish(); } cam = Camera.open(); param = cam.getParameters(); } @Override public void onClick (View v) { if(!flashOn) { i=0; flashOn=true; param.setFlashMode(Parameters.FLASH_MODE_TORCH); cam.setParameters(param); cam.startPreview(); } else{ i=0; flashOn=false; param.setFlashMode(Parameters.FLASH_MODE_OFF); cam.setParameters(param); cam.stopPreview(); } } I have added these permissions in Android Manifest as well. <uses-permission android:name="android.permission.FLASHLIGHT"/> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> Regards A: I have an app that checks the flashlight feature and it works fine. Here is the code I used for checking if the user has the light: if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { new AlertDialog.Builder(this) .setTitle("Sorry") .setMessage("It appears that your device is incompatible with this app. Sorry for the inconvenience.") .setNeutralButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { finish(); } }).show(); return; } Now to actually make the light work, I made a toggle button and wrote the following code: private boolean isLightOn = false; private Camera camera; private ToggleButton button; public Vibrator v; if (camera == null) { camera = Camera.open(); } final Parameters p = camera.getParameters(); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (isLightOn) { Toast.makeText(context, "Light off!", Toast.LENGTH_SHORT).show(); v.vibrate(40); p.setFlashMode(Parameters.FLASH_MODE_OFF); camera.setParameters(p); camera.stopPreview(); isLightOn = false; } else { Toast.makeText(context, "Light on!", Toast.LENGTH_SHORT).show(); v.vibrate(40); p.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(p); camera.startPreview(); isLightOn = true; } } }); And finally, here are the only permissions I used: <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> Note: All of the above code is in the onCreate method of my activity. Hope this helps solve your problem! A: I think you aren't setting your params again: I used this to check if there is a flashlight: public static Boolean hasFlashLight(Context context){ return context.getApplicationContext().getPackageManager() .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); } and to turn it off and on: Parameters params = mCamera.getParameters(); if (!isFlashlightOn) { params.setFlashMode(Parameters.FLASH_MODE_OFF); } else { params.setFlashMode(Parameters.FLASH_MODE_TORCH); } mCamera.setParameters(params); Let me know if it works for you too. A: I had the same problem. Use this if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) { //Flash ok Parameters params = mCamera.getParameters(); params.setFlashMode(Parameters.FLASH_MODE_TORCH); } else { //Flash not supported } to determinate if your device has flash. A: Some cameras need surface holder, otherwise they block the flash. SurfaceView preview = (SurfaceView) findViewById(...); SurfaceHolder holder = preview.getHolder(); holder.addCallback(this); Camera camera = Camera.open(); camera.setPreviewDisplay(holder);
{ "language": "en", "url": "https://stackoverflow.com/questions/17514555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Kafka 0.10.1.0 Test Server: Request METADATA failed I'm getting basic errors after setting up a super simple single-instance Kafka VM. This is for tiny volume development testing. This is using the latest Confluent Platform 3.1.1 which includes the almost latest Kafka 0.10.1.0. FYI, a slightly newer bug patch Kafka 0.10.1.1 is out, but the next post 3.1.1 Confluent Platform binary that includes that isn't available quite yet. I configure /etc/kafka/server.properties with (I'm using a static local IP for dev testing simplicity): listeners=PLAINTEXT://192.168.50.20:9092 advertised.listeners=PLAINTEXT://192.168.50.20:9092 (is that right?) Simple console admin commands are generating errors. This leads me to believe that there is something wrong with the basic setup/configuration. ~$ /usr/bin/kafka-consumer-groups --new-consumer --bootstrap-server localhost:9092 --list Error while executing consumer group command Request METADATA failed on brokers List(localhost:9092 (id: -1 rack: null)) java.lang.RuntimeException: Request METADATA failed on brokers List(localhost:9092 (id: -1 rack: null)) at kafka.admin.AdminClient.sendAnyNode(AdminClient.scala:67) at kafka.admin.AdminClient.findAllBrokers(AdminClient.scala:87) at kafka.admin.AdminClient.listAllGroups(AdminClient.scala:96) at kafka.admin.AdminClient.listAllGroupsFlattened(AdminClient.scala:117) at kafka.admin.AdminClient.listAllConsumerGroupsFlattened(AdminClient.scala:121) at kafka.admin.ConsumerGroupCommand$KafkaConsumerGroupService.list(ConsumerGroupCommand.scala:304) at kafka.admin.ConsumerGroupCommand$.main(ConsumerGroupCommand.scala:66) at kafka.admin.ConsumerGroupCommand.main(ConsumerGroupCommand.scala) EDIT: The problem, thanks to Gondola_Ride, was that I specified the IP in listeners in server.properties. I could connect via that IP, but not via localhost. The solution was to use host 0.0.0.0 which is Kafka's convention for binding to all local TCP interfaces: listeners=PLAINTEXT://0.0.0.0:9092 advertised.listeners=PLAINTEXT://192.168.50.20:9092 A: Try adding an entry in the /etc/hosts on the host where you are running this command for this host 192.168.50.20 and see if it works Something like 127.0.0.1 localhost.localdomain localhost OR 192.168.50.20 hostname hostname-alias Then try using it in the command OR Try using ip address directly in the command instead of localhost
{ "language": "en", "url": "https://stackoverflow.com/questions/41513132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google maps api and geolocation, Javascript and Html Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in Non-working code: var map; var infowindow; function initialize() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } function showPosition(position) { var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude ); map = new google.maps.Map(document.getElementById('map'), { mapTypeId: google.maps.MapTypeId.ROADMAP, center: latlon, zoom: 15, disableDefaultUI: true }); var request = { location: latlon, radius: 555, types: ['bar'] }; infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); service.search(request, callback); } function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { createMarker(results[i]); } } } } function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { alert(place.name); }); } google.maps.event.addDomListener(window, 'load', initialize); Working code var map; var infowindow; function initialize() { var latlon = new google.maps.LatLng(-33.8665433, 151.1956316); map = new google.maps.Map(document.getElementById('map'), { mapTypeId: google.maps.MapTypeId.ROADMAP, center: latlon, zoom: 15, disableDefaultUI: true }); var request = { location: latlon, radius: 555, types: ['bar'] }; infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); service.search(request, callback); } function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { createMarker(results[i]); } } } function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { alert(place.name); }); } google.maps.event.addDomListener(window, 'load', initialize); Any help if appreciated :) A: Replace your line: var latlon = new google.maps.LatLng (position.coords.latitude + "," + position.coords.longitude); with var latlon = new google.maps.LatLng (position.coords.latitude, position.coords.longitude); The problem is in concatenating two values into one where constructor expects two parameters.
{ "language": "en", "url": "https://stackoverflow.com/questions/12815168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Try/Catch with while loop can't work Problem * *Method asks user for an integer value. *Pass the value into a loop to ensure it is a positive number. *Add a in.nextline to ensure the value don't overrun into next line of code. - *Return integer value. private static int getIntFromUser(String aa) { int aaa = 0; while (true && aaa <= 0) { try { System.out.println(aa + ": "); aaa = in.nextInt(); if (aaa <= 0) { System.out.println("Please enter a positive number."); } } catch (Exception e) { System.out.println("Please enter an integer: "); in.next(); } } in.next(); return aaa; } Question Try/Catch with while loop can't work ? A: Tested it myself, it returns aaa properly (after removing in.next() at the bottom of the method and replacing it with in.nextLine()). When you do a return call, you need to send it somewhere. Such as System.out or to a variable like int x = getUserFromInput("test: "); public class Tester { private static Scanner in = new Scanner(System.in); private static int getIntFromUser(String aa) { int aaa = 0; while (true && aaa <= 0) { try { System.out.println(aa + ": "); aaa = in.nextInt(); if (aaa <= 0) { System.out.println("Please enter a positive number."); } } catch (Exception e) { System.out.println("Please enter an integer: "); in.next(); } } in.nextLine(); return aaa; } public static void main(String[] a) { System.out.println(getIntFromUser("test123")); } } Output
{ "language": "en", "url": "https://stackoverflow.com/questions/34180416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ActiveRecord STI delete doesn't work correctly I want to store two models using active record, but delete doesn't work as expected. * *Evaluation has id, name and description *and SqlEvaluation has additional two columns of query_string and database. I want to use those two tables, and eval_typ_id is used to distinguish which subclass should be used: 1 for SqlEvaluation. create table eval ( eval_id int, eval_name varchar, eval_desc varchar, eval_typ_id int ); create table sql_eval ( eval_id int query_str varchar database varchar ); After some research, I used the following code, it works well except "delete", which didn't delete the row in sql_eval. I cannot figure out where is wrong? require 'rubygems' require 'active_record' require 'logger' ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Base.establish_connection(:adapter => "ibm_db", :username => "edwdq", :password => "edw%2dqr", :database => "EDWV2", :schema => "EDWDQ" ) class Eval < ActiveRecord::Base set_table_name "eval" set_primary_key :eval_id TYPE_MAP = { 1 => 'SqlEval' } class << self def find_sti_class(type) puts "#{type}" super(TYPE_MAP[type.to_i]) end def sti_name TYPE_MAP.invert[self.name] end end set_inheritance_column :eval_typ_id end class SqlEval < Eval has_one :details, :class_name=>'SqlEvalDetails', :primary_key=>:eval_id, :foreign_key=>:eval_id, :include=>true, :dependent=>:delete default_scope :conditions => { :eval_typ_id => 1 } end class SqlEvalDetails < ActiveRecord::Base belongs_to :sql_eval, :class_name=>'SqlEval', :conditions => { :eval_type_id => 1 } set_table_name "sql_eval" set_primary_key :eval_id end se = SqlEval.find(:last) require 'pp' pp se pp se.details # Eval.delete(se.eval_id) se.delete A: Sorry for messing the code. It is first time to post for me. Here is the code. require 'rubygems' require 'active_record' require 'logger' ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Base.establish_connection(:adapter => "ibm_db", :username => "edwdq", :password => "edw%2dqr", :database => "EDWV2", :schema => "EDWDQ" ) class Eval < ActiveRecord::Base set_table_name "eval" set_primary_key :eval_id TYPE_MAP = { 1 => 'SqlEval' } class << self def find_sti_class(type) puts "#{type}" super(TYPE_MAP[type.to_i]) end def sti_name TYPE_MAP.invert[self.name] end end set_inheritance_column :eval_typ_id end class SqlEval < Eval has_one :details, :class_name=>'SqlEvalDetails', :primary_key=>:eval_id, :foreign_key=>:eval_id, :include=>true, :dependent=>:delete default_scope :conditions => { :eval_typ_id => 1 } end class SqlEvalDetails < ActiveRecord::Base belongs_to :sql_eval, :class_name=>'SqlEval', :conditions => { :eval_type_id => 1 } set_table_name "sql_eval" set_primary_key :eval_id end se = SqlEval.find(:last) e = Eval.where(:eval_id => 26) require 'pp' pp se pp e pp se.details # Eval.delete(se.eval_id) se.delete
{ "language": "en", "url": "https://stackoverflow.com/questions/3919707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET RSS feed error in link tag in item node? Issue with Razor in Umbraco RSS Feed Having an issue with creating an rss feed against a blog in umbraco using razor. The code below works but as soon as I try and add any value into the link tag under the item node I get an xml error, below is the code. <rss version="2.0"> <channel> <title>@landing.uBlogsyRssTitle</title> <description>@landing.uBlogsyRssDescription</description> <copyright>@landing.uBlogsyRssCopyright</copyright> @*<image>@landing.uBlogsyRssImage</image>*@ <link>@[email protected]</link> <lastBuildDate>@lastPubDate.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</lastBuildDate> <pubDate>@lastPubDate.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</pubDate> @foreach (var p in posts) { <item> <title>@p.GetProperty("uBlogsyContentTitle").Value</title> <link></link> <author>@p.GetProperty("uBlogsyPostAuthor").Value</author> <description>@p.GetProperty("uBlogsyContentBody").Value.StripHtml().Trim()</description> <guid>@p.Url</guid> <pubDate>@p.GetProperty("uBlogsyPostDate").Value.FormatDateTime("ddd, dd MMMM yyyy HH:mm:ss")</pubDate> </item> } </channel> </rss> A: This is my answer to another post with the same problem solved: Since MVC4 Razor verifies that what you are trying to write is valid HTML. If you fail to do so, Razor fails. Your code tried to write incorrect HTML: If you look at the documentation of link tag in w3schools you can read the same thing expressed in different ways: * *"The element is an empty element, it contains attributes only." *"In HTML the tag has no end tag." What this mean is that link is a singleton tag, so you must write this tag as a self-closing tag, like this: <link atrib1='value1' attrib2='value2' /> So you can't do what you was trying to do: use an opening and a closing tag with contents inside. That's why Razor fails to generate this your <xml> doc. But there is one way you can deceive Razor: don't let it know that you're writing a tag, like so: @Html.Raw("<link>")--your link's [email protected]("</link>") Remember that Razor is for writing HTML so writing XML with it can become somewhat tricky.
{ "language": "en", "url": "https://stackoverflow.com/questions/12761288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple framebuffers and textures not working on intel drivers I'm writing an application using PyOpengl and PySide. My main machine is installed with ubuntu and an nvidia card (proprietary drivers), the premise is just to tell that the application is working properly in this setting. I'm testing this application on a machine with an intel hd 3000 and Ubuntu 12.10, the drivers are the default intel drivers. Everything is working so far except for the application of multiple post-processing filters. The process works like that: render the scene and output a color texture (texture0) using a framebuffer object (called fb0). render the first postprocessing effect by binding the textures produced in the previous step. The processed color output is saved in another texture (extratexture1) by using another framebuffer (fb1). render another postprocessing effect by using the new color texture (extratexture2 and fb2). render the result on the screen. What I obtain is a white screen (my background color perhaps). If I remove the last step and render the extratexture1, I obtain the correct result. If I remove the second step only and render the extratexture2 I obtain the correct result. Therefore the problem should not be in the texture initialization code. It's like that this driver doesn't support more than 2 framebuffers (+ default one) at a time. Or probably failing to reset some important state. Was anybody able to code a similar thing on an intel video card? I'm running out of ideas of what the problem can be. I add some example code to troubleshoot any error: Initialization of framebuffers and textures, at initialization time. The texture are regenerated at each resize. self.fb0, self.fb2, self.fb1 = glGenFramebuffers(3) # Creation of texture0 glDrawBuffers(1, np.array([GL_COLOR_ATTACHMENT0], dtype='uint32')) # Creation of extratexture1 # Creation of extratexture2 Creation of each texture: def create_color_texture(fb, width, height): # Simple wrapper for glGenTexture and glTexImage2D texture = Texture(GL_TEXTURE_2D, width, height, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE) # Set some parameters texture.set_parameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST) texture.set_parameter(GL_TEXTURE_MIN_FILTER, GL_LINEAR) glBindFramebuffer(GL_FRAMEBUFFER, fb) glViewport(0, 0, width, height) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.id, 0) return texture Code that draws the texture to screen: def render(self, fb, textures): # We need to render to a quad glBindFramebuffer(GL_FRAMEBUFFER, fb) glViewport(0, 0, self.widget.width(), self.widget.height()) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(self.quad_program) qd_id = glGetUniformLocation(self.quad_program, "rendered_texture") # Setting up the texture glActiveTexture(GL_TEXTURE0) textures['color'].bind() # Set our "rendered_texture" sampler to user Texture Unit 0 glUniform1i(qd_id, 0) # Set resolution glUniform2f(glGetUniformLocation(self.quad_program, 'resolution'), self.widget.width(), self.widget.height()) # Set gamma value glUniform1f(glGetUniformLocation(self.quad_program, 'gamma'), self.gamma) # Let's render a quad quad_data = np.array([-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0], dtype='float32') vboquad = vbo.VBO(quad_data) vboquad.bind() glVertexPointer(3, GL_FLOAT, 0, None) glEnableClientState(GL_VERTEX_ARRAY) # draw "count" points from the VBO glDrawArrays(GL_TRIANGLES, 0, 6) vboquad.unbind() glDisableClientState(GL_VERTEX_ARRAY)
{ "language": "en", "url": "https://stackoverflow.com/questions/16493878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby TCPSocket Server - Can I tell to what host a client was connecting? I have a ruby server based on TCPSocket (non-HTTP). I have 2 different domains, both pointing with an A-Record to my servers IP Address (the same one). So, there are clients connecting to one of those domains. Is it possible to tell which domain a client was connecting to? I saw that this is possible in other protocols, but I'm not sure if this is based on manually added headers or really extracted from the basic tcp/ip connection. E.g. in PHP there is $_SERVER["HTTP_HOST"] which shows to which domain a client was connecting. A: At the TCP socket level, the only things that are known are the source and destination IP addresses (and ports) of the connection. How the IP address was resolved via DNS is not possible to know at this layer. Even though HTTP works on top of TCP, HTTP servers have to look at the HTTP headers from the client to know which domain they are making a request to. (That's how the HTTP_HOST value gets filled in.) One possible solution is to configure your server to have an additional IP address. This can be by assigning an additional IP address to the NIC or adding an additional NIC. Then have each domain use a different IP address. Otherwise, this is not possible and you may want to consider your application protocol on top of TCP to convey this information.
{ "language": "en", "url": "https://stackoverflow.com/questions/21251145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NumPy linear equations I was wondering to check for an algorithm that would solve set of three linear equations in two variables which change in every equation adjacently for example * *a + b = 0 *a + c = 0 *b + c = 1 I am open to all suggestions A: Use the np.linalg.solve library: https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html import numpy as np a = np.array([[1,1,0], [1,0,1], [0,1,1]]) b = np.array([0,0,1]) x = np.linalg.solve(a, b) A: alternative to the answer import numpy as np A = np.array([[1, 1, 0], [1, 0, 1], [0, 1, 1]]) B = np.array([0, 0, 1]) X = np.linalg.inv(A).dot(B) print(X)
{ "language": "en", "url": "https://stackoverflow.com/questions/64364381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extract elements of lists in an RDD What I want to achieve I'm working with Spark and Scala. I have two Pair RDDs. rdd1 : RDD[(String, List[String])] rdd2 : RDD[(String, List[String])] Both RDDs are joined on their first value. val joinedRdd = rdd1.join(rdd2) So the resulting RDD is of type RDD[(String, (List[String], List[String]))]. I want to map this RDD and extract the elements of both lists, so that the resulting RDD contains just these elements of the two lists. Example rdd1 (id, List(a, b)) rdd2 (id, List(d, e, f)) wantedResult (a, b, d, e, f) Naive approach My naive approach would be to adress each element directly with (i), like below: val rdd = rdd1.join(rdd2) .map({ case (id, lists) => (lists._1(0), lists._1(1), lists._2(0), lists._2(2), lists._2(3)) }) /* results in RDD[(String, String, String, String, String)] */ Is there a way to get the elements of each list, without adressing each individually? Something like "lists._1.extractAll". Is there a way to use flatMap to achieve what I'm trying to achieve? A: You can simply concatenate the two lists with the ++ operator: val res: RDD[List[String]] = rdd1.join(rdd2) .map { case (_, (list1, list2)) => list1 ++ list2 } Probably a better approach that would avoid to carry List[String] around that may be very big would be to explode the RDD into smaller (key value) pairs, concatenate them and then do a groupByKey: val flatten1: RDD[(String, String)] = rdd1.flatMapValues(identity) val flatten2: RDD[(String, String)] = rdd2.flatMapValues(identity) val res: RDD[Iterable[String]] = (flatten1 ++ flatten2).groupByKey.values
{ "language": "en", "url": "https://stackoverflow.com/questions/40133201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete all text in a file between two strings without importing any modules Due to restrictions I can't use any import modules like re, sys or os etc. Anything that I have to import at the beginning is out. This has made my life hell. Here is what I've got so far: #I CANT USE ANY IMPORT MODULES DUE TO RESTRICTIONS ON THE MACHINE THIS RUNS ON :( # # These Are the Variables for our file path and the start and ending points of what I want to delete. #---------------------------------------------------------------------------------------------------- DelStart = "//StartBB" DelEnd = "//EndBB" FilePath = "C:\\Users\\kenne_000\\Desktop\\New folder\\test.sqf" #---------------------------------------------------------------------------------------------------- #Opens the FilePath in Read set this command to f f = open(FilePath).read() #Sets value of out to create file in Write mode called "Filepath".out Out = open(FilePath + '.out', 'w') #assigns fL as open FilePath and split it up line by line for indexing fL = f.split('/n') #Assings LN as index our file and find the lines DelStart and DelEnd LN = fL.index(DelStart,DelEnd) #This Gives an error #>>> LN = fL.index(DelStart,DelEnd) #Traceback (most recent call last): # File "<stdin>", line 1, in <module> #TypeError: slice indices must be integers or None or have an __index__ method #text is replacing everything between our start and endpoints with nothing "" # STILL NEED THIS SECTION NO CLUE HOW TO DO THIS #Writes our new file Minus our designated start and end points out.write(text) #Closes Our New File out.close() #Ends Script Script.close() I was able to create a script that wrote all of the text and inserted the markers, which are individual for each set of text that gets inserted, but I no longer have any clue what to do when it comes to removing the section between the markers. A: While the code in your self-answer looks like it ought to work, it's not particularly elegant: * *You should really be using a with block to work with files. *Your variable line is misnamed: it doesn't contain a line at all, but the entire contents of your input file. *Your script reads in the entire file at once, which may be problematic for large files in terms of memory use. Here's an alternative: def excise(filename, start, end): with open(filename) as infile, open(filename + ".out", "w") as outfile: for line in infile: if line.strip() == start: break outfile.write(line) for line in infile: if line.strip() == end: break for line in infile: outfile.write(line) This function uses with open(...) (scroll down to the paragraph starting "It is good practice to use the with keyword ...") to ensure that files will be properly closed even if you hit an error of some kind, as well as reading and writing one line at a time to conserve memory. If you have a file example.txt with the following content: one two three //StartBB four five six //EndBB seven eight nine ... then calling excise() as follows ... excise("example.txt", "//StartBB", "//EndBB") ... will do what you want: example.txt.out one two three seven eight nine A: CREDITS FOR THIS ANSWER GOES TO lazy1 and his comment solution: fL is a list of lines. and fL.index will fine a line not part of it. Do you need to delete for every line or for the whole file? In any case, use string index to find start and end then slice away. Something like: i = line.find(DelStart) j = line.find(DelEnd) print line[:i] + line[j+len(DelEnd):] # These Are the Variables for our file path and the start and ending points of what I want to delete. #---------------------------------------------------------------------------------------------------- DelStart = "//StartBB" #Replace This With Proper Start Que DelEnd = "//EndBB" #Replace this with the proper End Que FilePath = "FILEPATH GOES HERE" #---------------------------------------------------------------------------------------------------- #Sets Line to open our filepath and read it line = open(FilePath).read() #i finds our start place j finds our ending place i = line.find(DelStart) j = line.find(DelEnd) #sets text as finding start and end and deleting them + everything inbetween text = line[:i] + line[j+len(DelEnd):] #Creates our out file and writes it with our filter removed out = open(FilePath + '.out', 'w') out.write(text) #Closes Our New File out.close() #Ends Script Script.close() A: This uses only built-in string functions: string = "This is the string" stringA = "This" stringB = " string" stringC = stringA + stringB stringD = stringC.replace(string, stringC) A: A rewrite of the important part of @KennethDWhite 's answer, as a function. I would simply have posted it as a comment to his answer, but that would not format correctly. # ToDo: this also deletes the delimiters. Perhaps add a parameeter to indicuate # whether to do so,or just to delete the text between them? def DeleteStringBetween(string, startDelimiter, endDelimiter): startPos = string.find(startDelimiter) endPos = string.find(endDelimiter) # If either delimiter was not found, return the string unchanged. if (startPos == -1) or (endPos == -1): return string return string[:startPos] + string[endPos + len(endDelimiter):]
{ "language": "en", "url": "https://stackoverflow.com/questions/28440722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Image fill is not working properly This is my html code <div class="feature-image"> <a class="featured_image_link" href="#"> <img src="1.jpg"> </a> </div> My image 1.jpg size is 150px x 150px and i have mentioned in the css as .feature-image{ width:150px; height:150px; display:block; position:relative; overflow:hidden; } .feature-image img{ position:absolute; top:-50; left:0; width:100%; } I know that when i give different image size (for eg: 300x200 or 600x350 etc) the image will fill inside that 150x150 and not stretches. But actually its not working properly. Please help whether there is any mistake in this code? A: Ok. Let me explain how this work. First things first. Your CSS has a bug. top:-50; This wont do anything. It has to be something like top:-50px; But my question is why do you want negative margins? it will only hide you image by 50 pixels on the top side. Ok, now coming to the real issue. You say you have no problems when your Image is 150X150 pixels. Thats because the parent <div> is 150x150. But if you have a different image size like 300x200 you have a problem. This happens because in your CSS you have only mentioned width: 100% for the image.From here on its plain math. The width=300 & height =200 Since you have mentioned width:100% the image automatically gets adjusted to the new width 300(original width)/150(new width)=2 So taking the same factor of 2 200(original height)/2=100(new height) Hence you rendered image will have height of 100px. if you want the rendered image to have same height of div just add this line to img CSS height: 100%; Working fiddle A: from the code you have pasted, it's working properly. Are you able to link to the site where this is live and not working? Cache issue? See jsfiddle: http://jsfiddle.net/FNQZn/ .feature-image { width:150px; height:150px; display:block; position:relative; overflow:hidden; } .feature-image img { position:absolute; top:-50; left:0; width:100%; }
{ "language": "en", "url": "https://stackoverflow.com/questions/18396068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: mongodb query different array have different condition I have the following datas. [{ "_id" : ObjectId("abc123"), "device_id": "A001", "A_status": "VALID", "B_status": "VALID" }, { "_id" : ObjectId("abc223"), "device_id": "A003", "A_status": "EXPIRED", "B_status": "VALID" }, { "_id" : ObjectId("abc323"), "device_id": "B001", "A_status": "EXPIRED", "B_status": "VALID" }, { "_id" : ObjectId("abc423"), "device_id": "B002", "A_status": "VALID", "B_status": "EXPIRED" },] I have two different device_id list: a_list = ["A001", "A003", ...] b_list = ["B001", "B002", ...] a_list need match A_status is VALID, b_list need match A_status is VALID. I want to find deive_id in a_list and A_status is VALID, deive_id in b_list and B_status is VALID, so I will get following correct data { "_id" : ObjectId("abc123"), "device_id": "A001", "A_status": "VALID", "B_status": "VALID" }, { "_id" : ObjectId("abc323"), "device_id": "B001", "A_status": "EXPIRED", "B_status": "VALID" } How do I execute once query and get the answer? Or have to separate queries for different conditions? A: You can use Regex to get different data from MongoDB. To get model AXXX and A_status is VALID you can use this query. { device_model: { $regex :/^A/}, A_status: 'VALID' } To get BXXX and B_status is VALID you can use: { device_model: { $regex :/^B/}, B_status: 'VALID' } It may be useful to take a look into mongo regex documentation. A: Use $or db.collection.find({ $or: [ { A_status: "VALID", device_model: { $in: [ "A001", "A003" ] } }, { B_status: "VALID", device_model: { $in: [ "B001", "B002" ] } } ] }) mongoplayground
{ "language": "en", "url": "https://stackoverflow.com/questions/71964668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why DOM changes are not visible in the function that changes DOM? I have the JS/jQuery code: function swapElements(parent, i) { var a = parent.eq(i); var b = parent.eq(i + 1); var atemp = a.clone(); var btemp = b.clone(); a.replaceWith(btemp); b.replaceWith(atemp); debugOutput(); // instead of some actions } swapElements(parent, i); But the debugOutput function sees old unchanged version DOM. I have tried to use MutationObserver and setTimeout to call debugOutput but got nothing. However if I manually check the DOM from another function: $("button").click(function () { debugOutput(); }); then debugOutput see new changed DOM immediately. Why this is happening? How can I work with changed DOM directly after replaceWith in swapElements? Thank you for any help.
{ "language": "en", "url": "https://stackoverflow.com/questions/37917129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recursive function that return result from 'if' statement instead of 'else' statement I'm pretty new in Python and I'm trying to write a simple recursive function: def bugged_recursion(inp_value,list_index=0): '''Define a recursive function that tag lists according to one parameter. ''' #check if a criterion is true at position 0 in the list if list_index == 0: if inp_value[list_index] == 'valid': status = 'valid inp_value' #if the criterion is false call the function at the next index else: status = 'invalid inp' list_index +=1 bugged_recursion(inp_value,list_index=list_index) #check if a criterion is true at position 1 in the list else: if inp_value[list_index] == 'valid': status = 'index {} is a valid inp_value'.format(list_index) else: status = 'index is never a valid inp_value' print(status) #return the input and its status return (inp_value,status) if __name__ == '__main__': inp_value = ['invalid','invalid'] bugged_recursion(inp_value) I don't understand why this function return the status from the if statement, instead of returning the status contained in the last else statement. For me, the strangest is that it prints the right status at some point but won't return it. I'm unable to understand why... I'm really curious about how I could perform this task using a recursive function. A: Wow wow, how tortured this is. def bugged_recursion(inp_value, list_index=0): # i don't get why you compare list_index here if list_index == 0: # you'll get an IndexError if list_index > len(inp_value) if inp_value[list_index] == 'valid': status = 'valid inp_value' else: status = 'invalid inp' # there is only one place where you increment list_index # i suppose there is something wrong here list_index +=1 # you forgot to return here return bugged_recursion(inp_value, list_index=list_index) else: if inp_value[list_index] == 'valid': status = 'index {} is a valid inp_value'.format(list_index) else: status = 'index is never a valid inp_value' return (inp_value,status) That aside, people usually tend to avoid recursion as much as possible (for example on Dive into Python). Does this cover your needs? def no_recursion(inp_value): for i, val in enumerate(inp_value): # you probably have a good reason to test the index if i == 0: if val == 'valid': yield 'valid inp_value: %s' % val else: yield 'invalid inp: %s' % val else: yield 'index %s is %s valid inp_value' % ( i, 'a' if val == 'valid' else 'never' ) print tuple(no_recursion(inp_value)) Gives: ('invalid inp: invalid', 'index 1 is never valid inp_value')
{ "language": "en", "url": "https://stackoverflow.com/questions/31787169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Align x-axis tick locations of additional subplot with x-axis tick locations of FacetGrid object I want to add a second x-axis to my FacetGrid object. I managed to create a second x-axis by adding a second subplot to my figure that is below the first axis following the suggestions of this post. The ticks of my second x-axis should match with the horizontal locations of the ticks of the upper x-axis. However, in contrast to the post mentioned before, when using seaborn.catplot, the x-axis ticks of the FacetGrid figure do not exactly match with the beginning and end of the x-axis. Instead, seaborn.catplot 'compresses' the x-axis ticks, so that the first and last tick do not align horizontally with the start and end of the x-axis. As a result, one cannot simply set the x-axis ticks of the added subplot using get_xticks and set_xticks. Here's a code example: import numpy as np import pandas as pd import seaborn as sns # simulate data rng = np.random.RandomState(42) measure_names = np.tile(np.repeat(['Train BAC','Test BAC'],10),4) model_numbers = np.repeat([0,1,2,3],20) measure_values = np.concatenate((rng.uniform(low=0.6,high=1,size=40), rng.uniform(low=0.5,high=0.8,size=40) )) folds=np.tile([1,2,3,4,5,6,7,8,9,10],8) plot_df = pd.DataFrame({'model_number':model_numbers, 'measure_name':measure_names, 'measure_value':measure_values, 'outer_fold':folds}) # plot data as pointplot g = sns.catplot(x='model_number', y='measure_value', hue='measure_name', kind='point', seed=rng, data=plot_df) ax2 = g.axes[0,0].twiny() # Move twinned axis ticks and label from top to bottom ax2.xaxis.set_ticks_position("bottom") ax2.xaxis.set_label_position("bottom") # Offset the twin axis below the host ax2.spines["bottom"].set_position(("axes",-0.30)) # set title ax2.set_xlabel('Title of the second axis') # get ticks of FacetGrid ax xtickslocs = g.axes[0,0].get_xticks() # set ticks of ax2 to first ax ax2.set_xticks(xtickslocs) which produces: A: Simply match the limits of the x-axis ax2.set_xlim(g.axes[0,0].get_xlim())
{ "language": "en", "url": "https://stackoverflow.com/questions/60789432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to setup and use Android Emulator (shipped in Android Studio) in a corporate environment (no internet access or admin rights)? I'm trying to use Emulator on a PC which has no internet connection and I'm not local admin. I've downloaded Android Studio (no install zip) on another PC and extracted contents, but it says "No SDK folder found". Then I manually downloaded sdk tools zip and tried to update SDK folder with no luck. It says this folder does not include Android SDK. Then I got my local admin guy to install Studio on the PC. But when I start Studio, I get the same "No SDK folder" error. I guess this is because setup installed SDK folder under local admin AppData folder. I cannot see his folder and couldn't contact him so far. What should I do? A: I got the admin guy to copy SDK folder from his directory under C:\Users\adminguy\AppData to somewhere I can read. Now it works ok.
{ "language": "en", "url": "https://stackoverflow.com/questions/47814166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why calling a function from shorthand function pointers array initialization doesn't compile? I have the following code in my project: printf("Please select one of the tests: "); int n; scanf("%d", &n); (void (* [])()) {test1, test2, test3, test4}[n - 1](); For me, this code compiles and works as indented. But my professor said that this doesn't compile for her. I write code compliant with the C23 standard and my compiler is Apple Clang v13.0.0. But about my professor, all I know is that she uses the MSVC compiler; I have no information on either the compiler version or the standard she marks the code with. I tried changing the C standard to C99 and it still worked, so I think this has to be a compiler issue. I don't have a Windows machine to play around with MSVC and test whether the problem is the anonymous array initialization, the subscript operator immediately after it, the call operator after the entire thing, or something else entirely. Now, of course I know that I can declare an array of function pointers first, and then assign every element, or just use a switch for this purpose. I also know that this is a kind of "clever code" that may not be welcome in actual projects maintained by more people, but this is my code, created for educational purposes only. Also, my professor likes this kind of "clever tricks" as extreme examples of what can you do with the language. What I do like to know is what could be the reason this code does not compile with MSVC. Is that syntax some compiler-specific language extension or is it just Microsoft which, as always, is not keeping up with support for all language features? A: Your teacher is probably compiling your code as C++. With dummy functions added, if this code is placed in a .c file and compiled with MSVC 2015, it compiles fine. If the file has a .cpp extension, it generates the following errors: x1.cpp(13): error C3260: ')': skipping unexpected token(s) before lambda body x1.cpp(13): error C2143: syntax error: missing ';' before '}' x1.cpp(13): warning C4550: expression evaluates to a function which is missing an argument list x1.cpp(13): error C2676: binary '[': 'main::<lambda_8caaf9f5b122025ad6cda2ca258a66a7>' does not define this operator or a conversion to a type acceptable to the predefined operator x1.cpp(13): error C2143: syntax error: missing ')' before ';' x1.cpp(13): error C2059: syntax error: ';' So it thinks your compound literal is a lambda function. Compound literals are a C-only construct, so unless your C++ compiler supports them as an extension it won't work. Have your teacher compile your code as C by putting it in a file with a .c extension. Alternately, don't use a compound literal. Create the array first, then index it and call the function. void (*f[])() = {test1, test2, test3, test4}; f[n - 1]();
{ "language": "en", "url": "https://stackoverflow.com/questions/72166043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Has there different JDKs or JVMs on each Java platforms? I am confused about java platforms.From the page Differences between Java EE and Java SE , java has four platforms. Has there any special things between them ? Are they use different JDKs or JREs ? For clear my question , when I download JDK , I think I can create not only java desktop applications (with swing or javafx) but also web applications.If so ,why java says it has different platforms. If yes , it should has different jdk or jvm for each specific platform. As I think , different platforms mean I need to download different version of JDK. For instance , I need to download JDK for JavaEE platform which contains API for JavaEE. A: It depends (like often). The JDK is a development kit for Java SE including FX. So you can develop desktop applications but also web applications depending on the type of integration you prefer. The Java EE SDK contains also the Glassfish server, examples and tutorials but they are not really needed. The ME is a special minimized versions for embedded device development including special tools for that. I am developing web application for years with a Java SE JDK only. As I normally use Spring Boot with an embedded container or install a Tomcat on demand, this works perfectly and the Java EE SDK is not needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/37687321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to adjust the y-axis of bar plot in R using only the barplot function Using this example: x<-mtcars; barplot(x$mpg); you get a graph that is a lot of barplots from (0 - 30). My question is how can you adjust it so that the y axis is (10-30) with a split at the bottom indicating that there was data below the cut off? Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible? A: This is not recommended. It is generally considered bad practice to chop off the bottoms of bars. However, if you look at ?barplot, it has a ylim argument which can be combined with xpd = FALSE (which turns on "clipping") to chop off the bottom of the bars. barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE) Also note that you should be careful here. I followed your question and used 0 and 30 as the y-bounds, but the maximum mpg is 33.9, so I also clipped the top of the 4 bars that have values > 30. The only way I know of to make a "split" in an axis is using plotrix. So, based on Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible? the answer is "no, this is not possible" in the sense that I think you mean. plotrix certainly does it, and it uses base R functions, so you could do it however they do it, but then you might as well use plotrix. You can plot on top of your barplot, perhaps a horizontal dashed line (like below) could help indicate that you're breaking the commonly accepted rules of what barplots should be: abline(h = 10.2, col = "white", lwd = 2, lty = 2) The resulting image is below: Edit: You could use segments to spoof an axis break, something like this: barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE) xbase = -1.5 xoff = 0.5 ybase = c(10.3, 10.7) yoff = 0 segments(x0 = xbase - xoff, x1 = xbase + xoff, y0 = ybase-yoff, y1 = ybase + yoff, xpd = T, lwd = 2) abline(h = mean(ybase), lwd = 2, lty = 2, col = "white") As-is, this is pretty fragile, the xbase was adjusted by hand as it will depend on the range of your data. You could switch the barplot to xaxs = "i" and set xbase = 0 for more predictability, but why not just use plotrix which has already done all this work for you?! ggplot In comments you said you don't like the look of ggplot. This is easily customized, e.g.: library(ggplot2) ggplot(x, aes(y = mpg, x = id)) + geom_bar(stat = "identity", color = "black", fill = "gray80", width = 0.8) + theme_classic()
{ "language": "en", "url": "https://stackoverflow.com/questions/30222178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: enter line to an object Hello in R how could I write a function which takes as an input a number at which aline should be entered into an existing object matrix(rnorm(9),ncol=3,nrow=5) x<-c(1,7,8) Each vector should now be entered into the matrix into the matrix at row 3 (so it should be the new co row 3 . The other rows would just be a pushed so the old row 3 is row 4 then A: Here's a function I wrote for that a while back. I've been using it. #Christopher Barry, 28/01/2015 insertRows <- function(DF, mtx, row){ if(is.vector(mtx)){ mtx <- matrix(mtx, 1, length(mtx), byrow=T) } nrow0 <- nrow(DF) nrows <- nrow(mtx) ncols <- ncol(DF) #should be same as for mtx if(is.matrix(DF)){DF <- rbind(DF, matrix(0, nrows, ncols))} if(nrow0 >= row){ DF[seq(row+nrows,nrow0+nrows),] <- DF[seq(row,nrow0),] DF[row:(row+nrows-1),] <- mtx }else{ DF[seq(nrow0+1,nrow0+nrows),] <- mtx } return (DF) } Edited to work for matrices and data frames. A: One way of doing this can be : aa<- matrix(rnorm(9),ncol=3,nrow=5) x<-c(1,7,8) rbind(aa[1:2,],x,aa[3:5,]) A similar solution ot this, actually: R: Insert a vector as a row in data.frame
{ "language": "en", "url": "https://stackoverflow.com/questions/31563040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Checkbox form validator Angularjs2 I need to validate something like this. In the following form, SignUp button should be enabled only if user checked the checkbox. If user uncheck the checkbox the button should get disabled. Following way enabled the button when user check the checkbox for the first time. But then if user uncheck the checkbox again the button remain enabled which actually should be disabled. All help appreciated. Thanks! <form id="login-form" action="" method="post" role="form" #loginForm='ngForm'> <div class="form-group"> <input type="text" required maxlength="12" minlength="12" required [(ngModel)]="user.ssn" name="ssn" #name="ngModel" tabindex="1" class="form-control input-box" placeholder="" value="" autocomplete="off"> </div> <div class="form-group center"> <input type="checkbox" id="chkTerm" ngModel name="cb" #cb="ngModel" required /> <label for="chkTerm"></label> </div> <div class="form-group"> <div class="center"> <button class="btn" (click)='clicked()' class="btn waves-effect waves-light" [disabled]="!loginForm.form.valid" [ngStyle]="{'background-color': '#57e5a1'}" type="submit" name="action">SignUp</button> </div> </div> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/40608901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SELECT query with ResultSet arguments in JAVA The server code of my Oracle database contains two files (classes) namely: Main.javaand DBManager.java. DBManager.java contains SQLPRocessing and SQLProcess methods (functions) that perform executeUpdate and executeQuery operations with the query statement, respectively. The SQL queries for dumping and fetching the data are written at the Main.java class. My database contains two tables T1and T2. My code has two queries for inserting the data as: public void SQLProcessing(String ID, String X, String Y, String XE, String YE){ db.SQLProcess("INSERT INTO T1 VALUES("+Double.parseDouble(ID)+ "," +Double.parseDouble(X)+ "," +Double.parseDouble(Y)+")"); db.SQLProcessing("INSERT INTO T2 VALUES("+Double.parseDouble(ID)+ "," +Double.parseDouble(XE)+ "," +Double.parseDouble(YE)+")"); } Similarly, for getting the data back from the database, I use single SELECT query as: public ResultSet SQLProcess(String msg1, String msg2, String msg3, String msg4, String msg5){ ResultSet rs = db.SQLProcess("SELECT * FROM T1, T2 WHERE T1.ID = T2.ID"); return rs; } While executing the code, I get an error: Exception in thread "Thread-1" java.lang.NullPointerException at Main.sendTo(Main.java:132) at Main$ServerReceiver.run(Main.java:79) The line 132 of Main.java contains while(rs.next()) and line 79 contains sendTo(socket.getInetAddress()); . However, when I see the database, data is sent and stored in the database. So, I think the problem is with the SELECT query. I tried many possible SELECT queries from different threads, I could not solve the problem. Is my guess correct? Could anybody provide the real SELECT query for my case? Or is the error is triggered from another source? The problem is with the cursor. It is null and I added an if statement as: if(rs!=null) { while(rs.next()){//code} Then it does not generate any error. However, the client device does not get any data from the server. How can I fix it? A: Have you checked if (T1.ID = T2.ID) there are IDs which equal each other? Otherwise your queryresponse is empty because your where case declines a result. Sometimes there is a extra column at first place. So maybe your data is not inserted correctly? A: Using Double or Float for id purposes is an issue here, I suppose, as precision is always in issue. Simply, when you save a floating point number, like 7.2 it may be represented as 7.199999 or 7.199998 or 7.2000001 etc, thus ids won't be equal. For id I suggest using integer or something like UUID.
{ "language": "en", "url": "https://stackoverflow.com/questions/46428162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I have a JTextArea that needs bottom margin I have a JTextArea with margins that work for the top, left, and right but not for the bottom. When the caret gets to the bottom, it just keeps going. Here is my code: frame = new JFrame(""); Container contentPane = frame.getContentPane(); contentPane.add(textArea); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); textArea.setLineWrap(true); textArea.setMargin(new Insets(10, 50, 50, 560));
{ "language": "en", "url": "https://stackoverflow.com/questions/51294487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to edit Sublime Text build settings? I want to enable -std=gnu++11 in Sublime Text 3's C++ Single File build on Ubuntu 12.04. I have already upgraded the tool chain to the latest g++ and do not want to see the following error on every build: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options. I browsed to /home/myuname/.config/sublime-text-3 but cannot find any file to edit. How can I edit the build settings? A: edited My original answer works, but there's a much better way of doing this, by creating your own build system. This use case is exactly why the feature is there. Go to Tools → Build System → New Build System… (all the way at the bottom) and enter the contents below. Save as C++ 11 Single File.sublime-build, and it will now be accessible in the build system menu. Select it, hit CtrlB to build, and then hit CtrlShiftB to run the resulting program. Or you can use a Build and Run option and call it by hitting CtrlB, then selecting that option. { "cmd": ["g++", "-std=gnu++11", "${file}", "-o", "${file_path}/${file_base_name}"], "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${file_path}", "selector": "source.c, source.c++", "variants": [ { "name": "Run", "cmd": ["${file_path}/${file_base_name}"] }, { "name": "Build and Run", "cmd": ["g++ -std=gnu++11 ${file} -o ${file_path}/${file_base_name} && ${file_path}/${file_base_name}"], "shell": true } ] } If you need to edit it in the future, the file is in the User folder of Packages. The Packages directory is the one opened when selecting Preferences → Browse Packages…: * *Linux: ~/.config/sublime-text-3/Packages or ~/.config/sublime-text/Packages *OS X: ~/Library/Application Support/Sublime Text 3/Packages or ~/Library/Application Support/Sublime Text/Packages *Windows Regular Install: C:\Users\YourUserName\AppData\Roaming\Sublime Text 3\Packages or C:\Users\YourUserName\AppData\Roaming\Sublime Text\Packages *Windows Portable Install: InstallationFolder\Sublime Text 3\Data\Packages InstallationFolder\Sublime Text\Data\Packages The exact path depends on version and whether or not you upgraded from Sublime Text 3. A: In my case, the problem is that in Windows, ST3 was calling py instead of python which was the default. If you change python in "cmd": ["python", "-u", "$file"] for your local python interpreter, the new system should work. { "cmd": ["python3", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "env": {"PYTHONIOENCODING": "utf-8"}, "windows": { "cmd": ["python", "-u", "$file"], }, "variants": [ { "name": "Syntax Check", "cmd": ["python3", "-m", "py_compile", "$file"], "windows": { "cmd": ["py", "-m", "py_compile", "$file"], } } ] }
{ "language": "en", "url": "https://stackoverflow.com/questions/23789410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Regex match of a string with numbers and uppercase letters failing I am trying to match lasko17A565 in the list below but the regex fails?specifically I am trying to look for the string present in variable train in the front followed by any combination of numbers and uppercase letters, can anyone provide guidance why it fails? import re xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko'] train = 'lasko' found_new_SDK = False for SDK in xbsfindupdates_output_list: if re.match(r'%s[0-9A-Z]'%train,SDK): found_new_SDK = True print found_new_SDK CURRENT OUTPUT:- False EXPECTED OUTPUT:- True A: I suspect that the error is in how you are building the regex pattern to be used here. I suggest concatenating the input list together by space to form a single input string, and then using the following regex pattern with re.findall: \b(lasko[A-Z0-9]+)\b The word boundaries are appropriate here, because the train value should be bounded on the left by a tab, and on the right by a space. xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko'] train = 'lasko' inp = ' '.join(xbsfindupdates_output_list) pattern = r'\b(' + train + r'[A-Z0-9]+)\b' matches = re.findall(pattern, inp) print(matches) This prints: ['lasko17A565'] Edit: If you just want to find out if there is a match, then try: xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko'] train = 'lasko' inp = ' '.join(xbsfindupdates_output_list) pattern = r'\b' + train + r'[A-Z0-9]+\b' if re.search(pattern, inp): print("MATCH") else: print("NO MATCH") A: Try this: for SDK in xbsfindupdates_output_list: print(SDK,re.search("%s[0-9A-Z]+"%train,SDK)) if re.match("%s[0-9A-Z]+"%train,SDK.strip()): print("FOUND") found_new_SDK = True print (found_new_SDK) re.match is returning True iff both strings are same. Try re.search, which would search in string the required pattern A: Match objects are always true, and None is returned if there is no match. Just test for trueness. So instead of match, i used re.search here: xbsfindupdates_output_list = ['project-707.1.5 was found in the following updates of lasko:', '\tlasko17A565', '\tNewestlasko', '\tBuiltlasko'] train = 'lasko' found_new_SDK = False for SDK in xbsfindupdates_output_list: if re.search(r'\b' + train + r'[\d\S]+', SDK): found_new_SDK = True print found_new_SDK O/p: True
{ "language": "en", "url": "https://stackoverflow.com/questions/57471809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NodeGit how to get last commit id of another branch? I have two branches checked out of my system Master and Dev. My Working directory is Master from Master I want to push/merge file to dev after knowing the difference. For say in Master I am working abc.txt file and I want to check the difference between the file present in dev with master. How can I do it? Getting this error error while pushing == Error: no reference found for shorthand 'dev' (node:93479) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: no reference found for shorthand 'dev' Code differenceCommit(fileName,branchName) { return new Promise(function (resolve,reject) { let repo, changes; open("./master") .then(function (repoResult) { repo = repoResult; return repo; }) .then(function (commitId) { return repo.getBranchCommit("dev"); }) ///Difference Before Push .then(function (commit) { return commit.getDiffWithOptions("dev"); }) .then(function (diffList) { console.log("************************"); }); } A: Add origin/ to the name of the branch: differenceCommit(fileName,branchName) { return new Promise(function (resolve,reject) { let repo, changes; open("./master") .then(function (repoResult) { repo = repoResult; return repo; }) .then(function (commitId) { return repo.getBranchCommit("origin/dev"); }) ///Difference Before Push .then(function (commit) { return commit.getDiffWithOptions("origin/dev"); }) .then(function (diffList) { console.log("************************"); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/45712721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Understanding the usecase of multiple recursive calls I was trying to solve a problem to get all the possible valid combinations of parenthesis given an integer. Eg. input: n = 2, output: (()), ()() Clearly as n increases, the current output builds on the output of the previous n. So it was easy to come up with a recursive by taking the previous result and adding to it to get the current result: HashSet<String> getCombinations(int n) { HashSet<String> result = new HashSet<String>(); if (n <= 0) return null; if (n == 1) { result.add("()"); return result; } for (String str: getCombinations(n - 1)) { for (int i = 0; i < str.length(); i++) { result.add(new StringBuffer(str).insert(i, "()").toString()); } } return result; } Though obviously the downside of the above code is the repetition of the same result values which are produced but not stored. So I looked online for a better solution (as I could not think of it), and found this: ArrayList<String> result = new ArrayList<>(); void getCombinations(int index, int nLeft, int nRight, String str) { if (nLeft < 0 || nRight < 0 || nLeft > nRight) return; if (nLeft == 0 && nRight == 0) { result.add(str); return; } getCombinations(index + 1, nLeft - 1, nRight, new StringBuffer(str).insert(index, "(").toString()); getCombinations(index + 1, nLeft, nRight - 1, new StringBuffer(str).insert(index, ")").toString()); } I understand how this solution works and why its better than the first. But even now I cannot imagine looking at the first solution and then coming up with second solution. How can I intuitively understand so as to when to use multiple recursive calls? In other words, after achieving solution 1, how can I come to think that I would probably be better off with multiple recursive calls? My question is not specific to the above problem, but the type of problems in general. A: You could look at this problem as permutations of 1 and -1, which while being summed together, the running sum (temp value while adding up numbers left-to-right) must not become less than 0, or in case of parenthesis, must not use more right-parenthesis than left ones. So: If n=1, then you can only do 1+(-1). If n=2, then can do 1+(-1)+1+(-1) or 1+1+(-1)+(-1). So, as you create these permutations, you see you can only use only one of the two options - either 1 or -1 - in every recursive call, and by keeping track of what has been used with nLeft and nRight you can have program know when to stop.
{ "language": "en", "url": "https://stackoverflow.com/questions/49601132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Complex Syntax Error php html I have a problem with syntax error. trying to upload image from directory into my list in html but it keeps saying things like: Parse error: syntax error, unexpected '"', expecting ',' or ';' in D:\xampp\htdocs\Waldi\index.php on line 243 <?php $dir="img/"; if($opendir=opendir($dir)){ while(($file=readdir($opendir))!==FALSE){ if($file!="." && $file!="..") echo '<li class="col-lg-4 col-md-4 col-sm-3 col-xs-4 col-xxs-12"> <img class="img-responsive" src='"$dir/$file"'> </li>'; } } ?> A: It's a quote question. Try This $dir = "img/"; if ($opendir = opendir($dir) ) { while ( ($file = readdir($opendir) ) !== FALSE) { if ($file != "." && $file != "..") { echo '<li class="col-lg-4 col-md-4 col-sm-3 col-xs-4 col-xxs-12"> <img class="img-responsive" src="'.$dir.'/'.$file.'"> </li>'; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/39149675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Spring AOP pointcut is not triggered as expected I have two methods with diferent pointcuts, one is executed, the other no, and I can`t see why. I have many methds and classes defined on the packages that you can see below. I am using spring-boot in my project. Here is the code: @Aspect @Component public class LoggingAspect { @AfterReturning(pointcut = "execution(* com.arlr.common.business.service..*(..))", returning = "result") public void afterReturningCommon(JoinPoint joinPoint, Object result) { doSomething(); } @AfterReturning(pointcut = "execution(* com.arlr.godzilla.service..*(..))", returning = "result") public void afterReturningMyProject(JoinPoint joinPoint, Object result) { doSomething(); } } A: Observing the methods on the other scanned classes, they are protected methdos, so I change it to public to solve the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/34231882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do you create SDL2 Visual Studio 2015 or 2017 Solution For Windows and Android? Visual Studio 2015 has integrated Android Emulator support. They even have a pre-made template to set up Windows Phone, Android, and iOS targets. It seems like there should be some way of setting up SDL 2.0 in the same solution to easily toggle between Android and Windows targets. A valid answer to this question will simply be a set of steps to set up the targets for an example SDL2 program that compiles and creates a simple OpenGL/ES context rotating cube or similar which will either create a window and run as a windows .exe or execute in the android emulator depending on the target. Please include all steps in the body of your answer in a numbered bullet list so that it is a complete stand-alone answer. A: For android specific settings. (Setting up makefiles, the AndroidManifest.xml, etc.) refer to SDL2/docs/readme.android and general "command line android help" on the internet. Setting up the VS2015 solution generally goes as follows: * *Create new folder project *Put game source in project/src *Create shared items project in project/ *Create an android makefile project into project/android *Create an android basic application(ANT) project into project/android *Copy the contents of SDL2/android-proj to project/android *In the solution explorer check "show all files" and "include in project" all files from SDL2/android-proj except jni to the basic application project. *In the references of the basic app project add the makefile project. *In the references of the makefile project add the shared items project. *Edit project/android/jni/src/Android.mk to compile your files in projects/src *After building the makefile project, add its resulting .so files from project/android/libs/ to the basic app project. *Create other project like usual except instead of including source, just include shared items project in references. Here is where you can find the shared items project:
{ "language": "en", "url": "https://stackoverflow.com/questions/42149447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get content-type in feathers hook Simple question which I havn't figured out yet. Is there a way to get the content type of a request in a feathers hook / context? I read about potentially using express middleware, but I want to still make use of the service, I dont want to replace it with middleware as from what I understand then I cannot make use of a feathers service afterwards. Any hints/tips/suggestions are welcome. Regards, Emir A: As mentioned in the FAQ it is possible to get access to the request object but it should be avoided because transport specific processing should be kept outside of services (for example, when using Feathers via websockets, there won't be a content type at all). Service call parameters (params) for HTTP calls can be set by using a custom Express middleware so you can add a params.contentType to every service call like this (or use it as a service specific middleware): app.use(function(req, res, next) { req.feathers.contentType = req.headers['content-type']; next(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/51441208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django server reporting "Forbidden (CSRF token missing or incorrect.)" despite sending token correctly? I am trying to send a JSON POST request to my Django server. It reports this error: Forbidden (CSRF token missing or incorrect.): In my Django template, options.html, I say this: <script>const incomingToken = "{{ csrf_token }}";</script> And this: <input type="hidden" name="csrf-token" id="csrf-token" value="{{ csrf_token }}" /> Then in my JavaScript file that runs in the client I say: const serverUrl = "http://127.0.0.1:8000/" const headers = new Headers({ 'Accept': 'application/json', // 'X-CSRFToken': getCookie("CSRF-TOKEN") "X-CSRFToken": document.getElementById("csrf-token").value }) fetch(serverUrl, { method: "POST", headers: { headers }, mode: "same-origin", body: JSON.stringify(editorState.expirationDate, editorState.contracts, editorState.theta) // FIXME: server goes "Forbidden (CSRF token missing or incorrect.)" and 403's }).then(response => { console.log(incomingToken) console.log(document.getElementById("csrf-token").value) console.log(response) }).catch(err => { console.log(err) }); Both incomingToken and document.getElementById("csrf-token").value report the same value. So I know I'm getting the correct string for the CSRF token. How can this be? What am I doing wrong? For reference, here is what I see in another thread on the subject: const csrfToken = getCookie('CSRF-TOKEN'); const headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded', 'X-CSRF-TOKEN': csrfToken // I substitute "csrfToken" with my code's "incomingToken" value }); return this.fetcher(url, { method: 'POST', headers, credentials: 'include', body: JSON.stringify({ email: '[email protected]', password: 'password' }) }); Instead of running a function to retrieve the value from a cookie, I simply insert the value Django embeds using {{ csrf_token }}. I also tried pasting the code from the top answer in this thread, including function getCookie(name). Nothing. Client still says POST http://127.0.0.1:8000/ 403 (Forbidden), server still cries with the same Forbidden (CSRF token missing or incorrect.) error. Suggestions please! Update: So I tried a function from Django's CSRF protection docs page that reads: function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } For whatever reason, this function returns a different value when I run getCookie("csrftoken") -- a value that is different from that of what is embedded by {{ csrf_token }}. Dunno what to make of that. Neither one works when inserting it into "X-CSRFToken" in my headers. A: I found the solution to the problem. The solution came when I ignored much of what I found on StackOverflow and instead opted just to use the Django docs. I had my code written as it is in my OP -- see how it makes headers out of new Headers()? And how the fetch has serverUrl plugged in as the first argument? Well, I changed it so that it reads like this: const serverUrl = "http://127.0.0.1:8000/" const request = new Request(serverUrl, { headers: { 'X-CSRFToken': getCookie("csrftoken") } }) fetch(request, { method: "POST", mode: "same-origin", body: JSON.stringify(editorState.expirationDate, editorState.contracts, editorState.theta) }).then(response => { console.log(response) }).catch(err => { console.log(err) }); And it worked! The difference was using the new Request() object in the fetch argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/63927791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: open child form in new page I have a sponsor which can have many warranty management urls. I have implemented the sponsor form but having trouble to create urls child form. Problem is I need to create child in new page and show the list back to the main form. How do I do it? My form: <%= form_for @sponsor, url: polymorphic_path([:a, @sponsor]) do |form| %> <%= form.file_field :logo %> <%= link_to "Add Warranty Service URL", new_a_sponsor_warranty_management_url_path(@sponsor), class: 'button green right' %> <% end %> Routes: resources :sponsors do resources :warranty_management_urls, only: [:new,:edit,:create,:update,:destroy] end Controller: def new @sponsor = Sponsor.new end Currently this error pops up: No route matches {:action=>"new", :controller=>"a/warranty_management_urls", :sponsor_id=>nil}, possible unmatched constraints: [:sponsor_id] A: It looks like your route helper is incorrect. The documentation for resource route helpers may be helpful for your situation: https://guides.rubyonrails.org/routing.html#path-and-url-helpers Have you tried running rake routes to get the list of available routes and route helpers? I imagine you need something more like: <%= link_to "Add Warranty Service URL", new_warranty_management_url_path, class: 'button green right' %> You can pass a sponsor_id param as an argument to the path helper, but that won't work unless the sponsor has been saved, which isn't true for a new record.
{ "language": "en", "url": "https://stackoverflow.com/questions/59896216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RSACryptoServiceProvider keysize 1024 is not generating a 128 byte key I have the following code: byte[] rsaKey; using (var rsa = new RSACryptoServiceProvider(1024)) { rsaKey = rsa.ExportCspBlob(false); } The result is that the length of rsaKey is 148 bytes and not 128. Why is that? I have to pass the public key rsaKey to other system so the other system encrypts some data, then this data is going to be sent again to me. What key do I have to use to decrypt? A: The key size for RSA is not the size of the encoded public key. The key size for asymmetric algorithms is a value that is directly related to the security strength. For RSA that is the size of the modulus, as factorization of the modulus is how you can attack RSA. The public key consists of the modulus of 128 bytes and a public exponent, so by definition it is already larger than the key size (although the public exponent is commonly just set to 0x010001 or 65537, the fifth prime of Fermat. Add additional information for this proprietary Microsoft format and you get to 148 bytes. As 148 - 128 - 3 is 17, you expect 17 bytes of overhead. To decrypt you've got to use the private key. I don't know why that isn't clear and what this has to do with the other question.
{ "language": "en", "url": "https://stackoverflow.com/questions/58331996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checking elements in a value in C How do I read element by elements in C? In Java I just do: for(int i = 0; i < str.length; i++){ if (str.charAt(i) == "X") return 1; } But I do I do something similar in C? ******Edit: I'm checking an int value for the first occurrence of 1, so the str operation doesn't work. Sorry i forgot to mention that at first. A: In C, you must know the length of the array: there is no language level ".length" to tell you. However, Strings are null-terminated, so standard functions like strlen() can be used. EXAMPLE: #include <stdio.h> #include <string.h> #define MAX_ELEMENTS 10 int main (int argc, char *argv[]) int my_array[MAX_ELEMENTS]; char my_string = "abc"; int i; for (int i=0; i < MAX_ELEMENTS; i++) my_array[i] = i*2; for (int i=0; i < MAX_ELEMENTS); i++) printf ("my_array[%d]=%d\n", i, my_array[i]); for (int i=0; i < strlen(my_string); i++) printf ("my_string[%d]=%c\n", i, my_string[i]); return 0; } A: You can just access the element directly: int SIZE_OF_STRING = 5; char string[SIZE_OF_STRING+1]; string[0] = 'h'; string[1] = 'e'; string[2] = 'l'; string[3] = 'l'; string[4] = 'o'; string[5] = '\0'; int sizeOfstring = strlen(string); for(int i = 0; i < sizeOfstring; i++){ if( str[i] == 'X'){ return 1; } } You can also explicitly use strcmp if you want to compare 2 char arrays. A: for(int i = 0; str[i]; i++){ if (str[i] == 'X') return 1; } A: Java strings hold at their beginning a 4 byte int value that indicates its size. Method length() just reads that value. In C however, string literals are ended with a null termination character \0. So strlen() in C iterates through single chars in string literal until it meets a \0. That's how it gets string's length. If you would like to use a method on string which returns you string's length, you can go with C++ and use a std::string class. It has a size() method for example. Here's a C code for snippet you provide. #include<string.h> /* ... */ size_t len = strlen(str); for(size_t i = 0; i < len; i++){ if (str[i] == 'X') return 1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/25923719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Python Tkinter: Why use Tkinter.W not str "w" I'm learning to use Tkinter and in the tutorials it tells me to import W from Tkinter, but W is just a str ("w"). My question is why use Tkinter.W not "w". Is it because Tkinter will sometimes have the var equal something else dependent upon system? A: I always use the string value. I see absolutely no benefit in using the constants. The chance of them changing is virtually zero. These constants have remained unchanged since Tkinter was created. tkinter takes backwards compatibility pretty seriously, so even if they are changed, the string values will undoubtedly continue to work for a year or two. My recommendation is to never use the constants. A: This is done mostly for user convinience. Consider the Image class from PIL/Pillow. It has a method to create a thumbnail out of an image, in the process resizing it. The method takes two arguments, the new size in a tuple and a resampling method. This can be antialias, bilinear, cubic, etc. These are internally represented with integer values, like 0, 1, etc. If you don't know which value represents which resampling method, it's cumbersome to look it and may also lead to more errors. But access it from the constant Image.BILINEAR and boom, you're done. In your case, importing W just for the string "w" seems to be needlessly polluting the namespace and typing tkinter.W is longer than "w". This might be so. However, remember, constants in a program are defined in one place so if you ever have to change them, it will be easy to so. You never know, the module may be internally use the constant W, even if you see no point in it. This also leads to the reason you pointed out. A constant may have a different value depending on the system or version. By using the internally consistent constant and not a static, hardcoded value, you make your life easier when you reuse that code on a diferent system or version.
{ "language": "en", "url": "https://stackoverflow.com/questions/34699869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I deleted the Anaconda, but it remains in the Start menu I deleted the anaconda, but it remains in the Windows Start menu. How do I delete anaconda from the Start menu? There is no anaconda in "C: \ ProgramData \ Microsoft \ Windows \ Start Menu \ Programs" However, it still appears in the Start menu. A: While running Windows 10 Pro, I recently had the same issue after uninstalling Anaconda3 with Anaconda's uninstaller. Try deleting the Anaconda3 folder from the following directory to remove the related shortcuts. "C:\ProgramData\Microsoft\Windows\Start Menu\Programs" Note: This fix assumes Anaconda3 was previously installed using default directories.
{ "language": "en", "url": "https://stackoverflow.com/questions/57347019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the name of a JButton on click @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == thirdBtn) { //System.out.println("Third Button Click"); System.out.println(e.getSource()+" Click"); } } In the code above, I was wondering if instead of doing this: //System.out.println("Third Button Click"); if I could do something like this: System.out.println(e.getSource()+" Click"); However the code outputs: BlackJack.OverBoard$BlackJackButton[,440,395,100x25,alignmentX=0.0,alignmentY=0.5, border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@7a3d8738, flags=16777504,maximumSize=,minimumSize=,preferredSize=, defaultIcon=,disabledIcon=,disabledSelectedIcon=, margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14], paintBorder=false,paintFocus=true, pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=, text=Change,defaultCapable=true] Click I don't want this, I want to know how to get the JButton name and output it on click. EDIT: Some people are confused. When I say "name" (maybe that's the wrong word for it), I meant say you initialize a JButton JButton btnExample = new JButton(); I want it so that when you click the button, it outputs btnExample in the console. A: System.out.println(((JButton) e.getSource()).getName() + " Click"); A: You can cast to a JComponent if you know that only JComponents will be the return value of e.getSource() I'm using JComponent as the cast since it gives more flexibility. If you're only using JButtons, you can safely cast to a JButton instead. @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == thirdBtn) { //System.out.println("Third Button Click"); System.out.println(((JComponent) e.getSource()).getName()+" Click"); } } Feel free to replace getName() with getText(), depending on what exactly you need. Also, the == operator should only be used to compare Object references, so consider casting to a JComponent from the beginning and using .equals() on the names or text. Edit You can't output the name of the variable, but you can set the name/text of the JComponent. Eg JButton btnExample = new JButton(); btnExample.setName("btnExample"); Or if you want "btnExample" to actually be displayed on the button: JButton btnExample = new JButton(); btnExample.setText("btnExample");
{ "language": "en", "url": "https://stackoverflow.com/questions/14310331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can Apache APISIX support Layer 4 and Layer 7 proxies by default and which Layer 7 and Layer 4 protocols are supported respectively? I am recently learning Apache APISIX and I would like to ask about the proxy layer 7, and layer 4 protocol. Can Apache APISIX proxy TCP and UDP directly, and what are the seven-layer protocols supported? What layer 4 protocols are supported? A: for TCP/UDP, you could use stream-route feature to support them. TCP is the protocol for many popular applications and services, such as > > > LDAP, MySQL, and RTMP. UDP (User Datagram Protocol) is the protocol for many > popular non-transactional applications, such as DNS, syslog, and RADIUS. APISIX can dynamically load balancing TCP/UDP proxy. In Nginx world, we call > TCP/UDP proxy to stream proxy, we followed this statement. Please check https://apisix.apache.org/docs/apisix/stream-proxy
{ "language": "en", "url": "https://stackoverflow.com/questions/72469718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add vue js language support to monaco-editor I've been trying to add vuejs language support to monaco editor, but all my attempts have failed so far. I've tried monaco-vue plugin for editor for but it doesnt seem to work either. The end result that I would want to achieve is to provide completions just as codesandbox.io if not as good as vetur (vuejs plugin for vscode). Any kind of help would be appreciate. Thanks in advance. A: Monaco-vue, to my knowledge, simply enables you to easily render the Monaco Editor into your Vue app by way of a Vue component. Vue language support within the editor requires that you hook up the editor to a Language Server Protocol (LSP)-compliant service. I believe Vetur is an LSP implementation - though I have not yet attempted to connect my Monaco editor to it as of yet. The Vetur LSP project seems to have decent documentation: https://github.com/vuejs/vetur/tree/master/server For an overview of integrating LSP into a Monaco editor, see this: https://typefox.io/teaching-the-language-server-protocol-to-microsofts-monaco-editor ...and a link to a module that helps with this (also from Typefox): https://github.com/TypeFox/monaco-languageclient Beware that, as of my last visit to that project, it does not work with the very latest version of Monaco - though I haven't lost any features of note by staying back at version 14.xx. Also, I couldn't get Monaco Vue to work for me. It isn't hard to embed via the mounted lifecycle hook that renders the editor to the DOM on the mounted hook, like this: mounted: function () { this.editor = monaco.editor.create(document.getElementById('container'), { value: 'this is code', automaticLayout: true }) },
{ "language": "en", "url": "https://stackoverflow.com/questions/54281131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Pytorch random tensor generation with one fix value and rest of random value In my testing dataset, I have to always include one specific image(image at position 0) in each batch but others values can be randomly selected. So I am making a tensor which will have 1st value 0 (for 1st image) and the rest of others can be anything other than 0. My code snippet is below. a= torch.randperm(len(l-1)) #where l is total no of testing image in dataset, code output->tensor([10, 0, 1, 2, 4, 5]) b=torch.tensor([0]) # code output-> tensor([0]) c=torch.cat((b.view(1),a))# gives output as -> tensor([0, 10, 0, 1, 2, 4, 5]) and 0 is used twice so repeated test image However, above approach can include 0 twice as torch.randperm many times includes 0. Is there a way in torch to generate random number skipping one specific value. Or if you think another approach will be better please comment. A: You could just remove these 0s using conditional indexing (also assumed you meant len(l) - 1): a= torch.randperm(len(l)-1) #where l is total no of testing image in dataset, code output->tensor([10, 0, 1, 2, 4, 5]) a=a[a!=0] b=torch.tensor([0]) # code output-> tensor([0]) c=torch.cat((b,a))# gives output as -> tensor([0, 10, 0, 1, 2, 4, 5]) and 0 is used twice so repeated test image Or if you want to make sure it's never put in: a=torch.arange(1,len(l)) a=a[torch.randperm(a.shape[0])] b=torch.tensor([0]) c=torch.cat((b,a)) The second approach is a bit more versatile as you can have whatever values you'd like in your initial a declaration as well as replacement.
{ "language": "en", "url": "https://stackoverflow.com/questions/66756131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Populating HTML from MySQL & PDO (PHP); foreach loop failing to write MySQL data As title states, my objective is to produce an HTML table using data from a MySQL database. The general method I am using is sound, as I have written manually a series of cells, but I am trying to scale it to include large numbers of fields, and as such am trying to write the HTML for the cells using PHP and foreach loops with arrays. I've written out the context and steps of my working to both give context to my problem and provide general help to people in a similar situation. I know, however, that the problem I have lies specifically in one section of code - indicated clearly below if you want to skip right to it. Step 1 define arrays for the titles I'd like the fields to have and the column names in the MySQL db: $titles = array('Name', 'Age', 'Height', 'Weight'); $headers = array('q1', 'q2', 'q3', 'q4'); Step 2: connect to the database ($username and $password previously defined): try { $pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password); $pdo->exec("SET CHARACTER SET utf8"); Step 3: Create my SQL statement via a few concatenations, and fetch the $result: $sql ="SELECT"; foreach(array_combine($headers, $titles) as $header => $title) { $sql .= "`$header` AS `$title`,"; } $sql .= "`q5` AS `Eye Color`"; $sql .= "FROM samdata.CO_data"; $result = $pdo->query($sql); Step 4: Create $html_table by concatenating static HTML and the results from the above SQL query if($result !== false) { $html_table = '<table><tr>'; foreach($titles as $title) { $html_table .= "<th> $title </th>"; } $html_table .='</tr> <tr>'; //*********PROBLEM SECTION BELOW ************************** foreach(array_combine($result, $titles) as $row => $title) { $html_table .= "<td>' .$row\['$title'\]. '</td>"; } } //*********PROBLEM SECTION ABOVE ************************** $html_table .= '</tr> </table>'; $conn = null; echo $html_table; } I know the problem lies with the section indicated, because I've test all the other parts, and if instead of combining arrays / foreach loops I manually write out, for example: foreach($result as $row) { $html_table .= ' <tr> <td>' .$row['Names']. '</td> <td>' .$row['Age']. '</td> <td>' .$row['Height']. '</td> </tr>'; } In place of the loop, then it works fine and displays the data for each result for those headings, the problem being I have hundreds and want to be more elegant (and lazy) than writing them all out one by one! Where am I going wrong? Many thanks in advance for your help. A: Looks like you have some mismatched quotes on your problem line: $html_table .= "<td>' .$row\['$title'\]. '</td>"; You begin with a double quote. Inside double quotes, single quotes cannot be used to terminate the string. Instead, double quotes can only be terminated by double quotes. And the same goes for the single quotes. Meaning, this can be fixed in one of two ways: $html_table .= "<td>" . $row[$title] . "</td>"; Or: $html_table .= '<td>' . $row[$title] . '</td>'; Also notice how I removed the quotes from around $title. They are unnecessary and will make PHP do a little more processing than necessary. Notice how the quotes match now. Be sure, when writing code in your editor, to look at how the syntax is highlighted. You should see that with your original code, the variable and index were inside the string, because it would all be the same color. If you are relying on variable expansion in double-quoted strings (like echo "Hello $name";), know that accessing string keys of arrays will not work unless they are surrounded with brackets like so: echo "Hello {$person['FirstName']}"; You can however, use numeric indices like so: echo "Hello $people[0]"; So with your code, you'd need to do this if you didn't want to end the string and concatenate the value and then begin the string again: $html_table .= "<td>{$row[$title]}</td>"; However, I find this syntax ugly and it makes PHP do extra processing to find the places where it needs to expand variables. IMHO, use concatenation to avoid all of these problems. A: Your are not looping correctly. $result is a PDOStatement which you must fetch. Try foreach( $result->fetchAll() as $row ) { $html_table .= '<tr>' . "\n"; foreach( $row as $col ) { $html_table .= '<td>' .$col. '</td>'; } $html_table .= '</tr>' . "\n"; } A: this solution seems to be working in my project and allows me to get the column from the query and the records into an html table, hopefully it might help someone else too: $conn = (...) $sqlselect = "SELECT name, last, othercol FROM persontable"; // I prepare and execute my query $stmt = $conn->prepare($sqlselect); $stmt->execute(); //get full recordset: header and records $fullrs = $stmt->fetchAll(PDO::FETCH_ASSOC); //get the first row (column headers) but do not go to next record $colheaders = current($fullrs) out = ""; //variable that will hold my table out .= <table>; //get my columns headers in the table foreach($colheaders as $key=>$val) { $out .= '<th>'.$key.'</th>'; } //get my records in the table foreach($fullrs as $row) { $out .= "<tr>"; $out .= '<td>'.$row['name'].'</td>'; $out .= '<td>'.$row['last'].'</td>'; $out .= '<td>'.$row['othercol'].'</td>'; $out .= "</tr>"; } out .= </table>; //spit my table out echo $out;
{ "language": "en", "url": "https://stackoverflow.com/questions/12993696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vertically center elements in WordPress header I am trying to vertically center my header elements, but the following code that I've tried isnt working. What am I doing wrong? Please let me know where I can add padding or something else. Here is the website: https://eagleroofingcontractor.com/ What I have so far: <div class="col-md-12"> <aside id="text-3" class="widget header-right widget_text"> <div class="textwidget"> <div class="container extra-info"> <div class="row"> <div class="col-md-4"> <i class="fa fa-phone"></i> <div class="phone"> <h3>631-209-7377</h3> <span>[email protected]</span> </div> </div> <div class="col-md-2"> <div> <img src="https://eagleroofingcontractor.com/wp-content/uploads/2019/02/Better-Business-Bureau-A-Logo.png"> </div> </div> <div class="col-md-2"> <div> <img src="https://eagleroofingcontractor.com/wp-content/uploads/2019/02/gaf-master-elite-gold800px-800x292.jpg"> </div> </div> <div class="col-md-2"> <div> <img src="https://eagleroofingcontractor.com/wp-content/uploads/2019/02/Google_Partners_logo_blogpage.jpg"> </div> </div> <div class="col-md-2"> <div> <img src="https://eagleroofingcontractor.com/wp-content/uploads/2019/02/googole-guaranteed-min.png"> </div> </div> </div> </div> </div> </aside> </div> A: You need to change the elements .textwidget, .extra-info and the col-md-2 columns inside .extra-info to flex items and then vertically center the columns using the css flex property align-items:center. Add the following to your CSS: .textwidget { display: flex; } .extra-info { display: flex; } .extra-info .col-md-2 { display: flex; align-items: center; } N.B. Your site has a lot of elements using a common ID (e.g. all your <aside> elements in your header uses the same #text-3 ID). You should not use the same ID for more than one elements. Replace them with a common class-name or use a different ID for each element instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/54840624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write an RSS feed with Java? I'm using Java, and need to generate a simple, standards-compliant RSS feed. How can I go about this? A: I recommend using Rome: // Feed header SyndFeed feed = new SyndFeedImpl(); feed.setFeedType("rss_2.0"); feed.setTitle("Sample Feed"); feed.setLink("http://example.com/"); // Feed entries List entries = new ArrayList(); feed.setEntries(entries); SyndEntry entry = new SyndEntryImpl(); entry.setTitle("Entry #1"); entry.setLink("http://example.com/post/1"); SyndContent description = new SyndContentImpl(); description.setType("text/plain"); description.setValue("There is text in here."); entry.setDescription(description); entries.add(entry); // Write the feed to XML StringWriter writer = new StringWriter(); new SyndFeedOutput().output(feed, writer); System.out.println(writer.toString());
{ "language": "en", "url": "https://stackoverflow.com/questions/113063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Variable variables in Progress 4GL Is there a way to dynamically reference a variable? Apparently value() does not work on a variable reference. def var export-columns as char extent. def var i as int. def var my-columns as char extent ["column1, column2"]. export-columns = value("my-columns"). do i = 1 to extent(export-columns): put export-columns[i]. end. A: The only way to dynamically access variables is if they're in a temp-table. local variables cannot be accessed dynamically.
{ "language": "en", "url": "https://stackoverflow.com/questions/8140220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make Rails table column attribute read only What is the best way to make my table column read only? disable the setter method? The column is set by postgres trigger, so I don't want to set it in the application level A: It seems like you look for ActiveRecord::Base attr_readonly: class Foo < ActiveRecord::Base attr_readonly :bar end foo = Foo.create(bar: "first_value") foo.bar => "first_value" foo.update(bar: "second_value") #column `bar` ignored in SQL query foo.bar => "first_value"
{ "language": "en", "url": "https://stackoverflow.com/questions/37097708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to update form structure using ajax Recently i have been working over a contact module.There are 3 columns ie. name, email, phone and a +1 button which includes anew row to add one more contact filed using ajax. And here the problem arise. When i update my structure, the data in old contact field vanishes. Eg: I entered 2 rows and filled the data as name1, email1, and so on.. name1 email1 phone1 name2 email2 phone2 Now in order to add one more contact filed i use +1 botton. and as soon i click it i get: blank_1 blank_1 blank_1 blank_2 blank_2 blank_2 blank_3 blank_3 blank_3 //here blank_1, blank_2, blank_3 are just expressing blank columns My jquery code is : <script> $(document).ready(function(e) { num = 0; $('#plus_contact').click(function(e) { num = num +1 ; $.ajax({ url : 'contact/contact_form.php', method : 'POST', data : "number="+num, success : function(data) { $('#contact_form_div').html(data); }, }); }); }); </script> contact_form.php <?php if(isset($_POST['number']) && is_numeric($_POST['number'])) { echo $list =$_POST['number']; if($list == 1) { for($i=0; $i<$list;$i++) { ?> <div class="form-group"> <label class="sr-only" for="exampleInputEmail2">Full Name</label> <input type="text" name="c_name[]" class="form-control" id="c_full_name" placeholder="Full Name"> </div> <div class="form-group"> <label class="sr-only" for="exampleInputEmail2">Email address</label> <input type="email" name="c_email[]" class="form-control" id="c_email_id" placeholder="Email"> </div> <div class="form-group"> <label class="sr-only" for="exampleInputEmail2">Phone</label> <input type="tel" name="c_phone[]" class="form-control" id="c_phone_number" placeholder="Phone"> </div> <?php } } } ?> How can i add a row without altering the old row data ?? A: Instead of doing: $('#contact_form_div').html(data); Do this: $('#contact_form_div').append(data); Then you just need to make sure on your PHP that you only return one new row. A: Instead of replacing the current form, append the new lines generated by your PHP script. So you need to use $('#contact_form_div').append(data); instead of $('#contact_form_div').html(data);. After you change that, you can use the num parameter to specify the number of rows to be added. A: Don't ask for the whole form on every request. Keep the page you have now to do the first load of the form when you load the page. Then, make a php page that outputs a single row of results, request it via ajax as you have done, then append the result to the current html of the page. A: replace this: $('#contact_form_div').html(data); with this : $('#contact_form_div').append(data); You just need to append it not to replace it. hope it help :)
{ "language": "en", "url": "https://stackoverflow.com/questions/18499986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to save entity with relationship in spring boot I have a spring boot application where I want to send an json object with a relationship. I have one entity called meetingSetting and one called meetingTime. MeetingSetting can have as many meetingTimes as possible and one meetingTime object belongs to one meetingSetting. But when I try to send it I am getting the following error: not-null property references a null or transient value : com.cbc.coorporateblinddateservice.entities.dates.MeetingTime.meetingsSetting I tried debugging and noticed that meetingSetting is empty when it is sent inside the times object send in the json. Could someone look at my code and tell me what I am missing, my guess is that I have to extend my saveMethod in meetingSettings but it is just a guess. here is my MeetingSetting entity: @Entity @Table(name = "meeting_settings") @Data public class MeetingsSetting { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "meeting_name") private String meetingName; @Column(name = "meeting_url") private String meetingUrl; @Column(name = "meeting_pw") private String meetingPw; @OneToMany(mappedBy = "meetingsSetting", cascade = CascadeType.ALL) private Set<MeetingTime> meetingTime = new HashSet<>(); } meetingTime entity: @Entity @Table(name = "meeting_times") @Data public class MeetingTime { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "meeting_date") private String date; @Column(name = "start_time") private String startTime; @Column(name = "end_time") private String endTime; @ManyToOne() @JoinColumn(name = "meeting_settings_name", nullable = false) private MeetingsSetting meetingsSetting; } MeetingSettingCOntroller: @RestController @RequestMapping("/api/meetingSetting") public class MeetingSettingController { @Autowired MeetingSettingService meetingSettingService; @PostMapping("/") public void saveMeeting(@RequestBody MeetingsSetting meetingsSetting){ meetingSettingService.saveMeeting(meetingsSetting); } Service: @Service public class MeetingSettingService { @Autowired MeetingSettingRepository meetingSettingRepository; public void saveMeeting(@RequestBody MeetingsSetting meetingsSetting){ meetingSettingRepository.save(meetingsSetting); } Update new code: MeetingTime: @Entity @Table(name = "meeting_times") @Data public class MeetingTime { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "meeting_date") private String date; @Column(name = "start_time") private String startTime; @Column(name = "end_time") private String endTime; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "meeting_name", nullable = false) private MeetingsSetting meetingName; } MeetingSettings: @Entity @Table(name = "meeting_settings") @Data public class MeetingsSetting { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "meeting_name") private String meetingName; @Column(name = "meeting_url") private String meetingUrl; @Column(name = "meeting_pw") private String meetingPw; @OneToMany(mappedBy = "meetingName", cascade = CascadeType.ALL) private Set<MeetingTime> meetingTime = new HashSet<>(); } Sql script: create table meeting_times ( id bigint auto_increment primary key, meeting_date varchar(255) null, start_time varchar(255) null, end_time varchar(255) null, meeting_name varchar(255) null, constraint fk_meeting_times__meeting_settings_name foreign key (meeting_name) references meeting_settings (meeting_name) ); A: The reason you're getting a null issue is that on @JoinColumn(name = "meeting_settings_name", nullable = false) you've got nullable = false. the column you're joining on is meeting_settings_name which doesn't seem to be a column on meeting_times and the actual name on meeting_settings is meeting_name. You'll have to add meeting_name to meeting_times to create a relation between the two tables to get this to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/67777691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Variadic templates with exactly n parameters I want to make a variadic template with exactly N arguments, where N is also a template parameter. For example, template <int N, typename T[N]> void function(T t[N]) { // do stuff with t[0] through t[N-1] } (I realize the above is not valid syntax) I know that one way to achieve this is to use a static_assert on sizeof...(ArgsT) where ArgsT is a variadic template definition (i.e. template <typename ...ArgsT>). I am just wondering if there is a better way, not necessarily involving static_assert. A: You can use std::enable_if instead of static_assert: template <std::size_t N, typename ...Args> auto function(Args&&... args) -> typename std::enable_if<N == sizeof...(Args), void>::type { ... } Update: It's also possible to use it in constructors, where N is a template argument of the class. template <std::size_t N> struct foobar { template <typename ...Args, typename = typename std::enable_if<N == sizeof...(Args), void>::type> foobar(Args&&... args) { ... } };
{ "language": "en", "url": "https://stackoverflow.com/questions/23458498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Knockout foreach binding creating extra columns can someone tell me why there's extra td columns in the following foreach binding? <table border="1" style="margin-top: 5px"> <thead> <tr> <th>rid</th> <th>ciname</th> <th>dId</th> <th>ReqName</th> <th>ReqType</th> <th>bus</th> <th>Req test</th> <th>no trace</th> <th>p r</th> </tr> </thead> <tbody data-bind='foreach: gifts'> <tr> <td><span data-bind='text: reqid' /></td> <td><span data-bind='text: ciname' /></td> <td><span data-bind='text: did' /></td> <td><span data-bind='text: reqname' /><td> <td><span data-bind='text: reqtype' /><td> <td><span data-bind='text: bus' /><td> <td><span data-bind='text: reqtest' /><td> <td><span data-bind='text: notrace' /><td> <td><span data-bind='text: pr' /></td> </tr> </tbody> </table> jsfiddle link here: http://jsfiddle.net/g3j94273/ A: td not closed properly <table border="1" style="margin-top: 5px"> <thead> <tr> <th>rid</th> <th>ciname</th> <th>dId</th> <th>ReqName</th> <th>ReqType</th> <th>bus</th> <th>Req test</th> <th>no trace</th> <th>p r</th> </tr> </thead> <tbody data-bind='foreach: gifts'> <tr> <td><span data-bind='text: reqid' /></td> <td><span data-bind='text: ciname' /></td> <td><span data-bind='text: did' /></td> <td><span data-bind='text: reqname' /><td> ^^ <td><span data-bind='text: reqtype' /><td> ^^ <td><span data-bind='text: bus' /><td> ^^ <td><span data-bind='text: reqtest' /><td> ^^ <td><span data-bind='text: notrace' /><td> ^^ <td><span data-bind='text: pr' /></td> </tr> </tbody> </table> Use http://jsfiddle.net/g3j94273/1/ A: Your tags are not properly closed, you need to convert some of the <td> to </td> <table border="1" style="margin-top: 5px"> <thead> <tr> <th>rid</th> <th>ciname</th> <th>dId</th> <th>ReqName</th> <th>ReqType</th> <th>bus</th> <th>Req test</th> <th>no trace</th> <th>p r</th> </tr> </thead> <tbody data-bind='foreach: gifts'> <tr> <td><span data-bind='text: reqid' /></td> <td><span data-bind='text: ciname' /></td> <td><span data-bind='text: did' /></td> <td><span data-bind='text: reqname' /></td> <td><span data-bind='text: reqtype' /></td> <td><span data-bind='text: bus' /></td> <td><span data-bind='text: reqtest' /></td> <td><span data-bind='text: notrace' /></td> <td><span data-bind='text: pr' /></td> </tr> </tbody> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/30069841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do we need to require and include a module for a class? Why do I need to require "stacklike" in stack.rb when I am already using the include method for the stacklike.rb? If I remove the require, it yields the error "Uninitialized constant Stack::Stacklike (NameError)". stacklike.rb module Stacklike def stack @stack ||= [] #@stack || @stack = [] end def add_to_stack(obj) stack.push(obj) end def take_from_stack stack.pop end end stack.rb require_relative "stacklike" class Stack include Stacklike end s = Stack.new s.add_to_stack("people") s.add_to_stack("people2") s.add_to_stack("people3") puts "obj currently on the stack:" puts s.stack taken = s.take_from_stack puts "Removed this stack:" puts taken puts "Now on stack:" puts s.stack A: Ruby's include doesn't access the file system. The given module must have already been defined or a NameError will be raised: # foo.rb class Foo include Bar # NameError: uninitialized constant Foo::Bar end This works (everything in one file): # foo.rb module Bar end class Foo include Bar end If your module is defined in a separate file, you have to load this file using require or require_relative: # bar.rb module Bar end # foo.rb require_relative 'bar' class Foo include Bar end A: require is about files. include is about modules. Since a module and a file does not correspond one-to-one in Ruby, requiring a file and including a module are different tasks. They need to be controlled separately. The content of the module Stacklike is written on the file stacklike.rb, so you need to require that file to access the module. Then, you need to include Stack if you want to. A: We use Module#include method with module names as parameter to that method, to add those modules in the requiring class's ancestor chain. Now Kernel#require_relative will made available the classes,modules etc from the requiring file to the required file on top level. When you did require_relative "stacklike",it means module(s),class(s) etc whichever you have defined inside the file stacklike.rb are now available to the top level of the file stack.rb. Now to use the instance methods of the module Stacklike,using the instance of the class Stack,you need to include that module to the class Stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/19636628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to support multi screen size in android apps I write an application in android. now i want to change my code to be suitable for multi screens. i search but i didn't completely understand what should i do for that? for example: 1- i should set text size dynamically 2- have different layout for different screens size is there additional work to do? any sample for my question? A: Building a Dynamic UI with Fragments...just use fragments in your application to make it flexible http://developer.android.com/guide/components/fragments.html http://developer.android.com/training/basics/fragments/index.html
{ "language": "en", "url": "https://stackoverflow.com/questions/14210170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Result exceeded maximum length error The below OREPLACE query is throwing the error. Select cast( OREPLACE (SimpledefinitionQuery , 'gpi','gpiREPLC') as varchar(40000)) as repl from SimpleDef0; The return string in the OREPLACE function is set to max of 64000. When I checked the length of column SimpledefinitionQuery, it does not exceed 16000. So I am unable to find why I am getting the error. Also when I replace 'gpi' with 'gpiRPLC', the query works perfectly. What is going wrong here? Thanks A: According to this Teradata support page, when using OREPLACE the returned string also depends on the second and the third arguments OREPLACE (SimpledefinitionQuery , 'gpi','gpiREPLC') OREPLACE function implicitly converts source string(first argument) to UNICODE when second or third argument is literal(UNICODE) even if the source string is LATIN. Thus maybe check if the function works if you truncate SimpledefinitionQuery for the first 8000 characters (as suggested in @dnoeth comment it returns Unicode VARCHAR(8000))? Or change the literal type of 2nd and 3rd arguments to Latin as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/44205785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is linuxrc purpose and is it needed in the rootfs? Question My question is, What does linuxrc do? Do i need it in my rootfs? Does it have anything to do with using systemd vs initd? Background I am currently attempting to build a rootfs for an ARM 7 processor using Yocto. The only modification I have made to the original BSP project is I specified that I would like to use systemd as my initialization manager (done in local.conf). The rootfs builds (bitbake core-image-minimal) and using Mgftool2 I load it onto the board. When I attempt to boot the image i get the following error: VFS: Mounted root (ext3 filesystem) readonly on device 179:2. devtmpfs: mounted Freeing unused kernel memory: 272K (80816000 - 8085a000) Kernel panic - not syncing: Requested init /linuxrc failed (error -2). CPU: 0 PID: 1 Comm: swapper/0 Tainted: G W 4.4.15-v4.4.15+g017b90c #1 Hardware name: Freescale i.MX6 Ultralite (Device Tree) [<80015d9c>] (unwind_backtrace) from [<80012c14>] (show_stack+0x10/0x14) This makes perfect sense because after i examined the rootfs I generated, I found that there was no executable named linuxrc. I changed u-boot's default_bootargs to not include init=/linurc and booted the image again. I then got this error: (Update #1) Update #1 The secondary error was caused by systemd needing certain kernel parameters enabled. Once the kernel was rebuilt with these parameters, the linux image did boot. I am still interested in knowing what exactly linuxrc does and why it at least appears i do not need it. A: Linuxrc (/linuxrc, also common name /init) on desktop OSes is on initramfs(ramdisk). Usualy this in script that probed modules, creates temporary device nodes in /dev, waits and mount rootfs, switches to real root. If initramfs is not used it may by symlinked to init. Systemd uses udev to create /dev/ tree so it non needed. Desktop linux uses it in initramfs to mount root. If rootfs mounted directly it can run from footfs. Example /init extracted from router. #!/bin/sh # # crucial mountpoints mount -t proc none /proc mount -t sysfs none /sys mount -n tmpfs /var -t tmpfs -o size=17825792 mount -t tmpfs dev /dev mknod /dev/console c 5 1 mknod /dev/ttyS0 c 4 64 mknod /dev/ttyS1 c 4 65 # setup console, consider using ptmx? CIN=/dev/console COUT=/dev/console exec <$CIN &>$COUT mknod /dev/null c 1 3 mknod /dev/gpio c 127 0 mknod /dev/zero c 1 5 mknod /dev/tty c 5 0 mknod /dev/tty0 c 4 0 mknod /dev/tty1 c 4 1 mknod /dev/random c 1 8 mknod /dev/urandom c 1 9 mknod /dev/ptmx c 5 2 mknod /dev/mem c 1 1 mknod /dev/watchdog c 10 130 mknod /dev/mtdblock0 b 31 0 mknod /dev/mtdblock1 b 31 1 mknod /dev/mtdblock2 b 31 2 mknod /dev/mtdblock3 b 31 3 mknod /dev/mtdblock4 b 31 4 mknod /dev/mtdblock5 b 31 5 mknod /dev/mtdblock6 b 31 6 mknod /dev/mtdblock7 b 31 7 mknod /dev/mtd0 c 90 0 mknod /dev/mtd1 c 90 2 mknod /dev/mtd2 c 90 4 mknod /dev/mtd3 c 90 6 mknod /dev/mtd4 c 90 8 mknod /dev/mtd5 c 90 10 mknod /dev/mtd6 c 90 12 mknod /dev/mtd7 c 90 14 mknod /dev/ttyUSB0 c 188 0 mknod /dev/ttyUSB1 c 188 1 mknod /dev/ttyUSB2 c 188 2 mknod /dev/ttyUSB3 c 188 3 mknod /dev/ttyUSB4 c 188 4 mknod /dev/ttyUSB5 c 188 5 mknod /dev/ttyUSB6 c 188 6 mknod /dev/ppp c 108 0 mknod /dev/i2c-0 c 89 0 mknod /dev/i2c-1 c 89 1 mknod /dev/i2c-2 c 89 2 mknod /dev/i2c-3 c 89 3 # # Create the ubnt-poll-host char dev entries # The major number is 189 # # NOTE: wifiN's minor number = N # mknod /dev/uph_wifi0 c 189 0 mkdir /dev/pts /dev/shm # rest of the mounts mount none /dev/pts -t devpts if [ -e /proc/bus/usb ]; then mount none /proc/bus/usb -t usbfs fi echo "...mounts done" mkdir -p /var/run /var/tmp /var/log /var/etc /var/etc/persistent /var/lock echo "...filesystem init done" # insert hal module [ ! -f /lib/modules/*/ubnthal.ko ] || insmod /lib/modules/*/ubnthal.ko # making sure that critical files are in place mkdir -p /etc/rc.d /etc/init.d # forced update for f in inittab rc.d/rc.sysinit rc.d/rc rc.d/rc.stop ppp; do cp -f -r /usr/etc/$f /etc/$f done echo "...base ok" mkdir -p /etc/udhcpc # do not update if exist for f in passwd group login.defs profile hosts host.conf \ fstab udhcpc/udhcpc startup.list; do if [ -e /etc/$f ]; then echo -n '.' else cp -f /usr/etc/$f /etc/$f fi done echo "...update ok" mkdir -p /etc/sysinit # make symlinks if do not exist for f in services protocols shells mime.types ethertypes modules.d; do if [ -e /etc/$f ]; then echo -n '.' else ln -s /usr/etc/$f /etc/$f fi done echo "...symlinks ok" mkdir -p /etc/httpd # check if we have uploaded certificates for f in server.crt server.key; do if [ -e /etc/persistent/https/$f ]; then ln -s /etc/persistent/https/$f /etc/httpd/$f else ln -s /usr/etc/$f /etc/httpd/$f fi done echo "...httpd ok" CFG_SYSTEM="/tmp/system.cfg" CFG_RUNNING="/tmp/running.cfg" CFG_DEFAULT="/etc/default.cfg" #Starting watchdog manager /bin/watchdog -t 1 /dev/watchdog # board data symlinks + default config if [ -e /sbin/ubntconf ]; then /sbin/ubntconf -i $CFG_DEFAULT echo "ubntconf returned $?" >> /tmp/ubntconf.log echo "...detect ok" fi # System configuration mkdir -p /etc/sysinit/ /sbin/cfgmtd -r -p /etc/ -f $CFG_RUNNING if [ $? -ne 0 ]; then /sbin/cfgmtd -r -p /etc/ -t 2 -f $CFG_RUNNING if [ $? -ne 0 ]; then cp $CFG_DEFAULT $CFG_RUNNING fi fi sort $CFG_RUNNING | tr -d "\r" > $CFG_SYSTEM cp $CFG_SYSTEM $CFG_RUNNING # But for DFS testing, it's useful to be able to overide this if [ -f /etc/persistent/enable_printk ]; then echo 9 > /proc/sys/kernel/printk dmesg -c else # Do not clutter serial port, normally echo 1 > /proc/sys/kernel/printk fi; # Set device date to firmware build date BDATE=201509091722 if [ ! -z $BDATE ]; then date -s $BDATE >/dev/null 2>&1 fi # Run configuration parser if [ -e /sbin/ubntconf ]; then /sbin/ubntconf echo "ubntconf returned $?" >> /tmp/ubntconf.log fi echo "...running /sbin/init" exec /sbin/init echo "INTERNAL ERROR!!! Cannot run /sbin/init."
{ "language": "en", "url": "https://stackoverflow.com/questions/45268712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Wait to code inside function $.get done to continue I have doing a website with javascript but I can't do that I want. I have this <script type="text/javascript"> res = new Array(); var fun1 = function () { var control = $.Deferred(); for (i=0;i<5;i++) { $.get("URL", function(data){ res[i]=data; console.log ("i is: " + i + "and res is: " + res); }); } } setTimeout(function () { control.resolve(); }, 3000); var show = function () { console.log("Res finally is: " + res); } fun1().done(show); </script> I want to do a $.get with 5 or more different URL (I have a param in the URL) but I can't do it. res[i] is always the last element in the array (in this case is always res[5]=data and I want to fill the complete array, from 0 to 15. First console.log always show i is: 5 and res is: ,,,,,20 i is: 5 and res is: ,,,,,10 ... i is: 5 and res is: ,,,,,38 and the second console.log always return the last Res finally is ,,,,,38 How can I do it correctly? Thanks! A: The main issue with i is that your callbacks close over the variable i, not its value as of when the function was created. So they all see i = 5. I'm not quite understanding why you're repeating the get five times, but if you want to, you have to give the callbacks something else to close over (or use res.push(...) rather than res[i] = ..., but I assume you have a reason for the latter). You can do that using a builder: // PARTIAL solution, see below var fun1 = function () { var control = $.Deferred(); for (i=0;i<5;i++) { $.get("URL", buildHandler(i)); } function buildHandler(index) { return function(data){ res[index]=data; console.log ("index is: " + index + "and res is: " + res); }; } }; Another way to do a builder is to use Function#bind (ES5+, but easily polyfilled), but you'd create more functions than you need; the above is more efficient in this case (not that it likely matters). Then, to have fun1 return something useful, you have it return a promise (you seem to be on your way to that, based on your control variable), and then fulfill the promise when all of the gets are done ($.when is useful for that): var fun1 = function () { var control = $.Deferred(); var promises = []; for (i=0;i<5;i++) { promises.push($.get("URL", buildHandler(i))); } $.when.apply($, promises).then(function() { control.resolve(); // Or .resolveWith(), passing in something useful }); return control.promise(); function buildHandler(index) { return function(data){ res[index]=data; console.log ("index is: " + index + "and res is: " + res); }; } }; All of this assumes res is in scope for this code; you haven't shown where it comes from.
{ "language": "en", "url": "https://stackoverflow.com/questions/28050058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which Spring Batch Partition is best suited I have one DB having around 400k records and using spring batch I need to migrate that to another DB. Using single threaded step may not give me performance edge , so thought of using scalability options provided by spring batch. After reading from multiple posts and documentation, I got to know below are the ways by which you could optimize the batch job. * *Multithreaded Step : Not good if you need retry functionality *AsyncItemProcessor/AsynItemWriter : unsuitable for my usecase as reader also need to work in parallel *Partitioning : Thinking of using local partitioning as remote need inbound/outbound channels. *Remote Chunking : Does not want to use it due to extra complexity Please suggest best approach for my usecase. I am thinking to use local partitioning. However, as the id column is varchar, I am unable to understand how to partition that and spring batch example shows the example of ColumnRangePartitioner where column is numeric id. Does gridSize represent number of slave threads which will be spawned? If yes, I want to make it dynamic using Runtime.getRuntime().availableProcessors()+1. is that right approach for I/O Job? A: Does gridSize represent number of slave threads which will be spawned? Not necessarily. The grid size is the number of partitions that will be created by the partitioner. Note that this is just a hint to the partitioner, some partitioners do not use it (like the MultiResourcePartitioner). This is different from the number of workers. You can have more partitions than workers and vice versa. If yes, I want to make it dynamic using Runtime.getRuntime().availableProcessors()+1. You can use Runtime.getRuntime().availableProcessors() to dynamically spawn as much workers as available cores (even though I don't see the value of adding 1 to that, unless I'm missing something). is that right approach for I/O Job? It depends on how you are processing each record. But I think this is a good start since each worker will handle a different partition and all workers can be executed in parallel.
{ "language": "en", "url": "https://stackoverflow.com/questions/61522994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to associate file extensions without a special permission from Microsoft? If no, are there any alternative solutions to mimic the given behavior ? I've developed a "parser" of sorts for a custom file format and would like to be able to open such a file on my WP Mango. A: No, this "feature" isn't available without explicit permission from Microsoft. And no, there are no real alternative solutions.
{ "language": "en", "url": "https://stackoverflow.com/questions/9503883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compare array of objects: Ramda way There are 2 arrays of objects, the first one is const blocks = [ { id: 1 }, { id: 2 }, { id: 3 }, ] and the second one is const containers = [ { block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 3 } }, ] I want to take blocks array, take each object from that and find if containers array has block with such id. So if at least one id not found then I want to break loop and return false, otherwise if all id's found return true. I've tried to implement this with .some() function but I couldn't break loop when id is not found. I would appreciate if you advise Ramda way to mplement this. Thank you. A: You can do this using R.differenceWith: const blocks = [ { id: 1 }, { id: 2 }, { id: 3 }, ]; const containers = [ { block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 4 } }, ]; const diff = R.differenceWith((x,y) => x.id === y.block.id); const mismatch = diff(blocks, containers).length > 0; console.log(mismatch); <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script> A: In a non ramda way, you could compare each object with the other items and use a deep check. const deep = id => o => o && typeof o === 'object' && (o.id === id || Object.values(o).some(deep(id))), compare = (source, target) => source.every(({ id }) => target.some(deep(id))), blocks = [ { id: 1 }, { id: 2 }, { id: 3 }], containers = [{ block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 3 } }] console.log(compare(blocks, containers)); A: You can use the equals() method. const blocks = [ { id: 1 }, { id: 2 }, { id: 3 }, ] const containers = [ { block: { id: 1 } }, { block: { id: 2 } }, { block: { id: 3 } }, ] console.log(R.equals(containers.map(x => x.block.id),blocks.map(x => x.id))) <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script> A: There is no particular Ramda WayTM. Ramda is a library, a toolkit, or in Underscore's description, a toolbelt. It is built to make a certain style of coding easier to read and write in JS. But it is not meant to dictate at all how you write your code. Ramda's biggest goal is to make it easier to build applications through composing functions, ensuring such FP goodies as immutability and referential transparency. So for this problem, I might start with something like the following: const hasBlock = (containers) => { const ids = containers .map (c => c.block.id) return (block) => ids .includes (block.id) } const allContained = (containers) => (blocks) => blocks .every (hasBlock (containers) ) That latter function can be quickly rewritten using Ramda to const allContained = (containers) => (blocks) => all(hasBlock(containers), blocks) which simplifies to const allContained = (containers) => all(hasBlock(containers)) and from there to the elegant: const allContained = compose (all, hasBlock) But I don't see any straightforward simplifications of hasBlock. I might on some days write it as const hasBlock = (containers, ids = containers .map (c => c.block.id) ) => (block) => ids .includes (block.id) but that's only to satisfy some internal craving for single-expression function bodies, and not for any really good reason. It doesn't make the code any cleaner, and for some readers might make it more obscure. So here is where I end up: const hasBlock = (containers) => { const ids = containers .map (c => c.block.id) return (block) => ids .includes (block.id) } const allContained = compose (all, hasBlock) const containers = [{block: {id: 1}}, {block: {id: 2}}, {block: {id: 4}}] console .log ( allContained (containers) ([{id: 1}, {id: 2}, {id: 3}]), //=> false allContained (containers) ([{id: 1}, {id: 2}, {id: 4}]), //=> true allContained (containers) ([{id: 4}, {id: 1}]), //=> true allContained (containers) ([{id: 42}]), //=> false ) <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script><script> const {compose, all} = R </script> A: You can achieve this with JS/Lodash/Ramda almost same exact way. JS/Lodash having the same exact methods for every and some and in Ramda with all and any: const blocks = [{ id: 1 },{ id: 2 },{ id: 3 }] const containers = [{ block: { id: 1 } },{ block: { id: 2 } },{ block: { id: 3 } }] const blocks2 = [{ id: 1 },{ id: 2 },{ id: 3 }] const containers2 = [{ block: { id: 4 } },{ block: { id: 2 } },{ block: { id: 3 } }] let hasAllBlocks = (blks, conts) => blks.every(b => conts.some(c => c.block.id === b.id)) let hasAllBlocksLD = (blks, conts) => _.every(blks, b => _.some(conts, c => c.block.id === b.id)) let hasAllBlocksR = (blks, conts) => R.all(b => R.any(c => c.block.id === b.id, conts), blks) console.log(hasAllBlocks(blocks, containers)) // true console.log(hasAllBlocks(blocks2, containers2)) // false console.log(hasAllBlocksLD(blocks, containers)) // true console.log(hasAllBlocksLD(blocks2, containers2)) // false console.log(hasAllBlocksR(blocks, containers)) // true console.log(hasAllBlocksR(blocks2, containers2)) // false <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/56163773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Symfony2, JMS Serializer, Doctrine Persistent Collection and FOSRestBundle I'm trying to figure out how to return the DBRef objects in my views when using FOSRestBundle and JMSSerializer. So in my document I have class Advert { //... /** * @var Image[] * @MongoDB\ReferenceMany(targetDocument="AppBundle\Document\Image", cascade={"persist", "update", "remove"}) * @Serializer\Groups({"Default", "list", "details"}) * @Serializer\AccessType("public_method") * @Serializer\Accessor(getter="getSerializableImages") */ protected $images; //... } then, my controller looks like this /** * @View(serializerGroups={"details"}) * @ParamConverter("advert", class="AppBundle:Advert") * @param Request $request * @param Advert $advert * @return array * @throws \Doctrine\ODM\MongoDB\LockException */ public function getAction(Request $request, Advert $advert) { $this->get('monolog.logger.advert')->info('Advert View', [ 'documents' => [ 'advert' => $advert->toLoggableArray(), ], ]); $advertContact = new AdvertContact(); $advertContact->setAdvert($advert); $form = $this->createForm('AppBundle\Form\AdvertContact\AdvertContactType', $advertContact, [ 'action' => $this->generateUrl('advert_contact_new'), 'method' => 'post', ]); return [ 'advert' => $advert, 'contact_form' => $form->createView(), ]; } I've been checking all over for solutions. Closest I came was with using JMS's @Accessor annotation, with a method that does $this->images->toArray() on the document, but that doesn't work properly and I'm concerned about deserialization. Any help would be much appreciated!
{ "language": "en", "url": "https://stackoverflow.com/questions/37930769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there is some change in google maps v2 api key access My google maps api v2 don't show the map. I checked even on v3 also can't see the map. I am getting this : http://maps.gstatic.com/maps-api-v3/api/js/20/0/intl/iw_ALL/main. I checked the api key and try to define a new key. the same problem occure. A: I've got exactly the same problem for a few days. I finally got a way to solve it temporarily. GoogleMaps has released a new version (3.19) the 17th of February. You can force your pages use the previous version (3.18), which is unchanged, by adding in the javascript parameters the version : <script language="JavaScript" type="text/javascript" src="http://maps.google.fr/maps/api/js?sensor=false&language=fr&v=3.18"> With the 3.18 version, maps are correctly displayed. We have now to find what we have to change to make the 3.19 version work !
{ "language": "en", "url": "https://stackoverflow.com/questions/28603219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to find out which bundles are using my Bundle? I'm a building an OSGI framework and I was wondering if there is a way to get all the bundles who bound themselves to mine? It's because I offer a service to those bundles, and make new resources to optimize my preformence while offering this service. I also offer a way to destroy those resources when no longer needed, but I want a failsafe for when a bundle unbinds without first deleting his used resources. Can I use my BundleContext for this? A: You seem to be asking two different questions. In the first paragraph you're asking about bundles that are bound to you, which I interpret to mean bundles that import your exported packaged. In the second you're asking about consumers of your services; these are orthogonal issues. For the first question, you can use the BundleWiring API: BundleWiring myWiring = myBundle.adapt(BundleWiring.class); List<BundleWire> exports = myWiring.getProvidedWires(PackageNamespace.PACKAGE_NAMESPACE); for (BundleWire export : exports) { Bundle importer = export.getRequirerWiring().getBundle() } For services, you can use the ServiceFactory pattern. By registering your service as an instance of ServiceFactory rather than directly as an instance of the service interface you can keep track of the bundles that consume your service. Here is a skeleton of a service implementation using this pattern: public class MyServiceFactory implements ServiceFactory<MyServiceImpl> { public MyServiceImpl getService(Bundle bundle, ServiceRegistration reg) { // create an instance of the service, customised for the consumer bundle return new MyServiceImpl(bundle); } public void ungetService(Bundle bundle, ServiceRegistration reg, MyServiceImpl svc) { // release the resources used by the service impl svc.releaseResources(); } } UPDATE: Since you are implementing your service with DS, things are a bit easier. DS manages the creation of the instance for you... the only slightly tricky thing is working out which bundle is your consumer: @Component(servicefactory = true) public class MyComponent { @Activate public void activate(ComponentContext context) { Bundle consumer = context.getUsingBundle(); // ... } } In many cases you don't even need to get the ComponentContext and the consuming bundle. If you are assigning resources for each consumer bundle, then you can just save those into instance fields of the component, and remember to clean them up in your deactivate method. DS will create an instance of the component class for each consumer bundle.
{ "language": "en", "url": "https://stackoverflow.com/questions/17854034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sqlite on mono: calling SELECT causes ResetIndexes and index rebuilding I'm developing a .net app that is using sqlite to maintain a database. On windows I use System.Data.Sqlite library and everything works fine. On Linux I use Mono.Data.Sqlite. When I start my app and call "SELECT * FROM TagInfo" a strange thing happen. The sqlite starts rebuilding the index without any apparent reason. After finishing rebuilding the app runs normally. As you can imagine, the problem is that index rebuilding is very slow and can take up to 20 minutes. Also, when I restart the app, rebuilding is called again. I'm attaching below the stack trace during the rebuilding. Does anybody have any idea what could be causing this and how could I prevent it. Thanks a lot for any info. gregor Stack trace: System.Data.Common.Index.MergeSort (to={int[4096]}, length=2821) in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data.Common/Index.cs:518 System.Data.Common.Index.Sort () in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data.Common/Index.cs:186 System.Data.Common.Index.RebuildIndex () in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data.Common/Index.cs:179 System.Data.Common.Index.Reset () in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data.Common/Index.cs:160 System.Data.DataTable.ResetIndexes () in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data/DataTable.cs:1485 System.Data.DataTable.set_EnforceConstraints (value=true) in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data/DataTable.cs:623 System.Data.DataTable.EndLoadData () in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data/DataTable.cs:968 System.Data.Common.DbDataAdapter.FillFromReader (table={}, reader={Mono.Data.Sqlite.SqliteDataReader}, start=0, length=0, mapping={int[4]}, loadOption=System.Data.LoadOption.PreserveChanges) in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data.Common/DbDataAdapter.cs:368 System.Data.DataTable.Load (reader={Mono.Data.Sqlite.SqliteDataReader}, loadOption=System.Data.LoadOption.PreserveChanges) in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data/DataTable.cs:2857 System.Data.DataTable.Load (reader={Mono.Data.Sqlite.SqliteDataReader}) in /root/mono/mono-2.10.8/mcs/class/System.Data/System.Data/DataTable.cs:2838 GenFiles.SQLiteDatabase.GetDataTable (sql="SELECT * FROM TagInfo") in
{ "language": "en", "url": "https://stackoverflow.com/questions/10251252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel VBA - Insert Username ONLY when cell is changed Here's my problem: I have working code to insert a username and timestamp when a user makes a change anywhere in a row. Great! So my code works and I answered my own question, right? Nope! There's a tiny issue which, while it doesn't break the code, does lead to a user having their username input as having made a change when a change was not made. Here's my code: Private Sub Worksheet_Change(ByVal Target As Excel.Range) ThisRow = Target.Row 'protect Header row from any changes If (ThisRow = 1) Then Application.EnableEvents = False Application.Undo Application.EnableEvents = True MsgBox "Header Row is Protected." Exit Sub End If For i = 1 To 61 If Target.Column = i Then ' time stamp corresponding to cell's last update Range("BK" & ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("BJ" & ThisRow).Value = Environ("username") Range("BJ:BK").EntireColumn.AutoFit End If Next i End Sub Here's how it happens: A user decides they want to make a change to a cell, so they double click the cell. Now, if they push the escape key, nothing happens and everything is hunky dory. But, if they double click the cell, then click outside of the cell to another cell to leave that cell, the system logs that as a change even though no change was made and the user's username is put into column 62. This is no bueno, because someone could be held responsible for a mistake that another individual has made if they're incorrectly put down as the last person to change something in that row. Conversely - it might be worthwhile to create a comment in a cell which is changed by a user, but I reckon I'd have the same issue with double-clicking a cell, so I'd still have to account for it. Thoughts? Edit: Full disclosure, I found this code elsewhere and adapted it to my purposes. A: You can test to see if the old value and the new value are the same. I use "new" loosely, meaning excel things that the cell was edited so it's a "new" value in terms of the Worksheet_Change event understanding. I also got rid of your For loop as it seemed very unnecessary. If I am mistaken, I apologize. Private Sub Worksheet_Change(ByVal Target As Excel.Range) Dim ThisRow As Long ' make sure to declare all the variables and appropiate types ThisRow = Target.Row 'protect Header row from any changes If (ThisRow = 1) Then Application.EnableEvents = False Application.Undo Application.EnableEvents = True MsgBox "Header Row is Protected." Exit Sub End If If Target.Column >= 1 And Target.Column <= 61 Then Dim sOld As String, sNew As String sNew = Target.Value 'capture new value With Application .EnableEvents = False .Undo End With sOld = Target.Value 'capture old value Target.Value = sNew 'reset new value If sOld <> sNew Then ' time stamp corresponding to cell's last update Range("BK" & ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("BJ" & ThisRow).Value = Environ("username") Range("BJ:BK").EntireColumn.AutoFit End If Application.EnableEvents = True End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/38334444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Solving the Monkey and Banana Using Basic STRIPS Algorithm We have been asked (for homework) to create solutions to a couple of AI problems using Python and making modifications to a basic STRIPS algorithm. At the moment I am trying to tackle the Monkey and Banana problem using it and have had some success but a lot of problems regarding behavior of the algorithm and I'm not sure what I'm missing here. This code has been trimmed down as I try to get the monkey to just push a chair somewhere and climb it. from string import * class Stripper: # A STRIPS-style planner for the blocks world # Initialization code def __init__(self): """ Initialize the global variables, and function dictionaries """ self.worldStack = [] self.goalStack = [] self.plan = [] # token to function mappings self.formulas = {"height": self.height, "at": self.at} self.Operators = {"GO": self.go, "PUSH": self.push, "CLIMB": self.climb} # safety net tests are denoted by the following as the first list item. self.SafetyTag = "SAFETYTAG" @staticmethod def populate(strng, statestack): """ Helper function that parses strng according to expectations and adds to the sateStack passed in. """ for x in (strng.lower().replace('(', '').replace(')', '').split(',')): ls = x.strip().split(' ') statestack.append(ls) statestack.reverse() def populategoal(self, strng): """ Populate the goal stack with data in strng. """ self.populate(strng, self.goalStack) # add original safety check goalcheck = [self.SafetyTag] for g in self.goalStack: goalcheck.append(g) self.goalStack.insert(0, goalcheck) def populateworld(self, strng): """ Populate the world state stack with data in strng. """ self.populate(strng, self.worldStack) # ---------------------------------------------------- # Solver # Attempts to solve the problem using the setup # goal and world states # ---------------------------------------------------- def solve(self): """ Attempts to solve the problem using STRIPS Algorithm Note: You need to setup the problem prior to running this by using populateWorld and populateGoal using a well formatted string. """ if (not len(self.worldStack) > 0) or (not len(self.goalStack) > 0): print "\nNothing to do.\nMake sure you populate the problem using\n" \ "populateWorld and populateGoal before calling this function." return while len(self.goalStack) > 0: # if the subgoal is in world state if self.top(self.goalStack) in self.worldStack: # pop it from the stack self.goalStack.pop() # if that item is an operator, elif self.top(self.goalStack)[0].upper() in self.Operators: subgoal = self.goalStack.pop() # store it in a "plan" self.plan.append(subgoal) # and modify the world state as specified self.Operators[(subgoal[0])](subgoal) # if the item is a safety check elif self.SafetyTag == self.top(self.goalStack)[0].upper(): safetycheck = self.goalStack.pop() for check in safetycheck[1:]: if not (check in self.worldStack): print " Safety net ripped.n Couldn't contruct a plan. Exiting...", check return else: # find an operator that will cause the # top subgoal to result if self.top(self.goalStack)[0] in self.formulas: self.formulas[self.top(self.goalStack)[0]]() else: raise Exception(self.top(self.goalStack)[0] + " not valid formula/subgoal") # or add to goal stack and try, but not doing that for now. print "\nFinal Plan:\n", for step in self.plan: print " ", join(step, " ").upper() # ---------------------------------------------------- # Predicate logic # ---------------------------------------------------- def at(self): topg = self.top(self.goalStack) assert(topg[0] == "at"), "expected at" assert(len(topg) == 3), "expected 3 arguments" print topg x = self.getloc(topg[1]) if topg[1] == "monkey": self.goalStack.append(["GO", x, topg[2]]) self.goalStack.append([self.SafetyTag, ["at", "monkey", x], ["height", "monkey", "low"]]) self.goalStack.append(["at", "monkey", x]) self.goalStack.append(["height", "monkey", "low"]) else: self.goalStack.append(["PUSH", topg[1], x, topg[2]]) self.goalStack.append([self.SafetyTag, ["at", topg[1], x], ["at", "monkey", x], ["height", "monkey", "low"], ["height", topg[1], "low"], ["handempty"]]) self.goalStack.append(["at", topg[1], x]) self.goalStack.append(["at", "monkey", x]) self.goalStack.append(["height", "monkey", "low"]) self.goalStack.append(["height", topg[1], "low"]) self.goalStack.append(["handempty"]) def height(self): topg = self.top(self.goalStack) print topg assert(topg[0] == "height"), "expected height" assert(len(topg) == 3), "expected 3 arguments" if topg[1] == "monkey": x = self.getloc("monkey") y = "low" if (self.getheight("monkey") == "low") else "high" self.goalStack.append(["CLIMB"]) self.goalStack.append([self.SafetyTag, ["at", "monkey", x], ["at", "chair", x], ["height", "monkey", y], ["height", "chair", "low"]]) self.goalStack.append(["at", "chair", x]) self.goalStack.append(["height", "monkey", y]) self.goalStack.append(["height", "chair", "low"]) self.goalStack.append(["at", "monkey", x]) # ---------------------------------------------------- # Operators # ---------------------------------------------------- def go(self, subgoal): # deletion self.worldstateremove(["at", "monkey", subgoal[1]]) # addition self.worldstateadd(["at", "monkey", subgoal[2]]) def push(self, subgoal): # deletion self.worldstateremove(["at", "monkey", subgoal[2]]) self.worldstateremove(["at", subgoal[1], subgoal[2]]) # addition self.worldstateadd(["at", subgoal[1], subgoal[3]]) self.worldstateadd(["at", "monkey", subgoal[3]]) def climb(self, subgoal): # deletion self.worldstateremove(["height", "monkey", "low"]) # addition self.worldstateadd(["height", "monkey", "high"]) # ---------------------------------------------------- # Utility functions # ---------------------------------------------------- # Returns the item that is being held in the world state, 0 if not def getholdingitem(self): for x in self.worldStack: if x[0] == "holding": return x[1] return 0 # Return height of object def getheight(self, item): for x in self.worldStack: if x[0] == "height" and x[1] == item: return x[2] raise Exception("Object " + item + " is on nothing!") # Return location of object def getloc(self, item): for x in self.worldStack: if x[0] == "at" and x[1] == item: return x[2] raise Exception("Object " + item + " has no location!") # Adds a state to world state if the state isn't already true def worldstateadd(self, toadd): if toadd not in self.worldStack: self.worldStack.append(toadd) # Tries to remove the toRem state from the world state stack. def worldstateremove(self, torem): while torem in self.worldStack: self.worldStack.remove(torem) @staticmethod def top(lst): """ Returns the item at the end of the given list We don't catch an error because that's the error we want it to throw. """ return lst[len(lst) - 1] I've got some basic tests set up: from monkey2 import Stripper def runtests(): print "\n\nRunning Monkey-Banana Problem - Part 1\n" ws = "((height chair low), (height monkey low), (handempty), (at monkey a), (at chair b))" gs = "((at monkey d))" s = Stripper() s.populateworld(ws) s.populategoal(gs) s.solve() print "\n\nRunning Monkey-Banana Problem - Part 2\n" ws = "((height chair low), (height monkey low), (handempty), (at monkey a), (at chair b))" gs = "((at monkey d), (height monkey high))" s = Stripper() s.populateworld(ws) s.populategoal(gs) s.solve() print "\n\nRunning Monkey-Banana Problem - Part 2 Rearranged\n" ws = "((height chair low), (height monkey low), (handempty), (at monkey a), (at chair b))" gs = "((height monkey high), (at monkey d))" s = Stripper() s.populateworld(ws) s.populategoal(gs) s.solve() if __name__ == "__main__": runtests() For the test Part 2 it works but for when it is rearranged, the monkey gets stuck and I'm aware it is probably something simple but I can't quite figure out why my algorithm isn't robust enough to handle this. Can anyone see what I am missing? Or point me in the right direction? I get the feeling that the problem lies in the base solve() method because it isn't designed to allow backtracking.
{ "language": "en", "url": "https://stackoverflow.com/questions/33048330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hadoop processing time in datanode I have two questions here: * *I have 1x master and 1 node setup and process a file of 5MB. I found the total processing time is almost same as below with or without the datanode. I am referring to CPU time spent which almost 6 seconds. Anyone can reply here that the datanode is actually doing the job? How can I monitor that? Map input records=1 Map output records=802685 Map output bytes=8428185 Map output materialized bytes=10033561 Input split bytes=97 Combine input records=0 Combine output records=0 Reduce input groups=3 Reduce shuffle bytes=10033561 Reduce input records=802685 Reduce output records=3 Spilled Records=1605370 Shuffled Maps =1 Failed Shuffles=0 Merged Map outputs=1 GC time elapsed (ms)=527 CPU time spent (ms)=5800 Physical memory (bytes) snapshot=550604800 Virtual memory (bytes) snapshot=5864865792 Total committed heap usage (bytes)=421007360 Peak Map Physical memory (bytes)=416796672 Peak Map Virtual memory (bytes)=2929139712 Peak Reduce Physical memory (bytes)=133808128 Peak Reduce Virtual memory (bytes)=2935726080 *I faced out of memory error when running a file size of 20MB. I have set 4GB for this processing. Wondering why does this hadoop consumes so much of resources. It's just a map reduce job as the simple text below and produce an output of the count of below. ,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car,TrainBUS,car, Does anybody has an answer?
{ "language": "en", "url": "https://stackoverflow.com/questions/52818868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MediaCodec encoding - dequeueInputBuffer returns INFO_TRY_AGAIN_LATER? I'm working on a project where I'm using the AudioRecord class to record audio and MediaMuxer to write the encoded data to an output file. Everything seems to be working fine once I start recording but after a few calls to the writeRecordingAudioFileSampleData method below, the dequeueInputBuffer method continuously returns INFO_TRY_AGAIN_LATER (-1). I tried flushing the encoder every time I call the method and the issue no longer occurs. But then the app crashes when I call the stop method on the the media muxer (it says "Failed to stop the muxer"). I shouldn't have to call flush the MediaCodec but without it, I keep getting INFO_TRY_AGAIN_LATER. Here is the method that starts the recording process. For brevity, I have not included the methods that get the presentation time or the methods that initialize the AudioRecord instance, the MediaMuxer, and the MediaCodec encoder. I don't believe the issue has to do with them but if they may be helpful, let me know and I'll post them. public ActionResponse startRecording() { ActionResponse response = new ActionResponse(); try { File recordDir = new File(RECORD_TEMP_DIR); if(!recordDir.exists()) { if(!recordDir.mkdirs()) throw new IOException("Could not create file"); } String fileName = generateRecordingName(); String path = RECORD_TEMP_DIR + "/" + fileName + "." + recordingOutputOptions.recordAudioFormat.name; currentTrack = new AudioFile(); currentTrack.setName(fileName); currentTrack.setPath(path); currentTrack.setFormat(recordingOutputOptions.recordAudioFormat); this.initializeAudioRecord(); if(audioRecord.getState() != AudioRecord.STATE_INITIALIZED) throw new IOException("Could not initialize audio record instance"); this.initializeRecordingAudioEncoder(); this.initializeRecordingMediaMuxer(); encoder.start(); audioRecord.startRecording(); recordReadThread = new Thread(readAudioRecordRunnable); recordReadThread.start(); recorderState = MEDIA_RECORDER_STATE.RECORDING; response.setStatus(ActionResponse.ResponseStatus.SUCCESS); } catch (IOException e) { response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setError(e); } return response; } And here is the runnable where I'm reading data from the AudioRecord instance: private Runnable readAudioRecordRunnable = new Runnable() { @Override public void run() { ActionResponse response = new ActionResponse(ActionResponse.ResponseStatus.SUCCESS); File outFile = new File(currentTrack.path); try { if(outFile.exists()) outFile.delete(); // Parent directory should have already been created before we started recording if(!outFile.createNewFile()) { response.setStatusMessage("Could not create file"); response.setStatus(ActionResponse.ResponseStatus.FAILURE); } else { ByteBuffer buffer = ByteBuffer.allocateDirect(recordingOutputOptions.bufferSize); int numReads = 0; while (recorderState == MEDIA_RECORDER_STATE.RECORDING) { int result = audioRecord.read(buffer, recordingOutputOptions.bufferSize); if (result >= 0) { audioAbsolutePtsUs = (System.nanoTime()) / 1000L; int samplesPerBuffer = recordingOutputOptions.bufferSize / recordingOutputOptions.bytesPerSample; long presentationTime = getPresentationTimeUs(audioAbsolutePtsUs,samplesPerBuffer); Log.e("TAG","Writing " + result + " bytes of recorded data with presentation time: " + String.valueOf(presentationTime)); ActionResponse encodeResponse = writeRecordingAudioFileSampleData(buffer,false,presentationTime); if(!encodeResponse.isSuccess()) { response = encodeResponse; break; } buffer.clear(); numReads++; //encoder.flush(); } else { response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setStatusMessage("Audio record return result: " + result); break; } } } if(response.isSuccess()) writeRecordingAudioFileSampleData(null,true,0); } catch (Exception e) { response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setStatusMessage("Error occurred while recording"); response.setError(e); } finally { try { encoder.stop(); encoder.release(); encoder = null; muxer.stop(); muxer.release(); muxer = null; isMuxerStarted = false; } catch (Exception ex) { Log.e("Recording Error","Error stopping and cleaning up encoder and muxer",ex); } } if(!response.isSuccess()) { stopRecording(); outFile.delete(); Log.e("Recording Error",response.statusMessage,response.error); if(recordEventHandler!=null) recordEventHandler.onRecordError(response); } } }; And here is the writeRecordingAudioFileSampleData method: public ActionResponse writeRecordingAudioFileSampleData(final ByteBuffer data,boolean isEndOfStream, long presentationTime) { ActionResponse response = new ActionResponse(ActionResponse.ResponseStatus.SUCCESS); try { boolean doneSubmittingInput = false; int index; int numBytesSubmitted = 0; int numBytesEncoded = 0; int numRetriesDequeueOutputBuffer = 0; ByteBuffer[] inputBuffers = encoder.getInputBuffers(); ByteBuffer[] outputBuffers = encoder.getOutputBuffers(); while (true) { if (!doneSubmittingInput) { index = encoder.dequeueInputBuffer(ENCODER_BUFFER_TIMEOUT_US); if (index != MediaCodec.INFO_TRY_AGAIN_LATER) { Log.e("TAG","Dequeued input buffer: " + index); if(isEndOfStream) { doneSubmittingInput = true; encoder.queueInputBuffer(index, 0, 0, 0, BUFFER_FLAG_END_OF_STREAM); } else { int dataSize = data.capacity(); if (numBytesSubmitted >= dataSize) { doneSubmittingInput = true; } else { ByteBuffer buffer = inputBuffers[index]; buffer.clear(); buffer.put(data); encoder.queueInputBuffer(index, 0, buffer.remaining(), presentationTime, 0); Log.e("TAG","Queued input buffer: " + index); numBytesSubmitted += buffer.remaining(); } } } else { response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setStatusMessage("Dequeue input buffer returned: " + index); break; } } MediaCodec.BufferInfo info = new MediaCodec.BufferInfo(); index = encoder.dequeueOutputBuffer(info, ENCODER_BUFFER_TIMEOUT_US); if (index == MediaCodec.INFO_TRY_AGAIN_LATER) { Log.e("TAG","No output buffer available"); if (++numRetriesDequeueOutputBuffer > MAX_NUM_RETRIES_DEQUEUE_OUTPUT_BUFFER) { if(!isEndOfStream) { // All data encoded Log.e("TAG","Max Retries Exceeded. All data has been encoded."); break; } else { Log.e("TAG","Max Retries Exceeded. End of stream input has been queued."); // EOS Input Queued, Continue Loop to Receive output } } } else if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // should only happen once before receiving buffers if (isMuxerStarted) { // should not occur response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setStatusMessage("Output format changed after muxer started"); break; } MediaFormat newFormat = encoder.getOutputFormat(); muxerTrackIndex = muxer.addTrack(newFormat); muxer.start(); isMuxerStarted = true; Log.e("TAG","Started Muxer"); } else if (index == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { // should not occur Log.e("TAG","Output buffers changed"); outputBuffers = encoder.getOutputBuffers(); } else if (index < 0) { Log.e("TAG","Unexpected index " + index + " received from dequeueOutputBuffer"); // Unexpected result - should not occur. Ignore it } else { Log.e("TAG","Dequeued output buffer: " + index); ByteBuffer encodedData = outputBuffers[index]; if ((info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { // The codec config data was pulled out and fed to the muxer when we got // the INFO_OUTPUT_FORMAT_CHANGED status. Ignore it. Log.e("TAG","Ignoring codec config data"); info.size = 0; } if (info.size != 0) { if (!isMuxerStarted) { // should not occur response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setStatusMessage("Attempting to write data but muxer was not started"); break; } info.presentationTimeUs = presentationTime; muxer.writeSampleData(muxerTrackIndex,encodedData,info); Log.e("TAG","Wrote " + info.size + " bytes to muxer"); numBytesEncoded += info.size; } encoder.releaseOutputBuffer(index, false); Log.e("TAG","Releasing output buffer: " + index); if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { // EOS Submitted if(!isEndOfStream) { // Unexpected EOS response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setStatusMessage("Unexpected buffer end of stream flag"); } else Log.e("TAG","Dequeued end of stream reached. All data has been encoded."); break; } } } } catch (Exception exc) { response.setStatus(ActionResponse.ResponseStatus.FAILURE); response.setStatusMessage(exc.getMessage()); response.setError(exc); } finally { } return response; } Finally, here is a sample of the output I get when running the app, which shows where the recording stops: W/ExtendedACodec: Failed to get extension for extradata parameter E/TAG: Writing 28288 bytes of recorded data with presentation time: 41035517230 E/TAG: Dequeued input buffer: 0 E/TAG: Queued input buffer: 0 I/MPEG4Writer: limits: 4294967295/0 bytes/us, bit rate: -1 bps and the estimated moov size 3195 bytes D/MPEG4Writer: Audio track starting E/TAG: Started Muxer E/TAG: Dequeued input buffer: 1 E/TAG: Dequeued output buffer: 0 Ignoring codec config data E/TAG: Releasing output buffer: 0 E/TAG: Dequeued output buffer: 1 I/MPEG4Writer: setStartTimestampUs: 41035517230 Earliest track starting time: 41035517230 E/TAG: Wrote 371 bytes to muxer Releasing output buffer: 1 E/TAG: Dequeued output buffer: 2 E/TAG: Wrote 372 bytes to muxer E/TAG: Releasing output buffer: 2 E/TAG: Dequeued output buffer: 3 W/MPEG4Writer: 0-duration samples found: 1 E/TAG: Wrote 520 bytes to muxer Releasing output buffer: 3 E/TAG: No output buffer available E/TAG: No output buffer available I/chatty: uid=10286(com.bandindustries.musicjournal) Thread-4 identical 3 lines E/TAG: No output buffer available E/TAG: Max Retries Exceeded. All data has been encoded. Writing 28288 bytes of recorded data with presentation time: 41035677592 Dequeued input buffer: 2 E/TAG: Queued input buffer: 2 E/TAG: Dequeued output buffer: 0 W/MPEG4Writer: 0-duration samples found: 1 E/TAG: Wrote 513 bytes to muxer E/TAG: Releasing output buffer: 0 E/TAG: Dequeued input buffer: 3 E/TAG: Dequeued output buffer: 1 Wrote 462 bytes to muxer E/TAG: Releasing output buffer: 1 E/TAG: Dequeued output buffer: 2 Wrote 433 bytes to muxer E/TAG: Releasing output buffer: 2 E/TAG: No output buffer available I/chatty: uid=10286(com.bandindustries.musicjournal) Thread-4 identical 4 lines E/TAG: No output buffer available Max Retries Exceeded. All data has been encoded. E/TAG: Writing 28288 bytes of recorded data with presentation time: 41035837955 E/TAG: Dequeued input buffer: 0 E/TAG: Queued input buffer: 0 E/TAG: Dequeued output buffer: 3 W/MPEG4Writer: 0-duration samples found: 2 E/TAG: Wrote 407 bytes to muxer E/TAG: Releasing output buffer: 3 E/TAG: Dequeued input buffer: 2 E/TAG: Dequeued output buffer: 0 Wrote 408 bytes to muxer E/TAG: Releasing output buffer: 0 E/TAG: Dequeued output buffer: 1 E/TAG: Wrote 392 bytes to muxer E/TAG: Releasing output buffer: 1 E/TAG: Dequeued output buffer: 2 E/TAG: Wrote 390 bytes to muxer E/TAG: Releasing output buffer: 2 E/TAG: No output buffer available I/chatty: uid=10286(com.bandindustries.musicjournal) Thread-4 identical 4 lines E/TAG: No output buffer available E/TAG: Max Retries Exceeded. All data has been encoded. E/TAG: Writing 28288 bytes of recorded data with presentation time: 41035998318 E/TAG: Dequeued input buffer: 0 E/TAG: Queued input buffer: 0 E/TAG: Dequeued output buffer: 3 W/MPEG4Writer: 0-duration samples found: 3 E/TAG: Wrote 356 bytes to muxer E/TAG: Releasing output buffer: 3 I/zygote64: Do partial code cache collection, code=27KB, data=29KB After code cache collection, code=27KB, data=29KB Increasing code cache capacity to 128KB D/MPEG4Writer: Audio track stopping. Stop source Audio track source stopping Audio track source stopped I/MPEG4Writer: Received total/0-length (11/0) buffers and encoded 11 frames. - Audio Audio track drift time: 0 us D/MPEG4Writer: Audio track stopped. Stop source Audio track stopped. Stop source Stopping writer thread D/MPEG4Writer: 0 chunks are written in the last batch D/MPEG4Writer: Writer thread stopped I/MPEG4Writer: Ajust the moov start time from 41035517230 us -> 41035517230 us D/MPEG4Writer: Audio track stopping. Stop source E/Recording Error: Dequeue input buffer returned: -1 Has anyone ever experienced this before? This is my first time working with low-level media classes in Android and I couldn't find many good examples online or in the documentation. I appreciate any help. Thank you. UPDATE: The issue where the app crashes when stopping the media muxer was due to sending 0 as the presentation time stamp for the last call, which is the end of stream. But I'm getting an empty file as output for some reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/51363500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Load single column of CSV into MySQL I have a csv file that is formated as follows: Rank, URL 1, www.google.com 2, www.facebook.com etc... I have a table with structure url, source, date_added Where each csv file has a different source ID. I am using the following query to load my data load data local infile 'this.csv' into table seeds.seed fields terminated by ','; Which doesn't quite do what I want but it's my starting point. What I want to do is select column 2 to be inserted as my URL field, and set the source to 0 for each entry. So I am thinking something like this... load data local infile 'this.csv' into table seeds.seed(url, source) select col1, '0' fields terminated by ','; What is the correct notation for col1? And am I missing any other key parts to the query? A: LOAD DATA INFILE 'this.csv' INTO TABLE seed (col1) SET source = 0; FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\r\n'; Have a look into SO answer. This is the reference A: Query that ended up working load data local infile 'this.csv' into table seeds.seed fields terminated by ',' lines terminated by '\n' (@col1,@col2) set url=@col2, source='0'; A: it's quite tricky using load data infile. I spent all last week trying to work it out with so many numerous errors. I'll give you my insights. I can't see your create table statement so I don't know what datatypes you are using. If you have integer fields then you have to put at least a 0 in each field in your csv file even if it is wrong. you remove it later post import. If your integer field is a auto_increment like a primary key then you can omit the field alltogether. don't make my mistake and just leave the field there with no values. Delete it completely otherwise your csv will start with a field terminator character and cause no end of issues. load data infile 'file.csv' into table mytablename fields terminated by ',' lines terminated by '\r\n' - ( for windows) ignore 1 lines (field1, field2, field4 etc.) - you list your fields in your csv there. If you have fields with no data then you can delete them from your csv and omit them from the list here too. ignore 1 lines - ignores the first line of the csv which contains your field list. set id=null, field3=null; I set my auto_increment id field to null as its not in the csv file and the mysql knows it exists and what to do with it. Also set field3 to null because that had no values and was deleted from the csv file as an example.
{ "language": "en", "url": "https://stackoverflow.com/questions/17791565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular 2 how to put object array in to another object array So I have 2 Arrays (Always equal index) : A: [ {name: Jhon1} {name: Jhon2} {name: Jhon3} ] B: [ {lastName: Pom1} {lastName: Pom2} {lastName: Pom3} ] Expected Result after merge : A: [ {name: Jhon1, lastName: Pom1} {name: Jhon2, lastName: Pom2} {name: Jhon3, lastName: Pom3} ] Concat method just merges the whole array in to one like this : A: [ {name: Jhon1} {name: Jhon2} {name: Jhon3} {lastName: Pom1} {lastName: Pom2} {lastName: Pom3} ] My own function that I am trying. Below there is two arrays: this.prices and this.search.favoriteItems, I want to merge then the same way as I described before : showProducts(){ for(let i of this.localStorageArray){ let id = localStorage.getItem(i); this.search.getProductsById(id).subscribe ((data: any) => { this.prices.push(data.lowestPrices.Amazon); this.search.favoriteItems.push(data); //something here to merge this.prices and this.search }); } } A: You can use .map() with Object destrcuturing: let arr1 = [{name: 'Jhon1'}, {name: 'Jhon2'}, {name: 'Jhon3'}], arr2 = [{lastName: 'Pom1'}, {lastName: 'Pom2'}, {lastName: 'Pom3'}]; let zip = (a1, a2) => a1.map((o, i) => ({...o, ...a2[i]})); console.log(zip(arr1, arr2)); .as-console-wrapper { max-height: 100% !important; top: 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/53632682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot initialize non-const reference from convertible type I cannot initialize a non-const reference to type T1 from a convertible type T2. However, I can with a const reference. long l; const long long &const_ref = l; // fine long long &ref = l; // error: invalid initialization of reference of // type 'long long int&' from expression of type // 'long int' Most problems I encountered were related to r-values that cannot be assigned to a non-const reference. This is not the case here -- can someone explain? Thanks. A: An integer promotion results in an rvalue. long can be promoted to a long long, and then it gets bound to a const reference. Just as if you had done: typedef long long type; const type& x = type(l); // temporary! Contrarily an rvalue, as you know, cannot be bound to a non-const reference. (After all, there is no actual long long to refer to.) A: long long is not necessarily sized equal to long and may even use an entire different internal representation. Therefor you cannot bind a non-const reference to long to an object of type long long or the other way around. The Standard forbids it, and your compiler is correct to not allow it. You can wonder the same way about the following code snippet: long a = 0; long long b = 0; a = b; // works! long *pa = 0; long long *pb = pa; The last initialization won't work. Just because a type is convertible to another one, doesn't mean another type that compounds one of them is convertible to a third type that compounds the other one. Likewise, for the following case struct A { long i; }; struct B { long long i; }; A a; B b = a; // fail! In this case A and B each compound the type long and long long respectively, much like long& and long long& compound these types. However they won't be convertible into each other just because of that fact. Other rules happen to apply. If the reference is to const, a temporary object is created that has the correct type, and the reference is then bound to that object. A: I'm not a standards lawyer, but I think this is because long long is wider than long. A const reference is permitted because you won't be changing the value of l. A regular reference might lead to an assignment that's too big for l, so the compiler won't allow it. A: Let's assume that it's possible : long long &ref = l; It means that later in the code you can change the value referenced by ref to the value that is bigger then long type can hold but ok for long long. Practically, it means that you overwrite extra bytes of memory which can be used by different variable with unpredictable results.
{ "language": "en", "url": "https://stackoverflow.com/questions/2516631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python Module Import Error "ImportError: No module named mrjob.job" System: Mac OSX 10.6.5, Python 2.6 I try to run the python script below: from mrjob.job import MRJob class MRWordCounter(MRJob): def mapper(self, key, line): for word in line.split(): yield word, 1 def reducer(self, word, occurrences): yield word, sum(occurrences) if __name__ == '__main__': MRWordCounter.run() I get the following error: :~ vskarich$ python mrjob_test.py < words Traceback (most recent call last): File "mrjob_test.py", line 1, in <module> from mrjob.job import MRJob ImportError: No module named mrjob.job I had used easy_install like so: sudo easy_install mrjob This command downloaded the needed .egg file, and my site-packages directory for python looks like this: :~ vskarich$ cd /Library/Python/2.6/site-packages :site-packages vskarich$ ls PyYAML-3.09-py2.6-macosx-10.6-universal.egg easy-install.pth README mrjob-0.2.0-py2.6.egg boto-2.0b3-py2.6.egg simplejson-2.1.2-py2.6-macosx-10.6-universal.egg I am not sure what to do here as I am somewhat new to python; any help would be much appreciated. Thank you! A: Two suggestions: * *Make sure you don't have any file or directory permissions problems for the installed eggs and files in the site-packages directory. *If you have installed another instance of Python 2.6 (besides the Apple-supplied one in /usr/bin/python2.6), make sure you have installed a separate version of easy_install for it. As is, your output indicates it was almost certainly installed using the Apple-supplied easy_install in /usr/bin which is for the Apple-supplied Python. The easiest way to do that is to install the Distribute package using the new Python. A: I had the same problem, I tried pip install mrjob, sudo easy_install mrjob. It looked like it installed successfully, but when I ran a simple example script, I got the import error. I got it to work by following the instructions at: http://pythonhosted.org//mrjob/guides/quickstart.html#installation. In a nutshell, I cloned the source code from github and ran python setup.py install. My problem might be different from yours, though. There was nothing in my site-packages directory for mrjob after running pip-install and easy_install. A: mrjob package can be installed by running following command: pip install mrjob After installation, the error will be solved. It worked in my case.
{ "language": "en", "url": "https://stackoverflow.com/questions/4199984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android - DatabaseUtils.sqlEscapeString() does not work I want to insert "women's cloth" in the database, so I use String name = DatabaseUtils.sqlEscapeString("women's cloth"); but it gives out put like "'Women''s Clothing'" and while inserting app crashes and gives E/SQLiteLog: (1) near ",": syntax error --------- beginning of crash ----------------- 07-12 12:42:19.628 22387-22521/com.i4ustores E/AndroidRuntime: FATAL EXCEPTION: Thread-8634 android.database.sqlite.SQLiteException: near ",": syntax error (code 1): A: From your simple code, I guess you create SQL statement manually. Try using String.format: String query = String.format("SELECT * FROM %s WHERE %s = ?", TABLE_NAME, SEARCH_KEY); Read more at: Local Databases with SQLiteOpenHelper Or try using PreparedStatement like below: PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setBigDecimal(1, 153833.00) pstmt.setInt(2, 110592) Please be aware that the parameterIndex (i.e 1 and 2 in above code) start from 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/38322543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Folder changes monitor made in Visual Basic 2010 does not write changes correctly I've made a program in Visual Basic 2010, that monitors and write down changes in a folder eg. when a file deletes, when a file renames, when a file creates and which files, but it's a problem. I've writed the code to make a new line when another change is made, when a change is made, it writes it down to a file named log.txt, but the log only looks like "File log.txt has been modified" because the program, when it write changes to the log, it changes the log.txt to write down the log, but the strange is, it deletes everything in the document and writes "File log..txt has been modified" even if I have writed in the code to make a new line before writing. Can someone help me with this problem? Here's the code: Imports System.IO Imports System.Diagnostics Public Class Form1 Public watchfolder As FileSystemWatcher Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click watchfolder = New System.IO.FileSystemWatcher() 'this is the path we want to monitor watchfolder.Path = TextBox1.Text 'Add a list of Filter we want to specify 'make sure you use OR for each Filter as we need to 'all of those watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _ IO.NotifyFilters.FileName watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _ IO.NotifyFilters.Attributes ' add the handler to each event AddHandler watchfolder.Changed, AddressOf logchange AddHandler watchfolder.Created, AddressOf logchange AddHandler watchfolder.Deleted, AddressOf logchange ' add the rename handler as the signature is different AddHandler watchfolder.Renamed, AddressOf logrename 'Set this property to true to start watching watchfolder.EnableRaisingEvents = True Button1.Enabled = False Button2.Enabled = True 'End of code for btn_start_click End Sub Private Sub logchange(ByVal source As Object, ByVal e As _ System.IO.FileSystemEventArgs) If e.ChangeType = IO.WatcherChangeTypes.Changed Then Dim writer As New IO.StreamWriter("log.txt") writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + " " + "has been modified") writer.Close() End If If e.ChangeType = IO.WatcherChangeTypes.Created Then Dim writer As New IO.StreamWriter("log.txt") writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + " " + "has been created") writer.Close() End If If e.ChangeType = IO.WatcherChangeTypes.Deleted Then Dim writer As New IO.StreamWriter("log.txt") writer.WriteLine(Chr(13) & "Filde" + " " + e.FullPath + " " + "has been deleted") writer.Close() End If End Sub Public Sub logrename(ByVal source As Object, ByVal e As _ System.IO.RenamedEventArgs) Dim writer As New IO.StreamWriter("log.txt") writer.WriteLine(Chr(13) & "File" + " " + e.FullPath + "has been renamed to" + " " + e.Name) writer.Close() End Sub Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click ' Stop watching the folder watchfolder.EnableRaisingEvents = False Button1.Enabled = True Button2.Enabled = False End Sub End Class A: When you open your streamwriter, you are not telling it to append, so it overwrites: Dim writer As New IO.StreamWriter("log.txt", True) Also, you dont need a new stream for each activity: Dim msg as string= Environment.NewLine & "File " & e.FullPath & " " Select case e.ChangeType case IO.WatcherChangeTypes.Created msg &= "has been created" case IO.WatcherChangeTypes.Deleted msg &= "has been deleted" ...etc End Select Dim writer As New IO.StreamWriter("log.txt", True) writer.WriteLine(msg) writer.Close() ..you could also leave the stream open until the watcher ends You probably should exempt logging changes to log.txt, so test e.FullPath: If System.Io.Path.GetFileName(e.FullPath).ToLower = "log.text" Then Exit Sub A: Now the program in working! Thank you MPelletier and Plutonix for the amazing help! Here is the complete code: Imports System.IO Imports System.Diagnostics Public Class Form1 Public watchfolder As FileSystemWatcher Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click watchfolder = New System.IO.FileSystemWatcher() watchfolder.IncludeSubdirectories = True watchfolder.Path = TextBox1.Text watchfolder.NotifyFilter = IO.NotifyFilters.DirectoryName watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _ IO.NotifyFilters.FileName watchfolder.NotifyFilter = watchfolder.NotifyFilter Or _ IO.NotifyFilters.Attributes AddHandler watchfolder.Changed, AddressOf logchange AddHandler watchfolder.Created, AddressOf logchange AddHandler watchfolder.Deleted, AddressOf logchange AddHandler watchfolder.Renamed, AddressOf logrename watchfolder.EnableRaisingEvents = True Button1.Enabled = False Button2.Enabled = True End Sub Private Sub logchange(ByVal source As Object, ByVal e As _ System.IO.FileSystemEventArgs) If System.IO.Path.GetFileName(e.FullPath).ToLower = "log.txt" Then Exit Sub Dim msg As String = Environment.NewLine & "File " & e.FullPath & " " Select Case e.ChangeType Case IO.WatcherChangeTypes.Created msg &= "has been created" + " " + "Time:" + " " + Format(TimeOfDay) Case IO.WatcherChangeTypes.Deleted msg &= "has been deleted" + " " + "Time:" + " " + Format(TimeOfDay) Case IO.WatcherChangeTypes.Changed msg &= "has been modified" + " " + "Time:" + " " + Format(TimeOfDay) End Select Dim writer As New IO.StreamWriter("log.txt", True) writer.WriteLine(msg) writer.Close() End Sub Public Sub logrename(ByVal source As Object, ByVal e As _ System.IO.RenamedEventArgs) Select e.ChangeType Case IO.WatcherChangeTypes.Created Exit Sub Case IO.WatcherChangeTypes.Changed Exit Sub Case IO.WatcherChangeTypes.Deleted Exit Sub Case Else Dim msgrn As String = Environment.NewLine & "File " + e.OldName + " " msgrn &= "has been renamed to" + " " + e.Name + " " + "Time:" + " " + Format(TimeOfDay) Dim writer As New IO.StreamWriter("log.txt", True) writer.WriteLine(msgrn) writer.Close() End Select End Sub Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click watchfolder.EnableRaisingEvents = False Button1.Enabled = True Button2.Enabled = False End Sub Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click Me.Hide() MsgBox("To close it later, don't open the program again, press CTRL+ALT+DELETE and press Start Task Manager or something like that, and go to processes and kill FolderMonitor.exe or what you have named the file", 0 + 64, "FolderMonitor") End Sub End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/19408602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TypeError: coercing to Unicode: need string or buffer, file found in python(writing data from existing files into single file) I am supposed to write the data from three existing files to a single file in python. I faced the error "TypeError: coercing to Unicode: need string or buffer", file found. My three existing files are e, g and m and I made a file named results for writing my data from those three mentioned existing files. I really appreciate for any help filenames= [e,g,m] with open(results, "w") as outfile: for file in filenames: with open(file) as infile: for line in infile: outfile.write(line) A: Your filename should be a string. Filename e, m, g should be "e", "m", "g", result should be "result". Refer to code below: #!/usr/bin/python # -*- coding: utf-8 -*- filenames= ["e","g","m"] with open("results", "w") as outfile: for file in filenames: with open(file) as infile: for line in infile: outfile.write(line)
{ "language": "en", "url": "https://stackoverflow.com/questions/45317802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: p Values for FUN="coef" in bootstrapLavaan Suppose I have a lavaan model: fit=' #Structural model var1=~item1+item2+item3 var2=~item1+item2+item3 var3=~item1+item2+item3 #Path model var3~var2 var2~var1 ' I then use sem to calculate: example=lavaan::sem(fit, data) Now I want to apply bootstrapLavaan as such: boot.example=bootstrapLavaan(example, FUN="coef") When I analyse the object using... summary(boot.example) ... I am only given values for the coefficients such as the means, medians, min, max, etc. Is there some way to get p values for these coefficients?
{ "language": "en", "url": "https://stackoverflow.com/questions/37271763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to upload attachments to testresult using TFS API I am trying to upload attachments using TFS API Following is the code snippet : result.State = TestResultState.Completed; result.RunBy = identity; var attachment = result.CreateAttachment(logFilePath); run.Attachments.Add(attachment); The code doesn't throw any error. Also i see that IAttachmentOwner.AttachmentUploadCompleted Event has been raised indicating it is completed. Yet I am not able to see the uploaded attachments on my TFSWebPortal. Am I missing something here ? P.S : First question here. Please feel free to correct me. A: You can get it works with the following code: TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://tfsservername:8080/tfs/DefaultCollection")); ITestManagementTeamProject project = tfs.GetService<ITestManagementService>().GetTeamProject("projectName"); foreach (ITestPlan p in project.TestPlans.Query("Select * From TestPlan")) { ITestRun testRun = p.CreateTestRun(false); var testPoints = p.QueryTestPoints("SELECT * from TestPoint"); foreach (ITestPoint testPoint in testPoints) { testRun.AddTestPoint(testPoint, null); } testRun.Save(); ITestCaseResultCollection results = testRun.QueryResults(); foreach (ITestCaseResult result in results) { result.Attachments.Add(result.CreateAttachment(@"C:\Users\visong\Pictures\000.jpg")); result.Outcome = TestOutcome.Warning; result.State = TestResultState.Completed; results.Save(true); } testRun.Save(); testRun.Refresh(); } Then you should be able to find the attachement in the test result you're working with in MTM.
{ "language": "en", "url": "https://stackoverflow.com/questions/31973569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I can't find Generate local resource from tools menu in visual studio 2013 When I'm in design view(markup) of a web page, I can't find the Generate Local Resource from my tools menu. Can anyone tell me how to enable this tool?
{ "language": "en", "url": "https://stackoverflow.com/questions/23268284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Level Order Traversal: Deleting a Subtree #include <iostream> using namespace std; struct node { int item; node* l; node* r; node (int x) { item = x; l = 0; r = 0; } node(int x, node* l, node* r) { item = x; this->l = l; this->r = r; } }; typedef node* link; class QUEUE { private: link* q; int N; int head; int tail; public: QUEUE(int maxN) { q = new link[maxN + 1]; N = maxN + 1; head = N; tail = 0; } int empty() const { return head % N == tail; } void put(link item) { q[tail++] = item; tail = tail % N; } link get() { head = head % N; return q[head++]; } }; link head = 0; // Initial head of the tree link find(int x) { if (head == 0) { cout << "\nEmpty Tree\n"; return 0; } link temp = head; // To find the node with the value x and return its link QUEUE q(100); q.put(temp); while (!q.empty()) { temp = q.get(); if (temp->item == x) { return temp; } if (temp->l != 0) q.put(temp->l); if (temp->r != 0) q.put(temp->r); } return 0; } void print(link temp) { QUEUE q(100); q.put(temp); while (!q.empty()) { temp = q.get(); cout << temp->item << ", "; if (temp->l != 0) q.put(temp->l); if (temp->r != 0) q.put(temp->r); } } void deleteAll(link h) { // This deletes the entire binary tree QUEUE q(100); q.put(h); while (!q.empty()) { h = q.get(); if (h->l != 0) q.put(h->l); if (h->r != 0) q.put(h->r); delete h; } } int main() { link temp = 0; char c; int n1, n2; cout << "\n\nPlease enter the input instructions (X to exit program) : \n\n"; do { cin >> c; switch (c) { case 'C': cin >> n1; if (head == 0) { head = new node(n1); cout << "\nRoot node with item " << n1 << " has been created\n\n"; } else { cout << "\nError: Tree is not empty\n\n"; } break; case 'L': cin >> n1 >> n2; temp = find(n1); if (temp != 0) { if (temp->l == 0) { temp->l = new node(n2); cout << "\nNode with item " << n2 << " has been added\n\n"; } else { cout << "\nError: The specified node already has a left child\n\n"; } } else { cout << "\nError: The specified node doesn't exist\n\n"; } break; case 'R': cin >> n1 >> n2; temp = find(n1); if (temp != 0) { if (temp->r == 0) { temp->r = new node(n2); cout << "\nNode with item " << n2 << " has been added\n\n"; } else { cout << "\nError: The specified node already has a right child\n\n"; } } else { cout << "\nError: The specified node doesn't exist\n\n"; } break; case 'P': cin >> n1; temp = find(n1); if (head != 0) { cout << "\nLevel-order traversal of the entire tree: "; print(temp); } else { cout << "\nError: No elements to print\n\n"; } break; case 'D': cin >> n1; temp = find(n1); deleteAll(temp); temp = 0; break; case 'X': cout << "\nExiting Program\n\n"; break; default: cout << "\nInvalid input entered. Try again.\n\n"; } } while (c != 'X'); system("pause"); return 0; } Sample Input: C 9 L 9 8 R 9 6 L 8 3 R 8 5 R 6 2 L 3 4 L 4 10 L 5 1 R 5 11 L 1 12 R 1 7 It all works fine until I delete a subtree and print when it prints garbage value before crashing. Please help me figure out the bug because I've been trying in vain for hours now. It all works fine until I delete a subtree and print when it prints garbage value before crashing. Please help me figure out the bug because I've been trying in vain for hours now. A: When you delete a node, you call deleteAll(temp) which deletes temp, but it doesn't remove the pointer value from the l or r of temp's parent node. This leaves you with a invalid pointer, causing garbage printing and crashing. Unfortunately, the way your find works currently, you don't know what the current temp node's parent is when you get around to checking its value. One way to fix it is to have a different type of find (called something like remove) that looks in l and r at each iteration for the value and sets l or r to NULL before returning the pointer. You might have to have a special case for when the value is found in the root. Edit (sample code added): I am assuming you are not using recursion for some reason, so my code uses your existing queue based code. I only changed enough to get it working. findAndUnlink find the node with the value given and "unlinks" it from the tree. It returns the node found, giving you a completely separate tree. Note: it is up to the caller to free up the returned tree, otherwise you will leak memory. This is a drop in replacement for find in your existing code, as your existing code then calls deleteAll on the returned node. link findAndUnlink(int x) { if (head == 0) { cout << "\nEmpty Tree\n"; return 0; } link temp = head; if (temp->item == x) { // remove whole tree head = NULL; return temp; } // To find the node with the value x and remove it from the tree and return its link QUEUE q(100); q.put(temp); while (!q.empty()) { temp = q.get(); if (temp->l != NULL) { if (temp->l->item == x) { link returnLink = temp->l; temp->l = NULL; return returnLink; } q.put(temp->l); } if (temp->r != NULL) { if (temp->r->item == x) { link returnLink = temp->r; temp->r = NULL; return returnLink; } q.put(temp->r); } } return 0; } A: Try the recursive function: void Delete(link h) { if(h) { if(h->l) Delete(h->l); if(h->r) Delete(h->r); delete(h); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/29484721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dotnetnuke 6 Ribbonbar Admin and dropdown gone Above is the ribbonbar after I have logged in as a super user. The Admin option next to Host is completely gone The site is running DNN6, the skin is only in the site portal folder, and it seems that all admin modules and options have gone away. Even the header, which I set in Site Settings (under Admin), went away! Has anyone else had their admin options completely disappear on them? Is it possible that the skin is messing it up (all other sites use the same _default menu files and they work fine)? Thanks for any replies. A: We've recently had this exact situation occur in one of our DNN sites. It turn out that one of the site's administrators had accidentally renamed the Admin page from within the "Page Management" section (it's easy to see how that could happen). The fix was to go directly to /Admin/Pages.aspx and change the "Page Name" back to "Admin" ... and it will show up in the ribbon bar again. As a suggestion to DNN developers, I would recommend making the Admin page and its subpages impossible to rename.... A: Can you check the database to see if those pages exist? What if you try to navigate to http://website/admin.aspx do you see the admin page and all the child pages there?
{ "language": "en", "url": "https://stackoverflow.com/questions/8084007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to deploy a background Function "myBgFunctionInProjectB" in "project-b" and triggered by my topic "my-topic-project-a" from "project-a" It's possible to create a topic "my-topic-project-a" in project "project-a" so that it can be publicly visible (this is done by setting the role "pub/sub subscriber" to "allUsers" on it). Then from project "project-b" I can create a subscription to "my-topic-project-a" and read the events from "my-topic-project-a". This is done using the following gcloud commands: (these commands are executed on project "project-b") gcloud pubsub subscriptions create subscription-to-my-topic-project-a --topic projects/project-a/topics/my-topic-project-a gcloud pubsub subscriptions pull subscription-to-my-topic-project-a --auto-ack So ok this is possible when creating a subscription in "project-b" linked to "my-topic-project-a" in "project-a". In my use case I would like to be able to deploy a background function "myBgFunctionInProjectB" in "project-b" and triggered by my topic "my-topic-project-a" from "project-a" But ... this doesn't seem to be possible since gcloud CLI is not happy when you provide the full topic name while deploying the cloud function: gcloud beta functions deploy myBgFunctionInProjectB --runtime nodejs8 --trigger-topic projects/project-a/topics/my-topic-project-a --trigger-event google.pubsub.topic.publish ERROR: (gcloud.beta.functions.deploy) argument --trigger-topic: Invalid value 'projects/project-a/topics/my-topic-project-a': Topic must contain only Latin letters (lower- or upper-case), digits and the characters - + . _ ~ %. It must start with a letter and be from 3 to 255 characters long. is there a way to achieve that or this is actually not possible? Thanks A: So, it seems that is not actually possible to do this. I have found it by checking it in 2 different ways: * *If you try to create a function through the API explorer, you will need to fill the location where you want to run this, for example, projects/PROJECT_FOR_FUNCTION/locations/PREFERRED-LOCATION, and then, provide a request body, like this one: { "eventTrigger": { "resource": "projects/PROJECT_FOR_TOPIC/topics/YOUR_TOPIC", "eventType": "google.pubsub.topic.publish" }, "name": "projects/PROJECT_FOR_FUNCTION/locations/PREFERRED-LOCATION/functions/NAME_FOR_FUNTION } This will result in a 400 error code, with a message saying: { "field": "event_trigger.resource", "description": "Topic must be in the same project as function." } It will also say that you missed the source code, but, nonetheless, the API already shows that this is not possible. * *There is an already open issue in the Public Issue Tracker for this very same issue. Bear in mind that there is no ETA for it. I also tried to do this from gcloud, as you tried. I obviously had the same result. I then tried to remove the projects/project-a/topics/ bit from my command, but this creates a new topic in the same project that you create the function, so, it's not what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/51963857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: where can i find metadata of all the amazon cloud services? I searching for what are the metadata that AWS uses for each and every service. For AWS instance it uses ami-id, ami_launch-index, hostname, instance-action and many more as the metadata like wise where i can find metadata for all the services like EBS, VPN.... Reference Information obtained from Amazon Elastic Compute Cloud User Guide for Microsoft Windows Instances pdf pg no : 232 – 242 A: I believe you are interested in knowing the properties of the each AWS Resource / Service and not the meta-data. I don't think there is a straight answer. The work around what I can recommend is using the AWS CloudFormation's Syntax definition of each AWS Resource. For Example : EC2 Instance is represented by the following syntax. Not all of them are mandatory. http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html Look at the KEYS of the Key:Value pair provided below [ "AvailabilityZone" : String ] { "Type" : "AWS::EC2::Instance", "Properties" : { "AvailabilityZone" : String, "BlockDeviceMappings" : [ EC2 Block Device Mapping, ... ], "DisableApiTermination" : Boolean, "EbsOptimized" : Boolean, "IamInstanceProfile" : String, "ImageId" : String, "InstanceInitiatedShutdownBehavior" : String, "InstanceType" : String, "KernelId" : String, "KeyName" : String, "Monitoring" : Boolean, "NetworkInterfaces" : [ EC2 Network Interface, ... ], "PlacementGroupName" : String, "PrivateIpAddress" : String, "RamdiskId" : String, "SecurityGroupIds" : [ String, ... ], "SecurityGroups" : [ String, ... ], "SourceDestCheck" : Boolean, "SsmAssociations" : [ SSMAssociation, ... ] "SubnetId" : String, "Tags" : [ Resource Tag, ... ], "Tenancy" : String, "UserData" : String, "Volumes" : [ EC2 MountPoint, ... ], "AdditionalInfo" : String } } For VPC [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html] { "Type" : "AWS::EC2::VPC", "Properties" : { "CidrBlock" : String, "EnableDnsSupport" : Boolean, "EnableDnsHostnames" : Boolean, "InstanceTenancy" : String, "Tags" : [ Resource Tag, ... ] } } For EBS Volume [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html] { "Type":"AWS::EC2::Volume", "Properties" : { "AutoEnableIO" : Boolean, "AvailabilityZone" : String, "Encrypted" : Boolean, "Iops" : Number, "KmsKeyId" : String, "Size" : String, "SnapshotId" : String, "Tags" : [ Resource Tag, ... ], "VolumeType" : String } } The CloudFormation Resource Page has details for most of the items [http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html]. Below is the current list as of today [7 Jan 2016] * *AWS::AutoScaling::AutoScalingGroup *AWS::AutoScaling::LaunchConfiguration *AWS::AutoScaling::LifecycleHook *AWS::AutoScaling::ScalingPolicy *AWS::AutoScaling::ScheduledAction *AWS::CloudFormation::Authentication *AWS::CloudFormation::CustomResource *AWS::CloudFormation::Init *AWS::CloudFormation::Interface *AWS::CloudFormation::Stack *AWS::CloudFormation::WaitCondition *AWS::CloudFormation::WaitConditionHandle *AWS::CloudFront::Distribution *AWS::CloudTrail::Trail *AWS::CloudWatch::Alarm *AWS::CodeDeploy::Application *AWS::CodeDeploy::DeploymentConfig *AWS::CodeDeploy::DeploymentGroup *AWS::CodePipeline::CustomActionType *AWS::CodePipeline::Pipeline *AWS::Config::ConfigRule *AWS::Config::ConfigurationRecorder *AWS::Config::DeliveryChannel *AWS::DataPipeline::Pipeline *AWS::DirectoryService::MicrosoftAD *AWS::DirectoryService::SimpleAD *AWS::DynamoDB::Table *AWS::EC2::CustomerGateway *AWS::EC2::DHCPOptions *AWS::EC2::EIP *AWS::EC2::EIPAssociation *AWS::EC2::Instance *AWS::EC2::InternetGateway *AWS::EC2::NetworkAcl *AWS::EC2::NetworkAclEntry *AWS::EC2::NetworkInterface *AWS::EC2::NetworkInterfaceAttachment *AWS::EC2::PlacementGroup *AWS::EC2::Route *AWS::EC2::RouteTable *AWS::EC2::SecurityGroup *AWS::EC2::SecurityGroupEgress *AWS::EC2::SecurityGroupIngress *AWS::EC2::SpotFleet *AWS::EC2::Subnet *AWS::EC2::SubnetNetworkAclAssociation *AWS::EC2::SubnetRouteTableAssociation *AWS::EC2::Volume *AWS::EC2::VolumeAttachment *AWS::EC2::VPC *AWS::EC2::VPCDHCPOptionsAssociation *AWS::EC2::VPCEndpoint *AWS::EC2::VPCGatewayAttachment *AWS::EC2::VPCPeeringConnection *AWS::EC2::VPNConnection *AWS::EC2::VPNConnectionRoute *AWS::EC2::VPNGateway *AWS::EC2::VPNGatewayRoutePropagation *AWS::ECS::Cluster *AWS::ECS::Service *AWS::ECS::TaskDefinition *AWS::EFS::FileSystem *AWS::EFS::MountTarget *AWS::ElastiCache::CacheCluster *AWS::ElastiCache::ParameterGroup *AWS::ElastiCache::ReplicationGroup *AWS::ElastiCache::SecurityGroup *AWS::ElastiCache::SecurityGroupIngress *AWS::ElastiCache::SubnetGroup *AWS::ElasticBeanstalk::Application *AWS::ElasticBeanstalk::ApplicationVersion *AWS::ElasticBeanstalk::ConfigurationTemplate *AWS::ElasticBeanstalk::Environment *AWS::ElasticLoadBalancing::LoadBalancer *AWS::IAM::AccessKey *AWS::IAM::Group *AWS::IAM::InstanceProfile *AWS::IAM::ManagedPolicy *AWS::IAM::Policy *AWS::IAM::Role *AWS::IAM::User *AWS::IAM::UserToGroupAddition *AWS::Kinesis::Stream *AWS::KMS::Key *AWS::Lambda::EventSourceMapping *AWS::Lambda::Function *AWS::Lambda::Permission *AWS::Logs::Destination *AWS::Logs::LogGroup *AWS::Logs::LogStream *AWS::Logs::MetricFilter *AWS::Logs::SubscriptionFilter *AWS::OpsWorks::App *AWS::OpsWorks::ElasticLoadBalancerAttachment *AWS::OpsWorks::Instance *AWS::OpsWorks::Layer *AWS::OpsWorks::Stack *AWS::RDS::DBCluster *AWS::RDS::DBClusterParameterGroup *AWS::RDS::DBInstance *AWS::RDS::DBParameterGroup *AWS::RDS::DBSecurityGroup *AWS::RDS::DBSecurityGroupIngress *AWS::RDS::DBSubnetGroup *AWS::RDS::EventSubscription *AWS::RDS::OptionGroup *AWS::Redshift::Cluster *AWS::Redshift::ClusterParameterGroup *AWS::Redshift::ClusterSecurityGroup *AWS::Redshift::ClusterSecurityGroupIngress *AWS::Redshift::ClusterSubnetGroup *AWS::Route53::HealthCheck *AWS::Route53::HostedZone *AWS::Route53::RecordSet *AWS::Route53::RecordSetGroup *AWS::S3::Bucket *AWS::S3::BucketPolicy *AWS::SDB::Domain A: Try using AWS CLI. You can execute the describe commands of the various services to see and understand the metadata
{ "language": "en", "url": "https://stackoverflow.com/questions/34651460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dot/point in datagridview when updating data So, I have a datagridview (datagridview1) and it's connected to SQL Server. datagridview in column 3 (adhb) can be update by pressing a button and just edit in the specific column. The problem is when I try to update a decimal number (e.g 100.25) it's just change to 10025. How can it be able to update decimal value? The database (tbl_tahunan), and column 3 (adhb) is set to decimal(18,2) query for update data query = "UPDATE tbl_tahunan SET adhb = " + datagridview1.Rows[0].Cells[2].Value + " WHERE id_coicop = 1"; cmd = new SqlCommand(query, conn); cmd.ExecuteNonQuery(); A: Editing databases with data grids is ridiculously easy if you make life easy. Try doing this: * *Make a brand new project, so you don't disturb existing code *Add a new file of type DataSet *Open it by double clicking *Right click anywhere on the surface, choose Add.. TableAdapter *Fill in the connection details of the db *Choose "SELECT that produces rows" *Put a query of SELECT * FROM tbl_tahunan *Finish the wizard *Switch to the form *Open the Data Sources tool panel (View menu, Other Windows submenu) *Expand the nodes in the name of your dataset *Drag the tbl_tahunan one onto the form *Run the program Yes, that's it, not a single line of code written by you; VS has done it all (and made a better job of it too) and this simple app will download, display, edit and save rows. And I bet it won't have any decimal problems either.. You can look at how it works by reading the code in .Designer.cs files: the datagridview is connected to a datatable (tbl_tahunandatatable) through a bindingSource. When you fill the table with data, you will see the grid show the data automatically. You do not need to interact with the datagridview cells collection. All programmatic editing of data should be done to the datatable. This is a concept called MVC (model- the datatable, view - the datagridview, controller - sometimes the datagridview in editing mode, other times something else) - keeping M separate from VC usually helps build a sensible program structure You can build on this simple app you've created by e.g.: * *opening dataset, *right clicking on the TableAdapter, *adding another query, *add a query with some relevant where clause (llike SELECT * FROM tbl_tahunan WHERE adhb BETWEEN @from AND @to) *call it a good name, like FillByAdhbBetween *putting some text boxes in the UI *putting a button on the ui that calls it: tbl_tahunanTableAdapter.FillByAdhbBetween(somedatasetname.tbl_tahunan, Convert.ToDecimal(adhbfromTextbox.Text), Convert.ToDecimal(adhbtoTextbox.Text)) Now the grid will only fill with some rows instead of all Personally I always make the first query in a table adapter have a WHERE clause, that selects by primary key. It is handy for loading related data. We almost never want to select all rows from a db into our program
{ "language": "en", "url": "https://stackoverflow.com/questions/67914859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }