text
stringlengths
64
81.1k
meta
dict
Q: List all combinations of factors (interactions) with no observations in a dataframe, up to a given dimension, removing redundancies For a given dataframe with only factor columns, I want to list all combinations of factors for up to m attributes that do not appear in the data. Below is a simple example: d <- expand.grid(w=factor(1:2), x=factor(1:2), y=factor(1:2), z=factor(1:2)) # These combinations are removed by tail(): rmcomb <- 5; head(d, rmcomb) ## w x y z ## 1 1 1 1 1 ## 2 2 1 1 1 ## 3 1 2 1 1 ## 4 2 2 1 1 ## 5 1 1 2 1 d <- tail(d, -rmcomb) ftable(d, row.vars=c("w", "x")) ## y 1 2 ## z 1 2 1 2 ## w x ## 1 1 0 1 0 1 ## 2 0 1 1 1 ## 2 1 0 1 1 1 ## 2 0 1 1 1 For m == 3, we consider all 4 + 6 + 4 = 14 combinations of up to three attributes in d: m <- 3 library(plyr) llply( 1:m, function(i) combn(ncol(d), i, simplify=F) ) -> cc unlist(cc, recursive=F) -> cc length(cc) ## [1] 14 We can now tabulate selected columns of the data using table, and use which to find entries with zeros: llply( cc, function(cols) { which(table(d[, cols]) == 0, arr.ind=T) -> z colnames(z) <- names(d)[cols] if (nrow(z) > 0) list(z) else NULL } ) -> zz unlist(zz, recursive=F) ## [[1]] ## y z ## 1 1 1 ## ## [[2]] ## w x z ## 1 1 1 1 ## ## [[3]] ## w y z ## 1 1 1 1 ## 2 2 1 1 ## ## [[4]] ## x y z ## 1 1 1 1 ## 2 2 1 1 However, items [[3]] and [[4]] in the result above are redundant, because they are covered by item [[1]] (=no observations with y == 1, z == 1). The solution should be thus (y,z) == (1,1); (w,x,z) == (1,1,1). Is there a built-in facility in R that would solve the problem with less coding, perhaps including removal of redundant (=covered) tuples? If not, how would you remove these redundant items for the code above? A: Here's how you can continue your algo to pick out those sequences. First let's convert your list to a matrix, with NA's filled in. I find this easier to deal with, but I'm sure with some effort you can make it work with a list as well: m = as.matrix(rbind.fill(lapply(zz, as.data.frame))) # y z w x #[1,] 1 1 NA NA #[2,] NA 1 1 1 #[3,] 1 1 1 NA #[4,] 1 1 2 NA #[5,] 1 1 NA 1 #[6,] 1 1 NA 2 Now let's introduce a function which will tell us if each row of a matrix given by subseq is a "subsequence" of seq, meaning it is already covered by seq as per OP's definitions: is.subsequence = function(seq, subseq) { comp = seq == t(subseq) rowSums(t(is.na(comp) == is.na(seq) & matrix(!(comp %in% FALSE), nrow = length(seq)))) == length(seq) } All that's left is to iterate over the matrix and throw out the covered sequences. We can do this going from top to bottom because of the automatic arrangement of zz from OP. i = 1 while(i < nrow(m)) { m = rbind(m[1:i,], tail(m, -i)[!is.subsequence(m[i,], tail(m, -i)),]) i = i+1 } m # y z w x #[1,] 1 1 NA NA #[2,] NA 1 1 1 And you can go back to a list if you like: apply(m, 1, na.omit)
{ "pile_set_name": "StackExchange" }
Q: Put JSON in a variable I have a hard time with $.ajax(). I have this HTML page : <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <form name="gettr" id="gettr"> <input type="hidden" name="lang" value="ro"> <input type="text" name="tickkey" id="tickkey" value=""> <br> <input type="submit" value="Send" id="submit"> <input type="reset" value="Cancel" onclick="$(&quot;#hereinfo&quot;).html(&quot;&quot;);"> </form> </body> </html> And the script : $("#gettr").submit(function() { var url = "handler.php"; $.ajax({ type: "GET", url: url, dataType: "application/json", data: $("#gettr").serialize(), // serializes the form's elements. success: function(data) { alert('Done'); } }); return false; }); I'm running the script locally now, and my problem is that the script doesn't do anything.When I click on send button it just adds ?lang=ro&tickkey=value_inputed_in_the_form at the end of the url in the address bar.What should I do so I can store the JSON returned by the server in a variable? Thank you! A: I think the reason your query variables are appending to url is because you're executing your script before the DOM loads. You should wrap your script within $(document).ready(function () { }); handler. Use event.preventDefault() instead of return false;. But Why not return false; see here $(document).ready(function () { //Let the DOM be loaded $("#gettr").submit(function(event) { event.preventDefault(); //Prevent window default behaviour var url = "handler.php"; $.ajax({ type: "GET", url: url, dataType: "application/json", data: $("#gettr").serialize(), // serializes the form's elements. success: function(data) { alert(data); //Alert your json data from server } }); }); //remember remove return false; because you're already preventing default behaviour }); A: Ensure that the DOM is ready and prevent the form submission before executing the AJAX request. var dataFromServer = {}; // Document ready. $(function() { $( '#gettr' ).on( 'submit', function( event ) { // Prevent form submission. event.preventDefault(); // AJAX request. var url = 'handler.php'; $.ajax({ type: 'GET', url: url, dataType: 'application/json', data: $( '#gettr' ).serialize(), success: function( data ) { dataFromServer = data; } }); }); }); A: Try to call preventDefault(); $("#gettr").submit(function(event) { event.preventDefault();
{ "pile_set_name": "StackExchange" }
Q: Android file upload progress dialog error i got this AsyncTask file upload: // ASync Task Begin to perform Billing information class performBackgroundTask extends AsyncTask<Void, Void, Void> { Context context; private ProgressDialog Dialog; protected void onPreExecute() { // here you have place code which you want to show in UI thread like // progressbar or dialog or any layout . here i am displaying a // progressDialog with test please wait while loading...... Dialog.setMessage(" please wait while loading............"); Dialog.show(); } private Context getApplicationContext() { // TODO Auto-generated method stub return null; } protected Void doInBackground(Void... params) { // write here the code to download or any background task. goforIt(); // example call method which will download vedio . return null; } protected void onPostExecute(Void unused) { Dialog.dismiss(); // the background task is completed .You can do the code here for next // things } public void goforIt() { FTPClient con = null; try { con = new FTPClient(); con.connect(globalconstant.host); if (con.login(globalconstant.nev, globalconstant.jelszo)) { con.enterLocalPassiveMode(); // important! con.setFileType(FTP.BINARY_FILE_TYPE); String substr = globalconstant.path.substring(4, globalconstant.path.length()); String filename = substr + "/Festivale.db"; Log.e("TravellerLog :: ", substr + "/Festivale.db"); String data = filename; FileInputStream in = new FileInputStream(new File(data)); boolean result = con.storeFile("/Festivale.db", in); in.close(); if (result) // Toast.makeText(getApplicationContext(), // "A fájl feltöltve!", Toast.LENGTH_SHORT).show(); Log.v("upload result", "succeeded"); con.logout(); con.disconnect(); } } catch (Exception e) { e.printStackTrace(); } } } but always got error meassage, this: 09-26 11:30:30.538: E/AndroidRuntime(456): java.lang.NullPointerException 09-26 11:30:30.538: E/AndroidRuntime(456): at com.eyecom.festivale.performBackgroundTask.onPreExecute(performBackgroundTask.java:25) ... the 25th line: Dialog.setMessage(" please wait while loading............"); please help me how to make a progress dialog which works with this. the original is like: private ProgressDialog Dialog = new ProgressDialog( this); but got error with this too, The constructor ProgressDialog(performBackgroundTask) is undefined A: You are doing wrong things as Dialog never ever initiated it just declared not defined. Another thing Dialog keyword is already a class name whenever you define any object/variable name start character if alphabet it must be in lower case. All the Upper case for start character are used for Class name. Editted private ProgressDialog dialog; protected void onPreExecute() { dialog = ProgressDialog.show(YourActivity.this, "Processing", "please wait while loading............"); } and in onPostExecution(Void unused) onPostExecution(Void unused){ if(dialog!=null) dialog.dismiss(); }
{ "pile_set_name": "StackExchange" }
Q: Angular doesn't load a module - $injector:modulerr I get the following error in my application: The problem only appears when loading a specific module, here's my main module: app.module.js (function () { 'use strict'; angular .module( 'app', [ /* * Shared modules */ 'app.layout', 'app.core', /* * Feature areas */ 'app.users', 'app.purchases'//This is the module that generates the modulerr error ] ) .config( [ '$locationProvider', hashbagRemove ] ); function hashbagRemove( $locationProvider ) { $locationProvider.html5Mode( true ); } })(); This is the module that generates the error: purchases.module.js (function () { 'use strict'; angular.module( 'app.purchases', [ 'app.purchases.suppliers' ] ); })(); suppliers.module.js (function () { 'use strict'; angular.module( 'app.purchases.suppliers', [] ); })(); As you can see i've got a modular application, the thing is that if i load that module the application crashes, i already checked all the controllers and factories to see if there was any mistake there, and all of them are correct, also i already verified that i was loading all the necesary scripts, i don't get why the error persists. To give you a clearer idea of the structure of my application here's a pic of it: And here's index.html <!DOCTYPE html> <html lang="es" ng-app="app"> <head> <meta charset="UTF-8"> <title>SOS Control</title> <link rel="stylesheet" href="./components/bootstrap/bootstrap-3.1.1.min.css"/> <link rel="stylesheet" href="./components/font-awesome/font-awesome-4.4.0.min.css"/> <base href="/"/> </head> <body> <div ui-view></div> <!--==================================================== SCRIPTS ====================================================--> <!----------------------------------------------Other--> <!--<script src="./components/lodash/lodash-3.10.1.min.js"></script>--> <script src="./components/underscore/underscore-1.8.3.min.js"></script> <!---------------------------------------------JQuery--> <script src="./components/jquery/jquery-2.1.4.min.js"></script> <!--------------------------------------------Angular--> <script src="./components/angular/angular-1.4.5.min.js"></script> <script src="./components/bootstrap/ui-bootstrap-0.13.4.min.js"></script> <script src="./components/angular-ui-router/angular-ui-router-0.2.15.min.js"></script> <script src="./components/restangular/restangular-1.5.1.min.js"></script> <!---------------------------------------Main Modules--> <script src="./app.module.js"></script> <script src="./modules/core/core.module.js"></script> <script src="./modules/layout/layout.module.js"></script> <!---------------------------------------Users Module--> <script src="./modules/users/users.module.js"></script> <script src="./modules/users/users.routes.js"></script> <script src="./modules/users/signin/signin.controller.js"></script> <script src="./modules/users/signout/signout.factory.js"></script> <script src="./modules/users/account/account.module.js"></script> <script src="./modules/users/account/account.routes.js"></script> <script src="./modules/users/account/edit-data/edit-data.controller.js"></script> <script src="./modules/users/account/reset-password/reset-password.controller.js"></script> <!-----------------------------------Purchases Module--> <script src="./modules/purchases/purchases.module.js"></script> <script src="./modules/purchases/purchases.routes.js"></script> <script src="./modules/purchases/suppliers/suppliers.module.js"></script> <script src="./modules/purchases/suppliers/suppliers.routes.js"></script> <script src="./modules/purchases/suppliers/suppliers-dashboard.controller.js"></script> <script src="./modules/purchases/suppliers/create-supplier/create-supplier.factory.js"></script> <script src="./modules/purchases/suppliers/create-supplier/create-supplier.controller.js"></script> <script src="./modules/purchases/suppliers/read-supplier/read-supplier.factory.js"></script> <script src="./modules/purchases/suppliers/read-supplier/read-supplier.controller.js"></script> <script src="./modules/purchases/suppliers/update-supplier/update-supplier.factory.js"></script> <script src="./modules/purchases/suppliers/update-supplier/update-supplier.controller.js"></script> </body> </html> UPDATE 1 With the updated error (using the dev. version of angular) it seems like the error is generated from this file: suppliers.routes.js (function () { 'use strict'; angular .module( 'app.purchases.suppliers' ) // Collect the ui-route states .constant( 'states', getRouteStates() ) // Configure the ui-route states and state resolvers .config( [ '$stateProvider', '$urlRouterProvider', 'states', stateConfigurator ] ); function stateConfigurator( $stateProvider, $urlRouterProvider, states ) { states.forEach( function ( state ) { $stateProvider.state( state.name, state.config ); } ); $urlRouterProvider.otherwise( "/" ); } // Define the ui-route states function getRouteStates() { return [ { name: 'suppliersDashboard', config: { url: '/compras/proveedores', templateUrl: './modules/purchases/suppliers/suppliers-dashboard.view.html', title: 'Menu Principal de Proveedores', controller: 'SuppliersDashboardController', controllerAs: 'vm' } }, { name: 'createSupplier', config: { url: '/compras/proveedores/nuevo', templateUrl: './modules/purchases/suppliers/create-supplier/create-supplier.view.html', title: 'Nuevo Proveedor', controller: 'CreateSupplierController', controllerAs: 'vm' } }, { name: 'listSupplier', config: { url: '/compras/proveedores/listado', templateUrl: './modules/purchases/suppliers/read-supplier/list-supplier.view.html', title: 'Listado de Proveedores', controller: 'ReadSupplierController', controllerAs: 'vm' } }, { name: 'detailSupplier', config: { url: '/compras/proveedores/:supplierId/:supplierName', templateUrl: './modules/purchases/suppliers/read-supplier/detail-supplier.view.html', title: 'Detalles del Proveedor', controller: 'ReadSupplierController', controllerAs: 'vm' } }, { name: 'updateSupplier', config: { url: '/compras/proveedores/:supplierId/:supplierName/editar', templateUrl: './modules/purchases/suppliers/update-supplier/update-supplier.view.html', title: 'Editar Proveedor', controller: 'UpdateSupplierController', controllerAs: 'vm' } } ]; } })(); What i do is that i create a constant in each module called states where i store the states properties (i'm using ui-router), then in the module.config i iterate over the constant states to add the states to the $stateProvider. Something that i think that might be causing the trouble is that in every module i declare the same constant, states, can't two different modules have constants with the same name? A: The problem was that i declared an empty json array at purchases.routes.js: (function () { 'use strict'; angular.module('app.purchases') // Collect the ui-route states .constant('states', getRouteStates()) // Configure the ui-route states and state resolvers .config(['$stateProvider', '$urlRouterProvider', 'states', stateConfigurator]); function stateConfigurator($stateProvider, $urlRouterProvider, states) { states.forEach(function (state) { $stateProvider.state(state.name, state.config); }); $urlRouterProvider.otherwise("/"); } // Define the ui-route states function getRouteStates() { return [ {}//THIS WAS THE ERROR ]; } })(); When iterating through the states constant that array didn't have any property, so that it couldn't find state.nameand state.config. Thanks @charlietfl i could solve this when i saw the complete error when using development version of Angular.
{ "pile_set_name": "StackExchange" }
Q: Getting random value from array in for loop (angular 2) I am creating a soundboard that when a button is clicked it plays a random sound. I am trying to do this by creating an array inside a for loop that gets all the mp3 file links (filename) and when a user clicks the button the file name is changes using (Math.floor(Math.random)). The problem i am having is that it just plays the same sound. It does not play a random sound. soundboard.ts /* Loop through them, saving their title and sound file */ for(let link of links) { let filename = link.getAttribute("href") let rand = [filename]; this.sounds.push({ file: filename, rand: rand }); } /* Plays the sound */ play(sound) { sound.rand = sound.file[Math.floor(Math.random() * sound.file.length)]; console.log(sound.rand) this.media = new Audio(sound.rand); this.media.load(); this.media.play(); } A: It seems there is a logic error. Based on your problem description, I think you want something like export class Component { soundFileNames: string[] = []; media?: Audio; ngOnInit() { for (const link of links) { const fileName = link.getAttribute("href"); soundFileNames.push(fileName); } } playRandomSoundFile() { const randomIndex = Math.floor(Math.random() * soundFileNames.length); const randomFileName = soundFileNames[randomIndex]; console.log(randomFileName); const audio = new Audio(randomFileName); audio.load(); audio.play(); this.media = audio; } }
{ "pile_set_name": "StackExchange" }
Q: How to Create Dynamic-Sized Paged Horizontal UIScrollView Using AutoLayout in Xcode 6 I Want to create a UIScrollView In Storyboard Using AutoLayout. Horizontal Paged Scrolling Enabled, Dynamic Page Size Adaptability (that is, page size should adapt for iPhone 4s thru iPhone 6 Plus screen size) I'd be thankful if someone would give me a direction as to how I Should proceed to achieve this. I have searched around the web for this but haven't found anything as clear and as accurate to what I want to achieve. A: I solved it myself. Here is the link to my demo of what I wanted to achieve. Hope this helps others too. https://github.com/ArshAulakh59/ScrollAutoLayoutTest Apologies for the delay guys but now I have added the steps to achieve this via video on the github page.
{ "pile_set_name": "StackExchange" }
Q: How do I make sure it's safe to return a pointer from a function Here's my problem: I read here on StackOverflow that it is unsafe sometimes to return pointers to local variables from a function. For example: #include<iostream> using namespace std; int *foo(void) { int x[] = {1,2,3}; return x; } int main() { int *numbers; numbers = foo(); return 0; } I'd like to know if this is unsafe, considering that x being a local array, the memory could be unallocated, what's the better way to achieve the same result? A: I read here on StackOverflow that it is unsafe sometimes to return pointers to local variables from a function. It is always unsafe to return pointers to local variables. Indeed it is wrong to do so, and using this pointer will cause undefined behavior. See also this awesome post. If you want to return data to the calling scope, you could use a std::vector as a copy: std::vector<int> foo(void){ std::vector<int> x = {1,2,3}; // using C++11 initializer list return x; } If it's a fixed length array (always of size 3), you could use std::array instead. Depending on your requirements you may also use a static variable. That is, the variable will never go out of scope, s.t. you can return it safely by reference (or by pointer). Note that you have only one copy. If you modify it, it will remain modified. (Make it const & if it's read only.) std::vector<int>& foo(void) { // this is only instantiated once when the function is first called static std::vector<int> x = {1,2,3}; return x; }
{ "pile_set_name": "StackExchange" }
Q: Problem in Rails scaffold for DATE fields When I use Rails scaffold, I can't access the page to edit fields. It shows me some kind of problem with all DATE fields. Here's the error: can't convert Symbol into String Extracted source (around line #124): 121: </p> 122: <p> 123: <%= f.label :dataDeCadastro %><br /> 124: <%= f.date_select :dataDeCadastro %> And part of the stackTrace: /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/date_helper.rb:564:in `include?' /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/date_helper.rb:564:in `select_date' /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/date_helper.rb:832:in `to_date_select_tag_without_error_wrapping' /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/active_record_helper.rb:268:in `to_date_select_tag' /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/date_helper.rb:179:in `date_select' /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/date_helper.rb:889:in `date_select' app/views/usuarios/edit.html.erb:124 /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/form_helper.rb:313:in `fields_for' /Library/Ruby/Gems/1.8/gems/actionpack-2.2.2/lib/action_view/helpers/form_helper.rb:253:in `form_for' app/views/usuarios/edit.html.erb:3 And the model sql: CREATE TABLE `usuarios` ( `id` int(11) NOT NULL AUTO_INCREMENT, `usuario` varchar(50) DEFAULT NULL, `recebeNews` smallint(1) DEFAULT NULL, `cidade` varchar(30) DEFAULT NULL, `email` varchar(40) DEFAULT NULL, `endereco` varchar(70) DEFAULT NULL, `estado` varchar(3) DEFAULT NULL, `cep` varchar(10) DEFAULT NULL, `numero` varchar(10) DEFAULT NULL, `telefone` varchar(30) DEFAULT NULL, `cnpj` varchar(20) DEFAULT NULL, `cpf` varchar(18) DEFAULT NULL, `inscricaoEstadual` varchar(20) DEFAULT NULL, `rg` varchar(15) DEFAULT NULL, `complemento` varchar(70) DEFAULT NULL, `sexo` varchar(1) DEFAULT NULL, `bairro` varchar(70) DEFAULT NULL, `telefoneResidencial` varchar(10) DEFAULT NULL, `dddTelefoneCelular` varchar(2) DEFAULT NULL, `dddTelefoneComercial` varchar(2) DEFAULT NULL, `dddTelefoneResidencial` varchar(2) DEFAULT NULL, `ramalDoTelefoneComercial` varchar(10) DEFAULT NULL, `telefoneCelular` varchar(10) DEFAULT NULL, `telefoneComercial` varchar(10) DEFAULT NULL, `creditoPessoal` smallint(1) DEFAULT NULL, `descontoPessoal` smallint(1) DEFAULT NULL, `motivoDoBloqueio` varchar(255) DEFAULT NULL, `nomeNaReceitaFederal` varchar(255) DEFAULT NULL, `valorDoCreditoPessoal` double DEFAULT NULL, `valorDoDescontoPessoal` double DEFAULT NULL, `bloqueio` smallint(1) DEFAULT NULL, `dataDeCadastro` datetime DEFAULT NULL, `dataLimiteDoDescontoPessoal` datetime DEFAULT NULL, `situacaoNaReceitaFederal` varchar(255) DEFAULT NULL, `dataDeNascimento` datetime DEFAULT NULL, `senha` varchar(255) DEFAULT NULL, `interior` smallint(1) DEFAULT NULL, `observacao` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=5754 DEFAULT CHARSET=latin1 ; full view source: <% form_for(@usuario) do |f| %> <%= f.error_messages %> <p> <%= f.label :usuario %> <%= f.text_field :usuario %> </p> <p> <%= f.label :cpf, "CPF" %> <%= f.text_field :cpf %> </p> <p> <%= f.label :rg, "RG" %> <%= f.text_field :rg %> </p> <p> <%= f.label :cnpj, "CNPJ" %> <%= f.text_field :cnpj %> </p> <p> <%= f.label :sexo, "Sexo" %><br> <%= f.radio_button :sexo, :M %>M<br> <%= f.radio_button :sexo, :F %>F </p> <p> <%= f.label :dataDeNascimento, "Data de Nascimento" %> <%= f.date_select :dataDeNascimento %> </p> <p> <%= f.label :endereco %> <%= f.text_field :endereco %> </p> <p> <%= f.label :cidade, "Cidade" %> <%= f.text_field :cidade %> </p> <p> <%= f.label :estado, "Estado" %> <%= f.text_field :estado, :maxlength => "2" %> </p> <p> <%= f.label :cep, "CEP" %> <%= f.text_field :cep, :maxlength => "10" %> (00000-000) </p> <p> <%= f.label :telefone, "Telefone" %> <%= f.text_field :telefone %> </p> <p> <%= f.label :email %> <%= f.text_field :email %> </p> <p> <%= f.label :senha, "Senha" %> <%= f.password_field :senha %> </p> <p> <%= f.label :senha_confirmation, "Confirmação da Senha" %> <%= f.password_field :senha_confirmation %> </p> <p> <%= f.label :recebeNews %><br /> <%= f.check_box :recebeNews %> </p> <p> <%= f.submit "Enviar" %> </p> <% end %> What could it be? A: I've found the solution on this link and this one: When in your application you have set the I18n.locale to something different than "en" and you have the following simple code in your view: <%= date_select("user_info", "birthdate") %> You'll get the can't convert Symbol into String for the date_select helper. The problem can be rescued by giving the date_select helper order like this: <%= date_select("user_info", "birthdate", :order => [:day,:month,:year]) %> or by doing order in the yml file usually located at config/locales/your_lang.yml like this date: formats: default: "" long: "" short: "" order: - :year - :month - :day A: This is highly likely to be caused by localization. You have entered a different standard locale than :en (in application.rb or environment.rb), but you have not declared the appropriate translations for month names, causing rails to balk. You can download standard translation files from GitHub.
{ "pile_set_name": "StackExchange" }
Q: How can I tell Rails/HAML to not escape a URL? I have this code: = link_to "unsubscribe instantly", "*|UNSUB|*".html_safe That generates this HTML: <a href="*%7CUNSUB%7C*">unsubscribe instantly</a> The | characters are escaped. That won't work, as I'm sending this HTML to a service that is supposed to replace *|UNSUB|* with an unsubscribe url. Instead, I want Rails/HAML to generate this: <a href="*|UNSUB|*">unsubscribe instantly</a> I went to http://haml-lang.com/try.html and entered %a{:href => "*|UNSUB|*"} unsubscribe and the output was what I was expecting. So I'm guessing this is a Rails thing. UPDATE: I tried this on a new Rails 3.1 application and the pipes aren't being escaped -- which is what I wanted. There's something weird happening with my main rails application that's causing the URLs to be escaped -- looking into it further now. UPDATE: I figured it out. I had some Rack middleware that was running something like: content = Nokogiri(response) # ... processing return content.to_html This was encoding the stuff inside the URLs. I asked a related question here: Preventing Nokogiri from escaping characters in URLs A: I figured it out. I had some Rack middleware that was running something like: content = Nokogiri(response) # ... processing return content.to_html This was encoding the stuff inside the URLs.
{ "pile_set_name": "StackExchange" }
Q: How to fire onListItemClick in Listactivity with buttons in list? I have a simple ListActivity that uses a custom ListAdapter to generate the views in the list. Normally the ListAdapter would just fill the views with TextViews, but now I want to put a button there as well. It is my understanding and experience however that putting a focusable view in the list item prevents the firing of onListItemClick() in the ListActivity when the list item is clicked. The button still functions normally within the list item, but when something besides the button is pressed, I want onListItemClick to be triggered. How can I make this work? A: as I wrote in previous comment solution is to setFocusable(false) on ImageButton. There is even more elegant solution try to add android:descendantFocusability="blocksDescendants" in root layout of list element. That will make clicks onListItem possible and separately u can handle Button or ImageButton clicks Hope it helps ;) Cheers A: I hope I can help here. I assume that you have custom layout for listView items, and this layout consists of button and some other views - like TextView, ImageView or whatever. Now you want to have different event fired on button click and different event fired on everything else clicked. You can achieve that without using onListItemClick() of your ListActivity. Here is what you have to do: You are using custom layout, so probably you are overriding getView() method from your custom adapter. The trick is to set the different listeners for your button and different for the whole view (your row). Take a look at the example: private class MyAdapter extends ArrayAdapter<String> implements OnClickListener { public MyAdapter(Context context, int resource, int textViewResourceId, List<String> objects) { super(context, resource, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { String text = getItem(position); if (null == convertView) { convertView = mInflater.inflate(R.layout.custom_row, null); } //take the Button and set listener. It will be invoked when you click the button. Button btn = (Button) convertView.findViewById(R.id.button); btn.setOnClickListener(this); //set the text... not important TextView tv = (TextView) convertView.findViewById(R.id.text); tv.setText(text); //!!! and this is the most important part: you are settin listener for the whole row convertView.setOnClickListener(new OnItemClickListener(position)); return convertView; } @Override public void onClick(View v) { Log.v(TAG, "Row button clicked"); } } Your OnItemClickListener class could be declared like here: private class OnItemClickListener implements OnClickListener{ private int mPosition; OnItemClickListener(int position){ mPosition = position; } @Override public void onClick(View arg0) { Log.v(TAG, "onItemClick at position" + mPosition); } } Of course you will probably add some more parameters to OnItemClickListener constructor. And one important thing - implementation of getView shown above is pretty ugly, normally you should use ViewHolder pattern to avoid findViewById calls.. but you probably already know that. My custom_row.xml file is RelativeLayout with Button of id "button", TextView of id "text" and ImageView of id "image" - just to make things clear. Regards! A: When a custom ListView contains focusable elements, onListItemClick won't work (I think it's the expected behavior). Just remove the focus from the custom view, it will do the trick: For example: public class ExtendedCheckBoxListView extends LinearLayout { private TextView mText; private CheckBox mCheckBox; public ExtendedCheckBoxListView(Context context, ExtendedCheckBox aCheckBoxifiedText) { super(context); … mText.setFocusable(false); mText.setFocusableInTouchMode(false); mCheckBox.setFocusable(false); mCheckBox.setFocusableInTouchMode(false); … } }
{ "pile_set_name": "StackExchange" }
Q: Why doesnt label display when I have two checkboxes ticked? JavaScript: function Checkbox() { //Deleted parenthesis below, because checked is a property, not a function var FirstClass = document.getElementById("First-Class"); var Standard = document.getElementById("Standard"); if (FirstClass.checked && Standard.checked) || !FirstClass.checked && !Standard.checked) { // document.getElementById("CheckError").textContent = ""; alert("Please"); } else { document.getElementById("CheckError").textContent = "Please Ensure everything is covered."; } } HTML : <header class="main-header"> <!--- Header container for the logo and title test---> <div class="main-logo"><h2><a href="#"><img src="img/main-logo.png"></a></h2></div> <!---Railine Logo--> <h1>ailLine</h1> </header> <input type="checkbox" id="Standard" name="Type" value="Standard"> <label class="light" for="Standard">Standard</label><br> <input type="checkbox" id="First-Class" name="Type" value="First-Class"> <label class="light" for="First-Class">First Class</label><br><br> <label id = "CheckError"></label> <p id="total-cost"></p> <button type = "button" value="checkout" id="checkoutbtn" onclick="Checkbox()" >CHECKOUT</button> <!------------END OF SECOND FORM---------> Hello guys In here I am trying to make a label display if both checkboxes and if both are empty, how can I do this I made an attempt but nothing happens. A: This is working for me: HTML: <input type="checkbox" id="Standard" name="Type" value="Standard"> <label class="light" for="Standard">Standard</label><br> <input type="checkbox" id="First-Class" name="Type" value="First-Class"> <label class="light" for="First-Class">First Class</label><br><br> <label id = "CheckError"></label> <p id="total-cost"></p> <!-- Assign click event on JS script --> <button type = "button" value="checkout" id="checkoutbtn" onclick="myFunction(); createcookie(); AdultNumber(); calculateFare();" >CHECKOUT</button> Javascript: document.getElementById("checkoutbtn").onclick = Checkbox; function Checkbox() { //Deleted parenthesis below, because checked is a property, not a function var FirstClass = document.getElementById("First-Class").checked; var Standard = document.getElementById("Standard").checked; if ((FirstClass && Standard) || (!FirstClass && !Standard)) { // Show the message when only one is checked document.getElementById("CheckError").textContent = "Please Ensure everything is covered."; } else { // Set empty string in other case document.getElementById("CheckError").textContent = ""; } } Now, "FirstClass" and "Standard" variables are boolean, so you don't have to use the .checked property inside the if condition.
{ "pile_set_name": "StackExchange" }
Q: Prove that if $\hat H | a_n\rangle=a_n|a_n\rangle$, then $f(\hat H)| a_n\rangle=f(a_n)|a_n\rangle$ In Quantum Mechanics you have the eigenvalue equation: $$\hat H | a_n\rangle=a_n|a_n\rangle \tag{1}$$ where $\hat H$ is the Hamiltonian operator, $\{|a_n\rangle\}$ is a complete set of eigenstates in Hilbert space and $\{a_n\}$ is the set of the eigenvalues (suppose there is no degeneration). So, how would you show that if $f(x):\Re \to \Re$ (with certain properties to specify later), then follows $$f(\hat H)| a_n\rangle=f(a_n)|a_n\rangle \tag{2}$$ Some books have this as part of the definition of the function of an operator: $f(\hat H)$, but can you derive (2) from (1) using whatever you need (spectral theory, calculus or whatever)? A: Functions of an operator are (or, can be) defined by their power series: $$f(\hat{A}) = f_0 + f_1 \hat{A} + f_2 \hat{A}^2 + \cdots$$ It's easy to prove that $$\hat{H}\lvert a_n\rangle = a_n\lvert a_n\rangle \quad\implies\quad \hat{H}^k\lvert a_n\rangle = a_n^k\lvert a_n\rangle$$ and if you plug that into the power series definition of the function, it will show that $f(\hat{H})\lvert a_n\rangle = f(a_n)\lvert a_n\rangle$.
{ "pile_set_name": "StackExchange" }
Q: MySQL Grouping Order Is it possible to force the order in which a result set is grouped? I have a table with multiple languages in it, and I'm doing a GROUP_CONCAT to get a comma separated list of the product name in each language, for each product_id. However it doesn't seem possible to get MySQL to return that concatenated string in any particular order of language_id's. What I'd like is to be able to order the grouping by language id, so that they'll always come out in a pre-determined order. Is this possible? If so, how? If not possible within the SELECT statement, is there a modification I can make to the table to adjust how the GROUP BY would order the result? A: You can use ORDER BY inside GROUP_CONCAT() function. You can also change the separator, if you don't want to use comma. Further details in MySQL documentation: GROUP_CONCAT() Example: SELECT product_id, GROUP_CONCAT(name ORDER BY language_id SEPARATOR ',' ) AS product_names FROM products_languages GROUP BY product_id ;
{ "pile_set_name": "StackExchange" }
Q: Binary value to float value conversion is not working due to type casting Here i add function from my code which use to generate float number from given binary number. Code: double binary_float(double f) /* Function to convert binary to float.*/ { long integral = 0, floatInt = 0, i = 1, temp1 = 0, k = 1; double floatFract = 0, fractional = 0, floatTotal = 0; //Separating the integral value from the floating point variable integral = (long)f; //Separating the fractional value from the variable fractional = f - (long)f; //Converting binary to decimal floatInt = binary_decimal(integral); //Loop for converting binary to Fractional value while( k < 10000000 && fractional != (double)0 ) { k = k * 10; i = i * 2; temp1 = (long)(fractional * k); printf("temp: %ld, r: %lf\n", temp1, (fractional * k)); floatFract = floatFract + (double)temp1/(double)i; printf("fact: %lf, r: %lf\n", floatFract, ((double)temp1/(double)i)); fractional = fractional - (double)temp1/(double)k; printf("frac: %lf, r: %lf\n", fractional, ((double)temp1/(double)k)); } //Combining both the integral and fractional binary value. floatTotal = floatInt + floatFract; return floatTotal; } long binary_decimal(long n) { long decimal=0, i=0, rem; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(2,i); ++i; } return decimal; } Output: Enter a binary number: 1010.001100 temp: 0, r: 0.011000 fact: 0.000000, r: 0.000000 frac: 0.001100, r: 0.000000 temp: 0, r: 0.110000 fact: 0.000000, r: 0.000000 frac: 0.001100, r: 0.000000 temp: 1, r: 1.100000 fact: 0.125000, r: 0.125000 frac: 0.000100, r: 0.001000 temp: 0, r: 1.000000 fact: 0.125000, r: 0.000000 frac: 0.000100, r: 0.000000 temp: 9, r: 10.000000 fact: 0.406250, r: 0.281250 frac: 0.000010, r: 0.000090 temp: 9, r: 10.000000 fact: 0.546875, r: 0.140625 frac: 0.000001, r: 0.000009 temp: 9, r: 10.000000 fact: 0.617188, r: 0.070312 frac: 0.000000, r: 0.000001 1010.001100 in binary = 10.617188 in float In output you can see temp: 0, r: 1.000000 which says temp1 = 0 which is typecasting of 1.000000 by long. Can any one explain me why this typecasting is not working? A: OP: "temp: 0, r: 1.000000 which says temp1 = 0 which is typecasting of 1.000000 by long." A: Conversion of double to long is working, for double is less than 1.0. Code is printing a rounded value of the double, not its exact value, which is slightly less than 1.0. (long) some_number_slightly_less_than_1 is 0. Try printing the double with more precision "%.20le" instead of "%lf". Given typical IEEE binary64 floating point, when code starts with a double of 1010.001100, code is really starting with a 1010.00109999999995125108..... As to why the wrong answer of 10.617188, I suspect unposted code binary_decimal(); Code has error: // floatFract = floatFract + (double) temp1 / (double) i; floatFract = floatFract + (double) temp1 / (double) k; ... // wrong result of 10.61718750000000000000 // correct result follows 10.00109989999999982047.... // or to 6 decimal places 10.001100 Minor: note that the below code only works for a double f in the range LONG_MIN to LONG_MAX. integral = (long)f;
{ "pile_set_name": "StackExchange" }
Q: How to "run" OSGi fragments on Tomcat? I want to integrate some existing OSGi bundles and fragments in a servlet and run it on Tomcat 7. Following this tutorial http://www.javaworld.com/javaworld/jw-06-2008/jw-06-osgi3.html I managed to run the bundles on the server. I read, that fragments have no life-cycle, so I assumed, I just have to run the bundle and the fragments are found automatically. Nevertheless, when the bundle is started on the server, it seems as if the OSGi fragments are not found. Calling "ss" on the OSGi console, I can see that my bundle is active. The fragment has the status "INSTALLED". 31 ACTIVE myBundle 34 INSTALLED myFragment Since the integration of the fragment in the bundle worked, when I run it in Eclipse (as OSGi platfrom), I assume, that the Manifest.MF files are correct. Is this assumption correct? Or is there another point I missed? Do I need to "start" the fragment somehow? Thanks! A: I just found the answer here: How do I ensure my OSGi fragments get installed before the host bundle? Citation: "One of the most common errors people make in OSGi is trying to start each bundle immediately after it is installed. You must not do this, i.e. you should not start any bundle until after you have installed all bundles that you intend to run."
{ "pile_set_name": "StackExchange" }
Q: Bootstrap: span inside span doesn't display right on Firefox and IE Using this HTML below: <span class="label label-default record"> Total <span class="label badge-number">12</span></span><br> <span class="label label-warning record"> Pending <span class="label badge-number">5</span></span><br> <span class="label label-success record"> Active <span class="label badge-number">6</span></span><br> <span class="label label-important record"> Inactive <span class="label badge-number">1</span></span> and CSS: .record { width: 84px; height: 16px; padding: 3px 0 3px 5px; margin-bottom:2px; } .badge-number { background-color: #666; width: 26px; height: 18px; float: right; text-align: right; margin: -3px 0 0 0; -webkit-border-bottom-left-radius:0; -moz-border-bottom-left-radius:0; border-bottom-left-radius:0; -webkit-border-top-left-radius:0; -moz-border-top-left-radius:0; border-top-left-radius:0; } http://jsfiddle.net/eWSRX/ At left is what I get on Chrome (latest version) and at right is on Firefox (v24) and IE8 screenshot Screenshot from Chrome is what I intended.. A: There's no need to nest elements to get what you're after. Twitter didn't intend for that, and it's causing more headaches than you need. Here's one option: http://jsfiddle.net/eWSRX/1/ <span class="label label-default record"> Total </span> <span class="label badge-number">12</span> ... .label { float: left; /* OR display: inline-block */ height: 18px; padding: 3px; } .record { width: 84px; margin-bottom:2px; -webkit-border-radius: 4px 0 0 4px; -moz-border-radius: 4px 0 0 4px; border-radius: 4px 0 0 4px; } .badge-number { background-color: #666; width: 26px; text-align: right; -webkit-border-radius: 0 4px 4px 0; -moz-border-radius: 0 4px 4px 0; border-radius: 0 4px 4px 0; }
{ "pile_set_name": "StackExchange" }
Q: "mais mal" ou "pior"? Estes dias, disse a um amigo: Tu conduzes mais mal do que eu. E ele respondeu: Não é mais mal é pior. Qual das duas formas é correta? Onde poderíamos usar mais mal e/ou pior e porquê? Estive a ver Mais mal ou pior? - Ciberdúvidas mas não fiquei esclarecido. A: Nos círculos educados do Brasil, se tu disseres "mais mal", serás logo corrigido por alguém, a não ser que logo em seguida venha um verbo adjetivado. mais mal feito, mais mal visto, mais mal encarado, mais mal falada. "Seu trabalho foi o mais mal feito de todos." "Ela é a mulher mais mal falada das redondezas." Da mesma forma, em pt-BR, não dizemos "mais bom", "mais grande", ou "mais pequeno". Todas essas formas são consideradas erradas. Quanto a "faz mais mal à saúde", "mal" nesse caso não é um advérbio e sim um substantivo, sinônimo de "danos". ("Ele pratica o bem.", "Não sabes o mal que ela me fez.") A: Em geral, pior é a resposta correta. Neste contexto, parece-me que o significado não é o mesmo. Mais mal, para mim, significa que os dois conduzem mal, um mais que o outro. Enquanto usar pior não implica que o primeiro condutor conduz mal. A: Normalmente no português original, utiliza-se sempre pior. Mais mal soa sempre mal. Contudo, é utilizado consoante o contexto. Quando as pessoas querem usar mais mal é porque dá sempre para usar pior. Por exemplo: Fazes tudo mais mal que os outros. (Não é que esteja mal escrita a frase, mas apenas serve para ser mais subtil e dócil com a pessoa, porque dizer: Fazes tudo pior que os outros é uma frase mais agressiva, ou seja se digo pior quer dizer que de 0 a 10 a pessoa é um 0, enquanto que dizer mais mal significa que não é bom o suficiente, e é uma abordagem menos bruta e menos direta). Também usa-se 'mais mal' antes dos adjetivos, como: mais mal agradecida; mais mal comportada( se quiséssemos qualificar o comportamento com pior seria: tem o pior comportamento[e comportamento é um nome])
{ "pile_set_name": "StackExchange" }
Q: Looping through json passed through to assemble partial as variable I'm having trouble trying to loop through my JSON data with an a assemble site setup in the following structure: -src --content ---index.hbs --data ---steps-data.json --partial ---steps.hbs The index.hbs in the content calls the partial passing through the object like so: {{> steps steps-data}} My steps-data.json file looks like so: { "steps":[{ "index": 1, "title": "Find a product", "description": "Go to a product page and click on the +PriceTrack short cut to add to your list." },{ "index": 2, "title": "Track its price", "description": "Go to a product page and click on the +PriceTrack short cut to add to your list." },{ "index": 3, "title": "Purchase", "description": "Go to a product page and click on the +PriceTrack short cut to add to your list." }] } In my steps.hbs i've tried looping through the JSON data but its not. <div class="g-col g-span4"> {{#each steps-data.steps}} <div class="working-step"> <span class="number"></span><h3>{{title}}</h3> </div> <p>{{description}}</p> {{/each}} </div> The problem I have is that its not looping through and not sure what I'm doing wrong. A: Since you passed steps-data into the partial as it's context, you can access steps directly or with this.steps: <div class="g-col g-span4"> {{#each this.steps}} <div class="working-step"> <span class="number"></span><h3>{{title}}</h3> </div> <p>{{description}}</p> {{/each}} </div>
{ "pile_set_name": "StackExchange" }
Q: can .bat windows file can be configured on control-M I have the java program which will be triggered from windows .bat file (having call to java program and requires JRE 1.6 on the client machine(calling machine) to run the java program. Is that possible to configure this job on control-M? I am not sure how the control- M configuration of a job will be done, hence wanted to know if we will be able to install JRE 1.6 or above on the Control-M machine and is possible to run the .bat file from control-M. A: Yes, It's possible to run a bat from Control-M and get the return code to stablish the ending state of the Job. Complete information about how it works in the BMC Control-M Manual: http://www.scheduler-usage.com/document/Version/630/Books/MAW620300AG52365.pdf JRE Must be installed in the machine before to work with good performance and with a correct environment. You probably can check if JRE 1.6 is installed in the bat and install it but it's a complicated process with probably thirdparty tools and use of silent JRE install. Not recommended, it's better to have JRE installed as requirement to run the job.
{ "pile_set_name": "StackExchange" }
Q: Dataflow pipeline reading csv from GCS and writing to BigBuery with calls to Vision and NL API I want to write a Dataflow program(Java and maven Implementation). Here are the steps I want to perform: Dataflow should read a csv file from google cloud storage. The csv file is in following format: Product Name, Image URL, Category, Description1, Description2 Sakura 30062 6-Piece Pigma Micron Ink Pen Set, https://images-na.ssl-images-amazon.com/images/I/71CkvpG3FEL.SY355.jpg, Arts, Includes 1 of size: #005 (0.20mm) CCbetter Mini Hot Melt Glue Gun with 25pcs Glue Sticks High Temperature Melting Glue Gun Kit Flexible Trigger for DIY Small Craft Projects&Sealing and Quick Repairs(20-watt, Blue), https://images-na.ssl-images-amazon.com/images/I/61iFrMg4%2B3L.SY355.jpg, Safety and comfortable power switch with LED light mode. With detachable and flexible support to keep the gun stable and upright, With high quality and insulated nozzle there's no deforming of the gun even long-term use under 500℉. . . . . For each of the rows in csv, I need to pick the picture URL and run vision API and get top 2 labels(e.g. we get labels L1 and L2 from vision API for first product/row and L3 and L4 for second product/row) For each of the row in csv, I need to concatenate product name, category, description1 and description2 and pass it to NL API. From the response of NL API I need to pick top 2 Entities under Consumer Goods category (e.g. we get E1 and E2 from first row and E3 and E4 for second row) I need to create following structure from retrieved response: Product Name, Topic Sakura 30062 6-Piece Pigma Micron Ink Pen Set, L1 Sakura 30062 6-Piece Pigma Micron Ink Pen Set, L2 Sakura 30062 6-Piece Pigma Micron Ink Pen Set, E1 Sakura 30062 6-Piece Pigma Micron Ink Pen Set, E2 CCbetter Mini Hot Melt Glue Gun with 25pcs Glue Sticks High Temperature Melting Glue Gun Kit Flexible Trigger for DIY Small Craft Projects&Sealing and Quick Repairs(20-watt, Blue), L3 CCbetter Mini Hot Melt Glue Gun with 25pcs Glue Sticks High Temperature Melting Glue Gun Kit Flexible Trigger for DIY Small Craft Projects&Sealing and Quick Repairs(20-watt, Blue), L4 CCbetter Mini Hot Melt Glue Gun with 25pcs Glue Sticks High Temperature Melting Glue Gun Kit Flexible Trigger for DIY Small Craft Projects&Sealing and Quick Repairs(20-watt, Blue), E3 CCbetter Mini Hot Melt Glue Gun with 25pcs Glue Sticks High Temperature Melting Glue Gun Kit Flexible Trigger for DIY Small Craft Projects&Sealing and Quick Repairs(20-watt, Blue), E4 . . . . I want to write this grid(structure in step 4) to Bigquery table I am new to Dataflow so any help, code snippet or whole source code or reference is highly appreciated A: You should start by reading one of the quick start guides, and taking a look at some of the example pipelines. Based on your description, a high-level outline might be: Use TextIO.read to read content from GCS. Note that it doesn't support ignoring the header, so you'll likely need to detect and drop it yourself. Write a DoFn that uses the vision API on the URL from each row of the file. You could even separate this into multiple DoFns -- one to transform the row into a URL, then a DoFn to use the vision API, then a DoFn to extract the top two tags. Write another DoFn or series of DoFns that performs the concatenation and uses the NL API. Write another DoFn or series of DoFns that generate rows with your desired output format as TableRows. Use a BigQueryIO.write transform to write those to BigQuery.
{ "pile_set_name": "StackExchange" }
Q: iOS: access device microphone in background app Im wondering, is there a way for an app to access the Microphone of an iDevice while running in the background (The device may or may not be locked)? I need to listen to the audio input and do some sound recognition. Cheers from Mexico A: According to Apple's developer page, you can use the "audio" permission, which gives this access: The app plays audible content to the user or records audio while in the background. (This content includes streaming audio or video content using AirPlay.)
{ "pile_set_name": "StackExchange" }
Q: Byte code stack versus three address When designing a byte code interpreter, is there a consensus these days on whether stack or three address format (or something else?) is better? I'm looking at these considerations: The objective language is a dynamic language fairly similar to Javascript. Performance is important, but development speed and portability are more so for the moment. Therefore the implementation will be strictly an interpreter for the time being; a JIT compiler may come later, resources permitting. The interpreter will be written in C. A: Read The evolution of Lua and The implementation of Lua 5.0 for how Lua changed from a stack-based virtual machine to a register-based virtual machine and why it gained performance doing it. A: Experiments done by David Gregg and Roberto Ierusalimschy have shown that a register-based bytecode works better than a stack-based bytecode because fewer bytecode instructions (and therefore less decoding overhead) are required to do the same tasks. So three-address format is a clear winner. A: Take a look at the OCaml bytecode interpreter - it's one of the fastest of its kind. It is pretty much a stack machine, translated into a threaded code on loading (using the GNU computed goto extension). You can generate a Forth-like threaded code as well, should be relatively easy to do. But if you're keeping a future JIT compilation in mind, make sure that your stack machine is not really a full-featured stack machine, but an expression tree serialisation form instead (like .NET CLI) - this way you'd be able to translate your "stack" bytecode into a 3-address form and then into an SSA.
{ "pile_set_name": "StackExchange" }
Q: AngularJS Filter throwing "Object Uncaught" error when injected When trying to add a set of filters to my Serenity app (https://github.com/jfox015/Serenity), I get an "Uncaught Object" error when trying to inject a filter into my app. When I remove the filters code from the app, it works fine. Can't figure out what's wrong with the filters so that they're not be recognized as valid resources. I had them as part of the global module and then a separate module and it still fails. Here's the relevant code: Filter code stored in app/src/admin/AdminFilters.js: 'use strict'; angular.module('AdminFilters', ['USER_ROLES']) .filter('userRoleFilter', ['USER_ROLES', function(USER_ROLES) { return function(input) { return USER_ROLES[input]; }; } ]) .filter('dateJoinedFilter', function() { return function(input) { var date = new Date(input); return (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear(); }; } ) ; Angular App Declaration in app/src/app.js: var angApp = angular.module("serenityApp", ['ngRoute', 'ngResource', 'angular-md5', 'AdminFilters']) Usage in my Admin code (Abridged) in app/src/admin/adminUsersList.html: <tbody> <tr data-ng-if="users" data-ng-repeat="user in users"> <td>{{ user.name }}</td> <td>{{ user.role | userRoleFilter }}</td> <td>{{ user.dateJoined | dateJoinedFilter }}</td> <td>{{ user.group }}</td> </tr> <tr data-ng-if="!users"> <td colspan="4">No users were found.</td> </tr> </tbody> The relevant JS files are all included in the index.html file as well: <script src="app/src/admin/AdminFilters.js" type="text/javascript"></script> <script src="app/src/admin/AdminServices.js" type="text/javascript"></script> <script src="app/src/admin/AdminController.js" type="text/javascript"></script> A: Is the USER_ROLES in the AdminFilters, a module or constant? If it is a constant belonging to another module then I believe it cannot be injected in AdminFilters module.
{ "pile_set_name": "StackExchange" }
Q: What is the difference of declaration of a variable in a loop and before the loop? Look at this example: int i; for (i=1;i....... and this: for (int i=1;i........ What's the difference between them? A: The first one declares the variable in the scope outside of the loop; after the loop has ended, the variable will still exist and be usable. The second one declares the variable such that it belongs to the scope of the loop; after the loop, the variable ceases to exist, preventing the variable from being inadvertantly/mistakenly used. In C99, C++, Java, and other similar languages, you will find mostly the second syntax as it is safer -- the loop index belongs to the loop and isn't modified / shared elsewhere. However, you will see a lot of the former in older C code, as ANSI C did not allow the loop variable to be declared in the loop like that. To give an example: int i; // ... lots of stuff for ( i = 0; i < 5; i++ ){ printf("%d\n",i); // can access i; prints value of i } printf("%d\n",i); // can access i; prints 5 By contrast: for (int i = 0; i < 5; i++ ){ std::cout << i << std::endl; // can access i; prints value of i } std::cout << i << std::endl; // compiler error... i not in this scope
{ "pile_set_name": "StackExchange" }
Q: does $ab$ divide $(ab-1)!$? i am interested in following thing, that for $a \gt 2$ , $b \gt2$, $ab$ divides $(ab-1)!$ ? I can take some simple example, for example $(3,3)$,or $(3,5)$ and show that this is true by this way; but I need ways to proof it by induction or by algebra maybe,how can i do it? $$(ab-1)! =1\times 2\times 3\times 4\times\cdots\times(ab-1)$$ my logic is that, because we are trying to calculate $(ab-1)!$, then we can find some pair of numbers, with by multiply together will cancel $ab$, because each $a$ and $b$ are less then result of this factorial,this is just a human logic,how to proof it by mathematics logic? A: Without loss of generality, let $a\leq b$. First, consider the case where $a<b$. Since $a,b>2$ ,$ab >2a$ and consequently $ab-1 \geq a$. The same argument shows that $ab-1 \geq b$. So, $a$ and $b$ will both occur in the product $(ab-1)!=1\times 2\times3\times \cdots \times a\times \cdots \times b\times (ab-1)$ for all $a,b > 2$. The case when $a=b$ is much more subtle. Since $a=b$, $(ab-1)!=(a^2-1)!=1\times 2\times3\times \cdots \times a\times \cdots (ab-1)$, so we know that $a$ divides $(a^2-1)$. We use the hypothesis that $a>2$ to deduce that $a^2>2a. \implies a^2-1 \geq 2a$. So $2a$ is also in the product $1\times 2\times3\times \cdots \times a\times \cdots (ab-1)$. Also note that $a$ is distinct from $2a$ for all non-zero integers. So, use this to summarize that $a^2|(a^2-1)!$.
{ "pile_set_name": "StackExchange" }
Q: Why does a module compile by itself but fail when used from elsewhere? I have a Perl module that appears to compile fine by itself, but is causing other programs to fail compilation when it is included: me@host:~/code $ perl -c -Imodules modules/Rebat/Store.pm modules/Rebat/Store.pm syntax OK me@host:~/code $ perl -c -Imodules bin/rebat-report-status Attempt to reload Rebat/Store.pm aborted Compilation failed in require at bin/rebat-report-status line 4. BEGIN failed--compilation aborted at bin/rebat-report-status line 4. The first few lines of rebat-report-status are ... 3 use Rebat; 4 use Rebat::Store; 5 use strict; ... A: Edit (for posterity): Another reason for this to occur, and perhaps the most common reason, is that there is a circular dependency among the modules you are using. Look in Rebat/Store.pm for clues. Your log says attempt to reload was aborted. Maybe Rebat already imports Rebat::Store, and Rebat::Store has some package-scope check against being loaded twice. This code demonstrates the kind of situation I mean: # m1.pl: use M1; use M1::M2; M1::M2::x(); # M1.pm package M1; use M1::M2; 1; # M1/M2.pm package M1::M2; our $imported = 0; sub import { die "Attempt to reload M1::M2 aborted.\n" if $imported++; } sub x { print "42\n" } 1; $ perl m1.pl Attempt to reload M1::M2 aborted. BEGIN failed--compilation aborted at m1.pl line 3. The code will compile (and print 42) if you just remove the use M1::M2 line in m1.pl. In your case, you might not need to explicitly use Rebat::Store in your program. A: perldoc perldiag: Attempt to reload %s aborted. (F) You tried to load a file with "use" or "require" that failed to compile once already. Perl will not try to compile this file again unless you delete its entry from %INC. See "require" in perlfunc and "%INC" in perlvar.
{ "pile_set_name": "StackExchange" }
Q: Remove leading and trailing zeros from multidimensional list in Python I have a list such as: my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]] I need to remove only the leading and trailing zeros from the inner lists, so that I end up with: new_list = [[1,2,2,1], [1,2], [1,2], [1,0,0,1]] Any help much appreciated. A: for sub_list in my_list: for dx in (0, -1): while sub_list and sub_list[dx] == 0: sub_list.pop(dx) A: my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]] my_list =[np.trim_zeros(np.array(a)) for a in my_list] >>> my_list [array([1, 2, 2, 1]), array([1, 2]), array([1, 2]), array([1, 0, 0, 1])] If you want numpy. Can also just do: >>> my_list =[np.trim_zeros(a) for a in my_list] >>> my_list [[1, 2, 2, 1], [1, 2], [1, 2], [1, 0, 0, 1]] Some timings: Numpy >>> timeit.timeit('my_list =[np.trim_zeros(a) for a in my_list]',setup='import numpy as np; my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]', number=10000) 0.08429217338562012 Numpy w/convert array >>> timeit.timeit('my_list =[np.trim_zeros(np.array(a)) for a in my_list]',setup='import numpy as np; my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]', number=10000) 0.6929900646209717 So really best off not to convert at np.array unless you are going to use that type later. A: new_list = [map(int,"".join(map(str,x)).strip("0")) for x in my_list] might work >>> new_list = [map(int,"".join(map(str,x)).strip("0")) for x in my_list] >>> new_list [[1, 2, 2, 1], [1, 2], [1, 2], [1, 0, 0, 1]]
{ "pile_set_name": "StackExchange" }
Q: array of arrays: infinite loop I am dynamically adding/removing elements using javascript & jQuery. For some reason my inner for loop is not exiting. The counter continues to climb past the arrays length, and continues to add elements until the browser crashes. When stepping through in Firefox debugger groupList[i].length shows the correct value. Any ideas why the internal loop never returns false? var $j = jQuery.noConflict(); // array of arrays var groupList = []; groupList[groupList.length] = ["Japan", "Honda", "Toyota", "Nissan"]; groupList[groupList.length] = ["America", "Ford", "Dodge", "Chevrolet"]; // loop that creates a radio button from the first element in each array for (var i = 0; i < groupList.length; ++i) { $j("#groupBtns").append("<label class=\"btn btn-primary active\" id=\"btn" + groupList[i][0] + "\"><input type=\"radio\">" + groupList[i][0] + "</label>"); } // function to add second group of radio button for remaining elements in selected array function groupClick(group) { for (var i = 0; i < groupList.length; ++i) { if (group == groupList[i][0]) { // -- this is the infinite loop -- // for (var o = 1; 0 < groupList[i].length; ++o) { $j("#subGroupBtns").append("<label id=\"btn" + groupList[i][o] + "\" class=\"btn btn-primary\"><input type=\"radio\">" + groupList[i][o] + "</label>"); } } } } // event listener $j("#groupBtns").on('click', function (e) { groupClick($j(e.target).text()) }); note: the arrays will not always be the same length so I cannot use a static terminator for the loop. A: You have a typo : for (var o = 1; 0 < groupList[i].length; ++o) { You are doing 0 < groupList[i].length, always resulting to true if there's a length. Should be : for (var o = 1; o < groupList[i].length; ++o) {
{ "pile_set_name": "StackExchange" }
Q: Who is the most powerful character Hulk has defeated ever? I am asking it just out of curiosity. In The Marvel universe/multiverse who is the most powerful character whom The Incredible Hulk has defeated ever on his own (without someone's help)? This question just popped in my head when I was reading this post. "Both have shown the ability to fight metahuman opponents of vast power and have fought and defeated some of the most powerful beings in the Marvel Universe." A: Sentry, Gladiator, Thor, the Abomination and Red Hulk, in that order! Before the arguments start, Gladiator has opened black hole with his hands and also destroyed planets with his hands so I would suggest he is more powerful than Thor. I thought I would mention that Gladiator is vulnerable to certain forms of radiation. During this legendary battle Hulk realises this when he puts his hands on Gladiator's head, then tosses him into a reactor core.
{ "pile_set_name": "StackExchange" }
Q: Can we change url from https to http from iframe loaded inside base url? Facebook App page will get a SSL error when coming from secure hypertext protocol(https)) Facebook account to non secure(http) Facebook App Page, which happens due to lack of SSL Certificate in Facebook App hosted server. I am trying to change base url from httpsto http to avoid SSL error. Is it possible to change base url from https to http from iframe? A: Is it possible to change base url from https to http from iframe? Even if it is, that’s no solution to your problem – because the iframe content will be pulled over HTTPS first, if the user is browsing Facebook over HTTPS – and since you app does not support HTTPS, this will fail already. So you will not even get to a point where code from your app will be loaded, let alone executed, in this scenario. You’ll have to get an SSL certificate for your app domain.
{ "pile_set_name": "StackExchange" }
Q: How to check Elasticsearch cluster health? I tried to check it via curl -XGET 'http://localhost:9200/_cluster/health' but nothing happened. Seems it's waiting for something. The console did not come back. Had to kill it with CTRL+C. I also tried to check for existing indices via curl -XGET 'http://localhost:9200/_cat/indices?v' Same behavior as above. A: To check on elasticsearch cluster health you need to use curl localhost:9200/_cat/health More on the cat APIs here. I usually use elasticsearch-head plugin to visualize that. You can find it's github project here. It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head and then you can open localhost:9200/_plugin/head/ in your web brower. You should have something that looks like this : A: You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch: $ curl -XGET 'localhost:9200/_cluster/health?pretty' This will give you the status and other related data you need. { "cluster_name" : "xxxxxxxx", "status" : "green", "timed_out" : false, "number_of_nodes" : 2, "number_of_data_nodes" : 2, "active_primary_shards" : 15, "active_shards" : 12, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0, "delayed_unassigned_shards" : 0, "number_of_pending_tasks" : 0, "number_of_in_flight_fetch" : 0 } A: The _cluster/health API can do far more than the typical output that most see with it: $ curl -XGET 'localhost:9200/_cluster/health?pretty' Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well. Examples all the indices health $ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50 { "cluster_name" : "rdu-es-01", "status" : "green", "timed_out" : false, "number_of_nodes" : 9, "number_of_data_nodes" : 6, "active_primary_shards" : 1106, "active_shards" : 2213, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0, "delayed_unassigned_shards" : 0, "number_of_pending_tasks" : 0, "number_of_in_flight_fetch" : 0, "task_max_waiting_in_queue_millis" : 0, "active_shards_percent_as_number" : 100.0, "indices" : { "filebeat-6.5.1-2019.06.10" : { "status" : "green", "number_of_shards" : 3, "number_of_replicas" : 1, "active_primary_shards" : 3, "active_shards" : 6, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 }, "filebeat-6.5.1-2019.06.11" : { "status" : "green", "number_of_shards" : 3, "number_of_replicas" : 1, "active_primary_shards" : 3, "active_shards" : 6, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 }, "filebeat-6.5.1-2019.06.12" : { "status" : "green", "number_of_shards" : 3, "number_of_replicas" : 1, "active_primary_shards" : 3, "active_shards" : 6, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 }, "filebeat-6.5.1-2019.06.13" : { "status" : "green", "number_of_shards" : 3, all shards health $ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50 { "cluster_name" : "rdu-es-01", "status" : "green", "timed_out" : false, "number_of_nodes" : 9, "number_of_data_nodes" : 6, "active_primary_shards" : 1106, "active_shards" : 2213, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0, "delayed_unassigned_shards" : 0, "number_of_pending_tasks" : 0, "number_of_in_flight_fetch" : 0, "task_max_waiting_in_queue_millis" : 0, "active_shards_percent_as_number" : 100.0, "indices" : { "filebeat-6.5.1-2019.06.10" : { "status" : "green", "number_of_shards" : 3, "number_of_replicas" : 1, "active_primary_shards" : 3, "active_shards" : 6, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0, "shards" : { "0" : { "status" : "green", "primary_active" : true, "active_shards" : 2, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 }, "1" : { "status" : "green", "primary_active" : true, "active_shards" : 2, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 }, "2" : { "status" : "green", "primary_active" : true, "active_shards" : 2, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 0 The API also has a variety of wait_* options where it'll wait for various state changes before returning immediately or after some specified timeout.
{ "pile_set_name": "StackExchange" }
Q: How to organize semaphors for writing several java processes to one text file We have several Java processes that write to one text file from time to time. These are not threads of the same virtual machine, but separate java.exe processes that are running from command line. These processes write to the same log file. We used canWrite... while (!Log.canWrite()) { System.out.println("File: " + LogPath + " is locked, waiting..."); Thread.sleep(2000); } ... but it seems don't work. We get the following error: The process cannot access the file because it is being used by another process) at java.io.FileOutputStream.openAppend(Native Method). The Question: what are the best practices for organizing semaphors in sutiations like this? It would be great if the solution wasn't too resource consuming, thus hugely affecting the total performance. A: You can synchronize access to the file using FileChannel.lock(). You can obtain a FileChannel from FileOutputStream. EDIT But in your case it will be solving a wring problem. What you need is a centralized logging server. Refer to this question for more details: Centralised Java Logging
{ "pile_set_name": "StackExchange" }
Q: What Is The Purpose of Negative Modulus Operator Results? I was previously under the (naive) assumption that the modulus operator returned the remainder of division. I was apparently wrong, as -2 % 5 returns 3. I would have thought that 5 divides -2 zero times with -2 as the remainder. Now I understand the mechanics of how this operation is performed, but my question is why? Could someone give me a link to something that explains why modulus and remainder are not synonymous, or an example of a situation where it would be useful? A: The result is entirely correct. Modular arithmetic defines the following (I'll use "congruent" since I can't type the equal sign with three lines) a congruent b mod c iff a-b is a multiple of c, i.e. x * c = (a-b) for some integer x. E.g. 0 congruent 0 mod 5 (0 * 5 = 0-0) 1 congruent 1 mod 5 (0 * 5 = 1-1) 2 congruent 2 mod 5 (0 * 5 = 2-2) 3 congruent 3 mod 5 (0 * 5 = 3-3) 4 congruent 4 mod 5 (0 * 5 = 4-4) 5 congruent 0 mod 5 (1 * 5 = 5-0) 6 congruent 1 mod 5 (1 * 5 = 6-1) ... The same can be extended to negative integers: -1 congruent 4 mod 5 (-1 * 5 = -1-4) -2 congruent 3 mod 5 (-1 * 5 = -2-3) -3 congruent 2 mod 5 (-1 * 5 = -3-2) -4 congruent 1 mod 5 (-1 * 5 = -4-1) -5 congruent 5 mod 5 (-1 * 5 = -5-0) -6 congruent 4 mod 5 (-2 * 5 = -6-4) -7 congruent 3 mod 5 (-2 * 5 = -7-3) ... As you can see, a lot of integers are congruent 3 mod 5: ..., -12, -7, -2, 3, 8, 13, ... In mathematics, the set of these numbers is called the equivalence class induced by the equivalence relation "congruence". Our understanding of the remainder and the definition of the "mod" function are based on this equivalence class. The "remainder" or the result of a mod computation is a representative element of the equivalence class. By declaration we have chosen the smallest non-negative element (so -2 is not a valid candidate). So when you read -2 mod 5 = x this translates to "Find the smallest non-negative x so that there exists an integer y with y * 5 = -2 - x", in concordance with the definition of congruence. The solution is y=1 and x = 3 as you can see by simply trying out other values for y.
{ "pile_set_name": "StackExchange" }
Q: TypeScript generics: argument type inference Consider the following code: function ensure<TModel, TValue>(accessor: { (obj: TModel): TValue; }) { } interface Person { firstName: string; lastName: string; } ensure((p: Person) => p.firstName); // <-- this works ensure<Person>(p => p.firstName); // <-- this does not work Why is the last line a syntax error? Supplied parameters do not match any signature of call target. Why is p inferred to be of type any instead of Person? Here's a link to the code in the TypeScript playground. A: (another edit: partial type parameter inference was scrapped/delayed and never made it into TS3.1 or any version since up to and including TS3.7. Oh well) EDIT: an upcoming feature of TypeScript 3.1 will allow partial type argument inference (making the example you cited work), see the pull request for more details. Original answer (applicable to TypeScript < 3.1): The reason the first example works is because both generics are inferred by the compiler from the types of the passed in anonymous lambda function. Unfortunately, in when consuming generic functions in TypeScript, it's all or nothing -- you have to provide either: types of all generics of the matching function's signature, or no generics, if you want the compiler to "guess" the function signature that best matches your call, while inferring the types automatically (if such inference is at all possible) Note that if a type cannot be inferred it is by default assumed to be of type: Object, e.g.: function example<T>(a: any): T { return a as T; } let test = example(123); The variable test in the above example, will be of type {}. Specifying both generic types or specifying the type of the parameter in the method are both proper ways to handle this: ensure<Person, string>(p => p.firstName); ensure((p: string) => p.firstName); The error you cite is correct, in that: no signature that takes in only one generic exists for the function ensure. The reason for this is that you can have functions with alternative signatures that take a different number of generic type parameters: interface Example { ensure<TModel, TValue>(accessor: { (obj: TModel): TValue; }): TValue; ensure<TModel>(accessor: { (obj: TModel): any; }): any; } interface Person { firstName: string; lastName: string; } let test: Example; // the method 'ensure' has now 2 overloads: // one that takes in two generics: test.ensure<Person, string>((p: Person) => p.firstName); // one that takes only one generic: test.ensure<Person>(p => p.firstName); // when not specified, TypeScript tries to infer which one to use, // and ends up using the first one: test.ensure((p: Person) => p.firstName); Playground of the above. If TypeScript did not enforce signature matching, it wouldn't know which signature it should choose. Now to answer the other part of your question: why is p assumed to be any when the function is called without explicitly stating the generics: One reason is that the compiler cannot make any assumptions as to its possible type, TModel is unconstrained and can literally be anything, thus the type of p is any. You could constrain the generic method to an interface, like this: ensure<TModel extends Person, TValue>(accessor: { (obj: TModel): TValue; }); Now, if you call that function without specifying the type of the parameter or types of the generics, it will be correctly inferred to Person: ensure(p => p.firstName); // p is now Person Hope this fully answers your question.
{ "pile_set_name": "StackExchange" }
Q: List view in jquery I am following this youtube video https://www.youtube.com/watch?v=ZwqTsxyhQAU and trying to make a simple webpage with a listview. However, I have followed the video exactly and have the same code, however I am not getting the same listview as in the video. Please can someone help me out; Below are my screenshots: What I should have: But instead, I am getting this: Code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Test</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> </head> <body> <header data-role="header"> <h1>List App</h1> </header> <!--Article, main text for the web page--> <article data-role="content"> <ul data-role="listview"> <li> <a href="#test"> <h1>This is a test</h1> <img src="Images/test.png" alt="Test image" /> <p>This is a image test to see if it works</p> </a> </li> <li> <a href="#test"> <h1>This is a test 2</h1> <img src="Images/test.png" alt="Test image" /> <p>This is a image test 2 to see if it works</p> </a> </li> </ul> </article> <!--Footer here--> <footer data-role="footer"> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">Photos</a></li> <li><a href="#">Info</a></li> </ul> </nav> </footer> </body> </html> A: The version used in the video is old and you're using latest release 1.4. The image should be first child of the anchor. <li> <a href="#test"> <img src="test.jpg" alt="Welcome to JS Bin"> <h1>This is a test 2</h1> <p>This is a image test 2 to see if it works</p> </a> </li>
{ "pile_set_name": "StackExchange" }
Q: PCR Accuracy Error in MPEG TS What is PCR Accuracy Error? I am developing application which extracts particular programs from TS, muxes them, makes stream CBR and transmits them. To make stream CBR, I am inserting NULL packets in output TS. But on analyser I get errors like PCR-Accuracy_error. What can cause this error. I think my logic add NULLs to make CBR is perfect. You can see this in attached picture. Please help me on this. A: Are you using PID 0x1FFF for the null packets? Or are you creating video packets with empty payloads? I could see this problem occurring if you are creating video packets with no payload.
{ "pile_set_name": "StackExchange" }
Q: Rails hidden_field name I have such code: = hidden_field(:user_id, nil, :value => params[:user_id]) But it is generating such html: <input id="user_id_" name="user_id[]" type="hidden" value="1"> But what i need to write, to generate such html code: <input id="user_id" name="user_id" type="hidden" value="1"> Without any arrays? Also, if i write only one input, without any form tags, will i see this value in params, or i must to write full: form_tag, then there hidden field? A: Use hidden_field_tag hidden_field_tag 'user_id', 1 # => <input id="user_id" name="user_id" type="hidden" value="1" />
{ "pile_set_name": "StackExchange" }
Q: Как правильно осуществить взаимодействие между абстрактным и наследуемыми классами в JAVA? Всем добрый день! Столкнулся с проблемой при решении задачи, суть которой в осуществлении правильного взаимодействия между классами: запутался в прописании методов. Прошу Вашей помощи! Вот условия задачи: Создаю абстрактный класс Account с тремя методами. Добавляю классы Сберегательный, Кредитный, Расчетный (SavingsAccount, CreditAccount, CheckingAccount соответственно) как потомков класса Счет. В них переопределяю методы. Каждый из них должен хранить баланс. Со сберегательного счета нельзя платить, только переводить и пополнять. Также сберегательный не может уходить в минус. Кредитный не может иметь положительный баланс – если платить с него, то уходит в минус, чтобы вернуть в 0, надо пополнить его. Расчетный может выполнять все три операции, но не может уходить в минус. Нужно продемонстрировать работу счетов. Также создать три переменные типа Account и присвоить им три разных типа счетов. Большинство методов оставил незаполненными. Вот мой код: public abstract class Account { protected int amount; protected int balance; public Account(int amount, int balance) { this.amount = amount; this.balance = balance; } void pay(int amount) { } void transfer(Account account, int amount) { } void addMoney(int amount) { } } public class SavingsAccount extends Account { public SavingsAccount(int amount, int balance) { super(amount, balance); } @Override void pay(int amount) { super.pay(amount); } @Override void transfer(Account account, int amount) { if (balance -= amount) { System.out.println("Баланс не может быть отрицательным!"); } } @Override void addMoney(int amount) { super.addMoney(amount); } } public class CreditAccount extends Account { public CreditAccount(int amount, int balance) { super(amount, balance); } @Override void pay(int amount) { super.pay(amount); } @Override void transfer(Account account, int amount) { super.transfer(account, amount); } @Override void addMoney(int amount) { super.addMoney(amount); } } public class CheckingAccount extends Account { public CheckingAccount(int amount, int balance) { super(amount, balance); } @Override void pay(int amount) { super.pay(amount); } @Override void transfer(Account account, int amount) { super.transfer(account, amount); } @Override void addMoney(int amount) { super.addMoney(amount); } } A: Начнем с того, что если у вас есть какой-то счет с которого нельзя что-то делать, то это явный признак того, что их нужно разбить. Ну конечно можно к примеру в вашем сберегательном счете переопределить метод pay() который будет бросать Exception или что-то вроде того, но это очень плохая практика. Вы можете создать родительский класс вроде такого: public abstract class Account { protected int balance; public Account(int balance) { this.balance = balance; } abstract void transfer(Account account, int amount); abstract void addMoney(int amount); } Если базовый класс не задает никакого общего поведения для наследников, то методы лучше сделать абстрактными. И интерфейс: interface Payment { void pay(int amount); } В каждом из наследников переопределить методы, например так: public class CreditAccount extends Account implements Payment { public CreditAccount(int balance) { super(balance); } @Override void pay(int amount) { balance = balance - amount; // возможно тут более сложная логика может быть } @Override void transfer(Account account, int amount) { account.addMoney(amount); balance = balance - amount; // тут может быть какая-то логика по обработке лимитов кредитки } @Override void addMoney(int amount) { if(balance + amount > 0) { // обработать ситуацию когда больше пополнять нельзя. Может быть вернуть остаток или запретить операцию } else { balance = balance + amount } } } ... public class SavingsAccount extends Account { public SavingsAccount(int balance) { super(balance); } @Override void transfer(Account account, int amount) { account.addMoney(amount); if (balance < amount) { // обработать ошибку - недостаточно средств } else { balance = balance - amount; // тут может быть какая-то логика по обработке лимитов кредитки } } @Override void addMoney(int amount) { balance = balance + amount } } Это в общих чертах, но выглядеть должно примерно так. Конечно можно вместо интерфейса сделать еще один абстрактный класс который будет наследоваться от Account и в нем будет метод pay() назвать его к примеру PaymentAccount. И сберегательный счет будет наследоваться от Account а кредитный и расчетный будут от PaymentAccount, но если в этом нет необходимости то всегда стоит предпочитать интерфейсы абстрактным классам. P.S. Я не совсем понял в чем разница полей amount и balance, поэтому оставил только одно. Но от этого суть не меняется. A: Я бы сделал по другому. Попробуйте так public abstract class Account { private int amount; private int balance; public Account(int amount, int balance) { this.amount = amount; this.balance = balance; } public int getAmount() { return this.amount;} void setAmount(int amount) { this.amount = amount;} // getter setter для баланса } // реализуйте интерфейсы Pay,Transfer, Add для каждого класса public class SavingsAccount extends Account implements Pay,Transfer, Add { } public class CheckingAccount extends Account implements Pay,Transfer, Add { } public class CreditAccount extends Account implements Pay,Transfer, Add { } Реализуйте только нужные интерфейсы для ваших классов и почитайте принципы SOLID. Почитайте повнимательней принцип постановки Liskov. Почитав его вы поймете что не надо плодить классы если нет в них необходимости.
{ "pile_set_name": "StackExchange" }
Q: How to set multiple properties in CSS? I've created CSS for a LineEdit. LineEdit.cpp void MyLineEdit::initStyleSheet() { QString css = Css::instance().css( m_element ); setProperty( "style", "normal" ); setStyleSheet( css ); } I have a separate .css file for style: MyLineEdit.css .... MyLineEdit[style="Normal"]:focus { border: 1px solid red; } MyLineEdit[style="Normal"]:disabled { border: 1px solid gray; background: gray; } Now there is one weird requirement: MyLineEdit should have a method called setNoFrame, in this function we set one more property for it, and this property is valid for only state disabled. This is what I did: MyLineEdit::setNoFrame() { setProperty("noFrame","true"); initSyleSheet(); } And this is my updated .css data .... MyLineEdit[style="Normal"]:focus { border: 1px solid red; } MyLineEdit[style="Normal"]:disabled { border: 1px solid gray; background: gray; } MyLineEdit[style="Normal", noFrame="true"]:disabled { border: none; background: gray; } It doesn't work as I expected, the border is still there for state disabled and noFrame = true. Do I have mistake in combining properties for CSS above? A: You're really, really close. Try MyLineEdit[style="Normal"][noFrame="true"]:disabled { border: none; background: gray; } From the CSS2 docs (which Qt StyleSheets supports): Multiple attribute selectors can be used to refer to several attributes of an element, or even several times to the same attribute. Here, the selector matches all SPAN elements whose "hello" attribute has exactly the value "Cleveland" and whose "goodbye" attribute has exactly the value "Columbus": span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }
{ "pile_set_name": "StackExchange" }
Q: UK inheritance: partner, sibling, child Let's start with person A. Person A wants to write a will leaving "everything" to their partner, person B. They are not married, or in a legal partnership of any kind. Person A would prefer that their only sibling inherit nothing. And that a child born out of wedlock, but acknowledged on their birth certificate (foreign, but not UK) , living overseas, receives a share, despite the will, as a gesture, stating that person B inherit "everything". Given the will, does person A's sibling have any claim? Their child? A: The child C cannot receive anything as a "gesture despite the Will" if everything in the Will is left to B; unless B agrees to a Deed of Variation the Executor is legally bound to follow the instructions in the Will. C may have a claim if he is dependent on A at the time of A's death and A has failed to make provision. It is possible that A's sibling S might also have a claim if dependent. Although you have tagged the question as United Kingdom, inheritance and intestacy law differs widely between England and Scotland. Such a Will should be drafted by a specialist trust and executry planning solicitor to avoid the risk of contentious probate.
{ "pile_set_name": "StackExchange" }
Q: is the new angle exactly half the original apex angle, for a triangle cut in half through that apex? Let each apex (point) of a triangle be apex $A$, apex $B$, and apex $C$. Let each length then be $\overline {AB},\overline {AC},\overline {BC}$. If triangle is cut in half, through an imaginary line from apex $A$ down to the exact middle (bisection) of $BC$, then will the new angle at apex $A'$ (angle of apex $C$ to apex $A$ to the point at $\frac{\overline {BC}}2$) be exactly equal to half the old angle at apex $A$ (that is equal to angle $\frac {B\hat AC}2$)? That is, does new angle $A'=\frac A2$ ? A: Ratio of sides and cut parts of opposite side is same for angle bisection at A. $ AB/AC = AM/MC $ So, unless the triangle is isosceles ( AB= AC) it will not be so.
{ "pile_set_name": "StackExchange" }
Q: uniform continuity on $[0, +\infty)$ Let $f:[0,\infty)\rightarrow R$ be a continuous function. If $\lim_{x\rightarrow+\infty} f(x)$ is finite, show that $f$ is uniformly continuous. Also, can I change "$\lim_{x\rightarrow+\infty} f(x)$ is finite" to "$f$ is bounded" and get the same conclusion? Thank you! A: Let $\epsilon>0$ be fixed and suppose $\lim_{x\to\infty} f(x) = L \geq 0.$ Then there exists $x_0$ such that $|L-f(x)|<\epsilon/4$ for all $x\geq x_0.$ In particular, for any $x,y\geq x_0$ we have $|f(x)-f(y)|<\epsilon/2.$ Continuous functions on compact domains are uniformly continuous so there is a $\delta>0$ such that $|f(x)-f(y)|<\epsilon/2$ for all $x,y\in [0,x_0].$ Now suppose $x,y\in [0,\infty)$ and $|x-y|<\delta.$ If $x,y$ are both in $[0,x_0]$ or $[x_0,\infty)$ then $|f(x)-f(y)|<\epsilon.$ If there is one in each segment, assume WLOG $x\in [0,x_0], y\in [x_0,\infty).$ Then $|f(x)-f(y)| = |f(x) - f(x_0)| + |f(x_0)-f(y)| < \epsilon/2 + \epsilon/2 = \epsilon$ so $f$ is uniformly continuous. I gave you a full solution because I share Paul Garrett's philosophy that students should be given good models for solutions to work from, rather than always be challenged to produce them from scratch. What is important to extract from my answer is 1) the idea behind the working and 2) the technique to make the idea rigorous. The idea was essentially this: Uniformly continuous means that if you pick an $\epsilon>0$ you must be able to find a $\delta>0$ such that points in the domain that are within $\delta$ distance of each other must have images whose difference is less than $\epsilon.$ It's quite a nice picture if you imagine what this means on the graph. Now we know continuous functions on compact domains are uniformly continuous. The limit condition means the function starts to become near a value $L$ so for big $x$ it doesn't change much, so it certainly seems to satisfy the uniform continuity condition there. Lastly, we can patch together the uniform continuity of the two pieces. For the second part of your question, the answer is no. You may have seen the theorem that if $f$ is differentiable then it is uniformly continuous if and only if $f'$ is bounded. You should try to prove this. Hint: The mean value theorem is important. So to see if your theorem true, maybe check if it's true with the extra condition that $f$ is differentiable. Can you think of a function that is bounded but has unbounded derivative?
{ "pile_set_name": "StackExchange" }
Q: What is the correct definition of $k$-tree? As the title says, what is the correct definition of $k$-tree? There are several papers that talk about $k$-trees and partial $k$-trees as alternative definitions for graphs with bounded treewidth, and I've seen many seemingly incorrect definitions. For example, at least one place defines $k$-trees as follows: A graph is called a $k$-tree if and only if either $G$ is the complete graph with $k$ vertices, or $G$ has a vertex $v$ with degree $k − 1$ such that $G \setminus v$ is a $k$-tree. A partial $k$-tree is any subgraph of a $k$-tree. According to this definition, one can create the following graph: Start with an edge $(v_1, v_2)$, a $2$-tree. For $i=1\ldots n$, create a vertex $v_i$ and make it adjacent to $v_{i-1}$ and $v_{i-2}$. Doing this would create a strip of $n$ squares with diagonals. Similarly, we can start creating a band from the first square in a direction orthogonal to the strip above. Then, we would have the first row and first column of an $n \times n$ grid. Filling in the grid is easy by creating vertices and joining them to the vertices to its above and to its left. The end result is a graph that contains an $n\times n$ grid, which, in effect, is known to be of treewidth $n$. A correct definition of $k$-trees has to be the following: A graph is called a $k$-tree if and only if either $G$ is a complete graph with $k$ vertices, or $G$ has a vertex $v$ with degree $k-1$ such that the neighbor of $v$ forms a $k$-clique, and $G \ v$ is a $k$-tree. Then, the grid-like graph described as above cannot be created. Am I correct? A: I basically agree with you, with just a tiny modification: A graph $G$ is a $k$-tree if and only if either $G$ is a complete graph with $k+1$ vertices, or $G$ has a vertex $v$ such that the (open) neighborhood of $v$ forms a $k$-clique, and $G - v$ is a $k$-tree. In other words, $v$ should have degree $k$, instead $k-1$ in your definition. I personally prefer the bottom-up definition, but this is just a matter of taste: The complete graph on $k+1$ vertices is a $k$-tree. A $k$-tree $G$ with $n+1$ vertices ($n\ge k+1$) can be constructed from a $k$-tree $H$ with $n$ vertices by adding a vertex adjacent to exactly $k$ vertices that form a $k$-clique in $H$. No other graphs are $k$-trees. This definition is a slightly modified version of the definition from Pinar Heggernes' lecture notes.
{ "pile_set_name": "StackExchange" }
Q: Easy table transpose in hive I need to transpose my table. Now i have that type of table: Atr_1|Atr_2 A | 1 A | 2 But i want to get the next result Atr_1|Atr_2|Atr_3 A | 1 | 2 How should i transpose my table for achieving this result? A: Use case statements with min() or max() aggregation: select Atr_1, max(case when Atr_2=1 then 1 end ) Attr_2, max(case when Atr_2=2 then 2 end ) Attr_3 from table t group by Atr_1;
{ "pile_set_name": "StackExchange" }
Q: Unable to call an Oracle Function I have a package with a function in it like following, which expects one of the parameter which is array. create or replace PACKAGE selected_pkg IS TYPE NUM_ARRAY IS TABLE OF NUMBER; FUNCTION get_selected_kml( in_layer IN NUMBER, in_solm_id IN NUMBER, in_feature_ids IN NUM_ARRAY, in_lx IN NUMBER, in_ly IN NUMBER, in_ux IN NUMBER, in_uy IN NUMBER) RETURN CLOB; END selected_pkg; Now I am trying to call the function from following anonymous block : declare result CLOB; TYPE NUM_ARRAY1 IS TABLE OF NUMBER; myarray NUM_ARRAY1 := NUM_ARRAY1 (); begin myarray.extend(3); myarray(1) := 1; myarray(2) := 5; myarray(3) := 9; EXECUTE IMMEDIATE 'truncate table demoresult'; result:=SELECTED_PKG.get_selected_kml(103, 19, myarray, 4.11, 56.27, 4.59, 56.39); insert into demoresult values(result); COMMIT; end; I am getting error PLS-00306: wrong number or types of arguments in call to 'GET_SELECTED_KML' Could someone please suggest me, what am I doing wrong? Thanks, Alankar A: You need to use the same array type that your function is expecting declare result CLOB; myarray selected_pkg.num_array := selected_pkg.num_array(); begin myarray.extend(3); myarray(1) := 1; myarray(2) := 5; myarray(3) := 9; EXECUTE IMMEDIATE 'truncate table demoresult'; result:=SELECTED_PKG.get_selected_kml(103, 19, myarray, 4.11, 56.27, 4.59, 56.39); insert into demoresult values(result); COMMIT; end;
{ "pile_set_name": "StackExchange" }
Q: How to copy local string array to private member string array in C++? I am trying to write a line reader to populate a string array which is private member of the same class. I want the loader function called by constructor to dynamically resize member array and populate it. This didn't worked. Then I managed to populate a local array in the loader function. But I couldn't copy these values to private member of the class. I think there must be a way of copying values from local "ReadLines" array to class private member "Lines" array. I have already read how vector class implemented internally. But I still think dynamically populating a string array must be achievable by some other simple way, similar to which I used to resize local array in Read() function. I searched the net, but couldn't find any answer without standart or self implemented vector classes. Has old methods before vectors (if any) completely forgotten? Is vector class that magical? Isn't there any other way than vectors? linereader.h : class LineReader { public: LineReader(); void Read(); private: string Lines[]; int LineCount; }; linereader.cpp : #include <string> #include <iostream> using namespace std; #include <fstream> #include "linereader.h" LineReader::LineReader() { Read(); cout << "Line Count : " << LineCount << endl; cout << "Lines Size : " << sizeof(Lines) << endl; cout << "Lines 0 : "; cout << Lines[0] << endl; //Gives segmantation fault } void LineReader::Read() { std::ifstream infile("lines.txt"); string *ReadLines = new string[1]; string line; int linenumber = 0; while (infile >> line) { cout << endl << linenumber << " :: " << line << " "; string* temp_Lines = new string[linenumber + 1]; for(int i = 0; i < linenumber; i++){ cout << i << ","; temp_Lines[i] = ReadLines[i]; } cout << "[" << linenumber << "]"; delete [] ReadLines; ReadLines = temp_Lines; ReadLines[linenumber] = line; linenumber++; } infile.close(); cout << endl << "----------------------------------" << endl; cout << "ReadLines Count : " << linenumber << endl; LineCount = linenumber; for(int i = 0; i < linenumber; i++){ cout << "ReadLines "<< i + 1 << " " << ReadLines[i] << endl; } ///////////////////////////////////// // HERE IS THE PROBLEM // // how to copy ReadLines to Lines? // ///////////////////////////////////// //string *Lines = new string[linenumber + 1]; // FLOODING TERMINAL WITH EMPTY LINES // Lines = ReadLines; // not working // Lines = *ReadLines; // error: cannot convert // Lines = **ReadLines; // error: no match for ‘operator*’ // *Lines = ReadLines; // error: invalid conversion from // *Lines = *ReadLines; // FLOODING TERMINAL WHEN RUN // *Lines = **ReadLines; // error: no match for ‘operator*’ // **Lines = ReadLines; // error: no match for ‘operator*’ // **Lines = *ReadLines; // error: no match for ‘operator* // **Lines = **ReadLines; // error: no match for ‘operator* } int main(int argc, char* argv[]) { LineReader linereader; return 0; } lines.txt : AAA BBB CCC DDD EEE FFF GGG compilation : g++ linereader.cpp -o linereader OUTPUT : 0 :: AAA [0] 1 :: BBB 0,[1] 2 :: CCC 0,1,[2] 3 :: DDD 0,1,2,[3] 4 :: EEE 0,1,2,3,[4] 5 :: FFF 0,1,2,3,4,[5] 6 :: GGG 0,1,2,3,4,5,[6] ---------------------------------- ReadLines Count : 7 ReadLines 1 AAA ReadLines 2 BBB ReadLines 3 CCC ReadLines 4 DDD ReadLines 5 EEE ReadLines 6 FFF ReadLines 7 GGG Line Count : 7 Lines Size : 0 Segmentation fault A: The problem lies here: string Lines[]; You declare an empty array. More exactly, you declare an incomplete array that is commonly implemented as a 0 size array. That is what the line Lines Size : 0 indicates. It used (mainly in C) when you create an object at a place where the memory for the array has already been allocated, and only as last element of a struct or class - in short never use it in your own code. It should at least raise a warning because it is not the last element of the class. But once you have declared it that way, nothing can be done. The less poor way IMHO is to declare a pointer: as you already know the length in the following member it is enough: private: string *Lines; int LineCount; You can then safely do: Lines = ReadLines; But what you do is close to non sense. You avoid to use a (well optimized and well tested) vector object, to play with allocation, copy and deallocation of arrays. That means that your code will give a much less efficient program than what you would get with a vector. In addition, as C++ has no garbage collection, this kink of code is likely to fragment the heap. Said differently, there is nothing bad in exploring the low level constructs, but please be aware that this one should never go in production code.
{ "pile_set_name": "StackExchange" }
Q: My UK visa is still in processing even though the intended date of travel has already passed. Will I still receive a visa? I applied for a Standard Visitor visa to the UK stating my travel date as Jan 1st 2017. My appointment was on Dec 15th 2016 but I could make it as I couldn't find a flight. I went to the consulate in Barbados on Jan 5th 2017 for my biometrics and was attended to. Will I get the visa even though my intended date of travel has passed? A: My guess is you have obtained your visa by now but have not yet found the time to report back. Missing your appointment should have triggered the return of your paperwork and a visa application rejection (ie no decision taken). You were probably lucky to have your biometrics taken when they were. Christmas and New Year holidays may have worked in your favour, other than for the flight issue. Also, appointments are only available once a fortnight anyway so I take it you made it to the first one possible after the one you missed. Your attending four days after the travel date you indicated is a sign you still wanted the visa and I suspect has been interpreted that way. Standard Visitor visas are generally valid for use any time within six months of issue, so it is understood there is time for a change in plans.
{ "pile_set_name": "StackExchange" }
Q: Количество, частота и содержание коммитов Заметил, что количество моих коммитов сильно превышает количество коммитов других людей в схожих проектах (на один не самый сложный проект на свете ушло больше 300). Это, конечно, не является моей основной проблемой в жизни, но у меня сложилось впечатление, что я делаю что-то не так, и это может затруднить копание в истории проекта. Я делаю коммит каждый раз, когда в проект добавляется новая фича, и он после этого приходит в работоспособное состояние, причем неважно, какого размера фича - простое выправление грамматики, багфикс, внедрение какого-то нового функционала (последнее может быть разбито и на несколько коммитов, но после каждого из них проект должен быть работоспособным), причем если я поправил css, сменил отвратительно кривой текст на просто кривой и пересобрал в контроллере экшен - это, по моей философии, должны быть три коммита, потому что они затрагивают разные невзаимосвязанные части проекта. В результате, с одной стороны, я могу получить чуть ли не любой слепок проекта и он в любой момент будет работоспособен, с другой - я получаю ворох коммитов типа 'Typo fix', 'CSS fix', 'Microfix', которые, наверное, могли бы и не существовать. Короче, как правильно делать? p.s. Одна из вероятных причин ситуации - то, что бранчингом почти не пользуюсь. Сам дурак, знаю. upd. Если точнее сформулировать вопрос - должны ли вводимые фичи быть атомарными (один коммит - одна фича или багфикс), или на это можно наплевать? A: По коммитам у меня такие правила: Коммит должен компилироваться без ошибок. Коммит должен обозначать как минимум новую фичу/класс/метод/багфикс. Или хотя бы коммит должен обозначать конец рабочего дня. Коммит не должен задерживать остальных членов команды, ибо merge - это зло (иногда необходимое). Из чего следует, что если я занимаюсь прожектом, то как минимум 1 коммит в день я должен делать. Терпеть не могу коммиты, когда изменения копятся-копятся, потом бабах - глобальный коммит с тучей конфликтов merge. С другой стороны, больше 2-3 коммитов в день - это излишне, ну разве что по просьбе сотоварищей. Update для фанатов git: в данном контексте коммит имеется ввиду не коммит в локальную репу, а гитовский push в глобальную репу. A: Вы все делаете правильно :) И переходите уже, наконец, на git :] Хотите новую фичу - делаете ветку, в которой реализовываете фичу, потом мержите ее в дев, тестите, и далее по списку... Не нужно себя ограничивать в количестве коммитов. Просто у вас будет более детальная история в случае чего :)
{ "pile_set_name": "StackExchange" }
Q: creating a navbar, items using full space (css) I'm not an expert using css, after 1 hour of time spent on this problem I will ask the community. my html code: <div class="content2"> <div class="Menu"> <a href="/all">All Investments (3)</a> <a href="/payouts">Payouts (0)</a> </div> ...some other code </div> my css code: .content2 {padding: 10px 30px; color: #fff} .Menu {background: #022000; width: 1000px; height: 50px; margin: 20px auto; text-align: center} .Menu a {float: left; height: 26px; width: 313px; padding: 12px 10px; color: #fff} .Menu a:hover {background: #277521} I would like the two items in my Menu class full fill the width of the navbar. Currently they don't take the complete width of the navbar. A: Use width: 50%; and modify the padding as padding: 12px 0px;. Explanation: width: 50% : As there are 2 elements, this will enable each element to take 50% of the parent's width. padding: 12px 0px : padding 0px for right and left helps remove the extra space required for each element. .content2 { padding: 10px 30px; color: #fff } .Menu { background: #022000; width: 1000px; height: 50px; margin: 20px auto; text-align: center } .Menu a { float: left; height: 26px; width: 50%; padding: 12px 0px; color: #fff; background-color: yellow; } .Menu a:hover { background: #277521 } <div class="content2"> <div class="Menu"> <a href="/all">All Investments (3)</a> <a href="/payouts">Payouts (0)</a> </div> ...some other code </div>
{ "pile_set_name": "StackExchange" }
Q: template using a non-existent main html tag in template block I got a theme which inside app.component.ts file on template block contains: <main [class.menu-collapsed]="isMenuCollapsed" baThemeRun> <div class="additional-bg"></div> <router-outlet></router-outlet> </main> AFAIK this element should have somewhere a selector referencing it but I am not able to find it anywhere. maybe this main tag is something internal for angular 2 and automatically loaded? Thanks, A: After some research, found the answer to your question. The <main> tag is new in HTML5. The tag specifies the main content of a document. Check this documentation about this tag.
{ "pile_set_name": "StackExchange" }
Q: TFS 2010 Branching Error on Label TF10169 I can't create a branch in TFS; when I try to branch the code in $/MainCode to $/BranchCode, using a label as the source, I get this error: TF10169: Unsupported pending change attempted on team project folder $/BranchCode. Use the Project Creation Wizard in Team Explorer to create a project or the Team Project deletion tool to delete one. Why would I need to create or delete a project? Both $/MainCode and $/BranchCode exist....... I don't get this. Thanks. A: I might be completely wrong here, but isn't it the case that the things immediately below $/ are Team Projects, rather than branches? So you would have $ SuperFoo Main vNext AmazingBar Main vNext vNextNext and you would branch (say) $/SuperFoo/Main to $/SuperFoo/MyNewBranch ? I can't right now find decent docs on Team Projects, and my experience is only with TFS 2005, but that's how I've always understood the hierarchy.
{ "pile_set_name": "StackExchange" }
Q: Using http query string as a database object node.js/express Experimenting with node.js / express / mongodb. I'm using http://localhost:3000/models/save?model={"name":"blah blah blah"} to pass a test JSON object to the express route /models/save for saving to the mongodb. Everything works great except the collection.insert statement which returns an "undefined" error. I think it must be that the parameter extracted from the query string by var model = req.query.model; is not in the correct format. Any ideas? The code is as follows: var express = require('express'); var router = express.Router(); router.get('/save', function(req, res) { // Set our internal DB variable var db = req.db; var model = req.query.model; console.log (model); // Set our collection var collection = db.get('models'); // Submit to the DB collection.insert ( model, function (err, doc) { if (err) { // If it failed, return error res.send("There was a problem saving to the database."); console.log(doc); } else { console.log ("model saved"); res.send("OK") } }); }); module.exports = router; A: Please try the following: var model = JSON.parse(req.query.model); instead of the line var model = req.query.model; JSON.parse method parses JSON string representation (which in your case is model request query parameter) and returns Javascript object which you can then use in your insert process. I hope it helps some way.
{ "pile_set_name": "StackExchange" }
Q: rewrite rule with htaccess i make this in htaccess for rewrite url Options +FollowSymLinks RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?username=$1 [QSA] RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?username=$1 [QSA] But Now i work hard to change it to be like this RewriteRule ^([a-zA-Z]{2}).([a-zA-Z0-9_-]+)$ index.php?prefix=$1&username=$2 [QSA] and its work fine .. but after change {2} to be {2,4} in rule like this RewriteRule ^([a-zA-Z]{2,4}).([a-zA-Z0-9_-]+)$ index.php?prefix=$1&username=$2 [QSA] it make website very slow .. final link should be sitename.com/prefix.name == index.php?prefix=$1&username=$2 can any one help me to rewrite the rule ?! Update : Options +FollowSymLinks ErrorDocument 400 /connect2/error.php?error=400 ErrorDocument 401 /connect2/error.php?error=401 ErrorDocument 403 /connect2/error.php?error=403 ErrorDocument 404 /connect2/error.php?error=404 ErrorDocument 500 /connect2/error.php?error=500 RewriteEngine on RewriteBase /connect2/ RewriteCond %{REQUEST_URI} !^/objects.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Block out any script that includes a <script> tag in URL RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR] # Block out any script trying to set a PHP GLOBALS variable via URL RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR] # Block out any script trying to modify a _REQUEST variable via URL RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) ########## Begin - File injection protection, by SigSiu.net RewriteCond %{REQUEST_METHOD} GET RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http:// [OR] RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=(\.\.//?)+ [OR] RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ [NC] RewriteRule .* - [F] ########## End - File injection protection ########## Begin - Basic antispam Filter, by SigSiu.net ## I removed some common words, tweak to your liking ## This code uses PCRE and works only with Apache 2.x. ## This code will NOT work with Apache 1.x servers. RewriteCond %{QUERY_STRING} \b(ambien|blue\spill|cialis|cocaine|ejaculation|erectile)\b [NC,OR] RewriteCond %{QUERY_STRING} \b(erections|hoodia|huronriveracres|impotence|levitra|libido)\b [NC,OR] RewriteCond %{QUERY_STRING} \b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\b [NC,OR] RewriteCond %{QUERY_STRING} \b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\b [NC] ## Note: The final RewriteCond must NOT use the [OR] flag. RewriteRule .* - [F] ## Note: The previous lines are a "compressed" version ## of the filters. You can add your own filters as: ## RewriteCond %{QUERY_STRING} \bbadword\b [NC,OR] ## where "badword" is the word you want to exclude. ########## End - Basic antispam Filter, by SigSiu.net ########## Begin - Advanced server protection - query strings, referrer and config # Advanced server protection, version 3.2 - May 2011 # by Nicholas K. Dionysopoulos ## Disallow PHP Easter Eggs (can be used in fingerprinting attacks to determine ## your PHP version). See http://www.0php.com/php_easter_egg.php and ## http://osvdb.org/12184 for more information RewriteCond %{QUERY_STRING} \=PHP[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} [NC] RewriteRule .* - [F] ## SQLi first line of defense, thanks to Radek Suski (SigSiu.net) @ ## http://www.sigsiu.net/presentations/fortifying_your_joomla_website.html ## May cause problems on legitimate requests RewriteCond %{QUERY_STRING} concat[^\(]*\( [NC,OR] RewriteCond %{QUERY_STRING} union([^s]*s)+elect [NC,OR] RewriteCond %{QUERY_STRING} union([^a]*a)+ll([^s]*s)+elect [NC] RewriteRule .* - [F] #Block mySQL injects RewriteCond %{QUERY_STRING} (;|<|>|’|”|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|cast|set|declare|drop|update|md5|benchmark) [NC,OR] ## Referrer filtering for common media files. Replace with your own domain name. ## This blocks most common fingerprinting attacks ;) ## Note: Change www\.example\.com with your own domain name, substituting the ## dots with \. i.e. use www\.example\.com for www.example.com # RewriteRule ^images/stories/([^/]+/)*([^/.]+\.)+(jp(e?g|2)?|png|gif|bmp|css|js|swf|ico)$ - [L] RewriteCond %{HTTP_REFERER} . RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC] RewriteCond %{REQUEST_FILENAME} -f # RewriteRule \.(jp(e?g|2)?|png|gif|bmp|css|js|swf|ico)$ - [F] ## Disallow visual fingerprinting of Joomla! sites (module position dump) ## Initial idea by Brian Teeman and Ken Crowder, see: ## http://www.slideshare.net/brianteeman/hidden-joomla-secrets ## Improved by @nikosdion to work more efficiently and handle template ## and tmpl query parameters RewriteCond %{QUERY_STRING} (^|&)tmpl=(component|system) [NC] RewriteRule .* - [L] RewriteCond %{QUERY_STRING} (^|&)t(p|emplate|mpl)= [NC] RewriteRule .* - [F] ## Disallow access to htaccess.txt, configuration.php, configuration.php-dist and php.ini RewriteRule ^(htaccess\.txt|configuration\.php(-dist)?|php\.ini)$ - [F] ########## End - Advanced server protection - query strings, referrer and config ########## Begin - Optimal default expiration time ## Note: this might cause problems and you might have to comment it out by ## placing a hash in front of this section's lines <IfModule mod_expires.c> # Enable expiration control ExpiresActive On # Default expiration: 1 hour after request ExpiresDefault "now plus 1 hour" # CSS and JS expiration: 1 week after request ExpiresByType text/css "now plus 1 week" ExpiresByType application/javascript "now plus 1 week" ExpiresByType application/x-javascript "now plus 1 week" # Image files expiration: 1 month after request ExpiresByType image/bmp "now plus 1 month" ExpiresByType image/gif "now plus 1 month" ExpiresByType image/jpeg "now plus 1 month" ExpiresByType image/jp2 "now plus 1 month" ExpiresByType image/pipeg "now plus 1 month" ExpiresByType image/png "now plus 1 month" ExpiresByType image/svg+xml "now plus 1 month" ExpiresByType image/tiff "now plus 1 month" ExpiresByType image/vnd.microsoft.icon "now plus 1 month" ExpiresByType image/x-icon "now plus 1 month" ExpiresByType image/ico "now plus 1 month" ExpiresByType image/icon "now plus 1 month" ExpiresByType text/ico "now plus 1 month" ExpiresByType application/ico "now plus 1 month" ExpiresByType image/vnd.wap.wbmp "now plus 1 month" ExpiresByType application/vnd.wap.wbxml "now plus 1 month" ExpiresByType application/smil "now plus 1 month" </IfModule> ########## End - Optimal expiration time ServerSignature Off RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-z]{2,4})\.([\w-]+)$ index.php?prefix=$1&username=$2 [QSA,L,NC] A: Try this Options +FollowSymLinks RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-z]{2,4})\.([\w-]+)/?$ index.php?prefix=$1&username=$2 [QSA,L,NC] This single rule takes care of all cases. \w is equivalent to [a-zA-Z0-9_]. Only [a-z] has been specified because the rule is now case-insensitive by using [NC]. Trailing slash is also optional /?.
{ "pile_set_name": "StackExchange" }
Q: Classification tree with less leafs than expected My tree diagram only shows the two leafs: "DIFF" and "REG" and completely ignores the other values of the response variable. Why is the tree ignoring the other 6 values?. Does it have to do with the fact that they only represent a small percentage of the total values in my response variable?. Table below shows frequency count by value in response variable 35785 ED 1% 38060 NONE 1% 45880 INC 1% 49787 UT 1% 53108 OR 1% 165945 ET 4% 1728019 DIFF 43% 1894532 REG 47% A: I suspect it is down to the unbalanced classes you refer to. Skewed data causes problems for machine learning algorithms. For example, clients of mine once naively built a fraud detection system using machine learning and were impressed when testing reported 97% accuracy with no tuning at all. Turning out the prediction rule was "There's never any fraud". Fraud was so rare that that "rule set" resulted in 97% accuracy. I assume something similar in your case---although without the details, I tend to sit on the fence. There are ways to address the issue.
{ "pile_set_name": "StackExchange" }
Q: Move Constructor - invalid type for defaulted constructor VS 2013 I was reading regarding move constructor and I did this code in VS 2013... class Student { unique_ptr<string> pName_; public: Student(string name) : pName_(new string(name)) { } ~Student() { } Student(Student&&) = default; // Here I get the error. void printStudentName(void) { cout << *pName_ << endl; } }; int main(void) { vector<Student> persons; Student p = Student("Nishith"); persons.push_back(std::move(p)); persons.front().printStudentName(); return 0; } I get the "Student::Student(Student&& ) : is not a special member function which can be defaulted" when I tried to compile it... Can anyone explain me why I am getting this error? A: Because the VS2013 compiler doesn't support defaulted move constructors. See the following note from MSDN: Visual Studio does not support defaulted move constructors or move-assignment operators as the C++11 standard mandates. For more information, see the Defaulted and Deleted functions section of Support For C++11 Features (Modern C++).
{ "pile_set_name": "StackExchange" }
Q: how do i destroy variables in vb.net formUI? I have written some code in visual studio using vb.net and I was just wondering how do I destroy variables when the program exits. Here is my code for the first form(Login): Public Class LoginForm1 'username variables Public username1 As String Public username2 As String Public username3 As String 'Password variables Public pwd1 As String Public pwd2 As String Public pwd3 As String 'user input variables Public userInputUsername As String Public userInputPwd As String 'switch form variable Public correctLoginForm As New correctLogin Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'setting usernames and passwords username1 = "Chops" username2 = "Jeff" username3 = "Bob" pwd1 = "Cheese" pwd2 = "Sign" pwd3 = "Speaker" 'set user input variables userInputUsername = TextBox1.Text userInputPwd = TextBox2.Text 'test for correct username/pwd If userInputUsername = username1 And userInputPwd = pwd1 Then correctLoginForm.Show() Me.Hide() ElseIf userInputUsername = username2 And userInputPwd = pwd2 Then correctLoginForm.Show() Me.Hide() ElseIf userInputUsername = username3 And userInputPwd = pwd3 Then correctLoginForm.Show() Me.Hide() Else Label3.ForeColor = Color.Red Label2.ForeColor = Color.Red End If End Sub this is the image of my first form (as above) my first form image I wanted to remove the variables so that I could free up space in ram A: Considering that you are trying to free up memory and if this is the example then , I would not worry too much about garbage collection which is the freeing up of memory by disposing of unneeded data. If the correctLogin is a class that is inherit of a form then you can simply dispose the variable correctLoginForm with .dispose, you can also set it to nothing but if you do remember to create a new instance of it or else you will get an object of of reference error. For integers and strings ect. you can simple set them to nothing , but the memory savings on doing this are non existence, but it is still get practice especially if you are reusing the data and do not want contamination of old data into new records.
{ "pile_set_name": "StackExchange" }
Q: Symbian Development I am currently doing iphone development. I wish to do development in the Symbian platform too. Rather than Java i am familiar with CPP. Can you please help me by giving me some advice to get start in this development environment.? What all are the softwares i need to get installed in my system.? Expecting a positive reply. Thanks and regards, Shibin A: The Qt framework is a free cross platform C++ based environment, with Symbian support just around the corner (looks like its available in beta). It supports desktop OSes (Windows/Mac) as well as device (Embedded Linux, Windows CE, etc.). However as of this writing it does not support iPhone, RIM or Android. A: Things you will need: IDE. For Symbian C++ development there's the free, Eclipse-based Carbide.c++. SDK. For example, the S60 Platform SDK enables you to write applications for S60-based devices. There's a lot of getting started documentation on Forum Nokia.
{ "pile_set_name": "StackExchange" }
Q: What is the topology on the free group with $n$ generators? I'm currently reading Functional Analysis, Spectral Theory, and Applications by Einsiedler and Ward and came upon this: Exercise 9.24. Show that if $G$ is a topological group with property (T), and is a continuous homomorphism from $G$ to $G'$ with dense image, then $G'$ also has property (T). Conclude that the free group $F$ (with at least one generator) does not have property (T). I think I'm meant to construct a continuous homomorphism from the free group $F$ generated by $\{1,2,\ldots,n\}$ to $\mathbb{R}$ or $\mathbb{Z}$ with dense image, since those two are known to not have property (T). Before doing so, I need to know what the topology on the free group is. Would this topology make $F$ the universal topological group such that for any topological group $G$ and any map $f: \{1,2,\ldots,n\} \rightarrow G$, there is a continuous homomorphism $\phi: F \rightarrow G$ such that $\phi \circ i = f$ ($i$ being the embedding)? If this is the case, how can I construct this topology explicitly? A: Put the discrete topology on the free group with $n$-generators $F(x_1,...,x_n)$ (every subset is open and closed) and define $f:F(x_1,...,x_n)\rightarrow Z$ by $f(x_i)=1$.
{ "pile_set_name": "StackExchange" }
Q: Display the 10 most used tags I am developing an API using Codeigniter and in this API the users can tag themself. I need to display the 10 most popular tags (most frequestly used tags). How can I do that? Update The tag table contains: id, user_id, tag, created_at, updated_at A: Jonathan, depending on your setup the solution will be different, I'm going to suggest something a bit different than what your table structure looks like, you can use it if you want to. .--------------. .-------------. | userTags | | tags | .--------------. .-------------. | id | | id | | user_id | | tagName | | tag_id | .-------------. .--------------. To add a tag to your database: $data = array('tagName' => 'Mr. Niceguy'); $this->db->insert('tags' => $data); To add a tag to your user, you could use the following in a model $data = array('user_id' => $uId, 'tag_id' => 1); $this->db->insert('userTags', $data); To recieve the most common used tags: $this->db->select('tag_id'); $this->db->order('tag_id DESC'); $this->db->limit(10); $this->db->join('tags', 'userTags.tag_id = tags.id'); $this->db->get('userTags'); Edit: If you have to use your setup, do this instead: $this->db->order_by('count(tag)', 'DESC'); $this->db->group_by('tag', 'DESC'); $tags = $this->db->get('userTags'); foreach($tags->result() as $tag) { var_dump($tag->tag); }
{ "pile_set_name": "StackExchange" }
Q: AngularJS - 10 $digest() iterations reached. Aborting On my angular app I display a list of items that I load directly from my database. I am trying to get at least 20 items displayed at all time. Users can filter them so when too many filters are applied I'd like to load more. The way I did it so far is the following: HTML: <section id="list" class="ease"> <article class='myItems' ng-repeat="job in filteredList = (items | filter: country | filter: category | filter: position)"> Items </article> </section> JS (in my controller): $scope.$watch('filteredList', function(newVal, oldVal){ if(newVal !== oldVal){ $log.info($scope.filteredList.length); // code to load more data } }); However I get the following error: Error: 10 $digest() iterations reached. Aborting I am guessing it is because the filteredList change too many times so angular blocks it. How can I fix this? Thanks A: Use $scope.$watchCollection instead of $scope.$watch since your filteredList is a collection. Using $scope.$watch actually fails since you rebuild the reference on each digestion loop, so the watcher loops and loops again and reach the digest limit. Interesting article about the watching methods
{ "pile_set_name": "StackExchange" }
Q: How to test conditional rendering of components using Jest and Enzyme I have a conditional rendering block in my React component which is defined as: {(props.email.primary.isPending) ? <PendingComponent emailAddress={props.email.primary.pendingEmail} /> : <SecondaryEmailContact state={props.email.secondary} retrieveInputData={props.retrieveInputData} handleSecondaryEmailToggle={props.handleSecondaryEmailToggle} handleDelete={props.handleDelete} handleSubmitContact={props.handleSubmitContact} refs={props.refs} /> } I have written a test case as below: it('renders the EditEmailContact component', () => { wrapper=mount(<EditEmailContact email={emailState} handleSecondaryEmailToggle={handleSecondaryEmailToggleFn} retrieveInputData={retrieveInputDataFn} handleDelete={handleDeleteFn} handleSubmitContact={handleSubmitContactFn} />); }); }); So, in my test result it shows the line where the statement for conditional rendering is defined is not tested. So, how do I test the conditional rendering? A: You could create two different test cases passing props to your component. For instance: const yourProps = { email: { primary: { isPending: true // create test cases passing a different value }, }, } const component = mount(<YourComponent {...yourProps} />)
{ "pile_set_name": "StackExchange" }
Q: Updating progressbar external class Basically, I have a class and inside it a function which counts all lines within a text file. I need it to update the progress bar from Form1 with each line it counts. I have tried: public static void rfile(string f) { string[] lines = File.ReadAllLines(f); Form1 form = new Form1(); foreach (string l in lines) { form.increaseProg(); } } Form.cs public void increaseProg() { progressBar.Value++; System.Threading.Thread.Sleep(1000); progressBar.Refresh(); } But that doesn't seem to increase the progress bar at all. A: You can leverage the Progress class to make updating the UI during a long running operation easy on everyone involved. Create the Progress class within your form, and indicate how it should update the UI when it is given progress. Then give that object to the other class that is going to be doing the long running work: private void button1_Click(object sender, EventArgs args) { Progress<int> progress = new Progress<int>(); progress.ProgressChanged += (p, value) => progressbar1.Value = value; Task.Run(() => SomeOtherClass.DoWork("c:/temp.txt", progress)); } The long running work is of course done in another thread to avoid blocking the UI. The Progress class will take care of marshaling the ProgressChanged event to the UI thread for us, so we don't need to think about it. Now for the worker we just need to report progress when needed: public class SomeOtherClass { public static void DoWork(string filepath, IProgress<int> progress) { int currentProgress = 0; foreach (var line in File.ReadLines(filepath)) { DoSomethingWithLine(); currentProgress++; progress.Report(currentProgress); } } } Note that another advantage of this approach is that SomeOtherClass doesn't need to know anything about the form. It can be called by anyone that can provide an IProgress object. If you have some other form needing to call that method you don't need to change it at all. It also means that if one developer is writing the form and another is coding the long running process they only need to agree on the signature of the DoWork method; and from then on the UI guy and do all of the UI work and the non-UI guy can do all of the non-UI work, and they don't need to worry about what the other person is doing. As for why your code isn't working, the problem is that your worker method isn't accessing the instance of the form that is being displayed, you're creating a brand new form, modifying it's progress bar, never showing it to anyone, and then throwing it away.
{ "pile_set_name": "StackExchange" }
Q: Select records that appear more than once I am trying to select records that appear more than once and are part of a specific department plus other departments. So far the query that I have is this: SELECT employeeCode, employeeName FROM Employees WHERE Department <> 'Technology' AND employeeCode IN (SELECT employeeCode FROM Employees GROUP BY employeeCode HAVING COUNT(*) > 1) The problem is that I want to select employees which are part of the Technology department, but they also participate in other departments. So, they must be from the Technology department, but they could also be from the Household department. In the database it could look like: 1 | A1 | Alex | Technology 2 | A2 | Thor | Household 3 | A3 | John | Cars 4 | A3 | John | Technology 5 | A4 | Kim | Technology 6 | A4 | Kim | Video Games So basically the query should return: A3 | John | A4 | Kim | I think it's a small part that I am missing but.. Any ideas on how to filter/sort it so that it always uses the technology and the other departments? Btw, I tried searching but I couldn't find a problem like mine.. A: If you want employees that could be in the technology department and another department: select e.employeeCode, e.employeeName from employees e group by e.employeeCode, e.employeeName having sum(case when e.department = 'Technology' then 1 else 0 end) > 0 and count(*) > 1; This assumes no duplicates in the table. If it can have duplicates, then use count(distinct department) > 1 rather than count(*) > 1.
{ "pile_set_name": "StackExchange" }
Q: Leaflet - Add remove GeoJSON polygon later on click by property? Im using leaflet and am looking into GeoJSON, id like to add remove a polygon on a click event. using the sample data from the GeoJSON examples in leaflet ive built the below, but I have no idea how to do this. I did use poly layers without geojson and did manage to get a on click to add a layer but not removed, it just repeatedly added layers thanks for any help <html> <head> <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> </head> <body> <a href="javascript:add_layer('Republican')">Republican</a> | <a href="javascript:add_layer('Democrat')">Democrat</a> <div id="map" style="height:700px;"></div> <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script> <script type="text/javascript"> var map = L.map('map').setView([40, -97.], 5); L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', maxZoom: 18, id: 'mapbox/streets-v11', accessToken: 'x' }).addTo(map); var states = [{ "type": "Feature", "properties": {"party": "Republican"}, "geometry": { "type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]] } }, { "type": "Feature", "properties": {"party": "Democrat"}, "geometry": { "type": "Polygon", "coordinates": [[ [-109.05, 41.00], [-102.06, 40.99], [-102.03, 36.99], [-109.04, 36.99], [-109.05, 41.00] ]] } }]; L.geoJSON(states); function add_layer(value){ if map.contains.feature.properties.party.case(value) { map.layer.remove(feature.properties.party.case(value)) } else { feature.properties.party.case(value.addTo(map)) } } </script> </body> </html> EDIT: new function to add/remove, which returns "TypeError: Attempted to assign to readonly property." for the map.hasLayer line function add_layer(value){ if(map.hasLayer(value)) { map.removeLayer(value); }else{ map.addLayer(value); } } A: For your your question: You can add and remove layers from map or layergroup with map.addLayer(layer) or layer.addTo(map) / map.removeLayer(layer) or layer.removeFrom(map). But I think the best for you is to use the Layer Control https://leafletjs.com/examples/layers-control/ var states = [{ "type": "Feature", "properties": {"party": "Republican"}, "geometry": { "type": "Polygon", "coordinates": [[ [-104.05, 48.99], [-97.22, 48.98], [-96.58, 45.94], [-104.03, 45.94], [-104.05, 48.99] ]] } }, { "type": "Feature", "properties": {"party": "Democrat"}, "geometry": { "type": "Polygon", "coordinates": [[ [-109.05, 41.00], [-102.06, 40.99], [-102.03, 36.99], [-109.04, 36.99], [-109.05, 41.00] ]] } }]; var democrat = L.geoJSON(states, { filter: function(feature, layer) { return feature.properties.party === "Democrat"; } }); var republican = L.geoJSON(states, { filter: function(feature, layer) { return feature.properties.party === "Republican"; } }); var overlayLayers= { "Republican": republican, "Democrat": democrat }; L.control.layers(null,overlayLayers).addTo(mymap); if you want to use external control (like your example): function add_layer(value){ map.removeLayer(republican); map.removeLayer(democrat); if(value === "Republican"){ map.addLayer(republican); }else{ map.addLayer(democrat); } } Also you can check if the map has a layer with: map.hasLayer(layer)
{ "pile_set_name": "StackExchange" }
Q: EF could not translate expression to sql It looks like EF is not able to translate the express in the following code, this is the call Counter lastCounter = unitOfWork.CounterRepository.FindLast(x => x.Div == counter.Div, x => x.Div); this is the method public Counter FindLast(Expression<Func<Counter, bool>> predicate, params Expression<Func<Counter, object>>[] includedProperties) { IQueryable<Counter> set = context.Set<Counter>().Where(predicate); foreach (var includeProperty in includedProperties) { set = set.Include(includeProperty); } return set.Last(); } Any idea what could be the problem? A: It's quite simple, really: Entity Framework just does not support Last(). The reason for this is that in SQL, you also cannot select the last element (i.e. you have SELECT TOP but don't have SELECT BOTTOM). See https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities
{ "pile_set_name": "StackExchange" }
Q: How to prevent your question being closed? Just post a bounty on it The question Win Server 2008 RDP Attack caught my eye as I was going through the bounty questions. To me it is clearly off topic, so I voted to close it as such... only to be told by the system that I couldn't: To me this is a bug. If the question is migrated then the bounty can go with it. If it is closed then the bounty doesn't matter - the OP has already had it deducted (I wouldn't even care if they got it refunded). But when a question is off topic (or closeable for another reason) then placing a bounty on it shouldn't make it immune from the correct actions of the community. Edit: I've since flagged the question for mod attention. I think there is the possibility to change the flow for this, so that OT/NARQ questions can still be close voted and don't get the bounty refunded, but maybe the other close reasons are either disabled or the bounty poster gets a refund (as they can be either purely accidental (Exact Duplicate) or arguably more subjective (Not Constructive / Too Localized)). Or maybe I'm just over-thinking this and the bounty should get auto refunded. A: Refunding a bounty is problematic, closing a question without refunding a bounty is also very problematic. Any mechanism that would allow to refund bounties by actions the community can take is prone to being abused. If a question that should be closed receives a bounty, it means the moderation has failed already. The question was then open for at least 2 days, in which it should have been closed. For this reason this situation is relatively rare, most questions are closed earlier. Diamond moderators can refund bounties, which enables them to close bad questions that somehow survived long enough to get a bounty on them. So there is a mechanism to deal with this, which I consider sufficient. A: This is status-bydesign and documented on the bounty FAQ. Note that you cannot migrate a bounty on a question if the user doesn't exist on the target site, or has too little reputation there to cover the bounty. Reputation should be subtracted on the site where the question resides and bounty is awarded. As such, edge cases like how to handle bounties on migration means that bountied questions require moderator intervention. Mods can refund a bounty, just flag the question for attention and they'll review the case. A: I don't see the real need for this feature, but I think it's as follows: Closure is subjective (and also can be wrong). The bounty allows one to preserve a question that is in the grey area of SE-appropriate (i.e, it can be both closeworthy and not closeworthy, depending on the user--and noth will be correct). Of course, if the question isn't such a "Schrodinger question" (i.e, is obviously OT/NC/NARQ/etc), then the bounty must be refunded. Mods can refund active bounties (awarded/expired bounties need dev magic), and then close the question. Use a custom flag, letting the mod know why you think that the question should be closed and unbountied.
{ "pile_set_name": "StackExchange" }
Q: Number theory problem and Diophantine Equations Suppose $m^3=n^4-4$ where $m,n \in \mathbb Z$. a) Show that $m$ cannot be even if $n$ is odd. b) Show that $m$ and $n$ cannot both be even. c) By considering the prime factors of $m$,$n^2-2$ and $n^2+2$, show there is no integer solutions to $m^3=n^4-4$ I can do the first two parts, but find it hard to start part c, how shall I think about this problem and where shall I start? A: From a) and b), $m$ must be odd and hence so must be $n^4-4=(n^2+2)(n^2-2)$. As $\gcd(n^2+2,n^2-2)\mid 4$, this implies that $n^2\pm2$ are coprime, hence each of them must be a cube. Hence we have two cubes that differ by $4$.
{ "pile_set_name": "StackExchange" }
Q: ImageBase + SizeOfHeaders will jump at the section table I was reading a tutorial on PE and it says Go to the section table either by adding ImageBase to SizeOfHeaders but SizeOfHeaders is The size of all headers+section table so if we add SizeOfHeaders to ImageBase won't we jump at the sections rather than the table? A: SizeOfHeaders indeed is the size of the entire header, including the DOS stub. To get the address of the section table, first get the address of the optional header, and add FileHeader.SizeOfOptionalHeader.
{ "pile_set_name": "StackExchange" }
Q: How to disable auto restore option in Visual Studio installer project? I have an installer prepared from Microsoft Visual Studio 2010. In my package, there are several libraries. Whenever I rename any of the package components from installation folder and run the app, it automatically restores the missing pieces. But problem is I don't want to do this. Is there a way to disable this? EDIT I have tried according to the suggestion of PhilDW's answer. But after modifying the component id it shows the following message - A: The documented way to do this for selected files is to set the Component id to null in the Copmponent table in the MSI file. See ComponentId: https://msdn.microsoft.com/en-us/library/aa368007(v=vs.85).aspx Visual Studio does not support null guids (it doesn't expose component guids at all) so you'd need to edit the MSI file with Orca be setting those ids to empty for those files.
{ "pile_set_name": "StackExchange" }
Q: With TypeORM, `SQLITE_CONSTRAINT: FOREIGN KEY constraint failed` when adding a column to an entity I'm using TypeORM as a TypeScript ORM library, with a SQLite database. I've got a TypeORM entity, called Photo with a @OneToOne relationship with another entity, called PhotoMetadata. Photo.ts: import { Entity, Column, PrimaryGeneratedColumn, OneToOne, BaseEntity, } from 'typeorm'; import PhotoMetadata from './PhotoMetadata'; @Entity() export default class Photo extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ length: 100 }) public name: string; @OneToOne( () => PhotoMetadata, (photoMetadata) => photoMetadata.photo, { cascade: true }, ) metadata: PhotoMetadata; } And here is PhotoMetadata.ts: import { Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn, } from 'typeorm'; import Photo from './Photo'; @Entity() export default class PhotoMetadata { @PrimaryGeneratedColumn() id: number; @Column() comment: string; @OneToOne( () => Photo, (photo) => photo.metadata, ) @JoinColumn() photo: Photo; } When I add a column to Photo, like: @Column({ nullable: true }) test: string; Then run the app, with logging enabled, I get: query: BEGIN TRANSACTION query: SELECT * FROM "sqlite_master" WHERE "type" = 'table' AND "name" IN ('photo_metadata', 'photo', 'user') query: SELECT * FROM "sqlite_master" WHERE "type" = 'index' AND "tbl_name" IN ('photo_metadata', 'photo', 'user') query: PRAGMA table_info("user") query: PRAGMA index_list("user") query: PRAGMA foreign_key_list("user") query: PRAGMA table_info("photo") query: PRAGMA index_list("photo") query: PRAGMA foreign_key_list("photo") query: PRAGMA table_info("photo_metadata") query: PRAGMA index_list("photo_metadata") query: PRAGMA foreign_key_list("photo_metadata") query: PRAGMA index_info("sqlite_autoindex_photo_metadata_1") query: SELECT * FROM "sqlite_master" WHERE "type" = 'table' AND "name" = 'typeorm_metadata' query: CREATE TABLE "temporary_photo_metadata" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "comment" varchar NOT NULL, "photoId" integer, CONSTRAINT "UQ_99f01ed52303cc16139d69f7464" UNIQUE ("photoId"), CONSTRAINT "FK_99f01ed52303cc16139d69f7464" FOREIGN KEY ("photoId") REFERENCES "photo" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION) query: INSERT INTO "temporary_photo_metadata"("id", "comment", "photoId") SELECT "id", "comment", "photoId" FROM "photo_metadata" query: DROP TABLE "photo_metadata" query: ALTER TABLE "temporary_photo_metadata" RENAME TO "photo_metadata" query: CREATE TABLE "temporary_photo" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(100) NOT NULL) query: INSERT INTO "temporary_photo"("id", "name") SELECT "id", "name" FROM "photo" query: DROP TABLE "photo" query failed: DROP TABLE "photo" error: [Error: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed] { errno: 19, code: 'SQLITE_CONSTRAINT' } query: ROLLBACK How can I fix this issue? It seems to fail dropping the Photo table that I modified, because of the foreign key. A: I tried using TypeORM migrations to do this, but I encountered the same problem. I then learned the following from this comment: const connection = await createConnection(); await connection.query('PRAGMA foreign_keys=OFF'); await connection.synchronize(); await connection.query('PRAGMA foreign_keys=ON'); Or if you want to use migrations instead, then from this comment: await connection.query("PRAGMA foreign_keys=OFF;"); await connection.runMigrations(); await connection.query("PRAGMA foreign_keys=ON;"); In either case, you need to set synchronize: false in your ormconfig.json.
{ "pile_set_name": "StackExchange" }
Q: Overload operator for arrays Is it possible to overload addition operator(+) for the addition of arrays? Something like: double operator+ (double a[], double b[]) { double c[]; c[] = a[] + b[]; return c; } A: No. A parameter of type "array of T" is adjusted, at compile time, to type "pointer to T", so your declaration: double operator+ (double a[], double b[]) really means: double operator+ (double *a, double *b) And you can't define an overloaded operator+ for pointer types (at least gcc doesn't think so, and I believe it's correct). Nor can you declare a function with an array type as its return type; if you try, it's not adjusted to a pointer type, it's just illegal. You can define functions that take arguments of some container type (std::vector, std::array) -- which is likely to be more useful anyway. Be sure to think about what your operator+ should do if the left and right operands have different sizes. (Throwing an exception is one reasonable approach.)
{ "pile_set_name": "StackExchange" }
Q: Best practice for removing all items from an ArrayList in Java I have a java ArrayList and need to remove all the items from it, then fill it up again, but this time with a different group of items. What is the best-practice way to remove all the items in an ArrayList, because I think there are a few and I don't know which is best: my_array_list.removeAll(my_array_list); //this seems a bit strange to be the norm? for (String aString : my_array_list) { //is it really needed to use a for loop just to remove all the elements? my_array_list.remove(aString); } for (int i = 0; i < my_array_list.size(); i++) { //for loop again, but using indexes instead of object to remove everything my_array_list.remove(i); } Thanks so much for you answers. A: To remove all elements from an ArrayList, you don't need a loop, use the clear() method: my_array_list.clear(); A: As this article mention: What is the difference between ArrayList.clear() and ArrayList.removeAll()? arrayList.clear() is really good
{ "pile_set_name": "StackExchange" }
Q: Mongodb getting error while creating new user I just installed a fresh mongodb on Ubuntu server and when i try to adduser i am getting error db.createUser( { user: "admin", pwd: "ADYkdfd332@@33", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } ) 2018-07-03T13:29:41.556+0530 E QUERY [thread1] Error: couldn't add user: Use of SCRAM-SHA-256 requires undigested passwords : _getErrorWithCode@src/mongo/shell/utils.js:25:13 DB.prototype.createUser@src/mongo/shell/db.js:1437:15 @(shell):1:1 A: This works for me: db.createUser({ user:"test1", pwd:"test1", roles:[ { role:"readWrite", db:"u8" } ], mechanisms:[ "SCRAM-SHA-1" ] }) A: If you use User Management Methods you have to set param passwordDigestor. db.createUser( { user: "admin", pwd: "ADYkdfd332@@33", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ], passwordDigestor: "<server|client>" } ) A: Go with following commands in Mongo Shell: use admin db.createUser({ user:"admin", pwd:"abc123", roles:[{role:"userAdminAnyDatabase",db:"admin"}], passwordDigestor:"server" }) Further you can refer enable authentication
{ "pile_set_name": "StackExchange" }
Q: getting wrong count when getting data from tables based on two dates In table the date will be saved as below, i need to generate reports in between dates using above column as date_column>= (selected from date) and date_column <= (Selected to date) 04/03/10 09:00:50.000000000 AM below is my query select * from table where date_column>= (selected from date) and date_column <= (Selected to date) group by date_column desc When i see the report the count of data in reports are different. Selected date will be in this format 21/09/2014 A: Because the Date entry includes time stamp also thus you need to use select * from table where date_column between TO_CHAR(selected from date, 'DD-MON-YYYY') and TO_CHAR(selected to date, 'DD-MON-YYYY') group by date_column desc With this it will include the timestamp in your where clause You can use TO_CHAR(selected from date, 'DD-MON-YYYY') To format dates also.
{ "pile_set_name": "StackExchange" }
Q: hgwebdir push - directory empty? I set up my "mercurial_server" as follows (except I used hgwebdir.cgi instead of hgweb.cgi) and I created a repo hg init then I create a local repo work on my code and then push my updates to the server (tortoisehg), they show up on the web, but not in the actual directory? Is this supposed to happen I cant find a write up on the database A: This is normal. The repository (.hg directory) contains the change history you pushed. The working copy is still empty. To update your working copy to a version from the repository, you need to run the "hg update" command on your server (use the "-C tip" argument to show the latest). This will make the files appear in the directory next to your .hg directory. In most cases, you do not need to do that on your server unless you are implementing a continuous integration/deployment process.
{ "pile_set_name": "StackExchange" }
Q: .htaccess rewriterules exclude directory I made all my htaccess rewriterules but now I want to exclude all the directories and files from it. All hints regarding this htaccess are welcome, because I haven't got experience with rewrite rules... I figured out that the RewriteCond will only work for the first rule that follows. Thus how can I exclude all files and directories from all rules? Allow from All RewriteEngine on SetEnv DEVELOPMENT_ENVIRONMENT true RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d #One url parameter RewriteRule ^([a-zA-Z0-9_]*)/$ index.php?language=$1 RewriteRule ^([a-zA-Z0-9_]*)$ index.php?language=$1 #Two url parameters RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)$ index.php?language=$1&page=$2 RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/$ index.php?language=$1&page=$2 #Three url parameters RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)$ index.php?language=$1&page=$2&feed=$3&message=$3&page_number=$3&id=$3 RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/$ index.php?language=$1&page=$2&feed=$3&message=$3&page_number=$3&id=$3 #Four url parameters RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_\-]*)$ index.php?language=$1&page=$2&id=$3 RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_\-]*)/$ index.php?language=$1&page=$2&id=$3 #Five url parameters RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)$ index.php?language=$1&page=$2&feed=$3&year=$4&month=$5 RewriteRule ^([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/([a-zA-Z0-9_]*)/$ index.php?language=$1&page=$2&feed=$3&year=$4&month=$5 A: Thus how can I exclude all files and directories from all rules? I guess you mean: Thus how can I exclude all files and directories THAT EXIST from all rules? Like this: RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule .* - [L] Replace the first 2 RewriteCond lines with the above set.
{ "pile_set_name": "StackExchange" }
Q: R: functions recursion I've got the following code: N <- 3 K <- 100 S0 <- 100 u <- 1.007 d <- 1/u r <- 0.002 a <- 1/6 ptil <- (1+r-d)/(u-d) qtil <- 1-ptil VN <- function(n,s,y){ V <- 1/(1+r)*(ptil*VN(n+1,u*s,a*u*s+y)+qtil*VN(n+1,s*d, a*d*s+y)) if (n < N){ return(V) } if (n == N){ return(max(c(0,y-K))) } } When I calculate VN(0,S0, aS0), I get the following error:Error: evaluation nested too deeply: infinite recursion / options(expressions=)?. What is wrong with my code? A: VN immediately calls VN again in the first line. Which will call VN again. And again. I don't know what this code is supposed to do but recursive algorithms need to check their bottoming out condition first before calling themselves. I suspect you just need to move that first line of the function into the first if clause.
{ "pile_set_name": "StackExchange" }
Q: Use python to run shell script with Popen behaves differently in python command line and actual program I have a shell script that I want to call from a python program, but doesn't work at all with following code(Popen already imported): bf_dir = '/home/wireless' bf_path = os.path.join(bf_dir, 'airdispatch.sh') sh = Popen("sudo " + bf_path, shell=True) print sh.communicate() Ideally, the script will generate output files, but by executing above code, those files don't appear, and the "print" result is [None, None]. My guess is that the "Popen" somehow doesn't get executed at all, or might be that I made a mistake here. So I run above code in python command line, but it turns out that everything works fine. How can that be possible? Please help, thanks. A: The reason you are not getting any output from the command is because you have not told the subprocess to open pipes for communication... from subprocess import Popen, PIPE sh = Popen("sudo %s" % bf_path, shell=True, stdout=PIPE, stderr=PIPE) Now communicate will return the output of both stdout and stderr. Also, its possible that the sudo might cause you problems if it requires a password input.
{ "pile_set_name": "StackExchange" }
Q: Dialog displayed black in VS2015 Recently I upgraded my VS2010 solution to VS2015. After coding a bit and compiling it w/o error I tried to take a look into the .rc - the main dialog. The problem here is, that this dialog is displayed completely black without showing controls on it. Clicking around (or using TAB in the black nothingness, shows that I am able to access the dialog controls. I also have one more dialog without any controls on it. This can be accessed without the 'bug'. Is this a actual bug or is something else wrong with it ? From my point of view, a control might be causing this, though I didn't find something suspicious in the .rc file. Please leave a comment if you need any more information. Edit: I have now tried to compile it again and it now DoModal returns -1. Dialog box could not be created The dialog does now not show up any more. A: I have installed VS2015 on a VM (Windows Server 2008 R2) and the dialog got rendered perfectly. For some reason it did not render correctly on a Windows 8.1 PC. After changing various changes in the .rc file and testing, I created a few dialogs (also pasted all items from the black dialog into the new Ctrl+A Copy & Paste), compared the flags, and changed every single one of them. Regarding the DoModal returning -1, it seems like the Style flag was set wrong after a few changes, my bad I didn't notice. Changing it back from Child to Popup solved this obvious issue. As for the rendering not being done correctly (black dialog), it appears to be the property Layered. After setting this from True to False it rendered correctly in an instant, changing it back to True caused no more issues. Hopefully this will be helpful to someone if this rare case occurs again. After comparing both .rc files, this has been added by Visual Studio below the version block: ///////////////////////////////////////////////////////////////////////////// // // AFX_DIALOG_LAYOUT // IDD_MYBROKEN_DIALOG AFX_DIALOG_LAYOUT BEGIN 0 END
{ "pile_set_name": "StackExchange" }
Q: What if after a patent is awarded, someone proves they invented it earlier? I'm referring to a US patent. (USPTO non provisional Utility patent) And I'm referring to that first inventor not only proving they thought of it, of course, but that they published the idea or even offered a product with it for sale (obviously not successfully, else the USPTO would have noticed it). Would that invalidate the patent? Would the patent hold except to with regard to this first inventor? Something else? A: Under the America Invents Act of 2012 nothing would happen unless someone - the original inventor or any third party - filed for an Inter Partes Review. The cost of filing to try to get an IPR going is $15,500. If the published information about the original inventor's work passed some hurdle, an IPR can be instituted by the USPTO. It is a trial-light proceeding that is estimated to cost at least $100,000. Any claims that are found invalid are invalid for everyone (pending any appeals). The AIA did introduce a new "feature" that could help you hypothetical first inventor to stay in business if he/she was actually producing and selling the thing. It is called "prior user rights" and lets you keep making what ever you were making at the location you are making them at. It is not automatic. Rather it is a defense in an infringement suit. Even before the AIA there was no such thing as "have the patent canceled". The issue of the first inventor's prior art would come up at a patent infringement lawsuit.
{ "pile_set_name": "StackExchange" }
Q: OpenID register on login (authlogic_openid) What is the proper way to register users automatically when they log in with openid? I am using authlogic with an authlogic-oid gem (and an older version of openid_authentication). The stuff I read online so far seems to be obsolete. Does anyone know the proper way to do it with the new gem? What I do now is: options = params[:user_session] || {} [:openid_identifier].each { |k| options[k] = params[k] if params[k] } @user_session = UserSession.new(options) @user_session.save do |result| if result flash[:notice] = "Login successful! (#{result.inspect})" redirect_back_or_default account_url else render :action => :new end end By the way, I don't see the Login Successful flash (but that is not that big of a deal). A: Here is a version with working auto_register http://github.com/mreinsch/authlogic_openid/tree/master
{ "pile_set_name": "StackExchange" }
Q: std::find with two different types I am trying to use std::find with two different types but providing the necessary boolean operators. class FooDetails { public: FooDetails(int size = 5) : m_size(size) { /* empty */ } bool operator<(const FooDetails& other) const { return m_size < other.m_size; } bool operator==(const FooDetails& other) const { return m_size == other.m_size; } private: int m_size; }; class Foo { public: Foo(int size) : m_details(size) { /* empty */} bool operator==(const Foo& other) const { return m_details == other.m_details; } bool operator==(const FooDetails& other) const {return m_details == other; } bool operator<(const Foo& other) const { return m_details < other.m_details; } bool operator<(const FooDetails& other) const { return m_details < other; } FooDetails m_details; }; bool operator==(const FooDetails& lhs, const Foo& rhs) { return lhs == rhs.m_details; } bool operator==(const Foo& lhs, const FooDetails& rhs) {return lhs.m_details == rhs; } bool operator<(const FooDetails& lhs, const Foo& rhs) { return lhs < rhs.m_details; } bool operator<(const Foo& lhs, const FooDetails& rhs) { return lhs.m_details < rhs; } int main() { std::vector<Foo> haystack = { FooDetails(5), FooDetails(6), FooDetails(7) }; FooDetails needle(6); std::find(haystack.begin(), haystack.end(), needle); return 0; } Since std::find uses operator== I would expect this to work, since all necessary functions are provided. However this does not compile. Why is that and how do I fix it? I know I could use std::find_if, but I assume that's a bit slower and even if it's not I'd like to know why std::find doesn't work. A: I've changed your code to this: #include <algorithm> class FooDetails { public: FooDetails(int size = 5) : m_size(size) { /* empty */ } bool operator<(const FooDetails& other) const { return m_size < other.m_size; } bool operator==(const FooDetails& other) const { return m_size == other.m_size; } private: int m_size; }; class Foo { public: Foo(int size) : m_details(size) { /* empty */} FooDetails m_details; }; bool operator==(const FooDetails& lhs, const Foo& rhs) { return lhs == rhs.m_details; } bool operator==(const Foo& lhs, const FooDetails& rhs) {return lhs.m_details == rhs; } bool operator<(const FooDetails& lhs, const Foo& rhs) { return lhs < rhs.m_details; } bool operator<(const Foo& lhs, const FooDetails& rhs) { return lhs.m_details < rhs; } int main() { std::vector<Foo> haystack = { Foo(5), Foo(6), Foo(7) }; FooDetails needle(6); std::find(haystack.begin(), haystack.end(), needle); return 0; } And it successfully compiles. Your original version contains two errors: You try to create std::vector<Foo> initialising it with std::initialization_list<FooDetails>. You have provided too many comparison operators: both free versions and members of the Foo struct. So during lookup compiler complains that it doesn't know which one of them to choose. You should leave only one of them.
{ "pile_set_name": "StackExchange" }
Q: Stripe redirectToCheckout - "TypeError: stripe.redirectToCheckout is not a function" I have a backend in express that takes a productID and returns a Stripe sessionID which I thought could be used with Stripe.redirectToCheckout. Output from backend: "status": "success", "session": { "id": "cs_test_8l6LSFDpAXXXXXXX", "object": "checkout.session", "billing_address_collection": null, "cancel_url": "http://127.0.0.1:3000/product/undefined", "client_reference_id": "5dfd96267d707d32dwe1834967532", "customer": null, "customer_email": "[email protected]", "display_items": [ { "amount": 3999, "currency": "usd", "custom": { "description": "Learn any long term commitment", "images": null, "name": "lifetime Product" }, "quantity": 1, "type": "custom" } ], "livemode": false, "locale": null, "mode": "payment", "payment_intent": "pi_1FvUXBLs8D14wk3oUL3dwxmMOO8", "payment_method_types": [ "card" ], "setup_intent": null, "submit_type": null, "subscription": null, "success_url": "http://127.0.0.1:3000/my-products/?product=5dfd96267d70723e1834967532&user=5e011031ac24131ed53d7439fb68&price=39.99" } } I am not sure how I can use Stripe.redirectToCheckout in my react frontend after the sessionID has been generated. Below is what i tried but getting "TypeError: stripe.redirectToCheckout is not a function" error. import { Link } from "react-router-dom"; import { connect } from "react-redux"; import { Elements, StripeProvider, Stripe } from "react-stripe-elements"; import MyStoreCheckout from "../../components/MyStoreCheckout/MyStoreCheckout"; import Spinner from "../../components/UI/Spinner/Spinner"; import * as actions from "../../store/actions/index"; import classes from "./Subscription.module.css"; const stripe = require("stripe-client")( "sk_test_XXXXXX" ); class Subscription extends Component { constructor(props) { super(props); } monthlySubscribeClickHandler = () => { const productId = "5dfd95e27dw4231707e1834967531"; this.props.onSubscribeClicked(this.props.token, productId); stripe.redirectToCheckout({ sessionId: this.props.sessionId }); }; render() { let buttonName = "SUBSCRIBE"; return ( <div className={classes.User}> <h1>Monthly Subscription</h1> <h3>Learn all modules for $9.99 per month</h3> <Link to=""> <button onClick={this.monthlySubscribeClickHandler}> {buttonName} </button> </Link> <h1>Lifetime Access</h1> <h3>Learn all modules for a nominal payment of $34.99</h3> <Link to=""> <button onClick={this.lifetimeSubscribeClickHandler}> Make one-time payment </button> </Link> </div> ); } } const mapStateToProps = state => { return { loading: state.auth.loading, error: state.auth.error, message: state.auth.message, status: state.auth.status, userId: state.auth.status, token: state.auth.token, sessionId: state.subscription.sessionId }; }; const mapDispatchToProps = dispatch => { return { onSubscribeClicked: (token, productId) => dispatch(actions.subscribeProduct(token, productId)) }; }; export default connect( mapStateToProps, mapDispatchToProps )(Subscription); Please help! A: This is because the stripe-client library used here is outdated and doesn't import the latest Stripe.js library which includes the function you're aiming to use (redirectToCheckout). You'll need to load Stripe.js using the script tag: <script src="https://js.stripe.com/v3/"></script>
{ "pile_set_name": "StackExchange" }
Q: Efficient load CSV coordinate format (COO) input to local matrix spark I want to convert CSV coordinate format (COO) data into a local matrix. Currently I'm first converting them to CoordinateMatrix and then converting to LocalMatrix. But is there a better way to do this? Example data: 0,5,5.486978435 0,3,0.438472867 0,0,6.128832321 0,7,5.295923198 0,1,7.738270234 Code: var loadG = sqlContext.read.option("header", "false").csv("file.csv").rdd.map("mapfunctionCreatingMatrixEntryOutOfRow") var G = new CoordinateMatrix(loadG) var matrixG = G.toBlockMatrix().toLocalMatrix() A: A LocalMatrix will be stored on a single machine and hence not make use of Spark's strengths. In other words, using Spark seems a bit wasteful, although still possible. The easiest way to get the CSV file to a LocalMatrix is to first read the CSV with Scala, not Spark: val entries = Source.fromFile("data.csv").getLines() .map(_.split(",")) .map(a => (a(0).toInt, a(1).toInt, a(2).toDouble)) .toSeq The SparseMatrix variant of the LocalMatrix has a method for reading COO formatted data. The number of rows and columns need to be specified to use this. Since the matrix is sparse this should in most cases be done by hand but it's possible to get the highest values in the data as follows: val numRows = entries.map(_._1).max + 1 val numCols = entries.map(_._2).max + 1 Then create the matrix: val matrixG = SparseMatrix.fromCOO(numRows, numCols, entries) The matrix will be stored in CSC format on the machine. Printing the example input above will yield the following output: 1 x 8 CSCMatrix (0,0) 6.128832321 (0,1) 7.738270234 (0,3) 0.438472867 (0,5) 5.486978435 (0,7) 5.295923198
{ "pile_set_name": "StackExchange" }
Q: translate this loop into purr? I'm trying to make a teaching example on sampling for students to run, but the result is too slow when the number of iterations gets in the thousands (the real data frame df has several million rows). Can I speed this up with purr? library(tidyverse) set.seed(1432) df <- data.frame(v1 = sample(1:10, 100, replace=TRUE), v2 = c(rep("A", 50), rep("B", 50)) ) output <- NULL for (i in 1:10) { set.seed(i) d <- df %>% filter(v2=="A") %>% sample_n(20, replace=FALSE) mean = mean(d$v1) output <- c(output, mean) } output A: You can use purrr as follows. map_dbl(1:10, function(x){ set.seed(x) d <- df %>% filter(v2=="A") %>% sample_n(20, replace=FALSE) return(mean(d$v1)) }) # [1] 5.15 5.90 5.70 5.55 5.60 4.95 5.40 5.40 5.65 5.40 A: purrr is not necessarily faster, but is more readable than basic control structures in R. When it comes to replacing the loop, here is what you can do in base R: sapply(1:10, function(x){ set.seed(x) d <- df %>% filter(v2=="A") %>% sample_n(20, replace=FALSE) mean(d$v1) }) UPDATE That you use dplyr and purrr does not guarantee that your code is going to be fast. IMO, these packages were developed to improve code readability in the first place rather than to speed up expensive calculations. You can achieve a significant speed up if you carefully use basic R data structures. d is the original loop, a and b are functional programming solutions, and f is the optimized solution: a <- function(y){sapply(1:y, function(x){ set.seed(x) d <- df %>% filter(v2=="A") %>% sample_n(20, replace=FALSE) mean(d$v1) })} b <- function(y) {map_dbl(1:y, function(x){ set.seed(x) d <- df %>% filter(v2=="A") %>% sample_n(20, replace=FALSE) return(mean(d$v1)) })} d <- function(y){ output <- NULL for (i in 1:y) { set.seed(i) d <- df %>% filter(v2=="A") %>% sample_n(20, replace=FALSE) output <- c(output, mean(d$v1)) } output } f <- function(y){ output <- vector("list", y) for (i in 1:y) { set.seed(i) d <- df[df$v2 == "A", ] d <- d[sample(1:nrow(d), 20, replace = FALSE), ] output[[i]] <- mean(d$v1) } output } microbenchmark::microbenchmark(a(100),b(100),d(100), f(100)) Unit: milliseconds expr min lq mean median uq max neval a(100) 172.06305 187.95053 205.19531 199.84411 210.55501 306.41906 100 b(100) 171.86030 186.18869 206.50518 196.07746 213.79044 397.87859 100 d(100) 174.45273 191.01706 208.07125 199.12653 216.54543 365.55107 100 f(100) 14.62159 15.80092 20.96736 19.14848 24.16181 37.54095 100 Observe that f is almost 10x faster that d, while a, b, and d have almost the same speed.
{ "pile_set_name": "StackExchange" }
Q: Add a running total/cumulative column I am trying to get a running total for the count of sales per Actual_Sale_Date in my table for the year 2015 but thus far all my attempts been futile. I took a look at the attached link and emulated the process but to no gain. Can someone help out here please? Calculating Cumulative Sum in PostgreSQL select Actual_Sale_Date, extract(week from Actual_Sale_Date) as week_number, count(*) from mytable where extract(year from Actual_Sale_Date) = 2015 Result: (Requested Running_Total) Actual_Sale_Date week_number count running_total 2015-01-04 00:00:00 1 1 1 2015-01-06 00:00:00 2 3 4 2015-01-08 00:00:00 2 4 8 2015-01-09 00:00:00 2 5 13 2015-01-11 00:00:00 2 1 14 2015-01-15 00:00:00 3 2 16 2015-01-21 00:00:00 4 1 17 2015-01-23 00:00:00 4 4 21 2015-01-24 00:00:00 4 1 22 2015-01-26 00:00:00 5 2 24 A: Just use window functions: select Actual_Sale_Date, extract(week from Actual_Sale_Date) as week_number, count(*), sum(count(*)) over (order by Actual_Sale_Date) from ?? where extract(year from Actual_Sale_Date) = 2015 group by Actual_Sale_Date, extract(week from Actual_Sale_Date);
{ "pile_set_name": "StackExchange" }
Q: How to convert formatted content of NSTextView to string I need transfer content of NSTextView from Mac app to iOS app. I'm using XML as transfered file format. So I need to save content of NSTextView (text, fonts, colors atd.) as a string. Is there any way how to do that? A: One way to do this is to archive the NSAttributedString value. Outline sample code typed directly into answer: NSTextView *myTextView; NSString *myFilename; ... [NSKeyedarchiver archiveRootObject:myTextStorage.textStorage toFile:myFilename]; To read it back: myTextView.textStorage.attributedString = [NSKeyedUnarchiver unarchiveObjectWithFile:myFilename]; That's all that is needed to create and read back a file. There are matching methods which create an NSData rather than a file, and you can convert an NSData into an NSString or just insert one into an NSDictionary and serialise that as a plist (XML), etc.
{ "pile_set_name": "StackExchange" }
Q: RIA Services SP1 build errors: csdlPath cannot be null We're trying to integrate RIA Services SP1 with one of our existing EF models; we're getting this strange build error, on one of the development machines and on the TFS build server, but other dev machines can build without a problem. I've given up on trying to find differences between the machines - any idea what the problem could be? C:\Program Files (x86)\MSBuild\Microsoft\Silverlight\v4.0\Microsoft.Ria.Client.targets (304): Value cannot be null. Parameter name: csdlPath Our EF model is somewhat customized - we needed to support both SQL Server and Oracle, and we have separate SSDL files for each; however, RIA shouldn't have anything to do with that, right? And even if it did, some of the dev machines can build and run the solution without a problem. Help? A: Well, Colin Blair pointed out that the RIA build task does parse the CSDL files when you use vanilla entities (not pocos), in order to find any additional information for automatically applied validation attributes etc. It seems the answer is to generate matching csdl and msl files (the RIA task does a GroupBy on the resource names without extension). Still not sure why it worked on some machines though... maybe GroupBy returns the groups in a different order and only the first match is processed? Not sure yet.
{ "pile_set_name": "StackExchange" }
Q: Cadê a opção de rejeitar por "edição insuficiente"? Estou louco ou a opção de rejeitar por "edição insuficiente" sumiu? É um das coisas que mais acontecem em edições. A: Com a alteração que introduziu os botões de editar+aprovar e editar+rejeitar, esse motivo foi considerado obsoleto. Isso ainda é um pouco polêmico (ref, ref), mas pelo que entendi vão insistir nesse caminho para ver se dá certo. A lógica é: se a edição é "insuficiente", em primeiro lugar você deve resolver o problema, e fazer uma edição que seja melhor – ou pelo menos "suficiente". Com os novos botões você poderá decidir se a edição original será considerada aprovada ou rejeitada. Se a edição não acrescentar nada válido (por exemplo, apenas adicionar formatação aleatória), rejeite como vandalismo. Infelizmente há outros casos, que ainda estão no limbo. Se não vir o que editar e nenhum motivo enlatado servir, use um motivo personalizado.
{ "pile_set_name": "StackExchange" }
Q: Number of automorphisms of saturated models I have the following assignment question: Let $M$ be an $L$-model of cardinality $\kappa$. Assume $M$ is saturated. How can you show that $|\text{Aut}(M)|=2^{|M|}$? I see two possible ideas/connections/intuitions here: Definable sets. Since $M$ is saturated, these are either finite or of cardinality $\kappa$. Then maybe you can somehow use the fact that these are preserved by automorphisms? Maybe some sort of diagonal argument. If you try to capture $\text{Aut}(M)$ with $\lambda<2^{|M|}$ automorphisms, then you can show that you'll be missing at least one. There's this question, whose title was originally going to be my title, but I wanted to avoid confusion. While it doesn't really answer my question, perhaps the idea of moving non-definable points via automorphisms could yield the required cardinality for $\text{Aut}(M)$. I imagine using the finite definable sets (I believe these are called algebraic, but correct me if I'm wrong), and "permutating" the points outside of these sets? Then perhaps it becomes an easy cardinality argument... I'm mostly thinking out loud, as I'm not sure how to make all of these ideas concrete, and I'm not even sure if they are on the right path. Help? A: I decided to write up an answer, so that this question can be removed form the list of unanswered questions. First enumerate $M = \{m_\alpha : \alpha < \kappa\}$. For every $s \in 2^{<\kappa}$ we construct a partial automorphism $f_s$. I.e. $f_s : M \to M$ is an elementary map. The idea is that these automorphisms extends one another ($t \subseteq s$ implies $f_t \subseteq f_s$) but $f_{s0}$ and $f_{s1}$ disagree on some element. In the end for $q \in 2^\kappa$ we define $f_q = \bigcup_{\alpha < \kappa} f_{q|_\alpha}$, which by the above is a well defined elementary map and $f_q \neq f_p$ for $q \neq p \in 2^\kappa$. We also throw in the back and forth condition to make $f_q$-s automorphisms. More precisely Let $f_\emptyset = \emptyset$. If $\delta$ is a limit ordinal and $s \in 2^\delta$, let $f_s = \bigcup_{\alpha < \delta} f_{s|_\alpha}$ If $s \in 2^{\alpha+1}$ consider two cases. If $\alpha$ is an even ordinal, then pick $m \in M$ of minimal index not in the domain of $f_{s|_\alpha}$. By saturation pick $n_0, n_1$ in $M$ such that $f_{si} = f_s \cup \{\langle m, n_i \rangle\}$ are elementary. If $\alpha$ is an odd ordinal, go back in a similar way. I.e. pick $n \in M$ with the least index not in the image of $f_{s|_\alpha}$ and find two distinct element to extend $f_{s|_\alpha}$ with.
{ "pile_set_name": "StackExchange" }
Q: Saving variable of unknown subclass type in switch statement I have a superclass TetrisPiece, with subclasses for each variation of the piece, i.e. class PieceI extends TetrisPiece{ } class PieceJ extends TetrisPiece{ } etc... In a different class I have a switch statement based on a random number that creates a random piece switch(rand){ //I case 1: { PieceI pieceI = new PieceI(); break; } //T case 2: { PieceT pieceT = new PieceT(); break; } etc... default: break; } My intention is to extract the piece that is generated from the scope of the switch statement so I can use it later on in the class. The switch method obviously does not work because of the scope issue, and I cannot create a superclass array outside of the switch statement because I would have no ability to cast the indices due to randomization. Any help is appreciated. A: Create an instance of the superclass TetrisPiece, and then assign PieceT, PieceI, etc to it inside the switch statement. TetrisPiece piece; switch(rand){ //I case 1: { piece = new PieceI(); break; } //T case 2: { piece = new PieceT(); break; } etc... default: break; }
{ "pile_set_name": "StackExchange" }
Q: Unterschied zwischen "Körper" und "Leib" Was ist der Unterschied zwischen den Begriffen Körper und Leib? Ich meine in dieser Bedeutung (nach dem Duden): Körper 1. a. das, was die Gestalt eines Menschen oder Tieres ausmacht; äußere Erscheinung eines Menschen oder Tieres, Gestalt; Organismus eines Lebewesens Leib 1. a. (gehoben) Körper b. (gehoben) äußere Erscheinung eines Menschen, Gestalt Gibt es neben dem Gebrauch (gehoben oder nicht) noch weitere Differenzierungen? A: Duden ist kein Lexikon für Deutschlernende. Lexika, die speziell für Deutschlernende konzipiert sind, müssen, glaube ich, erst noch geschaffen werden. Hier ist uns Englisch mit seinem Oxford Advanced Learner's Dictionary 100 Jahre voraus. Duden's Bemerkung "Leib ist gehoben" stimmt nur teilweise und ist nicht sehr präzise. Körper ist das normale Wort. Und man müßte genauer untersuchen, wo wir Leib benützen. 1 Wir sagen Oberkörper, aber Unterleib. 2 In religiösen Texten wird oft Leib im übertragenen Sinn gebraucht. 3 Hauptsächlich wird Leib idiomatisch benützt. Das heißt, in vielen feststehenden Redewendungen benützen wir Leib. Sie verbrannte bei lebendigem Leib. Du hast kein Herz im Leib. DWDS gibt einen guten Einblick in solche Wendungen. http://www.dwds.de/?qu=leib Der Umgang mit dem Digitalen Wörterbuch der deutschen Sprache (DWDS) will gelernt sein. Was hier an Material zusammen getragen wurde, ist allerdings phänomenal. Für die Benützung müßte es allerdings einen Kurs geben. Es gibt acht Teile: 1 Lexikonteil mit Worterklärung 2 Etymologisches Wörterbuch. Das ist das Lexikon von Pfeiffer. Scrollbar. 3 Synomymgruppen 4 Wortprofil. Scrollbar. 5-8 Textmaterial (in Unmengen). Alle Felder sind scrollbar. Die kurze Startseite ist lesenswert. http://www.dwds.de Es ist schade, das dieses erstaunliche Informationswerk zur deutschen Sprache keine Einführung für den Beñützer hat. A: Ein kleiner Versuch der Differenzierung: Leib ist aus dem mittelhochdeutschen "lip" entstanden, das sowohl Leben als auch Leib bezeichnete. Der Körper ist aus dem lateinischen "corpus" entlehnt, das den Körper als auch den Leichnam bezeichnete. Dementsprechend lässt sich der Leib als belebter individueller Körper beschreiben, der lebendig und erspürbar und eng mit den Befindlichkeiten und dem Lebensfunken eines Menschen verknüpft ist, während der Körper eher die Materie des Anatomen oder Physiologen beschreibt, die lebendig oder auch tot sein kann. Der eher ganzheitlich gemeinte Leib ist aus dem alltäglichen Sprachgebrauch ziemlich verschwunden, der leichter einer zergliedernden Weltsicht verbundene "Körper" ist im heutigen Sprachgebrauch üblich.
{ "pile_set_name": "StackExchange" }
Q: Ember.js: a way to do a real catch all route? I know something like this can be done but what I'm asking for is an else route that will match any URL (or state) that wasn't previously defined. This could be handy to catch if a user is trying to access an invalid state or URL. However, is okey if there is another way to do this :D Hope this makes sense. A: This is taken from the answer to another question, so upvote that one: App.Router.map(function() { this.route('catchAll', { path: '*:' }); }); App.CatchAllRoute = Ember.Route.extend({ redirect: function() { this.transitionTo('index'); } });
{ "pile_set_name": "StackExchange" }
Q: Java, Including int Variables in Print line How would you insert a variable in the middle of this sentence where the () are System.out.println("Since there are (trying to insert int bluerocks here) there must be less than 12 normal rocks "+bluerocks); A: You've got some options. Either with string concatenation, right in the spot that you want it (mind the number of quotes): System.out.println("Since there are (" + bluerocks + ") there must be less than 12 normal rocks"); ...or with symbol substitution, via printf: System.out.printf("Since there are (%d) there must be less than 12 normal rocks", bluerocks);
{ "pile_set_name": "StackExchange" }
Q: Validation message acess without for loop I wanta to access direct [0] => Please enter only spaecial characters., [0] => You cannot enter more than 1 character . this validation message ,but without foreach loop. My demo code is.. Array ( [CodeConfiguration] => Array ( [0] => Array ( [SeriesConcateCharacter] => Array ( [0] => Please enter only spaecial characters. ) [NumberPaddingCharacter] => Array ( [0] => You cannot enter more than 1 character. ) ) ) ) So please suggest appropriate solution. A: You can access like this.. echo $yourarray['CodeConfiguration'][0]['SeriesConcateCharacter'][0]; Demo Tip: Just start from the top and go down until you reach your destination and keep numbering the routes. EDIT : I didnt want to hard code value pass ['CodeConfiguration'] and ['SeriesConcateCharacter']. array_walk($yourarray['CodeConfiguration'][0],function ($v) { echo($v[0])."<br>";} ); Demo
{ "pile_set_name": "StackExchange" }
Q: displaying a series of youtube embeds that can be hidden/displayed My goal is to show a series of embedded youtube videos on one page but allowing the user to hide or show any youtube video by clicking a button associated with a specific youtube video on the page. I made a form that submits the youtube embed code to a mysql database and I created a php file to retrieve every embed code using a for loop. For each iteration of the for loop, a youtube video will pop up with a corresponding button which will allow the user to hide or show the youtube video. It works when there is only one entry in the mysql table but does not work when more youtube embed codes are uploaded. For example, when there are two youtube embed codes uploaded, two buttons are created, but when I click either of the two buttons, it will only show or hide the first youtube embed. None of the buttons will show the second youtube video. here is the code with some edits: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>hide/show iframe</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/> <style type="text/css"> <!-- #frDocViewer { width:70%; height:50%; display:none; } --> </style> <script type="text/javascript"> <!-- function HideFrame() { var fr = document.getElementById ("frDocViewer"); if(fr.style.display=="block") { fr.style.display="none"; } else { fr.style.display="block"; } } //--> </script> </head> <body> <?php mysql_connect ("","","") or die(mysql_error()); mysql_select_db ("") or die(mysql_error()); $lastid = mysql_query ("SELECT * FROM embed ORDER BY id DESC LIMIT 1"); $lastid = mysql_fetch_assoc($lastid); $lastid = $lastid['id']; for ($count=1; $count<= $lastid ; $count++) { $iframe = mysql_query ("SELECT * FROM embed WHERE id=$count "); $iframe = mysql_fetch_assoc($iframe); $iframe = $iframe['url']; echo " <image src='utube.gif' onclick='HideFrame()' /> <div id='frDocViewer'> $iframe </div> "; } ?> </body> </html> A: Because each div has the same ID. You need to create unique ID's for each DIV to show or hide ie. frDocViewer1, frDocViewer2 etc Use your $count variable to echo it's value onto the ID as it will increment by 1 for each iteration of the loop. echo " <image src='utube.gif' onclick='HideFrame()' /> <div id='frDocViewer_{$count}'> $iframe </div> "; Then you just need to make sure that you have corresponding Javascript for each of those DIV's. I would send the id into the javascript function using your onclick tag. for ($count=1; $count<= $lastid ; $count++) { $iframe = mysql_query ("SELECT * FROM embed WHERE id=$count "); $iframe = mysql_fetch_assoc($iframe); $iframe = $iframe['url']; echo " <image src='utube.gif' onclick='HideFrame({$count})' /> <div id='frDocViewer_{$count}' class='frDocViewer'> $iframe </div> "; } And then have the javascript code as something like: var old_element = null; function HideFrame(id) { var fr = document.getElementById("frDocViewer_" + id); if(fr != old_element) { fr.style.display = "block" if(old_element != null) old_element.style.display = "hide"; old_element = fr; } } Then finally you need to change your CSS to make frDocViewer a class rather than a unique style. Notice above in the PHP echo string I added in the new class attribute to the DIV <style type="text/css"> .frDocViewer { width:70%; height:50%; display:none; } </style> PS: This code might not actually compile, it's just a rough guide.
{ "pile_set_name": "StackExchange" }
Q: What is the practical limit of a textarea? Using IE6+, what is the maximum amount of text you can POST with a <textarea> before something breaks? Edit: The answer I'm hoping for is "there's no way you could actually type something meaningful and unmallicious into a textarea and crash Internet Explorer." A: Because of the way POST data is sent there's no low-end limit to the number of characters you can send. There is an upper bound, of course. How much data are you talking about here? The answer is sneezing will cause IE to collapse, sneezing softly doubly so for IE6
{ "pile_set_name": "StackExchange" }
Q: How to use Struts2 convention without using any action class In Struts2 we can define action without using action class in struts.xml as follows: <action name="error"> <result>/error.jsp</result> </action> In my application I am using struts2 convention. In this case how to avoid writing action classes. I have many scenarios where I just want to go to the page without using any business logic. My result path is not just a JSP. I am using tiles. I am using code as follows: @Action(value="homePage", results={@Result(name="success", location="homePage", type="tiles")}) A: You can place you jsp to the WEB-INF/content this the default result path. Also you can change this using a constant struts.convention.result.path. Convention plugin creates configuration from all JSPs there. So if you have do-something.jsp under result path you can use /do-something in the browser to return this actionless result.
{ "pile_set_name": "StackExchange" }
Q: Can i set the UITableViewCellAccessoryCheckmark on BarButton? i want UITableViewCellAccessoryCheckmark the all cells of tableView while am touching the Bar Button ? A: You need to set the cell accessory types in the method which you have given in the barbutton declaration. Check this code. Follow like that UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(showChecked)]; - (void)showChecked{ isChecked = YES; [tableView reloadData]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ cell.accessoryType = UITableViewCellAccessoryCheckmark; return cell; }
{ "pile_set_name": "StackExchange" }
Q: Arduino + WiFi 101 Gerber Files Is it possible to get the Gerber files for the Arduino Uno r3 and the WiFi 101? I've been teaching myself the SW side of this hobby (with much help from SE Arduino) and I'd like to better understand, or at least get some exposure to, the HW side. Are the Arduino Uno and WiFi 101 Gerber files available to the general public or are they considered IP? I am under the impression that it is open source but I'm not sure where the OS boundary ends. A: On the Arduino UNO and Wifi shield websites in the Documentation section you can download the Schematic (PDF) and PCB layout (Eagle) files. The page already says The Uno is open-source hardware! You can build your own board using the follwing files With the free version of Eagle, you can open it and export to gerber file format.
{ "pile_set_name": "StackExchange" }