text
stringlengths
64
81.1k
meta
dict
Q: Handling multiple requests on a TCP/IP Socket Is it quite easy to handle multiple requests on a Java TCP / IP socket. Simply accept a message and spawn a thread. Accept another message and spawn another thread. The thing is once you start spawning threads things get more non deterministic. Say you have 10 clients and one client keeps firing requests and the other 9 nine who send requests at 10% percent of the hyperactive client, find it harder to get a look in. One way you could handle this is have a hashmap of semaphores in your server where every client has a corresponding semaphore. Before you handle a request for any client, you could make it go thru its semaphore and configure the semaphores so that each client could only have a certain number of requests at any one time. At this stage,I'm thinking yeah that works but is there a better way or a library that does this? A: ... but is there a better way ...? I use one accepting-thread per serversocket and a pool of pre-spawned threads to handle the workload. The accepting-thread only accepts connections (does nothing else) and gives the handler-socket to one of the threads in the pool. That thread then works with the handler-socket until the client is done, then closes the handler-socket. You can scale-out this setup as far as you like: If you notice that the accepting-thread is waiting for pool-threads most of the time then you need to x2 your number of pool-threads, if you notice that the accepting-thread is the bottle-neck you create both (A) another accepting-thread and (B) another socket from which it accepts connections and optionally (C) put these on another machine. The specific problem you are describing with the one hyper-active client can be intended/desired if the client is more important than others: in which case you have to do nothing. Or it can be considered a denial-of-service attack, in which case you should have a heuristic that just disconnects the client and temporarily bans its ip-address.
{ "pile_set_name": "StackExchange" }
Q: Download multiple CSV files from a list in a single CSV (Python) I have a 2 column CSV with download links in the first column and company symbols in the second column. For example: http://data.com/data001.csv, BHP http://data.com/data001.csv, TSA I am trying to loop through the list so that Python opens each CSV via the download link and saves it separately as the company name. Therefore each file should be downloaded and saved as follows: BHP.csv TSA.csv Below is the code I am using. It currently exports the entire CSV into a single row tabbed format, then loops back and does it again and again in an infinite loop. import pandas as pd data = pd.read_csv('download_links.csv', names=['download', 'symbol']) file = pd.DataFrame() cache = [] for d in data.download: df = pd.read_csv(d,index_col=None, header=0) cache.append(df) file = pd.DataFrame(cache) for s in data.symbol: file.to_csv(s+'.csv') print("done") Up until I convert the list 'cache' into the DataFrame 'file' to export it, the data is formatted perfectly. It's only when it gets converted to a DataFrame when the trouble starts. I'd love some help on this one as I've been stuck on it for a few hours. A: import pandas as pd data = pd.read_csv('download_links.csv') links = data.download file_names = data.symbol for link, file_name in zip(links,file_names): file = pd.read_csv(link).to_csv(file_name+'.csv', index=False)
{ "pile_set_name": "StackExchange" }
Q: How do I stop my form from adding code to current page URL instead of re-directing. Been stuck for days I am currently setting up a WordPress website and everything is going fine except for one issue I simply can't figure out. So basically I have a booking form on my website that allows people to select a couple values (number of bedrooms and bathrooms) and then when they click the button those values are amended to the booking-page URL and loaded. The problem I'm running into is that the code is being amended to the end of my current (home) page and thus not having any effect/ just reloading the page. After hours of looking around/ troubleshooting, and guessing I believe the code of interest is as follows from the theme I have installed. Would it be an issue of permalink (20) not existing and thus just returning the current page? If so that's odd since this theme is supposed to be ready to go right from install. That same button further down my page directs to myhomepage.com/ ?post_type=acf-field&p=20 instead of the booking page. Literally any help whatsoever with this would be greatly appreciated. It's fun looking around and learning a lot, but I really need my website to work as soon as possible. Thank you again. The code I THINK might be part of the problem: <form action="<?php echo get_permalink( 20 ); ?>" method="get"> <select name="service_id" data-custom-class="select-bedrooms"> <option value="" disabled selected><?php _e( 'Bedrooms', 'themestreet' ); ?></option> <?php if ( have_rows( 'bedroom_list','option' ) ) : $i = 1; ?> <?php while ( have_rows( 'bedroom_list','option' ) ) : the_row(); // vars $value = get_sub_field( 'value' ); $title = get_sub_field( 'title' ); ?><option value="<?php echo $value; ?>"><?php echo $title; ?></option> <?php $i++; ?> <?php endwhile; ?> <?php else: ?> <option value="" disabled selected><?php _e( 'Bedrooms', 'themestreet' ); ?></option> <option value="1"><?php _e('One Bedroom','themestreet'); ?></option> <option value="2"><?php _e('Two Bedrooms','themestreet'); ?></option> <option value="3"><?php _e('Three Bedrooms','themestreet'); ?></option> <option value="4"><?php _e('Four Bedrooms','themestreet'); ?></option> <option value="5"><?php _e('Five Bedrooms','themestreet'); ?></option> <option value="6"><?php _e('Six Bedrooms','themestreet'); ?></option> <?php endif; ?> </select> <select name="pricing_param_quantity" data-custom-class="select-bathrooms"> <option value="" disabled selected><?php _e( 'Bathrooms', 'themestreet' ); ?></option> <?php if ( have_rows( 'bathroom_list','option' ) ) : $i = 1; ?> <?php while ( have_rows( 'bathroom_list','option' ) ) : the_row(); // vars $value = get_sub_field( 'value' ); $title = get_sub_field( 'title' ); ?><option value="<?php echo $value; ?>"><?php echo $title; ?></option> <?php $i++; ?> <?php endwhile; ?> <?php else: ?> <option value="" disabled selected><?php _e( 'Bathrooms', 'themestreet' ); ?></option> <option value="1"><?php _e('1 Bathroom','themestreet'); ?></option> <option value="2"><?php _e('2 Bathrooms','themestreet'); ?></option> <option value="3"><?php _e('3 Bathrooms','themestreet'); ?></option> <option value="4"><?php _e('4 Bathrooms','themestreet'); ?></option> <option value="5"><?php _e('5 Bathrooms','themestreet'); ?></option> <option value="6"><?php _e('6 Bathrooms','themestreet'); ?></option> <?php endif; ?> </select> <button class="btn btn--primary"><?php _e( 'BOOK A CLEANING NOW', 'themestreet' ); ?></button> </form> A: Would it be an issue of permalink (20) not existing and thus just returning the current page? Yes, it seems that is happened now. Try to change the id fo that permalink to your booking page id. get_permalink( BOOKING_PAGE_ID )
{ "pile_set_name": "StackExchange" }
Q: inline function in different translation units with different compiler flags undefined behaviour? in visual studio you can set different compiler options for individual cpp files. for example: under "code generation" we can enable basic runtime checks in debug mode. or we can change the floating point model (precise/strict/fast). these are just examples. there are plenty of different flags. an inline function can be defined multiple times in the program, as long as the definitions are identical. we put this function into a header and include it in several translation units. now, what happens if different compiler options in different cpp files lead to slightly different compiled code for the function? then they do differ and we have undefined behaviour? you could make the function static (or put it into an unnamed namespace) but going further, every memberfunction defined directly in a class is implicit inline. this would mean that we may only include classes in different cpp files if these cpp files share the identical compiler flags. i can not imagine this to be true, because this would basically be to easy to get wrong. are we really that fast in the land of undefined behaviour? or will compilers handle this cases? A: As far as the Standard is concerned, each combination of command-line flags turns a compiler into a different implementation. While it is useful for implementations to be able to use object files produced by other implementations, the Standard imposes no requirement that they do so. Even in the absence of in-lining, consider having the following function in one compilation unit: char foo(void) { return 255; } and the following in another: char foo(void); int arr[128]; void bar(void) { int x=foo(); if (x >= 0 && x < 128) arr[x]=1; } If char was a signed type in both compilation units, the value of x in the second unit would be less than zero (thus skipping the array assignment). If it were an unsigned type in both units, it would be greater than 127 (likewise skipping the assignment). If one compilation unit used a signed char and the other used unsigned, however, and if the implementation expected return values to sign-extended or zero-extended in the result register, the result could be that a compiler might determine that x can't be greater than 127 even though it holds 255, or that it couldn't be less than 0 even though it holds -1. Consequently, the generated code might access arr[255] or arr[-1], with potentially-disastrous results. While there are many cases where it should be safe to combine code using different compiler flags, the Standard makes no effort to distinguish those where such mixing is safe from those where it is unsafe.
{ "pile_set_name": "StackExchange" }
Q: FxCop fails to analyse the indirectly referenced assembly Metrics.exe: error: The referenced assembly 'Exception.dll, version=1.0.5289.9, Culture=neutral, publickeytoken=67er8..' could not be found. This assembly is required for analysis and was referenced by \bin\cancel.dll. But the assembly it is trying to refer to (Exception.dll) is GAC'd. i.e, present in the C:\windows\assembly. I have around 300 project files.. Copying the assembly to each project will be a cumbersome process.. Is there any workaround? A: *Important: Check the assembly versions. The assembly Exception.dll was of an older version in GAC. But the assemblies trying to refer this assembly was of another version. Simply GACd the newer version of the assembly - Exception.dll in the GAC and it worked :-)
{ "pile_set_name": "StackExchange" }
Q: Rails Tutorial Ch. 9 Exercise 6: Expected response to be a , but was <200> I am trying to write tests and application code to redirect users who are already signed-in to the root_path if they try to CREATE a user or visit the NEW user path. Here are the tests I have written in user_pages_spec.rb: describe "for signed in users" do let(:user) { FactoryGirl.create(:user) } before { sign_in user } describe "using a 'new' action" do before { get new_user_path } specify { response.should redirect_to(root_path) } end describe "using a 'create' action" do before { post users_path } specify { response.should redirect_to(root_path) } end end UsersController: class UsersController < ApplicationController before_action :unsigned_in_user, only: [:create, :new] def new @user = User.new end def create @user = User.new(user_params) if @user.save sign_in @user flash[:success] = "Welcome to the Sample App!" redirect_to @user else render 'new' end end private # Before filters def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end def unsigned_in_user puts signed_in? redirect_to root_url, notice: "You are already signed in." unless !signed_in? end end The puts signed_in? returns false. I am assuming this is the problem because I would expect it to return true. Here are the errors after running the tests using rspec. Any help is appreciated. Failures: 1) User pages for signed in users using a 'create' action Failure/Error: before { post users_path } ActionController::ParameterMissing: param not found: user # ./app/controllers/users_controller.rb:52:in `user_params' # ./app/controllers/users_controller.rb:20:in `create' # ./spec/requests/user_pages_spec.rb:162:in `block (4 levels) in <top (required)>' 2) User pages for signed in users using a 'new' action Failure/Error: specify { response.should redirect_to(root_path) } Expected response to be a <redirect>, but was <200> # ./spec/requests/user_pages_spec.rb:158:in `block (4 levels) in <top (required)>' Within the sessions_helper.rb file: def signed_in? !current_user.nil? end In spec/support/utilities.rb: def sign_in(user, options={}) if options[:no_capybara] # Sign in when not using Capybara. remember_token = User.new_remember_token cookies[:remember_token] = remember_token user.update_attribute(:remember_token, User.encrypt(remember_token)) else visit signin_path fill_in "Email", with: user.email fill_in "Password", with: user.password click_button "Sign in" end end A: Were you able to get your tests to pass? In case you weren't, I had the same problem as you today, and was able to get the tests to pass by making two changes to the tests - passing a user hash when POSTing, and using the no_capybara option on the sign_in method, since get and post are not capybara methods and I think RSpec doesn't behave as we might expect if we switch from capybara to non-capybara methods within the same test. describe "for signed-in users" do let(:user) { FactoryGirl.create(:user) } before { sign_in user, no_capybara: true } describe "using a 'new' action" do before { get new_user_path } specify { response.should redirect_to(root_path) } end describe "using a 'create' action" do before do @user_new = {name: "Example User", email: "[email protected]", password: "foobar", password_confirmation: "foobar"} post users_path, user: @user_new end specify { response.should redirect_to(root_path) } end end A: Same answer as najwa, but I used the FactoryGirl user with the Rails attributes method to avoid duplication: describe "using a 'create' action" do before { post users_path, user: user.attributes } specify { response.should redirect_to(root_path) } end Helps to keep the data decoupled from the test code.
{ "pile_set_name": "StackExchange" }
Q: Why doesn't jQuery carousel work with an iframe? I tried making several jQuery content slider and carousel scripts, working with iframe, without success. The iframe contains Google charts and are generated by a Ruby plugin ( google_visualr )... you can see what HTML is generated : <div class='carousel_charts'> <ul> <li id='bar_chart'> <script type='text/javascript'> google.load('visualization','1', {packages: ['corechart'], callback: function() { var data_table = new google.visualization.DataTable();data_table.addColumn('date', 'Date');data_table.addColumn('number', 'Refinery');data_table.addColumn('number', 'Locomotive');data_table.addColumn('number', 'Comf. Mexican Sofa');data_table.addColumn('number', 'Nesta');data_table.addRow([{v: new Date(2011, 10, 21)}, {v: 123}, {v: 3}, {v: 16}, {v: 12}]);data_table.addRow([{v: new Date(2011, 10, 22)}, {v: 130}, {v: 1}, {v: 9}, {v: 22}]);data_table.addRow([{v: new Date(2011, 10, 23)}, {v: 155}, {v: 2}, {v: 15}, {v: 8}]);data_table.addRow([{v: new Date(2011, 10, 24)}, {v: 118}, {v: 3}, {v: 3}, {v: 11}]);data_table.addRow([{v: new Date(2011, 10, 25)}, {v: 99}, {v: 2}, {v: 7}, {v: 11}]);data_table.addRow([{v: new Date(2011, 10, 26)}, {v: 58}, {v: 0}, {v: 1}, {v: 16}]);data_table.addRow([{v: new Date(2011, 10, 27)}, {v: 45}, {v: 0}, {v: 1}, {v: 5}]); var chart = new google.visualization.BarChart(document.getElementById('bar_chart')); chart.draw(data_table, {width: 860, height: 540, title: 'Ruby CMS Diffusion', vAxis: {title: 'Last week', titleTextStyle: {color: 'red'}}, oAxis: {title: 'RubyGems Downloads', titleTextStyle: {color: 'red'}}}); }}); </script> </li> <li id='geo_chart'> <script type='text/javascript'> google.load('visualization','1', {packages: ['geochart'], callback: function() { var data_table = new google.visualization.DataTable();data_table.addColumn('string', 'Country');data_table.addColumn('number', 'Popularity');data_table.addRow([{v: 'Germany'}, {v: 200}]);data_table.addRow([{v: 'United States'}, {v: 300}]);data_table.addRow([{v: 'Brazil'}, {v: 400}]);data_table.addRow([{v: 'Canada'}, {v: 500}]);data_table.addRow([{v: 'France'}, {v: 600}]);data_table.addRow([{v: 'RU'}, {v: 700}]); var chart = new google.visualization.GeoChart(document.getElementById('geo_chart')); chart.draw(data_table, {width: 860, height: 540}); }}); </script> </li> <li id='scatter_chart'> <script type='text/javascript'> google.load('visualization','1', {packages: ['corechart'], callback: function() { var data_table = new google.visualization.DataTable();data_table.addColumn('number', 'Age');data_table.addColumn('number', 'Weight');data_table.addRow([{v: 8}, {v: 12}]);data_table.addRow([{v: 4}, {v: 5.5}]);data_table.addRow([{v: 11}, {v: 14}]);data_table.addRow([{v: 4}, {v: 4.5}]);data_table.addRow([{v: 3}, {v: 3.5}]);data_table.addRow([{v: 6.5}, {v: 7}]); var chart = new google.visualization.ScatterChart(document.getElementById('scatter_chart')); chart.draw(data_table, {width: 860, height: 540, title: 'Age vs. Weight comparison', hAxis: {title: 'Age', minValue: 0, maxValue: 15}, vAxis: {title: 'Weight', minValue: 0, maxValue: 15}, legend: 'none'}); }}); </script> </li> </ul> </div> ... here it is the same code seen from FireBug. I want to slide the three google <script type='text/javascript'> injected into respective selectors <li id='bar_chart'> <li id='geo_chart'> <li id='scatter_chart'> ( see the previous code ). I'm trying to use this jQuery carousel script to slide html iframe contents but it doesn't works. The js is the following : $(function(){ // Looping carousel $("div.carousel_charts").carousel( { autoSlide: true, pagination: true } ); }); which is based on jquery.carousel.min.js. I'm currently using Rails-3.1.3 but pipelining works fine and this seems a more general js issue. No idea of what's wrong with that ( but I'm not a 'frontend developer' ) Any Idea ? A: Luca, From what i've seen after playing with the code you've passed in question, you can solve the issue by specifying some elements' sizes with the CSS like this: <style> #bar_chart, #geo_chart, #scatter_chart { height: 320px; width: 240px; display: block; float: left; } .carousel_charts ul { display: block; margin: 0; padding: 0; } .carousel-wrap { width: 240px; } </style> After applying above rules there is no need of specifying Google Chart size, so you can skip {width: 860; height: 540} from any chart.draw() call. Here is my result page code for your reference: http://pastebin.com/x0tpz1dq Please note - chart sizes are changed for illustration purpose.
{ "pile_set_name": "StackExchange" }
Q: Creat new project from GitExtensions clone I've been using GitExtensions with Visual Studio. However I've just realised it has only been tracking the project sub-directory - and not the project file itself. Now when I come to clone the repository, I cannot open the project - its just the individual files (eg. forms, classes, etc). So I thought I'd clone it into a sub folder just the same and just copy the project file across myself... But when I clone the tracked files, GE puts it all inside ANOTHER directory with the same name as the REMOTE repository - which is not the project name - so of course the project file won't work because it has the wrong paths...GAH! How can I either get GE to start tracking the original project file in the parent directory, or make it put the CONTENTS of the repository in the new directory that I want with the name I choose? Just about ready to delete the entire setup, remote and locals, and start from scratch without GE!! A: So I posted this Q after nearly a day of banging my head of the wall and shortly after posting found "an" answer, mostly out of the process of elimination. In GitExtensions I opened the GitBash and navigated to the project's parent directory - which holds the project file. Then I ran the following command the clone the project into a directory of the name I wanted and that matched what the project file was expecting: $ git clone https://www.github.com/myUserName/myRepositoryName theNeededDirectoryName Now the contents of the repository are in the directory theNeededDirectoryName which is the sub-directory I required. The project file has opened OK, will build, commit and push. BUT opening the solution in visual studio will no longer allow me to "start" debugging - only "attach" - dont know what this is but the OP is answered
{ "pile_set_name": "StackExchange" }
Q: "Stretching" a 2D Array in Java I need to "stretch" a 2D Array filled with chars of ' ', and '*'. The stretching is based on a "Int Factor" passed in through the method. Current Image looks like this: ***** * * * *** * * * * ***** Need it to look like this: (Assuming its Factor 2) ********** ** ** ** ****** ** ** ** ** ********** I started to write the loop for it but I have no idea if I'm on the right track or not, really struggling with this one. EDIT: I've gotten the array col length to stretch, I need to get the image to stretch with it now. public void stretch ( int factor ) { factor = 2; char[][] pixelStretch = new char[pixels.length][pixels[0].length * factor]; for (int row = 0; row < pixels.length; row++) { for (int col = 0; col < pixels[0].length; col+= factor) { for(int i=0; i<factor; i++) { pixelStretch[row][col+i] = pixels[row][col]; } } } pixels = pixelStretch; } Image printed from this: **** ** ** **** A: You're almost there. All you have to do, is change the code so that you're copying pixels[row][column] to the new array factor times // make sure factor is not 0 before you do this for (int col = 0; col < pixels[0].length; col++) { for(int i=0; i<factor; i++) { pixelStretch[row][col*factor+i] = pixels[row][col]; } }
{ "pile_set_name": "StackExchange" }
Q: Deserialize JSON Dictionary with StringComparer I'm trying to serialize/deserialize a dictionary, the problem is that I create the dictionary with a StringComparer.OrdinalIgnoreCase comparer. Here is a code snippet of the problem I'm experiencing: var dict = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); dict["x"] = new Dictionary<string, string>(); dict["x"]["y"] = "something"; var serialized = JsonConvert.SerializeObject(dict); var unSerialized = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(serialized); Console.WriteLine((dict.Comparer == unSerialized.Comparer ? "Same" : "Different")); (.NET Fiddle - Try It) Prints out the following on the console: Different Obviously the JSON serializer doesn't serialize the Comparer that I set when I create the dictionary, but the issue is that I can't set the Comparer after the fact since Dictionary<TKey, TValue>.Comparer is read-only. I'm sure it has to do with some custom JsonSerializerSetting but I can't seem to figure out how to intercept the collection creation and return a dictionary with a different comparer. A: You can specify the comparer to use in the constructor of your dictionary if you pass both the result of the deserialization and the comparer you want to use to the constructor of a new dictionary: var deserialized = JsonConvert .DeserializeObject<Dictionary<string, Dictionary<string, string>>>(serialized); var withComparer = new Dictionary<string, Dictionary<string, string>> ( deserialized, StringComparer.OrdinalIgnoreCase); A: You can also populate an existing object with PopulateObject: var dict = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); dict["x"] = new Dictionary<string, string>(); dict["x"]["y"] = "something"; var json = JsonConvert.SerializeObject(dict); var result = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); JsonConvert.PopulateObject(json, result); Console.WriteLine(result["x"]["y"]); Console.WriteLine(result.Comparer == dict.Comparer ? "Same" : "Diff"); Output: something Same
{ "pile_set_name": "StackExchange" }
Q: Give us a way to search for synonymed tags Someone finally created a synonym for interesting-tags to favorite-tags. It shows that there are still 146 questions with the old tag on them. I know the Team is unwilling to go change these (as per my linked question), so I figured I'd start in on it now that the tag has been synonymized. But lo and behold, it turns out that when you search on a synonymed tag it takes you to the master tag search page, so I'm unable to list the questions with the old tag using Search, so that I can do the conversions. Please give us a way to specifically do an advanced search for the tag without going to the master. NOTE: You can get to the specific tag search page if you click on the tag itself, so the logic is in there. This also means that this is just a minor feature request, since it can be worked around. A: The functionality to search by tag synonym is also converted to perform a search by the master tag. Take, for example, markdown-rendering (currently having 193 posts associated with it) which is a synonym of the master markdown (with 1,568 posts associated with it): Clicking on either will show posts under both markdown-rendering and markdown (a total of 193 + 1,568 = 1761 posts): Sifting through this list when the tags a more heavily weighted towards the master doesn't help. Currently, the only way to achieve this in some reasonable form is via SEDE. Specifically, here's a query that does that: Find questions by tags. As an example:
{ "pile_set_name": "StackExchange" }
Q: General Pointer issue I've tried the following: std::string* Member::GetName() { std::string name2 = "sdfsdfsd"; return &name2; } std::string* name; Member m; name = m.GetName(); std::cout << *name << std::endl; and it "works", but shouldn't be name2 unavailable after GetName() is called? and my pointer points to nothing? Edit: Coming back after years with more exp. some already answered this question below. Returning a local is bad!, you might get away with it, if the value on the stack didn't get overwritten, so often when you directly use it after returning a local you might get the correct values, but this is still undefined behaviour. Also not returning a const& also doesn't work, even now sometimes i think it binds the return value to a temporary as it does for const& parameters, but thats not the case for return types, the same goes for returning r-values refs. you can only return a copy and get it as const ref like this std::string GetName(); const std::string& name = GetName(); this will bind it to a temporary therefore is valid check herb sutters gotw: https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ for const ref temporaries. A: Taking the address of a local stack variable and using it when it's no longer in scope it's undefined behavior. As for "it works", it doesn't mean it will always work or that is a reliable practice. The stack isn't immediately wiped out when returning. Take a look at the definition of "undefined behavior"
{ "pile_set_name": "StackExchange" }
Q: Pass Function as Property to Vue Component I am trying to make my Vue Component reusable but there is a part in it which requires to run a function on button click which I have defined in the parent component. The component's button will always run a parent function and the parameter it passes is always the same (its only other property). Right now I am passing 2 properties to the component: 1) an object and 2) the parent function reference, which requires the object from 1) as a parameter. The Child-Component looks like this (stripped unnecessary code): <button v-on:click="parentMethod(placement)">Analyze</button> Vue.component('reporting-placement', { props: ['placement', 'method'], template: '#reporting-placement', methods: { parentMethod: function(placement) { this.method(placement); } } }); The parent is making use of the child like this: <reporting-placement v-bind:placement="placement" v-bind:method="analyzePlacement"></reporting-placement> methods: { analyzePlacement: function(placement) { this.active_placement = placement; }, } As you can see, the child has only one property, placement, and the callback reference. The placement must be put in as a parameter to the reference function from the parent. But since the parent defines the parameters, the child shouldn't concern itself with what it needs to pass to the parent function. Instead I would prefer to already pass the parameter along in the parent. So instead of <reporting-placement v-bind:placement="placement" v-bind:method="analyzePlacement"></reporting-placement> I would prefer <reporting-placement v-bind:placement="placement" v-bind:method="analyzePlacement(placement)"></reporting-placement> (including appropriate changes in the child). But passing the parameter along does not work that way. Is it possible (maybe in other syntax) to 'bind' the variable to the function reference so that it is automatically passed along when the callback is called? Info: I don't get an error message if I write it down as above but the whole Vue screws up when I pass the parameter along to the component. Hope the issue is clear :-) Thanks a lot! A: By reading your proposal I've found out that you are overusing the props passing. Your concern that child component should not have any knowledge about the way that the parent component uses the data is completely acceptable. To achieve this you can use Vue's event broadcasting system instead of passing the method as props. So your code will become something like this: Vue.component('reporting-placement', { props: ['placement', 'method'], template: '#reporting-placement', methods: { parentMethod: function(placement) { this.$emit('reporting-placement-change', placement) } } }); And you can use it like this: <reporting-placement v-bind:placement="placement" @reporting-placement-change="analyzePlacement($event)"></reporting-placement> But if you need the data which is provided by the method from parent it's better to consider using a state management system (which can be a simple EventBus or event the more complex Vuex) And finally, if you really like/have to pass the method as a prop, You can put it in an object, and pass that object as prop.
{ "pile_set_name": "StackExchange" }
Q: Need more explanation for finalize(), sample exam Given: class Finalizer { static int x = 0; static boolean gc = false; public static void main(String[] args) { for(x=0; x<100000; x++) { new Finalizer().finalize(); } x = 0; gc = true; System.gc(); } protected void finalize() { if(gc == true) x++; if(x % 10000 == 0) System.out.println(gc + " " + x); } } Which are always true? (Choose all that apply.) A: true will never be an output B: true will be output at least ones C: If true and false are both output, their respective values for x can be the same. D: If true and false are both output, their respective values for x can never be the same. The solution says C is correct, and I do not understand why, can someone please explain what is happening here. A: What's going on is this: finalize() overrides a method in the Object class. The javadoc explains when this is called. When an object is no longer referenced anywhere, it may then be garbage-collected; but when it's garbage-collected isn't defined by the language. The finalize() method will be called on each Finalize object when it's garbage-collected. Of course, the code you posted also calls finalize() explicitly. In this example, the loop will call new Finalize() 100,000 times to create new Finalize objects. Each time a new object is created, it's used to call finalize() explicitly, but then it's no longer used, so it could be garbage-collected right away. The consequence of this is that by the time we get to the System.gc() call, we don't know how many Finalize objects are still around waiting to be garbage-collected, but it could be anywhere from 0 to 100,000. (On my machine, it seems to be 1. That is, it's already garbage-collected all but one of the objects, and called finalize() on them.) During the first loop, x will go from 0 to 999,999 (the finalize() method won't modify x), and therefore you should see false x for every x that is a multiple of 10,000. (Note that finalize() could also be called by the runtime for objects that are garbage-collected early, so in theory it's possible to see false x for the same x more than once.) After the first loop, if N is the number of objects still to be garbage-collected, then System.gc() should cause them all to be garbage-collected at that point (it's not guaranteed); since x has been reset to 0 and finalize() will increment it, that means x will go from 1 to N. (Note that the first finalize() will increment x from 0 to 1 before the x % 10000 test.) You should see true x for every x in the range 1 to N that is a multiple of 10,000. But since N could be anything from 0 to 100,000, that means that we may or may not see any true outputs--we can't tell. That's why neither A nor B is "always true". If we do see any true outputs, since the output will show every multiple of 10,000 in its range, it's certain that the true output will have the same number as a previous false output, which explains why C is correct and D is not.
{ "pile_set_name": "StackExchange" }
Q: Crashing at point where there is seemingly no error I've just whittled out loads of erros and now my code compiles fine, however it always crashes in the createEntity method i made. there is seemingly nothing wrong with it, but could someone help me anyway? Anything to suggest? -(void)createEntityWithX:(int)newEntityX andY:(int)newEntityY withType:(int)newEntityType withWidth:(int)newEntityWidth andLength:(int)newEntityLength atSpeed:(int)newEntitySpeed { Entity tmpEntity; tmpEntity.entityX = newEntityX; tmpEntity.entityY = newEntityY; tmpEntity.entityLength = newEntityLength; tmpEntity.entityWidth = newEntityWidth; tmpEntity.entityType = newEntityType; tmpEntity.entitySpeed = newEntitySpeed; int arrayAmount = [entityArray count]; NSValue *tmp = [NSValue valueWithBytes:&tmpEntity objCType:@encode(struct Entity)]; [entityArray insertObject:tmp atIndex:arrayAmount]; [tmp release]; } A: One or both of two things is wrong here. It's possible that entityArray is not an NSMutableArray, but an NSArray, in which case you're getting an "unrecognized selector" error. After that's fixed, you need to fix your indexing. You can't insert an object into an NSMutableArray at the index corresponding to its count, because the last valid index for insertion is count-1. You should use addObject: to put something at the end of the array: NSValue *tmp = [NSValue valueWithBytes:&tmpEntity objCType:@encode(struct Entity)]; [entityArray addObject:tmp];
{ "pile_set_name": "StackExchange" }
Q: Can't load the In App Purchases when reloading the same scene I have an issue with my In App Purchases manager. I load my scene and can successfully purchase items. I go to a new scene in game and then back to that scene and now it says... `MissingReferenceException: The object of type 'IAPManager' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.`and then points my to this line moneyController = GetComponent<MoneyController>(); Why does it crash at that point? Do I need to add DontDestroyOnLoad or something? I'm not familiar with that or how to use it though. Am I missing something simple? Here are some more code snippets that may or may not prove useful. This code is from a tutorial hence why it's difficult for me to pin point the issue. public static IAPManager Instance{set;get;} private void Awake() { Instance = this; } A: you have to put in DontDestroyOnLoad this way you will not get any error for same. below is the code that you can use. private static IAPManager instance; public static IAPManager Instance { get { if (instance == null) { GameObject o = new GameObject ("IAPManager"); instance=o.AddComponent<IAPManager>(); DontDestroyOnLoad (o); } return instance; } }
{ "pile_set_name": "StackExchange" }
Q: Low exponent attack on RSA public key question is here. determine true or false I think that in the RSA cryptosystem, one should use large private key because of the low exponent attack. Also, In RSA cryptosystem, one should use large public key because of the low exponent attack. Is my thinking right? How much long or big do these key need to be? A: The reason to use a large private key (or rather, not to attempt to use a small private exponent) are given in 5. The reasons to use a large public key are in 1, and have nothing to do with exponent size (private or public). There is no known reason to use a larger public exponent than suggested in 2, and that's uncommon. In RSA: One should use a large enough size $n$ for the public modulus $N$; that's important because anything that factors $N$ will break the RSA instance using that $N$, and the resistance of $N$ to factorization tends to grow with $n$ (for constant number of factors of size proportional to $n$). The bit size $n$ of $N$, with $2^{n-1}\le N<2^n$, is known as the key size, public key size, or public modulus size. Official security recommendations start at $n=2048$. The public exponent $e$ can be fixed to $e=2^{16}+1$, which is most common, compatible, and unobjectionable; or $e=3$ which gives a significantly faster public-key operation (see cautionary note). In modern practice, $e$ is typically a small odd prime fixed and chosen before $N$ and its factors. In any case, $e$ must be odd and at least $3$. The factors of $N$ must be large distinct primes, and not one more than an integer sharing a prime factor with $e$. They must be randomly and secretly generated and combined into their product $N$. Standard practice is to select two primes $p$ and $q$ as about uniformly random primes in range $[2^{(n-1)/2},2^{n/2}]$ with $\gcd(p-1,e)=1=\gcd(q-1,e)$, simplifying to $p\bmod e\ne1$ and $q\bmod e\ne1$ when $e$ is prime; then compute $N=p\,q$. A private exponent $d$ is most commonly secretly computed from $e$ and factors of $N$. The smallest working positive $d$ is $d=e^{-1}\bmod\lambda(N)$ with $\lambda(N)=\operatorname{LCM}(p-1,q-1)$ when $N=p\,q$. It is also common to use $d=e^{-1}\bmod\varphi(N)$ with $\varphi(N)=(p-1)(q-1)$. No attempt should be made to significantly shorten $d$ ("small decryption key") by choosing $e$ or the factors $p$ and $q$ of $N$ for that purpose; that's not possible anyway when following advice in 2 and 3 above. It is known that $d$ shorter than $0.292\,n$ is unsafe; see Dan Boneh and Glenn Durfee, Cryptanalysis of RSA with Private Key $d$ Less than $N^{0.292}$, in proceedings of Eurocrypt 1999. It is unclear what a safe minimum would be; and better speedup is achieved by a common implementation of the private-key function uisng the Chinese Remainder Theorem. The textbook public-key function $x\to x^e\bmod N$ should be used for encryption, and/or the textbook private-key function $x\to x^d\bmod N$ used for signature generation, only when $x$ is essentially random in some large interval (with bit size of its width close to $n$) and not under the control of an adversary; for example, $x$ can safely be a random bitstring of $n-1$ bits, converted to integer from binary, encrypted as $y=x^e\bmod N$, decrypted as $x=y^d\bmod N$, and then considered a shared secret, used in part as an encryption key for a message encrypted using symmetric cryptography; or produced by some appropriate padding technique adapted to the usage (encryption or signature); a recommendable encryption padding is RSA-OAEP; a recommendable signature padding is RSASSA-PSS. Care should be taken that implementations using a private key (decryption, signature generation) or secret data (encryption) can be vulnerable to side-channel or fault attacks. Cautionary note: many uses of textbook RSA in introductory literature, and even in the industry, violate 6 to some degree. There is anecdotal evidence that when making goofs there, choosing very small $e$ (like $3$, or much smaller than $n$) makes things worse; but there is no evidence that $e=3$ is less safe than $e=2^{16}+1$, or that any low public-exponent attack applies, when abiding to 6. A: First note that the key size of RSA is determined by the size of the modulus $N$ denoted $n$. As the modulus is always the same size for both the public key and private key. So this question is probably about the size of the exponent rather than the actual key size. The private key exponent must be large otherwise RSA becomes vulnerable. This is the attack by Dan Boneh and Glenn Durfee , as fgrieu already explained in his answer. Of course if the private exponent is sufficiently small it could also be brute forced by an attacker. When setting the public key exponent to a small value, such as the fourth prime of Fermat ($2^{16} + 1$ or $65537$) and using the standard key pair generation procedures the private key will with a very high probability be large enough, given a high enough key size. Now the modulus and public exponent are considered public knowledge. So there is no good reason to choose a high public exponent to avoid brute force. The public exponent simply needs to be safe within the RSA cryptosystem. Furthermore, a small RSA key, especially one with as few bits as possible, is most efficient when calculating $p^e \bmod N$ (where $p$ is the padded message). So, in conclusion, no, you should not use a large public exponent. The public key size is always the same size as the private key size, so that part of the original question doesn't make sense.
{ "pile_set_name": "StackExchange" }
Q: How to initialize std::array in class definition? Since C++11, it is possible to initialize member variables in class definitions: class Foo { int i = 3; } I know I can initialize an std::array like this: std::array<float, 3> phis = {1, 2, 3}; How can I do this in a class definition? The following code gives an error: class Foo { std::array<float, 3> phis = {1, 2, 3}; } GCC 4.9.1: error: array must be initialized with a brace-enclosed initializer std::array<float, 3> phis = {1, 2, 3}; ^ error: too many initializers for 'std::array<float, 3ul>' A: You need one more set of braces, which is non-intuitive. std::array<float, 3> phis = {{1, 2, 3}};
{ "pile_set_name": "StackExchange" }
Q: How to import CSV files to SQLite3 with python This is my code. import sqlite3 import pandas db = sqlite3.connect('testdb.db') df = pandas.read_csv('testcsv.csv') df.to_sql('testTable', 'db', if_exists='append', index=False) I got the last two lines of code from another article on stackoverflow, but it doesn't work for me. This is the error I get, even after I installed sqlalchemy, because it complained that it wasn't installed. Traceback (most recent call last): File "C:/Users/pitye/PycharmProjects/gradeCalcV2/venv/sqlite.py", line 7, in <module> df.to_sql('testTable', 'db', if_exists='append', index=False) File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\pandas\core\generic.py", line 2663, in to_sql method=method, File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\pandas\io\sql.py", line 503, in to_sql pandas_sql = pandasSQL_builder(con, schema=schema) File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\pandas\io\sql.py", line 577, in pandasSQL_builder con = _engine_builder(con) File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\pandas\io\sql.py", line 564, in _engine_builder con = sqlalchemy.create_engine(con) File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\sqlalchemy\engine\__init__.py", line 479, in create_engine return strategy.create(*args, **kwargs) File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\sqlalchemy\engine\strategies.py", line 54, in create u = url.make_url(name_or_url) File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\sqlalchemy\engine\url.py", line 229, in make_url return _parse_rfc1738_args(name_or_url) File "C:\Users\pitye\PycharmProjects\gradeCalcV2\venv\lib\site-packages\sqlalchemy\engine\url.py", line 291, in _parse_rfc1738_args "Could not parse rfc1738 URL from string '%s'" % name sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'db' I just want to create a table from a CSV file in SQLite. Is this even the right way of doing it, or am I waaay off? A: I think you just have to replace df.to_sql('testTable', 'db', if_exists='append', index=False) With df.to_sql('testTable', db, if_exists='append', index=False)
{ "pile_set_name": "StackExchange" }
Q: Adding quotes around a parameter causes error? I have the following: {exp:email:contact_form charset="utf-8" form_class="customer-email-form" recipients={exp:stash:get name='recipients'} } Notice that the recipients parameter's value is not in quotes. When I put quotes and try to send an email, I get "no recipients" error. However, if I replace the Stash with hard coded email address(es), I need the quotes to make the email form work. Is there something wrong? Or is this expected behavior? A: I believe you're running into problems with the parse order. When you add quotes, recipients becomes a valid parameter but it isn't parsed yet. When you remove the quotes, it becomes an invalid parameter and is ignored. You should be able to add parse="inward" to the contact_form parameters to parse recipients first. {exp:email:contact_form charset="utf-8" form_class="customer-email-form" recipients="{exp:stash:get name='recipients'}" parse="inward" } There is some documentation and examples about this problem here.
{ "pile_set_name": "StackExchange" }
Q: Uso do carácter dois pontos ":" no Python No Python existe o carácter dois pontos :, sendo assim, o que eu entendo deste carácter é que ele é usado em funções def soma(x,y):, comandos condicionais if soma > 100: e para classes class Carro(object):, para indicar o fim do cabeçalho e assim por diante. Entretanto, existe outro propósito para ele alem dos citados anteriormente? Caso haver outro propósito, o dois pontos : se torna algum tipo de operador? Um pequeno exemplo prático do uso do dois pontos : para ilustração: def soma(x,y): return x + y x = input("Valor de x:") y = input("Valor de y:") soma = soma(x,y) if soma > 100: print("Resultado maior que 100") A: Como comentei acima, não acho um tipo de pergunta que ajude muito - mas vamos lá, são quatro usos que estou lembrando agora, e um uso que não acontece que vale a pena mencionar: : indica o início de um bloco. Como você apontou na pergunta, não ssó esses comandos, mas qualquer um que inicie um bloco de código tem um : no final da linha. Nesse sentido ele é parecido com o { de C e linguagens derivadas com a diferença de que nunca é opcional: Em C (ou seus descendentes sintáticos, comoC++, Java, Javascript, PHP, C# , objective C, etc), após um comando de controle de fluxo, em geral é opcional abrir uma chave - você pode colocar uma única expressão (terminada com ;). Em Python sempre é obrigatório o : e mais, sempre é obrigatório que na sequência venha um bloco de código com identação maior do que a da linha em que estava o : - mesmo que você não queria fazer nada nesse bloco (por exemplo, uma cláusula except e que você só queira silênciar um erro. Se quiser um bloco que não faça nada, ele deve conter o comando pass devidamente identado: a = 0 try: a = valor/ valor2 except ZeroDivisionError: pass : é usado na construção de dicionários - como bem lembrou o @IronMan em sua resposta. A sintaxe é parecida que a de dicionários de Javascript - dados = {"chave": "valor", "chave2": "valor2"}. Diciionários também podem ser criados com a chamada direta da função embutida dict, usando-se a sintaxe de chamada de função com argumentos com palavra chave, que dispensa os :: dados = dict(chave="valor", chave2="valor2") - note que nesse caso, a linguagem transforma automaticamente o nome dos parâmetros passados como palavra chave em strings que serão chaves no dicionário. Usando o construtor de dicionário com { }, as aspas são necessárias para indicar que as chaves são strings, e além disso as chaves podem uma grande variedade de objetos de Python, não só strings. Essas são diferenças para o dicionário de Javascript. Mais ainda, a construção com chaves, mas com valores separados por ,, sem pares de chave e valor, criam um outro objeto em Python: os conjuntos (sets): meu_conjunto = {"dado1", "dado2", "dado3"}. É um tipo de objeto bem diferente de um dicionário que só tem em comum com o mesmo o algorítmo para saber se um determinado item faz parte do mesmo ou não (no caso do Python a continência é em relação as chaves, não aos valores). : serve para declarar "fatias" (slices), como lembrou o @Pablo, ao recuperar items de sequências. Praticamente qualquer linguagem moderna permite que se recupere um único item de uma sequência com um número entre colchetes. a = "overflow"; a[0]; -> 'o' - mas Python permite que você especifique [inicio:fim] dentro dos colchetes a = "overflow"; a[1:5]; -> 'verf', ou [inicion:fim:passo]. Ainda esta semana expliquei bem como fatias funcionam nesta outra resposta: Como funciona a atribuição de lista usando intervalo? : pode criar anotações sobre parâmetros de uma função em Python 3.x, de forma opcional. Python é uma linguagem dinâmica, e qualquer parâmetro ou variável sempre fazer referência a qualquer tipo de objeto. No entanto, muitas vezes em sistemas grandes, frameworks, metodologias de trabalho, ou para ajudar ferramentas de teste estático e mesmo IDEs pode ajudar você ter alguma informação sobre o tipo de dados que um parâmetro deveria ser, ou que tipo de parâmetros deveria retornar. Em Python 3 criaram uma sintaxe para "anotations" - Normalmente declaramos uma função assim: >>> def soma2(a, b): ... return a + b ... Mas pode ser feito assim: >>> def soma(a: int, b: int) -> int: ... return a + b ... Essa sintaxe não faz nada por si, só cria uma função quer tem como um de seus atributos um dicionário de nome __annotations__, que armazena as informações colocadas na criação da função: >>> soma.__annotations__ {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>} Essa sintaxe é válida desde Python 3.0, em 2008 - mas não faz nada, nem modifica nenhum comportamento - e os valores depois do : não precisam ser classes, podem ser qualquer expressão válida. Isso não impede que o programador crie um decorador, ou outra forma de analisar o código tanto antes do uso, quanto em tempo de execução para fazer coisas com esses valores anotados. Mas foi somente em 2015, com a PEP 484, que a linguagem declarou uma forma preferencial de usar essas anotações, e ferramentas que auxiliam ou se beneficiam desse uso. Confira a PEP 484 que fala disso. É desnecessário dizer que enquanto os três primeiros usos de : fazem parte do dia a dia de qualquer programador iniciante ou fluente em Python, esse quarto tipo tem uso ainda incipiente e você dificilmente vai encontrar código que use essas marcações. É possível que alguns projetos de grande porte, ou trabalho interno de times, comece a usar anotações depois da PEP 484, em código feito a partir deste ano. : não funcionam, por fim, como lembrou o @ ӝ nos comentários, como parte do operador ternário de if, como acontece nas linguagens derivadas de C. Em C e descententes, funciona: condicao? valor1: valor2 - a expressão em condição é avaliada - se for verdadeira, a expressão toda vale valor1, senão é usado valor2. Em Python, esse if como expressão é escrito por extenso, de uma forma que lembra a linguagem falada: valor1 if condicao else valor2 - nesse caso, a expressão "valor1", como no "?:" de C, só é avaliada se a condição for verdadeira - senão é avaliada a expressão em "valor2".
{ "pile_set_name": "StackExchange" }
Q: How can I make an object render with a wireframe in the game engine? I want it to look like the top image when I press P, so it has those lines around each face. Like this: Not like this: A: You want to create a wireframe material. A quick 'n' dirty way to do generate a wireframe texture is described below: Unwrap your model. If you don't know how to do this simply select everything and press CtrlE > Mark Seam. Press U > Unwrap. Open up a UV/Image editor: Click UVs > Export UV Layout. Remember where you save this image. Press AltO to open a texture, then select the saved image. Tada! You may want to remove the transparency in an image editor if you want your model to be opaque.
{ "pile_set_name": "StackExchange" }
Q: Why is there a vertical asymptote at x = 3 but g(x) does not have a vertical asymptote at x = 3? The question was an explanation for why $f(x)$ has a vertical asymptote at $x = 3$, but $g(x)$ does not. Mention limits within the answer. Perhaps I'm solving them wrong but it looks like there is an asymptote in both. Also I would imagine that limits come into play because the values approach the asymptote at $x = 3$ $$f(x) = \frac{x^2 - 7x + 4}{4x^2 - 4x - 24}$$ $$g(x) = \frac{-2x^2 + 12x - 18}{4x^2 - 8x - 12}$$ A: Hint: Factor everything, and look for any $(x - 3)$ factors. If such a factor is found in both the numerator and denominator so that they cancel, then the limit as $x \to 3$ exists so that the discontinuity at $x = 3$ is a hole, not an asymptote. Otherwise, if the $(x - 3)$ factor is in the denominator but not the numerator, then the discontinuity must indeed be a vertical asymptote.
{ "pile_set_name": "StackExchange" }
Q: Delete duplicate rows from small table I have a table in a PostgreSQL 8.3.8 database, which has no keys/constraints on it, and has multiple rows with exactly the same values. I would like to remove all duplicates and keep only 1 copy of each row. There is one column in particular (named "key") which may be used to identify duplicates, i.e. there should only exist one entry for each distinct "key". How can I do this? (Ideally, with a single SQL command.) Speed is not a problem in this case (there are only a few rows). A: A faster solution is DELETE FROM dups a USING ( SELECT MIN(ctid) as ctid, key FROM dups GROUP BY key HAVING COUNT(*) > 1 ) b WHERE a.key = b.key AND a.ctid <> b.ctid A: DELETE FROM dupes a WHERE a.ctid <> (SELECT min(b.ctid) FROM dupes b WHERE a.key = b.key); A: This is fast and concise: DELETE FROM dupes T1 USING dupes T2 WHERE T1.ctid < T2.ctid -- delete the older versions AND T1.key = T2.key; -- add more columns if needed See also my answer at How to delete duplicate rows without unique identifier which includes more information.
{ "pile_set_name": "StackExchange" }
Q: Do enterprise GWT apps require extra client-server transfers? I'm trying to decide whether to use GWT or manually-written JavaScript. If I use regular JavaScript, the Java app works like this: The client accesses a URL, and the server executes a servlet. The servlet queries a database and forwards the data to a JSP. The JavaScript in the JSP displays the data in a table. From what I've read, the process changes when you use GWT: The client accesses a URL, and the server provides a page with GWT-generated JavaScript. The generated JavaScript creates a table and uses GWT-RPC to tell a servlet to provide data. The servlet queries a database and returns the data to the JavaScript, which displays the data in a table. In the second process, the client accesses the server twice: once to access the URL and once to tell the servlet to provide data. I understand that the second part is performed asynchronously, but it still seems very inefficient. I'm sure I'm missing something fundamental, and I hope someone will set me straight. A: OK, let look at this in terms of efficiency. Yes for the simple case you describe, the client may have to wait slightly longer. In terms of developing a useful site though, you most likely will be doing authentication and wanting to make ajax calls from the middle of your page. You too may want to do layout changes based on user input that are impractical and messy to do in a jsp page. Manually written javascript used to run quite differently in different browsers too, and that was a nice thing about GWT compiling different versions for particular browsers. It may not be as true today but you should consider browser differences if you need to target more than one. So my answer in terms of efficiency is that no GWT is not the most efficient for the simplest cases, but if you need to make a more complex web-application and want to avoid browser issues, then developing in Java is easier and simpler to maintain. I actually am returning a .jsp page on my first call, and then the GWT javascript get bootstrapped from there (instead of using an html page). There isn't any real reason you couldn't include whatever data you wanted with the jsp page, except that if your requirement is so simple, keep it that way as for sure there will be some cost in bootstrapping the GWT code. In my case, I need to do authentication first, and then data than gets returned depends on their credentials, and then a load of ajax calls depending on what the information the user needs. Developing in javascript by hand would be a nightmare.
{ "pile_set_name": "StackExchange" }
Q: Javascript confusion var allRapidSpells = $$('input[value^=RSW]'); Can anyone tell me what that does? A: I would venture to guess that you're using MooTools, a JavaScript framework. The $$() function is used to select an element (or multiple elements) in the DOM. More specifically, the $$('input[value^=RSW]'); syntax is selecting all input elements whose value attribute starts with RSW. Other attribute selectors include: = : is equal to *= : contains ^= : starts-with $= : ends-with != : is not equal to ~= : contained in a space separated list |= : contained in a '-' separated list Edit: It looks as though Prototype, another JavaScript framework, uses the same syntax.
{ "pile_set_name": "StackExchange" }
Q: How can I shortcut an expression who's repeating? I need help to know if can i use #definie for commands in batch or anything else like shortcuts for example i have del "C:\Games" so i definie "C:\Games" as {output} so I wrote: @echo off #Definie output "C:\Games" Del "{output}" But it didn't work for me my problem is, when i create a script, many things are repeating and sometimes i get error this is a part of the script https://i.stack.imgur.com/4q0j8.png as u can see in the pic, the yellow is repeating many times can u suggest me a shortcut, i mean like i difinie the yellow as {output} and i write the yellow just one time and then i replace all the yellows with {output} This is what I've tried later in another exemple @echo off From=[C:\Users\Easynote-TE69HW\Desktop\Ectended fromto\From] del /f /q from A: @echo off set "From=C:\Users\Easynote-TE69HW\Desktop\Ectended fromto\From" rd /s /q %from% The second line sets (defines) a variable named From. (Note: variable names are case insensitive) the third line uses that variable (%from%) with the RD command (Remvove Directory). The switch /s works recursive (delete all subdirectories), /q doesn't ask for confirmation. See the helpfile for any command with the switch /? (e.g. set /? or rd /?). Also SS64 should be extremely helpful (a complete list of possible commands and their description)
{ "pile_set_name": "StackExchange" }
Q: Powershell 3.0: Searching specific file names and sending the names to a .txt file Here is my code: Get-ChildItem 'R:\Source\Path' | ForEach-Object { $_.Name -notlike '*condition*' } > 'R:\Destination\Path\File.txt' The code is working to some extent. Except instead of copying the names of the files to the destination, it is instead writing either true or false into the text file depending on the status of the condition. So where I would expect a .txt file list of names, instead I have something that looks like: True True False True False False ...and so on ... What did I do wrong? A: To filter your output, use Where-Object instead of ForEach-Object: Get-ChildItem |Where-Object {$_.Name -notlike "*.zip"} > output.txt To get the full path to the file and nothing else, use Select-Object -ExpandProperty: Get-ChildItem |Where-Object {$_.Name -notlike "*.zip"} |Select-Object -ExpandProperty FullName > output.txt or change the logic inside your original ForEach-Object scriptblock to actually act on the result of -notlike: Get-ChildItem |ForEach-Object { if($_.Name -notlike "*.zip"){ $_.FullName } } > output.txt
{ "pile_set_name": "StackExchange" }
Q: is default backgroundColor or not? I want know programatically, my TextView has default backgroundColor or changed. for example: if (myTextView.backgroundColor == defaultColor){ NSLog(@"default"); } else { NSLog(@"changed"); } I have one idea: UITextView *etalon = [UITextVew new]; if (myTextView.backgroundColor == etalon.backgroundColor){ NSLog(@"default"); } else { NSLog(@"changed"); } But I think it's not quite right. Anybody have better ideas? A: Try this - const float* color1 = CGColorGetComponents(myTextView.backgroundColor.CGColor); const float* color2 = CGColorGetComponents(etalon.backgroundColor.CGColor); if(color1 == color2) { NSLog(@"Default"); } else { NSLog(@"Changed"); } A: You should use [myTextView.backgroundColor isEqual:etalon.backgroundColor] in order to make a color compare. Also be careful because different color spaces are going to give you a not equal result.
{ "pile_set_name": "StackExchange" }
Q: delegate.replace() is not working on Array List Grails 2.3.8 Here's my code in order to replace HTML tags: def str String.metaClass.removeHtml { def removeThisHtml = [ [htmlCode: "&#96;", value: "`"], [htmlCode: "&#64;", value: "@"], [htmlCode: "&amp;", value: "&"], [htmlCode: "&#92;", value: "\\"], [htmlCode: "&quot;", value: '"'], [htmlCode: "&#39;", value: "'"], [htmlCode: "&lt;", value: "<"], [htmlCode: "&gt;", value: ">"] ] removeThisHtml.each { element -> str = delegate.replace(element.htmlCode, element.value) } return str } And here is the code form my controller: def getProjectLists() { def currentUser = springSecurityService.currentUser def kups = ([['name':'<b>Sample 1</b>'.removeHtml()],['name':'<b>Sample 2</b>']]) render kups as JSON } My expected output is: < b >Sample1< / b> Sample2 But the output is: Sample1 Sample2 A: I think what you really want is to escape HTML - display HTML tags and entities, so the function's name removeHtml is a bit misleading, escapeHtml would fit it better. Generally I recommend not to do things like this by your self as others have already done that and most likely do it better. For example Apache Commons has an StringEscapeUtils.escapeHtml method. String.metaClass.removeHtml { return org.apache.commons.lang.StringEscapeUtils.escapeHtml(delegate) }
{ "pile_set_name": "StackExchange" }
Q: How to add an async "await" to an addrange select statement? I have a function like this: public async Task<SomeViewModel> SampleFunction() { var data = service.GetData(); var myList = new List<SomeViewModel>(); myList.AddRange(data.select(x => new SomeViewModel { Id = x.Id, DateCreated = x.DateCreated, Data = await service.GetSomeDataById(x.Id) } return myList; } My await isn't working as it can only be used in a method or lambda marked with the async modifier. Where do I place the async with this function? A: You can only use await inside an async method/delegate. In this case you must mark that lambda expression as async. But wait, there's more... Select is from the pre-async era and so it doesn't handle async lambdas (in your case it would return IEnumerable<Task<SomeViewModel>> instead of IEnumerable<SomeViewModel> which is what you actually need). You can however add that functionality yourself (preferably as an extension method), but you need to consider whether you wish to await each item before moving on to the next (sequentialy) or await all items together at the end (concurrently). Sequential async static async Task<TResult[]> SelectAsync<TItem, TResult>(this IEnumerable<TItem> enumerable, Func<TItem, Task<TResult>> selector) { var results = new List<TResult>(); foreach (var item in enumerable) { results.Add(await selector(item)); } return results.ToArray(); } Concurrent async static Task<TResult[]> SelectAsync<TItem, TResult>(this IEnumerable<TItem> enumerable, Func<TItem, Task<TResult>> selector) { return Task.WhenAll(enumerable.Select(selector)); } Usage public Task<SomeViewModel[]> SampleFunction() { return service.GetData().SelectAsync(async x => new SomeViewModel { Id = x.Id, DateCreated = x.DateCreated, Data = await service.GetSomeDataById(x.Id) } } A: You're using await inside of a lambda, and that lambda is going to be transformed into its own separate named method by the compiler. To use await it must itself be async, and not just be defined in an async method. When you make the lambda async you now have a sequence of tasks that you want to translate into a sequence of their results, asynchronously. Task.WhenAll does exactly this, so we can pass our new query to WhenAll to get a task representing our results, which is exactly what this method wants to return: public Task<SomeViewModel[]> SampleFunction() { return Task.WhenAll(service.GetData().Select( async x => new SomeViewModel { Id = x.Id, DateCreated = x.DateCreated, Data = await service.GetSomeDataById(x.Id) })); }
{ "pile_set_name": "StackExchange" }
Q: How to change the system font inter-letter spacing? I set my system font to 'aakar medium' in gnome-tweaks. Now the letters in a word are a bit closer to each other. There's no bug reported for this issue. Is there anything I can do to change the kerning, or inter-letter spacing? A: Unfortunately, this may just be a feature of the font itself in your gnome environment. I believe it is possible (at least on certain Mac environments) to increase letter/font spacing by editing your gnome.css (or, maybe gtk.css) stylesheet but I am not clear on how this method works or if it is still possible in the latest release of gnome/gtk. Try resizing the terminal or adjusting your desktop resolution to see if the problem persists.
{ "pile_set_name": "StackExchange" }
Q: One click SQL server /IIS installation I would like to distribute web application in asp.net / SQL server to end users, so they can install it on their machines locally). In order to do this I need them to install SQL server \ IIS, which seems overly complicated for end users. Any suggestions on how to do it best? A: The Microsoft Web Platform Installer makes it pretty easy to install IIS and SQL Server on your local machine. You would likely have to provide written instructions to get it and install them but it makes it pretty easy. Here is a link: http://www.microsoft.com/web/downloads/platform.aspx
{ "pile_set_name": "StackExchange" }
Q: Question about the matrix cookbook I've been learning matrix calculus by myself, and sometimes use this as a quick references: https://www.math.uwaterloo.ca/~hwolkowi/matrixcookbook.pdf. I got confused regarding two equations in this book. Eq.38 states that $\partial(ln(det(X)))=Tr(X^{-1}\partial{X})$. This is the equation that I've been using often recently. However, I just noticed that the other equation, Eq.51, states that $\frac{\partial\ln|det(X)|}{\partial{X}}=(X^{-1})^{T}$. I can observe some differences between the two equations. E.g., Eq.38 is about partial derivative wrt some parameters that are arguments of $X$ while Eq.51 seems to be about the derivative wrt to the matrix $X$. In addition, Eq.51 involves $|det(X)|$ while eq(38) involves only $det(X)$. Still, I think I haven't appreciated the difference between the two. Can anyone help? Thanks. A: A way to interpret this is that the equation $$ \partial \ln |\det X| \;\; =\;\; Tr \left (X^{-1}\partial X\right ) $$ is expressing the notion of a directional derivative where we have the inner product of the derivative of $\ln |\det X|$ in the direction of $\partial X$, seen as a tangent vector. Since the Euclidean inner product for matrices is given by $\langle A,B\rangle = Tr (A^TB)$, we can interpret this fully as saying that the derivative of the function is just given by the transpose of the expression inside the trace which is not part of the directional derivative. In other words, we precisely have that $$ \frac{\partial \ln |\det X|}{\partial X} \;\; =\;\; \left (X^{-1}\right )^T. $$ It's tempting to try to unravel the derivative in terms of the quantity $\partial X$ on the right hand side, but it's best to think of this as a dot product between the derivative of the function and some other vector.
{ "pile_set_name": "StackExchange" }
Q: GWT I18N on the server side What is the best way to implement GWT Server Side Internationalization? Use native Java properties files (not sure how to read and how to locate the right language file) (unicode string need to be ASCII encoded) Use GWTI18N.java - GWT module which gives you seamless use of GWT I18N on both the client and the server and uses "java.lang.reflect.Proxy method" Use Kotori I18N - ... Other ideas? How can I find and pass localization from client to sever? On the server side I have an Servlet which still doesn't use any GWT dependant source, is it better not to do so? A: I found this solution and it looks very good gwt-i18n-server - Provides a simple support of gwt i18n feature on the server side The aim is to permit to the GWT developer to use their Constants and Messages interfaces on the server side (See internationzation). The implementation is based on java reflect api. It loads the properties files from the classpath (same folder than the interface). It supports Constants, ConstantsWithLookup, Messages (plural too). The licence is LGPL. Client current locale can be found this way: LocaleInfo.getCurrentLocale().getLocaleName()
{ "pile_set_name": "StackExchange" }
Q: Which verse is the heart of Surah Ya-Sin? As it is relatively considered as a famous issue (that Surah Ya-sin is the heart of Quran), and as a narration, it is quoted that Imam Sadiq (a.s.) said: Everything has a heart, and surah Ya-Sin is the heart of the Quran. صدوق، محمد بن على‏، ثواب الاعمال و عقاب الأعمال So, I was wondering which verse of Surah Ya-Sin is considered as the heart of this Surah. A: Although the statement Everything has a heart, and surah Ya-Sin is the heart of the Quran is properly documented, what you are asking is not. Let me try to give an answer with argument. Coming to my argument, since Yasin is already called a heart, it doesn't have to have its own heart. But there is something called the deepest part of the heart, and by Allah, I believe the deepest part of this heart is the last two verses taken together: 36.82 Verily, His Command, when He intends a thing, is only that He says to it, "Be!" and it is! 36.83 So Glorified is He and Exalted above all that they associate with Him, and in Whose Hands is the dominion of all things, and to Him you shall be returned. These two verses are indeed very profound in meaning, and this is the primary message of the whole Quran. I expect my argument to be agreed upon. Jazak Allah Khair.
{ "pile_set_name": "StackExchange" }
Q: File storage in azure error handling with python I wrote a genecric function to upload files into azure storage,, but could not figure out two things.. How to check whether the upload was successful or not How to check the progress(the azure function takes a boolean parameter progress callback but I could not figure on how to use it) Here is the function that I wrote: def upload_files_to_azure(share, directory, path_of_file): """ Function to upload file to the azure storage, in a particular share into a particular directory :param share: name of share of azure storage :param directory: directory name inside azure storage :param path_of_file: the path of file to be uploaded :return: status of file uploaded """ file_service = FileService(account_name=ACCOUNT_NAME, account_key=ACCOUNT_KEY) file_service.create_file_from_path( share, directory, # We want to create this blob in the root directory, so we specify None for the directory_name 'test.sql20180103.tar.gz', path_of_file, content_settings=ContentSettings(content_type='application/x-gzip')) return A: 1.How to check whether the upload was successful or not. If you are using Azure Storage SDK , you could check if any exceptions exist. If the operation is successful, you could see your uploaded files on the portal. If you are using Azure Storage REST API, you could check the response message and status code.(200 is success) 2.How to check the progress(the azure function takes a boolean parameter progress callback but I could not figure on how to use it) I searched the Azure Storage Python SDK and find the progress_callback arguments in the create_file_from_path method. progress_callback func(current, total) You need to know the size of your file than you could check the progress of the operation. You could find the usage of it from here. Callback for progress with signature function(current, total) where current is the number of bytes transfered so far and total is the size of the file, or None if the total size is unknown. Hope it helps you.
{ "pile_set_name": "StackExchange" }
Q: Using recursion to find a 2D maze path. Seg Faulting. C I am having trouble finishing this program. The assignment is to use recursion to find a path through a maze composed of X's and O's. The path one can go through is designated by the O's The maze is stored as a text file. Here is a sample maze: XOXXXXXX XOXXXXXX XOOOOXXX XXXXOXXX XXXXOOXX XXXXXOXX XXXXXOOO XXXXXXXO And here is my attached code. I am attatching all of my code, but I would not like to be told exactly how to do it, I am here to learn :-).I do believe my problem is with not accounting for the same O i just looked for, but im not 100% sure. Thanks!! #include <stdio.h> #include <stdlib.h> #include <string.h> int find_path(char maze[8][8], int coorx, int coory); int main(int argc, char *argv[]) { char maze[8][8]; int i=0,j=0; FILE *fp; fp = fopen(argv[1], "r"); for(i=0;i<9;i++) for(j=0;j<9;j++) fscanf(fp,"%c",&maze[i][j]); fclose(fp); printf("%c", maze[2][3]); return 0; } int find_path(char maze[8][8], int coorx, int coory) { //if((maze[coorx][coory]!= 'O') && (coorx >=0) && (coorx < 8) && (coory >=0) && //(coorx < 8)){ if(find_path(maze, coorx + 1, coory) == 'O'){ printf("(%d,%d)",coorx, coory); } else if(find_path(maze, coorx - 1, coory) == 'O'){ printf("(%d,%d)",coorx, coory); } else if(find_path(maze, coorx, coory + 1) == 'O'){ printf("(%d,%d)",coorx, coory); } else if(find_path(maze, coorx, coory - 1) == 'O'){ printf("(%d,%d)",coorx, coory); } return 0; } A: find_path doesn't have a clear base case, since the if at the beginning is commented out. The very first thing it does, is call itself again with cell to the right. And the first thing that call does, is call itself again, with the cell to the right of that. There's nothing to stop it from just falling right off the end of the array, at which point it's just dumb luck you haven't caused missiles to launch somewhere. Even if that weren't the case, there's nothing keeping it from getting stuck between a cell with a wall to the right, and the cell just to the left of it. You try to go right, but can't, so you go left. Next step, you can go right again, so you do. Repeat for all eternity (or at least til you eat up your stack).
{ "pile_set_name": "StackExchange" }
Q: Would "endless scroll" work with things that are editable? I'm working on this application that's sort of like a blog. I'm thinking about doing a thing where the user can scroll through all their posts using an "endless scroll" functionality like Google Reader has. Here's the problem I'm anticipating... if the user clicks on a post to edit it, that will take him/her to a new page. Soon enough they're going to want to go back to the scrolling view and they'll probably want to return to the same place they were at when they clicked "edit." I imagine they'll be startled if they don't see the same collection of posts that was there when they clicked "edit." They aren't going to want to go back to the beginning of the scroll-while-progressively-loading-posts process and have to do it all over again. I had the thought of storing the IDs of the accumulated posts and the scroll position in the session and reconstructing everything when the user returned. But what if they had scrolled through dozens or hundreds of posts before they clicked "edit?" That could be too much data to load in a reasonable amount of time. Then there's the idea of using a dialog instead of going to a new page for editing, but that introduces a whole other set of problems. E.g., what's supposed to happen if the user tries to open the dialog in a new tab? So maybe this isn't a great setting for "endless scroll." Maybe conventional paging is way to go. Has anyone implemented something like this? Any thoughts? A: Beware: I find 'endless scroll' annoying. It messes up the scroll-thumb as an indicator of position, with surprise changes and pauses. At some point it will become unwieldy -- the 'hundreds of posts' scenario you mention -- unless there's even more complexity (discarding items off the top when you're deep, offering random access). But, consider how Google Reader, the example you cite, deals with the problem: you rarely navigate away from the endless-scroll window. Some per-item operations (tagging) happen inline, but most links open in another window to sidestep the issue entirely. If you go off to change settings, then 'return to google reader' your scroll-position returns to the top -- so maybe it's not that big of a deal. (Though notably: when you return, the extent of the list is all the previously-loaded items -- not the original just-top-loaded. More on this below.) I would consider non-modal in-place editing -- the edit box inserts in the scroll area, atop or adjacent to the item being edited. Or, if the one key bit of continuity is you want to send people back to view exactly the item they just edited, make sure the 'return to list' link includes a pointer to the one place the view should auto-roll-to (for example, in the #fragment anchor). Further, if either your code or the browser have effectively cached the hundreds to preceding items (as I noted above Google Reader appears to do), the roll-forward should be instantaneous, with no reloading necessary.
{ "pile_set_name": "StackExchange" }
Q: Unable to get distinct results for queryset here is models.py class Product(models.Model): brand = models.ForeignKey(Brand , related_name='products') category = models.ForeignKey('Category', verbose_name='categories', related_name='products' , default='') parent = models.ForeignKey('self' , related_name = 'children' , null=True , blank=True) title = models.CharField(max_length=500) class StoreProduct(models.Model): product = models.ForeignKey('products.Product') category = models.ForeignKey('products.Category') store = models.ForeignKey('Store') class Store(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL , null=True , blank=True) StoreName = models.CharField(max_length=50 , default = '') items = models.ManyToManyField('products.Product', through=StoreProduct) brand = models.ForeignKey('products.Brand' , null=True , blank=True) City = models.CharField(max_length=50 , default = '') Area = models.CharField(max_length=50 , default = '') Address = models.TextField(max_length=500) MallName = models.CharField(max_length=50 , null=True , blank=True) slug = models.SlugField(blank=True ,unique=True) here is views.py queryset = StoreProduct.objects.all().distinct() Multiple store can contain the same product and but they should appear once on the product grid page.Distinct query is not working.What can i do to show distinct values in the above case?Thanks in Advance A: If you are using PostgreSQL, specify the level of distinction: queryset = StoreProduct.objects.distinct('product') you can also use it in conjunction with values(), order_by(), etc: queryset = StoreProduct.objects.values('product').distinct() I will suggest the following as solution but not the solution; either you choose PosgreSQL as database, specially that the newest Django version is coming with more built-in support for complex data structure, or you try make you own filter as follow (but in case you have large dataset this will be really bad): store_product_id_list = StoreProduct.objects.values('product').distinct() store_product_list = [] for obj in store_product_id_list: store_product_obj = StoreProduct.objects.filter(product_id=obj.get('product')).first() store_product_list.append(store_product_obj) Check distinct for more examples
{ "pile_set_name": "StackExchange" }
Q: How to animate movement of 3d models in Mapbox GL JS The 3d model example in the Mapbox GL JS docs made me wonder how I could animate the movement of 3d vehicles across a map (e.g. Uber's AVS demo and Cesium). I tried adapting the 3d model example code by removing the current 3d model, creating a new one and then adding that. However this cycle is much too slow for smooth animation: const moveObject = () => { map.removeLayer('3d-model'); modelOrigin = incrementCoords(modelOrigin); modelTransform = createModelTransform(modelOrigin); const customLayer = createCustomLayer(modelTransform); map.addLayer(customLayer); }; Ideally I'd like to see smooth animation - like in the AVS demo or the various 'animate a line/point/marker' examples in the Mapbox GL JS docs. A: For a true 3D use case like in those demos, you'd be better off with a 3D tool rather than Mapbox GL JS. It's not a 3D renderer or true 3D so that's the reason you're not getting what you want. As for a Mapbox tool, the best option would be the Maps SDK for Unity. There's an example in the Unity SDK of how to replace a 3D building with a custom model. You can find it here: https://docs.mapbox.com/unity/maps/examples/replace-features/
{ "pile_set_name": "StackExchange" }
Q: Trying to add data from parse to an NSMutableArray in IOS So, I am able to successfully perform a query of my parse database. This query matches the logged in user with all objects that have the logged in user in the key user. The object I'm querying has keys "email" "firstName" "lastName" "friendUserName" and "phoneNumber" I would like to be able to store all the phone numbers into a mutable array named phoneNumbers. The code I am trying to use to do this is. int i=0; for (PFObject *object in objects) { NSLog(@"%@", objects[i]); phonenumber = object[@"phoneNumber"]; NSLog(@"%@", phonenumber); [phoneNumbers[i] addObject:phonenumber]; NSLog(@"%@", phoneNumbers[i]); i=i+1; } When I run this code the output for the code NSLog(@"%@", phoneNumbers[i]); comes out a null both times. All other outputs are as expected. A: The following should work for you: NSMutableArray *phoneNumbers = [NSMutableArray new]; for (PFObject *object in objects) { NSLog(@"%@", object); // Assuming your phone numbers are stored as strings - use a different data type if necessary NSString *phoneNumber = object[@"phoneNumber"]; NSLog(@"%@", phoneNumber); [phoneNumbers addObject:phoneNumber]; } NSLog(@"%@", phoneNumbers); If you're just adding items to the end of a mutable array, you don't need to worry about the index of the items. The place you were going wrong was when trying to add the object to your array. You were doing this: [phoneNumbers[i] addObject:phonenumber]; Which is actually saying "fetch the object at index i in the phoneNumbers array, and tell it to add the phone number object". However, presumably your array is empty or not initialised, which means addObject will be sent to a nil object and so not have any effect. Instead, you simply need to tell the phoneNumbers array itself to add the object.
{ "pile_set_name": "StackExchange" }
Q: Tomcat 8 enable debug logging to list unneeded jars When starting Tomcat 8 on Arch Linux ARM I get the following warning: INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.` I already modified ${catalina.home}/logging.properties like described here: How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs? I changed some logging levels from INFO to FINE, uncommented "org.apache.jasper.compiler.TldLocationsCache.level = FINE" and added "org.apache.jasper.servlet.TldScanner.level = FINE". So the end of the file now looks the following: org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = FINE org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.org.apache.juli.AsyncFileHandler org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = FINE org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.org.apache.juli.AsyncFileHandler org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].level = FINE org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].handlers = 4host-manager.org.apache.juli.AsyncFileHandler # For example, set the org.apache.catalina.util.LifecycleBase logger to log # each component that extends LifecycleBase changing state: #org.apache.catalina.util.LifecycleBase.level = FINE # To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE org.apache.jasper.servlet.TldScanner.level = FINE But I still get the warning at startup and not the unneeded JAR's paths. What's wrong? A: Try debugging for everything by: Adding this to the end of your logging.properties file located in {CATALINA-HOME}/conf: #To see the most detailed level of logging for all classes, uncomment the following line: org.apache.catalina.level=FINEST Restart Tomcat Run the following from Terminal to get a list of jars that need to be skipped (courtesy of @joseph-lust on this post): egrep "No TLD files were found in \[file:[^\]+\]" {CATALINA-HOME}/logs/catalina.out -o | egrep "[^]/]+.jar" -o | sort | uniq | sed -e 's/.jar/.jar,\\/g' > ~/skips.txt Open skips.txt in your user home directory Add this list to {CATALINA-HOME}/conf/catalina.properties after the following line: org.apache.catalina.startup.TldConfig.jarsToSkip= Make sure to remove/comment out this when you are done to prevent your log files from growing too large I am still not sure why this happens, as it seems to work for most to uncomment the TldLocationsCache line. A: An easier way, in step 1 of the above post, instead of enabling debugging for everything, limit to org.apache.jasper: Use this: org.apache.jasper.level = FINEST Instead of this: org.apache.catalina.level=FINEST
{ "pile_set_name": "StackExchange" }
Q: fork() and wait() in c while loop? I have this small program in c and I am trying to understand how it works, it is a simple while loop that uses fork() and wait() to print out a few lines on the command line, I have commented to the best of my ability what I think is happening for (i = 1; i <= 3; i++) /*simple while loop, loops 3 times */ { pid = fork(); /*returns 0 if a child process is created */ if(pid == 0){ /*pid should be a 0 for first loop */ printf("Hello!\n"); /*we print hello */ return (i); /*will this return i to the parent process that called fork? */ } else { /*fork hasn't returned 0? */ pid = wait(&j); /*we wait until j is available? */ printf("Received %d\n", WEXITSTATUS(j)); /*if available we print "received (j)" */ } } This program is supposed to print: Hello! Received 1 Hello! Received 2 Hello! Received 3 When one of the child processes returns i does the parent process wait for it as &j? This is really confusing me, any help would be greatly appreciated. A: In each iteration of the loop fork() creates a child process. The child process prints Hello! and returns i to the system. The parent process blocks on wait() until child finishes execution. j will contain the value that the child process returned to the system.
{ "pile_set_name": "StackExchange" }
Q: Java connection to Sql server with jtds error I use this code to make a connection with Sql server and i get that error when i use Class.forName(driver) it connect correctly but i prefer to use DataSourse. static final BasicDataSource dataSource = new BasicDataSource(); static { dataSource.setDriverClassName("net.sourceforge.jtds.jdbc.Driver"); dataSource.setUrl("jdbc:jtds:sqlserver://Mypc/Mydb;instance=SQLEXPRESS;"); dataSource.setUsername(""); dataSource.setPassword(""); } public static void main(String[] args){ try{ dataSource.getConnection(); } catch (SQLException ex){ System.out.println(ex); }} public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } and i get this Exception in thread "main" java.lang.AbstractMethodError at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833) at org.apache.commons.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:918) at org.apache.commons.dbcp2.PoolableConnection.validate(PoolableConnection.java:283) at org.apache.commons.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:357) at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2307) at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2290) at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2039) at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533) A: You have to add validationQuery="select 1" to your dataSource dataSource.setValidationQuery("select 1");
{ "pile_set_name": "StackExchange" }
Q: iOS SWReveal sidebar with links to Detail Segue My iOS application is based on John-Lluch's SWRevealViewController to get sidebar navigation. I have ran into a navigation problem that I don't know how to solve. I want one of the menu items to lead to a page that doesn't contain a sidebar but a back button instead. (The other menu items leads to pages where the sidebar can be opened). To get a back button on a view I need to use a Show Detail Segue, but I also need a navigation controller "somewhere" for the back button to show up. (I don't mean that I need a navigation controller AFTER the segue - I have that already - but I need it somewhere before). Have someone used SWRevealViewController in this way or know how to achieve this? "Where" should I place a navigation controller? Thanks! A: The only working solution I came up with was to use a Category on UIView, that could do my Detail Segues. @interface UIViewController (SidebarView) (void)setupSidebarWithGestureRecognizer:(BOOL)useGestureRecognizer; (void)openSettingsPage; (void)openAboutPage; @end and the .m-file's code for openAboutPage: /* This method is called by the sidebar. If the sidebar opens the settings page from itself, the back button * doesn't know where it should point. This method opens the about menu when the sidebar tells it to, and the back button * is pointing to the home page. */ - (void)openAboutPage { UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; UIViewController *about = [storyboard instantiateViewControllerWithIdentifier:@"About"]; [self.revealViewController rightRevealToggleAnimated:YES]; [self.navigationController pushViewController:about animated:NO]; self.navigationController.navigationItem.title = @"About"; } and the setupSideBarWithGestureRecognizer... method - (void)setupSidebarWithGestureRecognizer:(BOOL)useGestureRecognizer { SWRevealViewController *revealViewController = self.revealViewController; if (revealViewController) { UIBarButtonItem *sidebarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"reveal"] landscapeImagePhone:[UIImage imageNamed:@"reveal"] style:UIBarButtonItemStylePlain target:self.revealViewController action:@selector(rightRevealToggle:)]; self.navigationItem.rightBarButtonItem = sidebarButton; if(useGestureRecognizer) { [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer]; } } } Then for each page I want to show a sidebar, I just call [self setupSidebar:YES]; in the viewWillAppear method of that view controller.
{ "pile_set_name": "StackExchange" }
Q: Get several buttons' ID with single method I'm building a program with C# in Windows Forms, and the following question came to me. I have several buttons in my form and when any of them is clicked, I want to be able to store its ID in a single variable that will handle only one ID at a time. I already have a method that does this, but the fact is I don't want to call this method from the event handler of each button: button1_Click(object senders /* ... yada yada ... */) Is there a way how I can simplify this with a single method? Is it even possible? A: You don't need many Click event handlers for your buttons, just 1 is enough: private void buttons_Click(object sender, EventArgs e){ Button button = sender as Button; //do something with the clicked button //... }
{ "pile_set_name": "StackExchange" }
Q: Backing up logs I've been looking at my site logs recently. I have the limit of logs set to 10,000. The problem is, due to the amount of traffic we get, that number will only represent, at best, half a day of logs. Most of these are ether from access denied (I'm guessing spam bots trying to create nodes) or page not founds. The rest are items from custom modules I've built that I use to monitor how those modules are functioning (Like a notification that a queue is being run, or nodes are being created, etc.). I've toyed with the idea of bumping the log messages to keep up to 100,000 or 1,000,000, but I'm not sure if this will cause performance issues or if it will drastically increase the size of my db. Ultimately though, that would only really be a band-aid at best. As it would be nice to be able to keep a longer track of error messages, say weeks or months, so that I can further analyze what my site is doing, what areas need to be improved, etc. Is there any way to create a back up of log files so I don't loose them forever once they hit that ceiling? A: I believe it's a best practice to not enable the core Logging module for Production Drupal websites (eg, outside of your development environment) and to setup server (host) based logging -- or offload the logging to a remote service. See the Syslog documentation page. Which is what I mean by "host based logging". The Syslog module logs events by sending messages to the logging facility of your web server's operating system. Syslog is an operating system administrative logging tool that provides valuable information for use in system management and security auditing. Most suited to medium and large sites, Syslog provides filtering tools that allow messages to be routed by type and severity. It is not suitable for shared hosting environments. It might not be as user friendly as Database Logging but will allow you to see logs and troubleshoot if your site is not accessible. Because the Database logging module writes logs to the database it can slow down the website. By using Syslog you can improve the performance of the site. An example of a remote log is Redis Logging, there are numerous other 3rd party logging modules. EDIT A common practice for webservers is to Rotate Logfiles which builds an archive of compressed logfiles after your logfile has accrued to a certain size or after X days. By using Syslog you can configure your webserver to then rotate logfiles.
{ "pile_set_name": "StackExchange" }
Q: What happens to a single quark in lattice QCD simulations? I understand that if a pair quark/antiquark, out of the vacuum, tries to separate then the energy increases, another pair is produced, and we finish with two mesons or generically two hadron jets. But in numerical simulations we can just put a single quark and calculate the field, can we? What does it happen, does the total energy diverge? Or does it increases up to, say, some "constituient" mass? A: As usual with these things, the presence of QFT and a non-Abelian gauge theory makes life hard, so let's take the prototypical theory that we can actually calculate with easily: Maxwell's equations. The question is then something like "what happens if I put a single electron in a (classical) lattice simulation?". Immediately, one realises that this question is nonsense because Maxwell's equations only define the time evolution of physical states, which in this case implies things that satisfy Gauss' law (which is a constaint!): $$\nabla \cdot E = \rho.$$ In other words, in a simulation one must start with a physical state before one can run it. The Gauss constraint can be solved in this case, and gives the obvious $1/r^2$ decaying $E$ field. At this point, we can zoom back out to QCD, and think about what changes. Solving for the Gauss constraint (i.e. finding an element of the physical Hilbert space) is now highly non-trivial, but heuristically we can have a guess at what might go wrong. The basic problem (as Scott Carnahan points out in the comments) is anti-screening. The colour field self-interacts and gets stronger at larger $r$ --- so the total energy diverges, which does not correspond to any element of the physical Hilbert space. Incidentally, this general problem of needing to solve a constraint equation before being able to start a simulation is quite hard, and numerically one has to be quite clever to avoid instabilities --- many time evolution codes are only stable if you start them with things that satisfy the gauge constraints. Apart from gauge field simulations, simulations of GR also have this problem. A: The total energy diverges, but you can't simulate a single static colored source because this conflicts with periodic boundary conditions. You need to have the box color neutral. The easiest way to do this is to put a color source and antisource far apart, and this was the situation in the earliest lattice QCD simulations. The color fields in these simulations run in a narrow tube from the source to the antisource. The energy diverges as a linear function of the separation, and the coefficient of the divergence is the QCD string tension. In a simulation with dynamical quarks, quarks will pop out of the vacuum to screen the two sources, so that they will be noninteracting at long distances.
{ "pile_set_name": "StackExchange" }
Q: How does one do a Type-III SS ANOVA in R with contrast codes? Please provide R code which allows one to conduct a between-subjects ANOVA with -3, -1, 1, 3 contrasts. I understand there is a debate regarding the appropriate Sum of Squares (SS) type for such an analysis. However, as the default type of SS used in SAS and SPSS (Type III) is considered the standard in my area. Thus I would like the results of this analysis to match perfectly what is generated by those statistics programs. To be accepted an answer must directly call aov(), but other answers may be voted up (espeically if they are easy to understand/use). sample.data <- data.frame(IV=rep(1:4,each=20),DV=rep(c(-3,-3,1,3),each=20)+rnorm(80)) Edit: Please note, the contrast I am requesting is not a simple linear or polynomial contrast but is a contrast derived by a theoretical prediction, i.e. the type of contrasts discussed by Rosenthal and Rosnow. A: Type III sum of squares for ANOVA are readily available through the Anova() function from the car package. Contrast coding can be done in several ways, using C(), the contr.* family (as indicated by @nico), or directly the contrasts() function/argument. This is detailed in §6.2 (pp. 144-151) of Modern Applied Statistics with S (Springer, 2002, 4th ed.). Note that aov() is just a wrapper function for the lm() function. It is interesting when one wants to control the error term of the model (like in a within-subject design), but otherwise they both yield the same results (and whatever the way you fit your model, you still can output ANOVA or LM-like summaries with summary.aov or summary.lm). I don't have SPSS to compare the two outputs, but something like > library(car) > sample.data <- data.frame(IV=factor(rep(1:4,each=20)), DV=rep(c(-3,-3,1,3),each=20)+rnorm(80)) > Anova(lm1 <- lm(DV ~ IV, data=sample.data, contrasts=list(IV=contr.poly)), type="III") Anova Table (Type III tests) Response: DV Sum Sq Df F value Pr(>F) (Intercept) 18.08 1 21.815 1.27e-05 *** IV 567.05 3 228.046 < 2.2e-16 *** Residuals 62.99 76 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 is worth to try in first instance. About factor coding in R vs. SAS: R considers the baseline or reference level as the first level in lexicographic order, whereas SAS considers the last one. So, to get comparable results, either you have to use contr.SAS() or to relevel() your R factor. A: This may look like a bit of self-promotion (and I suppose it is). But I developed an lsmeans package for R (available on CRAN) that is designed to handle exactly this sort of situation. Here is how it works for your example: > sample.data <- data.frame(IV=rep(1:4,each=20),DV=rep(c(-3,-3,1,3),each=20)+rnorm(80)) > sample.aov <- aov(DV ~ factor(IV), data = sample.data) > library("lsmeans") > (sample.lsm <- lsmeans(sample.aov, "IV")) IV lsmean SE df lower.CL upper.CL 1 -3.009669 0.2237448 76 -3.4552957 -2.564043 2 -3.046072 0.2237448 76 -3.4916980 -2.600445 3 1.147080 0.2237448 76 0.7014539 1.592707 4 3.049153 0.2237448 76 2.6035264 3.494779 > contrast(sample.lsm, list(mycon = c(-3,-1,1,3))) contrast estimate SE df t.ratio p.value mycon 22.36962 1.000617 76 22.356 <.0001 You could specify additional contrasts in the list if you like. For this example, you'll get the same results with the built-in linear polynomial contrast: > con <- contrast(sample.lsm, "poly") > con contrast estimate SE df t.ratio p.value linear 22.369618 1.0006172 76 22.356 <.0001 quadratic 1.938475 0.4474896 76 4.332 <.0001 cubic -6.520633 1.0006172 76 -6.517 <.0001 To confirm this, note that the "poly" specification directs it to call poly.lsmc, which produces these results: > poly.lsmc(1:4) linear quadratic cubic 1 -3 1 -1 2 -1 -1 3 3 1 -1 -3 4 3 1 1 If you wish to do a joint test of several contrasts, use the test function with joint = TRUE. For example, > test(con, joint = TRUE) This will produce a "type III" test. Unlike car::Anova(), it will do it correctly regardless of the contrast coding used in the model-fitting stage. This is because the linear functions being tested are specified directly rather than implicitly via model reduction. An additional feature is that a case where the contrasts being tested are linearly dependent is detected, and the correct test statistic and degrees of freedom are produced. A: You may want to have a look at this blog post: Obtaining the same ANOVA results in R as in SPSS - the difficulties with Type II and Type III sums of squares (Spoiler: add options(contrasts=c("contr.sum", "contr.poly")) at the beginning of your script)
{ "pile_set_name": "StackExchange" }
Q: Storing a div contents into an array and retrieving it back I was trying to save a div into an array and trying to retrieve it back later. I am saving it when the user unchecks a checkbox and try to retrieve the div contents when he checks it again here is the code myDivBackups = new Array(); function backupMydiv(myDivID) { myDivBackup = {}; var isExist = false; myDivBackup['name'] = myDivID; myDivBackup['html'] = $(myDivID); for (var index in myDivBackups) { if (myDivBackups[index].name == myDivID) { isExist = true; break; } else { isExist = false; } } if (isExist === false) { myDivBackups.push(myDivBackup); } //clearing the textboxes in dom $(myDivID).find('input:text').val(''); } //restoring div contents by taking from myDivbackups array function restoreMydiv(myDivID) { for (var index in myDivBackups) { if (myDivBackups[index].name === myDivID) { var temp = myDivBackups[index].html; return (temp[0]); //in temp[0] i am getting div contents with cleared inputs } } } I don't really understand how javascript is taking care of it , I get the logs right ( I am getting the div contents) but textboxes are getting cleared every time. thanks. Edit : here is the div which I am trying to save <div id="mydiv_4" class="mydiv_values" style="display: block;"> <div class="mySubdiv"> <span class="myvalue_title">Values</span> <input type="button" id="add_value" class="blue" value="Add Value"> <label class="my-text" id="caption_text">my Text</label> <input type="text" name="mytext_4" class="my-text-value" value=""> <p><input type="text" id="1" name="myinput_4_1" value="1"></p> <p><input type="text" id="2" name="myinput_4_2" value="2"></p> </div> </div> A: Use $(myDivID).html(); to get the html :)
{ "pile_set_name": "StackExchange" }
Q: Why should avoid singleton in C++ People use singleton everywhere. Read some threads recently from stackoverflow that singleton should be avoided in C++, but not clear why is that. Some might worry about memory leak with undeleted pointers, things such as exceptions will skip the memory recycle codes. But will the auto_ptr solve this problem? A: In general, as mentioned in another answer, you should avoid mutable global data. It introduces a difficulty in tracking code side effects. However your question is specifically about C++. You could, for instance, have global immutable data that is worth sharing in a singleton. In C++, specifically, it's nearly impossible to safely initialize a singleton in a multithreaded environment. Multithreaded Environment You can use the "construct on first use" idiom to make sure the singleton is properly initialized exactly by the time it is needed: http://www.parashift.com/c++-faq-lite/static-init-order.html. However, what happens if you have 2 (or more) threads which all try to access the singleton for the first time, at exactly the same time? This scenario is not as far fetched as it seems, if the shared immutable data is data required by your calculateSomeData thread, and you initialize several of these threads at the same time. Reading the discussion linked above in the C++ FAQ Lite, you can see that it's a complex question in the first place. Adding threads makes it much harder. On Linux, with gcc, the compiler solves this problem for you - statics are initialized within a mutex and the code is made safe for you. This is an enhancement, the standard requires no such behavior. In MSVC the compiler does not provide this utility for you and you get a crash instead. You may think "that's ok, I'll just put a mutex around my first use initialization!" However, the mutex itself suffers from exactly the same problem, itself needing to be static. The only way to make sure your singleton is safe for threaded use is to initialize it very early in the program before any threads are started. This can be accomplished with a trick that causes the singleton to be initialized before main is called. Singletons That Rely on Other Singletons This problem can be mostly solved with the construct on first use idiom, but if you have the problem of initializing them before any threads are initialized, you can potentially introduce new problems. Cross-platform Compatibility If you plan on using your code on more than one platform, and compile shared libraries, expect some issues. Because there is no C++ ABI interface specified, each compiler and platform handles global statics differently. For instance, unless the symbols are explicitly exported in MSVC, each DLL will have its own instance of the singleton. On Linux, the singletons will be implicitly shared between shared libraries.
{ "pile_set_name": "StackExchange" }
Q: Netbeans + Scala + play-framework : index.html isn't found I've just netbeansified a plain play project with scala. Netbeans has no problems with opening or editing the project but if I try to run it this happens: @68095ke10 Application.index action not found Action not found Action Application.index could not be found. Error raised is Controller controllers.Application not found play.exceptions.ActionNotFoundException: Action Application.index not found at play.mvc.ActionInvoker.getActionMethod(ActionInvoker.java:588) at play.mvc.ActionInvoker.resolve(ActionInvoker.java:85) at Invocation.HTTP Request(Play!) Caused by: java.lang.Exception: Controller controllers.Application not found ... 3 more First I tried to rename and restructure the project so that index.html would be found. Yet I soon realized that this was no help at all. After undoing my changes I tried to start the app by play run on the console. Somehow this worked. Netbeans is version 7.0.1. Play is version 1.2.3 . Scala was installed by the typesafe-stack. Netbeans plugin is up to date with version 2.9.x. What is wrong ? A: Add a path to the scala module lib folder to your project, and when you run the app, see if it says "Scala support is active" you'll notice this happens when running from the console, but not netbeans.
{ "pile_set_name": "StackExchange" }
Q: How Ridge or Lasso regression really work? Very basic question here, but I would like to understand (not mathematically) how the fact to add a "penalty" (sum of squared coeff. times a scalar) to the residual sum of square can reduce big coefficients ? thanks ! A: Because your "penalty" represenation of the minimization problem is just the langrange form of a constraint optimization problem: Assume centered variables. In both cases, lasso and ridge, your unconstrained target function is then the usual sum of squared residuals; i.e. given $p$ regressors you minimize: $$RSS(\boldsymbol{\beta}) = \sum_{i=1}^n (y_i-(x_{i,1}\beta_1 +\dots +x_{i,p}\beta_p))^2.$$ over all $\boldsymbol{\beta} =(\beta_1,\dots, \beta_p)$. Now, in the case of a ridge regression you minimize $RSS(\boldsymbol{\beta})$ such that $$\sum_{i=1}^p\beta_p^2 \leq t_{ridge},$$ for some value of $t_{ridge}\geq 0$. For small values of $t_{ridge}$ it will be impossible to derive the same solution as in standard least square scenario in which case you only minimize $RSS(\boldsymbol{\beta})$ -- Think about $t_{ridge}=0$ then the only possible solution can be $\beta_1\equiv \dots \equiv \beta_p = 0$. On the other hand, in the case of the lasso, you minimize $RSS(\boldsymbol{\beta})$ under the constraint $$\sum_{i=1}^p|\beta_p| \leq t_{lasso},$$ for some value of $t_{lasso}\geq 0$. Both constrained optimization problems can be equivalently forumlated in terms of an unconstrained optimization problem, i.e. for the lasso: you can equivalently minimize $$\sum_{i=1}^n (y_i-(x_{i,1}\beta_1 +\dots +x_{i,p}\beta_p))^2 + \lambda_{lasso}\sum_{i=1}^p|\beta_p|.$$
{ "pile_set_name": "StackExchange" }
Q: MS Graph API Photo endpoint not working with App Permissions for Groups I´m trying to call MS Graph API to get the Photo from a Group using Application permissions, but I´m getting an "Access is denied. Check credentials and try again." According to this link: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/profilephoto_get App permissions are supported: For user resource: User.Read.All, User.ReadWrite.All For group resource: Group.Read.All, Group.ReadWrite.All I´m getting an App token, and I can see those permissions: "roles": [ "User.ReadWrite.All", "Group.Read.All", "Group.ReadWrite.All", "Directory.Read.All", "User.Read.All" ] Seems a bug in the Photo endpoint for Groups, as curiously, I can get any User photo using same App token. None of the Photo endpoints works for Groups: /groups/{id}/photo /groups/{id}/photo/$value /groups/{id}/photos Am I missing something? is there any other permission required (not documented). In case anyone from MS product team can take a look, here is one of the error Ids: { "error": { "code": "ErrorAccessDenied", "message": "Access is denied. Check credentials and try again.", "innerError": { "request-id": "ac884427-69ee-407e-b198-06bd6af5f4be", "date": "2018-10-30T13:12:19" } } } Thanks! A: I had the same use case, apparently it seems that it's a known issue documented by Microsoft here : https://docs.microsoft.com/fr-fr/graph/known-issues#permissions-for-groups-and-microsoft-teams You must use a delegated permission and not an app permission. Examples of group features that support only delegated permissions: Group conversations, events, photo External senders, accepted or rejected senders, group subscription User favorites and unseen count
{ "pile_set_name": "StackExchange" }
Q: Documentation String Stub, Python I'm learning Python because I think is an awesome and powerful language like C++, perl or C# but is really really easy at same time. I'm using JetBrains' Pycharm and when I define a function it ask me to add a "Documentation String Stub" when I click yes it adds something like this: """ """ so the full code of the function is something like this: def otherFunction(h, w): """ """ hello = h world = w full_word = h + ' ' + w return full_word I would like to know what these (""" """) symbols means, Thanks. A: """ """ is the escape sequence for strings spanning several lines in python. When put right after a function or class declaration they provide the documentation for said function/class (they're called docstrings)
{ "pile_set_name": "StackExchange" }
Q: Result Set Get all row values in a single column I am writing a test at the moment where I need to compare some database results against a UI table using Selenium in Java. I have my UI results arriving in an ArrayList format. My console tells me that the results look like "[27002, 55691, 58716, 95362]". This is working fine. I have another class which does a JDBC call into my database to obtain the expected results. I'm using the ResultSet method to grab these values. My code looks like the following: (Note: my JDBC connections etc are handled in the method "runQuery" which I pass my SQL query into) public ArrayList queryForTPOSMembersByHospital() throws SQLException { String strQueryText = "select distinct _Member_Number and rest of query here that returns one column of results and 4 rows of data"; ResultSet rs = runQuery(strQueryText); ArrayList<String> memberNos = new ArrayList<String>(); while (rs.next()) { memberNos.add(rs.getString("_Member_Number")); return memberNos; } return null; } But when I output the memberNos I only get a single value [27002] rather than 4 I am expecting. I'm thinking I need to do something like memberNos.addAll perhaps? rather than memberNos.add? Tried a few things around this method but not getting any luck yet. A: It is because you are returning inside while loop, your code should be while (rs.next()) { memberNos.add(rs.getString("_Member_Number")); } return memberNos
{ "pile_set_name": "StackExchange" }
Q: Improving Caesar Cipher security One of the weaknesses of Ceasar is that an attacker knows the order of my alphabet, IE ABC...Z If I scramble this, then are there enough permutations to ensure my resultant ciphertext cannot be brute forced. Does this then only leave me vulnerable to frequency analysis. A: This is a monoalphabetic substitution cipher (with a mixed alphabet; in the first section of the article there is a paragraph about its security) While the keyspace of this cipher is huge (relatively speaking for a classical cipher) with $26!\approx 2^{88.4}$ possible keys, it is still quite easy to break with frequency analysis. Caesar is much worse of course, because you can simply try out all $26$ possible keys, and that is not possible for a simple substitution cipher (with arbitrary permutation). Does this then only leave me vulnerable to frequency analysis. Well, that statement is true. But "more than almost nothing" doesn't mean much.
{ "pile_set_name": "StackExchange" }
Q: print double quotes in shell programming I want to print double quotes using echo statement in shell programming. Example: echo "$1,$2,$3,$4"; prints xyz,123,abc,pqrs How to print "xyz","123","abc","pqrs"; I had tried to place double quotes in echo statement but its not being printed. A: You just have to quote them: echo "\"$1\",\"$2\",\"$3\",\"$4\"" As noted here: Enclosing characters in double quotes (‘"’) preserves the literal value of all characters within the quotes, with the exception of ‘$’, ‘`’, ‘\’, and, when history expansion is enabled, ‘!’. The characters ‘$’ and ‘`’ retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘`’, ‘"’, ‘\’, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ‘!’ appearing in double quotes is escaped using a backslash. The backslash preceding the ‘!’ is not removed. The special parameters ‘*’ and ‘@’ have special meaning when in double quotes (see Shell Parameter Expansion). A: Use printf, no escaping is required: printf '"%s","%s","%s","%s";\n' $1 $2 $3 $4 and the trailing ; gets printed too! A: You should escape the " to make it visible in the output, you can do this : echo \""$1"\",\""$2"\",\""$3"\",\""$4"\"
{ "pile_set_name": "StackExchange" }
Q: selectedIndex is not working for mat-tab-nav-bar angular material tabs I wrote the tabs code like below <nav mat-tab-nav-bar [selectedIndex]="0"> <a mat-tab-link *ngFor="let link of navLinks; let i = index;" [routerLink]="link.path" routerLinkActive #rla="routerLinkActive" [active]="rla.isActive"> <div class="link-tab-label">{{link.label}}</div> <mat-icon class="link-tab-close" (click)="closeTab(i)">close</mat-icon> </a> </nav> When I run the project, I am getting the issue which is shown below compiler.js:485 Uncaught Error: Template parse errors: Can't bind to 'selectedIndex' since it isn't a known property of 'nav'. (" <mat-card> <mat-card-content> <nav mat-tab-nav-bar [ERROR ->][selectedIndex]="0"> How to use selectedIndex with mat-tab-nav-bar? A: mat-tab-nav-bar does not have a selectedIndex property and the mat-tab-links inside a mat-tab-nav-bar are not really tabs. mat-tab-nav-bar "provides a tab-like UI for navigating between routes." To set the active "tab" or link, you set the active route through your application's router. The "tab" shows as active via the routerLinkActive directive and the active property.
{ "pile_set_name": "StackExchange" }
Q: SQL Server shrink command 'estimated_completion_time' keeps going up Running SQL 2012 R2... Microsoft SQL Server 2014 (SP2-GDR) (KB4019093) - 12.0.5207.0 (X64) Standard Edition (64-bit) Ran the shrink command DBCC SHRINKDATABASE(databaseNameHere) (Yes, I know this shouldn't be done regularly, if ever... we have a 200 GB database and cleared out many years worth of data, and should be able to reclaim about 100 GB of space) When I checked the status of the task at 1.5 hours, it was 49.1xxx percent_complete. It's been running for 2.5 hours... and now at 49.5xxx percent_complete. Additionally, just in the last 20 minutes, the estimated_completion_time (found in sys.dm_exec_requests) has gone from 8,741,035 milliseconds to 9,385,086 milliseconds... There is still a ton of space available on the drive. It is a development/test database that nobody is using... so whats the deal? why does the estimated time keep increasing? I've been using sp_who2 active to verify there are no blocks... A: SHRINKDATABASE and SHRINKFILE won't actually release the space to disk until the very last moment: it has to move all the contents around within the files first (which is the part that takes a long time). For why the progress doesn't seem constant: the free/used space is spread out across a large file, so it is going to "skip ahead" when it encounters an empty patch and "slow down" when it hits a section of used pages. As mentioned in the comments, I would highly recommend using SHRINKFILE instead of SHRINKDATABASE, since you can control the target sizes of each individual file, and give each one a reasonable target. For example, I usually try to leave 15-25% free space in each data file.
{ "pile_set_name": "StackExchange" }
Q: Points to Understand Architecture of an Application/System We are working on a knowledge transition of multiple applications (around 700). To make the process easy, I am preparing a list of key points we need to consdier for understanding the architecture of each application like below. Why the list is important is once the transition is over, we are trying to integrate/rewrite/refactor these applications. Technology Stack ( a. Programming languages b. Tools used c. Third party components) Database ( a. Data model b. Data flow c. Clustering) Interfaces with other applications Dependencies NFR Anyone has any exclusive check list for this or enrich the above list? A: If you built a house and you want to describe it to someone, would you talk about what kind of flooring material you used? About what kind of hammer and tools you used? About the plumbing? You might, but none of this has to do with architecture. Architecture is about what kind of rooms there are, where they are and how they are connected. So the first thing you should talk about when describing your application is what it does. What its modules are and what those individual modules do. Then you should talk about how those modules relate to and interact with each other. That's its architecture. The next thing is to talk about how the application and its modules work. And the last thing is to talk about what tools you used to make that. Your list so far only mentions tools and implementation details. I'm afraid none of those has to do with the architecture of the system.
{ "pile_set_name": "StackExchange" }
Q: SharePoint 2010: Where is the schema.xml for the OOTB blog lists? Question: Where is the schema of the OOTB blog lists defined? (i.e. for the Posts, Categories and Comments lists) The list templates and instances are embedded in the onet.xml of the OOTB blog site template at 14/TEMPLATE/Blog, however there is no mention of the lists' content types, fields or views. Background: I have created a custom site definition (based on a copy of the OOTB blog site template) so that we can apply branding and other customisations to our blogs. Some of these customisations are performed by a feature receiver that is activated as part of the site def. Unfortunately, the order in which SharePoint provisions items from the onet.xml is as follows: Site is provisioned Features are activated Feature receivers are activated Other elements (such as lists) defined in the site definition's onet.xml are provisioned As you can see, the feature receivers (which in my case are trying to update the permissions of the Comments and Categories lists) are activated before the lists have been created. The solution to this is very simple: just create the lists as part of the feature as per normal. To do this, I need to create a list definition in Visual Studio, however I can't find the schema.xml files for these OOTB lists. A: I am working on a similar project, but I found those schema under 14\TEMPLATE\SiteTemplate\Blog\Lists\Categories or \Posts or \Comments in your solution you have to have the same mapping as far as I know Hope that helps
{ "pile_set_name": "StackExchange" }
Q: Access parent state controller from nested state in angularui I have defined nested states in my project: $stateProvider .state("MultiStepForm", { url: "/Sensor/MultiStepForm", templateUrl: "/app/MultiStepForm/MultiStepForm.html", controller: "MultiStepFormController", controllerAs: "MultiStepLogic" }) .state('MultiStepForm.step1', { url: '/step1', templateUrl: '/app/MultiStepForm/NestedViews/FormStep1.html', controller: "MultiStepLogicStep1Controller", controllerAs: "Step1" }) .state('MultiStepForm.step2', { url: '/step2', templateUrl: '/app/MultiStepForm/NestedViews/FormStep2.html', controller: "MultiStepLogicStep2Controller", controllerAs: "Step2" }) .state('MultiStepForm.step3', { url: '/step3', templateUrl: '/app/MultiStepForm/NestedViews/FormStep3.html', controller: "MultiStepLogicStep3Controller", controllerAs: "Step3" }); In MultiStepForm state I have defined this property: var self = this; this.data = "someObject"; In MultiStepForm.step3 state controller(Step3) I want to access property that defined in parent state controller: this.data = "some data from MultiStepForm.step3 state" My question is how can I access parent property from nested state controller? A: You need to 'resolve' that data before injecting it into the controller. If it is resolved at the parent, it will be available to the children. Like this: $stateProvider .state("MultiStepForm", { url: "/Sensor/MultiStepForm", templateUrl: "/app/MultiStepForm/MultiStepForm.html", controller: "MultiStepFormController", controllerAs: "MultiStepLogic", resolve: { your_custom_data: ['$stateParams', 'another_service', function($stateParams, another_service) { //you can use $stateParams or other services here as needed to get the data you want return the_value_of_your_custom_data; }], }) Then in your controller: angular .module('your_app') .controller('MultiStepLogicStep3Controller', MultiStepLogicStep3Controller); function MultiStepLogicStep3Controller($state, your_custom_data) { //access your $state or custom data here this.custom_data = your_custom_data; }
{ "pile_set_name": "StackExchange" }
Q: How can you complain about being wrongly denied boarding and demand compensation? An African friend of mine was traveling from Dar es Salaam to the UK (Manchester) and had an "Indefinite leave to remain" visa. His wife and children live in the UK. He was flying on Turkish Airlines and was denied boarding the plane to Manchester at Ataturk Airport Istanbul when he was at the gate. The Turkish official would not explain the reasons or respond to questions of my friend but said the documents were not adequate and kept shouting "don't talk". After 6 stressful hours and a lot of unpleasant chatting to other officials, my friend begged the police to help him. They organised a flight back to Tanzania using my friend's return ticket (which should have been in Jan 2017). He had no food or drink until he arrived back home. Two days later he did fly to Manchester on another airline (Etihad) using the same documents which where accepted by both the airline and the immigration. How can you complain about the behavior of the offical at Ataturk airport? How can you claim compensation for the ticket if my friend has wrongly been denied boarding? This cost my friend £800 and I'd like it to be investigated. A: How can you claim compensation for the ticket if my friend has wrongly been denied boarding? Assuming the "Turkish official at the gate" was the Turkish Airlines agent (and not for example Turkish government official), then according to what you said and following the Turkish airlines Passengers Right document your friend should be eligible for "denied boarding" compensation. Here your friend can go one of two routes: Via normal channels (such as using Turkish Airline website, phones etc). Submit the copies of the documents, and the statement that exactly the same documents were presented, and were accepted by a different carrier later. This is typically the best route to start with. Via informal channels (such as explaining the situation in a blog post, and spreading this information through various social media). This may be quite effective when normal channels do not work, depending on your and your friends' social media activity. Turkish Airlines does care about their image and good customer service, so they do tend to resolve the issues when they got nasty in social media (at least here in US) - even in cases where, in my opinion, the airline wasn't really at fault. Your friend also has an option to sue them, but this is more difficult route, and requires reading at least his condition of carriage and laws of Tanzania (there's possibility, for example, that he'd have to file a lawsuit in Istanbul or some 3rd party country like Netherlands).
{ "pile_set_name": "StackExchange" }
Q: How to extract years from a string in each row and generate new rows with those years I have a dataframe shown below. df = pd.DataFrame({'business_id':["a","b","c"], 'time':['2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-11-18 01:54:50, 2017-04-20 18:39:06', '2017-03-12 17:47:20, 2018-09-10 16:40:17', '2014-02-28 12:11:16, 2019-05-30 18:36:57, 2019-07-20 04:54:28'] }) Here is the input generated from the above code. business_id time a '2016-04-26 19:49:16, 2016-08-30 18:36:57, 2016-11-18 01:54:50, 2017-04-20 18:39:06' b '2017-03-12 17:47:20, 2018-09-10 16:40:17' c '2014-02-28 12:11:16, 2019-05-30 18:36:57, 2019-07-20 04:54:28' Below is the output I'd like to generate. business_id year a 2016 a 2016 a 2016 a 2017 b 2017 b 2018 c 2014 c 2019 c 2019 How should I do this? A: If you only need the year and ID: df[['business_id']].merge(df['time'].str .extractall('(?P<year>\d{4})-') .reset_index(1,drop=True), left_index=True, right_index=True) Output: business_id year 0 a 2016 0 a 2016 0 a 2016 0 a 2017 1 b 2017 1 b 2018 2 c 2014 2 c 2019 2 c 2019
{ "pile_set_name": "StackExchange" }
Q: Javascript File not Caching Im using the Keenthemes Metronic admin template and having real trouble with 1 file. Its a javascript file and for some reason no matter what i try i cannot get it to cache. Its a static file with a size of 3.5mb so loading this each time is killing the scripts. I have tried adding bits to me htaccess and to the header but this changes nothing. Has anyone else come across this? Thanks A: As I could see from the comment section, you have already tried minimising the file, but it is still very large. You can control the cache of your own browser, but cannot control the cache of the browsers your users are using. Therefore you will not be able to enforce caching the file. You will therefore need to thoroughly read the file and divide it into separate files. You will end up having a core file, which will be useful everywhere and which will be needed to be downloaded and you will have some other files, which are specific to some features, like a file for register/login, another for handling separate features, like choosing colors and so on. You will need to load your core JS file everywhere, but your specific features will be needed at specific places. You will not need login features, for instance, if the user has already logged in, so you will be able to include the JS files for separate features where they are needed and nowhere else. Also, You might want to lazy load your JS files, so you will initially load the core file and when it has been successfully loaded, separately load the other files. Those features will be unable initially when the page is loaded, so the page will need to somehow handle or prevent attempts from users of using a feature before its script was loaded. It would not hurt to minify all these separate files either. Possibly RequireJS can help you to handle requirements, but you can implement your own feature to handle requirements as well.
{ "pile_set_name": "StackExchange" }
Q: Решаем логическу задачку с python Я изучаю python и мне случайно попалась логическая задачка, которую я взялся решать на python Задачу решил, но костыльно. Чувствую, правильнее было бы решать рекурсией. В общем, подскажите более красивое решение. d = '5' t = '0' n, a, l, g, e, r, b, o = '-1', '-1', '-1', '-1', '-1', '-1', '-1', '-1' rob = -1 roberto = 0 ran_set = set() for i in range(12346789, 98764322): i_s = str(i) for j in i_s: ran_set.add(j) if len(ran_set) == len(i_s) and '5' not in i_s and '0' not in i_s: n, a, l, g, e, r, b, o = i_s[0], i_s[1], i_s[2], i_s[3], i_s[4], i_s[5], i_s[6], i_s[7] don = d + o + n + a + l + d ger = g + e + r + a + l + d rob = r + o + b + e + r + t roberto = (int(don) + int(ger)) print(roberto) if roberto == int(rob): print() print('got it!') break ran_set = set() P.S. На картинке изображено сложение столбиком, если вдруг кого то смущает плюс посередине A: Проще всего решить перебором, но не всех размещенией с повторениями, как у вас, а всех перестановок import itertools def solve(a, b, c, known): letters = set(a + b + c) - known.keys() digits = set('0123456789') - set(known.values()) for variant in itertools.permutations(digits, len(letters)): table = dict(zip(letters, variant), **known) trans = str.maketrans(table) if int(a.translate(trans)) + int(b.translate(trans)) == int(c.translate(trans)): return table print(solve('ДОНАЛД', 'ГЕРАЛД', 'РОБЕРТ', {'Д': '5'})) {'Г': '1', 'Л': '8', 'Р': '7', 'Н': '6', 'А': '4', 'Т': '0', 'Е': '9', 'Б': '3', 'О': '2', 'Д': '5'}
{ "pile_set_name": "StackExchange" }
Q: X-Requested-With/HTTP_X_REQUESTED_WITH weird problem I'm building a Django site and trying to use the request.is_ajax() function... But it's only working locally and it's driving me crazy! I'm at the point where I've just dumped the headers. Here (on the django test server) there's HTTP_X_REQUESTED_WITH but on the production server (cherokee+scgi) all I get is X-Requested-With. I've used firebug to snoop the sent headers and it's X-Requested-With (on both versions of the site). I'm very, very confused. Can anybody explain what's happening and how I can work around it without losing my mind? A: wrt/ the X-Requested-With => HTTP_X_REQUESTED_WITH stuff, it's in conformance with the CGI specifications. Since FastCGI, SCGI and WSGI are all based on the CGI specs, Django developpers choosed to stick to this convention (FWIW, the ModPythonRequest class do the same rewrite for consistency). So it seems that your problem is that something in the cherokee/scgi chain doesn't rewrite the headers correctly. Which scgi implemetation are you using ?
{ "pile_set_name": "StackExchange" }
Q: vba regex only returns first match my regex match in VBA (WORD) only gives one result. I created this function Function RE6(strData As String) As String Dim RE As Object, REMatches As Object Set RE = CreateObject("vbscript.regexp") With RE .MultiLine = False .Global = False .IgnoreCase = True .Pattern = "\[substep [a-zA-Z]\](.*?); {1}" End With Set REMatches = RE.Execute(strData) RE6 = "" End Function The problem here is that it only gives the first result. For example I got a string: [step 1] title for substeps; [substep a] step a; [substep b] step b; [substep c] step c; My result is: [substep a] step a; only 1 match, not the step b and c. A: You need to set Global to True http://msdn.microsoft.com/en-us/library/tdte5kwf%28v=vs.84%29
{ "pile_set_name": "StackExchange" }
Q: Data truncation: Data too long for column 'content' at row 1 *Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'content' at row 1 I'm try to solve this problem many days Name:vivek srivastava Desc:Contact person File:file ContentType:application/pdf service:managed,co-location Hibernate: insert into documents (address, contact, content, mobileno, name, poname, serviceprovided, status, uploaddate) values (?, ?, ?, ?, ?, ?, ?, ?, ?) org.hibernate.exception.DataException: could not insert: [com.ams.bean.Document] package com.ams.bean; import java.sql.Blob; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; @Entity @Table(name="documents") public class Document { @Id @GeneratedValue @Column(name="id") private Integer id; @Column(name="name") private String name; @Column(name="poname") private String poname; @Column(name="mobileno") private String mobileno; @Column(name="contact") private String contact; @Column(name="content") @Lob private Blob content; @Column(name="serviceprovided") private String serviceprovided; @Column(name="status") private String status; @Column(name="uploaddate") private String uploaddate; @Column(name="address") private String address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobileno() { return mobileno; } public void setMobileno(String mobileno) { this.mobileno = mobileno; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public Blob getContent() { return content; } public void setContent(Blob content) { this.content = content; } public String getServiceprovided() { return serviceprovided; } public void setServiceprovided(String serviceprovided) { this.serviceprovided = serviceprovided; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUploaddate() { return uploaddate; } public void setUploaddate(String uploaddate) { this.uploaddate = uploaddate; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPoname() { return poname; } public void setPoname(String poname) { this.poname = poname; }enter code here } @RequestMapping(value = "/save", method = RequestMethod.POST) public String save( @ModelAttribute("document") Document document, @RequestParam("file") MultipartFile file) { System.out.println("Name:" + document.getName()); System.out.println("Desc:" + document.getContact()); System.out.println("File:" + file.getName()); System.out.println("ContentType:" + file.getContentType()); System.out.println("service:"+document.getServiceprovided()); try { Blob blob = Hibernate.createBlob(file.getInputStream()); document.setServiceprovided(document.getServiceprovided()); document.setContent(blob); document.setAddress(document.getAddress()); document.setName(document.getName()); document.setPoname(document.getPoname()); document.setMobileno(document.getMobileno()); document.setStatus(document.getStatus()); document.setUploaddate(document.getUploaddate()); document.setContact(document.getContact()); } catch (IOException e) { e.printStackTrace(); } try { VMDao.save(document); } catch(Exception e) { e.printStackTrace(); } return "redirect:/customer_details.do"; } @Transactional(propagation=Propagation.REQUIRED) public void save(Document document) { Session session = sessionFactory.getCurrentSession(); session.save(document); } A: Exception is clear, value for content id too large (more than 64Kb). Consider usign another, such as MEDIUMBLOB or LONGBLOB: BLOB Types Object type Value length that the object can hold TINYBLOB from 0 to 255 bytes BLOB from 0 to 65535 bytes MEDIUMBLOB from 0 to 16 777 215 bytes LONGBLOB from 0 to 4 294 967 295 bytes
{ "pile_set_name": "StackExchange" }
Q: SOAP Requests not working on one machine, but works perfectly fine on another Using a small derivative from the following website: http://servicenowsoap.wordpress.com/2013/10/26/vb-script/ ...where I'm implementing the call in VB.Net instead of VBScript. I'm using Microsoft XML 3.0 resource, and during initial testing... it would work fine. I could send a "getKeys" update passing a number, and it would return with the sys_id number needed for ServiceNow. Now, when I send any SOAP/XML envelope out, the server pretends that I sent it something foreign. It returns a 0 for the count and no sys_id. I've tried using direct XML implementation, and loading the WSDL through web services. Both return the same: Nothing. BUT, when I try this code on any other machine, it will send and receive the SOAP request using the exact same code, and receives the request as expected. Example SOAP envelope request on both machines: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <getKeys xmlns:tns="http://www.service-now.com/sc_req_item"> <number> examplerequestnumber </number> </getKeys> </soap:Body> </soap:Envelope> What returns on anyone else's machine: <?xml version="1.0" ?> - <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <SOAP-ENV:Body> - <getKeysResponse> <sys_id>examplesysidnumber</sys_id> <count>1</count> </getKeysResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> What returns on only my machine: <?xml version="1.0" ?> - <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <SOAP-ENV:Body> - <getKeysResponse> </sys_id> <count>0</count> </getKeysResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Is there something on my machine that may be blocking the request from completing? I have no antivirus running, no firewall up. I CAN however, send the exact same envelope in SOAPUI, and get a response. This is driving me crazy. A: Figured out what the issue was. We have multiple domains on our server, and the account that was tied to the SOAP requests was on our old domain. The new domain had not yet been integrated with ServiceNow, and MSXML (what I was using to send the SOAP request) tried to do passthrough authentication with the new domain. So, my next goal was to make sure MSXML was doing preemptive authentication, since this account using for SOAP requests was local to the ServiceNow server. I found something similar to my problem, so I tried the following: First, I ran the query in SOAPUI. Looking at the RAW tab, I pulled the "Authentication: Basic xxxxxx" header, and copied it directly into my code. I added the setRequestHeader to my request, and bam! It works. Example code: oWSRequest.open("POST", sEndpointURL, False, gServiceNowUser, gServiceNowPass) oWSRequest.setRequestHeader("Content-Type", "text/xml") oWSRequest.setRequestHeader("Authorization", "Basic c3J2Y1FsaWt2aWV3X09EQkM6bzc3MzQ4QTI4TnZV") oWSRequest.send(oWSRequestDoc.xml)
{ "pile_set_name": "StackExchange" }
Q: how to insert records from a aspx.vb file to a mdb datase code Hey there good evening can anyone tell me whats wrong with my code? I'm getting an 'operation not updateable' error like the one below Server Error in '/' Application. Operation must use an updateable query. Description: An unhandled exception occurred during the execution of the current webrequest. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.OleDb.OleDbException: Operation must use an updateable query. Source Error: Line 20: cmd.Parameters.AddWithValue("paswords", TextBox4.Text) Line 21: conn.Open() Line 22: cmd.ExecuteNonQuery() Line 23: End Using Line 24: End Using My code is Imports System.Web.Security Imports System.Data Imports System.Data.OleDb Imports System.Configuration Imports System.Web.Configuration Partial Class Registration Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|onlineregistration.mdb" Dim SqlString As String = "Insert Into registration (firtsname, telephone, email, paswords) Values (?,?,?,?)" Using conn As New OleDbConnection(ConnString) Using cmd As New OleDbCommand(SqlString, conn) cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("firtsname", TextBox1.Text) cmd.Parameters.AddWithValue("telephone", TextBox2.Text) cmd.Parameters.AddWithValue("email", TextBox3.Text) cmd.Parameters.AddWithValue("paswords", TextBox4.Text) conn.Open() cmd.ExecuteScalar() End Using End Using End Sub End Class A: That error "must use an updateable query" is tipically thrown when the mdb file is write-only, or when there is no write permission on the file.
{ "pile_set_name": "StackExchange" }
Q: What is "*;1" in TADOStoredProc.ProcedureName value in Delphi? You may specify TADOStoredProc.ProcedureName in Delphi with the following value: MSSQLProcedureName;1 But what does meen ";1" in this value? Thanks for the help! A: This is an optional value that can be used to specify multiple definitions for the same stored procedure name... I think that the original intention was to allow versioning, but I've never seen it used that way in the wild. When you don't specify the number in the create procedure statement, it defaults to 1. Some of the various data access layers that call SQL Server will explicitly add the ;1 when executing the stored procedure. From MSDN: ;*number* Is an optional integer used to group procedures of the same name so they can be dropped together with a single DROP PROCEDURE statement. For example, the procedures used with an application called orders may be named orderproc;1, orderproc;2, and so on. The statement DROP PROCEDURE orderproc drops the entire group. If the name contains delimited identifiers, the number should not be included as part of the identifier; use the appropriate delimiter around procedure_name only.
{ "pile_set_name": "StackExchange" }
Q: Se cierra la aplicación cuando uso la cámara de fotos en un fragment Estoy intentando hacer mi primera app para android (bastante novato) y tengo un problema y ya no veo la luz por ningún sitio: Estoy haciendo una aplicación en la que quiero capturar una imagen con la cámara y ponerla en un ImageView en un Fragment. En el método. El fragment se carga correctamente, la cámara se abre, pero al aceptar la imagen se cierra la aplicación. En el método onCreate del activity principal llamo a otro activity (también con OnActivityResult) que hace un login. El código para abrir la cámara en el fragment: img = (ImageView)viewPrincipal.findViewById(R.id.imgView); Button btn_hacerfoto = (Button) viewPrincipal.findViewById(R.id.botonCamara); //Añadimos el Listener Boton btn_hacerfoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); int code = HACER_FOTO; nombreFoto = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/test.jpg"; intent.putExtra("ventana","foto"); Uri output = Uri.fromFile(new File(nombreFoto)); intent.putExtra(MediaStore.ACTION_IMAGE_CAPTURE, output); startActivityForResult(intent, code); } }); En el fragment el método OnActivityResult: @Override public void onActivityResult(int requestCode, int resultCode, Intent data) // protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); /** * Se revisa si la imagen viene de la c‡mara (TAKE_PICTURE) */ if (requestCode == HACER_FOTO) { /** * A partir del nombre del archivo ya definido lo buscamos y creamos el bitmap * para el ImageView */ ImageView iv = (ImageView)viewPrincipal.findViewById(R.id.imgView); iv.setImageBitmap(BitmapFactory.decodeFile(nombreFoto)); /** * Para guardar la imagen en la galer’a, utilizamos una conexi—n a un MediaScanner */ new MediaScannerConnection.MediaScannerConnectionClient() { private MediaScannerConnection msc = null; { msc = new MediaScannerConnection(viewPrincipal.getContext(), this); msc.connect(); } public void onMediaScannerConnected() { msc.scanFile(nombreFoto, null); } public void onScanCompleted(String path, Uri uri) { msc.disconnect(); } }; } } En el Activity principal, así funciona correctamente la aplicación, sin el login: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } Pero si pongo algo en el método, como esto, para saber de donde viene la llamada, automáticamente se cierra la aplicación, cuando cierras la ventana de la cámara de fotos: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //aqui falla la aplicacion String ventana= data.getStringExtra("ventana"); if(!ventana.equals(null)) { if (ventana.equals("login") { //blablalba } } } Y el error que obtengo es: FATAL EXCEPTION: main Process: com.j2app.pruebafragments, PID: 27116 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65546, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.j2app.pruebafragments/com.j2app.pruebafragments.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference at android.app.ActivityThread.deliverResults(ActivityThread.java:3699) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) at android.app.ActivityThread.-wrap16(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference at com.j2app.pruebafragments.MainActivity.onActivityResult(MainActivity.java:93) at android.app.Activity.dispatchActivityResult(Activity.java:6428) at android.app.ActivityThread.deliverResults(ActivityThread.java:3695) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)  at android.app.ActivityThread.-wrap16(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) ¿Alguien puede ayudarme? El archivo manifest es: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.j2app.pruebafragments"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Modal1Activity"></activity> </application> </manifest> A: Tu programa busca de una manera muy extraña la existencia de "ventana": String ventana = data.getStringExtra("ventana"); if (!ventana.equals(null)) { /* ... */ En ningún momento compruebas si existe la cadena "ventana", por lo que esa llamada falla devolviendo null, pero la comprobación que haces comprueba el contenido de la cadena (que es null) con una cadena que está alojada en null (un poco enrevesado). Deberías hacer uso de Intent.hasExtra(): if (data.hasExtra("ventana")) { String ventana = data.getStringExtra("ventana"); /* ... */ } Esa comprobación ya no te producirá el error que sufres.
{ "pile_set_name": "StackExchange" }
Q: ListFragment displays wrong items I am new to the android api and I have some problems with .. the basics. I'm trying to get a list working, but the list displays the wrong text: Each row has two TextViews (title, subtitle), heres the xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip" > <TextView android:id="@+id/row_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TITLE" android:textSize="15dip" android:layout_gravity="center_vertical" /> <TextView android:id="@+id/row_subtitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/row_title" android:text="SUBTITLE" android:textSize="10dip" android:layout_gravity="center_vertical" /> </RelativeLayout> I extend ListFragment (I need this fragment thing, because of a slidingMenu library), have a custom adapter and an item class. in the onActivityCreated() method I add some random items to the adapter: package com.slidingmenu.example; import android.app.Fragment; import android.app.ListFragment; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class SampleListFragment extends ListFragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.list, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); SampleAdapter adapter = new SampleAdapter(getActivity()); for (int i = 0; i < 20; i++) { adapter.add(new SampleItem(new Fragment(), "title no. " + i, "some subtitle")); } setListAdapter(adapter); } private class SampleItem { public Fragment frag; public String title; public String subTitle; public SampleItem(Fragment frag, String title, String subTitle) { this.frag = frag; this.title = title; this.subTitle = subTitle; } } public class SampleAdapter extends ArrayAdapter<SampleItem> { public SampleAdapter(Context context) { super(context, 0); } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null); } TextView title = (TextView) convertView.findViewById(R.id.row_title); TextView subTitle = (TextView) convertView.findViewById(R.id.row_subtitle); return convertView; } } } So I thougt that the list would display something like this: title no. 0 some subtitle - title no. 1 some subtitle - title no. 2 some subtitle - etc. but instead it just displays what I defined in the row.xml: TITLE SUBTITLE - TITLE SUBTITLE - etc. I think getView() needs to be changed (at least it doesn't make to much sense to me) but I'm not sure. Everything I try results in some nullpointer exception or worse. Please, can someone tell me what I need to change? A: The error is int the Adapter: public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null); } TextView title = (TextView) convertView.findViewById(R.id.row_title); TextView subTitle = (TextView) convertView.findViewById(R.id.row_subtitle); return convertView; } the getView never fills up the title and subtitle. Second you never submit to the superclass the dataset you want to show in the ListFragment. Here you have to ways. Or you ovveride the getCount and getItem and getItemId methods, or feed up the superclass with the dataset, using this constructor. Read carefully the documentation.
{ "pile_set_name": "StackExchange" }
Q: php mysql loop memory leaks? My php script stop running because it goes out of memory. Here is my code: $files = array_diff(scandir($dir_name), array('..', '.')); if (!empty($files)) { foreach ($files as $file) { if (pathinfo($file, PATHINFO_EXTENSION) == "csv") { $fp = fopen($dir_name.$file, 'r'); while (($line = fgetcsv($fp, 0, $delimiter)) !== FALSE) insert_update(array_map('addslashes', $line), $connect_id); fclose($fp); } } mysqli_close($connect_id); } I did run the script like 4 times on the same csv (more than 600k rows). And with exactly the same script it stop at different moments... Number of request done before it stop : 205 286 // 200 514 // 192 429 // 211 164 (I truncate the table before each try). I used always the same variables... how the memory used can increase ? Its only a foreach loop... if its work once, it should work unlimited times, right ? Thank you, Mickael. PS: Here is my function 'insert_update' function insert_update($row, $connect_id) { $table_name = "xxxxxxxx"; $maxcol = 42; $my_request = "INSERT INTO $table_name VALUES ('$row[0]'"; $i = 1; while ($i < $maxcol) { if (isset($row[$i])) $my_request = $my_request.", '$row[$i]'"; else $my_request = $my_request.", ''"; $i++; } $my_request = $my_request.")"; if (mysqli_query($connect_id, $my_request) == FALSE) { echo "<p>$my_request</p>"; exit(); } } A: Your function does not contain statics and should not leave anything behind. Your loop also does not keep anything in RAM. So, if you didnt accidently discover any memory_leaks in the used PHP functions, another issue might be the garbage collector. This service frees no longer used memory. THis garbage collector does not run after each variable id freed but in it's own time frame. You can however try to force the garbage collector to free memory now. (Some people say it wont affect memory as. Dunno) gc_collect_cycles() Some debugging may also help you identify the source of the leak: memory_get_peak_usage(); You can also try to increase the memory limit for this script. This shuldnt be done on a public available file however as it may take up all of your server memory fast then. ini_set('memory_limit', '1024M'); Another option might be to try different methods of file access and db connection depending on what's available to you. If all else fails, create some kind of iteration. Process 10 files, then redirect to your script with a offset parameter to start from where you left off last time. Repeat until all files are processed. http://php.net/manual/en/function.gc-collect-cycles.php
{ "pile_set_name": "StackExchange" }
Q: building wso2 from source - mvn eclipse:eclipse from which folder? I'm looking through some instructions for building a WSO2 product from source. The instructions state that mvn clean install is to be performed from the folder <local-platform-directory>/repos/wso2/carbon/platform/tags/turing-chunk05/product-releases/chunk-05 mvn eclipse:eclipse can then be peformed, but from which directory? Should mvn elipse:eclipse be performed from: <local-platform-directory> (the top level source folder), or <local-platform-directory>/repos/wso2/carbon/platform/tags/turing-chunk05/product-releases/chunk-05 (the folder from which you performed mvn clean install) A: You can run mvn elipse:eclipse in any directory with a Maven pom.xml I think you already know the structure of the WSO2 platform. For example, turing platform has following structure. build/ components/ dependencies/ features/ parent/ platform-integration/ product-releases/ products/ samples/ service-stubs/ When you use <local-platform-directory>, the top level source directory, you will get all modules references by the root pom.xml. When you use <local-platform-directory>/repos/wso2/carbon/platform/tags/turing-chunk05/product-releases/chunk-05/, the source directory for chunk-05 release, you will get all modules referenced by the chunk-05 pom.xml. If you go through the chunk-05 release pom.xml and sub module pom.xml files, you will see that it just builds the relevant components, dependencies, features, products etc. If you want to build the chunk-05 release, you must build from chunk-05 pom.xml, which will build all released maven projects with chunk-05. The wiki doc just explains the commands to get a maven project to your IDE. i.e. Eclipse or IntelliJ IDEA. So, I would recommend you to open only the required Maven projects. I usually use the Eclipse to edit the code only and most of the real code is in components and dependencies. For other directories, editing pom.xml via a text editor is enough for me. If you want to patch any component in chunk-05 release, you can use chunk-05 pom.xml and sub modules to identify relevant Maven project. I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Validation using Regular Expressions in iOS I'm implementing validation for username field using Regular Expression(Regex) in iOS. I don't want username to start with the word "guest". I tried below code but it's not working. [txtUserName addRegx:@"^(guest)" withMsg:@"Username Can't start with the word guest"]; Ideas? A: You can try to use this Regex: ^(?!guest).*$ Explanation: ^ assert position at start of the string (?!guest) Negative Lookahead - Assert that it is impossible to match the regex below guest matches the characters guest literally (case sensitive) .* matches any character (except newline) Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy] $ assert position at end of the string EDIT: To make it case insensitive you can try this: ^(?i:(?!guest)).*$
{ "pile_set_name": "StackExchange" }
Q: Find all the numbers in the range [a, b] that are not in the given std::set S Let a and b be integers, a < b. Given an std::set<int> S what is an efficient and elegant (preferably without explicit loops) way to find and store (into a vector) all the numbers from [a, b] that are not in S. Solution 1: vector<int> v; for(int i = a; i <= b; ++i) { if(S.find(i) == S.end()) { v.push_back(i); } } Solution 2: Push all the numbers from a to b into a set and use std::set_difference Solution1 contains an explicit loop, and solution2 does not seem very efficient (at least in terms of memory). What would you suggest? I am looking for an elegant STL-ish (boost is also acceptible) idiomatic way to do this. A: You can do something like your solution #2. But instead of creating an actual container containing the range [a,b], use boost::irange, which is a virtual container for a numeric range. This way you have no explicit loops, it will run in linear time, and not take too much memory. To make it even faster, make it cover only the relevant part of the set by using lower_bound/upper_bound: auto abRange = boost::irange(a,b+1); std::set_difference(abRange.begin(), abRange.end(), s.lower_bound(a), s.upper_bound(b), std::back_inserter(resultVector)); Or using Boost.Range's set_difference: boost::set_difference(boost::irange(a,b+1), std::make_pair(s.lower_bound(a), s.upper_bound(b)), std::back_inserter(resultVector));
{ "pile_set_name": "StackExchange" }
Q: Call interface method using reference of class I want to call an interface method using the reference of a class which implements that interface. I am using reflection for that but my code is not working and I am getting null object reference exception. The code is give below: interface IntA { void MethodFirst(); } interface IntB { void MethodFirst(); } class ClassA : IntA, IntB { public void MethodFirst() { Console.WriteLine("this.ClassA.MethodFirst"); } void IntA.MethodFirst() { Console.WriteLine("IntA.ClassA.MethodFirst"); } void IntB.MethodFirst() { Console.WriteLine("IntB.ClassA.MethodFirst"); } } class Program { static void Main(string[] args) { Type t = Type.GetType("ClassA"); t.GetMethod("MethodFirst").Invoke(Activator.CreateInstance(t,null), null); Console.ReadLine(); } } Please let me know what I am doing wrong over here. A: You need to try creating instance of your class using the full namespace of that class. for example, Type t = Type.GetType("ConsoleApplication1.ClassA"); In case, if you want to call a method from a particular interface - Type t = Type.GetType("ConsoleApplication1.ClassA"); t.GetInterface("ConsoleApplication1.IntB").GetMethod("MethodFirst").Invoke(Activator.CreateInstance(t, null), null);
{ "pile_set_name": "StackExchange" }
Q: SQL - making several groupings (performance) I have some SQL query that founds records based on provided parameters. That query is pretty heavy, so I want to execute it less as possible. After I getting result from that query, I need to perform its breakdown. For example, consider the following query: SELECT location, department, industry FROM data WHERE ... After that, I need to perform breakdown of that results, e.g. I need to provide list of all locations where from I have results and counts of each type, same for departments and same for industries. As I know, in order to get breakdown by locations, I need to perform GROUP BY (location) and then count. My question is: is it possible, for performance considerations, to perform several groupings/ counts on query result without recalculating it over and over again for each grouping? A: Yes, this is possible. Unless I misunderstood you. You need to use windowed functions. For instance: SELECT location , department , industry , COUNT(*) OVER(PARTITION BY location, department) , COUNT(*) OVER(PARTITION BY location, department, industry) FROM data WHERE ...; Keep in mind, that doing a COUNT(DISTINCT column) is not possible.
{ "pile_set_name": "StackExchange" }
Q: How can I refactor this method? private void Update_Record_Click(object sender, EventArgs e) { ConnectionClass.OpenConnection(); if (textBox4.Text == "" && textBox2.Text == "") { MessageBox.Show("No value entred for update."); } else if (textBox4.Text != "" && textBox2.Text != "") { SqlCommand cmd = new SqlCommand("update medicinerecord set quantity='" + textBox2.Text + "' where productid='"+comboBox1.Text+"'", ConnectionClass.OpenConnection()); cmd.ExecuteNonQuery(); cmd = new SqlCommand("update myrecord set price='" + textBox4.Text + "' where productid='" + comboBox1.Text + "'", ConnectionClass.OpenConnection()); cmd.ExecuteNonQuery(); ConnectionClass.CloseConnection(); } else if (textBox2.Text != "") { SqlCommand cmd = new SqlCommand("update myrecord set quantity='" + textBox2.Text + "' where productid='" + comboBox1.Text + "'", ConnectionClass.OpenConnection()); cmd.ExecuteNonQuery(); ConnectionClass.CloseConnection(); } else if (textBox4.Text != "") { SqlCommand cmd = new SqlCommand("update myrecord set price='" + textBox4.Text + "' where productid='" + comboBox1.Text + "'", ConnectionClass.OpenConnection()); cmd.ExecuteNonQuery(); ConnectionClass.CloseConnection(); } } It's working correctly but I want to make it shorter so that it's easier to understand. How can I refactor it? A: Disclaimer: as suggested by Darin, I changed his original solution a little bit. Doc Brown. The fact that this code is large is the least problem. You have a far bigger problems with SQL injection here. You should use parametrized queries to avoid this. So I would start with externalizing the data access logic into a separate method: public void UpdateMedicineRecordQuantity(string tableName, string attributeName, string productId, string attributeValue) { using (var conn = new SqlConnection("YOUR ConnectionString HERE")) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "UPDATE " + tableName + "SET " + attributeName+ " = @attributeValue where productid = @productid"; cmd.Parameters.AddWithValue("@attributeValue", attributeValue); cmd.Parameters.AddWithValue("@productid", productId); cmd.ExecuteNonQuery(); } } and then: string productId = comboBox1.Text; string quantity = textBox2.Text; UpdateMedicineRecordQuantity("medicinerecord", "quantity", productId, quantity); Using "tableName" and "attributeName" as dynamic parts of your SQL is no security problem as long as you don't let the user provide input for those two parameters. You could proceed reusing this method for the other cases. A: Statments like if (textBox4.Text == "" && textBox2.Text == "") means nothing at all, if you are not up to speed on what that particular part of the application is up to. In this case it seems as if they represent one value each, and that at least one of them should contain something for any operation to be legal. Studying the SQL statements suggests that textBox2 is a quantity and textBox4 is a price. First thing would be to change those control names into something more meaningful. Second, I'd wrap the checks into methods with more descriptive names: private bool HasPriceValue() { return !string.IsNullOrEmpty(textBox4.Text); } private bool HasQuantityValue() { return !string.IsNullOrEmpty(textBox2.Text); } Then you can rewrite the if-block as so: if (!HasPriceValue() && !HasQuantityValue()) { MessageBox.Show("No value entred for update."); } else { ConnectionClass.OpenConnection(); if (HasQuantityValue()) { SqlCommand cmd = new SqlCommand("update medicinerecord set quantity='" + textBox2.Text + "' where productid='"+comboBox1.Text+"'", ConnectionClass.OpenConnection()); cmd.ExecuteNonQuery(); } if (HasPriceValue()) { SqlCommand cmd = new SqlCommand("update myrecord set price='" + textBox4.Text + "' where productid='" + comboBox1.Text + "'", ConnectionClass.OpenConnection()); cmd.ExecuteNonQuery(); } ConnectionClass.CloseConnection(); } This way you don't repeat the SQL queries in the code and it's fairly easy to read the code and understand what it does. The next step would be to rewrite the SQL queries to use parameters instead of concatenated strings (which opens your code for SQL injection attacks), as suggested by Darin.
{ "pile_set_name": "StackExchange" }
Q: Python: Looping over and combining values in nested dictionaries I am creating a nested dictionary that describes several cases ('1ql' and '2ql'), each with a different number of variations ('var0', 'var1', ...). I use dict comprehension in the following manner: from numpy import random as rnd QLS = { key: { idx: rad for idx, rad in enumerate(['var{}'.format(i) for i in range(rnd.randint(1, 4))]) } for key in ['1ql', '2ql'] } This works great, but I have been struggling with the how to handle the dictionary for saving to file(s). I would like to iterate over each variation of '1ql', and then iterate simultaneously over each iteration of '2ql'. This can easily be accomplished like this: for key1, val1 in QLS['1ql'].items(): for key2, val2 in QLS['2ql'].items(): print('1ql: {}, 2ql: {}'.format(val1, val2)) which, for 2 variations of '1ql' and 3 variation '2ql', produces 6 total permutations: 1ql: var0, 2ql: var0 1ql: var0, 2ql: var1 1ql: var0, 2ql: var2 1ql: var1, 2ql: var0 1ql: var1, 2ql: var1 1ql: var1, 2ql: var2 However, I would like to get this automatically for any number of cases, for any number of variations per case, without having to specify these by hand. I have tried different iteration schemes and even by inverting the inner and outer keys, but to no avail. I would really like the to learn the most pythonic way to accomplish this. Thanks! A: First, transform the data to remove the parts we don't need: x = [[(case, var) for var in QLS[case].values()] for case in QLS.keys()] Now x is something like: [[('1ql', 'var0'), ('1ql', 'var1'), ('1ql', 'var2')], [('2ql', 'var0'), ('2ql', 'var1'), ('2ql', 'var2')]] Finally, use itertools.product() to get the result: list(itertools.product(*x)) Probably in your real code you'll iterate over the results and use print() on each one to get the format you need, but wrapping with list() as above gives you an idea: [(('1ql', 'var0'), ('2ql', 'var0')), (('1ql', 'var0'), ('2ql', 'var1')), (('1ql', 'var0'), ('2ql', 'var2')), (('1ql', 'var1'), ('2ql', 'var0')), (('1ql', 'var1'), ('2ql', 'var1')), (('1ql', 'var1'), ('2ql', 'var2')), (('1ql', 'var2'), ('2ql', 'var0')), (('1ql', 'var2'), ('2ql', 'var1')), (('1ql', 'var2'), ('2ql', 'var2'))]
{ "pile_set_name": "StackExchange" }
Q: How can I skip the header in Python? This is my code. I am trying to import the data from net Skip 12 lines Store the rest of the data in a variable and perform some simple operations. import urllib2 airtemp = urllib2.urlopen('http://coastwatch.glerl.noaa.gov/ftp/glsea/avgtemps/2013/glsea-temps2013_1024.dat').read(30000) airtemp = airtemp.split("\n") lineskip1 = 0 for line in airtemp: if lineskip1 <12: continue print line lineskip1+=1 But I'm not able to print the lines. Could you please help. I know this is Python 101. Sorry for that. A: You are continuing the loop without incrementing lineskip1, so the condition is always true. lineskip1 = 0 for line in airtemp: lineskip1 += 1 if lineskip1 <= 12: # Skip lines numbered 1 through 12 continue print line A better method is to use enumerate to count the lines for you. for i, line in enumerate(airtemp): if i < 12: # Skip lines numbered 0 through 11 continue print line or to use itertools.islice: from itertools import islice for line in islice(airtemp, 12, None): # Skip lines numbered 0 through 11 print line
{ "pile_set_name": "StackExchange" }
Q: Are there any measures to limit inheritance in capitalistic countries? I'm not asking here whether this should be done or not and not going to argue here that it's fair/unfair. Currently in most (if not all) market economy countries people are allowed to inherit property. Are there some of them that are limiting inheritance? Was there any attempt for it? If no why? Is it considered as undemocratic? Edit: while I could find info about Google on taxes, I don't consider tax as real limit. It is either percentage (or even fixed) payment. Nothing other that Google says me about inheritance. A: Yes. Many (but not all) countries have some form of estate or inheritance tax on a deceased person's assets. For example the UK has an inheritance tax; but Sweden does not, having abolished the tax in 2004. In countries which levy an inheritance tax, typically all assets below a certain threshold are exempt. There may also be exemptions for family businesses, farms, or inheritance by a spouse. The rate of taxation also varies. The UK rate peaked at 85% in 1969, but has since been reduced to 40%. As usual for international tax law, the details are complex. A simplified summary for 37 countries makes up a 400-page document (PDF link).
{ "pile_set_name": "StackExchange" }
Q: Find the Duration in Months between the contents in an Iterator Code: Iterator<String> termIncomeKeys = termIncome.keySet().iterator(); while(termIncomeKeys.hasNext()){ String month = termIncomeKeys.next(); System.out.println(month); } The month is printed as Jan(2012) - Jan(2012) Feb(2012) - Mar(2012) Apr(2012) - May(2012) Jun(2012) - Jun(2012) Jul(2012) - Oct(2012) What I want to achieve is I want to print the duration in terms of months between each of the entries. That is, Duration between first entry is 1 month, duration between second is 2 and so on. A: I do not know if there is a ready-made class that could parse these strings for you, but the logic is simple: convert the three-letter months to numbers (e.g. 0-11), and convert the years to numbers as well. The difference is <year-diff>*12 + <month-diff>, where <month-diff> might be negative.
{ "pile_set_name": "StackExchange" }
Q: How Do I Create/Configure Spring Actuator for Multiple Datasources? I have a project with multiple datasources and also implements spring actuator. When I access /health I get the following: {"status":"DOWN"} This doesn't make any sense to me. What is down? Also, why is database health missing? I'm assuming it's because my datasource prefix forks from the default. How do I configure actuator /health to display both datasource health statuses? A: In fact, health endpoint check more than one indicator. You only have {"status":"DOWN"} because by default spring boot application are secure. You can modify your application.properties with endpoints.health.sensitive=false to show all health indicators. You can find all auto-configured health indicators in this page : http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#_auto_configured_healthindicators And also, you can write your own health indicator by implementing HealthIndicator. @Component public class MyHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down().withDetail("Error Code", errorCode).build(); } return Health.up().build(); } }
{ "pile_set_name": "StackExchange" }
Q: In general how do Event Handlers work? This is a general topic, How do Event Handlers work? This means behind the scenes - what happens when they are created. I have a rough idea - but would like to have it confirmed. A: On a low-level, event handlers often work by polling a device and waiting for a hardware interrupt. Essentially, a background thread blocks, while waiting for a hardware interrupt to occur. When an interrupt occurs, the poll function stops blocking. The application can then find out which device handle caused the interrupt, and what type of interrupt it was, and then act accordingly (e.g. by invoking an event handler function). This is usually done in a separate thread so that it happens asynchronously. Of course, the way this is actually implemented varies considerably depending on the OS and the type of device/input. On UNIX systems, one way that event handlers are implemented for things like sockets, serial or USB ports is through the select or poll system calls. One or more file/device descriptors (which are associated with a device, like a network socket, serial/USB port, etc) are passed to the poll system call - which is made available to the programmer through a low-level C API. When an event occurs on one of these devices, (like say, some data arrives on a serial port), the poll system call stops blocking, and the application can then determine which device descriptor caused the event, and what type of event it was. On Windows this is handled differently, but the concepts are basically the same.
{ "pile_set_name": "StackExchange" }
Q: Open saved png's by savefig to plot them in subplots I saved plots with savefig like plt.savefig('1.png') and now I want to adjust them to determined subplots like: import matplotlib.pyplot as plt from PIL import Image img1 = Image.open("1.png") img1 = Image.open("2.png") img1 = Image.open("3.png") fig, (ax_1, ax_2, ax_3) = plt.subplots(nrows=3, ncols=1, sharex=True, figsize=(8.27,11.7)) ax_1.set_title('Plot1') ax_1 = img1 ax_2.set_title('Plot2') ax_2 = img2 ax_3.set_title('Plot3') ax_3 = img3 fig.suptitle('Name') plt.show() But I get 3 empty plots without an error A: Use ax.imshow(): import matplotlib.pyplot as plt from PIL import Image img1 = Image.open("1.png") img1 = Image.open("2.png") img1 = Image.open("3.png") fig, (ax_1, ax_2, ax_3) = plt.subplots(nrows=3, ncols=1, sharex=True, figsize=(8.27,11.7)) ax_1.set_title('Plot1') ax_1.imshow(img1) ax_2.set_title('Plot2') ax_2.imshow(img2) ax_3.set_title('Plot3') ax_3.imshow(img3) fig.suptitle('Name') plt.show() If you want to remove the ticks and tick labels, you can add ax.axis('off') for every axis you to remove them.
{ "pile_set_name": "StackExchange" }
Q: Combination problem question. I am working on a combination problem and I need to check if I'm doing this right. There is a deck of cards that consist of 20 cards. There are four different colors, including 2 Green, 6 Yellow, 8 Black and 4 Red cards. Each colors are numbered, so they are distinguishable. If one draws 4 cards from this deck without replacement, how many different hands of 4 cards can one make given that exactly two cards are black ? This is my claim. Two cards are black, so there are 8*7 ways of having them. The rest have to be non-black, so there are 12*11 ways of having them. Since we don't care about the order of how we have the four cards, we divide the permutations by the number of order, namely, 4!. So I think the ans is $\frac{8*7*12*11}{4!}$. However, a book that contains this problem says that instead of dividing the bottom by 4!, it is divided by 4. I think it is saying that there are 2! ways of ordering the black cards and 2! ways of ordering the non-black cards, but I don't think their claim is right, because it ignores the cases where Black-NonBlack-Black-NonBlack is treated as a different permutation. Can someone confirm which argument is correct ? A: We are not ordering the cards, we are counting the number of pairs of black cards, and the number of pairs of non-black cards. I would say that there are $\binom{8}{2}$ "tiny hands" of $2$ black cards, and $\binom{12}{2}$ tiny hands of $2$ non-black, fpr a total of $\binom{8}{2}\binom{12}{2}$ full hands of $4$. Or else imagine picking the $2$ black cards in order from the black bunch. This can be done in $(8)(7)$ ways. But this double-counts each tiny hand of two black cards, so the actual number is $\frac{8\cdot 7}{2}$. A similar calculation can be made with the non-black.
{ "pile_set_name": "StackExchange" }
Q: Detect which element is clicked In briefly, I load a local HTML page into a div inside other web form in asp.net. JQuery: <script> $(function () { $("#includedContent").load("../HtmlHolder/index.html"); }); </script> HTML: <div id="includedContent" class="WebHolder" style="width: 450px; height: 300px; border: 1px solid #808080; margin: 0px auto; overflow-y: scroll;"></div> Now I want to get element's class name by click on them by below script: <script> $(document).ready(function () { $('.WebHolder').on("click", "*", function (e) { alert("Class :" + $(this).attr("class")); }); }); </script> My Problem is, when I click on any element, this code alert this Class name and it's Parent! How to resolve it? Note: element is not specific object, maybe it's an input or button or textarea or ... . A: You should use e.target(Use this as selector) not this(Because it is the parent) alert("Class :" + $(e.target).attr("class")); To avoid performing the action on parent: You can compare this and e.target to validate if it is the parent. if( this !== e.target ) CODE SNIPPET FOR DEMO: $('div').on('click', function(e){ if( this !== e.target ) alert( 'Class is '+ $(e.target).attr('class') ); }); div{ background: #fe7a15; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> I am the parent, Clicking me will not get you an alert but headers does, because they are my children. <br /><br /> <h1 class="class-header-child-one">Header 1</h1> <h2 class="class-header-child-two">Header 2</h2> </div> A: Use event.stopPropagation() in the event handler. $('.WebHolder').on("click", "*", function (e) { alert("Class :" + $(this).attr("class")); e.stopPropagation(); }); This will prevent the event bubbling up the DOM tree. Demo: $(document.body).on('click', '*', function(e) { alert($(this).text()); e.stopPropagation(); }); div { background: red; } div > div { background: orange; } div > div > div { background: yellow; } div > div > div > div { background: gray; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Main <div>1 <div>11</div> <div>12</div> <div>13 <div>131</div> </div> </div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div>
{ "pile_set_name": "StackExchange" }
Q: WP_query twice on a single taxonomy I have a simple WP_query on a custom post and works fine: $args = array( 'post_type' => 'post-type', 'showposts' => 2, 'location' => 'london' ); but I want it to query two locations so used an array: $args = array( 'post_type' => 'post-type', 'showposts' => 2, 'location' => array('london','paris') ); but it only pulls in the last term. Is there another way that I should be doing this? A: $args = array( 'post_type' => 'post-type', 'tax_query' => array( array( 'taxonomy' => 'location', 'field' => 'slug', 'terms' => array('london','paris') ) ) ); Try this
{ "pile_set_name": "StackExchange" }
Q: CSS3PIE issues in IE6 and 8 I'm using CSS3PIE to apply some rounded corners to elements in Internet Explorer that will get them by stylesheet in other browsers. I've run into some issues with it though. In IE8, I discovered that any element that had the PIE behaviour would behave strangely. The container would jump a few pixels to the right, but the content would stay in its original position, giving the appearance that the content had all shifted left relative to its container. This would be especially problematic on elements with no or small amounts of padding. I was able to hack my way around the problem in IE8 by using X-UA-Compatible, but I'd rather avoid this solution if at all possible. I don't have access to IE9 for testing but my understanding hacks like PIE aren't necessary and it would be wasteful to force a compatibility mode in a browser that doesn't need it. I have worse issues in IE6, with the PIE layout breaking down completely on a list that is set up to use display:inline; zoom:1; list items (to simulate inline-block, which works in IE8 and the other browsers). Here the borders of the list items get rendered in completely the wrong place. So ideally, I'd like to have PIE work properly in IE6, and in IE8 without having to resort to compatibility mode. As far as IE6 goes, a graceful fallback where PIE is just not applied will do. IE7 is the only browser where the page displays as intended. I can't provide an example page just at the moment unfortunately, I can add one later though. Follow up: Here are some screen grabs made with IE Tester. I'm hoping they will make things a little more clear for everybody. As you can see, IE7 is fine. However, in IE8, the containers are offset to the left relative to their content, and in IE6 the list elements (with the rounded 1 pixel border) are a complete mess! Full size versions for IE8, IE7 and IE6 are also available Followup 2 Here's a link to a demo page. As other designers are working on the stylesheets and other parts of the design I can't promise it will remain fully reflective for very long, but hopefully it will for long enough to solve the problem. (Yes, I'm aware there's JS errors in IE6, those aren't my problem). Example page A: i prefer using http://www.curvycorners.net/
{ "pile_set_name": "StackExchange" }
Q: How do I branch a modified working copy with SVN? I started working on what I thought would be a small change to trunk, walked away for a month and now I realize this is really a whole side-project (full of bugs) that really needs its own branch. Furthermore, once I've branched these changes off, I want to reset my working copy back to what's currently in trunk so I can help out the main development effort and high-priority items before coming back to this side project when there's time. So: I would like to make a new branch, based on my working copy, without having to check in my working copy (it IS up to date with the latest HEAD revision though) Once I have forked my working copy, I would like to basically remove all changes that are in the branch, and just set it to match the current HEAD revision in trunk. What's the procedure? I'm using TortoiseSVN, but even command line instructions would be helpful. A: So I've tried two methods to branching my working copy without checking it in, not sure which one is going to end up being the best method: Method 1: Copy entire directory to new branch Right-click on your working copy folder and choose Tortoise SVN > Repo Browser In Repo Browser create a new directory called "branches" at the same level as "trunk" Inside the "branches" dir, create a new dir with the "name" of your branch (by "name" I mean, a label that will identify this branch, so e.g.: if you're working on a special notification system in this branch, call it "notifications" etc...) Now, still in Repo Browser right click and choose "Add Folder" and select your local working copy This will take a while, since all files (including .svn files) are being copied. This also copies unversioned files and files that you have svn:ignored, which may not be desired. Method 2: use Branch/tag Right click your working copy folder and choose Tortoise SVN > Branch/tag... It opens up the Repo Browser, so create a new directory "branches" and then inside that, a new dir with the "name" of your branch You select the "Working Copy" button in the "create copy in the repository from" section. This is what will commit the diff of your local changes to this branch This seems to only copy the files that are DIFFERENT from what's in the HEAD revision. However, if you then use the Repo Browser again to see what's in there, the entire HEAD revision + your local changes are all in there It looks like Method 2 is definitely preferable. Then, to clean up, it was a matter of Tortoise SVN > Revert... and "Delete all unversioned" A: In command-line you can create a patch with the subversion "diff" command, and then apply it to your new branch with the subversion "patch" command. (You can read about these commands by executing 'svn help diff' and 'svn help patch'). Let's say you have the trunk and a branch called new_branch in the same parent directory. cd trunk svn diff > ..\my_stuff.diff Now you have the patch, then apply it to your newly created branch. cd new_branch svn patch ..\my_stuff.diff You can dry run the patch first by adding the --dry-run flag to the patch command, to see if anything strange happens before actually applying it. svn patch ..\my_stuff.diff --dry-run A: In case you prefer to continue working on in the same folder, this post shows how to. Basically svn copy to create a branch svn switch to point to new branch from the same working copy and svn commit to commit your changes. Be sure you branch off your from the same branch/revision you started modify (svn info to check) or you may endup with many conflicts after switch.
{ "pile_set_name": "StackExchange" }
Q: reading files and averging, keeps asking for user input I am supposed to ask the user for the name of the file, then read the file and average the numbers in the file, my program just keeps asking for the name of the file. import java.util.Scanner; import java.io.*; public class A13_Average { public static void main(String[] args) { getFile(); } public static void getFile() { String name; int sum = 0; int num = 0; try { //Gets the user to input name of file Scanner in = new Scanner(System.in); System.out.print("Enter the name of your file: "); name = in.nextLine(); //gets each line of numbers Scanner input = new Scanner(new File(name)); input.nextInt(); while(input.hasNextLine()); { //sum of the numbers sum += input.nextInt(); //number of numbers num += 1; } System.out.println("The average of your numbers is: "); System.out.printf("#0.00", (sum/num)); in.close(); } catch (Exception i) { System.out.println("Error: " + i.getMessage()); } } } This is the numbers.txt the file to test with: 10 84 39 93 34 14 11 33 88 83 28 97 75 49 32 69 80 95 48 19 33 85 48 20 48 22 87 72 9 55 14 21 79 94 40 99 90 1 1 66 38 76 59 57 29 29 32 71 2 72 13 74 35 24 29 24 21 78 76 52 74 29 25 54 100 96 59 55 9 71 1 99 88 82 24 38 72 10 3 8 43 43 49 28 6 48 15 27 93 34 4 87 73 24 28 12 52 66 10 63 8 34 100 2 56 22 89 96 56 27 83 29 22 98 80 96 64 17 84 39 82 16 62 99 88 85 52 72 15 25 48 14 10 82 21 75 50 40 99 92 27 86 66 38 79 85 54 94 46 93 34 15 31 57 31 55 10 99 90 100 99 95 47 5 98 85 48 17 90 2 27 92 17 87 74 34 8 36 42 30 46 89 92 26 64 15 46 95 52 72 14 16 68 63 11 39 88 77 71 100 96 62 93 32 82 21 60 71 6 53 90 2 28 3 21 78 78 78 77 64 19 25 52 69 74 33 85 48 15 45 80 96 58 53 82 19 33 97 68 64 25 49 25 57 41 14 3 9 75 42 31 64 19 19 34 7 9 56 22 88 81 6 48 22 87 74 32 83 35 22 96 61 90 100 97 75 41 10 92 21 70 91 13 89 94 38 77 63 12 59 57 30 49 32 72 9 73 20 56 17 91 11 38 71 6 75 46 90 98 82 19 23 1 63 3 13 83 29 23 9 67 60 72 17 74 34 11 33 87 73 28 11 26 66 46 90 99 93 32 81 13 72 16 63 5 4 43 54 91 8 34 1 4 72 8 24 28 97 73 20 59 62 100 1 49 29 22 84 44 66 47 5 1 93 28 98 76 58 45 70 85 48 13 75 41 12 49 34 8 20 50 48 10 5 15 41 10 3 27 95 48 18 11 36 45 78 74 36 40 9 53 84 45 80 97 72 9 57 36 38 64 22 93 28 7 94 37 58 46 91 10 87 68 63 5 37 49 26 61 88 81 11 19 27 91 12 54 1 3 12 52 65 28 98 80 98 77 69 73 27 82 23 12 66 45 70 93 31 51 59 55 10 1 75 49 35 18 97 70 86 59 65 35 31 54 100 98 76 58 43 41 21 78 82 16 48 12 50 46 84 45 75 43 48 22 97 70 91 10 7 94 39 94 44 65 33 100 98 84 36 43 50 42 25 44 60 77 65 30 43 46 86 62 100 1 49 29 22 84 44 66 47 5 1 93 28 98 76 58 45 70 85 48 13 75 41 12 49 34 8 20 50 48 10 5 15 41 10 3 27 95 48 18 11 36 45 78 74 36 40 9 53 84 45 80 97 72 9 57 36 38 64 22 93 28 7 94 37 58 46 91 10 87 68 63 5 37 49 26 61 88 81 11 19 27 91 12 54 1 3 12 52 65 28 98 80 98 77 69 73 27 82 23 12 66 45 70 93 31 51 59 55 10 1 75 49 35 18 97 70 86 59 65 35 31 54 100 98 76 58 43 41 21 78 82 16 48 12 50 46 84 45 75 43 48 22 10 70 91 10 7 94 39 94 44 65 33 100 98 84 36 43 50 42 25 44 60 77 65 30 43 46 86 62 100 1 49 29 22 84 44 66 47 5 1 93 28 98 76 58 45 70 85 48 13 75 41 12 49 34 8 20 50 48 10 5 15 41 10 3 27 95 48 18 11 36 45 78 74 36 40 9 53 84 45 80 97 72 9 57 36 38 64 22 93 28 7 94 37 58 46 91 10 87 68 63 5 37 49 26 61 88 81 11 19 27 91 12 54 1 3 12 52 65 28 98 80 98 77 69 73 27 82 23 12 66 45 70 93 31 51 59 55 10 1 75 49 35 18 97 70 86 59 65 35 31 54 100 98 76 58 43 41 21 78 82 16 48 12 50 46 84 45 75 43 48 22 97 70 91 10 7 94 39 94 44 65 33 100 98 84 36 43 50 42 25 44 60 77 65 30 43 46 86 62 100 1 49 29 22 84 44 66 47 5 1 93 28 98 76 58 45 70 85 48 13 75 41 12 49 34 8 20 50 48 10 5 15 41 10 3 27 95 48 18 11 36 45 78 74 36 40 9 53 84 45 80 97 72 9 57 36 38 64 22 93 28 7 94 37 58 46 91 10 87 68 63 5 37 49 26 61 88 81 11 19 27 91 12 54 1 3 12 52 65 28 98 80 98 77 69 73 27 82 23 12 66 45 70 93 31 51 59 55 10 1 75 49 35 18 97 70 86 59 65 35 31 54 100 A: Here's your problem while(input.hasNextLine()); Delete the ; while(input.hasNextLine()) The ; is an ending statement
{ "pile_set_name": "StackExchange" }
Q: iOS "info.plist" Добрый день, изучаю iOS^ и сейчас пытаюсь засунуть значение в Plist файл но ничего не выходит. NSString *path = [[NSBundle mainBundle] bundlePath]; NSString *finalPath = [path stringByAppendingPathComponent:@"test.plist"]; NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:finalPath]; [plistDict setValue:@"over" forKey:@"over"]; [plistDict writeToFile:finalPath atomically: YES]; NSLog(@"the value is %@",plistDict); Вот мой код, подскажите что тут неверно ?? A: Вы не можете писать в бандл. Чтобы сохранить файл в плист нужно писать его в другое место, что-то вроде NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; NSString *finalPath = [path stringByAppendingPathComponent:@"test.plist"]; ... У каждого приложения есть своя "песочница", и они могу писать только туда. Детальнее здесь, пункт The App Sandbox
{ "pile_set_name": "StackExchange" }
Q: String alignment does not work with ansi colors Facing this issue with Python: a = "text" print('{0:>10}'.format(a)) # output: text b = "\x1b[33mtext\x1b[0m" print('{0:>10}'.format(b)) # output: text As you can see the right-justification stopped working once the coloring tags get added to the text. The second "text" should be indented as the first one, but it was not. A: This is to be expected because the data is already longer than your field width: >>> len(b) 13 >>> len('{0:>10}'.format(b)) 13 To see a workaround, check here: Printed length of a string in python (in particular, the answer from user dawg)
{ "pile_set_name": "StackExchange" }
Q: While loop over range(0,5) with ran = ran[:-1]; ran != [] is always true I have a very simple code in Python and can't figure out why the loop won't stop. I specifically wanted to use a helper function inside the function. Any ideas? def x(): a = range(0,5) def y(ran): while ran != []: ran = ran[:-1] print(ran) return y(ran) return y(a) x() A: use while ran: as the condition you specified will always be true as ran is a range rather than a list.
{ "pile_set_name": "StackExchange" }
Q: Editor of manuscript assigned after reviews were completed Recently, I submitted a paper to a journal. The paper was reviewed and the reviewers asked for some changes. I revised the paper and sent it again. The paper was reviewed again and after a few months the status was shown as "reviews completed". But the status was again changed to "editor assigned". Could you please explain to me what does this imply? A: Each journal has its specific take, but the most likely explanation is that the peer review process took longer than usual and the same editor had expired and had to be reassigned, or that he was no longer interested in handling your manuscript and it was thus assigned to another editor. In most busy journals several associate editors cooperate with the editor-in-chief, and it is likely that your manuscript was switched from one associate editor to another one.
{ "pile_set_name": "StackExchange" }