text
stringlengths
64
89.7k
meta
dict
Q: does x = User.all create a hash? How do I traverse it? Let's say I have a User table and a Messages table, they have a has_many belongs_to relationship. I want to find the id: for users who's names are "Bob", then pull the message history for one of the id's. x = User.where(name: "Bob") Does that create a hash in variable x, with all the results of users whose names were Bob? The result in the console certainly looks like a hash when I run x. To includes the messages tied to all the Bobs, I think I do: x = User.where(name: "Bob").includes(:messages) Now that I have x...how do I find the id's of the people whose names are Bob? I don't want to query the db again, I'd like to do it all via the variable, is that possible? I then want to get the first message of the first id (the first Bob) in my table. Can that be done via the variable, or do I have to go back to the DB once I have the first id? Thanks for all the help guys and gals! A: Most ActiveRecord queries return a Relation. You can call x = x.to_a to make rails perform the actual query(there will be 2 SQL queries - one for users and one for messages) and then traverse the resulting array.
{ "pile_set_name": "StackExchange" }
Q: How to write like statements in Entity Framework when the liked valued contains % I know that String.Contains('x') would translate to LIKE '%x%', and String.StartsWith('x') and String.EndsWith('x') would translate into LIKE '%x' and LIKE 'x%' respectively. However, I'm now in a situation in which I'm gonna build the LIKE operator regular expression clause in the business layer, and send it to the SQL Server through Entity Framework. I mean, now the end users builds the regular expression through a GUI and we need to retrieve the result based on that. For example, user creates something like [Any Letter][Any Number]ab[Many Characters] and we translate it into [a-zA-Z][0-9]ab%. Now we want to send this to SQL Server using Entity Framework. However, it seems that Entity Framework can't do this, and the query won't get the correct result back. Any idea how we should implement this requirement? A: Entity framework is able to do this but linq-to-entities are not. You must use Entity SQL and LIKE operator. Some example.
{ "pile_set_name": "StackExchange" }
Q: Automorphism group Let $G=PSL(2,q)$ where $q$ is prime power. What is Aut$(G\times G)$ and Aut$(G\times G\times G)$? Also if $G=A_{n}$ where $A_{n}$ is the alternating group of degree $n$, then what is Aut$(G\times G)$? Thanks in advance A: In general, if $S$ is a finite non-Abelian simple group, and $E$ is a direct product of $n$ copies of $S$, then ${\rm Out}(E) = {\rm Aut}(E)/E$ is isomorphic to ${\rm Out}(S) \wr S_{n}.$ This is because every minimal normal subgroup of $E$ is isomorphic to $S$ (in fact, is one of the obvious simple direct factors of $E$) and the automorphism group of $S$ permutes the minimal normal subgroups of $E$. To provide more detail in order to make up for the lack of a reference: The $n$ "obvious" simple direct factors of $E$ are called the components of $E.$ The direct product of $n$ copies of ${\rm Aut}(S)$ obviously sits inside ${\rm Aut}(E).$ Furthermore, the assumed isomorphisms between the $n$ components may be included to show that ${\rm Aut}(S) \wr S_{n}$ embeds in ${\rm Aut}(E).$ On the other hand, the permutation action of ${\rm Aut}(E)$ on the components of $E$ gives a homomorphism from ${\rm Aut}(E)$ to $S_{n}.$ The kernel of this homomorphism is the intersection $K$ of the normalizers of the individual components. Since $E$ contains its centralizer in ${\rm Aut}(E)$, the group $K/E$ is isomorphic to a subgroup of a direct product of $n$ copies of ${\rm Out}(S).$ Hence this establishes that $|{\rm Aut}(E)| \leq | {\rm Aut}(S) \wr S_{n}|.$ But we have the inequality the other way round, so ${\rm Aut}(E) \cong {\rm Aut}(S) \wr S_{n}.$ A: See this wikipedia article. The result mentioned there implies that the automorphism group is the wreath product power of the automorphism group of $G.$
{ "pile_set_name": "StackExchange" }
Q: How do I use OAuth with Imgur? So I am trying to get information of various images, for which I will use the Imgur API through Java. I have found a library: https://github.com/fernandezpablo85/scribe-java, but when trying the ImgUrTest.java @ https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/ImgUrExample.java, I get the following stacktrace: Exception in thread "main" org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'OAuth Verification Failed: The consumer_key "<Client-ID>" token "" combination does not exist or is not enabled.' at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41) at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27) at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:64) at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:40) at org.scribe.oauth.OAuth10aServiceImpl.getRequestToken(OAuth10aServiceImpl.java:45) at ImgUrExample.main(ImgUrExample.java:31) where <Client-ID> is my client id, as found on ImgUr's page. I have checked that my Client Id and Client Secret are correct, I have tried making multiple apps on the ImgUr site, none of which work. Edit: This code works: URL imgURL = new URL(YOUR_REQUEST_URL); HttpURLConnection conn = (HttpURLConnection) imgURL.openConnection(); conn.setRequestMethod("GET"); if (accessToken != null) { conn.setRequestProperty("Authorization", "Bearer " + accessToken); } else { conn.setRequestProperty("Authorization", "Client-ID " + CLIENT_ID); } BufferedReader bin = null; bin = new BufferedReader(new InputStreamReader(conn.getInputStream())); A: First, the example is using Imgur API v2 which is old and unsupported. You should be using API v3. Also note that: For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests. from docs at https://api.imgur.com/oauth2 -- so you don't really need OAuth for what you're doing. There is some example Imgur API code that might help you, listed at https://api.imgur.com/ -- the Android example might be more relevant to you, since it uses Java, but unsurprisingly it comes with all the overhead of an Android project, compared with a plain Java application.
{ "pile_set_name": "StackExchange" }
Q: Mostrar imagem abaixo de div on hover Boa tarde, Preciso construir um efeito em um blog onde quando você passa o mouse sobre a div rosa, mostra uma imagem que está ao fundo dela. Porém preciso mostrar essa imagem somente na área onde está a fechadura. O layout é esse aqui. A parte que eu preciso que apareça a imagem é somente no box rosa do topo. Basicamente, o ícone de fechadura iria seguir o cursor, e conforme vai mexendo o mouse, vai mostrando a imagem. Poderiam me ajudar com referências ou um norte de como fazer? Creio que dê pra fazer isso com jquery ou canvas, talvez até com um pouco de css e js. A estrutura já está toda montada, só preciso mesmo fazer isso. Obrigado. A: Consegui resolver usando uma imagem como "máscara" e um background fixed. Segue o site: http://lancamentos.euroamericaconstrutora.com.br/papodecasa/
{ "pile_set_name": "StackExchange" }
Q: "In between" or "between"? There's a misunderstanding (in) between us. Is it natural with in or without? In which case should we add in? A: You can use in between when referring to something physical: There is a puddle in between us. But when referring to something intangible or metaphorical, stick with between: There is some tension between us. Note that, in the first case, the in is optional; one could just as well say: There is a puddle between us. However, the in reads awkwardly when talking about something more abstract, and should therefore be omitted: We have a disagreement in between us. Note: American English; other dialects may treat this differently
{ "pile_set_name": "StackExchange" }
Q: Quasar Vue Socket.io Laravel-Echo Implementation Im using quasar framework and trying to add laravel-echo with socket.io. Socket server is up and running and broadcasting event with no issues. But for some reason my client side does not want to connect it keeps giving me error that cannot read property 'channel' of undefined. My Setup package.json "laravel-echo": "^1.5.4", "quasar": "^1.0.5", "socket.io-client": "^2.2.0", boot/laravel-echo.js import Echo from 'laravel-echo' window.io = require('socket.io-client') const echo = new Echo({ broadcaster: 'socket-io', host: window.location.hostname + ':6001' }) export default ({ Vue }) => { Vue.prototype.$echo = echo } quasar.conf.js boot: [ 'axios', 'laravel-echo' ], index.vue created () { this.listen() }, methods: { listen() { this.$echo.channel('test').listen('event', payload => { console.log('THIS IS THE PAYLOAD: ' + payload) }) } } Browser [Vue warn]: Error in created hook: "TypeError: Cannot read property 'channel' of undefined" found in ---> <AllEvents> <QPage> <DashboardIndex> at src/pages/dashboard/Index.vue <QPageContainer> Socket.io L A R A V E L E C H O S E R V E R version 1.5.6 ⚠ Starting server in DEV mode... ✔ Running at localhost on port 6001 ✔ Channels are ready. ✔ Listening for http events... ✔ Listening for redis events... Server ready! Channel: test Event: event I have even change the code to the same as in the laravel documentation (https://laravel.com/docs/5.8/broadcasting#receiving-broadcasts) with window.Echo import Echo from 'laravel-echo' window.io = require('socket.io-client') window.Echo = new Echo({ broadcaster: 'socket-io', host: window.location.hostname + ':6001' }) export default async ({ Vue }) => { } and trying to connect to channel window.Echo.channel('test').listen('event', payload => { console.log('Here') console.log(payload) }) but still getting the same error on the browser, not sure what im missing here, any help would be greatly appreciated. A: :( uh man, what a noob, Should be broadcaster: 'socket.io', and not broadcaster: 'socket-io',
{ "pile_set_name": "StackExchange" }
Q: HTACCESS: How to URL rewrite a sub-subdomain? I have the subdomain apps.domain.com pointing to domain.com/apps I would like to URL rewrite appName.apps.domain.com, where appName is the variable pointing to domain.com/apps/appName I'm looking for an internal forward (no change in the browser's URL) What should I have in my .htaccess file and where should I save it? Within /apps/ folder? Or within the root folder? Lastly, if it is not possible with an .htaccess file, how can I do this? I'm using a Linux godaddy server as host. **** Question updated 07/08/2018; added more details **** I am using GoDaddy SHARED hosting It is currently hosting multiple domains Thus, the directory structure is public_html/domain.com/, where /domain.com/ is the name of the hosted domain name(s) The sub-subdomain is exclusive to 1 specific domain Example: If the domain name is domain.com There's multiple names, but to give an example. if the name of the app is awesome If the uri is: awesome.apps.domain.com will point to...public_html/domain.com/apps/awesome/ If the uri is: ubertz.apps.domain.com will point to...public_html/domain.com/apps/ubertz/ And so on... A: I'm using this code for subdomain forwarding: RewriteEngine on RewriteCond %{HTTP_HOST} ^(.*)\.apps\.domain\.com$ RewriteRule (.*) /apps/%1/$1 Explanation: In RewriteCond you catch app name using regular expression (.*) - it will be saved to variable %1 In RewriteRule you forward everything - that's another (.*) expression which content will be saved in variable $1 - to the directory /apps/<appName>/<path after URL> For more information about Regular Expressions I recommend to check this tutorial: http://www.webforgers.net/mod-rewrite/mod-rewrite-syntax.php You should save your .htaccess in the root directory of the domain, in your case in the public_html/domain.com/. If it doesn't work, place it in the apps folder. A: Create wildcard sub-subdomain The first thing that you need to do is to create a wildcard *.apps.domain.com sub-subdomain. (If you're using Nameservers, skip this step!) Log in to your domain name registrar, and create an A record for *.apps.domain.com (yeah, that's an asterisk) and point it to the server IP address. Note that DNS can take up to 48 hours to propagate. Log in your web hosting account and go to the menu 'Subdomains' under Domains section. Create a Subdomain *.apps.domain.com that's pointed to the "/public_html/domain.com/apps" folder as its Document Root. And wait until the propagation is over. Visit How to create wildcard subdomain in cPanel and How to Create a Sub-Subdomain for more info. If your server's configuration didn't allow you to create a wildcard sub-subdomain then just create *.domain.com and point it to "/public_html/domain.com/apps". Rewrite wildcard sub-subdomain Place these directives in the .htaccess file of the document root of the wildcard *.apps.domain.com which in this case is "/public_html/domain.com/apps". RewriteEngine on RewriteCond %{HTTP_HOST} ^(.+)\.apps\.domain\.com RewriteRule (.*) http://domain.com/apps/%1/$1 [QSA,P,L] The %1 is the numbered backreference of (.+) and the $1 is of (.*). You need to include the [P] flag if you URL rewrite from a specific domain http://domain.com/apps/%1/$1 in the same server, without that it will be redirected. Use the [QSA] flag if you'll going to use the query string of a rewritten wildcard subdomain. Visit P|proxy and QSA|qsappend for more info about them. And just tweak some adjustment if I forgot something, other than that, is the server's fault. Few things to consider You must configure your .htaccess file for the duplicate subdomains that will be going to exist, such the otherwildcard.apps.domain.com, another.wilcard.apps.domain.com and the other.deep.level.apps.domain.com that will duplicate apps.domain.com as they're all have the same document root. Configure to redirect or to tell to the client that those subdomains aren't exist.
{ "pile_set_name": "StackExchange" }
Q: Filtering a Django model using the related names of 2 M2M fields I have the following structure in my models: class Sauce(models.Model): ... class Topping(models.Model): ... class Pizza(models.Model): sauces = models.ManyToManyField(Sauce, related_name='pizzas') toppings = models.ManyToManyField(Topping, related_name='pizzas') Now, lets say I want to query all the pizzas given a list of toppings and sauces. For example: sauces_ids = [2, 5, 7, 8] toppings_ids = [1, 4, 5, 21] What is the most efficient way to query this using Django's ORM? Thanks for any help. A: Assuming those are values of pk/id field, you can use the __in lookup: Pizza.objects.filter(sauces__in=sauces_ids, toppings__in=toppings_ids) If those are values of some other field, you need to reference the field name as well, e.g. with field name field: Pizza.objects.filter(sauces__field__in=sauces_ids, toppings__field__in=toppings_ids)
{ "pile_set_name": "StackExchange" }
Q: Devise Recoverable says Email can't be blank on Rails 4/5 Given I am a registered user And I am not logged in When I visit "http://localhost:3000/member/password/edit?reset_password_token=BVE492WU1YqMp6nmxCX4" And I fill in "asdfasdf" in "user[:password] And I fill in "asdfasdf" in "user[:password_confirmation] And I submit form Then I see "Email can't be blank" -> which should be skipped routes.rb devise_for :users, path: 'member', controllers: {registrations: 'member/registrations', sessions: 'member/sessions', passwords: 'member/passwords', confirmations: 'member/confirmations', unlocks: 'member/unlocks', omniauth_callbacks: 'member/omniauth_callbacks'} devise_scope :user do match 'member/finish_signup/:id', to: 'member/registrations#finish_signup', via: [:get, :post], :as => :finish_signup match 'member/show_token', to: 'member/registrations#show_token', via: [:get, :post] # also tried without the following lines patch 'member/password' => 'member/passwords#update' put 'member/password' => 'member/passwords#update' end application_controller.rb before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_in, keys: [:email, :password]) devise_parameter_sanitizer.permit(:account_update, keys: [:email, :password, :password_confirmation]) # NONE of the both below change anything devise_parameter_sanitizer.permit(:sign_up, keys: [:email, :password, :password_confirmation]) # this one does not work anymore # devise_parameter_sanitizer.for(:sign_up) do |u| # u.permit(:email,:password,:password_confirmation) # end end passwords/edit.html.erb <%= form_for(resource, as: resource_name, url: password_path(resource_name), method: :put) do |f| %> <%= devise_error_messages! %> <%= f.hidden_field :reset_password_token %> <% if @minimum_password_length %> <em>(<%= @minimum_password_length %> characters minimum)</em><br/> <% end %> <%= f.password_field :password, autofocus: true, autocomplete: "off" %> <%= f.password_field :password_confirmation, autocomplete: "off" %> <%= f.submit "Change my password" %> <% end %> also tried this: <%= form_for(resource, as: resource_name, url: member_password_path(resource_name), html: {method: :put}) do |f| %> The rendered HTML is which looks good (post method): <form class="new_user" id="new_user" action="/member/password.user" accept-charset="UTF-8" method="post"> <input name="utf8" type="hidden" value="✓"><input type="hidden" name="_method" value="patch"> <input type="hidden" name="authenticity_token" value="Egh7QFhtHwcBVCuUgTDFnOF2C/g2Ql/sKeiuwjchjmpDh4JqyBPuLTaN9VT9iFFiP7JDxbp0+BeeA2QUSJWN3g=="> <input type="hidden" value="BVE492WU1YqMp6nmxCX4" name="user[reset_password_token]" id="user_reset_password_token"> <em>(8 characters minimum)</em><br> <input autofocus="autofocus" autocomplete="off" type="password" name="user[password]" id="user_password"> <input autocomplete="off" type="password" name="user[password_confirmation]" id="user_password_confirmation"> <input type="submit" name="commit" value="Change my password" data-disable-with="Change my password"> </form> member/passwords_controller.rb class Member::PasswordsController < Devise::PasswordsController end rake routes: new_user_session GET /member/sign_in(.:format) member/sessions#new user_session POST /member/sign_in(.:format) member/sessions#create destroy_user_session GET /member/sign_out(.:format) member/sessions#destroy user_omniauth_authorize GET|POST /member/auth/:provider(.:format) member/omniauth_callbacks#passthru {:provider=>/facebook/} user_omniauth_callback GET|POST /member/auth/:action/callback(.:format) member/omniauth_callbacks#(?-mix:facebook) user_password POST /member/password(.:format) member/passwords#create new_user_password GET /member/password/new(.:format) member/passwords#new edit_user_password GET /member/password/edit(.:format) member/passwords#edit PATCH /member/password(.:format) member/passwords#update PUT /member/password(.:format) member/passwords#update cancel_user_registration GET /member/cancel(.:format) member/registrations#cancel user_registration POST /member(.:format) member/registrations#create new_user_registration GET /member/sign_up(.:format) member/registrations#new edit_user_registration GET /member/edit(.:format) member/registrations#edit PATCH /member(.:format) member/registrations#update PUT /member(.:format) member/registrations#update DELETE /member(.:format) member/registrations#destroy user_confirmation POST /member/confirmation(.:format) member/confirmations#create new_user_confirmation GET /member/confirmation/new(.:format) member/confirmations#new GET /member/confirmation(.:format) member/confirmations#show user_unlock POST /member/unlock(.:format) member/unlocks#create new_user_unlock GET /member/unlock/new(.:format) member/unlocks#new GET /member/unlock(.:format) member/unlocks#show finish_signup GET|POST /member/finish_signup/:id(.:format) member/registrations#finish_signup member_show_token GET|POST /member/show_token(.:format) member/registrations#show_token member_password PATCH /member/password(.:format) member/passwords#update PUT /member/password(.:format) member/passwords#update And this is the log when I submit the filled out "/passwords/edit.html.erb" (http://localhost:3000/member/password/edit?reset_password_token=BVE492WU1YqMp6nmxCX4) Started GET "/member/password/edit?reset_password_token=[FILTERED]" for 127.0.0.1 at 2016-03-04 12:40:41 +0100 Processing by Member::PasswordsController#edit as HTML Parameters: {"reset_password_token"=>"[FILTERED]"} DEPRECATION WARNING: [Devise] Changing the sanitized parameters through "Devise::ParameterSanitizer#for(sign_up) is deprecated and it will be removed from Devise 4.1. Please use the `permit` method: devise_parameter_sanitizer.permit(:sign_up) do |user| # Your block here. end (called from deprecate_for_with_block at /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/devise-4.0.0.rc1/lib/devise/parameter_sanitizer.rb:177) Rendered devise/shared/_links.html.erb (1.6ms) Rendered devise/passwords/edit.html.erb within layouts/application (3.5ms) Completed 200 OK in 14ms (Views: 11.5ms) Incoming Headers: Origin: http://localhost:3000 Access-Control-Request-Method: Access-Control-Request-Headers: Started POST "/member/password.user" for 127.0.0.1 at 2016-03-04 12:41:19 +0100 Processing by Member::PasswordsController#create as Parameters: {"utf8"=>"✓", "authenticity_token"=>"gmyAZDVZR4Z/OO3oa934MzNUwCFnzDSd7QLo6ZCoAnjT43lOpSe2rEjhMygXZWzN7ZCIHOv6k2Za6SI/7xwBzA==", "user"=>{"reset_password_token"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Change my password"} Completed 406 Not Acceptable in 2ms ActionController::UnknownFormat (ActionController::UnknownFormat): responders (2.1.1) lib/action_controller/respond_with.rb:207:in `respond_with' devise (4.0.0.rc1) app/controllers/devise/passwords_controller.rb:19:in `create' /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/bundler/gems/rails-c901fad42cb4/actionpack/lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action' /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/bundler/gems/rails-c901fad42cb4/actionpack/lib/abstract_controller/base.rb:183:in `process_action' /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/bundler/gems/rails-c901fad42cb4/actionpack/lib/action_controller/metal/rendering.rb:30:in `process_action' /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/bundler/gems/rails-c901fad42cb4/actionpack/lib/abstract_controller/callbacks.rb:20:in `block in process_action' /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/bundler/gems/rails-c901fad42cb4/activesupport/lib/active_support/callbacks.rb:126:in `call' /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/bundler/gems/rails-c901fad42cb4/activesupport/lib/active_support/callbacks.rb:126:in `call' /Users/jan/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/bundler/gems/rails-c901fad42cb4/activesupport/lib/active_support/callbacks.rb:506:in `blo I think the routing from password_path(resource_name) is incorrect. It brings me to member/passwords#create instead of member/passwords#update which seems to be right. Please, how can I fix this? .gemfile gem 'rails', github: "rails/rails" gem 'active_model_serializers', github: "rails-api/active_model_serializers", branch: 'master' gem 'mongoid', git: 'https://github.com/estolfo/mongoid.git', branch: 'MONGOID-4218-rails-5' # api token authentication for devise gem 'devise', "4.0.0.rc1" # we can switch back when Rails 5, and Devise 4 is supported gem 'simple_token_authentication', github: "consti/simple_token_authentication" gem 'bootstrap_form' gem 'omniauth' gem 'omniauth-facebook' A: Changing the as: name and the of the route and the method to post did the trick. It seems that they got not overridden in my devise_scope. 'member/password/update' => 'member/passwords#update', as: :member_password_custom_update
{ "pile_set_name": "StackExchange" }
Q: Server can't find file 'will_paginate' after will_paginate gem installed I have gem 'will_paginate', '~> 3.0.6' installed on my app. But when I add the code //= require will_paginate into my application.js and try to load a page, I get the following error: Couldn't find file 'will_paginate' Does anyone know why my server might not be able to find the file? A: If I understand correctly, your Application.js has this line: //= require will_paginate When the app launches it looks for the listed JavaScript files/libraries to be available. will_paginate.js doesn't exist, so app errors out on load. "will_paginate" is a gem, so I think rubykid is right--bundle all. The next step is make sure all the .paginate hooks are in all the right places in the controllers and views. But you didn't ask about that, so I won't go there. Good luck.
{ "pile_set_name": "StackExchange" }
Q: How do I replace an attribute in a function with a variable? I have this code: .load($(this).attr('href'), function (responseText, textStatus) { Now, I want to modify that to loading a predefined variable instead of the href attribute. I tried this here but get an error: params="option=1"; // example var URL=ajax_url+"/?"+params; .load($(this)URL, function (responseText, textStatus) { What's the correct way? A: If your "URL" is valid, then it should just be: .load(URL, function (responseText, textStatus) { }
{ "pile_set_name": "StackExchange" }
Q: iOS self taught developer transitioning to Android Hi I've been making iOS apps for about 3 1/2 years, I'm self taught and basically learnt how to program iOS apps by trial and error & youtube. I want to have my apps available on android because I've started making a lot of sales and want to expand my market, where is the best place to start? A: Understand very clearly how the android activity lifecycle works, and look a lot into the style guide. Android is a whole different look/feel/style from iOS.
{ "pile_set_name": "StackExchange" }
Q: How to check where the code redirect in a PHP and jquery project I am working on a open source e-shop called Prestashop. The problem is, when I disable a module, the site will auto refresh. I would like to know which part of the code and file caused the problem. Here is the site: prestigefood.com.hk/zh/ Are there any way to check through browser's developer console / tools to see: Redirect caused by JS / PHP? Where is that part of code A: The redirect is caused by a JS function inside /js/tools.js : function autoUrl(name, dest) { var loc; var id_list; id_list = document.getElementById(name); loc = id_list.options[id_list.selectedIndex].value; if (loc != 0) location.href = dest+loc; return ; } Or function autoUrlNoList(name, dest) { var loc; loc = document.getElementById(name).checked; location.href = dest + (loc == true ? 1 : 0); return ; } It will be your work to find where it's called ;)
{ "pile_set_name": "StackExchange" }
Q: How to output only the whole passage [Google Cloud Vision API, document_text_detection] I try Google Cloud Vision API's document_text_detection. It works really well in Japanese, but I have a problem. The response contains both the whole passage and partial passages with line breaks. I only need the whole passage. This is the response. Google keep の画像 テキスト化 画像文字認識で手書き文字をどこ までテキスト化が出来るのかをテスト。 Google keep OCR機能がとれた け使えるかを確認 この手書き文書を認献してiPhone のGoogle keepでテキスト化して Macで編集をするのにどれだけ 出来るかも確認する。 Google keep の画像 テキスト化 画像文字認識で手書き文字をどこ までテキスト化が出来るのかをテスト 。 Google keep OCR機能がとれた け使えるかを確認 この手書き文書を認献してiPhone のGoogle keepでテキスト化して Macで編集をするのにどれだけ 出来るかも確認する 。 This is my python code. import io import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="credentials.json" """Detects text in the file.""" from google.cloud import vision client = vision.ImageAnnotatorClient() directory = 'resources/' files = os.listdir(directory) for i in files: with io.open(directory+i, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.document_text_detection(image=image) texts = response.text_annotations for text in texts: print('{}'.format(text.description)) I read API reference (https://cloud.google.com/vision/docs/reference/rest/v1/AnnotateImageResponse#TextAnnotation) and came up with the idea to use response.full_text_annotation instead of response.text_annotations. image = vision.types.Image(content=content) response = client.document_text_detection(image=image) texts = response.full_text_annotation print('{}'.format(text)) But I got a error message. File "/home/kazu/language/ocr.py", line 21, in <module> print('{}'.format(text)) NameError: name 'text' is not defined Could you give me any information or suggestion? Thank you in advance. Sincerely, Kazu A: Looks like a typo. You named your variable "texts", but tried to use variable "text".
{ "pile_set_name": "StackExchange" }
Q: Nested CSS Div and Span Styles Not Working I can't seem to understand why certain span properties (in particular, the width and text-align of "controller-row-number" and "controller-row-name"): #controller { width: 250px; float: left; font-size: 14px; line-height: 1.5; text-align: left; } .controller-row { background-color: blue; } .controller-row-number { background-color: yellow; width: 60px; text-align: right; padding: 0 15px 0 0; } .controller-row-name { background-color: orange; width: 150px; text-align: left; padding: 0 0 0 0; } Are being ignored in the following code: <div id="controller"> <div class="controller-row"> <span class="controller-row-number">1</span> <span class="controller-row-name">First Name</span> </div> <div class="controller-row"> <span class="controller-row-number">2</span> <span class="controller-row-name">Second Name</span> </div> </div> I have a JSFiddle located here: http://jsfiddle.net/WZFJD Can anyone point me to the correct edits to make, so that the styles are adhered? Thanks! A: display: inline-block; to the rescue ! Fiddle .controller-row-number { background-color: yellow; width: 60px; display: inline-block; text-align: right; padding: 0 15px 0 0; } .controller-row-name { background-color: orange; width: 150px; display: inline-block; text-align: left; padding: 0 0 0 0; } span elements are by default inline, so you have to make them block, or inline-block if you want your width rule to be applied, otherwise they just take up enough width to fit. The width and height of display: inline; elems cannot be set as you tried to do. Tho you can fake the height using line-height.
{ "pile_set_name": "StackExchange" }
Q: GitLab backup doesn't include wiki We have GitLab CE 9.1.2 installed on our server where a backup is scheduled to run every 8:00 PM Mon-Fri. So far things are fine but yesterday we started using the Wiki. I double checked the backup file and somehow it had the exact same size as the backup the previous day (nothing was done in the system other than creating Wiki pages). Because of that I suspected that the Wiki wasn't included in the backup process so I opened up a VM and tried to restore the backup file. After the successful operation I went over to the Wiki section of the project and it was empty. I was reading some resources and they say the repo shouldn't be empty for the Wiki to be included but our repo is full of codes, commits, branches, issues, etc. I followed the backup instructions for the Omnibus installation because that's what we have. 0 20 * * 1-5 /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1 As you could see I didn't include any SKIP environment variable so it shouldn't skip anything. Am I missing something? I followed the instructions properly. I need a full backup of the system. A: From the link @fedorqui provided it looks like this is an issue with the cache not being flushed out when you create a Wiki and so the backup process sees the Wiki as being empty therefore skipped. To fix this it looks like we manually have to flush the cache ourselves. sudo gitlab-rails console p = Project.find_by_full_path 'namespace_path/project_path' wiki = ProjectWiki.new p wiki.repository.empty? wiki.repository.expire_all_method_caches wiki.repository.empty? The first time you run wiki.repository.empty? it will return true which is why the backup process skips the Wiki. After running wiki.repository.expire_all_method_caches you should be good to go (I tried this and our Wiki is now being backed up). If you'd like to confirm that everything does look good, simply run the wiki.repository.empty? again and it should return false this time. As of June 5, 2017 it seems like the bug hasn't been fixed yet. Update (August 22, 2017) GitLab CE 9.5.0 has been released (changelog) which has the fix for this issue. If you don't want to manually have to expire the cache I recommend that you upgrade your GitLab installation to at least v9.5.0 and you should be fine.
{ "pile_set_name": "StackExchange" }
Q: Understanding the DNS lookup mechanism The specific query that led me to try and unpick this process was: Will a DNS lookup for a subdomain, such as assets.example.com, be faster if the parent domain, example.com, has already been resolved? By my (naive) understanding, the basic process for translating a domain name into an IP address is quite simple. The addresses of the thirteen root servers, who know how to resolve top-level domains like com and net, are hard coded in network hardware. In the case of a lookup for example.com, our local DNS server, probably our router, asks one of these root servers where to find a top-level nameserver for com. It then asks the resultant nameserver if it knows how to resolve example. If it does, we're done, if not, we're passed to another server. Each nameserver in this process may well be caching, so that for a time our local router will now know offhand where to look for com and example, and the com server will know where to look for example. Still, I don't really get it. I know there are other intermediate DNS servers, such as those provided by ISPs. At what point are they queried? If the com TLD nameserver does not know how to resolve example, how does it work out what other nameservers to check? Or would this simply mean that example.com cannot be resolved? When I register a domain and configure nameservers, am I in effect editing a group of NS records for my subdomain of a particular TLD in the database used by the nameservers for that TLD? Wikipedia explains that some DNS servers combine caching with a recursive query implementation which allows them to serve cache hits and reliably resolve cache misses. I don't understand how these servers come to be queried, or how (even broadly) the resolving algorithm works. Looking back at my initial question, I might take a stab at "no", assuming the A records are both on the same nameserver. Is this accurate? A: First, the misconceptions: The root hints (names and IP addresses of the 13 root servers) are hardly ever "hard coded in network hardware". Network hardware such as a router, may sometimes have a built in DNS resolver if it happens to also have a DHCP server, but if it does, it's usually just a forwarding resolver that passes the query along to an upstream nameserver (obtained from an ISP) if it doesn't know the answer. nameservers provided by ISPs don't usually act as "intermediate DNS servers". Either you use your own nameservers (e.g. corporate nameservers, or you installed BIND on your computer) or you use the ones provided by your ISP. In either case, whichever nameserver you choose will take care of the recursive resolution process from beginning to end. The exception is the aforementioned forwarding nameservers. If the com TLD nameserver does not know how to resolve example, it does not work out what other nameservers to check. It is itself the nameserver to check. It either knows about example, or example doesn't exist. The answer to your question is yes. If a nameserver has already resolved example.com (and that result is still valid in its cache), then it will be able to resolve assets.example.com more quickly. The recursive resolution process is much as you described it: First find out the nameservers for . (the root), then find out the nameservers for com, etc... Only the recursive resolver does not actually ask for the nameservers for . and com and example.com. It actually asks for assets.example.com each time. The root servers won't give it the answer to that question (they don't know anything about assets.example.com) but they can at least offer a referral to the nameservers for com. Similarily, the nameservers for com won't answer the question (they don't know either) but they can offer a referral to the nameservers for example.com. The nameservers for example.com may or may not know the answer to the question depending on whether assets.example.com is delegated further to other nameservers or provisioned in the same zone as example.com. Accordingly, the recursive resolver will receive either a final answer or another referral.
{ "pile_set_name": "StackExchange" }
Q: Simple IIS Redirection expression ("*") throws an error: The expression "*" contains a repeat expression I have the world's simplest regular expression: * I put it in a web site in IIS because I want one of the sites to be a proxy, and the others to serve locally. So, the web.config is: <system.webServer> <rewrite> <rules> <rule name="AllRewrite" stopProcessing="true"> <match url="*" /> <action type="Rewrite" url="http://tom-pc/{R:0}" /> </rule> </rules> </rewrite> </system.webServer> However, that throws this error: The expression "" contains a repeat expression (one of '', '?', '+', '{' in most contexts) that is not preceded by an expression. Any ideas? A: The error says it all. Your regular expression is invalid. The * is a repeat character (zero or more times). You should indicate which character is allowed to be repeated zero or more times. You probably want any character, so your regular expression should be: .* <match url=".*" /> To answer your other question about proxying, it's not possible to proxy by rewriting to another host name. You can only rewrite to other URI's on the same server. To proxy with IIS you have to install the ARR (Application Request Routing) module.
{ "pile_set_name": "StackExchange" }
Q: Expanding an Expandablelistview crashes the app Following is my getChildView method @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String childText = (String) getChild(groupPosition, childPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_item, null); } TextView txtListChild = (TextView) convertView .findViewById(R.id.lblListItem); txtListChild.setText(childText); return convertView; } Following is my getGroupView method @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.assignee_list_group, null); } TextView lblListHeader = (TextView) convertView .findViewById(R.id.lblListHeader); lblListHeader.setTypeface(null, Typeface.BOLD); lblListHeader.setText(headerTitle); if (isExpanded) { ImageView img_indicator = (ImageView) convertView .findViewById(R.id.indicator_list); img_indicator.setImageResource(R.drawable.circle_arrowdown); } else { ImageView img_indicator = (ImageView) convertView .findViewById(R.id.indicator_list); img_indicator.setImageResource(R.drawable.circle_arrow); } return convertView; } Im getting the following error, java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setBounds(android.graphics.Rect)' on a null object reference at android.widget.ExpandableListView.drawDivider(ExpandableListView.java:537) at android.widget.ListView.dispatchDraw(ListView.java:3313) at android.widget.ExpandableListView.dispatchDraw(ExpandableListView.java:356) at android.view.View.draw(View.java:15125) at android.widget.AbsListView.draw(AbsListView.java:4250) at android.view.View.updateDisplayListIfDirty(View.java:14056) at android.view.View.getDisplayList(View.java:14079) at android.view.View.draw(View.java:14846) at android.view.ViewGroup.drawChild(ViewGroup.java:3405) Im getting the above error while expanding the expandable listview. How can I be able to sort this out? Following is my childview 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="55dip" android:background="@color/light_color_2" android:orientation="vertical"> <TextView android:id="@+id/lblListItem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginLeft="15dp" android:layout_marginStart="15dp" android:paddingBottom="5dp" android:paddingTop="5dp" android:textAppearance="?android:attr/textAppearanceSmall"/> <ImageView android:layout_width="12dp" android:layout_height="12dp" android:layout_alignParentEnd="true" android:layout_centerVertical="true" android:src="@drawable/chevron"/> </RelativeLayout> Following is my groupview xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="8dp"> <TextView android:padding="8dp" android:id="@+id/lblListHeader" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:text="assa" android:textAppearance="?android:attr/textAppearanceSmall" android:textColor="@color/black" android:textStyle="normal"/> <ImageView android:id="@+id/indicator_list" android:layout_width="wrap_content" android:layout_height="10dp" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_gravity="center_vertical|center_horizontal" android:layout_margin="3dp" android:layout_weight="1" android:src="@drawable/circle_arrow"/> </RelativeLayout> Following is my expandablelistview xml code <ExpandableListView android:id="@+id/lvExp" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_below="@+id/app_bar" android:childDivider="@null" android:divider="@color/gray" android:dividerHeight="1dp" android:groupIndicator="@null"/> A: Problem is in childDivider, it shouldn't be null, change it to transparent <ExpandableListView android:id="@+id/lvExp" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_below="@+id/app_bar" android:childDivider="@android:color/transparent" android:divider="@color/gray" android:dividerHeight="1dp" android:groupIndicator="@null"/> Or just delete whole line, it's not required attribute
{ "pile_set_name": "StackExchange" }
Q: Would the Vulcan nerve pinch work on a Borg drone? If the Borg were to attack the planet Vulcan, could Vulcans incapacitate Borg drones using the Vulcan nerve pinch? A: A nerve pinch would (with reasonable certainty) work on a humanoid Borg. Tuvok is just about to "attempt" it in VOY: Unimatrix Zero, Part II when he's interrupted. Given that he's the ship's Security Officer and has extensive hands-on knowledge of Borg physiology, it seems very unlikely that he'd try it if he wasn't reasonably confident that it'll work. TUVOK: I will attempt to deactivate him. And we see Spock doing it (successfully) in the Star Trek comic Boldly Go #4 For the record, it doesn't work at all in the non-canon Star Trek Online game, showing effectiveness only on (some) entirely biological organisms.
{ "pile_set_name": "StackExchange" }
Q: android spinner for list and "All" option I have a android spinner that works like a filter for product listview. The spinner adapter has the list of Brand class objects. The listview then shows only the products with selected brand. Now I need to add to the top of the list another special option "All" that turns off the filter and shows all products. I have implemented the adapter with creation of the fake Brand class instance so that I can add this to the Brand ArrayList used by the adapter but this is not ideal - all other objects are valid database objects so I would like to ask for better approach how to achieve that. Thanks A: The way which I am doing this in all my apps is equal. Add All item as first item to your spinner adapter and in your onItemClick you can do something like this : mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { if(position == 0){ // show all products } else { // show the selected brand's products } } @Override public void onNothingSelected(AdapterView<?> parentView) { } }); The best option which I had during my development is this one. I didn't saw any other way to achieve this.
{ "pile_set_name": "StackExchange" }
Q: How to mark other components invalid in a custom multi-field validator I refer to one of BalusC's answers: JSF doesn't support cross-field validation, is there a workaround? I follow the same way, and come out with code as below: in .xhtml <h:form id="form1"> <div> <p:messages globalOnly="true" display="text" /> <h:inputHidden value="true"> <f:validator validatorId="fooValidator" /> <f:attribute name="input1" value="#{input1}" /> <f:attribute name="input2" value="#{input2}" /> <f:attribute name="input3" value="#{input3}" /> </h:inputHidden> <h:panelGrid columns="3"> <h:outputText value="name 1: " /> <p:inputText binding="#{input1}" id="input11" value="#{testPage.input1}" /> <p:message for="input11" display="text"/> </h:panelGrid> <h:panelGrid columns="3"> <h:outputText value="name 2: " /> <p:inputText binding="#{input2}" id="input22" value="#{testPage.input2}" /> <p:message for="input22" display="text"/> </h:panelGrid> <h:panelGrid columns="3"> <h:outputText value="name 3: " /> <p:inputText binding="#{input3}" id="input33" value="#{testPage.input3}" /> <p:message for="input33" display="text"/> </h:panelGrid> <p:commandButton value="Submit" action="#{testPage.submitValidator}" update=":updateBody" /> </div> </h:form> java class: @FacesValidator(value="fooValidator") public class CustomValidator2 implements Validator { @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { UIInput input1 = (UIInput) component.getAttributes().get("input1"); UIInput input2 = (UIInput) component.getAttributes().get("input2"); UIInput input3 = (UIInput) component.getAttributes().get("input3"); Object value1 = input1.getSubmittedValue(); Object value2 = input2.getSubmittedValue(); Object value3 = input3.getSubmittedValue(); if (value1.toString().isEmpty() && value2.toString().isEmpty() && value3.toString().isEmpty()) { String errorMsg = "fill in at least 1"; FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsg, errorMsg); FacesContext.getCurrentInstance().addMessage("form1:input11", msg); //throw new ValidatorException(msg); } } } the code is working fine, but i face a problem. How to highlight border of name1 inputText(or both name1 and name2 inputText) with red color as usually done by JSF when validation fails. image as reference: http://img443.imageshack.us/img443/8106/errork.jpg thanks in advance A: Mark them invalid by UIInput#setValid(), passing false. input1.setValid(false); input2.setValid(false); input3.setValid(false); The borders are specific to PrimeFaces <p:inputText>, so you don't need to add any CSS boilerplate as suggested by the other answerer. Note that this can also be achieved by OmniFaces <o:validateAll> tag without the need to homegrow a custom validator.
{ "pile_set_name": "StackExchange" }
Q: enctype="multipart/form-data" does not submit data with Seam multipart-filter Ever since I add the following config to the components.xml to customize an editor plugin, every form with enctype="multipart/form-data" in my app does not submit data. I can't find any source saying that this is conflicting. <web:multipart-filter create-temp-files="true" max-request-size="1000000" url-pattern="*" /> I'm working with Seam 2.2.2 and Jsf 1.2 Update: I thought I could stop using forms with enctype="multipart/form-data". But I can't. I need some help and there goes more info. First: the problem above only aplies to a4j forms and a4j commandButtons. As I said before, I add the above web:multipart-filter config at components.xml to make this editor plugin works (which is done via apache commons ServletFileUpload). I was taking the enctype config off the project forms to make everything work but there is one scenario that it was not possible. When I have to upload an image. But when I use url-pattern="*.seam": <web:multipart-filter create-temp-files="true" max-request-size="1000000" url-pattern="*.seam" /> Then the upload works, but the ServletFileUpload doesn't. If I don't use any web:multipart-filter this also occurs. (image upload ok, and plugin fails) Now it is like this: <h:form id="editPhoto" enctype="multipart/form-data"> <div id="photoAttribute" class="attribute-relationship spacer-top-bottom"> <div class="label"> <h:outputText>#{messages['person.photo.alter']} </h:outputText> </div> <s:fileUpload id="photoPerson" data="#{person.profilePhoto}" fileName="#{person.profilePhotoName}" fileSize="#{person.profilePhotoSize}" accept="images/*"> </s:fileUpload> </div> <h:commandButton id="editPersonButtonTop" value="#{messages['button.savePhoto']}" action="#{personController.prepareSavePhoto(person)}" styleClass="button btn-info" onclick="showAjaxStatus()"/> </h:form> It seems I am missing some ajax config here but I can't tell what it is. And also Why can't I have both the ServletFileUpload and the image upload together? The ServletFileUpload is from commons-fileupload-1.3.1, and it works like this: List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); processItems(items); saveOpenAttachment(); ... private void processItems(List<FileItem> items) { // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { processUploadedFile(item); } } } private void processUploadedFile(FileItem item) { setFileName(FilenameUtils.getName(item.getName())); try { InputStream fileContent = item.getInputStream(); byte[] bytes = IOUtils.toByteArray(fileContent); setFileData(bytes); } catch (IOException e) { e.printStackTrace(); } setFileContentType(item.getContentType()); } I appreciate if somebody can tell how I manage to make ServletFileUpload works with the previous components config or How to have the form to submit the data. My components.xml: <core:init debug="true" jndi-pattern="@jndiPattern@"/> <web:rewrite-filter view-mapping="*.seam"/> <web:multipart-filter create-temp-files="true" max-request-size="1024000" url-pattern="*.seam"/> <core:manager concurrent-request-timeout="10000" conversation-timeout="3720000" conversation-id-parameter="cid" parent-conversation-id-parameter="pid" default-flush-mode="MANUAL"/> <persistence:managed-persistence-context name="entityManager" auto-create="true" persistence-unit-jndi-name="java:/SinapseEntityManagerFactory"/> <security:identity authenticate-method="#{authenticatorContext.authenticate}" remember-me="true" /> <international:time-zone-selector time-zone-id="GMT-3"/> <international:locale-selector name="defaultLocale" locale-string="pt" scope="application" /> <international:locale-selector locale-string="pt" /> <event type="org.jboss.seam.security.notLoggedIn"> <action execute="#{redirect.captureCurrentView}"/> </event> <event type="org.jboss.seam.security.postAuthenticate"> <action execute="#{redirect.returnToCapturedView}"/> </event> <async:quartz-dispatcher/> <cache:jboss-cache-provider configuration="ehcache.xml" /> <transaction:ejb-transaction/> A: To solve my problem, I changed the apache-commons FileUpload solution to handle the request like Seam multipart filter does: ServletRequest request = (ServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); try { if (!(request instanceof MultipartRequest)) { request = unwrapMultipartRequest(request); } if (request instanceof MultipartRequest) { MultipartRequest multipartRequest = (MultipartRequest) request; String clientId = "upload"; setFileData(multipartRequest.getFileBytes(clientId)); setFileContentType(multipartRequest.getFileContentType(clientId)); setFileName(multipartRequest.getFileName(clientId)); saveOpenAttachment(); } } This way, I could take off the web:multipart-filter config that was breaking the other requests.
{ "pile_set_name": "StackExchange" }
Q: How Java class are loaded from the same directory? How a java application launched with the classpath: "lib/*" will choose witch class to load if the lib directory contains several JAR with the same class? The comportment will be the same every time? With different servers? A: From the documentation: The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required, then the JAR files can be enumerated explicitly in the class path.
{ "pile_set_name": "StackExchange" }
Q: How to get C-like performance when filling up a mutable buffer in GHC Haskell I need to prefill up a mutable IOVector (with a given value). The Haskell code I am using is -- use Control.Monad, Data.Vector.Unboxed.Mutable, Data.Word, and run in IO monad buff <- new buffsize::IO (IOVector Word8) forM_ [0..buffsize-1] $ \p -> write buff p (100::Word8) This runs 1-2 orders of magnitude slower than the comparable c code char *buff = (char *) malloc(BUFFERSIZE); char *maxbuff = buff + BUFFERSIZE; for(char *p = buff; p < maxbuff; p++) *p = 0; For instance, for buffsize=4000000000, it takes about 7 seconds in c, but about 3 minutes in Haskell. (FYI, I am using Ubuntu running on an Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz, GHC version 7.8.4, but these specifics probably shouldn't matter) Does anyone see any changes I could make to the Haskell code to get comparable speeds? A: Three main things: write is bounds-checked, while a direct pointer write in C isn't. Change that to unsafeWrite if you want to keep C's lack of safety. forM_ [0..buffsize-1] has overhead due to being optimized for generality. If you want to remove all the generality, like the C loop, write the loop as something directly recursive. Use the llvm backend for code that needs to optimize tight loops. I coded up a criterion benchmark to test a whole bunch of variants: import Control.Monad import Data.Vector.Unboxed.Mutable import Data.Word import Criterion.Main buffsize :: Int buffsize = 1000000 fillBuff1 :: IOVector Word8 -> IO () fillBuff1 buff = do forM_ [0..buffsize-1] $ \p -> write buff p 100 fillBuff2 :: IOVector Word8 -> IO () fillBuff2 buff = do forM_ [0..buffsize-1] $ \p -> unsafeWrite buff p 100 fillBuff3 :: IOVector Word8 -> IO () fillBuff3 buff = do let fill n | n < buffsize = unsafeWrite buff n 100 >> fill (n + 1) | otherwise = return () fill 0 fillBuff4 :: IOVector Word8 -> IO () fillBuff4 buff = do let fill n | n < buffsize = write buff n 100 >> fill (n + 1) | otherwise = return () fill 0 main = do buff <- new buffsize let b n f = bench n . whnfIO . f $ buff defaultMain [ b "original" fillBuff1 , b "unsafeWrite" fillBuff2 , b "unsafeWrite + recursive" fillBuff3 , b "recursive" fillBuff4 ] Note that I'm only benchmarking filling, not allocation + filling. Here's a typical session without llvm: carl@debian:~/hask$ ghc --version The Glorious Glasgow Haskell Compilation System, version 7.8.4 carl@debian:~/hask$ ghc -O2 mutvectorwrite [1 of 1] Compiling Main ( mutvectorwrite.hs, mutvectorwrite.o ) Linking mutvectorwrite ... carl@debian:~/hask$ ./mutvectorwrite benchmarking original time 6.659 ms (6.599 ms .. 6.728 ms) 0.999 R² (0.998 R² .. 1.000 R²) mean 6.638 ms (6.599 ms .. 6.683 ms) std dev 120.7 μs (97.36 μs .. 165.9 μs) benchmarking unsafeWrite time 5.413 ms (5.319 ms .. 5.524 ms) 0.998 R² (0.995 R² .. 0.999 R²) mean 5.346 ms (5.309 ms .. 5.394 ms) std dev 127.4 μs (85.00 μs .. 220.2 μs) benchmarking unsafeWrite + recursive time 3.363 ms (3.323 ms .. 3.409 ms) 0.999 R² (0.998 R² .. 0.999 R²) mean 3.371 ms (3.343 ms .. 3.411 ms) std dev 104.6 μs (65.11 μs .. 187.1 μs) variance introduced by outliers: 16% (moderately inflated) benchmarking recursive time 3.389 ms (3.330 ms .. 3.438 ms) 0.998 R² (0.996 R² .. 1.000 R²) mean 3.435 ms (3.424 ms .. 3.451 ms) std dev 43.38 μs (34.49 μs .. 67.38 μs) And a typical session with llvm: carl@debian:~/hask$ ghc -O2 -fllvm mutvectorwrite [1 of 1] Compiling Main ( mutvectorwrite.hs, mutvectorwrite.o ) Linking mutvectorwrite ... carl@debian:~/hask$ ./mutvectorwrite benchmarking original time 5.302 ms (5.251 ms .. 5.365 ms) 0.999 R² (0.999 R² .. 1.000 R²) mean 5.286 ms (5.262 ms .. 5.322 ms) std dev 87.47 μs (63.29 μs .. 115.0 μs) benchmarking unsafeWrite time 3.929 ms (3.867 ms .. 4.001 ms) 0.998 R² (0.996 R² .. 0.999 R²) mean 4.039 ms (3.994 ms .. 4.131 ms) std dev 204.2 μs (114.6 μs .. 378.5 μs) variance introduced by outliers: 30% (moderately inflated) benchmarking unsafeWrite + recursive time 496.4 μs (492.8 μs .. 500.8 μs) 0.999 R² (0.998 R² .. 1.000 R²) mean 496.6 μs (492.8 μs .. 503.9 μs) std dev 17.46 μs (9.971 μs .. 31.42 μs) variance introduced by outliers: 27% (moderately inflated) benchmarking recursive time 556.6 μs (548.4 μs .. 563.8 μs) 0.998 R² (0.996 R² .. 0.999 R²) mean 565.4 μs (559.7 μs .. 574.3 μs) std dev 23.95 μs (16.41 μs .. 33.78 μs) variance introduced by outliers: 35% (moderately inflated) Performance gets down to pretty reasonable when you combine everything.
{ "pile_set_name": "StackExchange" }
Q: Random Spikes while logging raw data from IMU using SPI on Arduino I would need to make the noise characterization of the LSM9DS1 IMU. For this purpose I would need to acquire raw data from the sensors for a long time (around 10 hours) while in static conditions. I prepared a logging system composed by an Arduino Uno and the IMU connected to it using SPI protocol. The system works good enough, however, I get random spikes on the accelerometer and gyroscope even if the IMU is in static condition. These spikes seem to be always around +/- 250 from the mean value. The following figure shows these spikes on the X axis of the accelerometer. The IMU is set to provide data at 50 Hz and I also read data at the same frequency. Following is my Arduino code based on the LSM9DS1 library provided by Sparkfun: #include <Wire.h> #include <SPI.h> #include <SparkFunLSM9DS1.h> LSM9DS1 imu; #define LSM9DS1_M_CS 10 // Can be any digital pin #define LSM9DS1_AG_CS 9 // Can be any other digital pin void setup() { Serial.begin(115200); imu.settings.device.commInterface = IMU_MODE_SPI; imu.settings.device.mAddress = LSM9DS1_M_CS; imu.settings.device.agAddress = LSM9DS1_AG_CS; if (!imu.begin()) { Serial.println("Failed to communicate with LSM9DS1."); while (1); } imu.enableFIFO(false); imu.setFIFO(FIFO_OFF,0x00); } void loop() { Serial.print(micros()); Serial.print(" "); printAccel(); printGyro(); delay(20); } void printGyro() { imu.readGyro(); Serial.print(imu.gx); Serial.print(" "); Serial.print(imu.gy); Serial.print(" "); Serial.println(imu.gz); } void printAccel() { imu.readAccel(); Serial.print(imu.ax); Serial.print(" "); Serial.print(imu.ay); Serial.print(" "); Serial.print(imu.az); Serial.print(" "); } A: The "spikes" seem to be very low energy, maybe one spurious reading every now and again. You could certainly try to figure out exactly what is causing them (it could be something like some one slamming a door for all you know), but I think that is more of a hardware debug issue. I think ultimately you will want to filter out all that noise anyway. How complicated a digital filter you will need is dependent on how fast your "measurements" compared to the random noise in the measurements. One of simplest filters is the following, where filterValue is the "running" value, senseValue is the current raw measurement, and scaleFactor is a number < 1 (0.1, or 0.01 for eample). The smaller the number the more it will filter, but also the more "lag" you will see. filterValue = filterValue + scaleFactor * (senseValue - filterValue); I think once you filter the data reasonably, those "spikes" will vanish. Since you have data stored you can just run it thru the filter and see how it looks.
{ "pile_set_name": "StackExchange" }
Q: Pass struct array to function with malloc I'am writing a program where I need to add students to a array of structs. Well, at the beginning I have the following struct array: struct student *students[4]; After the declaration I add students like this to the array (just to have examples ...): students[0] = malloc(sizeof(struct student)); students[0]->firstname = "Max"; students[0]->secondname = "Taler"; students[0]->number = 123456l; ... Now I have to write a additional function, where I can pass the array as a parameter and add a new student. So my function looks like this: void add_student(struct student *students[],char *fristname, char *secondname, long number) { int i=0; int new_position=0; int return_value = 0; // Search for the first available position for a new student for(i=0; i<sizeof(students); i++) { if(students[i]==NULL) { new_position=i; return_value = 1; break; } } struct student *new_student = malloc(sizeof(struct student)); students[new_position] = new_student; students[new_position]->fristname = fristname; students[new_position]->secondname = secondname; students[new_position]->number = number; return return_value; } I call the function with this code: add_student(students, "Anni", "Karls", 123232); But now my issue: In my "add_student" function I get an array that has a strange structur: it includes itself as the first element and every other element is shifted by 1 element. Cant figure out what the problem is ... Can somebody please help? EDIT: Somebody asked me, how this can be. How the array can include "itself" as the first element. Well, here are screenshots of the debugger (xCode): Before entering "add_student": After entering "add_student" -> IN the function "add_student": As you see, "students" has now 5 elements ... A: Pass the length of the array to the function and change this for(i=0; i<sizeof(students); i++) to this for(i=0; i<arrayLen; i++) It seems you are inserting an element to some position in an array which has been allocated before hand; inserting is maybe more proper term than adding, but that is opinion. You were applying sizeof operator on array type inside function - this will likely give you size of pointer in bytes because array name decays to pointer.
{ "pile_set_name": "StackExchange" }
Q: Multiple filters via MongoDB C# driver How runtime generate filters with official drivers? I want get contacts that contains specific user id and can be filtered for some properties (contains some text) Current code dont work with request.Filter > 1: private FilterDefinition<Contact> BuildFilter(NgTableRequest request, string userId) { var filters = new List<FilterDefinition<Contact>> { Builders<Contact>.Filter.Where(q => q.ContactUsers.Any(w => w.UserId == userId)) }; if (request.Filter != null && request.Filter.Any()) { foreach (var reqFilter in request.Filter) { filters.Add(Builders<Contact>.Filter.Regex(reqFilter.Key, reqFilter.Value[0])); } } var result = Builders<Contact>.Filter.And(filters); return result; } A: Check generated filter using following code and found error in another place var documentSerializer = BsonSerializer.SerializerRegistry.GetSerializer<Contact>(); var renderedFilter = result.Render(documentSerializer, BsonSerializer.SerializerRegistry).ToString(); Trace.WriteLine("Filter: " + renderedFilter);
{ "pile_set_name": "StackExchange" }
Q: What will happen after the maximum number of images pushed to ECR repository According to Amazon ECR Service Limits, the maximum number of images per repository is 1,000. After exceeding this limit, the oldest image won't remove automatically. It blocks pushing to the repository. So I have to clean old images manually. Update: AWS introduced ECR Lifecycle Policies. We can now automate the cleanup with this. A: Having experienced this exact scenario, I can confirm that upon reaching the limit, AWS will block you from pushing with this very unhelpful error message: Error pushing to registry: Server error: 403 trying to push <repo>:<label> manifest You'll need to manage the number of repositories yourself. As there is currently no built in garbage collection (nor 'remove oldest') functionality, you have a few options: Remove the images via the console (which really is just woeful with so many images) Write your own tool that interfaces with the AWS CLI/SDK using the ecr batch-delete-image commands Request a limit to the maximum number you can store per repository. We've recently done this and was very easy to get the 1,000 limit increased to 5,000.
{ "pile_set_name": "StackExchange" }
Q: Use variable in R substitute I have an expression stored in a variable a <- expression(10 + x + y) I want to use substitute to fill the expression with x = 2 substitute(a, list(x=2)) But this returns a and a evaluates to expression(10 + x + y) Ideally a would evaluate to expression(12 + y) (or (10 + 2 + y)) Is there any way to implement this behavior while using an expression stored in the variable a (mandated by other parts of my project)? A: Use do.call. substitute won't descend into some objects but if you use a[[1]] here then it will work. a <- expression(10 + x + y) do.call("substitute", list(a[[1]], list(x = 2))) ## 10 + 2 + y
{ "pile_set_name": "StackExchange" }
Q: When might a compiler generate JG/JS/JP conditional jumps? I was wondering where i might encounter JO/JS/JP JCCs (and their not-counterparts) in compiler generated code? What would it mean? I scrolled through a lot of random code, but wasnt able to find a single instance in straight forward way. thanks. A: Most compiled code, these days, is C, C++, or possibly Delphi. These languages lack high-level support for some of your instructions, so there is no reason for them to generate them. If C had an operation to determine the parity of a number, the compiler would probably generate a JP instruction for it. But C doesn't have this operation, and since the only reason for it (that i can think of) is serial communications, and serial chips have done parity checking in hardware since at least the 80s, there wasn't ever reason to introduce an extension for it. (There are actually bit operations that are useful in certain scenarios, have processor operations to do them, and are supported by compilers. See http://en.wikipedia.org/wiki/Find_first_set.) Likewise, C doesn't have overflow checking. If a given compiler had a --warn-on-overflow flag, it might be implemented using JC, however. Your other two instructions are just variations of the "compare two numbers" topic. JG is a "reversed" JLE, JS is a version of JL after comparing to 0. For the compiler, it's more efficient to "normalize" comparisons first, then run the optimizer over the normalized comparison, then emit machine code, than maintaining different, but similar, optimizations. "Greater than" is the same as "Not less or equal"; "Less than" is the same as "not greater or equal". I've seen gcc produce the latter (JLE and JGE) but not the former (JL and JG). And since JS is just a special case of these, there's not much reason for a compiler to use it.
{ "pile_set_name": "StackExchange" }
Q: Can anyone help me understand my loan payment? My loan was $40500 for five years with 9% interest per year. I do not understand the total I would have to pay. I have been paying 700 per month since 2006 and it feels like I've been paying forever. I really don't understand...my balance now is $13,092.50. Please help me understand this, in layman's term. A: If your loan payment schedule was set up correctly, you should have been paying $840.71 per month for 5 years and would have been finished with the loan by 2011. By paying only $700 each month, you have effectively extended the loan to a longer term than 5 years, about 6 years and 4 month. Who told you that the monthly payment was $700? the lender? or is that amount what you could afford to pay and you decided to cut back on the required payments? Did you miss any payments? paid late and were charged late payment fees that got added to the loan? Because if you have been paying $700 on time each month beginning some time in 2006, your loan should have been paid off more than 2 years ago. So, something is awry here, and perhaps you have not revealed the whole story. Several websites have free calculators that can tell you how long it would take to pay off $40,500 at 9% for a fixed monthly payment. See, for example, this one which I used to calculate the numbers mentioned here
{ "pile_set_name": "StackExchange" }
Q: Waiting for a method to finish using C#? I have method which writes a file to the local disk. Another method takes that file and uploads it to a sftp server. The problem is, that the file on the sftp server is empty. This is a small piece of my code: WriteToLocalFolder(content, filename); WriteToSftpServer(filename, server logon params); Could it be that WriteToSftpServer gets called before WriteToLocalFolder finished writing? If yes, how can I say that WriteToSftpServer should start only after WriteToLocalFolder has finished writing the file? WriteToLocalFolder looks like this in the real code: public static void WriteToFolder(StringBuilder content, string whereTo) { File.WriteAllText(whereTo, content.ToString()); } So the stream is closed I think... Thanks :-) A: The code in WriteToSftpServer shouldn't ever happen before WriteToLocalFolder is done (because it does not seem to be async). However it could be that filestream is not properly closed and so WriteToSftpServer can't access it. Try getting a breakpoint inside WriteToSftpServer where the file gets loaded to see what does it load. You can always "step next" inside the method, if the file loads correctly, to see where does it break.
{ "pile_set_name": "StackExchange" }
Q: socket.io compatibility issue with IE7 It seems that many people get socket.io working with IE7, but not me... I have done some experiments with socket.io v0.9.16: with jsonp-polling: client running on IE7 can connect the server, receive first message but not send/emit with xhr-polling: IE7 can connect the server, but cannot receive or send/emit messages. with htmlfile: even worse, no connection can be established. I have Apache web server listening on port 80 and socket.io listening on port 8080. Could anyone tell me how to get IE7, IE8 talk to socket.io server correctly? Tons of thanks in ahead. A: it turns out that there is a console.log() call in my js code, which is not supported in IE7. IE7 (its js thread) silently dies, no warning no prompt. With console.log() removed, everything works fine. so, watch out for such issues that can waste a lot of time
{ "pile_set_name": "StackExchange" }
Q: How to determine traffic flow from server How can I determine the path traffic takes from a server with 2 Ethernet ports, each port connecting to a separate switch. The switches are not cable of layer3 so I cannot use HSPR where I could make the one switch the default gateway. Is there a layer two solution I can Implement? A: Each server decides based on it's own routing table which interface to use when connecting out. Unless you use some special features like bonding, you should get useful output by entering sudo ip route show. For example in my case the output looks like this: root@mr-burns:~ ssh# ip route show default via 10.60.0.1 dev em1 10.20.0.0/16 via 10.60.0.165 dev em2 10.60.0.0/16 dev em1 proto kernel scope link src 10.60.1.150 10.60.0.0/16 dev em2 proto kernel scope link src 10.60.1.151 127.0.0.0/8 dev lo scope link I read this like following: Let's say the destination is inside the network 10.20.0.0/16, it will use the interface em2 because of the second rule. But if the destination is using the default gw because its not in any of the listed destination networks, it uses em1.
{ "pile_set_name": "StackExchange" }
Q: Trying to understand the statement of Nakayama's lemma for coherent modules in Mumford' red book Here is the statement of a version of Nakayama's lemma in Mumford's red book. Let $X$ be a noetherian scheme, $F$ a coherent $O_X$-module and $x \in X$. If $U$ is a neighbourhood of $x$ and $a_1, \ldots a_n \in \Gamma(U,F)$ have the property: the images $\overline{a_1}, ..., \overline{a_1}$ generate $F_x \otimes_{O_{X,x}} k(x)$ then there exists a neighbourhood $U_0 \subset U$ of $x$ such that $a_1, ..., a_n $ generate $F |_{U_0}$. There are two things I don't understand in this statement, which I haven't been able to deduce looking at the proof. -"$\overline{a_1}, ..., \overline{a_1}$ generate $F_x \otimes_{O_{X,x}} k(x)$" over $O_{X,x}$ or $k(x)$? -what does it mean by $a_1, ..., a_n $ generate $F |_{U_0}$? thank you. A: The map $O_{X,x} \to k(x)$ is surjective, so generated over $O_{X,x}$ or $k(x)$ is the same thing. For the second question, it means that the images of $a_1, ..., a_n $ in $F_y$ are generators for this $O_{X,y}$-module for each $y\in U_0$.
{ "pile_set_name": "StackExchange" }
Q: multinom() in R: can I use for prediction on other dataset? I have run a multinom() model, then how can I use these model on other dataset? For example I want to fit this model to another dataset and generate predicted probabilities for that dataset, like mnrval() did in Matlab--- it takes the model estimated by mnrfit() and apply it to outside data to generate predicted probability. I'm currently constrained with R so can't use Matlab. Thanks. A: See example in ?multinom: mymultinommodel <- multinom(low ~ ., bwt) predict(mymultinommodel,new.data=newdata) To get probabilities instead of predicted class: predict(mymultinommodel,new.data=newdata, type="probs")
{ "pile_set_name": "StackExchange" }
Q: ruby-on-rails params missing or value is empty (when using with angularJS form) I am a newbie at ruby on rails and I am currently developing a part of portal. I have encountered some errors which I could not find an solution. First error: ActionController::ParameterMissing (param is missing or the value is empty: user): app/controllers/admin/manage_users_controller.rb:97:in `user_params' app/controllers/admin/manage_users_controller.rb:32:in `update' Second error: ArgumentError (When assigning attributes, you must pass a hash as an argument.): app/controllers/admin/manage_users_controller.rb:32:in `update' My manage_users_controller: def edit if request.format.json? t = @user @user = {:id => t.id, :email => t.email} end respond_to do |format| format.json { render :json => @user, :status => 200} format.html end end def update @user.attributes = user_params if @user.save respond_to do |format| format.json {render :json => {:redirect_to => admin_manage_users_path}, :status => 200 } end else respond_to do |format| format.json { render :json => {:errMsg => print_out_message('form-update','user'), :errors => @user.errors}, :status => 400 } end end end def user_params return params.require(:user).permit(:user_id, :email) end for the first error, I am not sure why the param is missing. for the second error, I have read on other posts that I need to use the require and permit method in my user_params. however, I still cannot figure out what exactly is the problem. Any help would be deeply appreciated. Thank you. --------------------------UPDATE----------------------------- edit.html.erb in the view <div class="row" ng-controller="AdminManageUsersCtrl"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="rs-content" data-ng-init="loadUser()"> <div class="portlet listing" cg-busy="loadUser" ng-cloak> <div class="portlet-body"> <form name="form" ng-submit="uploadUser()" confirm-on-exit> <%= render "admin/manage_users/form" %> <div class="row row-space-top-1"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <button type="submit" class="btn red-mint" ng-click="form.$setPristine()">Update</button> <%= link_to "Cancel".html_safe, admin_manage_users_path, :class => "btn dark btn-outline" %> <%= link_to 'Remove', URI::unescape(admin_manage_user_path(:users => '{{user.id}}')), :method => :delete, :class => "pull-right btn red btn-outline", :data => {:confirm => 'Are you sure you want to delete this user?', "ng-click"=>"form.$setPristine()"} %> </div> </div> </form> </div> </div> </div> </div> </div> And the _form.html.erb <div class="col-md-12 space-1" ng-class="{ 'has-error' : form['email'].$invalid }"> <label class="control-label">Email</label> <div> <div class="input-icon right"> <i ng-show="form['email'].$invalid" class="fa fa-warning tooltips" data-original-title="{{errors['email']}}" data-container="body"></i> <input ng-model= "user.email" name="email" type="text" class="form-control"> </div> </div> </div> in the app.js $scope.uploadUser = function() { $scope.errors = []; AdminManageUsers.$patch('update', $scope.user).then(function(response) { $window.location.href = response.redirectTo; }, function(response) { angular.forEach(response.data.errors, function(errors, key) { $scope['form'][key].$invalid = true; $scope.errors[key] = errors.join(', '); }); alertMessage.danger(response.data.errMsg, 1, 10000); }); } And this is the routing in route.rb resources :manage_users, :only => [:index,:destroy], :param => :id match "manage_users/data" => "manage_users#data", via: [:post], :defaults => { :format => 'json' } match "manage_users/load" => "manage_users#load", via: [:get], :defaults => { :format => 'json' } match "manage_users/:id/edit" => "manage_users#edit", via: [:get] match "manage_users/:id/update" => "manage_users#update", via: [:patch] Sorry I am posting a lot of code, but I think they are all related. To be honest, I am actually trying to follow the style of coding my mentor adopted, so he used angularJS to design the form, so I still have some trouble understanding how everything links together. A: The error itself is caused by your strong_params method: params.require(:user).permit(:user_id, :email) Specifically, the require argument means that the controller is expecting a params hash which has "user" as the main element: params: { "user" => { "user_id" => "1", "email" => "[email protected]" } } As you don't have the above set up, the error comes back that you don't have the user in the params hash. Solution Make sure you're passing the right object through your params. You should have the following set up: #app/views/admin/manage_users/edit.html.erb <%= form_for @user do |f| %> <%= f.text_field :email %> <%= f.submit %> <% end %> Along with this, the entire way you're doing this is flawed; you'd be better using the following: #app/controllers/admin/manage_users_controller.rb class Admin::ManageUsersController < ApplicationController respond_to :js, :json, :html before_action :set_user def edit respond_with @user end def update respond_to do |format| if @user.update user_params format.json {render :json => {:redirect_to => admin_manage_users_path}, :status => 200 } else format.json { render :json => {:errMsg => print_out_message('form-update','user'), :errors => @user.errors}, :status => 400 } end end end private def set_user @user = User.find params[:id] end def user_params params.require(:user).permit(:user_id, :email) #-> Ruby automatically returns the last line of a method end end
{ "pile_set_name": "StackExchange" }
Q: Pandas: Filter by date range / exact id I'm looking to filter a large dataframe (millions of rows) based on another much smaller dataframe that has only three columns: ID, Start, End. The following is what I put together (which works), but it seems like a groupby() or np.where might be faster. SETUP: import pandas as pd import io csv = io.StringIO(u''' time id num 2018-01-01 00:00:00 A 1 2018-01-01 01:00:00 A 2 2018-01-01 02:00:00 A 3 2018-01-01 03:00:00 A 4 2018-01-01 04:00:00 A 5 2018-01-01 05:00:00 A 6 2018-01-01 06:00:00 A 6 2018-01-03 07:00:00 B 10 2018-01-03 08:00:00 B 11 2018-01-03 09:00:00 B 12 2018-01-03 10:00:00 B 13 2018-01-03 11:00:00 B 14 2018-01-03 12:00:00 B 15 2018-01-03 13:00:00 B 16 2018-05-29 23:00:00 C 111 2018-05-30 00:00:00 C 122 2018-05-30 01:00:00 C 133 2018-05-30 02:00:00 C 144 2018-05-30 03:00:00 C 155 ''') df = pd.read_csv(csv, sep = '\t') df['time'] = pd.to_datetime(df['time']) csv_filter = io.StringIO(u''' id start end A 2018-01-01 01:00:00 2018-01-01 02:00:00 B 2018-01-03 09:00:00 2018-01-03 12:00:00 C 2018-05-30 00:00:00 2018-05-30 08:00:00 ''') df_filter = pd.read_csv(csv_filter, sep = '\t') df_filter['start'] = pd.to_datetime(df_filter['start']) df_filter['end'] = pd.to_datetime(df_filter['end']) WORKING CODE df = pd.merge_asof(df, df_filter, left_on = 'time', right_on = 'start', by = 'id').dropna(subset = ['start']).drop(['start','end'], axis = 1) df = pd.merge_asof(df, df_filter, left_on = 'time', right_on = 'end', by = 'id', direction = 'forward').dropna(subset = ['end']).drop(['start','end'], axis = 1) OUTPUT time id num 0 2018-01-01 01:00:00 A 2 1 2018-01-01 02:00:00 A 3 6 2018-01-03 09:00:00 B 12 7 2018-01-03 10:00:00 B 13 8 2018-01-03 11:00:00 B 14 9 2018-01-03 12:00:00 B 15 11 2018-05-30 00:00:00 C 122 12 2018-05-30 01:00:00 C 133 13 2018-05-30 02:00:00 C 144 14 2018-05-30 03:00:00 C 155 Any thoughts on a more elegant / faster solution? A: Why not merge before filter. notice this will eating up your memory when the data set are way to big . newdf=df.merge(df_filter) newdf=newdf.loc[newdf.time.between(newdf.start,newdf.end),df.columns.tolist()] newdf Out[480]: time id num 1 2018-01-01 01:00:00 A 2 2 2018-01-01 02:00:00 A 3 9 2018-01-03 09:00:00 B 12 10 2018-01-03 10:00:00 B 13 11 2018-01-03 11:00:00 B 14 12 2018-01-03 12:00:00 B 15 15 2018-05-30 00:00:00 C 122 16 2018-05-30 01:00:00 C 133 17 2018-05-30 02:00:00 C 144 18 2018-05-30 03:00:00 C 155
{ "pile_set_name": "StackExchange" }
Q: JDialog size not suitable, why isn't the PreferredSize used in BoxLayout? I have a JDialog with only a few simple components, one JTextArea, one JtextField and one JRadioButton. I just want it displayed with a suitable size. The PreferredSize of the components seems reasonable but everything gets truncated. I'm using BoxLayout with Y_AXIS. I don't want to have to set explicit sizes, I just want a suitable size for the components that are there. In particular, why is the PreferredSize for the textarea ignored? The minimal code that I have created follows:- It creates the following output:- 0|Name: dialog0, Class: javax.swing.JDialog, [175, 132], H: 103, W: 132, AlignmentX: 0, AlignmentY: 0 1|-Name: null, Class: javax.swing.JRootPane, [137, 116], H: 65, W: 116, AlignmentX: 0, AlignmentY: 0 2|--Name: null.glassPane, Class: javax.swing.JPanel, [10, 10], H: 65, W: 116, AlignmentX: 0, AlignmentY: 0 2|--Name: null.layeredPane, Class: javax.swing.JLayeredPane, [1, 1], H: 65, W: 116, AlignmentX: 0, AlignmentY: 0 3|---Name: null.contentPane, Class: javax.swing.JPanel, [137, 116], H: 65, W: 116, AlignmentX: 0, AlignmentY: 0 4|----Name: null, Class: javax.swing.JPanel, [137, 116], H: 65, W: 116, AlignmentX: 0, AlignmentY: 0 5|-----Name: null, Class: javax.swing.JTextArea, [94, 116], H: 22, W: 116, AlignmentX: 0, AlignmentY: 0 5|-----Name: null, Class: javax.swing.JRadioButton, [23, 57], H: 23, W: 57, AlignmentX: 0, AlignmentY: 0 5|-----Name: null, Class: javax.swing.JTextField, [20, 6], H: 20, W: 116, AlignmentX: 0, AlignmentY: 0 The code follows:- package testing.example; import java.awt.Component; import java.awt.Container; import javax.swing.BoxLayout; import static javax.swing.BoxLayout.Y_AXIS; import javax.swing.ButtonGroup; import javax.swing.CellRendererPane; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JViewport; import testing.Panel; import testing.testPanel; public class DialogSize { final private static String LOOKANDFEEL = "Windows"; private static JDialog dialog; private static JTextArea textArea; private static JTextField textField; private static JPanel panel; private static JRadioButton button; // <editor-fold defaultstate="collapsed" desc="initLookAndFeel"> private static void initLookAndFeel() { if (LOOKANDFEEL != null) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BlankBorder.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } } // </editor-fold> private static void createAndShowDialog() { initLookAndFeel(); dialog = new JDialog(); panel = new JPanel(); panel.setLayout(new BoxLayout(panel, Y_AXIS)); textArea = new JTextArea(); textArea.setText("Enter the dribble furble that you wish to frangle from all time."); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); button = new JRadioButton("Button"); textField = new JTextField(); panel.add(textArea); panel.add(button); panel.add(textField); dialog.add(panel); dialog.setVisible(true); dialog.pack(); analyseComponent(dialog); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowDialog(); } }); } private static int level = 0; private static String indent = "|"; public static void analyseFrame(JFrame frame) { if (frame == null) return; int h = frame.getHeight(); int w = frame.getWidth(); Container container = frame.getContentPane(); analyseComponent(frame); System.out.print("\n\n"); } public static void analyseContainer(Container container) { level++; indent += "-"; int componentCount = container.getComponentCount(); Component[] components = container.getComponents(); for (int i=0; i < componentCount; i++) { Component component = components[i]; analyseComponent(component); } indent = indent.replaceAll("(.*)-", "$1"); level--; } public static void analyseComponent(Component component) { Class componentClass = component.getClass(); String className = componentClass.getName(); int alignmentX = (int) component.getAlignmentX(); int alignmentY = (int) component.getAlignmentY(); int h = component.getHeight(); int w = component.getWidth(); System.out.print(level+indent+ "Name: "+component.getName()+", "+ "Class: "+component.getClass().getName()+", "+ " ["+(int)component.getPreferredSize().getHeight() +", "+ (int)component.getPreferredSize().getWidth()+"], "+ "H: "+h +", "+"W: "+w+", "+ "AlignmentX: "+alignmentX+", "+ "AlignmentY: "+alignmentY+ "\n"); if (className.contains("Dialog")) { analyseContainer((Container)component); } else if (className.contains("Pane")) { analyseContainer((Container)component); } } } A: In particular, why is the PreferredSize for the textarea ignored? Good question. I can't explain why it appears to be ignored. The default preferred size calculation will try to display all the text on a single line, but for some reason the calculated preferred width is not used when calculating the preferred size of the panel and therefore the dialog. All I can suggest is some guidelines for creating the GUI: First of all the order of execution should be: dialog.pack(); dialog.setVisible(true); When you do it the other way around the dialog will initially be displayed at its default size and then when the pack() is done it will be resized. There is a possibility that you could see the dialog painted and the default size and then jump to its larger size. When using text components you will want to provide additional information to the component so that it can better determine its preferred size. So you would use something like: JTextArea textArea = new JTextArea(3, 20); JTextField textField = new JTextField(10); This will allow each component to determine its preferred width based on the column value specified. With the text area the rows will provide information to be used to determine the height. When you use this approach the preferred size of the text area and text field will be used in the pack() calculation. Also you should use: panel.add( new JScrollPane( textArea ) ); This will make sure that 3 lines are initially displayed. If more lines are needed to display the text then scrollbars will appear.
{ "pile_set_name": "StackExchange" }
Q: What's the deal with Janeway's punishments? In "Meld," Suder commits murder, for basically no reason, and Janeway eventually puts him in his quarters under guard for the duration of the journey. He is initially put into the brig, but it seems as though it's only for a few days, if that. Paris is given a month in the brig, and reduced in rank, for disobeying the captain's orders ("Thirty Days"). This seems as though Janeway is awfully inconsistent when doling out punishment. Commit murder, spend a few days in the brig, then enjoy your quarters (presumably keeping your rank). Violate the captain's orders and interfere with another civilization, and you're in big trouble. In-universe reasons for this apparent discrepancy? It seems kind of ridiculous. A: As far as Suder was concerned, Janeway's goal wasn't to simply keep punishing him for the next 70+ years but to bring him back to a point where he might be useful to the ship and crew. That included radical "mind-meld" therapy and allowing him some measure of normality, as would befit someone who had committed a crime from a position of mental illness. JANEWAY: I don't. I prefer to rehabilitate him, not to end his life. We'll confine him to quarters. Work with Kim to install maximum security containment. TUVOK: Pardon me, Captain, but allowing him the comfort of his own quarters doesn't seem an appropriate punishment for murder. JANEWAY: If we don't get home soon, he'll be in that room a long time, Mister Tuvok. I think this is the best we can do under these circumstances. By comparison, Paris' punishment is exactly that, intended to actually punish him. By depriving him of the most basic facilities, Janeway seems convinced that he might actually learn something from his transgressions, in the same way that he was improved by his time in the prison on New Zealand. JANEWAY: I admire your principles, Tom, but I can't ignore what you've done. I hereby reduce you to the rank of Ensign, and I sentence you to thirty days solitary confinement. Take Ensign Paris to the brig. PARIS: I know the way. Purely as an aside, you may wish to note that it's pretty normal (in most countries) for long-term prisoners to be granted better facilities than those serving short-term sentences.
{ "pile_set_name": "StackExchange" }
Q: CSS: select a class whose name has a space? I have this D3 code which creates my x axis: svg.append("g") .attr("class", "x axis") .call(xAxis) How do I select my x axis in my css file? I have: .axis line { fill: none; stroke: black; shape-rendering: crispEdges; } But this would apply to all my axes (both x axis and y axis). How do I select only x axis? I know css selectors can be cascaded, but I'm not sure exactly how to do that... A: Class names cannot have spaces. you have 2 classes if your class name has a space. Use x-axis for your class name if you would like to reference it. ... none of which are space characters [0] [0] http://www.w3.org/TR/html5/infrastructure.html#set-of-space-separated-tokens A: Technically it is two separate classes, x and axis, but that doesn't mean you can't select and affect only what you want on the x-axis. Cascading selectors looks like this: .x.axis line { fill: none; stroke: black; shape-rendering: crispEdges; }
{ "pile_set_name": "StackExchange" }
Q: The effect of decoupling a coupled system of PDEs I asked a somewhat similar question previously but perhaps it might have been too specific for anyone to really answer. Here is a bit more general of a question that I am struggling with. Consider the following system: $$ -\nabla\cdot(D_{1}(u_{2})\nabla u_{1}) = \nabla\cdot\mathbf{f}_{1}(u_{2}) $$ $$ \frac{\partial u_{2}}{\partial t} + \nabla\cdot\mathbf{f}_{2}(u_{1},u_{2}) - \nabla\cdot(D_{2}(u_{2})\nabla u_{2}) = 0 $$ assuming a general set of BCs: $$ u_{i} = u_{i,D}, \;\;\;\text{on}\;\Gamma_{D} $$ $$ D_{i}\nabla u_{i}\cdot\mathbf{n} = u_{i,N}, \;\;\;\text{on} \;\Gamma_{N} $$ Using DGFEM for spatial discretizations and backwards Euler for the time derivative. We decouple like this: Solve for $u_{1}^{k+1}$ using $u_{2}^{k}$: $$ -\nabla\cdot(D_{1}(u_{2}^{k})\nabla u_{1}^{k+1}) = \nabla\cdot\mathbf{f}_{1}(u_{2}^{k}) $$ Solve for $u_{2}^{k+1}$ using $u_{1}^{k+1}$: $$ \frac{\partial u_{2}}{\partial t} + \nabla\cdot\mathbf{f}_{2}(u_{1}^{k+1},u_{2}^{k},u_{2}^{k+1}) - \nabla\cdot(D_{2}(u_{2}^{k+1})\nabla u_{2}^{k+1}) = 0 $$ Newton's method is used to handle the non-linearity. In the particular example I'm looking at, I have $$ \mathbf{f}_{2}(u_{1},u_{2}) = u_{2}(-\nabla u_{1} + u_{2}\nabla u_{2}) $$ so $$ \mathbf{f}_{2}(u_{1}^{k+1},u_{2}^{k},u_{2}^{k+1}) = u_{2}^{k+1}(-\nabla u_{1}^{k+1} + u_{2}^{k}\nabla u_{2}^{k}) $$ The issue is that the evaluation of $\mathbf{f}_{2}$ at $u_{1}^{k+1}$ and $u_{2}^{k}$ is really messing up my solution of $u_{2}^{k+1}$ to the point where Newton's method is not converging quadratically and I'm not observing the correct convergence of the discretization errors. I originally wanted to evaluate $\mathbf{f}_{2}$ at $u_{2}^{k}$ so that the vector part, $-\nabla u_{1}^{k+1} + u_{2}^{k}\nabla u_{2}^{k}$ could be treated as a constant at each Newton iteration. Otherwise, it would have to be added to the second order term, which I wanted to avoid doing. To test my code, I'm using method of manufactured solutions. As a test, I'm considering the second equation by itself and evaluating $\mathbf{f}_{2} = \mathbf{f}_{2}(u_{1,\text{exact}}^{k+1}, u_{2}^{k+1}, u_{2,\text{exact}}^{k+1}) = u_{2}^{k+1}(-\nabla u_{1,\text{exact}}^{k+1} + u_{2,\text{exact}}^{k+1}\nabla u_{2,\text{exact}}^{k+1})$ using the exact solutions and there's, no problem here. Newton's method converges quadratically, I'm observing correct convergence of discretization error, etc. so I'm pretty sure the error here lies with the decoupling and not the discretization. Is this suboptimal performance in the first scenario expected given the decoupling? I know the decoupling will limit the time step, but I'm pretty sure I'm taking the time step sufficiently small. The next step I was going to take was to split up $\mathbf{f}_{2}$ and toss the $u_{2}\nabla u_{2}$ into the second order term. This would have the advantage of making the formulation more implicit since the only explicit part would be the use of $u_{1}^{k+1}$ in the convective term. I hadn't been able to find much literature on what effect decoupling would have on convergence, so if anyone could point me in the right direction or offer some advice, that would be great. A: This is definitely whats known as a splitting scheme and are very popular in nonlinear optics as well as Quantum simulations, an example being the dirac equation but you can also do it on nonlinear PDES'. I think the issue you're having is that you're solving for $u_1^{k+1}$ first in terms of $u_2^k$, when you should really be solving for $u_1^{k+1}$ in terms of $u_2^{k+1}$, (if you want to use an upwind scheme in (2). To see this, notice that the first equation is linear in $u_1$, with coefficients and an inhomogeneity only depending on $u_2$. So 'in principle' (it could be brutally tough), you could find you're solution to $u_1$ from the first equation (1), analytically in terms of a Greens function (which also may depend on $u_2$) convoluted with the LHS of one. ie. let $ Lu_1$ be the RHS of (1) and $f=\nabla \cdot f_2(u_2)$ and let $G(x;u_2)$ satisfy $LG=\delta(x-s)$ and the boundary conditions for $u_1$, then $u_1=\int_{\Omega} G((x-s);u_2)fds$ So you've reduced the coupled set to an integro-differential equation for (2). However, now look what happens if you want to do an upwind scheme for $u_2^{k+1}$, you find that $u_1^{k+1}$ depends on $u_2^{k+1}$. There is definitely flexibility though in this decoupling or splitting though that could make for a nice scheme in your equations. A nice introduction to splitting in the context you're interested in can be found in Chapter 13 'Splitting and its cousins' of Boyd 'Chebyshev and Fourier Spectral Methods'. Hope this helps
{ "pile_set_name": "StackExchange" }
Q: Is it possible to Inherit from a structure without having another initialized structure in C I am a new data structures student and trying to get familiar with c structs. I know inheritance from my past python experiences so I wanted to pseudo try it in c. My code goes like this: typedef struct{ char name[20]; int age; int weight; int selling_price; } Animal; typedef struct{ Animal *animal; int can_speak; }super_animal; int main() { Animal monkey; strcpy(monkey.name,"Mustafa"); monkey.age=19; monkey.weight=80; super_animal human; human.animal=&monkey; human.can_speak=1; printf("%s, can speak bool:%d\n",human.animal->name,human.can_speak); return 0; } I want to cut that middle monkey step from the code.Is it possible to use an unassigned structure pointer like that? A: As long as animal has type Animal *, it must point to valid memory before it is used. That memory does not have to have a name or be referenced by another pointer with a name. That is, you can remove the separate monkey variable by directly allocating memory for the human: super_animal human = { .animal = malloc(sizeof *human.animal), .can_speak = 1 }; if (human.animal == NULL) HandleError(); strcpy(human.animal->name, "Mustafa"); human.animal->age = 19; human.animal->weight = 80; If you instead change the type of the animal member to Animal instead of Animal *: typedef struct{ Animal animal; int can_speak; }super_animal; thus embedding an Animal structure directly in the super_animal structure, then you do not need to provide separate memory: super_animal human = { .animal.name = "Mustafa", .animal.age = 19, .animal.weight = 80, .can_speak = 1 }; printf("%s, can speak bool:%d\n",human.animal.name,human.can_speak); Note that this changes .animal.name to point to a string literal directly instead of making a copy of it. That is not necessary for this example. There are a variety of ways to decide how to handle the name, how to initialize the structure, and so on.
{ "pile_set_name": "StackExchange" }
Q: Demand loading a UIScrollView I would like to implement an app using a UIScrollView with paging, similar to the apple weather app. But I am a little concerned about performance. The example implementation I have been using loads all of the views then the application launches. After a certain point, once this prove slow? I wonder how Apple's camera roll is dealing with this, where a user may have 100+ photos that can be scrolled through. Should I try to figure out a way to build the view only when it is needed? Or maybe there is a way to replicate the dequeue reusable cell technique from a UITableView, only for horizontal view loading, since each view will have the same layout. A: By far the most efficient solution (and this is used in many photo-browsing apps such as Facebook, and probably the native Photos app too) is going to be to load the content on-demand, just as UITableView does. Apple's StreetScroller sample project should get you on the right track. A: A very efficient solution, is to make sure to reuse any views whenever possible. If you are going to be simply displaying images, you could use a subclass of UIScrollView, and layout these reusable views within layoutSubviews. Here you could detect what views are visible and not visible and create the subviews as needed. An example dequeuing function may look like: - (UIImageView *)dequeueReusableTileWithFrame:(CGRect) frame andImage:(UIImage *) image { UIImageView *tile = [reusableTiles anyObject]; if (tile) { [reusableTiles removeObject:tile]; tile.frame = frame; } else { tile = [[UIImageView alloc] initWithFrame:frame]; } tile.image = image; return tile; } Where reusableTiles is just an iVar of NSMutableSet type. You could then use this to load fetch any currently offscreen image views and quickly and easily bring them back into view. Your layoutSubviews may look something like: - (void)layoutSubviews { [super layoutSubviews]; CGRect visibleBounds = [self bounds]; CGPoint contentArea = [self contentOffset]; //recycle all tiles that are not visible for (GSVLineTileView *tile in [self subviews]) { if (! CGRectIntersectsRect([tile frame], visibleBounds)) { [reusableTiles addObject:tile]; [tile removeFromSuperview]; } } int col = firstVisibleColumn = floorf(CGRectGetMinX(visibleBounds)/tileSize.width); lastVisibleColumn = floorf(CGRectGetMaxX(visibleBounds)/tileSize.width) ; int row = firstVisibleRow = floorf(CGRectGetMinY(visibleBounds)/tileSize.height); lastVisibleRow = floorf(CGRectGetMaxY(visibleBounds)/tileSize.height); while(row <= lastVisibleRow) { col = firstVisibleColumn; while (col <= lastVisibleColumn) { if(row < firstDisplayedRow || row > lastDisplayedRow || col < firstDisplayedColumn || col >lastDisplayedColumn) { UImageView* tile = [self dequeueReusableTileWithFrame:CGRectMake(tileSize.width*col, tileSize.height*row, tileSize.width, tileSize.height) andImage:YourImage]; [self addSubview:tile]; } ++col; } ++row; } firstDisplayedColumn = firstVisibleColumn; lastDisplayedColumn = lastVisibleColumn; firstDisplayedRow = firstVisibleRow; lastDisplayedRow = lastVisibleRow; } I used something similar to this to tile in areas of a line when I was working with an exceptionally large area of a scroll view and it seemed to work quite well. Sorry for any typos that I may have created when updating this for an image view instead of my custom tileView class.
{ "pile_set_name": "StackExchange" }
Q: How Would I Go About Aggregating Text Results Into A Singular Temporary Column? I have a database. From this database, I have queried and received the results: Breed | Name Mastiff | John Golden | Jojo Shih Tzu| Mimi Poodle | John Labrador| Jojo Mastiff | Jojo And I was hoping to learn how I would be able to manipulate the data so that the results would look something like this - or (however the SQL operating procedure is) Breed | Names Mastiff | John, Jojo Labrador| Jojo Golden | Jojo Shih Tzu| Mimi Poodle | Jojo Where basically the Breeds' have had all the names pointing to them aggregated to them. Like COUNT() but for Strings A: you can do this with GROUP_CONCAT SELECT Breed, GROUP_CONCAT(Name ORDER BY Name SEPARATOR ', ') Names FROM tbl GROUP BY Breed ORDER BY Breed;
{ "pile_set_name": "StackExchange" }
Q: Another Chinese Remainder Theorem Problem This is very similar to: Chinese Remainder Theorem Problem in that in applying an algorithm, I get an incorrect answer and do not see where my mistake lies. One of the answers to the question linked to above noted that there are many different algorithms circulating for solving the CRT. The one I am using is similar to that used above, but not exactly the same. I got mine from Chapter 33 of Algorithms, by Cormen, Leiserson, and Rivest. The problem is to find z that satisfies $$3\ mod\ 8$$ $$7\ mod\ 21$$ $$22\ mod\ 25$$ $$2\ mod\ 11$$ Since 8, 21, 25, and 11 are relatively prime, there is a solution. The method hinges on finding constants $c_1, .., c_4$ in the following manner. Let $(a_1, .., a_4) = (3, 7, 22, 2)$, and $(n_1,..,n_4) = (8, 21, 25, 11)$. $n$ is the product of the $n_i$: Here 46200. Define $(m_1,..,m_4)$ by dividing out $n_i$ from $n$, e.g. ($\frac{46200}{8}, \frac{46200}{21}, \frac{46200}{25}, \frac{46200}{11}$), or $(5775, 2200, 1848, 4200)$. Find $(m_i^{-1}\ mod\ n_i)$. For the $m_i$ given these calculations are below. By way of explanation, in the calculation below for $m_1^{-1}$, $m_1 + 1 = 5775 + 1 = 5776$ is divisible by $8$, which is true (in other words that 1 is the inverse of 5775 in the mod 8 equivalence class). $$m_1^{-1}\ mod\ 8 = 1$$ $$m_2^{-1}\ mod\ 21 = 5$$ $$m_3^{-1}\ mod\ 25 = 2$$ $$m_4^{-1}\ mod\ 11 = 2$$. The constants $c_i$ are now formed from the $m_i$ and the inverses just found $(1, 5, 2, 2)$ by multiplying corresponding pairs: $(1 \cdot 5775, 5 \cdot 2200, 2 \cdot 1848, 2 \cdot 4200)$, or ($5775, 11000, 3696, 8400$). Finally, one solves $$a = (a_1 \cdot c_1 + .. + a_4 \cdot c_4)\ mod\ n$$ to get $$(3 \cdot 5775 + 7 \cdot 11000 + 22 \cdot 3696 + 2 \cdot 8400)\ mod\ 46200$$ I get as one of the solutions for this the number $a = 7637$. However 7637 does not work! For example, $7637\ mod\ 8 = 5$, whereas to be a solution it must be true that $7637\ mod\ 8 = 3$. If someone can point out what I am doing wrong, I would greatly appreciate it! A: The arithmetic is usually easier if you solve the congruences successively instead of in parallel. Start off with $\,x = 22+25i\,$ by $\,x\equiv 22\pmod{25}.$ Substitute that into $\,7\equiv x\pmod{21},$ solve for $\,i$ to get a new value for $\,x,\,$ then substitute that into the next congruence, etc. ${\rm mod}\ 21\!:\ 7 \equiv 22+25\,\color{#c00}i\equiv 1+4i\!\iff\! 4i\equiv 6\!\iff\! 2i\equiv 3\iff\! \smash[t]{\overbrace{\color{}i\equiv 3/2\equiv 24/2\equiv \color{}{12}}^{\Large \color{#c00}{i\, =\, 12}\, +\, 21j}}\phantom{1^{1^{1^{1^{1^(1^1}}}}}$ ${\rm mod}\ 11\!:\ 2\equiv 22+25(\color{#c00}{12}+21\color{#0a0}j)\,\equiv\, 3(1-j)\iff 3j\equiv 1\iff\! \smash[b]{\underbrace{\color{}j\equiv 1/3\equiv 12/3\equiv \color{}4}_{\Large\color{#0a0}{j\,=\, 4}\,+\,11k}}$ ${\rm mod}\,\ \ 8\!:\ 3\equiv 22+25(12+21(\color{#0a0}4+11k))$ $\qquad\qquad\! 3 \equiv -2\ \ +\ (\ \ 4\ -\ 3(4\,+\ \,3\color{#c0f}k)) \equiv\, {-}2-k \iff \smash[b]{\underbrace{\color{}k\equiv-5\equiv \color{}3}_{\Large \color{#c0f}{k\,=\,3}\,+\,8n}}$ $\!\begin{align}{\rm Hence}\ \ x\equiv &\ \ 22+25(12+21(4+11(\color{#c0f}3+8n)))\\ =&\ \ 19747+46200 n\end{align}$ Notice that this way all the numbers are so small that all the arithmetic can be done mentally, except possibly for the final additions and multiplications in the last line.
{ "pile_set_name": "StackExchange" }
Q: How to convert a SQL subquery to a join I have two tables with a 1:n relationship: "content" and "versioned-content-data" (for example, an article entity and all the versions created of that article). I would like to create a view that displays the top version of each "content". Currently I use this query (with a simple subquery): SELECT t1.id, t1.title, t1.contenttext, t1.fk_idothertable t1.version FROM mytable as t1 WHERE (version = (SELECT MAX(version) AS topversion FROM mytable WHERE (fk_idothertable = t1.fk_idothertable))) The subquery is actually a query to the same table that extracts the highest version of a specific item. Notice that the versioned items will have the same fk_idothertable. In SQL Server I tried to create an indexed view of this query but it seems I'm not able since subqueries are not allowed in indexed views. So... here's my question... Can you think of a way to convert this query to some sort of query with JOINs? It seems like indexed views cannot contain: subqueries common table expressions derived tables HAVING clauses I'm desperate. Any other ideas are welcome :-) Thanks a lot! A: This probably won't help if table is already in production but the right way to model this is to make version = 0 the permanent version and always increment the version of OLDER material. So when you insert a new version you would say: UPDATE thetable SET version = version + 1 WHERE id = :id INSERT INTO thetable (id, version, title, ...) VALUES (:id, 0, :title, ...) Then this query would just be SELECT id, title, ... FROM thetable WHERE version = 0 No subqueries, no MAX aggregation. You always know what the current version is. You never have to select max(version) in order to insert the new record. A: Maybe something like this? SELECT t2.id, t2.title, t2.contenttext, t2.fk_idothertable, t2.version FROM mytable t1, mytable t2 WHERE t1.fk_idothertable == t2.fk_idothertable GROUP BY t2.fk_idothertable, t2.version HAVING t2.version=MAX(t1.version) Just a wild guess...
{ "pile_set_name": "StackExchange" }
Q: Drawing complex shapes in Eagle I have two parallel lines intersecting a circle. Is there a command that will break the drawing up into separate pieces (2) at the intersection points? I want to send up with what's in (3). A: Unlike AutoCAD or SolidWorks, there is no command in Eagle, which would break or trim lines at intersections. Your shape isn't very complex. There are several options. Find/calculate the coordinates of the intersection points. Then draw 2 separate arcs and 2 separate lines. Draw a rectangle. Then change the Curve property of the sides, which will make them into arcs.
{ "pile_set_name": "StackExchange" }
Q: How much leverage pressure is it needed to compress coffee for an espresso? Some espresso machines come with a lever to compact the ground coffee before the espresso starts the brewing, other machines do the compacting part by themselves. How much leverage or pressure is it required to make the coffee compact enough to go to the next step of brewing the espresso, and what happens if I put too much pressure (i.e equivalent to 1ton)? A: Based on your comment on the question, you are referring to compacting ground coffee in the portafilter. This process is referred to as tamping when making espresso. The widely-accepted amount of downward force to use when tamping a standard double shot of espresso is 30 lbs. You can view a source here but if you simply do a google search for "espresso tamping pressure" you will see 30 lbs mentioned ubiquitously. If you are using a tamper directly on the coffee grinds, it is easy to practice putting down 30 lbs of force by practicing on a scale. If you are indeed using a lever to do the tamping, I suggest reading the instructions that came with your machine. 30 lbs of force on the lever may not result in 30 lbs of force on the espresso, depending on the setup of your machine. The lever may even be engineered specifically to stop tamping at 30 lbs. Tamping espresso with a lever setup can be a bit of controversial thing in the coffee world. Whatever your setup, you want 30 lbs of downward force to result from whatever it is that contacts with the ground coffee and tamps it down. Putting too much force on the ground coffee is called over-tamping. The coffee grinds can become over-compacted which can slow down extraction (lead to over-extraction) of the espresso, lead to channeling (where water finds inconsistencies in the grind and channels through in small spots, leading to unequal extraction in the espresso puck), or even block it completely. If you used 1 ton of downward force when tamping, I suggest that you will likely break your portafilter and its basket, along with whatever is beneath it.
{ "pile_set_name": "StackExchange" }
Q: Cannot upgrade to 16.04 after failed attempt I have ubuntu 14.04 LTS and it kept jumping out a message asking me to upgrade to 16.04. So one day I clicked "yes". But then, it failed and it said it would restore to the old system (which is 14.04). That's pretty much a success except that one of the startup screen reads "Ubuntu 16.04". So far I haven't noticed other differences. The upgrade error messages are: Could not install 'linux-image-extra-4.4.0-34-generic' The upgrade will continue but the 'linux-image-extra-4.4.0-34-generic' package may not be in a working state. Please consider submitting a bug report about it. subprocess installed post-installation script returned error exit status 1 Could not install 'initramfs-tools' The upgrade will continue but the 'initramfs-tools' package may not be in a working state. Please consider submitting a bug report about it. subprocess installed post-installation script returned error exit status 1 Could not install the upgrades The upgrade has aborted. Your system could be in an unusable state. A recovery will run now (dpkg --configure -a). I figured that at least one of the reasons that the upgrade failed may be due to disk full in /boot. So I cleaned it up and tried to upgrade again. But now, I don't know how to do it. The automatic reminder doesn't jump out anymore. I tried command line and the response is as follows: sudo do-release-upgrade Checking for a new Ubuntu release No new release found So how can I re-enable the upgrade? A: It appears that your upgrade was partially successful except for perhaps the latest kernel. Since you have now made room in /boot, you can try installing the metapackage linux-generic-lts-xenial which will get you the latest xenial kernel. If other portions of the upgrade didn't succeed, I do not know how to diagnose that.
{ "pile_set_name": "StackExchange" }
Q: Defining a C++ struct return type in Cython I have written a small C++ library to simulate a system of ODEs, and have used Cython to wrap a function that initializes and solves the system. The C++ function takes in a handful of parameters, and returns a struct containing two matrices: a set of patterns used to construct the system, and the solved state of the system at every time step. These matrices are implemented using the Eigen library, so I am using the Eigency interface to transfer the underlying contents of these data structures to NumPy arrays. All is good if, in Python, I return a view to one of these matrices. However, I would like to return a tuple containing both of these matrices, which requires temporarily storing this struct, and then returning each of its matrix members: ## kernel.pyx from eigency.core cimport * cdef extern from "kernel_cpp.h": cdef cppclass network: MatrixXf state MatrixXf patterns cdef network _run "run" (int N, int K, int P, double g, double T, double tau, double dt) def run(N=10000, K=100, P=30, g=1.5, T=0.5, tau=1e-3, dt=1e-3): return ndarray_view(_run(N,K,P,g,T,tau,dt).state) # <--- This works # This does not: # cdef network net = _run(N,K,P,g,T,tau,dt): # return (ndarray_view(net.state), ndarray_view(net.patterns)) The error that I get when building the commented code with python setup.py build_ext --inplace is kernel.cpp:1552:11: error: no matching constructor for initialization of 'network' network __pyx_v_net; ^` and this makes sense to me -- Cython is trying to call a constructor for network. But I want the construction to take place within "run." What is the correct type declaration here? In case it helps, a stripped-down version of the code is here. Thanks! A: It's worth knowing how Cython translates code which stack allocates C++ variables: def run(N=10000, K=100, P=30, g=1.5, T=0.5, tau=1e-3, dt=1e-3): cdef network net = _run(N,K,P,g,T,tau,dt) the inside of the function gets translated to: { // start of function network net; // actually some mangled variable name (see your error message) // body of function net = _run(N,K,P,g,T,tau,dt); } i.e. it requires both a default constructor and a copy/move assignment operator. This doesn't match how C++ code tends to be written so occasionally causes problems. Cython usually assumes the existence of these (unless you tell it about other constructors) so you don't need to explicitly write these out in your cdef cppclass block. I think your error message looks to occur when compiling the C++ code and it's not defining a default constructor. (The copy assignment later shouldn't be a problem since C++ will automatically generate this). You have two options: If you're happy modifying the C++ code then define a default constructor. This will allow the Cython code to work as written. If you're using >=C++11 then that could be as easy as: network() = default; It's possible that this won't work depending on whether the internal Eigen types can be default constructed though. If you don't want modify the C++ code, or if it turns out you can't easily define a default constructor, then you'll have to modify the Cython code to allocate the network with new. This also means you'll have to deal with deallocation yourself: # earlier cdef cppclass network: # need to tell Cython about copy constructor network(const network&) # everything else as before def run(N=10000, K=100, P=30, g=1.5, T=0.5, tau=1e-3, dt=1e-3): cdef network* net try: net = new network(_run(N,K,P,g,T,tau,dt)) return (ndarray_view(net.state), ndarray_view(net.patterns)) finally: del net In this case no default constructor is needed, only a copy/move constructor (which you have to have anyway to be able to return a network from a function). Note use of finally to ensure than we free the memory.
{ "pile_set_name": "StackExchange" }
Q: Parameter is not valid when saving TIFF to stream I have a multi-page TIFF that I'm splitting up page by page using Leadtools, and changing the compression on them to be compatible with a third party. When I try to save the image to a memoryStream, I get a Parameter is not valid exception. However, this only happens on their machine, or my test machine running Server 2008. I cannot reproduce this on my development machine (Win 7 using VS2008). Here is the code: RasterImage image = codecs.Load( file, 0, CodecsLoadByteOrder.RgbOrGray, currentPage, currentPage + (detail.Pages - 1) ); Image newImage = RasterImageConverter.ConvertToImage( image, ConvertToImageOptions.None ); MemoryStream memStream = new MemoryStream(); ImageCodecInfo encoderInfo = GetEncoderInfo( ); EncoderParameters encoderParams = new EncoderParameters( 1 ); EncoderParameter parameter = new EncoderParameter( System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT4 ); encoderParams.Param[0] = parameter; newImage.Save(memStream, encoderInfo , encoderParams); Any thoughts on this? Thanks for the help! A: Check the pixel format of the image. If it's anything other than 1 bit, this will fail - you can't use CCITT on anything other than 1 bit. It could also be that the particular OS doesn't have a CCITT4 subcodec and might only have a CCITT3 (although this is highly unlikely).
{ "pile_set_name": "StackExchange" }
Q: How to apply a patchfile such that it creates new files if needed? I have a set of patch files, which include newly created files. Is there a way to tell patch to create those files or do I have to touch each one manually? A: patch will create new files if they were created in the patch file.
{ "pile_set_name": "StackExchange" }
Q: Can I send almost 1MB transaction? Block size is still limited to 1MB. As I understood, transaction size is no longer limited. So can I be sure that my transaction with 29000 outputs and reliable fee will be included into block? Or what is the max transaction size? A: Can I send almost 1MB transaction? To be able to send a transaction that a miner will accept, that transaction has to be a standard transaction. As defined in policy.h /** The maximum weight for transactions we're willing to relay/mine */ static const unsigned int MAX_STANDARD_TX_WEIGHT = 400000; For non-Segwit transactions, the limit is 400,000 KB / 4 = 100,000 B = 100 kB. Therefore, if you have a Pre-Segwit transaction larger than 100 kB but smaller than the block s̶i̶z̶e weight limit, you should contact a miner, and they'll be able to add your transaction to their block manually, if it's profitable for them.
{ "pile_set_name": "StackExchange" }
Q: WUBI - Super Block Error We had installed ubuntu 10.04 using Wubi on my machine. After a reboot it stopped working. Its says super block corrupted Is there any tool or how can I get my data from the Ubuntu OS which is already installed on my mahcine Please help me to solve this issue. A: There isn't anything already installed that can access the disk. This tool can be used from Windows to get readonly access to the \ubuntu\disks\root.disk but you may have issues if there is file system corruption. You should boot from an Ubuntu CD/USB in live mode (select "Try Ubuntu") and fsck the root.disk as described here. For example, if your root.disk is on /dev/sda1 you would (change /dev/sda1 as appropriate): Boot a live CD/USB Mount the Windows partition sudo mkdir /media/win sudo mount /dev/sda1 /media/win Fsck the root.disk sudo fsck /media/win/ubuntu/disks/root.disk Don't fsck the root.disk if it's mounted. PS for Wubi it's important not to do hard resets. See here.
{ "pile_set_name": "StackExchange" }
Q: Add top and left borders with magick command Is there a way to add 5 or any number of white/transparent pixels at the top and left borders of an image with the magick command in Linux? A: Use the -splice operator. First make a solid magenta rectangle: magick -size 100x50 xc:magenta image.png Now splice on a yellow chunk (so you can see it) 10 wide and 20 tall: magick image.png -background yellow -gravity northwest -splice 10x20 result.png Change yellow to none for transparent pixels. Change magick to convert for v6 ImageMagick. If you just want to splice to the East side: magick image.png -background yellow -gravity east -splice 10x east.png If you just want to splice to the South side: magick image.png -background yellow -gravity south -splice x10 south.png
{ "pile_set_name": "StackExchange" }
Q: Auto Layout size of CollectionViewCell in relation to CollectionView I have a CollectionViewCell placed in a CollectionView. The size of the CollectionView is set via Auto Layout and can change at times. I want to (programmatically) set constraints on my CollectionView, so that the size of the CollectionViewCell is responsive to the size of the CollectionView (Say the width of the Cell is equal to the width of the CollectionView-100 and the height should be equal). How can I declare constraints between the Cell and the CollectionView? When, where and how do set those constraints? Do I have to call setNeedsLayout on the Cells when the size of the CollectionView changes? I searched for this quite long and all I found was always about changing the size of the Cell according to its content – that’s not what I am trying to do. The only hint that I got is that I might have to subclass CollectionViewLayout – but I’m not sure about that. Any help is appreciated! A: You cant achieve this by using constrains but you can easily do that by using UICollectionViewDelegate sizeForItemAtIndexPath method. Example : func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ return CGSizeMake(collectionView.frame.size.width / 2 ,collectionView.frame.size.height/ 2) } And after changing collectionView size all you need to do is calling its reloadData method
{ "pile_set_name": "StackExchange" }
Q: ASP.net MVC project not compiling on IIS I used to just upload asp.net websites to the live server, and IIS compiles them automatically. But when I do the same with asp.net MVC projects I just get errors, and I need to release Build the project before I upload it. Note1: I'm using VWD 2008 Express Note2: The project is working perfectly if I release build it on my machine then upload to the server A: Charles Boyung's comment should have been considered as an answer. MVC applications are like Web Projects, not Web Sites in Visual Studio - they must be compiled before deployment. – Being not compiling on the server is one of the difference points between Web Application Projects (WAPs) and Web Site Projects (WSPs) http://vishaljoshi.blogspot.com/2009/08/web-application-project-vs-web-site.html Q1. Do you intend to deploy source code on your production server and edit it right on the server if there was a time sensitive bug reported ? If you answered Yes to the above question, you want to use Web Site projects (WSPs)… In case of Web Site projects Visual Studio does not really compile your source code on your dev box, it merely uses aspnet_compiler to validate that your source code will actually compile and run on the server… Hence when you try to deploy a web site people typically also deploy the source code on the server which allows them to edit the source right on the production server if there was a time sensitive bug reported
{ "pile_set_name": "StackExchange" }
Q: control background music from 3rd party apps ios Is there a way to control music currently playing in the background? I am able to control the native ipod application with the MPMusicPlayerController iPodMusicPlayer, but what i basically want is the functionality of the ipod controller in the task switcher. I want to be able to control the app currently playing (next/prev). The controls in the task switcher controls spotify, pandora or any other app currently playing. Any ideas? A: You can do this. Make sure you are using the AVAudioSessionCategoryPlayback audio session, first off. After you activate the audio session, call: [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; See here for more details http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/RemoteControl/RemoteControl.html
{ "pile_set_name": "StackExchange" }
Q: Installing Teamspeak and creating TeamSpeak3 .desktop file I am very new to Ubuntu and I want to create desktop launcher. I have this in my TeamSpeak3.desktop in [Desktop Entry] Name=TeamSpeak 3 Comment=TeamSpeak 3 VoIP Communicator Exec=/opt/TeamSpeak3-Client-linux_amd64/ts3client_runscript.sh Terminal=false Type=Application Categories=Network;Application; Icon=/opt/TeamSpeak3-Client-linux_amd64/styles/default/logo-128x128.png in my ~/.local/share/applications/TeamSpeak3.desktop But I dont see it in my launcher and when I double click on it files, it just opens the text file. I even made it executable with chmod +x TeamSpeak3.desktop drwx------ 15 hung hung 4096 srp 16 12:29 . drwxr-xr-x 3 root root 4096 pro 9 19:22 .. -rw------- 1 hung hung 174627 srp 16 12:29 CHANGELOG -rwx------ 1 hung hung 227136 srp 16 12:29 error_report drwx------ 2 hung hung 4096 srp 16 12:29 gfx drwx------ 3 hung hung 4096 srp 16 12:29 html drwx------ 2 hung hung 4096 srp 16 12:29 iconengines drwx------ 2 hung hung 4096 srp 16 12:29 imageformats -rwx------ 1 hung hung 334520 srp 16 12:29 libc++abi.so.1 -rwx------ 1 hung hung 1934744 srp 16 12:29 libcrypto.so.1.0.0 -rwx------ 1 hung hung 746960 srp 16 12:29 libc++.so.1 -rwx------ 1 hung hung 5842312 srp 16 12:29 libQt5Core.so.5 -rwx------ 1 hung hung 484832 srp 16 12:29 libQt5DBus.so.5 -rwx------ 1 hung hung 5683224 srp 16 12:29 libQt5Gui.so.5 -rwx------ 1 hung hung 1335584 srp 16 12:29 libQt5Network.so.5 -rwx------ 1 hung hung 290008 srp 16 12:29 libQt5Positioning.so.5 -rwx------ 1 hung hung 3829280 srp 16 12:29 libQt5Qml.so.5 -rwx------ 1 hung hung 3831288 srp 16 12:29 libQt5Quick.so.5 -rwx------ 1 hung hung 234552 srp 16 12:29 libQt5Sql.so.5 -rwx------ 1 hung hung 331232 srp 16 12:29 libQt5Svg.so.5 -rwx------ 1 hung hung 117104 srp 16 12:29 libQt5WebChannel.so.5 -rwx------ 1 hung hung 67570152 srp 16 12:29 libQt5WebEngineCore.so.5 -rwx------ 1 hung hung 208344 srp 16 12:29 libQt5WebEngineWidgets.so.5 -rwx------ 1 hung hung 6439120 srp 16 12:29 libQt5Widgets.so.5 -rwx------ 1 hung hung 1334528 srp 16 12:29 libQt5XcbQpa.so.5 -rwx------ 1 hung hung 180248 srp 16 12:29 libquazip.so -rwx------ 1 hung hung 22936 srp 16 12:29 libsnappy.so.1 -rwx------ 1 hung hung 111888 srp 16 12:29 libsrtp.so.0 -rwx------ 1 hung hung 383072 srp 16 12:29 libssl.so.1.0.0 -rwx------ 1 hung hung 51080 srp 16 12:29 libudev.so.0 -rw------- 1 hung hung 4340 srp 16 12:29 openglblacklist.json -rwx------ 1 hung hung 260232 srp 16 12:29 package_inst drwx------ 2 hung hung 4096 srp 16 12:29 platforms -rw------- 1 hung hung 26 srp 16 12:29 qt.conf drwx------ 2 hung hung 4096 srp 16 12:29 qtwebengine_locales -rwx------ 1 hung hung 19720 srp 16 12:29 QtWebEngineProcess drwx------ 2 hung hung 4096 srp 16 12:29 resources drwx------ 6 hung hung 4096 srp 16 12:29 sound drwx------ 2 hung hung 4096 srp 16 12:29 soundbackends drwx------ 2 hung hung 4096 srp 16 12:29 sqldrivers drwx------ 3 hung hung 4096 srp 16 12:29 styles drwx------ 2 hung hung 4096 srp 16 12:29 translations -rwx------ 1 hung hung 18987008 srp 16 12:29 ts3client_linux_amd64 -rwx------ 1 hung hung 1364 srp 16 12:29 ts3client_runscript.sh -rwx------ 1 hung hung 2206064 srp 16 12:29 update drwx------ 2 hung hung 4096 srp 16 12:29 xcbglintegrations A: Ok you have some things wrong in your whole setup and like this it can not really work so I'm going through the whole installation process for you so you can pick up where you got astray. download the TeamSpeak3-Client-linux_amd64-3.1.6.run from The Teamspeak Website run the TeamSpeak3-Client-linux_amd64-3.1.6.run file with: chmod 755 TeamSpeak3-Client-linux_amd64-3.1.6.run ./TeamSpeak3-Client-linux_amd64-3.1.6.run move the whole new directory to /opt with sudo mv TeamSpeak3-Client-linux_amd64 /opt/ change the ownership of the moved copy and recursively change the file permissions with: sudo chown -Rv root:root /opt/TeamSpeak3-Client-linux_amd64 sudo chmod -Rv 755 /opt/TeamSpeak3-Client-linux_amd64 download some nice icon for Teamspeak, since the provided does not really look good, google simply for teamspeak ico png and download one and move it to the /opt/TeamSpeak3-Client-linux_amd64 and name it appropriately; I have chosen here simply teamspeak-icon.png create your .desktop file in /usr/share/applications (you can copy and paste the whole code-block to the terminal): sudo su && cat > /usr/share/applications/teamspeak.desktop << EOF [Desktop Entry] Name=TeamSpeak 3 Comment=TeamSpeak 3 VoIP Communicator Exec=/opt/TeamSpeak3-Client-linux_amd64/ts3client_runscript.sh Terminal=false Type=Application Categories=Network;Application; Icon=/opt/TeamSpeak3-Client-linux_amd64/teamspeak-icon.png EOF exit This should leave you with a working Teamspeak client working for every user on the system.
{ "pile_set_name": "StackExchange" }
Q: int array to int number in Java I'm new on this site and, if I'm here it's because I haven't found the answer anywhere on the web and believe me: I've been googling for quite a time but all I could find was how to convert a number to an array not the other way arround. I'm looking for a simple way or function to convert an int array to an int number. Let me explain for example I have this : int[] ar = {1, 2, 3}; And I want to have this: int nbr = 123; In my head it would look like this (even if I know it's not the right way): int nbr = ar.toInt(); // I know it's funny If you have any idea of how I could do that, that'd be awesome. A: Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result. Result: 0 Loop 1: Result * 10 => 0, Result + 1 => 1 Loop 2: Result * 10 => 10, Result + 2 => 12 Loop 3: Result * 10 >= 120, Result + 3 => 123 This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal. A: First you'll have to convert every number to a string, then concatenate the strings and parse it back into an integer. Here's one implementation: int arrayToInt(int[] arr) { //using a Stringbuilder is much more efficient than just using += on a String. //if this confuses you, just use a String and write += instead of append. StringBuilder s = new StringBuilder(); for (int i : arr) { s.append(i); //add all the ints to a string } return Integer.parseInt(s.toString()); //parse integer out of the string } Note that this produce an error if any of the values past the first one in your array as negative, as the minus signs will interfere with the parsing. This method should work for all positive integers, but if you know that all of the values in the array will only be one digit long (as they are in your example), you can avoid string operations altogether and just use basic math: int arrayToInt(int[] arr) { int result = 0; //iterate backwards through the array so we start with least significant digits for (int n = arr.length - 1, i = 1; n >= 0; n --, i *= 10) { result += Math.abs(arr[n]) * i; } if (arr[0] < 0) //if there's a negative sign in the beginning, flip the sign { result = - result; } return result; } This version won't produce an error if any of the values past the first are negative, but it will produce strange results. There is no builtin function to do this because the values of an array typically represent distinct numbers, rather than digits in a number. EDIT: In response to your comments, try this version to deal with longs: long arrayToLong(int[] arr) { StringBuilder s = new StringBuilder(); for (int i : arr) { s.append(i); } return Long.parseLong(s.toString()); } Edit 2: In response to your second comment: int[] longToIntArray(long l) { String s = String.valueOf(l); //expand number into a string String token; int[] result = new int[s.length() / 2]; for (int n = 0; n < s.length()/2; n ++) //loop through and split the string { token = s.substring(n*2, (n+2)*2); result[n] = Integer.parseInt(token); //fill the array with the numbers we parse from the sections } return result; } A: yeah you can write the function yourself int toInt(int[] array) { int result = 0; int offset = 1; for(int i = array.length - 1; i >= 0; i--) { result += array[i]*offset; offset *= 10; } return result; } I think the logic behind it is pretty straight forward. You just run through the array (last element first), and multiply the number with the right power of 10 "to put the number at the right spot". At the end you get the number returned.
{ "pile_set_name": "StackExchange" }
Q: Git subtree split + merge works poorly My code depends on files provided by an existing repository. As each file requires some work, I want to bring the files in as they become supported, rather than just adding all files at once. I would also like to track from and commit changes to upstream for the imported files. After some reading git subtree split seems promising and I followed the directions in Git Subtree only one file or directory with some modifications git remote add project _URL_ git fetch project then git branch project_master project/master git checkout project_master then git subtree split --squash --prefix=path_of_interest_in_project -b temp_branch then git checkout master git subtree merge --prefix=directory_destination_path temp_branch What happens is that git subtree merge seems to ignore the prefix flag and checks out the content of path_of_interest_in_project in the projects root folder. No squashing seems to be performed as the whole history of project/master is imported. Is this the correct behavior or a bug in Git? Are there better solutions to achieve what I want? A: I'm seeing something like what you describe, but it's not the subtree merge that is placing the subproject files in your project root, it's happens when you do a harmless old git pull with no specs. The git remote add you did now thinks that the subproject is a valid upstream peer, and is pulling from it. Resulting in the unexpected stuff landing here. My current work-around is to ensure I ONLY git pull from 'origin' from now on, but there is probably a setting in the tracking configs that would restore expected behaviour. I'm trying to find it...
{ "pile_set_name": "StackExchange" }
Q: for loops getting skipped + define function to re-use string splitting I am working on a simple program that takes a list of filenames and transforms it into an import file (.impex). The import file has three sections, each of which requires their own header. After printing the header to an output file, I use a for loop to iterate over the list of filenames and extract the necessary information from them to generate the import entry row. input a .csv containing filenames, like such: 3006419_3006420_ENG_FRONT.jpg desired output a .impex file formatted thusly: header-1 line-1 header-1 line-2 header-1 line-3 ;E3006419_3006420_FRONT_Image_Container; header-2 line-1 ;3006419_3006420D_ENG_FRONT-92x92;cloudfronturl;3006419_3006420D_ENG_FRONT.jpg;image/jpg;;;100Wx100H;E3006419_3006420_FRONT_Image_Container header-3 line-1 ;3006420;E3006419_3006420_FRONT_Image_Container Here is my code: file = open(sys.argv[1]) output = open('output.impex','w+') #define our output impex file #write variables and header for media container creation output.write('{}\n{}\n{}\n'.format('header-1 line-1','header-1 line-2','header-1 line-3')) #write media container creation impex rows for line in file: nameAndExtension = line.split('.') name = nameAndExtension[0] extension = nameAndExtension[1] elements = name.split('_') parentSKU = elements[0] childSKU = elements[1] lang = elements[2] angle = elements[3] output.write(";E" + parentSKU + "_" + childSKU + "_" + angle + '_Image_Container;\n') #write header for media creation output.write('{}\n'.format('header-2 line-1')) #write media creation impex rows for line in file: nameAndExtension = line.split('.') name = nameAndExtension[0] extension = nameAndExtension[1] elements = name.split('_') parentSKU = elements[0] childSKU = elements[1] lang = elements[2] angle = elements[3] output.write('{}\n'.format(';' + name + '-92x92;https://' + cloudfront + '.cloudfront.net/92x92/product-images/ACTIVE-HYBRIS/' + line + ';' + line + ';image/' + extension + ';;100Wx100H')) #write header for product association output.write('{}\n'.format('header-3 line-1')) for line in file: nameAndExtension = line.split('.') name = nameAndExtension[0] extension = nameAndExtension[1] elements = name.split('_') parentSKU = elements[0] childSKU = elements[1] lang = elements[2] angle = elements[3] output.write(childSKU + ";E" + parentSKU + "_" + childSKU + "_" + angle + '_Image_Container;\n') My output looks like this: header-1 line-1 header-1 line-2 header-1 line-3 ;E3006419_3006420_FRONT_Image_Container; ;E3006419_3006421_FRONT_Image_Container; ;E3006419_3006422_FRONT_Image_Container; ;E3006419_3006423_FRONT_Image_Container; ;E3006419_3006424_FRONT_Image_Container; header-2 line-1 header-3 line-1 So you can see it's doing the first for-loop correctly, but not writing anything for the second or third for loops. And I know it could be more nicely done with a clean function. A: Just change each for loop to open the file beforehand: file = open(sys.argv[1]) for line in file: nameAndExtension = line.split('.') # etc
{ "pile_set_name": "StackExchange" }
Q: The import org.springframework.web.bind.annotation.CrossOrigin cannot be resolved Não estou conseguindo importar a annotation @CrossOrigin. A ide não encontra o pacote necessário apesar de todas as outras annotations estarem funcionando normalmente. O erro que ocorre é esse: The import org.springframework.web.bind.annotation.CrossOrigin cannot be resolved Está faltando alguma dependência no meu maven? <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>java-property-utils</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.1.RELEASE</version> </dependency> <springframework.version>4.0.6.RELEASE</springframework.version> A: A anotação @CrossOrigin foi adicionada ao Spring na versão 4.2 e você está usando a versão 4.0.6.RELEASE. Mude sua versão para a mais recente do Spring 4.3.6.RELEASE e Isso resolverá o problema. Além disso, como você está usando o Spring Boot, as seguintes dependências não precisam ser declaradas no seu pom.xml já que elas são dependências do próprio Spring Boot: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency>
{ "pile_set_name": "StackExchange" }
Q: DKIM + EXIM + Dovecot for outgoing emails I am running exim+dovecot. I tried to generate a dkim key with opendkim but i got as a result that my dkim is not valid. Should i sign a DKIM signature with openssl or with opendkim? And what are the correct steps to correctly setup dkim with exim for outgoing emails? What is the correct setting in exim.conf? A: DKIM do not need signing at all. All that you need is a proper pair of RSA/DSA keys that can be generated by ssh-keygen bundled with preinstalled openssh. Leave passphrase empty: > ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): mydomain.tld Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in mydomain.tld. Your public key has been saved in mydomain.tld.pub. The key fingerprint is: SHA256:CD0n/Ut/GQgjYgKwONoj7FGXUJvdgyJt4FFczGZfqoE [email protected] The key's randomart image is: +---[RSA 2048]----+ |...++o+. | |....=o=*o . | |+ +oOXo=o= | |oo. +E.B =.o . | |ooo . S o . . | |.... . . o o | | . . . o | | . | | | +----[SHA256]-----+ Now we have two files: mydomain.tld and mydomain.tld.pub. Second file contains one long line where second field (marked as bold italic) is the public key you have to place into the zone record for your domain. ssh-rsa AAAAB3NzaC1yc.....9akAq8YqPJN [email protected] The first file is already ready to be used by the MTA. Just rename it to the mydomain.tld.key and copy it to the secure place and refer it from the MTA config. Keep in mind that MTA in general require private DKIM key to be readable by MTA user only so permissions should be set to the 600 instead of usual 644. DNS configuration is pretty well described in the number of howtos. And exim should be configured that way: begin transports xmit: driver = smtp dkim_domain = mydomain.tld dkim_selector = mydomaintld dkim_private_key = /path/to/the/mydomain.tld.key . . . . .
{ "pile_set_name": "StackExchange" }
Q: Possible ways to sort elements of set so that all elements of type x are next to each other. We have a set $A=\{a_1, a_2, ..., a_{2n}\}$ such that $|A|=2n$. We have subsets of $A$, $G = \{a_1, a_2, ..., a_n\}$, $B=\{a_{n+1}, a_{n+2}, ..., a_{2n}\}$. For the sake of this example, lets say $A$ is all the students in a classrom; $G$ are girls and $B$ are boys. There are $n$ girls and $n$ boys, such that in total there are $2n$ students. We are asked to line these students so that all girls are together forming a single block on the line. For example, if first letters of the alphabet are girls and last are boys, $wxyabcdefzuv$ In this line we have three boys, $wxy$, six girls, $abcdef$, and three other boys $efg$ lined up in a way that all girls are together. Of course in this example $n=6$. The question is: how many possible ways are there to sort the students for any value of $n$ so that girls are all next to each other on the line? What I've tried so far is to state that, when forming a line, I can either choose a boy or a girl. So I have $2n$ possibilities, $n$ for choosing a girl and $n$ for choosing a boy. If I choose a boy, my alternatives for the second choice are down to $n-1$ for the boys and still $n$ for the girls. If, on the other hand, I'd chosen a girl, my alternatives would have been $(n-1)!$, this is all the girls that I didnt choose in the first place. In either decisition, it seems I can choose $n!$ for the boys or $n!$ for the girls, so the ways to line them up should be $n! + n!=2n!$ But I then supposed $n=3$ and tested the possibilities and I think there are more than $3! + 3!=12$. What am I getting wrong? A: Treat the girls as a block. Then we have $n + 1$ objects to arrange, the $n$ boys and the block of $n$ girls. The objects can be arranged in $(n + 1)!$ ways. The girls can be arranged within the block in $n!$ ways. Hence, there are $(n + 1)!n!$ ways to arrange $n$ boys and $n$ girls in a row if all $n$ girls are together. To keep the numbers manageable, consider the case of two boys and two girls. Suppose the boys are Alan and Bruce and the girls are Claire and Debra. The block of girls must start in the first, second, or third position. The block of girls, Alan, and Bruce can be arranged in $3!$ ways. The girls can be arranged within the block in $2!$ ways, giving us $3!2! = 12$ possible arrangements. They are Alan, Bruce, Claire, Debra Bruce, Alan, Claire, Debra Alan, Bruce, Debra, Claire Bruce, Alan, Debra, Claire Alan, Claire, Debra, Bruce Bruce, Claire, Debra, Alan Alan, Debra, Claire, Bruce Bruce, Debra, Claire, Alan Claire, Debra, Alan, Bruce Claire, Debra, Bruce, Alan Debra, Claire, Alan, Bruce Debra, Claire, Bruce, Alan
{ "pile_set_name": "StackExchange" }
Q: Calling activity if the app is closed I need to create a fullscreen notification for alarm clock. I suppose it should be a simple activity, but I have troubles with calling it. If app is running, everything is ok, but if I manually ruine process of this app, the activity is not shown. It also is not shown if the screen is off. So, two questions. 1) How to call AlarmActivity if the app is closed? 2) How to call it if the screen is off? It's AlarmReceiver class: public class AlarmReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent alarmIntent = new Intent(); alarmIntent.setComponent(new ComponentName("com.enjoyalarm.enjoyalarm", "com.enjoyalarm.enjoyalarm.AlarmActivity")); alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(alarmIntent); } } AlarmActivity: public class AlarmActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm); Intent intent = getIntent(); } } If it's impossible, how to deal with my problem: fullscreen notification (with buttons, etc)? A: change your intent from Intent alarmIntent = new Intent(); to Intent alarmIntent = new Intent(context, AlarmActivity.class); and remove alarmIntent.setComponent(new ComponentName("com.enjoyalarm.enjoyalarm", "com.enjoyalarm.enjoyalarm.AlarmActivity"));
{ "pile_set_name": "StackExchange" }
Q: Display random div according to their data-role with jQuery Mobile I'm actually building a web application using jQuery Mobile. I have pages full of elements with specials data-role and I would like to randomly display some of these div on the homepage according to their data-role. Is it possble? If it is, does some of you know how to do that ? HTML : <div id="home" data-role="page" data-theme="b"> <div class="content" data-role="content"> </div></div> Elements of pages in my HTML file: <div data-role="place"> <h1 class="blue">Ballymastocker's beach</h1> <p>Ballymastocker, Fanad, Co. Donegal, Ireland. <br/> </p> <a href="#gmap"><img src="img/exploring/lakes-beaches/ballymastocker1.jpg" /></a> <a href="#" data-role="button" data-icon="arrow-r" data-iconpos="right">Read More</a><br/><br/> </div> <div data-role="place"> <h1 class="blue">Coral beach</h1> <p>Coral beach, Saint John's point, Co. Donegal, Ireland. <br/> </p> <a href="#gmap"><img src="img/exploring/lakes-beaches/coralbeach1.jpg" /></a> <a href="#" data-role="button" data-icon="arrow-r" data-iconpos="right">Read More</a><br/><br/> </div> <div data-role="place"> <h1 class="blue">Dunfanhagy's beach</h1> <p>Dunfanhagy, Co. Donegal, Ireland. <br/> </p> <a href="#gmap"><img src="img/exploring/lakes-beaches/dunfanhagy1.jpg" /></a> <a href="#" data-role="button" data-icon="arrow-r" data-iconpos="right">Read More</a><br/><br/> </div> I used the Js script as you provide me below : $( "div[data-role='place']" ).each(function( home ) { if ( Math.random() < 0.5 ) $( this ).hide(); }); But nothing happend. Some one know why ? Check it out here A: $( "div[data-role]" ).each(function( index ) { if ( Math.random() < 0.5 ) $( this ).hide(); });
{ "pile_set_name": "StackExchange" }
Q: PHP static class Array[] operator? I need to implement the square brackets (array operator) in a static PHP class. The main goal is to have class calls like this at the end : MyStaticClass[ $something ] = $somethingElse ; $SomeVar = MyStaticClass[ $something ] ; I know that this is an heresy, but I really need it... Any idea ? I'm wondering if a static call to such an operator is possible, since I found nothing on the web. Thanks for every help :) A: [] can not be overloaded only variable and methods Sample Class class MyStaticClass { static public $somthing = array("somthingElse"=>"Hello Benj") ; } Calling it directly var_dump(MyStaticClass::$somthing["somthingElse"]); You can also use $MyStaticClass = MyStaticClass::$somthing ; var_dump($MyStaticClass["somthingElse"]); Both of them would Output string 'Hello Benj' (length=10) In PHP 5.4 function MyStaticClass() { return MyStaticClass::$somthing ; } var_dump(MyStaticClass()["somthingElse"]);
{ "pile_set_name": "StackExchange" }
Q: A split infinitive de-emphasises the verb? At about 60%-way down the page http://chronicle.com/article/50-Years-of-Stupid-Grammar/25497: ...But what interests me here is the descriptive claim about stress on the adverb. It is completely wrong. Tucking the adverb in before the verb actually de-emphasizes the adverb, so a sentence like "The dean's statements tend to completely polarize the faculty" places the stress on polarizing the faculty. The way to stress the completeness of the polarization would be to write, "The dean's statements tend to polarize the faculty completely." I don't perceive the differences; what's the lesson here? Don't these two sentences convey the same meaning? Either way, isn't the polarisation of the faculty complete? A: Pullum is not speaking of meaning but of emphasis—what is the focal term in the sentence?—so to understand Pullum's argument you must read with your ears, not your eyes. The strictly verbal meaning of a sentence will have very different pragmatic meanings in different discourse situations; and writers sensitive to the discourse situation will frame their sentences so their syntax elicits the prosodic emphasis which their situations require. In Pullum's example, for instance, it may be that the faculty as a whole previously took only a dispassionate and scholarly attitude toward the issue which the Dean addressed, and the Dean’s statements aroused their ideological and professional concerns, dividing them into opposed camps. In that case, the ‘new information’ in the sentence, the key point it seeks to convey, resides in polarized, and the ‘completeness’ of the polarization is of secondary interest. On the other hand, it may be the case that there was some degree of polarization before the Dean weighed in—perhaps there was a small number of professors on each side of the issue, but most faculty were indifferent—and that the effect of his statement was to compel every professor to take a stand on the issue. In that case, polarization is ‘old information’ and the ‘new information’ resides in completely. Pullum’s argument speaks to the different ways a sentence may be organized to realize different emphases. Other things being equal, the strongest position in an English sentence, the position where ‘new information’ is placed, is the right end of the main clause. Placing the single adverb after the verb (and its complement—English syntax dislikes interrupting that collocation) provides a stress point further to the right. The prosodic contour of the sentence—the rise and fall of stress- and pitch-emphasis—will rise toward a peak on completely. ° ′ ′ ° ′ ° ° ° ′ ° ° ° ″ ° The Dean’s statements polarize the faculty completely. In contrast, placing the adverb completely before the verb puts the verb (with its complement) as far to the right as it can go, so it occupies the more emphatic position. ° ′ ′ ° ° ′ ° ″ ° ° ° ′ ° ° The Dean’s statements completely polarize the faculty. The adverb is weakened even further when it interrupts a to + infinitive construction, because the ‘local’ effect—the need for emphasis to rise from unstressed to toward the infinitive it marks—puts the adverb is a destressed position and reinforces the ‘global’ sentence-long prosodic contour. ° ′ ′ ° ′ ° ° ° ° ″ ° ° ° ′ ° ° The Dean’s statements tend to completely polarize the faculty.
{ "pile_set_name": "StackExchange" }
Q: Autolayout constraints and child view controller I have two view controllers, parent and child. So in the viewDidLoad method I do the following: ChildViewController* childViewController = [[ChildViewController alloc] init]; [self addChildViewController:childViewController]; // ChildViewController sets his own constraints in viewDidLoad [self.view addSubview:childViewController.view]; [childViewController didMoveToParentViewController:self]; // // setup constraints to expand childViewController.view to // fill the size of parent view controller // So basically what happens is that updateViewConstraints is called on ChildViewController before parent controller constraints apply, so in fact self.view.frame == CGRectZero, exactly the same as I specified in custom loadView method in ChildViewController. translatesAutoresizingMaskIntoConstraints all set to NO for all views. What's the proper way to setup constraints in this case so ChildViewController updates his constraints after parent? Current log from both controllers is pretty frustrating, I do not understand how updateViewConstraints can be called before viewWillLayoutSubviews: App[47933:c07] ChildViewController::updateViewConstraints. RECT: {{0, 0}, {0, 0}} App[47933:c07] ParentViewController::updateViewConstraints App[47933:c07] ChildViewController:viewWillLayoutSubviews. RECT: {{0, 0}, {984, 454}} App[47933:c07] ChildViewController:viewDidLayoutSubviews. RECT: {{0, 0}, {984, 454}} A: I have a similar situation where I add a child controller to a visible controller (a popup). I define the child view controller in interface builder. It's viewDidLoad method just calls setTranslatesAutoresizingMaskIntoConstraints:NO Then I define this method on the child controller which takes a UIViewController parameter, which is the parent. This method adds itself to the given parent view controller and defines its own constraints: - (void) addPopupToController:(UIViewController *)parent { UIView *view = [self view]; [self willMoveToParentViewController:parent]; [parent addChildViewController:self]; [parent.view addSubview:view]; [self didMoveToParentViewController:parent]; NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[view]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]; [parent.view addConstraints:horizontalConstraints]; NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[view]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]; [parent.view addConstraints:verticalConstraints]; } then inside the parent UIViewController (the one which is already displayed), when I want to display my child popup view controller it calls: PopUpNotificationViewController *popup = [[self storyboard] instantiateViewControllerWithIdentifier:@"NotificationPopup"]; [popup addPopupToController:self]; You can define whatever constraints you want on the child controller's view when adding it to the parent controller's view. A: You can add constraints right after invoke of addSubview: , don't forget to set translatesAutoresizingMaskIntoConstraints to false Here is a code snippet of adding and hiding child view controller with constraints (inspired by apple guide) Display private func display(contentController content : UIViewController) { self.addChildViewController(content) content.view.translatesAutoresizingMaskIntoConstraints = false self.containerView.addSubview(content.view) content.didMove(toParentViewController: self) containerView.addConstraints([ NSLayoutConstraint(item: content.view, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: content.view, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: 0), NSLayoutConstraint(item: content.view, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: content.view, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1, constant: 0) ]) } Hide private func hide(contentController content : UIViewController) { content.willMove(toParentViewController: nil) content.view.removeFromSuperview() content.removeFromParentViewController() } A: According to the following link, I moved constraints creation to viewWillLayoutSubviews, this is the place where view bounds are set properly. I feel this answer misses explanation on why Child view controller's updateViewConstraints called before parent view controller, or maybe it's just some bug in my code, but this workaround solves the problem...
{ "pile_set_name": "StackExchange" }
Q: USA: Do 911/PD phone operators have a 'duty to rescue'? As I understand it: 'duty to rescue' does not generally exist for regular citizens in the USA. (Some exceptions apply!) Let's say I'm in Europe and I call the general inquiry phone number of a local (city) police department in the United States to report a suicidal individual local to them. Do any of the following entities have a 'duty to rescue' in the following situations?: Police officers answering the phone. Non-police officer employees answering phones at a (local?) PD. The dispatch operators that #1 and #2 connect me to. The dispatch operators I get when I dial 911 while being in the USA myself. The legal entities of either the police department or the emergency services dispatch (or other involved party?) Note: I have tried to keep this question as narrow/focused as possible. Let me know if there's any issues with the question. I'm not familiar with law all that much. A: No More generally, government agencies have no duty to protect. In the cases DeShaney vs. Winnebago and Town of Castle Rock vs. Gonzales, the supreme court has ruled that police agencies are not obligated to provide protection of citizens. In other words, police are well within their rights to pick and choose when to intervene to protect the lives and property of others — even when a threat is apparent. In the united-kingdom , the situation is the same with the relevant case being Hill v Chief Constable of West Yorkshire, a precedent followed in australia. However, the police, fire fighters, ambulance officers etc. do owe the same common law duty of care as everyone else where such a duty exists if and when they do choose to act, unless specifically exempted by law. For example, they owe a duty to people in custody or innocent bystanders.
{ "pile_set_name": "StackExchange" }
Q: Mule 4: DW2 - Array of objects, distinct by object field I want an array of objects that are distinct by a certain field. The array is already sorted by this field so identifying which fields to remove should follow this: the value of the previous field should be different from current value of the field. For example, this array [{A:'1',B:'1'},{A:'2',B:'2'},{A:'2',B:'3'}] should transform to [{A:'1',B:'1'},{A:'2',B:'2'}] I tried the following: %dw 2.0 output application/json var payload=[{A:'1',B:'1'},{A:'2',B:'2'},{A:'2',B:'3'}] --- (payload map ( (a,i) -> ( (a) if payload[i-1].A != $.A ) )) but it does not work. If I do not use the current item ($) then it works like this (a,i) -> ( (a) if payload[i-1].A != '2' ) But I need the current and previous items to be present to determine that current item is new (not equal for previous one). A: You should be able to ignore the fact that your array is sorted: you don't need the convenience of knowing the current value is distinct from the previous. You can use distinctBy instead: %dw 2.0 output application/json var arr = [{A:'1',B:'1'},{A:'2',B:'2'},{A:'2',B:'3'}] --- arr distinctBy $.A Returns [ { "A": "1", "B": "1" }, { "A": "2", "B": "2" } ] Here are the docs for distinctBy if you're interested: https://docs.mulesoft.com/mule-runtime/4.1/dw-core-functions-distinctby
{ "pile_set_name": "StackExchange" }
Q: "undefined" added into output in JavaScript/HTML5 I am new to HTML5 and JavaScript, so this may be a stupid question, but when I attempt to execute this code it adds undefined before the morse answer. I haven't the slightest idea why, and a fairly extensive scrounging of the internet yielded no results. I think the issue may lie in printing the variable output to the HTML, but I have no idea what is making it add undefined. <html> <head> <title>Morse Code</title> <script type="text/javascript"> function whole(){ function convert(input){ for (var i=0; i<input.length; i++){ if (input.charAt(i)=="a"||input.charAt(i)=="A"){ output=output+".-/";} else if (input.charAt(i)=="b"||input.charAt(i)=="B"){ output=output+"-.../";} else if (input.charAt(i)=="c"||input.charAt(i)=="C"){ output=output+"-.-./";} else if (input.charAt(i)=="d"||input.charAt(i)=="D"){ output=output+"-../";} else if (input.charAt(i)=="e"||input.charAt(i)=="E"){ output=output+"./";} else if (input.charAt(i)=="f"||input.charAt(i)=="F"){ output=output+"..-./";} else if (input.charAt(i)=="g"||input.charAt(i)=="G"){ output=output+"--./";} else if (input.charAt(i)=="h"||input.charAt(i)=="H"){ output=output+"..../";} else if (input.charAt(i)=="i"||input.charAt(i)=="I"){ output=output+"../";} else if (input.charAt(i)=="j"||input.charAt(i)=="J"){ output=output+".---/";} else if (input.charAt(i)=="k"||input.charAt(i)=="K"){ output=output+"-.-/";} else if (input.charAt(i)=="l"||input.charAt(i)=="L"){ output=output+".-../";} else if (input.charAt(i)=="m"||input.charAt(i)=="M"){ output=output+"--/";} else if (input.charAt(i)=="n"||input.charAt(i)=="N"){ output=output+"-./";} else if (input.charAt(i)=="o"||input.charAt(i)=="O"){ output=output+"---/";} else if (input.charAt(i)=="p"||input.charAt(i)=="P"){ output=output+".--./";} else if (input.charAt(i)=="q"||input.charAt(i)=="Q"){ output=output+"--.-/";} else if (input.charAt(i)=="r"||input.charAt(i)=="R"){ output=output+".-./";} else if (input.charAt(i)=="s"||input.charAt(i)=="S"){ output=output+".../";} else if (input.charAt(i)=="t"||input.charAt(i)=="T"){ output=output+"-/";} else if (input.charAt(i)=="u"||input.charAt(i)=="U"){ output=output+"..-/";} else if (input.charAt(i)=="v"||input.charAt(i)=="V"){ output=output+"...-/";} else if (input.charAt(i)=="w"||input.charAt(i)=="W"){ output=output+".--/";} else if (input.charAt(i)=="x"||input.charAt(i)=="X"){ output=output+"-..-/";} else if (input.charAt(i)=="y"||input.charAt(i)=="Y"){ output=output+"-.--/";} else if (input.charAt(i)=="z"||input.charAt(i)=="Z"){ output=output+"--../";} else if (input.charAt(i)=="1"){ output=output+".----/";} else if (input.charAt(i)=="2"){ output=output+"..---/";} else if (input.charAt(i)=="3"){ output=output+"...--/";} else if (input.charAt(i)=="4"){ output=output+"....-/";} else if (input.charAt(i)=="5"){ output=output+"...../";} else if (input.charAt(i)=="6"){ output=output+"-..../";} else if (input.charAt(i)=="7"){ output=output+"--.../";} else if (input.charAt(i)=="8"){ output=output+"---../";} else if (input.charAt(i)=="9"){ output=output+"----./";} else if (input.charAt(i)=="0"){ output=output+"-----/";} else if (input.charAt(i)==" "){ output=output+"//";} else{output=output;} } document.getElementById('results').innerHTML=output; } var start = prompt ("Enter your sentence:"); convert(start); var output = document.getElementById('results').innerHTML; } </script> <style> body{ text-align:center; } p{ font-size:23px; } </style> </head> <body> <h1>Clicka de button below to do some morsey codes.</h1> <button onclick="whole()">Try it out!</button> <p id="results">Your sentence will appear here</p> </body> </html> A: You need to initialize output before calling convert(). Note that else{output=output;} is a pointless operation.
{ "pile_set_name": "StackExchange" }
Q: Reading from a Serial Port with Ruby I'm trying to use ruby to do a simple read + write operation to a serial port. This is the code I've got so far. I'm using the serialport gem. require 'rubygems' require 'serialport' ser = SerialPort.new("/dev/ttyACM0", 9600, 8, 1, SerialPort::NONE) ser.write "ab\r\n" puts ser.read But the script hangs when it is run. A: I had the problem to. It's because using ser.read tells Ruby to keep reading forever and Ruby never stops reading and thus hangs the script. The solution is to only read a particular amount of characters. So for example: ser.readline(5) A: To echo what user968243 said, that ser.read call is going to wait for EOF. If your device is not sending EOF, you will wait forever. You can read only a certain number of characters as suggested. Your device may be ending every response with an end of line character. Try reading up to the next carriage return: response = ser.readline("\r") response.chomp! print "#{response}\n"
{ "pile_set_name": "StackExchange" }
Q: How to make sure that you don't start a service twice android Is there a way to check that the service is not already running before starting it? If it could be in the onCreate() of the service it will be even better, Thank you! A: You can't start a service twice, it will remain running if you try to start it again. Link to the Android docs. A: fix it with a boolean/flag in the service. (A service can only be started once)
{ "pile_set_name": "StackExchange" }
Q: Get content with RegEx between braces and a keyword I'm just facing with a problem, what I cannot solve it. I tried to build up my regex pattern which has to be get the content between braces but if only an exact keyword is stands before the open brace. (?<=(?:\testlist\b)|(?:){)((.*?)(?=})) The whole content itself may contains many blocks (which are always beginning with a keyword), like: nodelist{ ... ... } testlist { ... ... } With the above pattern I can get each of node contents but I would like to specify in regex that only 'testlist' node's content has to be grabbed. (Position of braces are different by design because I would like to get the content even if the braces are in the same line as the keyword or no matter, how many line breaks contains after it) Does anyone any idea, how can I achieve this? Thank you! A: You can use a regex like (?s)testlist\s*{(.*?)} This matches testlist literally, followed by spaces and a literal opening brace. (.*?) captures everything until the next closing brace. Usage: PS C:\Users\greg> 'nodelist{ >> ... >> ... >> } >> testlist >> { >> ... >> ... >> }' -match '(?s)testlist\s*{(.*?)}' True PS C:\Users\greg> $Matches.0 testlist { ... ... } PS C:\Users\greg> $Matches.1 ... ... PS C:\Users\greg> If you want a full match instead of a capture group: PS C:\Users\greg> 'nodelist{ >> ... >> ... >> } >> testlist >> { >> ... >> ... >> }' -match '(?s)(?<=testlist\s*{).*?(?=})' True PS C:\Users\greg> $Matches.0 ... ... PS C:\Users\greg>
{ "pile_set_name": "StackExchange" }
Q: Why jQuery rounds value? Using ajax i request a authenticationID like this: This is wrong because the real HTTP-Transfer is this: (By the way: response-type is "application/json;charset=UTF-8") I see a clash between -1369082024195183657 and -1369082024195183600 How to prevent the rounding or is it a bug? A: jQuery tries to parse the HTTP response as integer based on the JSON content-type. > JSON.parse("-1369082024195183657") -1369082024195183600 You can override it by telling jQuery you expect a string by setting the dataType property in $.ajax configuration: $.ajax({ dataType : "text", url : "rest/Registration", success : function(data){ // data should be "-1369082024195183657" } }) I guess you don't need to do any arithmetic operations on an authenticationID token, so you can just keep it as a string. A: Yes it is a bug. The Server returns illegal JSON! Created report: https://github.com/FasterXML/jackson-core/issues/291
{ "pile_set_name": "StackExchange" }
Q: adding comments using php and html I was wondering if there were any kind people out there who would be able to help me with my php conundrum! Im very very new to php and I can't quite understand how to add a comment section that is functional. I have made a database table (named 'comments') to store all of the comments that users will submit. I am not sure of these things: 1. how to connect the comment section (on php page - home.php) to my database table (comments) 2. how to make the comments that people post be posted onto the the same page - home.php I have done something wrong as now when I type in the URL this error comes up Parse error: syntax error, unexpected '{', expecting '(' in .../home.php on line 34 Anyway I hope someone can help me! Thanks <?php session_start(); if (!isset($_SESSION['logged'])){ $_SESSION = array(); session_destroy(); header('location: home_start.php'); //your login form require_once("functions.php"); include_once("home_start.php"); require_once("db_connect.php"); } //EXISTING DATABASE CONNECTION CODE //if (!$db_server){ //die("Unable to connect to MySQL: " . mysqli_connect_error($db_server)); }else{ $ db_status = "not connected"; //NEW SUBMISSION HANDLING CODE HERE //if(trim($_POST['submit']) == "Submit"){ //}//EXISTING CODE (to create the options list) HERE... //} require_once('recaptcha/recaptchalib.php'); $privatekey = " 6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); $message = ""; if (!$resp->is_valid) { $message = "The reCAPTCHA wasn't entered correctly. Go back and try it again (reCAPTCHA said: " . $resp->error . ")"; } else { // ADD YOUR CODE HERE to handle a successful ReCAPTCHA submission // e.g. Validate the data $unsafe_name = $_POST['fullname']; } $message .= "Thanks for your input $unsafe_name !"; echo $message; if { $bedrooms = $_POST['year']; $bedrooms = clean_string($db_server, $year); $comment = clean_string($db_server, $_POST['comment']); else ($comment != "") { $query2 = "INSERT INTO comments (comment) VALUES ('$comment')"; mysqli_query($db_server, $query2) or die("Insert failed: " . mysqli_error($db_server)); $message = "Thanks for your comment"; } $query3 = "SELECT * FROM comments"; $result3 = mysqli_query($db_server, $query3); while($array = mysqli_fetch_array($result3)){ $comments = date('d/m/Y', strtotime($array['commDate'])) . "<p>" . $array['comment'] . "</p><br/>"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="home.css" rel="stylesheet" type="text/css"/> <title>Home</title> </head> <body> <div id="middle"> <h2><strong>HELLO!</strong></h2> <h2>Welcome to <strong>Cosy Cribs</strong> website!</h2> <p>This website combines all the possible lettings available to YOU from the most prefered letting companies in the great city of Leeds!</p> <p>It was recognised that when students attempt to let a house for the next year, there were far too many different websites and companies visit; making the whole ordeal of finding a house more stressful then needs be!</p> <p>We, at <strong>Cosy Cribs</strong>, decided that your lives needed to be made easier, and so we announce a website that provides you with all of the lettings from these different companies - all on one website - and links to the house you like.</p> <h2>ENJOY!</h2> </div> <form id="comments" action="home.php" method="post"> <select name="comments"> </select> <h1>Do you have a comment on preferred company or number of bedrooms?</h1> Comment: <textarea rows="2" cols="30" name="comment"></textarea> <?php echo $recaptcha_form; ?> <input type="submit" id="submit" name="submit" value="Submit form" /> </form> </body> </html> A: Your below statement is syntactically incorrect, if { $bedrooms = $_POST['year']; $bedrooms = clean_string($db_server, $year); $comment = clean_string($db_server, $_POST['comment']); else ($comment != "") { Should be, if (isset($comment) && $comment == '') { $bedrooms = $_POST['year']; $bedrooms = clean_string($db_server, $year); $comment = clean_string($db_server, $_POST['comment']); } else {
{ "pile_set_name": "StackExchange" }
Q: jQuery cookie from data-attributes using JSON string I have a series of divs that are toggled with Bootstrap's toggle jQuery. I need to create a cookie that remembers and preserves the toggled state of the divs. I'm attempting to set the toggled states to a json string (as recommended by here) in order to only have one cookie. I've run into a snag that I can't seem to get passed. The json array is getting created, but it's always one behind, so to speak. The jQuery: $('#style-widget [data-toggle="collapse"]').on('click', function() { var check_open_divs = []; var toggled_div = $('#style-widget [data-toggle="collapse"]:not(.collapsed)'); // PROBLEM BELOW ▼ -- on initial click the data attribute is not going into the array // on second click (when the class 'toggled' is being added by Bootstrap code) the // data attribute is added to the array $(toggled_div).each(function() { check_open_divs.push($(this).attr('data-target')); }); // stringify array object check_open_divs = JSON.stringify(check_open_divs); $.cookie('bg-noise-div-state', check_open_divs, {expires:365, path: '/'}); }); The (simplified) HTML: <div id="style-widget"> <!-- div one --> <p title="click to toggle" class="collapsed" data-toggle="collapse" data-target="#background-noise-wrap">Background Noise</p> <div id="background-noise-wrap" class="collapse"> <!-- content here, removed for brevity --> </div> <!-- div two --> <p title="click to toggle" class="collapsed" data-toggle="collapse" data-target="#extra-header-selection-wrap">Extra Header</p> <div id="extra-header-selection-wrap" class="collapse"> <div class="selection-wrap first"> <!-- content here, removed for brevity --> </div> </div> <!-- div three --> <p title="click to toggle" class="collapsed" data-toggle="collapse" data-target="#wide-or-boxed-wrap">Wide or Boxed?</p> <div id="wide-or-boxed-wrap" class="collapse"> <p>Header &amp; Footer</p> <div id="wide-boxed-selection-wrap"> <!-- content here, removed for brevity --> </div> </div> </div> By default the divs are collapsed, which is why they initially have the .collapsed class. In pseudo-code thinking: 1. create function on click of collapse toggle (the p tag) 2. select divs that are not collapsed 3. save these to a json string, then cookie 4. check for this cookie on page load to persist the toggled states Much obliged for any insights. A: You need to encapsulate the cookie creation into a function and then call the function after toggling the class. $('[data-toggle="collapse"]').on('click', function() { // toggle your div class here $(this).toggleClass('expanded collapsed'); // call function to store value storeState(); }); function storeState() { var check_open_divs = []; var toggled_div = $('#style-widget [data-toggle="collapse"]:not(.collapsed)'); $(toggled_div).each(function() { check_open_divs.push($(this).attr('data-target')); }); // stringify array object check_open_divs = JSON.stringify(check_open_divs); console.log(check_open_divs); $.cookie('bg-noise-div-state', check_open_divs, {expires:365, path: '/'}); }
{ "pile_set_name": "StackExchange" }
Q: is "と” always needed for when saying "with?" can I say しごとがんばってね for saying have a nice day at work? do I need the particle と to make it "with work" しごととがんばってね A: Japanese がんばる is a transitive verb that means "to work hard on/with ~". That is to say, you have to say しごとをがんばってね if you don't want to omit particles, but しごとがんばってね is fine in casual conversations, too. しごととがんばってね is ungrammatical. In general, と meaning with cannot be easily omitted like が/は/を. Being able to omit と freely would obviously introduce a lot of confusion and ambiguity. For example, 彼【かれ】映画【えいが】見た【みた】 will always mean "He watched a movie" rather than "I watched a movie with him."
{ "pile_set_name": "StackExchange" }
Q: Fetch Max from a date column grouped by a particular field I have a table similar to this: LogId RefId Entered ================================== 1 1 2010-12-01 2 1 2010-12-04 3 2 2010-12-01 4 2 2010-12-06 5 3 2010-12-01 6 1 2010-12-10 7 3 2010-12-05 8 4 2010-12-01 Here, LogId is unique; For each RefId, there are multiple entries with timestamp. What I want to extract is LogId for each latest RefId. I tried solutions from this link:http://stackoverflow.com/questions/121387/sql-fetch-the-row-which-has-the-max-value-for-a-column. But, it returns multiple rows with same RefId. The LogId as well as RefId should be unique. Can someone help me with this? Thanks Vamyip A: You need to use a subquery that extracts the latest Entered value for each RefId, and then join your source table to this on RefId, Entered: SELECT DISTINCT MyTable.LogId, MyTable.Entered FROM MyTable INNER JOIN (SELECT RefId, MAX(Entered) as Entered FROM MyTable GROUP BY RefId) Latest ON MyTable.RefId = Latest.RefId AND MyTable.Entered = Latest.Entered
{ "pile_set_name": "StackExchange" }
Q: Programming R : how to put multi-plots in a same coordinates? I don't know how to put four plots(y=3^x, y=(1/3)^x, y=(3/2)^x, y=e^x) into a same coordinates. I typed: a = function(x){y=3^x} b = function{y=(1/3)^x} c = function{y=(3/2)^x} d = function(x){exp(x)} plot(-4:4, a, b, c, d) but it did not work. How can I fix this? A: Use the add=TRUE option, Also you have your second and third functions written wrong (they take no parameters). So you have: a = function(x){y=3^x} b = function(x){y=(1/3)^x} c = function(x){y=(3/2)^x} d = function(x){exp(x)} and you plot using: plot(a , -4 , 4) plot(b , -4 , 4, add=TRUE) plot(c , -4 , 4, add=TRUE) plot(d , -4 , 4, add=TRUE)
{ "pile_set_name": "StackExchange" }
Q: What did Jesus mean by 'take up your cross and follow me'? What exactly did Jesus mean when He said, “Take up your cross and follow Me” (Matthew 16:24; Mark 8:34; Luke 9:23). Does it mean we should carry our burdens in life, or what? A: What Jesus means is to crucify our "old man" ie. our flesh. Paul talks about this. That ye put off concerning the former conversation the old man, which is corrupt according to the deceitful lusts; Eph 4:22 (KJV) We are to crucify (put off) the old man. A: following is what John H. Yoder had to say about "What is our cross?" i have edited, but see no reason to rewrite it. it comes from "The way of peace in a world of war" and "Living the disarmed life". in a sense of the word, think of the cross as a formidable spiritual weapon. Following the example of Jesus himself, the first Christians and the writers of the New Testament were quick to see in the book of the prophet Isaiah a description of the innocent sufferings of Christ. They read there: "He was counted among evildoers. For our welfare he was chastised. Mistreated, he bore it humbly, without complaint, silent as a sheep led to the slaughter, silent as a ewe before the shearers. They did away with him unjustly though He was guilty of no violence and had not spoken one false word. " (Is 53:4-9) In all ages these words concerning the one called the "servant of the Lord" have been beloved by Christians for the portrait they paint of our crucified master. We find these same words echoing in the New Testament, not only because they are beautiful words to describe Christ and his sacrifice on behalf of sinful humanity, but also because they constitute a call to the Christian to do likewise. There we read: "If you have done right and suffer for it, your endurance is worthwhile in the sight of God. To this you were called, because Christ suffered on your behalf, and left you an example; it is for you to follow in his steps. He committed no sin, he was guilty of no falsehood; when he suffered he uttered no threat." (1 Pe 2:20-22) The innocent, silent uncomplaining suffering of Christ is, in this teaching of Peter, not only an act of Christ on our behalf from which we benefit; it is also an example of Christ for our instruction which we are to follow. This portrait of Christ is to be painted again on the ordinary canvas of our lives. Had not Jesus himself said that those who would follow him must deny themselves and take up their cross? What then does it mean for the Christian to bear a cross? We meet in this world some suffering which is our own fault; we bring accidents upon ourselves by our carelessness, our punishment by our offenses. This is not "bearing a cross"; as Peter wrote, there is no merit in taking punishment for having done wrong. "What credit is it," he asks, "if when you do wrong and are beaten for it, you take it patiently? We also sometimes suffer in ways we cannot understand, as from an unexpected or unexplained illness or catastrophe which strikes us. Such suffering the Christian can bear, trusting in God's supporting presence and learning to depend more fully and more joyfully in God's sustaining grace. Yet this is not what Jesus was talking about when he predicted suffering for his disciples. The cross of Christ was the price of his obedience to God amid a rebellious world; it was suffering for having done right, for loving where others hated, for representing in the flesh the forgiveness and the righteousness of God among humanity, which was both less forgiving and less righteous. The cross of Christ was God's overcoming evil with good. The cross of the Christian is then no different; it is the price of our obedience to God's love toward all others in a world ruled by hate. Such unflinching love for friend and foe alike will mean hostility and suffering for us, as it did for him. ... When the apostle Paul says that "the weapons we wield are not merely human" or "not those of the world" (2 Cor 10:4), most of us, accustomed to thinking on the "merely human" level, would have expected him to say, "not human but spiritual," or "not of this world but of another world." But he says, "not merely human, but divinely potent." This is the "almighty meekness" of our reigning Lord. When the Christian whom God has disarmed lays aside carnal weapons, it is not, in the last analysis, because they are too dangerous, but because they are too weak. The believers in Jesus as Lord direct their lives toward the day when all creation will praise, not kings and chancellors, but the Lamb that was slain as worthy to receive blessing and honor and glory and power.
{ "pile_set_name": "StackExchange" }
Q: can one order the elements of a finite group such that their product is equal to the first element in the list? This question is inspired by this question. Given a finite group $G$, is there an ordering $G=\{a_1, \dots, a_n\}$ of its elements such that the product of all group elements in that specified order equals the first element, i.e $a_1\cdot\dots\cdot a_n=a_1$. Equivalently, can we multiply all but one element of the group in such a way to obtain the unit $1$. Trivial cases (probably not very helpful): $G$ is abelian (just define $a_1$ to be the product of all elements). $G$ has no element of order $2$ ($a_1=1$ and pair the elements with their inverses in the list). $G$ has a unique element of order $2$ (set $a_1$ to be that element and pair the others with their inverses). Slightly less trivial cases (still probably not that useful) $G=S_3$ (symmetric group) if $a=(12), b=(23)$ are the standard generators, then $(aba)=(aba)(a)(ba)(b)(ab)1$ $G$ with $|G|>6$ has exactly two or three elements of order $2$: Consider the conjugation action of $G$ on the set $X$ of elements of order $2$. If this action is non-trivial, then for at least one $x\in X$ the centralizer of $x$ has at most $\frac{|G|}{2}$ elements, hence we find a $g\in G\setminus X$ with $y:= gxg^{-1}\neq x$; then the product $ygxg^{-1}$ followed by all the elements of order $\geq3$ paired with their inverses is trivial. If the action is trivial, then $X$ lies in the center and is thus an abelian subgroup (because the product of commuting elements of order $2$ has order $\leq 2$); hence we can first multiply all elements of $X$, followed by all other elements paired with their inverses. A: We will prove a bit stronger result: Given an element $x_0$ of order two, we can order the elements in the group such that one of the following cases occur: The product is trivial, and you can set $a_1=1$. The product is equal to $x_0$ and the first element is $x_0$. Proof: Let $X$ be the set of elements of order two and set $$X_0=\{ x\in X\setminus \{x_0\}: \ xx_0=x_0x\}$$ and $$X_1=\{ x\in X: \ xx_0\ne x_0x\}.$$ Then we have the disjoint union $$ X=\{x_0\}\cup X_0\cup X_1$$ Consider the orbits $\{x,x_0x\}$ in $X_0$ corresponding to (left) multiplication by $x_0$, and the orbits $\{x, x_0 x x_0\}$ in $X_1$ corresponding to the adjunction with $x_0$. Clearly all orbits have cardinality two. For each pair of orbits $\{\{x,x_0 x\}, \{ y, x_0 y\}\}$ in $X_0$ consider the product $$ x\cdot (x_0 x)\cdot y \cdot (x_0 y)= x_0 \cdot x_0=1,$$ and for each orbit $\{ x, x_0 x x_0\}$ in $X_1$ set $g= x_0 x$ (so $g^{-1}=x x_0=x_0(x_0 x x_0)$) and consider the product $$ g \cdot x \cdot g^{-1}\cdot (x_0 x x_0)= x_0 \cdot x_0=1.$$ Note that the sets $\{ g, g^{-1}\}$ are disjoint, since the orbits are disjoint. So, if there is an odd number of orbits in $X_0$, set $a_1=1$, then take one orbit $\{ x,x_0 x\}$ in $X_0$, and consider the product $$ x_0 \cdot x \cdot (x_0 x)=1.$$ Then form the product of all elements in $G$ multiplying by the products corresponding to pairs of orbits in $X_0$, then by the products corresponding to orbits in $X_1$, and finally multiplying by pairs $\{ g, g^{-1}\}$ of elements in $G\setminus X$ that have not been used in any of the previous products. Then the product of all elements is trivial. If there is an even number of orbits in $X_0$, then set $a_1=x_0$ and multiply as before by the remaining elements. Then the product of all the elements is $x_0$, which is the first element.
{ "pile_set_name": "StackExchange" }
Q: How to post product with image on REST API? I'm trying to post an image to a product, but on post I dont know where exactly to put it. Should I put on custom_attributes as when I get it on GET ? Didn't have success, even using image, small_image and thumbnail and the same link image as one that I added manually. Or should I use other way like Media Gallery Entries? If so could I get an example? because on documentation they only tell me things like "string" and don't know which are the possibilities. Thanks. A: request url : magentourl/index.php/rest/V1/products/sku/media use this : { "entry": { "media_type": "image", "label": "Image", "disabled": false, "types": [ "image", "small_image", "thumbnail" ], "file": "string", "content": { "base64_encoded_data": "basec64encoded", "type": "image/png", "name": "new_image2.png" } } }
{ "pile_set_name": "StackExchange" }
Q: Informix - Aggregating list of values into comma-delimited string Is there a way to convert a list of values into a comma-delimited string in Informix? For example, I have the following query as a subselect: SELECT [State] From States I would like to convert all the values from that select into a comma-separated list. Can I do that in informix? A: I think the answer you need is given in these questions: SO 715350, SO 489081. It shows how to create and use a GROUP_CONCAT() aggregate that will do exactly what you want. The functionality is otherwise not available - that is, you have to add it to Informix, but it can (fairly) easily be added.
{ "pile_set_name": "StackExchange" }
Q: Accessing Parameters From A Polymorphic Enclosing Function Inside A Polymorphic Local Function I'm attempting to make a function polymorphic but I am running into the following problem. The following function compiles: libraryDependencies += "org.spire-math" %% "spire" % "0.10.1" import spire.math._ import spire.implicits._ def foo(a : Int, b : Int) : Int = { def bar(c : Int, d :Int) : Int = { c * b } a * bar(1,2) } The basic idea here is one of local functions and being able to reference parameters from the enclosing function in the local function. However, if I try to make this function polymorphic as follows: import spire.math._ import spire.implicits._ def foo[A:Numeric] (a : A, b : A) : A = { def bar[A:Numeric](c : A, d :A) : A = { c * b } a * bar(1,2) } <console>:22: error: overloaded method value * with alternatives: (rhs: Double)(implicit ev1: spire.algebra.Field[A(in method bar)])A(in method bar) <and> (rhs: Int)(implicit ev1: spire.algebra.Ring[A(in method bar)])A(in method bar) <and> (rhs: A(in method bar))A(in method bar) cannot be applied to (A(in method foo)) c * b ^ I run into a problem where the compiler cannot resolve the multiplication operator inside the bar function. There are multiple implicit alternatives. How can I resolve this issue? A: There's no need for bar to be generic: import spire.math._ import spire.implicits._ def foo[A: Numeric] (a: A, b: A) : A = { def bar(c: A, d: A) : A = { c * b } a * bar(1, 2) } You're only getting an error, though, because you've written c * b (while the second argument to bar is named d), which means you're trying to multiply the outer A and the inner generic A, without giving any evidence that they're related.
{ "pile_set_name": "StackExchange" }
Q: Hereditary torsion theories and preradicals I'm stumped with what should be an easy question from Stenström's Rings of Quotients: For a fixed module $V$, take $(\mathscr{T,F})$ to be the torsion theory cogenerated by $\{V\}$, and define the preradical $r_V$ as follows: $$r_V(M) = \bigcap\{\operatorname{ker}\varphi\mid \varphi \in \hom_R(M, V) \} $$ The question then is: $(\mathscr{T,F})$ is hereditary if and only if $r_V = r_{E(V)}$ Where $E(V)$ is the injective hull of $E$. A: We know that the torsion theory $(\mathscr{T},\mathscr{F})$ cogenerated by $V$, is the one that has as torsion-free class $\mathscr{F}$ the class of the modules cogenerated by $V$. That is $M\in \mathscr{F}$ if and only if there is mononomorphism $M\longrightarrow V^X$ for some set $X$. Now, $r_V$ is the idempotent radical asociated to this torsion theory. Is easy to see that $\mathscr{F}=\mathscr{F}_{r_V}$. $\Rightarrow)$ We want to show that $\mathscr{F}_{r_V}=\mathscr{F}_{r_{E(V)}}$. To do this we use that these are the classes of modules cogenerated by $V$ and $E(V)$ respectively. As $V\subseteq E(V)$, we have that $\mathscr{F}_{r_V}\subseteq\mathscr{F}_{r_{E(V)}}$. We know that, $(\mathscr{T},\mathscr{F})$ is hereditary if and only if $\mathscr{F}$ is closed under injective envelopes. As $\mathscr{F}=\mathscr{F}_{r_V}$ is closed under injectivee envelopes and $V\in\mathscr{F}$, then $E(V)\in \mathscr{F}$. Therefore $\mathscr{F}_{r_V}=\mathscr{F}_{r_{E(V)}}$. $\Leftarrow)$ As $r_V=r_{E(V)}$, we have that $\mathscr{F}_{r_V}\subseteq\mathscr{F}_{r_{E(V)}}$. Let $M\in\mathscr{F}$, then $M$ is submodule of $E(V)^X$ for some set $X$. It follows that $E(M)$ is submodule of $E(V)^X$. Thus $E(M)\in\mathscr{F}$. Therefore $(\mathscr{T},\mathscr{F})$ is hereditary.
{ "pile_set_name": "StackExchange" }
Q: XML blank attribute creation, issue with ':' character I am trying to create an xml with the following code. XmlDocument xmlDocument = new XmlDocument(); XmlProcessingInstruction xPI = xmlDocument.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlDocument.AppendChild(xPI); XmlElement xElmntheader = xmlDocument.CreateElement("soapenv:Header", " "); xmlDocument.AppendChild(xElmntheader); MemoryStream ms = new MemoryStream(); xmlDocument.Save(ms); string text = System.Text.Encoding.GetEncoding("UTF-8").GetString(ms.GetBuffer(), 0, (int)ms.Length); Output is <xml version='1.0' encoding='UTF-8'?> <soapenv:Header xmlns:soapenv=" " /> I was trying to create like this <xml version='1.0' encoding='UTF-8'?> <soapenv:Header/> How do I eliminate xmlns:soapenv=" " from soapenv:Header? Any help would be greatly appreciated. A: What you're asking how to do is create ill-formed (syntactically incorrect) XML. The XmlDocument API is not designed to do that. If you use the element name soapenv:Header that means soapenv is a namespace prefix, which has been declared on this element (or an ancestor) using the xmlns:soapenv pseudoattribute. If it has not been declared, your XML output will not be accepted by any self-respecting XML parser. The method signature you called, xmlDocument.CreateElement(string1, string2); takes two arguments: the qualified name of the element (which may include a prefix, as it does in your case); and a namespace URI. The documentation shows what the expected output is: The following C# code XmlElement elem; elem = doc.CreateElement("xy:item", "urn:abc"); results in an element that is equivalent to the following XML text. <xy:item xmlns:item="urn:abc"/> The expected namespace URI for this element is "http://schemas.xmlsoap.org/soap/envelope/". So you will want to declare the soapenv prefix with that namespace URI: string soapNSURI = "http://schemas.xmlsoap.org/soap/envelope/"; and use it thus: XmlElement xElmntheader = xmlDocument.CreateElement("soapenv:Header", soapNSURI);
{ "pile_set_name": "StackExchange" }
Q: Как открыть список контактов при нажатии на ссылку в HTML? У меня есть веб-страница, на которой расположена ссылка вида <a href="..."/>. Как сделать так, чтобы при нажатии на неё открывался список контактов телефона? A: Нужно переопределить WebViewClient private class Client extends WebViewClient{ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if(url.contains("ваша ссылка")){ Intent intent= new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivity(intent); } return super.shouldOverrideUrlLoading(view, url); } } При инициализации WebView назначить его webView.setWebViewClient(new Client()); Если контакт будет выбираться то вызывать startActivityForResult
{ "pile_set_name": "StackExchange" }
Q: How to intent SharedPreferences into next activity value using PostResponseAsyncTask in Android Studio? my question is the extension of this question here but in this question I added two function which are : SharedPreferences Remember me function (Checkbox) Currently, I managed to login with/without remember me checkbox and intent the rest of the JSON Object fetch from mysql database. But the problem is inside LoginActivity.java PART A block . When I restart/rebuild the apps, the intent data is null which is not stored and sent into next activity. The data could not be stored and sent into next activity when it automatically logged in. The code as below JSON Object { "access":"PA001", "password":"123", "fullname":"ARCADE", "branch":"HQ", "section":"MPR" } access.php <?php $conn = mysqli_connect("","","",""); if( isset($_POST['access']) && isset($_POST['password']) ){ $access = $_POST['access']; $password = $_POST['password']; $sql = "SELECT * FROM table WHERE access = '$access' AND password = '$password' "; $result = mysqli_query($conn, $sql); if($result && mysqli_num_rows($result) > 0){ while($row = mysqli_fetch_array($result)){ $accessdb = $row['access']; $passworddb = $row['password']; $fullnamedb = $row['fullname']; $branchdb = $row['branch']; $sectiondb = $row['section']; echo "success_access"; $response = array('access' => $accessdb, 'password' => $passworddb, 'fullname' => $fullnamedb, 'branch' => $branchdb, 'section' => $sectiondb); echo json_encode($response); } mysqli_free_result($result); } else { echo "access_failed"; } } ?> LoginActivity.java public class LoginActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { final String TAG = this.getClass().getName(); SharedPreferences sharedPreferences; SharedPreferences.Editor editor; EditText etLogin, etPassword; CheckBox cbRememberMe; Button bLogin; boolean checkRememberMe; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); etLogin = (EditText)findViewById(R.id.etLogin); etPassword = (EditText)findViewById(R.id.etPassword); cbRememberMe = (CheckBox)findViewById(R.id.cbRememberMe); cbRememberMe.setOnCheckedChangeListener(this); checkRememberMe = cbRememberMe.isChecked(); sharedPreferences = getSharedPreferences("login.conf", Context.MODE_PRIVATE); editor = sharedPreferences.edit(); //////////////////////////////////////// PART A ///////////////////////////////////// final String accessdb = sharedPreferences.getString("access", ""); final String passworddb = sharedPreferences.getString("password", ""); final String fullnamedb = sharedPreferences.getString("fullname", ""); final String branchdb = sharedPreferences.getString("branch", ""); final String sectiondb = sharedPreferences.getString("branch", ""); final HashMap data = new HashMap(); data.put("access", accessdb); data.put("password", passworddb); data.put("fullname", fullnamedb); data.put("branch", branchdb); data.put("section", sectiondb); if(!(accessdb.contains("") && passworddb.contains("") && fullnamedb.contains("") && branchdb.contains("") && sectiondb.contains(""))){ PostResponseAsyncTask task = new PostResponseAsyncTask(LoginActivity.this, data, new AsyncResponse() { @Override public void processFinish(String s) { // edited here ,add Log Log.d(TAG, "processFinish : " + s); String responseToJSONObject = s.substring(s.indexOf("{")); if(s.contains("success_access")){ try { JSONObject jsonObject = new JSONObject(responseToJSONObject); final String logindb = jsonObject.getString("login"); final String pwdb = jsonObject.getString("pw"); final String realnamedb = jsonObject.getString("real_name"); final String deptdb = jsonObject.getString("dept"); Intent intent = new Intent(LoginActivity.this, NextActivity.class); intent.putExtra("login", logindb); intent.putExtra("pw", pwdb); intent.putExtra("real_name", realnamedb); intent.putExtra("dept", deptdb); LoginActivity.this.startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } } }); task.execute("http://localhost/login.php"); } //////////////////////////////////////// PART A ///////////////////////////////////// bLogin = (Button)findViewById(R.id.bLogin); bLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = "http://localhost/login.php"; StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // edited here ,add Log Log.d(TAG, "onResponse : " + response); if(response.contains("success_access")){ String resp = response.substring(response.indexOf("{")); // LOGIN WITH CHECK REMEMBER ME if(checkRememberMe){ try { JSONObject jsonObject = new JSONObject(resp); final String accessdb = jsonObject.getString("access"); final String passworddb = jsonObject.getString("password"); final String fullnamedb = jsonObject.getString("fullname"); final String branchdb = jsonObject.getString("branch"); final String sectiondb = jsonObject.getString("section"); editor.putString("access", etLogin.getText().toString()); editor.putString("password", etPassword.getText().toString()); editor.putString("fullname", fullnamedb); editor.putString("branch", branchdb); editor.putString("section", sectiondb); editor.putBoolean("isLoggedIn", true); editor.apply(); Intent intent = new Intent(LoginActivity.this, NextActivity.class); intent.putExtra("access", accessdb); intent.putExtra("password", passworddb); intent.putExtra("fullname", fullnamedb); intent.putExtra("branch", branchdb); intent.putExtra("section", sectiondb); LoginActivity.this.startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } // LOGIN WITH CHECK REMEMBER ME // LOGIN WITHOUT CHECK REMEMBER ME else { try { JSONObject jsonObject = new JSONObject(resp); final String accessdb = jsonObject.getString("access"); final String passworddb = jsonObject.getString("password"); final String fullnamedb = jsonObject.getString("fullname"); final String branchdb = jsonObject.getString("branch"); final String sectiondb = jsonObject.getString("section"); Intent intent = new Intent(LoginActivity.this, NextActivity.class); intent.putExtra("access", accessdb); intent.putExtra("password", passworddb); intent.putExtra("fullname", fullnamedb); intent.putExtra("branch", branchdb); intent.putExtra("section", sectiondb); LoginActivity.this.startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } // LOGIN WITHOUT CHECK REMEMBER ME } else{ Toast.makeText(getApplicationContext(), "Error" , Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Error" , Toast.LENGTH_SHORT).show(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("login", etLogin.getText().toString()); params.put("pw", etPassword.getText().toString()); return params; } }; MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest); } }); } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { checkRememberMe = isChecked; Log.d(TAG, "Remember me is = " + checkRememberMe); } } EDITED : my Logcat 08-22 16:50:28.802 21022-21022/? I/art: Not late-enabling -Xcheck:jni (already on) 08-22 16:50:28.802 21022-21022/? W/art: Unexpected CPU variant for X86 using defaults: x86 08-22 16:50:28.822 21022-21029/? I/art: Debugger is no longer active 08-22 16:50:28.822 21022-21029/? I/art: Starting a blocking GC Instrumentation 08-22 16:50:28.895 21022-21022/? W/System: ClassLoader referenced unknown path: /data/app/com.app.test-2/lib/x86 08-22 16:50:28.901 21022-21022/? I/InstantRun: starting instant run server: is main process 08-22 16:50:29.129 21022-21040/? I/OpenGLRenderer: Initialized EGL, version 1.4 08-22 16:50:29.129 21022-21040/? D/OpenGLRenderer: Swap behavior 1 08-22 16:50:29.130 21022-21040/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... 08-22 16:50:29.130 21022-21040/? D/OpenGLRenderer: Swap behavior 0 08-22 16:50:29.133 21022-21040/? D/EGL_emulation: eglCreateContext: 0xb3305060: maj 2 min 0 rcv 2 08-22 16:50:29.150 21022-21040/? D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360) 08-22 16:50:29.156 21022-21040/? D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360) 08-22 16:50:29.964 21022-21022/com.app.test W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable 08-22 16:50:30.037 21022-21022/com.app.test W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView 08-22 16:50:30.040 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360) 08-22 16:50:44.279 21022-21022/com.app.test W/IInputConnectionWrapper: finishComposingText on inactive InputConnection 08-22 16:50:46.163 21022-21022/com.app.test D/com.app.test.LoginActivity: Check flag is = true 08-22 16:50:47.820 21022-21323/com.app.test D/NetworkSecurityConfig: No Network Security Config specified, using platform default // LOG.d after i logged in with remember me check in 08-22 16:50:47.824 21022-21022/com.app.test E/com.app.test.LoginActivity: Response is = success_access{"access":"ID001","password":"1233","fullname":"ARCADE","branch":"HQ", "section":"MPR"} 08-22 16:50:47.825 21022-21022/com.app.test E/com.app.test.LoginActivity: JSON Object is = {"access":"ID001","password":"1233","fullname":"ARCADE","branch":"HQ", "section":"MPR"} 08-22 16:50:47.825 21022-21022/com.app.test D/com.app.test.LoginActivity: ID001 08-22 16:50:47.825 21022-21022/com.app.test D/com.app.test.LoginActivity: 123 08-22 16:50:47.982 21022-21025/com.app.test I/art: Do partial code cache collection, code=29KB, data=30KB 08-22 16:50:47.982 21022-21025/com.app.test I/art: After code cache collection, code=29KB, data=30KB 08-22 16:50:47.982 21022-21025/com.app.test I/art: Increasing code cache capacity to 128KB 08-22 16:50:47.994 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360) 08-22 16:50:48.083 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360) 08-22 16:50:48.100 21022-21040/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305060: ver 2 0 (tinfo 0xb3303360) 08-22 16:50:48.135 21022-21022/com.app.test W/IInputConnectionWrapper: finishComposingText on inactive InputConnection // LOG.d when I restarted apps without logout. 08-22 16:54:32.607 24710-24710/? I/art: Not late-enabling -Xcheck:jni (already on) 08-22 16:54:32.607 24710-24710/? W/art: Unexpected CPU variant for X86 using defaults: x86 08-22 16:54:32.694 24710-24710/com.app.test W/System: ClassLoader referenced unknown path: /data/app/com.app.test-2/lib/x86 08-22 16:54:32.699 24710-24710/com.app.test I/InstantRun: starting instant run server: is main process 08-22 16:54:34.256 24710-24811/com.app.test I/OpenGLRenderer: Initialized EGL, version 1.4 08-22 16:54:34.257 24710-24811/com.app.test D/OpenGLRenderer: Swap behavior 1 08-22 16:54:34.257 24710-24811/com.app.test W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... 08-22 16:54:34.257 24710-24811/com.app.test D/OpenGLRenderer: Swap behavior 0 08-22 16:54:34.258 24710-24811/com.app.test D/EGL_emulation: eglCreateContext: 0xb3305360: maj 2 min 0 rcv 2 08-22 16:54:34.266 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200) 08-22 16:54:34.274 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200) 08-22 16:54:35.124 24710-24710/com.app.test W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable 08-22 16:54:35.292 24710-24710/com.app.test W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView 08-22 16:54:35.299 24710-24811/com.app.test D/EGL_emulation: eglMakeCurrent: 0xb3305360: ver 2 0 (tinfo 0xb3303200) Appreciate if someone can help. Thanks. A: Try this. public class SharedPreferenceUtils { private static final String SP_NAME = "sp"; public static final String ACCESS = "access"; public static final String FULL_NAME = "fullname"; public static final String BRANCH = "branch"; public static final String SECTION = "section"; public static final String IS_LOGGED_IN = "isLoggedIn"; // create public static boolean createSP(Context context, String access, String fullname, String branch, String section, boolean isLoggedIn) { SharedPreferences.Editor editor = context.getSharedPreferences("login.conf", Context.MODE_PRIVATE).edit(); editor.putString(ACCESS, access); editor.putString(FULL_NAME, fullname); editor.putString(BRANCH, branch); editor.putString(SECTION, section); editor.putBoolean(IS_LOGGED_IN, isLoggedIn); return editor.commit(); } // clear public static void clearSP(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear().apply(); } // get access info public static String getAccess(Context context) { SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); return sp.getString(ACCESS, ""); } // get branch info public static String getFullName(Context context) { SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); return sp.getString(FULL_NAME, ""); } // get fullname info public static String getBranch(Context context) { SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); return sp.getString(BRANCH, ""); } // get section info public static String getSection(Context context) { SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); return sp.getString(SECTION, ""); } // get isLoggedIn info public static boolean getIsLoggedIn(Context context) { SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); return sp.getBoolean(ACCESS, false); } } And in your code. // edited here final String accessdb = SharedPreferenceUtils.getAccess(this); final String fullnamedb = SharedPreferenceUtils.getFullName(this); final String branchdb = SharedPreferenceUtils.getBranch(this); final String sectiondb = SharedPreferenceUtils.getSection(this); final HashMap data = new HashMap(); data.put("access", accessdb); data.put("password", passworddb); data.put("fullname", fullnamedb); data.put("branch", branchdb); data.put("section", sectiondb); And if isRemember if(checkRememberMe){ SharedPreferenceUtils.createSP(LoginActivity.this,etLogin.getText().toString(),fullnamedb,branchdb,sectiondb,true); } A: From what I see and understand in your question, you want the data to be stored and intent into next activity on next auto logged in (inside PART A). After I tried it from my end based on your code above and I assume your "isLoggedIn" is from other activity file. You just need to change boolean "isLoggedIn" into false because whenever user log in with remember me, it stored the sharedPreferences data and intent it into next activity. Same as log in without remember me, it stored the sharedPreferences data but isLoggedIn is false. Therefore, when your apps restart or rebuild, it will not auto logged in anymore. Don't forget to clear and commit the sharedPreferences when "isLoggedIn" is false. Here's the code. LoginActivity.java if(checkRememberMe){ // Data added } else { try { JSONObject jsonObject = new JSONObject(resp); final String accessdb = jsonObject.getString("access"); final String passworddb = jsonObject.getString("password"); final String fullnamedb = jsonObject.getString("fullname"); final String branchdb = jsonObject.getString("branch"); final String sectiondb = jsonObject.getString("section"); editor.putString("access", etLogin.getText().toString()); editor.putString("password", etPassword.getText().toString()); editor.putString("fullname", fullnamedb); editor.putString("branch", branchdb); editor.putString("section", sectiondb); editor.putBoolean("isLoggedIn", false); editor.apply(); Intent intent = new Intent(LoginActivity.this, NextActivity.class); intent.putExtra("access", accessdb); intent.putExtra("password", passworddb); intent.putExtra("fullname", fullnamedb); intent.putExtra("branch", branchdb); intent.putExtra("section", sectiondb); LoginActivity.this.startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } And inside NextActivity.java, add sharedPreferences and set it as String. sharedPreferences sharedPreferences = getSharedPreferences("login.conf", Context.MODE_PRIVATE); final String accessdb = sharedPreferences.getString("access",""); final String pwdb = sharedPreferences.getString("pw",""); final String fullnamedb = sharedPreferences.getString("fullname",""); final String branchdb = sharedPreferences.getString("branch",""); final String sectiondb = sharedPreferences.getString("section",""); Intent intent = getIntent(); String access_db = intent.getStringExtra("access"); String pw_db = intent.getStringExtra("pw"); String fullname_db = intent.getStringExtra("fullname"); String branch_db = intent.getStringExtra("branch"); String section_db = intent.getStringExtra("section"); Toast.makeText(getApplicationContext(), "access is = " + accessdb, Toast.makeText.LENGTH_SHORT).show();
{ "pile_set_name": "StackExchange" }
Q: What is flag weight? I have no idea what flag weight stands for. Which is better, having low flag weight or high flag weight? Could you elaborate on it? A: In short, flag weight is a measure of how reliably you flag content. High flag weight is good. It can range between 0 and 750. It increases if your flags are positively reviewed. The more flag weight you have, the more you can flag, and the higher the priority of your flags is. High flag weight is rewarded by a Deputy (500) or a Marshal badge (749). Flagging posts is a privilege that you gain once you have 15 reputation points; so this is a way of helping the community that you can use pretty early on. There's more information on the corresponding flag privilege info page, the faq entry "flagging", and the extensive answer on meta.stackoverflow.com: What is flag weight?
{ "pile_set_name": "StackExchange" }
Q: CSS hover firing more than once with webkit 3d transform When I use a webkit 3d transform on hover, only the top 50% of the hover area works, while the bottom 50% is unstable. I'm currently testing on Chrome (31.0.1650.63). Is it a bug? Is there any workaround? Try to place your mouse on the top of the div and slowly bring it to the bottom. HTML <div class="hoverArea"></div> <div class="flip"> <div class="front">front</div> <div class="back">back</div> </div> CSS .hoverArea, .flip, .front, .back { width: 200px; height: 200px; position: absolute; top: 0; left: 0; } .hoverArea { z-index: 10; } .flip { -webkit-transform-style: preserve-3d; -webkit-transition: 0.5s; -webkit-perspective: 800; z-index: 9; } .front { background-color: #f00; -webkit-backface-visibility: hidden ; } .back { background-color: #f0f; -webkit-transform: rotatex(-180deg); -webkit-backface-visibility: hidden ; } .hoverArea:hover + .flip { -webkit-transform: rotatex(-180deg); } http://jsfiddle.net/4P53y/ A: You can fix it by removing the .hoverArea element and instead apply the :hover event on the .flip element. .flip:hover { -webkit-transform: rotatex(-180deg); } Demo If you want to still use the .hoverArea element then you can use transform:translateZ(1px); on .hoverArea to make it function correctly. It makes the browser render the element more carefully .hoverArea { z-index: 10; -webkit-transform:translateZ(1px); } Demo
{ "pile_set_name": "StackExchange" }
Q: Python and T-API on OpenCV OpenCV 3.0 now uses T-API (Transparent API), see: https://github.com/Itseez/opencv/wiki/Opencv3 it does not need to specify cv::ocl::Canny, cv::gpu::Canny etc; cv::Canny just works on both CPU and GPU. And this is an example: http://www.learnopencv.com/opencv-transparent-api/ My question is: This works with OpenCV with Python? Can anyone give me an example? A: In C++ to use OpenCL implementations of methods - you should pass UMat instead of Mat, when you call method from Python with numpy array or so - you effectively call it with Mat as argument. UMat was adopted for Python bindings since OpenCV 3.2. Now you can pass cv2.UMat(someNumpyMat) to function just like in C++. Example: ps, descs_umat = orb.detectAndCompute(cv2.UMat(img), None) descs = descs_umat.get() matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) res = matcher.match(descs_umat, descs_umat)
{ "pile_set_name": "StackExchange" }
Q: How does JavaScript's in object feature work? I am learning JavaScript and something I cannot understand at the moment is this example below. Using in to check if an item exist in the Object on the right side. This code will merge user options into default options. What is confusing to me is the i is not defined anywhere, so how does it know what i is? If I print out i inside of the for block, it lists every option of my object. I have read MDN's article about the in operator but it does not explain this handling of an undefined variable. var i; for(i in options) { if(i in this.options) { this.options[i] = options[i]; } else { throw new Error("Notice doesn't support option: " + i); } } A: There are two different kinds of "in": For ... in The in operator The first in in your code is not the in operator. It is a For ... in loop which iterates through the keys of an object assigning each key to the variable which in this case is i. The second in in your code is the oner that you have already read the docs for. An operator which returns true or false. Note: Unless you have var i earlier in that function scope, you are declaring a global variable i by leaving out the var keyword in your loop. You most likely want: for(var i in options){
{ "pile_set_name": "StackExchange" }
Q: Regular expression required in JAVA The following strings: "strAlpha" & "strNum" are my sample string format: String strAlpha = "[fields=A,B,C,D]"; String strNum = "[sales=15,20,16,100,500,54555]"; strAlpha.matches("regex"); strNum.matches("regex"); Required regular expression, so the resulted array will only contain the comma separated values of the above string. A: \[[^=]*=|\] Use replace instead to clean up the strings.Replace by empty string.See demo. https://regex101.com/r/tJ2mW5/17
{ "pile_set_name": "StackExchange" }
Q: Convenient way to dump Azure SQL DB database Using geo-replication is a nice way of duplicating data but it requires the two servers to be registered on the same Azure account. That could be a potential security risk if an employee decides to log in and delete both servers. In that case there would be no possible way of recovering data. To counter this potential threat, a scheduled dump sounds like a good way to keep data in another account that another set of users have access to. Using Database Sync results in new tables being generated and seems messy. Does Azure SQL DB provide any convenient way of dumping data? A: You can create an automation account and runbook which runs a task to export the backup of databases to a storage account every so often. Here is an example: $ResourceGroupName = "rg" $ServerName = "sqlserver" $StorageKeytype = "StorageAccessKey" $StorageKey = "examplestoragekey" $sqldbs = ("userdb1,userdb2") $UserName = "sqladminaccount" $BacpacUri_Stem = "https://example.blob.core.windows.net/sqlbackup/" $Password = Get-AutomationPSCredential -Name 'MyCredential' foreach ($sqldb in $sqldbs){ $BacpacUri = $BacpacUri_Stem + $database + (Get-Date -Format ddmmyy) + ".bacpac" $exportRequest = New-AzureRmSqlDatabaseExport -ResourceGroupName $ResourceGroupName -ServerName $ServerName ` -DatabaseName $Database -StorageKeytype $StorageKeytype -StorageKey $StorageKey -StorageUri $BacpacUri ` -AdministratorLogin $UserName -AdministratorLoginPassword $Password }
{ "pile_set_name": "StackExchange" }