text
stringlengths
64
81.1k
meta
dict
Q: What web programming language is this? I've been looking through the Netgear firmware source for some of the firmwares and while looking at the web directories and HTML files in the source, I've noticed most or all of the HTML files have something similar to this at the top or at random positions in the page: <% http_header("style/form.css", "/funcs.js", "/upnp.js") %> <% body_header("_upnp", "UPNP_upnp.htm", "upnp") %> It looks like some sort of templating engine/language but I'm not sure what. Just thought this would be interesting to know. If anybody has any information, please leave a response. Thanks! A: It appears to be a custom scripting language modelled after ASP, and referred to internally as "ASP". The source code for the interpreter is missing from the Netgear source dump (argh!), but the Makefile mentions a number of files with "ASP" in their name, and the binary includes similarly named methods, such as: asp_bridge_mode_gateway asp_wds_enable asp_wla_wps asp_dns_check_host asp_check_hijack_status asp_show_devices
{ "pile_set_name": "StackExchange" }
Q: PHP SimpleTest - Handling Exceptions I have a few simple classes used in a forum application. I'm trying to run some tests using SimpleTest, but I'm having problems with exceptions. I have a section of code which generates a custom exception. Is there a way to catch this exception in my test and assert that it is what I expect? This is the method within my class: public function save() { $this->errors = $this->validate(); try { if (empty($this->errors)) { Database::commitOrRollback($this->prepareInsert()); } else { throw new EntityException($this->errors); } } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } } Any advice appreciated. Thanks. A: function testSaveMethodThrows() { $foo = new Foo(); try { $foo->save(); $this->fail("Expected exception"); } catch (EntityException $e) { $this->pass("Caught exception"); } } Or use expectException:
{ "pile_set_name": "StackExchange" }
Q: Module - JavaScript: Good Parts. How is this callback getting its arguments? I am engaging with the famous "JavaScript: The Good Parts" by Douglas Crockford. It is an awesome book of course. While, I may not have been ready for it yet, i thought of giving it a shot. I need some help to understand the following example. The second argument in the replace() takes 2 arguments a and b. But where are they defined? How do they take a value? Thanks in advance. I did refer to another stack, but i don't think it really helped. String.method('deentityify', function ( ) { // The entity table. It maps entity names to // characters. var entity = { quot: '"', lt: '<', gt: '>' }; // Return the deentityify method. return function ( ) { // This is the deentityify method. It calls the string // replace method, looking for substrings that start // with '&' and end with ';'. If the characters in // between are in the entity table, then replace the // entity with the character from the table. return this.replace(/&([^&;]+);/g, function (a, b) { var r = entity[b]; return typeof r === 'string' ? r : a; } ); }; }( )); A: Functions can be written to accept other functions as arguments. Such functions are called Higher-order functions. In this example a and b are just names for parameters of the function. What exactly will be assigned to that parameters is up-to the implementation of the replace. A good illustration of this idea would be var items = [{name:"item1",price:100}, {name:"item2",price:200}]; // lets find an object in the array, that has name "item2" var result = items.find(function(a){return a.name==="item2"}); console.log(result); in this code function find accepts a function that determines a match-criteria. Code of function find will iterate the array and apply match-criteria function to each element until either an array ends or first match is found. For better understanding you can change parameter function like: result = items.find(function(whatever){return whatever.price>=100}); result = items.find(function(whatever){return whatever.price>100});
{ "pile_set_name": "StackExchange" }
Q: For U.S. history 1800-1830, what was GDP by sector and industry? The U.S. Census Bureau's Historical Statistics of the United States does not appear to break GDP down. I'm aware that the terminology is imprecise: GDP is a modern term, but is much shorter than the contemporary understanding, "What was the total value of goods and services produced by sector?" "Industry" is also an imprecise term, but is much clearer than "what was the total value of goods and services produced in agriculture, craft, finance, and other sectors including nascent industrial activity". A: According to this source (page 70), the shares of labor devoted to "industry" in the U.S. economy were 11.9% in 1800, 14.9% in 1810, 19.0% in 1820, and 20.0% in 1830, with the remainder devoted to agriculture. '"Industrialization" was only getting started in the first half of the 19th century, but picked up greatly in the second half.
{ "pile_set_name": "StackExchange" }
Q: Can Python's asyncio.coroutine be thought of as a generator? I googled python coroutine, and saw only generators (Almost almost all the examples use yield without asyncio.) Are they really the same? What is the difference between asyncio.coroutine and a generator? A: Most coroutine implementations in Python (including those provided by asyncio and tornado) are implemented using generators. This has been the case since PEP 342 - Coroutines via Enhanced Generators made it possible to send values into running generator objects, which enabled the implementation simple coroutines. Coroutines technically are generators, they're just designed to be used in a very different way. In fact, the PEP for asyncio explicitly states this: A coroutine is a generator that follows certain conventions. asyncio.coroutine is a generator. Quite literally: >>> import asyncio >>> @asyncio.coroutine ... def mycoro(): ... yield from asyncio.sleep(1) ... >>> a = mycoro() >>> a <generator object mycoro at 0x7f494b5becf0> The difference, again, is in how the two things are meant to be used. Trying to iterate over a asyncio.coroutine like an ordinary generator will not work: >>> next(a) Future<PENDING> >>> next(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in mycoro File "/usr/lib/python3.4/asyncio/tasks.py", line 548, in sleep return (yield from future) File "/usr/lib/python3.4/asyncio/futures.py", line 349, in __iter__ assert self.done(), "yield from wasn't used with future" AssertionError: yield from wasn't used with future Clearly, you're not meant to iterate over it. You're only meant to yield from it, or register it with the asyncio event loop using asyncio.create_task or asyncio.async. As I mentioned earlier, it's been possible to implement coroutines using generators since PEP 342, which was long before asyncio or yield from came along; that feature was added back in 2005. asyncio and yield from just add features that make writing coroutines easier.
{ "pile_set_name": "StackExchange" }
Q: How to get a single header column cell value using pandas? This seems so easy but I cannot figure out what I'm missing Column_Name = excel_data_df.columns(0) print (Column_Name) Error: Traceback (most recent call last): File "C:/Users/206415779/Python/FINDIT/FINDIT START", line 169, in Column_Name = excel_data_df.columns(0) TypeError: 'Index' object is not callable Do I need to index my headers and then call the specific index I'm looking for? I am just trying to print the header value of a specific row, but I only want the header value not the entire column A: Just answering this so nobody wastes their time, fix was this below, simple misuse of ( rather than using the correct [. Column_Name = excel_data_df.columns[0] print (Column_Name)
{ "pile_set_name": "StackExchange" }
Q: Limiting characters to be placed in a cell from a VLOOKUP function? We are doing inventory and using some VLOOKUP functions to pull information from our database. I've come a long way in setting up the sheets we will be using. However, for the Length and Width of the Slabs we have, I would want to also pull the information either from the DATABASE sheet, or from the same sheet, under the DESCRIPTION column. Basically, I need columns N and O to be filled automatically with the appropriate information from the description of the item (column H in the same sheet), which is only L X W, always as the first piece of information for any item in our database, or column H. I've tried data validation rules but it only works to tell me it is invalid, I need the cell to be cleared automatically of any unwanted characters. I thought about SPLIT function using the X as a delimiter , but it won't work well as I have to bring back the sheet to Excel later. UPDATE: Sorry folks I will upload an image of the entire sheet. F27 is the "Product Code", which is used to pull the description, class 1, class 2, and U/M from the database. I can either pull L X W from the database as well, or pull it from description from within the same sheet Any suggestions on how to accomplish this? TEST SHEET BELOW: https://drive.google.com/open?id=1StOWs0sTsdIUT76tKVvdjGHW7s-PXSNA1ceIQsYsFFY A: Please use the following formula in cell N5: =ArrayFormula(IFERROR(SPLIT(REGEXEXTRACT(H5:H11,"(\d+[X|x]\d+)"),"X|x",1,1))) Functions used: ArrayFormula IFERROR SPLIT REGEXEXTRACT
{ "pile_set_name": "StackExchange" }
Q: How can I overwrite file contents with new content in PHP? I tried to use fopen, but I only managed to append content to end of file. Is it possible to overwrite all contents with new content in PHP? A: Use file_put_contents() file_put_contents('file.txt', 'bar'); echo file_get_contents('file.txt'); // bar file_put_contents('file.txt', 'foo'); echo file_get_contents('file.txt'); // foo Alternatively, if you're stuck with fopen() you can use the w or w+ modes: 'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. 'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. A: MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU] $f=fopen('myfile.txt','w'); fwrite($f,'new content'); fclose($f); Warning for those using file_put_contents It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time A: $fname = "database.php"; $fhandle = fopen($fname,"r"); $content = fread($fhandle,filesize($fname)); $content = str_replace("192.168.1.198", "localhost", $content); $fhandle = fopen($fname,"w"); fwrite($fhandle,$content); fclose($fhandle);
{ "pile_set_name": "StackExchange" }
Q: Quickblox android API for chat messaging free or not? I have used git hub code sample .It work very good i want to develop a application using this api but i am confused this api free or not.If not than what type of payment plan they have. I have already to visit Quickblox website's plan section but i don't understand about their plan A: QuickBlox offers a starter tier which you can use absolutely free. All you need is register a free QuickBlox account and add your App there. Each tier has particular server configuration. E.g. with free tier you can have 20/s chat messages, 1000 concurrent users, 20/s notifications etc (check details). If you feel that free tier is not enough for you, you can upgrade to bigger plan any time. Besides if you are looking for good quality and support you should pay attention to Pro and Enterprise plans.
{ "pile_set_name": "StackExchange" }
Q: I am a bit confused about deployment of cloud services, and particular whether just code can be replaced Just getting used to VS2012 publishing of Cloud Services. At present I have a one instance webrole which contains a MVC3 application. I can publish it to Azure without issue, and it creates the Cloud Service>Web Role>VMs. Fine. Takes a little while. However when I do a little code change how can I migrate just this code change without replacing all the VMs that implement the WebRole etc. It seems that Code and infrastructure are inseparable, or have I misunderstood. Is there a way to just update the code bit? Thanks. A: When you roll out an update, you upload an entire package containing not only your code files, but also the configuration for the VM, such as # of instances, ports to open on the firewall, local resources to allocate, etc. These configuration settings are part of the code package - so there is more going on than just updating code files. However, there are a couple of methods you can use to have more granular control over updates. Use Web Deploy. One thing to keep in mind, is that any automatic service updates will restore your website to the last fully-deployed package, which may not be as up-to-date. You would only want to use this in staging, then do a full package update for production rollout. Use an Azure Web Site instead, which allows continuous integration with your source control provider, and direct updates to the code. Use an Iaas VM instead. These are basically the same as running your own custom server in the Azure cloud, and you have full control over the OS. However, you also have full responsibility for keeping the OS updated and secure. You can also enable RDP to your Azure Web Role VM's. You will find all your code files there and IIS, but I wouldn't recommend updating your code this way for the same reasons listed in #1.
{ "pile_set_name": "StackExchange" }
Q: Delphi Indy Cliente envía paquetes de 64 KB y el Server recibe 2 paquetes que suman 64 KB Con el componente TIDTCPServer de Indy en Delphi se recibe un paquete fraccionado que el cliente envió de 64 KB. ¿Cómo recibo el paquete completo en el evento Execute del Server? Gracias A: No tienes control de esto, TCP no es un protocolo orientado a mensajes, sino un protocolo orientado al flujo de datos (no sabría como traducir: stream based protocol). En otras palabras, el stack TCP, en cualquier punto (puede ser la propia tarjeta de red del cliente, routers, switch, hubs, etc.) puede dividir un mensaje en la cantidad de paquetes que considere convenientes (y regularmente lo hace, por ejemplo a medida que los paquetes van atravesando redes antiguas con diferentes capacidades, velocidades o incluso que funcionan sobre protocolos distintos a TCP). Otra forma de verlo, es que si tu envías los siguientes mensajes ABC DEF En el cliente, podrías recibir todas las combinaciones de secuencias, por citar algunos ejemplos: ABCDEF ABC DEF A BCD EF A BCDEF ABCDE F Y una larga lista de etcéteras De hecho, hablando de tu pregunta particular, ninguna red que yo conozca sería capaz de transmitir 64 Kb en un solo paquete, el hecho de que tu veas solo dos paquetes es una mera casualidad y producto de la red y equipo particular dónde te encuentras ejecutando tu cliente o servidor, pero en otra red, otro equipo, incluso el mismo equipo bajo condiciones distintas, muy probablemente verías un comportamiento distinto. Es normal diseñar, sobre TCP, protocolos (de más alto nivel) orientados a mensajes, pero en este caso, para implementar las soluciones debes tener en mente como funciona el protocolo subyacente. Suena más complicado de lo que es, hay básicamente tres formas de trabajo. Si vas a recibir mensajes de longitud fija, en un ciclo lees datos, y simplemente sigues a la espera de más datos hasta que se complete un nuevo mensaje. Hay protocolos que están en este ciclo hasta que reciben un mensaje con el cual terminar la comunicación. Cada vez que completas un mensaje, lo procesas, y sigues en el ciclo esperando más mensajes. Si vas a recibir mensajes de longitud variable, una técnica bastante común es enviar primero la longitud en bytes del mensaje que se enviará (que es un dato de longitud fija). En el otro punto, lees primero este dato, y luego, pues, ya sabes cuantos bytes esperar antes de terminar la comunicación o de dar por completado ese nuevo mensaje. En protocolos donde hay un flujo continuo de información, regularmente se establecen secuencias de bytes que indican el inicio o fin de los mensajes o de la comunicación. Todo el tiempo el receptor está inspeccionando los datos recibidos hasta encontrar una de estas secuencias y actuar en consecuencia. Hay muchos ejemplos de todos estos tipos en el Internet de hoy. Suponiendo el caso de mensajes de longitud fija, y tomando tu ejemplo de 64Kb, la manera más simple de implementarlo (solo para efectos ilustrativos), es hacer muy grande el ReadTimeout, y que el propio componente TidTCPServer se encargue de esperar hasta lograr leer los 64Kb, por ejemplo: function TForm1.BytesToHex(const AData; Size: Cardinal): string; var I: Integer; B: pByte; const Digits : array [0..15] of char = '0123456789ABCDEF'; begin Result := ''; B := @AData; for I := 0 to Size - 1 do begin Result := Result + Digits[B^ shr 4] + Digits[B^ and 15]; if ((I + 1) mod 4) = 0 then Result := Result + ' '; Inc(B); end; end; procedure TForm1.IdTCPServer1Execute(AContext: TIdContext); var Data: TidBytes; strData: string; begin SetLength(Data, 64 * 1024); //no es recomendable hacer esto en producción, es solo un ejemplo //Establecer el ReadTimeout a 60 segundos podría romper ciertas cosas //pues el sistema esperará hasta 60 segundos por cada siguiente paquete //que potencialmente podría ser de hasta 1 byte de longitud, haciendo //la espera realmente larga para un _mensaje_ de 64Kb //en una red lenta. AContext.Connection.IOHandler.ReadTimeout := 60000; while AContext.Connection.Connected do begin AContext.Connection.IOHandler.ReadBytes(Data, Length(Data), False); strData := BytesToHex(Data[0], Length(Data)); TThread.Synchronize(nil, procedure begin Memo1.Lines.Add(strData); Inc(FNumeroMensajes); Label1.Caption := IntToStr(FNumeroMensajes); end); end; end; Puedes probar fácilmente la teoría, haciendo un solo envío de 1Mb, desde un cliente, como este: procedure TForm1.Button1Click(Sender: TObject); var Datos: TidBytes; I: Integer; begin Inc(FNumeroMensaje); IdTCPClient1.Connect; try SetLength(Datos, 1024 * 1024); for I := Low(Datos) to High(Datos) do Datos[I] := FNumeroMensaje; IdTCPClient1.IOHandler.Write(Datos); finally IdTCPClient1.Disconnect; end; end; Esto, produce que el contador de mensajes en el servidor se dispare a 16. Ya con el código de ejemplo, puedes jugar y enviar, por ejemplo, paquetes de 8Kb, esperar unos cuantos segundos y enviar otro paquete, y verás cómo el servidor los sigue leyendo en fragmentos de 64Kb.
{ "pile_set_name": "StackExchange" }
Q: Set timeout to a PHP function I have this script <?php function get_reverse_dns($Ip) { $result = exec("nslookup -n ".escapeshellarg($Ip)." | grep 'name = '"); if(strpos($result,"name =") === false) { return "NO REVERSE"; } else { $result = trim($result); $ExplodedResult = explode("name =",$result); $ExplodedResult[1] = trim($ExplodedResult[1]); $ReverseDns = trim($ExplodedResult[1],"."); return $ReverseDns; } } ?> that gives me the reverse dns, now the problem is that sometimes, an IP can have a really long delay, and i want that this script to check it the IP can be "looked up", and if 5 seconds passed and this is not happening, then return false How can i make that? I have tried in linux nslookup --timeout 5 1.1.1.1 | grep 'name = ' timeout 5 nslookup 1.1.1.1 | grep 'name = ' Thanks. A: I would use dig: dig -x ${ip} +time=5 +tries=1 +retry=0 +short This command will only return the IP address so it will simplify your parsing bit.
{ "pile_set_name": "StackExchange" }
Q: How to place a text as a overlay on a image vertically aligned to top left in a div With the below code, why does the COMING SOON text going further to right and not getting aligned to left. The text has to be placed as an overlay vertically at the top left corner of the image HTML: <div class="grid"> <div class="block"> <div class="badge">NEW</div> </div> <div class="block"> <div class="badge">SALE</div> </div> <div class="block"> <div class="badge">COMING SOON</div> </div> </div> CSS: .grid{display:block;width:100%;} .block{width:255px;height:255px;border:1px solid #333;margin:12px;float:left;position:relative;} .badge{position:absolute;transform:rotate(90deg);top:12px;left:0;} A: Use transform-origin. It says to the browser around which point should transform: rotate happen. Find code at: http://jsfiddle.net/yv0Lugp8/1/ More info on transform-origin can be found HERE EDIT: Changed url after updating code.
{ "pile_set_name": "StackExchange" }
Q: Data attribute search with lower case and upper case I created searchbar with looking for names of agents that comes from laravel backend. Right now it is working that when user type first upper case letter and then lower case it search for agents. I want it to look for agents when user type first upper case and then lower case, all lower cases and all upper cases. Do you have any tip for my problem? HTML/BLADE.PHP <div class="container"> <div class="row"> <div class="show-hide-section"> <button class="btn btn-success show-hide-search-bar">Pokaż wyszukiwarkę</button> </div> <div class="col-xs-12 col-md-12"> <div class="searcher-section" style="display: none"> <div class="show-hide-searcher"> <div class="input-section"> <div class="label-input-searcher"> <label for="" class="searcher-label">Imię, Nazwisko, Adres email</label> <input type="text" placeholder="Podaj Imię, Nazwisko lub Adres email" class="searcher-input form-control"/> <div class="null-data" style="display: none;">Wprowadź poprawne dane</div> </div> </div> <div class="container"> <div class="row"> <h3 class="title" id="agents">Doradcy</h3> {{----}} <div class="cards"> @foreach($company_agents as $agent) <div class="col-xs-12 col-sm-5 col-md-4"> <div class="card" data-agent="{{$agent->firstname}} {{$agent->lastname}} {{$agent->email}}"> <figure> <div class="img-ref"> <a href="{{URL::action("", array('pageId' => $page->id, 'objectId' => $object->id, 'companyId' => $company->id, 'agentId' => $agent->id))}}" class=""> @if(isset($agent->has_avatar) && $agent->has_avatar !== 0) <div style="background: url('{{$staticUrl . 'images/users/' . $agent->company_id . '/' . $agent->id . '_max.jpg?' . rand(1,99999)}}'); background-size: cover;" class="photo"></div> @else <div style="background: url(''); background-size: cover;" class="photo"></div> @endif </a> </div> <ul> <li> <a href="{{URL::action("", array('pageId' => $page->id, 'objectId' => $object->id, 'companyId' => $company->id, 'agentId' => $agent->id))}}" class="teamLink"> <h3 class="agent-name">{{$agent->firstname}} {{$agent->lastname}}</h3></a> </li> </ul> <div class="teams-summary"> {{$company->name}} </div> <div class="contact-position"> {{--telefon kontaktowy--}} <div class="mobile-info card-contact-info"> {{$agent->phone}} </div> {{--adres mailowy--}} <div class="email-info card-contact-info"> {{$agent->email}} </div> </div> </figure> </div> </div> @endforeach </div> {{----}} </div> </div> JS $(document).ready(function () { var lowerAgentName = $(".card").text().toLowerCase(); var upperAgentName = $(".card").text().toUpperCase(); console.log(lowerAgentName); console.log(upperAgentName); // var lowerAgentName = $('h3.agent-name').text().toLowerCase(); // var lowerAgentName = $(".card").text().toLowerCase(); // var upperAgentName = $('h3.agent-name').text().toUpperCase(); $('.show-hide-search-bar').on('click', function () { if ($('.searcher-section').is(":visible")) { $('.searcher-section').hide("slide"); $('.show-hide-search-bar').text('Pokaż Wyszukiwarkę'); } else { $('.searcher-section').show("slide"); $('.show-hide-search-bar').text('Ukryj Wyszukiwarkę'); } }); $('.searcher-input').keyup(function (event) { $('.null-data').hide(); if ($(this).val()) { var input = $(this).val(); var trimmedInput = input.trim(); var terms = input.split(/\W+/g); $(".card").hide(); $(".clearfix.alt").hide(); $(".card[data-agent*='" + trimmedInput + "']").show(); $(".clearfix[data-name*='" + trimmedInput + "']").show(); $(".col-xs-12").css("min-height", "0"); $(".col-md-4").css("min-height", "0"); $(".col-sm-5").css("min-height", "0"); if (!$('.card:visible').get(0)) { $('.null-data').show(); } if (!$('.clearfix:visible').get(0)) { $('.null-data').show(); } } else { $(".clearfix.alt").show(); $(".card").show(); $('.null-data').show(); } }); }); CSS a { text-decoration: none; } .card { margin: 10px auto; background-color: white; -webkit-box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); box-shadow: 0 0 15px rgba(0, 0, 0, 0.2); padding: 10px; height: 300px; } .cardHover { -webkit-box-shadow: 0 0 10px rgba(207, 168, 168, 1); -moz-box-shadow: 0 0 10px rgba(207, 168, 168, 1); box-shadow: 0 0 15px rgba(207, 168, 168, 1); } .photo { border-radius: 50%; height: 150px; width: 150px; background-color: white; margin: 0 auto; background-position: 50% 50%; -webkit-box-shadow: inset 0px 0px 5px 1px rgba(0, 0, 0, 0.3); -moz-box-shadow: inset 0px 0px 5px 1px rgba(0, 0, 0, 0.3); box-shadow: inset 0px 0px 5px 1px rgba(0, 0, 0, 0.3); } .card ul { list-style: none; text-align: center; padding-left: 0; } .img-ref { display: block; margin-right: auto; margin-left: auto; width: 160px; height: 160px; } .agent-name { height: 25px; text-overflow: ellipsis; overflow: hidden; font-size: 16px; text-align: center; } .card-contact-info.mobile-info { overflow: hidden; text-overflow: ellipsis; width: 100px; position: absolute; left: 0; } .card-contact-info.email-info { overflow: hidden; flex: 1; text-overflow: ellipsis; position: absolute; right: 0; } .contact-position { position: relative; font-size: 11px; display: flex; bottom: 5px; } .searcher-section { display: block; } .searcher-label { } .searcher-button { padding: 10px 40px; margin-top: 10px; } .select-section { float: right; } .searcher-input { height: 40px; } .input-section { width: 70%; float: left; } .label-input-searcher { margin: 10px 0; } .show-hide-section { margin: 15px; } .show-hide-search-bar { display: table-cell; vertical-align: bottom; } A: Use i as case insensitive selector in attribute name search $(".card[data-agent*='" + trimmedInput + "' i]").show(); $(".clearfix[data-name*='" + trimmedInput + "' i]").show(); $('.searcher-input').keyup(function (event) { var input = $(this).val(); var trimmedInput = input.trim(); var terms = input.split(/\W+/g); $(".card").hide(); $(".card[data-agent*='" + trimmedInput + "' i]").show(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <div class="card" data-agent="TEST1">TEST1</div> <div class="card" data-agent="test2">test2</div> <div class="card" data-agent="teSt3">teSt3</div> <input class="searcher-input" />
{ "pile_set_name": "StackExchange" }
Q: Setting locale on a per-user basis when using devise and rails 3 I have just been through one of my apps converting the authentication from authlogic to devise. By and large this has been amazingly straight-forward to do but there is one issue I can't find an easy fix for. In the app, the user has the option of choosing their locale. Then whenever they login, they view the app in the language they choose. Previously, I did this by simply setting the locale in the create method of my UserSessions controller. With Devise, all the controllers are automatically setup, which is great. I know that I could create a custom Controller that extends the DeviseController and do it like this but, from what I understand, that means that I will also need to create all the views to go with it which seems a bit over the top when I just need to run one extra line of code. Is there an easier way of specifying some code to be run on a successful devise authentication? A: I found the solution I was looking for here As I just wanted to set the locale for the user when they logged in, all I needed was to add the following method to my ApplicationController def after_sign_in_path_for(resource_or_scope) if resource_or_scope.is_a?(User) && resource_or_scope.locale != I18n.locale I18n.locale = resource_or_scope.locale end super end
{ "pile_set_name": "StackExchange" }
Q: How to increase font size of TabControl item? In my winform project I need to increase the font size of the TabControl items, but if I increase the size, also the content of the TabControlchanges the own size... any ideas? I also want to change the background of the TabControl palette (not the entire tabControl). A: If you want to change the font and back color of tab pages without changing the font and back color of child controls, you should know: The Font and BackColor properties are ambient properties. An ambient property is a control property that, if not set, is retrieved from the parent control. For example, a Button will have the same BackColor as its parent Form by default. For more information about ambient properties, see the AmbientProperties class or the Control class overview. You can set the Font and BackColor for each tab page explicitly. This way, the child controls of tab pages, use Font and BackColor of TabPage. You can explicitly set control's ambient properties to prevent them from using parent's property value. (Thanks to TaW for better option rather than using panel as container of controls in the tab page.)
{ "pile_set_name": "StackExchange" }
Q: Delay Parsley.js form submission I need to be able to validate a form in Parsley on submit, but to delay the actual submission itself until some other (timed) action is completed. I tried this: $("#myform").on('submit', function(e){ e.preventDefault(); var form = $(this); form.parsley().validate(); if (form.parsley().isValid()){ // do something here... setTimeout(function() { form.submit(); }, 3000); } }); As you can probably guess, form.submit() just sends me into an infinite loop. I'm unable to determine how to trigger a submit after a delay without recalling the validation. To be clear, I need to: Check the form is valid Do something unrelated Wait X seconds Submit form Any ideas? Is there a Parsley specific method that will submit the form without revalidating? A: As per this question once an action is canceled (with preventDefault()), the only option is to triggered it again. You are already doing that. What you need to add to your logic is a condition to whether the event should be stopped or not. You could use something like this: $(document).ready(function() { $("form").parsley(); // By default, we won't submit the form. var submitForm = false; $("#myform").on('submit', function(e) { // If our variable is false, stop the default action. // The first time 'submit' is triggered, we should prevent the default action if (!submitForm) { e.preventDefault(); } var form = $(this); form.parsley().validate(); // If the form is valid if (form.parsley().isValid()) { // Set the variable to true, so that when the 'submit' is triggered again, it doesn't // prevent the default action submitForm = true; // do something here... setTimeout(function() { // Trigger form submit form.submit(); }, 3000); } else { // There could be times when the form is valid and then becames invalid. In these cases, // set the variable to false again. submitForm = false; } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.0.7/parsley.min.js"></script> <form id="myform"> <input type="text" name="field" required /> <input type="submit" /> </form>
{ "pile_set_name": "StackExchange" }
Q: Adding a code to be compiled in lex first I'm looking for a way to insert an #undef to the lex generated source code that will appear before the built in lines lex generates. When compiling a file.l with lex, I generate a lex.yy.c file. In my file.l I have written : #include "y.tab.h" #undef __STRICT_ANSI__ #include <string.h> The #undef helps me compile the code under the flag -std=c99 So it needs to be done before including string.h. But the generated file includes string.h before copying my undef. Without the #undef I am getting a lot of warnings due to the use of strdup. I have seen the normal fixes using flags, but like I said I can't access the makefile. Adding 'manually' the line #undef __STRICT_ANSI__ into lex.yy.c before fixes everything. But i prefer not to touch any of the generated code and have it done by lex. I have read this, strdup(): Confused about warnings ('implicit declaration', 'makes pointer...without a cast', memory leak) And like i said it does solve it. But only if I can somehow force the generated file to run the undef first. A: To start with, #undef __STRICT_ASCII__ is not the correct way to enable the declaration of Posix functions like strdup. Posix extensions which are declared in standard C library header files are made conditional on "feature test macros". You can read a summary in man feature_test_macros but in any case, the documentation for any function which requires a feature test macro includes a description of which macros are required. In the case of strdup, we can read in man strdup: Feature Test Macro Requirements for glibc (see feature_test_macros(7)): strdup(): _XOPEN_SOURCE >= 500 (Followed by more possibilities.) Personally, I always use #define _XOPEN_SOURCE 700 which requests declarations for all functions in the latest version of Posix. One way to insert the feature test macro before any include of a standard library function is to do so on the compile command line: -D_XOPEN_SOURCE=700 I like doing it this way, because I can add it to my Makefile and then it applies to every compilation (which is basically what I want). Usually, makefiles include a feature which allows you to add this option to your compiler flags without modifying the file. For example, the following will often work: make file CPPFLAGS="-D_XOPEN_SOURCE=700" (CPPFLAGS is a common makefile variable used to set preprocessor flags.) But if you want to put it into your flex file, you can use a %top block: %top { #define _XOPEN_SOURCE 700 } %top is like %{ but it puts the inserted code right at the beginning of the generated code. If nothing else works, you can always just insert the declaration for strdup, (also taken from man strdup) into your flex prologue. %{ char *strdup(const char *s); #include "y.tab.h" %} Both the C standard and the Posix standard allow explicit declaration of library functions (but not macros) as an alternative to including relevant headers.
{ "pile_set_name": "StackExchange" }
Q: Issue publishing report to Power BI Workspace I created a report using Power BI desktop APP. Publishing the report from Desktop application doesn't publish report to PowerBI workspace in azure. Here is report that I uploaded using Desktop app I used this article to get my uploaded report [https://azure.microsoft.com/en-us/documentation/articles/power-bi-embedded-get-started-sample/] from my Power BI embedded but the code doesn't return any report A: You can not publish a report into power bi embedded with the desktop application. The power bi desktop will publish reports into the "power bi service" not power bi embedded. You need to use the "Provision Sample" from the application on GitHub here. When you run the provision sample choose option 6 to "import" your pbix file into the workspace you have created in power bi embedded. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: How to convert json-string into CLOS object using cl-json library? If there is a class and a json: (defclass foo () ((bar :initarg :bar))) (defvar *input* "\{ \"bar\" : 3 }") How to convert *input* into an instance of foo using cl-json library? I guess it should be something like: (with-decoder-simple-clos-semantics (let ((*prototype-name* 'foo)) (decode-json-from-string *input*))) But it produces: Invalid SB-MOP:SLOT-DEFINITION initialization: the initialization argument :NAME was constant: :BAR. [Condition of type SB-PCL::SLOTD-INITIALIZATION-ERROR] What am I doing wrong? A: The cause of the error is that cl-json:*json-symbols-package* is bound to the KEYWORD package: when JSON keys are turned into symbols, they become keywords which apparently are not valid as slot names. Fluid objects The following works: (let ((json:*json-symbols-package* (find-package :cl-user))) (json:with-decoder-simple-clos-semantics (json:decode-json-from-string "{ \"bar\" : 3 }"))) (note: you only need backslashes before double-quote characters) You obtain a FLUID-OBJECT. Prototype key in JSON data Now, you can also define your own class: (in-package :cl-user) (defclass foo () ((bar :initarg :bar))) And then, the JSON needs to have a "prototype" key: (let ((json:*json-symbols-package* (find-package :cl-user))) (json:with-decoder-simple-clos-semantics (json:decode-json-from-string "{ \"bar\" : 3 , \"prototype\" : { \"lispClass\" : \"foo\", \"lispPackage\" : \"cl-user\" }}"))) The above returns an instance of FOO. You can use a different key than "prototype" by rebinding *prototype-name*. Force a default prototype (hack) Without changing the existing library code, you can hack around it to change the behavior of the decoding step. The code is organized around special variables that are used as callbacks at various point of the parsing, so it is a matter of wrapping the expected function with your own: (defun wrap-for-class (class &optional (fn json::*end-of-object-handler*)) (let ((prototype (make-instance 'json::prototype :lisp-class class))) (lambda () ;; dynamically rebind *prototype* right around calling fn (let ((json::*prototype* prototype)) (funcall fn))))) The above creates a prototype object for the given class (symbol), capture the current binding of *end-of-object-handler*, and returns a closure that, when called, bind *prototype* to the closed-over prototype instance. Then, you call it as follows: (let ((json:*json-symbols-package* *package*)) (json:with-decoder-simple-clos-semantics (let ((json::*end-of-object-handler* (wrap-for-class 'foo))) (json:decode-json-from-string "{ \"bar\" : 3 }")))) And you have an instance of FOO. Recursion Note that if you define foo as follows: (defclass foo () ((bar :initarg :bar :accessor bar) (foo :initarg :foo :accessor foo))) Then the hack also reads nested JSON objects as FOO: (let ((json:*json-symbols-package* *package*)) (json:with-decoder-simple-clos-semantics (let ((json::*end-of-object-handler* (wrap-for-class 'foo))) (json:decode-json-from-string "{ \"bar\" : 3, \"foo\" : { \"bar\" : 10} }")))) => #<FOO {1007A70E23}> > (describe *) #<FOO {1007A70E23}> [standard-object] Slots with :INSTANCE allocation: BAR = 3 FOO = #<FOO {1007A70D53}> > (describe (foo **)) #<FOO {1007A70D53}> [standard-object] Slots with :INSTANCE allocation: BAR = 10 FOO = #<unbound slot>
{ "pile_set_name": "StackExchange" }
Q: Create a background-image over a background-color with different opacities for each element Here the demo The code below creates a background-image over a background-color with different opacities for each element. Is there a cleaner way of achieving this? .component{ min-height: 100vh; min-width:100vw; font-size:5em; display:flex; justify-content: center; align-items: center; color:black; } .component::before{ content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; min-height: 100vh; min-width:100vw; opacity:1; z-index:-1; background: url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat; } .component_background_color::after{ content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; min-height: 100vh; min-width:100vw; opacity:0.3; z-index:-2; background:green; } <div class="component"> <div class="component_background_color"> Awesome WebPage </div> </div> A: You can shorten that code a bit, and then, by using rgba(), you can have both transparent background and image in one pseudo, and using attr() together with the second pseudo, display the text. The 4th argument in rgba() is the opacity level. Stack snippet .component { min-height: 100vh; min-width:100vw; font-size:5em; display:flex; justify-content: center; align-items: center; color:black; } .component::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity:1; background: rgba(0,255,0,0.3) url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat; } .component::after { content: attr(data-text); position: relative; } <div class="component" data-text="Awesome WebPage"> </div> If you intend to use something else inside the component, and to avoid using negative z-index on the pseudo (which can cause other issue when it comes to the stacking context), use e.g. a div and give it position: relative and it will float on top of the pseudo. Stack snippet .component { min-height: 100vh; min-width:100vw; font-size:5em; display:flex; justify-content: center; align-items: center; color:black; } .component::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity:1; background: rgba(0,255,0,0.3) url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat; } .component div { position: relative; } <div class="component"> <div> Awesome WebPage </div> </div> If you want to alter the opacity on the background color and the image individually, you will need both pseudo, and here's how-to. As the div will become before the ::after pseudo, markup wise, we need to give it z-index: 1 to "float" on top. Note, this is not as bad as using a negative z-index on the pseudo. Stack snippet .component { min-height: 100vh; min-width:100vw; font-size:5em; display:flex; justify-content: center; align-items: center; color:black; } .component::before, .component::after { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity:.3; background: green; } .component::after { opacity:.7; background: url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat; } .component div { position: relative; z-index: 1; } <div class="component"> <div> Awesome WebPage </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Binding Image in ASP.NET MVC4 from a byte array I am binding an image from a byte array in MVC4 view , The byte array is returned from a WEB API which I need to bind it to a view . Below is the code string str="JVBERi0xLjUNJeLjz9MNCjQgMCBvYmoNPDwvRSA0NDc1L0ggWyA3NjMgMTI1IF0vTCA1MTczL0xpbmVhcml6ZWQgMS9OIDEvTyA2L1QgNDcwMj4+DWVuZG9iag0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIA0xNCAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbNCAxMV0vSW5mbyAzIDAgUi9MZW5ndGggNTQvUHJldiA0NzAzL1Jvb3QgNSAwIFIvU2l6ZSAxNS9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiZBBgYGJg2gAkGHeAiLlAgiEHSPAUMTAxfhADcRkYmf4zffrPxCCQAuS+C2cAALmiCM4KZW5kc3RyZWFtDWVuZG9iag1zdGFydHhyZWYNIDANJSVFT0YNDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ01IDAgb2JqDTw8L1BhZ2VzIDIgMCBSL1R5cGUgL0NhdGFsb2cvVmVyc2lvbiAvMS40Pj4NZW5kb2JqDTEyIDAgb2JqDTw8L0ZpbHRlciAvRmxhdGVEZWNvZGUvTGVuZ3RoIDUxL1MgNDE+Pg1zdHJlYW0KeJxjYGBgYWBg+s0ABHzMDKiAGQhZGDgSfBrAXEaoMAsUMzDkMPAwCzAcSJBhAAB7SQQhCmVuZHN0cmVhbQ1lbmRvYmoNNiAwIG9iag08PC9Db250ZW50cyA3IDAgUi9NZWRpYUJveCBbMCAwIDYxMiAxMzNdL1BhcmVudCAyIDAgUi9SZXNvdXJjZXMgPDwvUHJvY1NldCBbL1BERiAvVGV4dCAvSW1hZ2VCIC9JbWFnZUMgL0ltYWdlSV0vWE9iamVjdCAxMCAwIFI+Pi9UeXBlIC9QYWdlPj4NZW5kb2JqDTcgMCBvYmoNPDwvRmlsdGVyIC9GbGF0ZURlY29kZS9MZW5ndGggNDA+Pg1zdHJlYW0KeJxTKOQt5DUzNFIwAEJDY2MwnZzLq++Za6Dgks8byKsQqAAAjOIHjgplbmRzdHJlYW0NZW5kb2JqDTggMCBvYmoNPDwvQml0c1BlckNvbXBvbmVudCA4L0NvbG9yU3BhY2UgMTEgMCBSL0ZpbHRlciAvRENURGVjb2RlL0hSZXMgOTYvSGVpZ2h0IDE3L0xlbmd0aCAzMDE3L1N1YnR5cGUgL0ltYWdlL1R5cGUgL1hPYmplY3QvVlJlcyA5Ni9XaWR0aCA3OD4+DXN0cmVhbQr/2P/gABBKRklGAAEAAAABAAEAAP/+AEFKUEVHIEVuY29kZXIgQ29weXJpZ2h0IDE5OTgsIEphbWVzIFIuIFdlZWtzIGFuZCBCaW9FbGVjdHJvTWVjaC7/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIABEATgMBEQACEQEDEQH/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+gEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoLEQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/AP7Ofil8YP2jvgn4713X9X+Av/C9/wBmW6/sy+tvFH7Pd3dX/wC0d8HbWPR9PHiyTx5+zx4lmj/4Xv8AD/w5/YPi/wAbt4z/AGcfHevftHeIrrxj4E+B3w1/YW+JWteHNZ+LniwA9f8Agp8fvg1+0X4V1Dxj8FfiF4f8e6RoXiC68GeMbTTZp7PxV8NviFpenaVqniH4V/FrwLrEGneNvhD8YPB1trmlRePPhD8TvD3hP4meANRvI9H8aeFNC1dZbFADyD9pX4peO7Hx38Ef2a/htrv/AAqnxb+0t/wsmC2/aG1rTNH1HR/h1o/wu0fQfEPizwj8KtM8S6frHhLx3+1/478JaxrniT4AfDrxtpOo+BNK8CfC79oL9pHxz4d+K3hL9mnWf2fPjQAeP/Db4k/tcfDr9rjwT+yd498bfB/9qnwTrXwf8c/FrxV8XNL8Da38CPjL+zx8PfBGt6H4D+EUnx503wrrnxd+FPxz+MH7WfinXde/4RTUvC/gr9gn4Zzwfs3/ALU3jL4ZeA/ENt4WHwl8CAH6P0AFAHyB+wH+2L4E/wCCgH7G37Pf7Yfw6s/7I8P/ABx+H9n4i1Dw19o1i/8A+EH8d6RfX/hP4pfDr+2dd8MeDL3xL/wrf4m+H/F3gT/hLoPDGkaP4w/4R3/hKPDsEnh/V9MuZgD6/oAKAP5of+DmP41+FfFX/BIz/gqJ8B00/wAQaJ8RPg54f/YS8c6tY6za6c2neJ/hn8Z/2vPhhafD/wCJPhPVNF1XWbZ/D+reNvhX8Zvhtc6H4nPhj4haX4q+EfiXVtR8E23w78S/Czx18Q/8/wD9qR/ygl45/wDeMv8A18Xh8f5//tSP+UEvHP8A7xl/6+Lw+P6Xq/0AP9AD5g+Nf7G37PHx+8Vaf8Q/HXg7xBoXxW03w/a+DLf42/BT4p/Fr9mv4+yfD2z1HVdch+FeofHv9nTx18K/jHq3wffxJrN34tuvhDqnji8+Gd940h0rxnfeFLjxToWh6vpwB8f/ABr/AOCVWnfFbwrp/hfTf20P239C0j4aeILX4k/s0+HPEHx78VeKIPgT8ZbPTtV0S88bN8f9Eu/An/BRD4oeH/H3hDxj8XPhV8TvA3jz9u+8guvg18cviP4K+EuufBnV9C+Bni/4LAB8FPFs/wDwT88K6h8Mvi5+xj4g8I+G9X8QXXiXVP2lP2F/hZ8Zf2tvCv7RfxMv9O0rw/ffE/49fDfwL4a+Jn7eHh39p/4u2HgvUvHvxR8WfFrwv+078PdI0628I6D48/4KJ/Gn4x+JLTTr8A9g/wCHj/wX1H/iX+D/AIK/t/8AjHxbf/6H4W8I/wDDtL9vr4a/8JV4juv3GieHP+Fi/HT9nX4UfBLwD/bmpva6Z/wmvxi+KXw1+FnhX7V/bvxB8f8Ag7wlYav4i04AP7C/ax/ax/cfEPT/AIgfsE/AUfvJ/A3g34pfDbXf2yfjDa3X/Ej8ReCPix42+HWmfEz4Zfsq/D97KDxNNpusfsl/H74k/tHeMbHxX8NPiF4O/aQ/Y38dfDbxd8NvHYAf8O+/Anwu/wCJz+xX8QfiB+xZ4g0z954d+H/w01vWPFH7Gy2sX/E1n8Eal+wp4u1u5/Zy8E/D/wAbeM7bTvFnxY1j9lzw1+zF+0d4vvpfGVz4Z/aQ+H/iD4n/ABF8SeJAA/4WN/wVN/6M3/YA/wDFln7RX/0p2gA/s/8A4Ka/Fb/iVeItT/ZA/Yv8Pp/xL9d1n4T678T/ANuj4p+KdH1z/RtT1P4aeJfil8Lf2MPhl+z98QPAtlbz3Xg3XfiL8FP20fAninxHr+m6h4u+Ftp4f8A6h4T+KwB+UH/BxH8FPCvwN/4N/v29dC0LUPEHirxJ4q8Qfs4eOfin8U/HN1p2qfEz4zfEzVP2sv2aNJ1r4k/EnWtJ0rQtIvPEF5pGhaB4a0PQ/DWgeGPh78NPh74Y8E/CD4QeCfh58HPh58P/AIf+F/8AP/8Aakf8oJeOf/eMv/XxeHx/n/8AtSP+UEvHP/vGX/r4vD4/zZP+HsX/AAVN/wCkln7f/wD4mR+0V/8APGr/AJf/APibL6U//SS/0gP/ABcviL/9EZ/y/wD/ABNl9Kf/AKSX+kB/4uXxF/8AojD/AIexf8FTf+kln7f/AP4mR+0V/wDPGo/4my+lP/0kv9ID/wAXL4i//RGH/E2X0p/+kl/pAf8Ai5fEX/6Iw/4exf8ABU3/AKSWft//APiZH7RX/wA8aj/ibL6U/wD0kv8ASA/8XL4i/wD0Rh/xNl9Kf/pJf6QH/i5fEX/6Iw/4exf8FTf+kln7f/8A4mR+0V/88aj/AImy+lP/ANJL/SA/8XL4i/8A0Rh/xNl9Kf8A6SX+kB/4uXxF/wDojD/h7F/wVN/6SWft/wD/AImR+0V/88aj/ibL6U//AEkv9ID/AMXL4i//AERh/wATZfSn/wCkl/pAf+Ll8Rf/AKIw/wCHsX/BU3/pJZ+3/wD+JkftFf8AzxqP+JsvpT/9JL/SA/8AFy+Iv/0Rh/xNl9Kf/pJf6QH/AIuXxF/+iMP+HsX/AAVN/wCkln7f/wD4mR+0V/8APGo/4my+lP8A9JL/AEgP/Fy+Iv8A9EYf8TZfSn/6SX+kB/4uXxF/+iMP+HsX/BU3/pJZ+3//AOJkftFf/PGo/wCJsvpT/wDSS/0gP/Fy+Iv/ANEYf8TZfSn/AOkl/pAf+Ll8Rf8A6Iw/4exf8FTf+kln7f8A/wCJkftFf/PGo/4my+lP/wBJL/SA/wDFy+Iv/wBEYf8AE2X0p/8ApJf6QH/i5fEX/wCiM8/+KX/BQn9vr44+BNd+Fvxr/bh/a/8AjB8MvFH9mf8ACS/Dr4pftLfGj4geBPEX9iaxp/iLRv7d8I+LPGur+H9X/sjxBpGla7pn9oafcfYNY0zT9TtfKvbK2nj+f4p+kL4+8c5DjuFuNvHHxg4w4YzT6r/afDnFPiXxpxBkOY/UsZh8xwX17KM2zrF5fi/qmYYTCY7C/WMPU+r4zC4fFUuSvRpzj8/xT9IXx945yHHcLcbeOPjBxhwxmn1X+0+HOKfEvjTiDIcx+pYzD5jgvr2UZtnWLy/F/VMwwmEx2F+sYep9XxmFw+KpclejTnH/2QplbmRzdHJlYW0NZW5kb2JqDTkgMCBvYmoNPDwvRmlsdGVyIC9GbGF0ZURlY29kZS9GaXJzdCAxMS9MZW5ndGggNDIvTiAyL1R5cGUgL09ialN0bT4+DXN0cmVhbQp4nDM0UDBQMDRUMDRRsLHR98w1ULAACgTZ2em7pJZlJqcGuTsBAIFSCFYKZW5kc3RyZWFtDWVuZG9iag0xIDAgb2JqDTw8L0ZpbHRlciAvRmxhdGVEZWNvZGUvRmlyc3QgOS9MZW5ndGggMTM0L04gMi9UeXBlIC9PYmpTdG0+Pg1zdHJlYW0KeJwzUjBQMFYwNlewsdF3zi/NK1Ew1PfOTClWiDYDygTF6odUFqQq6AckpqcW29mBFBWlJpZk5ue5JJakKmi4WBkZGJoamBgaGxkYmRqYRhkYqAORpr5vfgoBFQFF+SmlyalFChoBLm4hRfl5CkDaL7VERyHMTM/YwMjEKCZP084OAIrZKrEKZW5kc3RyZWFtDWVuZG9iag0xMyAwIG9iag08PC9EZWNvZGVQYXJtcyA8PC9Db2x1bW5zIDQvUHJlZGljdG9yIDEyPj4vRmlsdGVyIC9GbGF0ZURlY29kZS9JRCBbKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KSAoblwzNjRcZlwyMzZcMzI1XDI2Mn1cMjY0XDI3MFwzNTAqXDE3N1wwMzdcMzY3XDAwN1wzMTYpXS9JbmRleCBbMCA0XS9JbmZvIDMgMCBSL0xlbmd0aCAyNC9Sb290IDUgMCBSL1NpemUgNC9UeXBlIC9YUmVmL1cgWzEgMiAxXT4+DXN0cmVhbQp4nGNiAAImRsFqIPG+jYEJyGMEABJTAg0KZW5kc3RyZWFtDWVuZG9iag10cmFpbGVyDTw8L1NpemUgNA0vSUQgWyhuXDM2NFxmXDIzNlwzMjVcMjYyfVwyNjRcMjcwXDM1MCpcMTc3XDAzN1wzNjdcMDA3XDMxNikgKG5cMzY0XGZcMjM2XDMyNVwyNjJ9XDI2NFwyNzBcMzUwKlwxNzdcMDM3XDM2N1wwMDdcMzE2KV0+Pg1zdGFydHhyZWYNMTgyDSUlRU9GDQ=="; Byte[] image = GetBytes(str); { Model.ImageData = image; } static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } in view Bind it as <img src="data:image;base64,@System.Convert.ToBase64String(Model.ImageData)" /> The image is not rendering , it is showing an image icon only in page . Where it is going wrong .Please suggest . A: Your str looks like it is already base64, so you don't need to dance to binary and back. You can just stick it in the view where it should be. Decoding that string from base64 revealed that it is not an image, it's a pdf file. So your api (3d party, I guess) serves you not an image. And lastly to successfully use an image like that you probably need to specify mime type like this <img src="data:image/png;base64,some text representation of binary data" /> http://en.wikipedia.org/wiki/Data_URI_scheme
{ "pile_set_name": "StackExchange" }
Q: Can we access one control Id registered in one aspx in to another ascx control,, Can we access one control Id registered in one aspx in to another ascx control,, A: If you are in an ascx and need to access a control in the parent aspx page, you could do this as follows: Control myControl = this.Page.FindControl("myControl"); However, it is worth investigating exactly why you need to do this - in general it is not a good practice for the child user control to perform actions inside the parent page. An alternative approach would be to have the ascx throw an event in a given scenario, which the parent Page would in turn subscribe to (and potentially perform an internal action based on the event). This would allow interoperability between the page and User Control while still encapsulating each one's functionality properly.
{ "pile_set_name": "StackExchange" }
Q: Best practice to load savegame of a management game? I'm creating a Football Manager style management game for android phone & tablet. So I have quite a deep object model (players, teams, races, ... with all their stats, history and so on). I want to know the best way to load a users savegame. (in my c# desktop variant for this app I load the whole object in a static class variable so I can access it from everywhere.) I don't know the best practice for an android app, I can't believe that loading the data from storage in the viewmodel of every individual Activity is the way to go. But I also don't know if it's a good idea to load the entire savegame in an application-object. A: You could make a GlobalDataAccess class which holds your data, like you do it with c#. The class could look like this and the mehtod is important to access youre objects in other classes: // your objects and other: private Player player; // etc. private static GlobalDataAccess globalInstance; public static GlobalDataAccess Global(){ if(globalInstance == null) { globalInstance = new GlobalDataAccess(); } return globalInstance; } And if you will get some data from another class you make simply: Player player = GlobalDataAccess.Global().player; The only problem is to store the data... One way is to store it about sharedpreferences, but this is little bad... Hope i could help you in any way!
{ "pile_set_name": "StackExchange" }
Q: Is there a portable way to query the type of void* pointer? Basic question: is there a portable (or at least, a library that is found in most compilers) way to query the type of a void* pointer at runtime? In particular, is it possible to determine if the pointer is of type struct x or of type struct y (as an example). Additional info: I know gcc offers the typeof operator, but I want a more portable, less compiler-dependent way of accomplishing the same thing. Requirements: Must not be completely compiler-dependent. This includes compiler-specific macros and other features not commonly implemented in most compilers. I would prefer a function that works on any compiler over any less portable implementation (though I will accept the answer that best suits my goals). It is okay to suggest using a function in a library that is not in the C11 function, but is commonly found in most compilers. Make sure you explain how it works and the arguments though. A: What you're asking for is impossible. A void * pointer is by definition a generic pointer. It can be cast to or from a pointer of any type; there is no way to determine what type of data (if any!) it points to.
{ "pile_set_name": "StackExchange" }
Q: Exchange label from the box ticked I have in my page a boolean that allows me to choose between two labels to display package.properties: viaje.tel=Numéro de téléphone viaje.tel2=N° de téléphone portable My Jsp: <%-- Numéro de téléphone --%> <div class="yui3-g-r margin-bottom-small"> <div class="yui3-u"> <c:choose> <c:when test="${viaje.blCcoEtablissementScolaire==true}"> <s:label for="viaje.tel2" required="true" value="%{getText('viaje.tel2')}" tooltip="%{getText('tooltip.telephone')}" tooltipConfig="#{'tooltipIcon':'%{icoTooltipUrl}', 'jsTooltipEnabled':'true'}" /> </c:when> <c:otherwise> <s:label for="viaje.tel" required="true" value="%{getText('viaje.tel')}" tooltip="%{getText('tooltip.telephone')}" tooltipConfig="#{'tooltipIcon':'%{icoTooltipUrl}', 'jsTooltipEnabled':'true'}" /> </c:otherwise> </c:choose> </div> <div class="yui3-u-1-2"> <s:textfield id="viaje.tel" name="viaje.tel" maxlength="20" size="20" /> </div> </div> Could my code be simplified? A: You can use ternary operator <s:set var='tel' value="%{viaje.blCcoEtablissementScolaire?'viaje.tel2':'viaje.tel'}"/> <s:label for="%{#tel}" required="true" value="%{getText(#tel)}" tooltip="%{getText('tooltip.telephone')}" tooltipConfig="#{'tooltipIcon':'%{icoTooltipUrl}', 'jsTooltipEnabled':'true'}" />
{ "pile_set_name": "StackExchange" }
Q: Struts 2 action class not working I am using struts2 for developing a web application. I have include the required jars for struts2 but when it is going to call the struts action class it is throwing 404 error. There is no error on console and browser does not showing .action extension whitch it shows when struts.xml call an action class. I am using jdk 1.6 and struts 2.0. Am I missing any jar who is responsible for all this. In jsp I am simply calling the function from <s:form action = "Mergexmlaction" method = "post"/> Here is my struts.xml and web.xml struts.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.multipart.maxSize" value="6000000000" /> <package name="default" namespace="/jsp" extends="struts-default"> <action name="Mergexmlaction" class="com.hm.merge.mergeaction.Mergexmlaction"> <result name="success" >/jsp/Result.jsp</result> <result name="error" >/jsp/Browse_multiplexmlfiles.jsp</result> <interceptor-ref name="fileUpload"> <param name="maximumSize">600000000</param> </interceptor-ref> </action> </package> </struts> web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app id="xml_file_merging" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>xml_file_merging</display-name> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>jsp/Browse_multiplexmlfiles.jsp</welcome-file> </welcome-file-list> </web-app> A: There are a few issues. <package name="default" namespace="/jsp" extends="struts-default"> 1) I'd recommend against having a namespace of "jsp", it doesn't make any sense. Namespaces should be something meaningful to the application and/or user. <action name="Mergexmlaction" class="com.hm.merge.mergeaction.Mergexmlaction"> 2) Don't name an action with "action", there will either be a .action extension, or no extension at all. Either way, there's no reason to duplicate "action" in the first case, and no reason to use "action" if there's no extension. Just "mergexml", "mergeXml", etc. <result name="success" >/jsp/Result.jsp</result> 3) I recommend putting your JSP pages under WEB-INF to avoid direct client access. <interceptor-ref name="fileUpload"> 4) Once you declare any interceptors, you must declare all interceptors. This action has only a single interceptor running. It's possible this is okay, but it's almost never the right thing to do. <welcome-file>jsp/Browse_multiplexmlfiles.jsp</welcome-file> 5) And this is the ultimate issue, depending on how you're accessing the application. You show the welcome file as being a JSP page, which is presumably using S2 tags. This won't work: the tags depend on their being a complete S2 request, a value stack, etc. All access to an S2 app should take place through an S2 action, not a JSP. If you look at the rendered HTML for the directly-accessed JSP you'll see neither namespace nor action extension rendered.
{ "pile_set_name": "StackExchange" }
Q: Como fazer uma matriz associativa em python 3? Possuo um código que pede uma matriz 8x8, mas preciso que no input ele peça os valores assim: matriz [A][1]: matriz [A][2]: Ou seja, que ele peça a linha em forma de letra e a coluna em forma de número. Até agora só consegui fazer ele aparecer a linha e coluna em forma de número, assim: matriz [1][1]: matriz [1][2]: A: O python possui a função chr, ela retorna um caracter a partir de um número inteiro. Para o alfabeto maiúsculo, esse número começa com 65 (A) e acaba em 90 (Z). >>> chr(65) 'A' >>> chr(90) 'Z' O contrário desta função é o ord. >>> ord('A') 65 >>> chr('Z') 90 Para printar matriz [A][1]: a partir de um i=0 e j=0, é só fazer: print('matriz [{}][{}]: '.format(chr(65+i),j+1))
{ "pile_set_name": "StackExchange" }
Q: Advice on moving a machine room to a new location? Our company is moving to new offices in a couple of months, and I am responsible for looking after the move of the development servers in the company. most of the dev equipment is in 5, 42U cabinets + rack for switching/routing equipment. How do most people do this sort of thing? Move the cabinent whole or extract the indvidual components and move the racks empty. any advise on prep and shutdown before the move would be welcome A: We have done a couple of moves with racks. Here's what I took away from the experience: Before: label everything. Both ends. And the rack slot it's plugged into too. diagram everything. if you have important data, schedule a full backup to finish 6-12 hours before the move. At a minimum, validate the last full backup you have. plan to take everything out of the rack during the move. At a minimum take out half the mass, from the top down -- this means leave the top empty Don't expect movers to move a top-heavy rack. In a rack with a UPS at the base that means you are taking out probably 2/3 of the servers. Anything which is left racked MUST have rails and be secure in the rails (less than 0.5mm movement, and tolerant of any orientation -- including upside down and face down -- was our margin). We've moved full racks, and half-full racks, and the racks always need to be tilted/rotated, and it is downright scary to watch your livelyhood being dangled over a concrete loading dock. in our experience, front and rear doors are more decorative than load-bearing and leaving them on can make moving the racks very awkward because all the good hand-holding points are unavailable. Plan to remove the doors during the actual move. This forces the movers to lift, pull, push, and tug the rack by its strongest parts. Usually side panels can stay on, but be prepared to remove them if the movers think having them gone would help. hire someone with an insured truck to to the transportation. DO NOT do it yourself. You might think you are insured, but your insurance company will probably think otherwise. The second last thing you want is to be involved in a three-way blamestorm between your employer's insurance company and your insurance company. hire someone insured to physically pick up, move, put down, and (during an accident) drop your gear for you. DO NOT do it yourself. The last thing you want to do is hurt yourself or be involved in a co-worker's injury. make sure your insured someones specialize in high-tech moves and can supply blankets, anti-static bubble-wrap, and if necessary crates. During the move: backups are good, right? do the wire disconnect yourself. Pull ALL wires that are disconnectable. Each wire should be labelled and go into a box that itself is well labelled. let the strong, well insured guys do the server extractions from the rack. Supervise the wrapping personally. stay out of the strong, well-insured guys' way when they do the loading and unloading. supervise the unwrapping and re-insertion into the racks. If there is ANY question about a server's condition, mention it, and note that it was mentioned. If the job is taking a while, have coffee and/or doughnuts available for the guys. If appropriate (and if they've done a good job), cold beer for after the job goes well too. Physical bring-up: double your time estimate for getting things back on track. have a build-up plan. A good build up plan includes a checklist of all services, servers, and a test plan. validate, validate, validate. check any servers which may have been damaged in transit as noted above. don't let management cheap out when it comes to food if you are working through meal times. Hungry techs make mistakes. If the bring-up is going to be long and complicated, schedule time to get out of the room for 90 minutes to go get a real meal. After: a cold beer for you may be appropriate, too. A: I'm with Kevin on unracking and disconnecting. Racks that I've worked with that are built to ship loaded typically have additional bracing and must be attached to a fixed base (like a pallet) during shipping. Usually the servers have some kind of locking mechanism, too. If you're not moving something that isn't built to be moved loaded don't. I would add this to Kevin's answer: Part of documenting is knowing why the various connections and cables are there. You can make all the notes, take all the pictures, etc, that you want to, but at the end of the day if you don't understand why something is there you're running a risk of not knowing what to test to establish, after the move, that you "got everything". This is a golden opportunity to, as you're documenting the "what's plugged into what" of the move, ask yourself "why is this plugged into this"? I've had too many cases of the "I'll just patch this here and temporarily change a VLAN assignment" that turns into a semi-permanent configuration that no one documented come back to bite me when moving equipment years later. Before any equiment goes into a personal vehicle, find out how the company's insurance is handling claims in the event of damage during transport. Back everything up before you begin moving. Assume that all the equipment will be destroyed during the move because (if you're driving on public roads, at least) it could be. It goes w/o saying that the backup media should not move with the infrastructure gear! A: Extract the individual components and move the racks empty. This also has the advantage of allowing you to reconnect things in an optimal configuration and get your wiring exactly the way you want it. Just be sure to document everything before, during and after. Take digital pictures to help.
{ "pile_set_name": "StackExchange" }
Q: Get special combinations of string Using some code in python that outputs special combinations of string in order: How to do that on c# def getOrderCombinations(me): l = len(me) looped = me+ me for start in range(0, l): for length in range(1, l): print(looped[start:start+length]) which gives: >>> getOrderCombinations("ABCD") A AB ABC B BC BCD C CD CDA D DA DAB I was trying public static string[] Combinations(string str) { if (str.Length == 1) return new string[] { str }; char c = str[str.Length - 1]; //here I was planning to make recursion string[] returnArray = Combinations(str.Substring(0, str.Length - 1)); // keep final string combinations List<string> finalArray = new List<string>(); //how to loop correctly and avoid getting all combinations foreach (string s in returnArray) finalArray.Add(s); finalArray.Add(c.ToString()); } for string 'ABCD', output should be 'A', 'B', 'C', 'D', 'AB', 'BC', 'CD', 'DA', 'ABC', 'BCD', 'CDA', DAB'. Thus, the amount of possible substrings of string length n will always be n*(n-1). How to do it on c#? A: What's wrong with the way it's implemented in python? A direct port should work pretty well, I'd think: public IEnumerable<string> GetOrderCombinations(string me) { int l = me.Length ; string looped = me + me ; for ( int start = 0 ; start < l ; ++start ) { for ( int length = 1 ; length < l ; ++length ) { yield return looped.Substring( start , length ) ; } } } You could even make it a Linq one-liner, pretty much a direct port of the Python implementation: public static IEnumerable<string> GetOrderCombinations( string me ) { string looped = me + me; return Enumerable .Range(0,me.Length) .SelectMany( x => Enumerable.Range(1,me.Length) , looped.Substring ) ; } A: EDIT: Consider the following Code... string str = "LEQN"; List<char> characters = str.ToCharArray().ToList(); List<string> combinations = new List<string>(); for (int i = 0; i < characters.Count; i++) { int combCount = 1; string comb = characters[i].ToString(); combinations.Add(comb); for (int j = 1; j < characters.Count - 1; j++) { int k = i + j; if (k >= characters.Count) { k = k - characters.Count; } comb += characters[k]; combinations.Add(comb); combCount++; } } Good Luck! Here is the output from the above code...
{ "pile_set_name": "StackExchange" }
Q: Maximal ideal space of $c_{\mathcal{U}}$ Let $\mathcal{U}$ be an filter over $\mathbb{N}$. Define $$c_{\mathcal{U}} = \{{(x_n)\in \ell_\infty\colon \lim_{\mathcal{U}, n}x_n =0\}},$$ which is a C*-algebra. Is there an accessible topological description of the maximal ideal space of $c_{\mathcal{U}}$? At least for ultrafilters? A: (I will use $\omega$ for the ultrafilter since using a lowercase letter will improve readability) The way I see it, your algebra $c_\omega$ is simply $$ c_\omega=\{f:\ f(\omega)=0\}\subset C(\beta \mathbb N). $$ So you can make the identification $c_\omega=C_0(\beta\mathbb N\setminus\{\omega\})$. Note that $c_\omega$ is an ideal in $C(\beta\mathbb N)$, so the ideals in $c_\omega$ are ideals in $C(\beta\mathbb N)$. This is important because, with $\beta\mathbb N$ being compact, the ideals of $C(\beta\mathbb N)$ are precisely the sets of functions that annihilate a fixed closed subset. Thus, the ideals of $c_\omega$ are the sets of the form $$ \{f\in C_0(\beta\mathbb N\setminus\{\omega\}):\ f=0\ \mbox{ on }\{\omega\}\cup K\} $$ for a fixed closed $K\subset\mathbb N\setminus\{\omega\}$. We conclude that maximal ideals of $c_\omega$ are of the form $$ \{f\in C_0(\beta\mathbb N\setminus\{\omega\}):\ f(\omega)=f(\eta)=0\} $$ for some $\eta\in\beta\mathbb N\setminus\{\omega\}$.
{ "pile_set_name": "StackExchange" }
Q: Cannot click on List item I Am Extremely new to Adroid! I have a login page, when i click login it gives the users a listview After which when I click on the row should make a request to the server and login according to those credentials. I have made my list view using a custom adapter but i cannot click on the items. Just need some help with how to make it clickable. Before when I was using a simple adapter, the list was clickable and my object was returned. When I de-bug, I Can see that it hits the "AgencyListview.setOnItemClickListener(new OnItemClickListener()" line but does not make the items clickable. My listview xml is set to clickable. P.S I am not extending ListActivity as I Am doing all this in one activity. private void showList(final String deviceId, final String TokenId) { findViewById(R.id.emailText).setVisibility(View.INVISIBLE); findViewById(R.id.passwordText).setVisibility(View.INVISIBLE); findViewById(R.id.loginButton).setVisibility(View.INVISIBLE); findViewById(R.id.listview).setVisibility(View.VISIBLE); final ListView AgencyListview = (ListView) findViewById(R.id.listview); //ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, agencyList); // ListAdapter adapter = new SimpleAdapter (this,agencyList, android.R.layout.item_row, // new String[] { "Eid", "Ename", "Eaddress" }, // new int[] { R.id.TextView1,R.id.TextView2,R.id.TextView3 }); // setListAdapter(adapter); // AgencyListview.setAdapter(arrayAdapter); AgencyAdapter aa = new AgencyAdapter(this, R.id.listview, list) { public boolean isEnabled(int position){ return false; } }; AgencyListview.setAdapter(aa); AgencyListview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Log.i("HelloListView", "You clicked Item: " + " at position:" + position); Object o = AgencyListview.getItemAtPosition(position); o.toString(); url= "http://10.0.1.41/api/Account/select?deviceid="+deviceId+"&TokenId="+TokenId+"&userid=a29a5dba-d8f9-474b-92ca-b5dcadcc6390&agencyid=62b904fa-b38f-4686-b2e4-d748fa129c50"; new ServiceTask(){ protected void onPostExecute(String result){ System.out.println( "NEW MULTI***" + result); try { userObject = new JSONObject(result); HasMultiple = "false"; convertJson(result); saveSession( AgencyName); startMain(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.execute(url); } }); } This is my Custom Adapter : class AgencyAdapter extends ArrayAdapter<AgencyItems> { private Context context; private List<AgencyItems> items; public AgencyAdapter(Context context, int textViewResourceId, List<AgencyItems> items){ super(context, textViewResourceId, items); this.context = context; this.items = items; } @Override public View getView(int position, View convertView, ViewGroup parent){ View v = convertView; if(v==null) { LayoutInflater layoutInflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = layoutInflator.inflate(R.layout.agency_row, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.textViewItemName = (TextView)v.findViewById(R.id.agency_label_text); viewHolder.textViewItemValue = (TextView)v.findViewById(R.id.agency_value_text); v.setTag(viewHolder); } ViewHolder holder = (ViewHolder) v.getTag(); final int currentPosition = position; holder.textViewItemName.setText(items.get(currentPosition).getName()); holder.textViewItemValue.setText(items.get(currentPosition).getValue()); return v; } public void OnClick(View v) { } public class ViewHolder { public TextView textViewItemName; public TextView textViewItemValue; } } This is my agency_row <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="0dp" android:layout_height="wrap_content" android:paddingTop="@dimen/list_padding" android:paddingBottom="@dimen/list_padding" android:orientation="horizontal" > <TextView android:id="@+id/agency_label_text" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:text="Default" android:layout_weight="0.3" android:textColor="@android:color/darker_gray" /> <TextView android:id="@+id/agency_value_text" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Default value" android:layout_weight="0.7" android:clickable="true" /> </LinearLayout> enter code here A: I assume you mean you want to react to an item tap in the list, not react to the list itself being tapped. For this, you need to put a listener in the getView method of the adapter, not the the list itself as you have depicted here: AgencyListview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Log.i("HelloListView", "You clicked Item: " + " at position:" + position); Object o = AgencyListview.getItemAtPosition(position); o.toString(); url= "http://10.0.1.41/api/Account/select?deviceid="+deviceId+"&TokenId="+TokenId+"&userid=a29a5dba-d8f9-474b-92ca-b5dcadcc6390&agencyid=62b904fa-b38f-4686-b2e4-d748fa129c50"; new ServiceTask(){ protected void onPostExecute(String result){ System.out.println( "NEW MULTI***" + result); try { userObject = new JSONObject(result); HasMultiple = "false"; convertJson(result); saveSession( AgencyName); startMain(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.execute(url); } }); } Should be: @Override public View getView(int position, View convertView, ViewGroup parent){ View v = convertView; if(v==null) { LayoutInflater layoutInflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = layoutInflator.inflate(R.layout.agency_row, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.textViewItemName = (TextView)v.findViewById(R.id.agency_label_text); viewHolder.textViewItemValue = (TextView)v.findViewById(R.id.agency_value_text); v.setTag(viewHolder); } ViewHolder holder = (ViewHolder) v.getTag(); final int currentPosition = position; holder.textViewItemName.setText(items.get(currentPosition).getName()); holder.textViewItemValue.setText(items.get(currentPosition).getValue()); // put your click listener here v.OnClickListener{ @Override public void onClick( // example activity.methodToExecute(); } } return v; }
{ "pile_set_name": "StackExchange" }
Q: How to capture PyQt5 QMainWindow losing focus What I want to achieve: if a user clicks outside of the QMainWindow the window should hide. How I tried to to tackle this problem: find a way to determine if the QMainWindow lost focus, and if so, hide the window using a followup function. Unfortunately I can not totally grasp how to achieve this. It can be done using the flag Qt::Popup but than I am not able to give any keyboard input to the widget my QMainWindow contains. A: void QApplication::focusChanged(QWidget *old, QWidget *now) This signal is emitted when the widget that has keyboard focus changed from old to now, i.e., because the user pressed the tab-key, clicked into a widget or changed the active window. Both old and now can be the null-pointer. import sys from PyQt5 import QtCore, QtGui, QtWidgets class MyWin(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setFocus() QtWidgets.qApp.focusChanged.connect(self.on_focusChanged) @QtCore.pyqtSlot("QWidget*", "QWidget*") def on_focusChanged(self, old, now): if now == None: print(f"\nwindow is the active window: {self.isActiveWindow()}") # window lost focus # do what you want self.setWindowState(QtCore.Qt.WindowMinimized) else: print(f"window is the active window: {self.isActiveWindow()}") if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = MyWin() MainWindow.show() sys.exit(app.exec_())
{ "pile_set_name": "StackExchange" }
Q: How can I convert a text file stored in HDFS containing Rows into a Dataframe in Pyspark? I am working with Pyspark and recentrly stored a dataframe as textfile in HDFS like this: df.rdd.repartition(1).saveAsTextFile(path) The file was succesfully created but the format of the content is as follows: Row(APP_PRESS=0.8322056773315432, LINE_PRESS=0.0, POSITION=324.17885120541024, SH_SP=-1.610030115550595, TEMP=24.300001144400007, TRIGGER=4.0869775365401934e-19, V_IND=98.36323547359974) Row(APP_PRESS=0.8025359920151738, LINE_PRESS=0.0, POSITION=324.12892475616513, SH_SP=1.8780468896210554, TEMP=24.300001144399893, TRIGGER=-1.7645281682240943e-19, V_IND=98.36323547359977) ... Now, what I want to do is to load those data in a dataframe in Pyspark, just to get the same dataframe as the saved before ('df'). How can I do it? A: Try something like this: df=sc.textFile(...).toDF() But you could avoid this step by amending your code above to: df.rdd.repartition(1).toDF() and then saving.
{ "pile_set_name": "StackExchange" }
Q: DDD Entity in orm and java I started reading chapter 5 of E. Evans DDD and try to make head or tail of the concepts. In context of ddd what is and what is not entity and what is value object ? looking at Value object or entity object in my Hibernate mapping? - but it is about Hibernate, not DDD, I ask about DDD In above sample of hibernate OrderLine is Entity, but is OrderLine still a DDD entity ? And more generally, can we say that any jpa/Hibernate @Entity is DDD entity, or not ? It seems to me, that OrderLine is a good example of Jpa/Hibernate entity that is not a DDD entity, is it ? If we for instance had used some object database we would possibly store Order togeter with it's OrderLines, wouldn't we ? In terms of relational databases could we say, that Jpa @Entity that is mapped in database as OnDeleteCascade is not a DDD Entity, but it is still a value object ? Is hibernate @Embedded always a DDD value object ? (seems yes, it has no identity) Ok, and now other case with other doubts. Lets say that we have two different systems one in Java other in Python. One for billing other for marketing. Both of them have a Customer Entity. Do we say that BillingCustomer is the same DDD Entity as MarketingCustomer (assuming both of them represent the same Customer John Doe born 01.01.1980 wiht ssn 12-34-56)? This would imply that in java two different classes, even not having common parent (except from Object) can represent the same DDD entity. If so, how should equals be implemented in above classes ? Should java equals return true for two different java classes representing the same DDD entity ? It is often written that Entities are mutable and value objects are immutable. How would we implement below with java and hibernate : @Entity Person has @Embedded Address, Person class has getters and setters and Address only getters ? And to change address street we would do sth like person.setAddress (Address.builder(person.getAddress()).setStreet("newStreet").build()) ? A: Looking for an objective answer to all those might be difficult as there are multiple conflicting interpretations. Generally though, DDD Entities and Value Objects have some resemblance to ORM Entities and Values, but they are very distinct concepts. The two main reasons being: The "identity" referred to in both are different. Database things have database-related identity which rarely if ever matches to business-related identities, especially when denormalized. ORM and Persistence in general is a technology and has nothing to do with "business". DDD Entities and Value Objects are Objects not Data. With that I mean that they should generally conform to Object-Oriented principles, one of which is that Objects should be concerned with behavior not data. This usually leads to completely different forces being applied to them. Because of these points, and there might be others, ORMs should never be mixed into "real" business objects. So with all that in mind, let's answer your questions: No, a Hibernate Entity should never be a DDD Entity. Not, JPA/Hibernate Entity should never be a DDD Entity. Correct. No, JPA Entities/Value Objects have no direct relation to DDD Objects. No, no relation. No, objects' identity can refer to pure conceptual things. BillingCustomer and MarketingCustomer are conceptually different things, so they would never equal, even though the "real" human behind them is the same. In general "real" has a different meaning in software designs. We consider everything "real" that is part of the business (i.e. part of the Ubiquitous Language), even if some or even most of it is not "real" in the conventional sense. No, equals() should also conform to normal Java rules. Objects of different classes should never equal. It would be extremely confusing. Define another relation, for example matches(), or sameCustomer(), etc. Don't know what you mean. HTH.
{ "pile_set_name": "StackExchange" }
Q: Sed command not working:Observed sed: unmatched '#' Inside Following dert.ini file i have a string like this LOG.RDK.SI = FATAL ERROR WARNING using sed command iam trying to replace LOG.RDK.SI = FATAL ERROR WARNING with LOG.RDK.SI = FATAL ERROR WARNING INFO This is the sed command i used.. root@FRT1v3:~# sed -i s#LOG.RDK.SI = FATAL ERROR WARNING#LOG.RDK.SI = FATAL ERROR WARNING INFO#g /opt/dert.ini While executing this command I observed sed: unmatched '#' whats wrong with the sed command iam using A: sed script should be quoted, regex-active characters should be escaped with backslashes, & on the replacement side expands to matched substring. sed -i 's#LOG\.RDK\.SI = FATAL ERROR WARNING#& INFO#g' /opt/dert.ini
{ "pile_set_name": "StackExchange" }
Q: Find the solution to the following differential equation: $ \frac{dy}{dx} = \frac{x - y}{xy} $ The instructor in our Differential Equations class gave us the following to solve: $$ \frac{dy}{dx} = \frac{x - y}{xy} $$ It was an item under separable differential equations. I have gotten as far as $ \frac{dy}{dx} = \frac{1}{y} - \frac{1}{x} $ which to me doesn't really seem much. I don't even know if it really is a separable equation. I tried treating it as a homogeneous equation, multiplying both sides with $y$ to get (Do note that I just did the following for what it's worth)... $$ y\frac{dy}{dx} = 1 - \frac{y}{x} $$ $$ vx (v + x \frac{dv}{dx}) = 1 - v $$ $$ v^2x + vx^2 \frac{dv}{dx} = 1 - v $$ $$ vx^2 \frac{dv}{dx} = 1 - v - v^2x$$ I am unsure how to proceed at this point. What should I first do to solve the given differential equation? A: We write the differential equation as \begin{align*} xyy^\prime=x-y\tag{1} \end{align*} and follow the receipt I.237 in the german book Differentialgleichungen, Lösungsmethoden und Lösungen I by E. Kamke. We consider $y=y(x)$ as the independent variable and use the substitution \begin{align*} v=v(y)=\frac{1}{y-x(y)}=\left(y-x(y)\right)^{-1}\tag{2} \end{align*} We obtain from (2) \begin{align*} v&=\frac{1}{y-x}\qquad\to\qquad x=y-\frac{1}{v}\\ v^{\prime}&=(-1)(y-x)^{-2}\left(1-x^{\prime}\right)=\left(\frac{1}{y^{\prime}}-1\right)v^2 \end{align*} From (1) we get by taking $v$: \begin{align*} \frac{1}{y^{\prime}}=\frac{xy}{x-y}=\left(y-\frac{1}{v}\right)y(-v)=y-y^2v\tag{3} \end{align*} Putting (2) and (3) together we get \begin{align*} v^{\prime}=\left(y-y^2v-1\right)v^2 \end{align*} respectively \begin{align*} \color{blue}{v^{\prime}+y^2v^3-(y-1)v^2=0}\tag{4} \end{align*} and observe (4) is an instance of an Abel equation of the first kind.
{ "pile_set_name": "StackExchange" }
Q: How to find and update nested array element in an object on mongodb I have a collection down below. I am trying to update an array element. I am trying to update if lineItem _id value is 1 then go to spec list and update characteristicsValue from 900 to 50 if specName is "Model", as you can see, _id is also an array. collection data: { "_id": "100", "name": "Campaign", "status": "Active", "parts": { "lineItem": [ { "_id": [ { "name": "A", "value": "1" } ], "spec": [ { "specName": "Brand", "characteristicsValue": [ { "value": "500" } ] }, { "specName": "Model", "characteristicsValue": [ { "value": "900" } ] } ] }, { "_id": [ { "name": "B", "value": "2" } ], "spec": [ { "specName": "Brand", "characteristicsValue": [ { "value": "300" } ] }, { "specName": "Model", "characteristicsValue": [ { "value": "150" } ] } ] }, { "_id": [ { "name": "C", "value": "2" } ] } ] } } related update doesnt work as I expected. db.Collection.update({"parts.lineItem._id.value" : "1", "parts.lineItem.spec.specName" : "Model" },{ $set: { "parts.lineItem.spec.$.characteristicsValue" : "50" } }) EDIT: Every _id has a spec array. so, we need to find _id and then go to spec under _id array, find the brand and update the value. A: Try this way: db.Collection.update( {}, { $set: { "parts.lineItem.$[outer].spec.$[inner].characteristicsValue" : "50" } }, { multi: true, arrayFilters: [{"outer._id.value" : "1"}, {"inner.specName" : "Model"}]} );
{ "pile_set_name": "StackExchange" }
Q: How to draw a border (stroke) around a UIImage's opaque pixels Given a UIImage that contains non-opaque (alpha < 1) pixel data, how can we draw an outline / border / stroke around the pixels that are opaque (alpha > 0), with a custom stroke color and thickness? (I'm asking this question to provide an answer below) A: I've come up with the following approach by piecing together suggestions from other SO posts and adapting them to something I'm happy with. The first step is to obtain a UIImage to begin processing. In some cases you might already have this image, but in the event that you might want to add a stroke to a UIView (maybe a UILabel with a custom font), you'll first want to capture an image of that view: public extension UIView { /// Renders the view to a UIImage /// - Returns: A UIImage representing the view func imageByRenderingView() -> UIImage { layoutIfNeeded() let rendererFormat = UIGraphicsImageRendererFormat.default() rendererFormat.scale = layer.contentsScale rendererFormat.opaque = false let renderer = UIGraphicsImageRenderer(size: bounds.size, format: rendererFormat) let image = renderer.image { _ in self.drawHierarchy(in: self.bounds, afterScreenUpdates: true) } return image } } Now that we can obtain an image of a view, we need to be able to crop it to it's opaque pixels. This step is optional, but for things like UILabels, sometimes their bounds are bigger than the pixels they are displaying. The below function takes a completion block so it can perform the heavy lifting on a background thread (note: UIKit isn't thread safe, but CGContexts are). public extension UIImage { /// Converts the image's color space to the specified color space /// - Parameter colorSpace: The color space to convert to /// - Returns: A CGImage in the specified color space func cgImageInColorSpace(_ colorSpace: CGColorSpace) -> CGImage? { guard let cgImage = self.cgImage else { return nil } guard cgImage.colorSpace != colorSpace else { return cgImage } let rect = CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height) let ciImage = CIImage(cgImage: cgImage) guard let convertedImage = ciImage.matchedFromWorkingSpace(to: CGColorSpaceCreateDeviceRGB()) else { return nil } let ciContext = CIContext() let convertedCGImage = ciContext.createCGImage(convertedImage, from: rect) return convertedCGImage } /// Crops the image to the bounding box containing it's opaque pixels, trimming away fully transparent pixels /// - Parameter minimumAlpha: The minimum alpha value to crop out of the image /// - Parameter completion: A completion block to execute as the processing takes place on a background thread func imageByCroppingToOpaquePixels(withMinimumAlpha minimumAlpha: CGFloat = 0, _ completion: @escaping ((_ image: UIImage)->())) { guard let originalImage = cgImage else { completion(self) return } // Move to a background thread for the heavy lifting DispatchQueue.global(qos: .background).async { // Ensure we have the correct colorspace so we can safely iterate over the pixel data let colorSpace = CGColorSpaceCreateDeviceRGB() guard let cgImage = self.cgImageInColorSpace(colorSpace) else { DispatchQueue.main.async { completion(UIImage()) } return } // Store some helper variables for iterating the pixel data let width: Int = cgImage.width let height: Int = cgImage.height let bytesPerPixel: Int = cgImage.bitsPerPixel / 8 let bytesPerRow: Int = cgImage.bytesPerRow let bitsPerComponent: Int = cgImage.bitsPerComponent let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue // Attempt to access our pixel data guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo), let ptr = context.data?.assumingMemoryBound(to: UInt8.self) else { DispatchQueue.main.async { completion(UIImage()) } return } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height)) var minX: Int = width var minY: Int = height var maxX: Int = 0 var maxY: Int = 0 for x in 0 ..< width { for y in 0 ..< height { let pixelIndex = bytesPerRow * Int(y) + bytesPerPixel * Int(x) let alphaAtPixel = CGFloat(ptr[pixelIndex + 3]) / 255.0 if alphaAtPixel > minimumAlpha { if x < minX { minX = x } if x > maxX { maxX = x } if y < minY { minY = y } if y > maxY { maxY = y } } } } let rectangleForOpaquePixels = CGRect(x: CGFloat(minX), y: CGFloat(minY), width: CGFloat( maxX - minX ), height: CGFloat( maxY - minY )) guard let croppedImage = originalImage.cropping(to: rectangleForOpaquePixels) else { DispatchQueue.main.async { completion(UIImage()) } return } DispatchQueue.main.async { let result = UIImage(cgImage: croppedImage, scale: self.scale, orientation: self.imageOrientation) completion(result) } } } } Finally, we need the ability to fill a UIImage with a color of our choosing: public extension UIImage { /// Returns a version of this image any non-transparent pixels filled with the specified color /// - Parameter color: The color to fill /// - Returns: A re-colored version of this image with the specified color func imageByFillingWithColor(_ color: UIColor) -> UIImage { return UIGraphicsImageRenderer(size: size).image { context in color.setFill() context.fill(context.format.bounds) draw(in: context.format.bounds, blendMode: .destinationIn, alpha: 1.0) } } } Now we can get to the problem at hand, adding a stroke to our rendered / cropped UIImage. This process involves flooding the input image the desired stroke color, then rendering the image offset from our original image's centre point by the stroke thickness, in a circular formation. The more times we draw this "stroke" image within the 0...360 degree range, the more "precise" the resulting stroke will appear. That being said, a default of 8 strokes seems to suffice for most things (resulting in a stroke being rendered at 0, 45, 90, 135, 180, 225, and 270 degree intervals). Further, we also need to draw this stroke image multiple times for a given angle. In most cases, 1 draw per angle will suffice, but as the desired stroke thickness increases, the number of times we should draw the stroke image along a given angle should also increase to maintain a good looking stroke. When all of the strokes have been drawn, we finish off by re-drawing the original image in the centre of this new image, so that it appears in front of all of the drawn stroke images. The below function takes care of these remaining steps: public extension UIImage { /// Applies a stroke around the image /// - Parameters: /// - strokeColor: The color of the desired stroke /// - inputThickness: The thickness, in pixels, of the desired stroke /// - rotationSteps: The number of rotations to make when applying the stroke. Higher rotationSteps will result in a more precise stroke. Defaults to 8. /// - extrusionSteps: The number of extrusions to make along a given rotation. Higher extrusions will make a more precise stroke, but aren't usually needed unless using a very thick stroke. Defaults to 1. func imageByApplyingStroke(strokeColor: UIColor = .white, strokeThickness inputThickness: CGFloat = 2, rotationSteps: Int = 8, extrusionSteps: Int = 1) -> UIImage { let thickness: CGFloat = inputThickness > 0 ? inputThickness : 0 // Create a "stamp" version of ourselves that we can stamp around our edges let strokeImage = imageByFillingWithColor(strokeColor) let inputSize: CGSize = size let outputSize: CGSize = CGSize(width: size.width + (thickness * 2), height: size.height + (thickness * 2)) let renderer = UIGraphicsImageRenderer(size: outputSize) let stroked = renderer.image { ctx in // Compute the center of our image let center = CGPoint(x: outputSize.width / 2, y: outputSize.height / 2) let centerRect = CGRect(x: center.x - (inputSize.width / 2), y: center.y - (inputSize.height / 2), width: inputSize.width, height: inputSize.height) // Compute the increments for rotations / extrusions let rotationIncrement: CGFloat = rotationSteps > 0 ? 360 / CGFloat(rotationSteps) : 360 let extrusionIncrement: CGFloat = extrusionSteps > 0 ? thickness / CGFloat(extrusionSteps) : thickness for rotation in 0..<rotationSteps { for extrusion in 1...extrusionSteps { // Compute the angle and distance for this stamp let angleInDegrees: CGFloat = CGFloat(rotation) * rotationIncrement let angleInRadians: CGFloat = angleInDegrees * .pi / 180.0 let extrusionDistance: CGFloat = CGFloat(extrusion) * extrusionIncrement // Compute the position for this stamp let x = center.x + extrusionDistance * cos(angleInRadians) let y = center.y + extrusionDistance * sin(angleInRadians) let vector = CGPoint(x: x, y: y) // Draw our stamp at this position let drawRect = CGRect(x: vector.x - (inputSize.width / 2), y: vector.y - (inputSize.height / 2), width: inputSize.width, height: inputSize.height) strokeImage.draw(in: drawRect, blendMode: .destinationOver, alpha: 1.0) } } // Finally, re-draw ourselves centered within the context, so we appear in-front of all of the stamps we've drawn self.draw(in: centerRect, blendMode: .normal, alpha: 1.0) } return stroked } } Combining it all together, you can apply a stroke to a UIImage like so: let inputImage: UIImage = UIImage() let outputImage = inputImage.imageByApplyingStroke(strokeColor: .black, strokeThickness: 2.0) Here is an example of the stroke in action, being applied to a label with white text, with a black stroke:
{ "pile_set_name": "StackExchange" }
Q: É possível acessar a propriedade um objeto dentro dele mesmo? Cadastro = { "descricao" : "Novo usuário", "editando" : false } É possível em tempo de execução eu obter o valor da propriedade "editando" e usa-lo? Algo como: Cadastro = { "descricao" : "Novo usuário", "editando" : false, "titulo" : "editando" ? "Editar" : "Criar" } Eu encontrei uma forma mas não é usando a propriedade e sim criando uma variavel no escopo global: window.editando = true; Cadastro = { "descricao" : "Novo usuário", "editando" : false, "titulo" : (window.editando ? "Editar" : "Novo") } Existe alguma outra forma de fazer isso? O que eu quero é quando o valor da variável mudar o valor do retorno "titulo" também mude. A: code, você pode fazer da seguinte forma: var Cadastro = function (descricao, editando) { this.descricao = descricao; this.editando = editando; }; Object.defineProperty(Cadastro.prototype, "titulo", { get: function () { return this.editando ? "Editar" : "Criar"; }, enumerable: true }); var cadastro1 = new Cadastro("Novo usuário", false); console.log(cadastro1.titulo); // Criar var cadastro2 = new Cadastro(); cadastro2.descricao = "Novo perfil"; cadastro2.editando = true; console.log(cadastro2.titulo); // Editar Depedendo da sua implementação, você pode encontrar alguma dificuldade por causa da combinação de Object.defineProperty e *.prototype, neste caso defina a propriedade no construtor da "Classe". var Cadastro = function (descricao, editando) { this.descricao = descricao; this.editando = editando; Object.defineProperty(this, "titulo", this.descriptor.titulo); }; Cadastro.prototype.descriptor = {}; Cadastro.prototype.descriptor.titulo = { get: function () { return this.editando ? "Editar" : "Criar"; }, enumerable: true } var cadastro1 = new Cadastro("Novo Usuario", true); var cadastro2 = new Cadastro("Novo Perfil", false); console.log(JSON.stringify(cadastro1)); console.log(JSON.stringify(cadastro2)); A: var Cadastro = { descricao: "Novo usuário", editando: false, get titulo() { if (this.editando) { return "Editar"; } else { return "Criar"; } } }; console.log(Cadastro.titulo); Cadastro.editando = true; console.log(Cadastro.titulo); A: Com que com uma pequena gambiarra é possível sim. Utilize uma self-invoking function fazendo e utilize o this, assim você referenciará o próprio objeto. Utilizei a propriedade __init para poder referênciar o próprio objeto. Daí, como a variável this só não fica acessível no contexto de declaração, eu chamo ela ao fim da declaração do objeto. Para que a variável Cadastro importe o valor de declaração do nosso objeto, é necessário retornar o this ao final dessa função. Veja isso como um "construtor" do nosso objeto. Cadastro = { "descricao" : "Novo usuário", "editando" : false, "__init" : function () { alert(this.editando) this.titulo = this.editando ? "Editar" : "Novo"; return this; } }.__init() Confira no JSFiddle Nesse caso, é necessário que o this esteja dentro do contexto do objeto que deseja referenciar (no caso a nossa função anônima referencia Cadastro). Se você usar o this fora de um contexto de um objeto, a referência será window. Outra forma de fazer essa declaração que você precisa seria declarando esse índice titulo depois de declarar o objeto. Faça assim: Cadastro = { "descricao" : "Novo usuário", "editando" : false, } Cadastro.titulo = Cadastro.editando ? "Editar" : "Novo";
{ "pile_set_name": "StackExchange" }
Q: Make 2 JButtons Equal in size I have two JButtons with texts "Ok" and "Cancel". I am using GridBagLayout to align them in a JDialog. I have set the anchor to GridBagConstraints.CENTER. Due to the difference in the number of characters in the texts "Ok" and "Cancel", the buttons are of different sizes. How do I align them correctly so that each of them have the same size. I tried the following but no avail. okayButton.setSize(cancelButton.getSize()); A: Try setting the fill to GridBagConstraints.BOTH and give both buttons equal weight.
{ "pile_set_name": "StackExchange" }
Q: Create a document that references a collection's ObjectId Have a postSchema that reference an ObjectId from a User Schema: var postSchema = new Schema({ text: { type: String, required: true, maxlength: 140 }, _creator: { type: mongoose.Schema.ObjectId, ref: 'User', required: true }, }); In my postController, how do I set the _creator attribute when creating a new Post?: exports.postCreatePost = function(req, res, next) { console.log(req.body); var newPost = new Post({ text: req.body.text, _creator: req.body.User._id // What is this supposed to be in order to reference User's ObjectId? }); newPost.save(function(err, newPost) { res.status(200).json(newPost); }); } Receiving "Unexpected string in JSON at position 30" error when attempting to Post this JSON using Postman with that ObjectId for an existing user: { "text": "first test post" "_creator": "5a13b3c695fcb47ea5c71308" } A: Here your postSchema should be like this, var postSchema = new Schema({ text: { type: String, required: true, maxlength: 140 }, _creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, }); _creator property should have type as mongoose.Schema.Types.ObjectId
{ "pile_set_name": "StackExchange" }
Q: Preload marker images for Google Maps I am using Google Maps V3 API to create a google map where the markers change their marker icons on mouseover. However i notice the icons flicker once the first time the user does it to that specific marker, and to every marker, which I guess is due to the mouseover images taking some time to download. To solve this, I am thinking of preloading the mouseover icon images. How can I do this? A: I'm unsure if this works in every browser, but on modern browsers (FF 3.6+, IE8/9 (I think), Safari/Chrome), with cache enabled, simply adding the elements to the DOM loads them and caches them (i.e. put them on the page in a hidden div), so the next time they're requested, its from your cache, not the server, totally eliminating the flash.
{ "pile_set_name": "StackExchange" }
Q: How create movement buttons left/right? Please help. I am a beginner on Swift. I've added sprites for player and left/right buttons. But how can I add an action for every button and apply these actions to the player? import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var player: SKSpriteNode! var leftMove: SKSpriteNode! var rightMove: SKSpriteNode! override func didMoveToView(view: SKView) { player = SKSpriteNode (imageNamed: "player") player.position = CGPoint(x:127, y:125) addChild(player) leftMove = SKSpriteNode (imageNamed: "leftMove") leftMove.position = CGPoint(x:80, y:35) leftMove.size = CGSize (width: 55, height: 55) addChild(leftMove) rightMove = SKSpriteNode (imageNamed: "rightMove") rightMove.position = CGPoint(x:160, y:35) rightMove.size = CGSize (width: 55, height: 55) addChild(rightMove) physicsWorld.contactDelegate = self } A: Give the buttons a unique name like: leftMove.name = "Left" rightMove.name = "Right" Implement the logic in touchesBegan: override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ for touch: AnyObject in touches { let location = touch.locationInNode(self) let node = self.nodeAtPoint(location) if (node.name == "Left") { // Implement your logic for left button touch here: player.position = CGPoint(x:player.position.x-1, y:player.position.y) } else if (node.name == "Right") { // Implement your logic for right button touch here: player.position = CGPoint(x:player.position.x+1, y:player.position.y) } } }
{ "pile_set_name": "StackExchange" }
Q: Using acceptsMouseMovedEvents for SpriteKit mouse actions with Storyboards and Swift I have created a SpriteKit scene by referencing a custom NSView using Storyboards in Xcode. However, I cannot implement any mouseMoved events using SpriteKit because I do not know how to reference the program's NSWindowto set its acceptsMouseMovedEvents property to "true". How can I create an @IBOutlet reference to my NSWindow in my AppDelegate.swift file so that I can change this property? A: You can configure an NSTrackingArea object to track the movement of the mouse as well as when the cursor enters or exits a view. To create an NSTrackingArea object, you specify a region of a view where you want mouse events to be tracked, the owner that will receive the mouse event messages, and when the tracking will occur (e.g., in the key window). The following is an example of how to add a tracking area to a view. Add to your SKScene subclass, such as GameScene.swift. Swift 3 and 4 override func didMove(to view: SKView) { // Create a tracking area object with self as the owner (i.e., the recipient of mouse-tracking messages let trackingArea = NSTrackingArea(rect: view.frame, options: [.activeInKeyWindow, .mouseMoved], owner: self, userInfo: nil) // Add the tracking area to the view view.addTrackingArea(trackingArea) } // This method will be called when the mouse moves in the view override func mouseMoved(with theEvent: NSEvent) { let location = theEvent.location(in: self) print(location) } Swift 2 override func didMoveToView(view: SKView) { // Create a tracking area object with self as the owner (i.e., the recipient of mouse-tracking messages let trackingArea = NSTrackingArea(rect: view.frame, options: NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseMoved, owner: self, userInfo: nil) // Add the tracking area to the view view.addTrackingArea(trackingArea) } // This method will be called when the mouse moves in the view override func mouseMoved(theEvent: NSEvent) { let location = theEvent.locationInNode(self) println(location) }
{ "pile_set_name": "StackExchange" }
Q: Adding a PATCH method to Backbone collections I have a web application that is using a Django/Tastypie backend with a Backbone/Marionette frontend. I'd like to use Tastypie's bulk operations to create multiple objects via my API using a PATCH request to a list endpoint. My understanding is that Backbone doesn't support this. What is the best way to add this to Backbone? I assume I'll need to add a save method to Backbone's collection object and extend the Backbone sync method. A: From http://backbonejs.org/ If instead, you'd only like the changed attributes to be sent to the server, call model.save(attrs, {patch: true}). You'll get an HTTP PATCH request to the server with just the passed-in attributes. Fiddle Sending patch request on backbone collection sync: $(function() { Backbone.$ = $; var User = Backbone.Model.extend({ urlRoot: "/testUrl", isNew : function () { return false; }, defaults: { name: 'John Doe', age: 25 } }); var user1 = new User(); var user2 = new User(); var user3 = new User(); var user4 = new User(); var UserCollection = Backbone.Collection.extend({ model: User, url: "/testUrl" }); var userCollection = new UserCollection([ user1, user2, user3]); // update user1.set('name','Jane Doe'); user4.set('name','Another User'); // delete userCollection.remove(user2); // add userCollection.add(user4); userCollection.sync('patch', userCollection , { error: function () { console.log(userCollection); } }); });
{ "pile_set_name": "StackExchange" }
Q: how do i make list of list python Extracting data from Excel sheet for value in quoted.findall(str(row[2])): i.append(value.replace('"', '').strip()) print i Then i get a set of lists as below ['M', 'N', 'O'] ['P', 'Q', 'R'] ['S', 'T', 'U'] ['W', 'X', 'Y'] how do i make this set of list in another list, i am expecting output as [ ['M', 'N', 'O'], ['P', 'Q', 'R'], ['S', 'T', 'U'], ['W', 'X', 'Y'] ] if i want to access this list, i simply use listOfList[2] and i should get ['S', 'T', 'U'] thanks in advance. A: The same as in Nirk's answer but using list comprehensions: j = [[value.replace('"', '').strip() for value in quoted.findall(str(row[2]))] for row in ...] A: Instead of printing. just append the entire list to another list: j=[]; for row in ... : i = [] for value in quoted.findall(str(row[2])): i.append(value.replace('"', '').strip()) j.append(i)
{ "pile_set_name": "StackExchange" }
Q: How to migrate VMs from ESXi 3.5 to 4? Before I jump into this headfirst I want to make sure this will work. I currently have an ESXi 3.5 host, but I would like to upgrade to ESXi 4. I'm using the free version. My plan is to: 1) Copy the VM folders from the current ESXi 3.5 datastore to a local 2TB hard drive for temporary storage. 2) Wipe the current ESXi 3.5 install and datastore, then install ESXi 4 (clean slate). 3) Copy the VMs from the local 2TB drive back to the new ESXi 4 datastore. Is it as simple as that? A: Yes, it's really that simple, it'll just work - but you may well wish to update each VM's model version, reboot them, update the VMTools, reboot and maybe reconfigure your vNICs - then you'll benefit from the performance benefits best. Oh and take into consideration that 4.1 has just been launched which can be faster than 4.0U2, although it's newer so potentially less stable/tested.
{ "pile_set_name": "StackExchange" }
Q: Compare [Sheet 2] to [Sheet 1] & add any missing unique numbers in [Sheet 1] to the bottom of table in [Sheet 2] Just wondering if anybody could help with the below problem: I have two sheet: Mini Master Critical Path New data is added to the mini master on daily basis. Both the Mini Master Critical Path hold the unique number in column A. I would like to run a macro that compares Column A in the Mini Master to column A in the Critical Path. If the Mini Master has any unique numbers (that are not listed in column A of the Critical Path) I would like to copy & paste them to the bottom of the Critical Path Table. Data should only flow Mini Master > Critical path. Never Critical Path > Mini Master. Example: it would be great if i could find a macro that identifies the missing unique numbers such as the one (highlighed in pink) in the below image. Mini Master Sheet Then copy & paste that unique number onto the bottom of the table on the Critical Path Sheet (also highlighted in pink) Critical Path Sheet Once the data is in i have written a code that will keep the Critical Path Sheet Up to date with any changes made in the Mini Master, that will then populate columns B, C & D. Thank-you in advance for your help. A: Try, Sub test() Dim Ws As Worksheet Dim toWs As Worksheet Dim rngDB As Range, rngT As Range Dim vDB As Variant, vR() As Variant Dim i As Long, n As Long, j As Integer Set Ws = Sheets("MINI MASTER") Set toWs = Sheets("CRITICAL PATH") vDB = Ws.Range("a1").CurrentRegion With toWs Set rngDB = .Range("a2", .Range("a" & Rows.Count).End(xlUp)) For i = 2 To UBound(vDB, 1) If WorksheetFunction.CountIf(rngDB, vDB(i, 1)) Then Else n = n + 1 ReDim Preserve vR(1 To 4, 1 To n) For j = 1 To 4 vR(j, n) = vDB(i, j) Next j End If Next i Set rngT = .Range("a" & Rows.Count).End(xlUp)(2) If n Then rngT.Resize(n, 4) = WorksheetFunction.Transpose(vR) End If End With End Sub
{ "pile_set_name": "StackExchange" }
Q: pymysql ProgrammingError (syntax) al llamar una función de python con una cadena que representa el nombre de la tabla Estoy intentando llamar una función que ejecute una consulta de una base de datos y segun el input del usuario busque en la tabla country o en la tabla city a través del parámetro popType de la función cityLw(). Entonces al llamar a esta función se le pasa el valor city o country. def cityLw(popType, popQue): query = 'SELECT * FROM %s WHERE population < %s' with conn: cursor = conn.cursor() if popType == 'city': cursor.execute(query, (popType, int(popQue))) else: cursor.execute(query, (popType, int(popQue))) return cursor.fetchall() popType las he definido en la funcion main, que es la que llama a cityLw() así: city = 'city' cities = WorldConn.cityLw(city, popQue) luego otra funcion llamará a cityLw() para que busque en la tabla country: country = 'country' countries = WorldConn.cityLw(country, popQue) y tengo este error: pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''city' WHERE population < 145' at line 1") Entonces parece que a la consulta le llega el string city con las comillas y por eso SQL lo rechaza. He probado varias cosas pero no funciona A: El problema es exactamente el que comentas, la query queda como: 'SELECT * FROM 'city' WHERE population < 145' cuando debería ser: 'SELECT * FROM city WHERE population < 145' Esto pasa porque en las especificaciones de DB-API 2 no se permite la parametrización del nombre la tabla. En tal caso, debes recurrir a formatear la cadena. Si te preocupa la inyección de código siempre puedes validar el nombre de la tabla. Si tienes solo dos tablas de nombre conocido, lo más simple es usar el bloque condicional: def cityLw(popType, popQue): with conn: cursor = conn.cursor() if popType == 'city': query = 'SELECT * FROM city WHERE population < %s' cursor.execute(query, (int(popQue, ))) elif popType == 'country': query = 'SELECT * FROM country WHERE population < %s' cursor.execute(query, (int(popQue, ))) else: raise ValueError("Invalid table name") return cursor.fetchall() Si tienes muchas tablas, puedes usar una "lista blanca" de nombres TABLES = {"city", "country"} def cityLw(popType, popQue): if popType not in TABLES: raise ValueError("Invalid table name") query = f'SELECT * FROM {popType} WHERE population < %s' cursor.execute(query, (int(popQue, ))) En última instancia puedes realizar un filtro más genérico, por ejemplo permitiendo solo nombres válidos para una tabla según las especificaciones SQL: import re TABLE_NAME_VAL = re.compile(r'^[0-9a-zA-Z_\$]+$') def cityLw(popType, popQue): if not TABLE_NAME_VAL.match(popType): raise ValueError("Invalid table name") query = f'SELECT * FROM {poptype} WHERE population < %s' cursor.execute(query, (int(popQue)))
{ "pile_set_name": "StackExchange" }
Q: Getting a column as concatenated column from a reference table and primary id's from a Dataset I'm trying to get a concatenated data as a single column using below datasets. Sample DS: val df = sc.parallelize(Seq( ("a", 1,2,3), ("b", 4,6,5) )).toDF("value", "id1", "id2", "id3") +-------+-----+-----+-----+ | value | id1 | id2 | id3 | +-------+-----+-----+-----+ | a | 1 | 2 | 3 | | b | 4 | 6 | 5 | +-------+-----+-----+-----+ from the Reference Dataset +----+----------+--------+ | id | descr | parent| +----+----------+--------+ | 1 | apple | fruit | | 2 | banana | fruit | | 3 | cat | animal | | 4 | dog | animal | | 5 | elephant | animal | | 6 | Flight | object | +----+----------+--------+ val ref= sc.parallelize(Seq( (1,"apple","fruit"), (2,"banana","fruit"), (3,"cat","animal"), (4,"dog","animal"), (5,"elephant","animal"), (6,"Flight","object"), )).toDF("id", "descr", "parent") I am trying to get the below desired OutPut +-----------------------+--------------------------+ | desc | parent | +-----------------------+--------------------------+ | apple+banana+cat/M | fruit+fruit+animal/M | | dog+Flight+elephant/M | animal+object+animal/M | +-----------------------+--------------------------+ And also I need to concat only if(id2,id3) is not null. Otherwise only with id1. I breaking my head for the solution. A: Exploding the first dataframe df and joining to ref with followed by groupBy should work as you expected val dfNew = df.withColumn("id", explode(array("id1", "id2", "id3"))) .select("id", "value") ref.join(dfNew, Seq("id")) .groupBy("value") .agg( concat_ws("+", collect_list("descr")) as "desc", concat_ws("+", collect_list("parent")) as "parent" ) .drop("value") .show() Output: +-------------------+--------------------+ |desc |parent | +-------------------+--------------------+ |Flight+elephant+dog|object+animal+animal| |apple+cat+banana |fruit+animal+fruit | +-------------------+--------------------+
{ "pile_set_name": "StackExchange" }
Q: href javascript is not working on my image I'm adding images stored in firebase to my html page from the database. That works and the image shows up, but I am unable to make the href property work on the img element. I want it to be clickable. Suggestions what I am doing wrong here? var img = document.createElement("img"); img.src = snapshot.child("urlToImage " + (i) + " Content").val(); img.href = snapshot.child("urlToImage " + (i) + " Content").val(); img.height = 30; img.width = 30; contentA[i].appendChild(img); A: Clickable image function clickMe(){ alert('Clicked!'); } <!DOCTYPE html> <html> <body> An image as a link: <a onclick="clickMe()"> <img src="https://s3.eu-central-1.amazonaws.com/live-resource/productCategories/HF-AT/HF_PRINT_WEB_F781A5E7-1575-4D81-8317-BC51C8653EBB.jpeg" border="0" alt="W3Schools" src="logo_w3s.gif" width="100" height="100"> </a> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: not getting all cookie info using python requests module I'm learning how to login to an example website using python requests module. This Video Tutorial got me started. From all the cookies that I see in GoogleChrome>Inspect Element>NetworkTab, I'm not able to retrieve all of them using the following code: import requests with requests.Session() as s: url = 'http://www.noobmovies.com/accounts/login/?next=/' s.get(url) allcookies = s.cookies.get_dict() print allcookies Using this I only get csrftoken like below: {'csrftoken': 'ePE8zGxV4yHJ5j1NoGbXnhLK1FQ4jwqO'} But in google chrome, I see all these other cookies apart from csrftoken (sessionid, _gat, _ga etc): I even tried the following code from here, but the result was the same: from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler import cookielib #Create a CookieJar object to hold the cookies cj = cookielib.CookieJar() #Create an opener to open pages using the http protocol and to process cookies. opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler()) #create a request object to be used to get the page. req = Request("http://www.noobmovies.com/accounts/login/?next=/") f = opener.open(req) #see the first few lines of the page html = f.read() print html[:50] #Check out the cookies print "the cookies are: " for cookie in cj: print cookie Output: <!DOCTYPE html> <html xmlns="http://www.w3.org the cookies are: <Cookie csrftoken=ePE8zGxV4yHJ5j1NoGbXnhLK1FQ4jwqO for www.noobmovies.com/> So, how can I get all the cookies ? Thanks. A: The cookies being set are from other pages/resources, probably loaded by JavaScript code. You can check it making the request to the page only (without running the JS code), using tools such as wget, curl or httpie. The only cookie this server set is csrftoken, as you can see in: $ wget --server-response 'http://www.noobmovies.com/accounts/login/?next=/' --2016-02-01 22:51:55-- http://www.noobmovies.com/accounts/login/?next=/ Resolving www.noobmovies.com (www.noobmovies.com)... 69.164.217.90 Connecting to www.noobmovies.com (www.noobmovies.com)|69.164.217.90|:80... connected. HTTP request sent, awaiting response... HTTP/1.1 200 OK Server: nginx/1.4.6 (Ubuntu) Date: Tue, 02 Feb 2016 00:51:58 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Vary: Accept-Encoding Expires: Tue, 02 Feb 2016 00:51:58 GMT Vary: Cookie,Accept-Encoding Cache-Control: max-age=0 Set-Cookie: csrftoken=XJ07sWhMpT1hqv4K96lXkyDWAYIFt1W5; expires=Tue, 31-Jan-2017 00:51:58 GMT; Max-Age=31449600; Path=/ Last-Modified: Tue, 02 Feb 2016 00:51:58 GMT Length: unspecified [text/html] Saving to: ‘index.html?next=%2F’ index.html?next=%2F [ <=> ] 10,83K 2,93KB/s in 3,7s 2016-02-01 22:52:03 (2,93 KB/s) - ‘index.html?next=%2F’ saved [11085] Note the Set-Cookie line.
{ "pile_set_name": "StackExchange" }
Q: BYTE typedef in VC++ and windows.h I am using Visual C++, and I am trying to include a file that uses BYTE (as well as DOUBLE, LPCONTEXT...) , which by default is not a defined type. If I include windows.h, it works fine, but windows.h also defines GetClassName wich I don't need. I am looking for an alternative to windows.h include, that would work with VC++ and would define most of the types like BYTE, DOUBLE ... Thanks A: I think windows.h at most declares GetClassName(), not that it defines it. A function declaration like that (and there will be many, many more brought in by windows.h) doesn't cost anything. If you're worried that it collides with a function name you want to use, consider putting your own in a namespace. A: You need to include windows.h to get those types. If you want to reduce the number of defines that windows.h brings in, you can #define WIN32_LEAN_AND_MEAN before including windows.h, which will exclude a lot of stuff (but not everything). See http://support.microsoft.com/kb/166474.
{ "pile_set_name": "StackExchange" }
Q: Rails + AWS + sendmail: Emails not being sent even with (seemingly) correct config settings? So in my development my emails are sending fine when I change the settings. However in my preview environment on my server, in the logs it looks like emails are sending properly with no errors, but I never receive anything. This applies to not just one mailer, but all of them. This is my config/environments/preview.rb file: EdmundWeb::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true config.action_mailer.raise_delivery_errors = true config.action_mailer.perform_deliveries = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store config.action_view.cache_template_loading = true config.cache_store = :dalli_store, 'localhost', { :namespace => 'preview' } # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 # For Devise config.action_mailer.default_url_options = { :host => 'mysite.com' } config.to_prepare { Devise::SessionsController.force_ssl } config.to_prepare { Devise::RegistrationsController.force_ssl } config.to_prepare { Devise::PasswordsController.force_ssl } end In my environment.rb I set my mailer to sendmail: # Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application EdmundWeb::Application.initialize! ActionMailer::Base.delivery_method = :sendmail Could it be mailer settings on my AWS server that is preventing my mailer from sending mail? A: My AWS machine was running on ubuntu. The fix was running apt-get install postfix as root and accepting all the default answers. How is this not documented anywhere else!
{ "pile_set_name": "StackExchange" }
Q: When first incorporated, I created 100,000 company shares worth $1 each. What does this mean? When first incorporated, I created 100,000 company shares worth $1 each. What does this mean? Does the value mean anything? Because I just started, no capital was paid. Do I also have to pay Capital Gain Tax if my company increases in value to say $1,000,000 (a tax on $900,000)? A: There’s the notion of share capital and a separate notion of authorised share capital (which, confusingly, isn’t necessarily share capital). Share capital consists of all funds raised by a company in exchange for shares of either common or preferred shares of stock. - investopedia Authorized share capital is the number of stock units (shares) that a company can issue as stated in its memorandum of association or its articles of incorporation. Authorized share capital is often not fully used by management in order to leave room for future issuance of additional stock in case the company needs to raise capital quickly. - investopedia If your 100,000 shares were simply authorised but not issued, it means you can issue up to that many shares. How many shares you actually issue is a separate matter. If you issued all the 100,000 shares to yourself at $1 per share, you personally would have bought that many shares. The $100,000 could be funded by cash. If you didn’t pay for the shares, you’d owe the company $100,000. Capital gains are only calculated when you sell, and is the difference between what you paid on purchase and what you got back on the sale. The price could go up and down, but unless you are obliged to (or perhaps elect to) revalue the asset to the prevailing market price, you have not made any capital gain or loss until you actually sell. Disclaimer: I am not a tax, finance or law professional and the above is not professional advice of any kind. Please seek professional advice where appropriate.
{ "pile_set_name": "StackExchange" }
Q: JQuery Autocomplete doesn't filter results Yeah, there are many questions in the forum but somehow none works for me. I am not doing very special. My Autocomplete is populating the results but the results are not getting filtered My code is : $("#empName").autocomplete({ source: function(request, response) { $.ajax({ url: "api/clientEmp/of/" + sessionClientId + "/notingroup/" + groupId, type: "GET", dataType: "json", data: { term: $("#empName").val() }, success: function(data) { response($.map(data, function(item) { return { label: item.EmpName, value: item.EmpId }; })); } }); }, minLength: 0, focus: function(event, ui) { $("#empName").val(ui.item.label); } }); And the json output is something like this [ { "EmpId": 26, "EmpNum": "Rel-72015-31", "EmpName": "R.durai" }, { "EmpId": 21, "EmpNum": "REL-42015-22", "EmpName": "Zishan" }, { "EmpId": 56, "EmpNum": "Rel-22015-19", "EmpName": "Raj Singh" } ] It neatly shows the options but when i type anything this all results shows up and they are not filtered I am missing a piece of code which asks to filter the results. Can anyone please suggest. thanks in advance. A: $("#empName").autocomplete({ source: function(request, response) { $.ajax({ url: "api/clientEmp/of/" + sessionClientId + "/notingroup/" + groupId, type: "GET", dataType: "json", data: { term: $("#empName").val() }, success: function(data) { var array = $.map(data, function(item) { return { label: item.EmpName, value: item.EmpId }; }); //call the filter here response($.ui.autocomplete.filter(array, request.term)); } }); }, minLength: 0, focus: function(event, ui) { $("#empName").val(ui.item.label); } });
{ "pile_set_name": "StackExchange" }
Q: jquery css with object container I've probleme with $pagContainer = $(sets.lists.container); // container: 'cart' $bg = $($pagContainer + " li").css("background", "#FFFFFF"); $bg1 = $($pagContainer + " li:nth-child(2n)").css("background", "#767676"); I don't know if I need to put "#" before the $pagContainer like: $pagContainer = $(sets.lists.container); // container: 'cart' $bg = $("#" + $pagContainer + " li").css("background", "#FFFFFF"); or something like that. who can be help me with this issue? Thanks, A: If sets.lists.container contains a reference to a DOM element, or a selector in the form #my_id, then $pagContainer will already be a jQuery object, and cannot be used as a selector. In this case, you can use .find: $pagContainer.find("li") $pagContainer.find("li:nth-child(2n)")
{ "pile_set_name": "StackExchange" }
Q: Why do upgrades to KDM/KDE not preserve changes to configuration files? The kdebase-workspace package on Arch Linux only preservers changes made to /usr/share/config/kdm/kdmrc when the package is updated. I need to edit /usr/share/config/kdm/Xsetup to get my monitors to rotate correctly, but the changes get lost every time kdebase-workspace gets updated. The Arch Wiki recommends copying /usr/share/config/kdm/Xsession to /usr/share/config/kdm/Xsession.custom. I could do this with /usr/share/config/kdm/Xsetup, but I thought files in /usr/share/ are supposed to be managed by the package manager. It seems like this might be a bug in the package (i.e., should it be saving all the configuration files) or should I be making a change in /usr/share/config/kdm/kdmrc to tell it to look some place else and if so where? A: Files under /usr are meant to be under the control of the package manager (except for files under /usr/local). Configuration files that the system administrator may modify live in /etc. This is part of the traditional unix directory structure and codified for Linux in the Filesystem Hierarchy Standard. The recommendation in the Arch Wiki to edit files under /usr is a bad idea; the fact that your changes are overwritten by an upgrade is expected. Arch Linux manages files in a somewhat nonstandard way. You can mark the file as not to be changed on upgrade (this is documented on the wiki) by declaring it in /etc/pacman.conf: NoUpgrade = usr/share/config/kdm/Xsetup You may want to replace /usr/share/config/kdm/Xsetup by a symbolic link to a file under /etc (e.g. /etc/kdm/Xsetup), to make it easier to keep track of the customizations that you've made.
{ "pile_set_name": "StackExchange" }
Q: Connected Graph Prove that if $P$ and $Q$ are two longest paths in a connected graph, then $P$ and $Q$ have atleast one vertex in common. If I assume to the contrary that there are no vertices in common how can I arrive at a contradiction? A: Suppose that $P$ and $Q$ are both longest paths (and thus have equal length $l$). Assume that they have no vertices in common. There are now two vertex-disjoint paths. Because the graph is connected, we know there is a path from a vertex $p\in P$ to a vertex $q\in Q$ with length at least $1$ that is disjoint with $P$ and $Q$, apart from $p$ and $q$. Now, $p$ and $q$ divide $P$ and $Q$ in two halves (if they are not one of the endpoints). Take the longer half of both $P$ and $Q$ and connect them to the endpoints $p$ and $q$ of the path between $p$ and $q$. Because the longer halves of both $P$ and $Q$ have as least length $\frac l2$ and the path between them has as least length $1$, the new path has length $$ l'\geq \frac l2+1+\frac l2>l $$ We have thus found a path with length strictly greater than $l$, and thus our assumption that $P$ and $Q$ are vertex-disjoint must have been wrong. We conclude that every pair of longest path shares at least one vertex.
{ "pile_set_name": "StackExchange" }
Q: Guava Interner misses some potential for performance improvement I'm interested in Java object internalization. It seems that its difficult to provide a performant implementation that avoids pitfalls, so I'm inclined to use libraries. One option is Interner from Google Guava. But it occured to me: doesn't that implementation miss some potential for performance improvement? (Guava misses something? Cannot be true. Most likely, I'm missing something here! Please enlight me.) One advantage of object internalization is that object equality can be realized by pointer comparison, i.e., a.equals(b) is equivalent to a == b, which is much faster than equaliy based on field comparison. But an object to be internalized cannot implement its boolean equals(Object b) function as return this == b: the Interner library requires you to creat an object, which is then compared to the interned objects by the object's "real" equals() method (i.e., by comparing the object's fields). Only after internalization, == can be used. A similar argument holds for hash(). Now, I do not want to replace all a.equals(b) by a == b in my code. (The functional equivalent would be Objects.requireNonNull(a) && a == b anyways.) And for hash(), there is no such "trick". Therefore, you pay the price for internalization but you do not get the full advantage of it. How could things be improved? Provide an interface Internalizable that defines two methods boolean realEquals(Object other) and int realHash(). When planning to internalize objects of a certain class, make that class implement Internalizable and rename equals() and hash() accordingly. The Interner, requiring its objects to implement that interface, would use a special implementation of WeakHashMap (or like) that uses these methods instead of equals() and hash(). A: Even the call of a virtual equals method (containing a == comparison) is less performant than comparing directly by ==. I suggest you replace the equals methods. Yet if there is a reason you cannot do this safely: Good equals methods (and those generated by IDEs) start with some short circuit returns, e.g. if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } MyObject other = (MyObject) obj; Such an equals methods should be nearly as performant as you expect.
{ "pile_set_name": "StackExchange" }
Q: implement parallel execute in scheme In SICP section 3.4 (serializers in scheme) on Currency there is a procedure called parallel-execute that is described but not implemented in MIT scheme. I wonder if anyone has actually implemented it; if not how would one get started in implementing such procedure? http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-23.html#%_sec_3.4.1 A: This is how I implemented parallel-execute for solving the exercises in section 3.4 of SICP, using Racket: (define (parallel-execute . procs) (map thread-wait (map (lambda (proc) (thread proc)) procs))) I can't guarantee that it has the same semantics as the parallel-execute procedure defined in the book, but it allowed me to solve the exercises. A: This book's official site offers a implement parallel.scm. Open MIT Scheme like this: mit-scheme -load PATH/parallel.scm or put this (load "PATH/parallel.scm") at the head of your scheme source file. A: Actually you can load all the necessary implementations in racket with the following package. Just type this in either the definitions or the interactions window and the necessary package will be installed and when you need it, include the same comment in the definitions window: (require (planet dyoo/sicp-concurrency:1:2/sicp-concurrency))
{ "pile_set_name": "StackExchange" }
Q: $n$-words over the alphabet $\{0,...,d\}$ without consecutive $0$'s I'm trying to solve the following problem in chapter 3 of Aigner's A Course in Enumeration: Let $f(n)$ be the number of $n$-words over the alphabet $\{0,1,2\}$ that contain no neighboring 0's. Determine $f(n)$. One is easily led to the recurrence $f(n)=2(f(n-1)+f(n-2))$ and the generating function $$F(x)=\frac{1+x}{1-2x-2x^2}.$$ At this point, I am trying to solve for $f(n)$. I used partial fractions to get $$f(n)=\frac{1+\sqrt{3}}{2\sqrt{3}}(\frac{-1+\sqrt{3}}{2})^n+\frac{-1+\sqrt{3}}{2\sqrt{3}}(\frac{-1-\sqrt{3}}{2})^n$$ for $n\geq 2$, but I cannot reconcile this with Brian M. Scotts answer here: Recurrence relation for the number of ternary strings containing 2 consecutive zeros vs not containing I also tried generalizing, by looking at the $n$-words over $\{0,...,m\}$ with no consecutive $0$'s. This leads one to the generating function $$F_m(x)=\frac{1+x}{1-mx-mx^2}.$$ Since my determination of $f(n)$ gives incorrect values, I made a mistake. After an hour of checking, I just cannot find it. Furthermore, Aigner gives the following answer $$f(n)=\sum_i(\binom{n+1}{2i+1}+\binom{n}{2i+1})3^i,$$ which cannot come from this fibonacci-like approach. Any ideas? A: Start with $${1+x\over 1-2x-2x^2}={\left({{1\over 2}+{1\over\sqrt{3}}}\right)\over 1-x(1+\sqrt{3}) }+{\left({{1\over 2}-{1\over\sqrt{3}}}\right)\over 1-x(1-\sqrt{3}) } $$ to get \begin{eqnarray*}p(n)&=&\left({{1\over 2}+{1\over\sqrt{3}}}\right)(1+\sqrt{3})^n+\left({{1\over 2}-{1\over\sqrt{3}}}\right)(1-\sqrt{3})^n\\[5pt]&=&{1\over 2}[(1+\sqrt{3})^n+(1-\sqrt{3})^n]+{1\over\sqrt{3}}[(1+\sqrt{3})^n-(1-\sqrt{3})^n]\\[5pt] &=&\sum_j {n\choose 2j}\,3^j+\sum_j 2{n\choose 2j+1}\,3^j. \end{eqnarray*} A: It looks to me that you, Aigner and Brian Scott are all saying the same thing. We have $f(n) = 2 f(n-1) + 2 f(n-2)$, together with $f(1)=3$ and $f(2)=8$, hence: $$ \sum_{n\geq 1}f(n)\,x^n = \frac{3x+2x^2}{1-2x-2x^2}$$ and by partial fraction decomposition: $$ f(n) = \left(11+\frac{14}{\sqrt{3}}\right)\left(\frac{-1+\sqrt{3}}{2}\right)^n + \left(11-\frac{14}{\sqrt{3}}\right)\left(\frac{-1-\sqrt{3}}{2}\right)^n. $$ In order to recover Aigner's representation as a weighted sum of binomial coefficients, it is enough to expand $(-1\pm\sqrt{3})^n$ by using the binomial theorem. A: Here is another variation of the theme. It's not the shortest one, but it could be helpful for similar cases and it provides a slightly different representation of the solution. Since we often have to cope with series of the form \begin{align*} G(x)=\frac{p+qx}{ax^2+bx+c} \end{align*} we derive a general representation by a series expansion at $x=0$. Based upon this result we obtain a solution for $F(x)$ and $F_m(x)$. Using partial fraction decomposition of $G(x)$ and denoting the zeros of $ax^2+bx+c$ with $x_0,x_1$ we obtain \begin{align*} G(x)&=\frac{p+qx}{ax^2+bx+c}\\ &=\frac{1}{a}\frac{p+qx_0}{x_0-x_1}\frac{1}{x-x_0}-\frac{1}{a}\frac{p+qx_1}{x_0-x_1}\frac{1}{x-x_1}\tag{1}\\ &=\frac{1}{ax_0}\frac{p+qx_0}{x_1-x_0}\frac{1}{1-\frac{x}{x_0}} -\frac{1}{ax_1}\frac{p+qx_1}{x_1-x_0}\frac{1}{1-\frac{x}{x_1}}\\ &=\frac{1}{ax_0}\frac{p+qx_0}{x_1-x_0}\sum_{k=0}^{\infty}\left(\frac{x}{x_0}\right)^k -\frac{1}{ax_1}\frac{p+qx_1}{x_1-x_0}\sum_{k=0}^{\infty}\left(\frac{x}{x_1}\right)^k\tag{2}\\ &=\frac{x_1}{c}\frac{p+qx_0}{x_1-x_0}\sum_{k=0}^{\infty}\left(\frac{a}{c}x_1\right)^kx^k -\frac{x_0}{c}\frac{p+qx_1}{x_1-x_0}\sum_{k=0}^{\infty}\left(\frac{a}{c}x_0\right)^kx^k\tag{3} \end{align*} Comment: In (1) we use partial fraction decomposition and $$ax^2+bx+c=a(x-x_0)(x-x_1)=a(x^2-(x_0+x_1)x+x_0x_1)$$ In (2) we represent the fractions as geometric series at $x=0$. In (3) we use the relationship $x_0x_1=\frac{c}{a}$ In the following we use the coefficient of operator $[x^n]$ to denote the coefficient of $x^n$ of the series in (3) \begin{align*} [x^n]G(x)&=\frac{p+qx_0}{x_1-x_0}a^n\left(\frac{x_1}{c}\right)^{n+1} -\frac{p+qx_1}{x_1-x_0}a^n\left(\frac{x_0}{c}\right)^{n+1}\\ &=\frac{a^n}{c^{n+1}}\frac{1}{x_1-x_0}\left[(p+qx_0)x_1^{n+1}-(p+qx_1)x_0^{n+1}\right] \end{align*} Now it's time to harvest. With \begin{align*} F(x)&=\frac{p+qx}{ax^2+bx+c}=\frac{1+x}{-2x^2-2x+1} \end{align*} we obtain \begin{align*} x_{0,1}&=\frac{1}{2a}\left(-b\pm\sqrt{b^2-4ac}\right)=-\frac{1}{2}(1\pm\sqrt{3})\\ x_1-x_0&=\sqrt{3}\\ p+qx_0&=\frac{1}{2}(1-\sqrt{3})\\ p+qx_1&=\frac{1}{2}(1+\sqrt{3}) \end{align*} and we derive the coefficient $[x^n]F(x)$ as \begin{align*} [x^n]F(x)&=(-2)^n\frac{1}{\sqrt{3}}\left[\frac{1}{2}(1-\sqrt{3})\left(-\frac{1}{2}\right)^{n+1}(1-\sqrt{3})^{n+1}\right.\\ &\qquad\qquad\qquad\left.-\frac{1}{2}(1+\sqrt{3})\left(-\frac{1}{2}\right)^{n+1}(1+\sqrt{3})^{n+1}\right]\\ &=\frac{1}{4\sqrt{3}}\left[(1+\sqrt{3})^{n+2}-(1-\sqrt{3})^{n+2}\right]\\ &=\frac{1}{4\sqrt{3}}\sum_{j}2\binom{n+2}{2j+1}\left(\sqrt{3}\right)^{2j+1}\\ &=\frac{1}{2}\sum_{j}\binom{n+2}{2j+1}3^j\tag{4} \end{align*} Note, that from (4) and OPs representation we obtain the identity \begin{align*} \frac{1}{2}\sum_{j}\binom{n+2}{2j+1}3^j=\sum_{j}\left[\binom{n+1}{2j+1}+\binom{n}{2j+1}\right]3^j \end{align*} $$ $$ Similarly we obtain from the generating function \begin{align*} F_m(x)=\frac{1+x}{-mx^2-mx+1} \end{align*} the coefficient $[x^n]$ of $F_m$: \begin{align*} [x^n]F_m(x)&=\frac{\left(\frac{m}{2}\right)^n}{4\sqrt{1+\frac{4}{m}}} \left[\left(1+\sqrt{1+\frac{4}{m}}\right)^{n+2}-\left(1-\sqrt{1+\frac{4}{m}}\right)^{n+2}\right]\\ &=\frac{1}{2}\left(\frac{m}{2}\right)^n\sum_{j}\binom{n+2}{2j+1}\left(1+\frac{4}{m}\right)^j \end{align*} Note: With the help of Wolfram Alpha we find \begin{align*} F(x)=\frac{1+x}{-2x^2-2x+1}=1+3x+8x^2+22x^3+60x^4+164x^5+\mathcal{O}(x^6) \end{align*} Regarding a comment, note the generating function of Jack D'Aurizio is \begin{align*} H(x)&=\frac{3x+2x^2}{-2x^2-2x+1}\\ &=F(x)-1\\ &=3x+8x^2+22x^3+60x^4+164x^5+\mathcal{O}(x^6) \end{align*}
{ "pile_set_name": "StackExchange" }
Q: Fixed Positioning breaking z-index I have a webpage that I need to modify, the background, which is currently absolute positioned with z-index to push it back, needs to stay put when scrolling, i need to change it to fixed, yet doing so seems to break z-index and push the content below it vertically. Any ideas? edit: OK I managed to get it to work in FF, but IE is still broken... A: Maybe look at the rules below for how elements are stacked. The Stacking order and stacking context rules below are from this link Stacking Order within a Stacking Context The order of elements: The stacking context’s root element (the <html> element is the only stacking context by default, but any element can be a root element for a stacking context, see rules below) You cannot put a child element behind a root stacking context element Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML) Non-positioned elements (ordered by appearance in the HTML) Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML) Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML) When a Stacking Context is Formed When an element is the root element of a document (the <html> element) When an element has a position value other than static and a z-index value other than auto When an element has an opacity value less than 1 Several newer CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged media, and possibly others. See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context As a general rule, it seems that if a CSS property requires rendering in an offscreen context, it must create a new stacking context.
{ "pile_set_name": "StackExchange" }
Q: Testing multiple features at once in Git-Flow We working on git-flow in our current project and adding multiple features concurrently. We got only one QA environment that can hold only one build at a time. If there are more than one features waiting to be tested and our QA members can test them in parallel we need (as answered here) to create an integration branch to upload to the QA environment and to be tested. However, we found some problems in that solution that this flow raise: We can't merge the integration feature into develop if not all of the features got sign-off in time or some of them needed to be fixed. OR: After successfully getting sign-off for one or more of the features we can "finish feature" the original features - but then the code in develop is probably differ from the integration because of difference in the merge. Every fix for issue raised by the QA require merges from the original feature branch to integration, so people often fix issue on the integration branch, making chaos if it is done in parallel and make the original feature outdated. It's hard to hold track on what features are in the integration and what got tested and most important, Which feature is causing a bug. Is there any better way to test multiple feature in parallel? Do you have tips to make the process better? A: The solution you mentioned is merged all the changes from feature branches together. If it suit for your situation you can use it. If you want to test the feature separately, you can use below ways: Create branches from your QA environment (develop branch), each of the branch is used to test different features. When one feature is finished, you can merge it in develop branch. If you want to record the process of test in develop branch, you can rebase these commits onto develop branch.
{ "pile_set_name": "StackExchange" }
Q: Are the Iron Islands independent now? In the Game of Thrones series finale, a council is held where the North asks for and receives its independence. Another question touched on the subject of why the Iron Islands didn't ask for independence as well, and the consensus there seems to be that Yara didn't have the political savvy or the clout to pull that off. However, could an alternative interpretation be that the question of the Iron Islands' independence was already settled, because Daenerys promised it to Yara in Season 6, Episode 9, and this promise was honoured? A: The Iron Islands aren't independent. Yara voted to put Bran as King of the Seven Kingdoms, thus recognizing that he would have authority over her and the Iron Islands, before Sansa declared the independence of the North. And, during the reunion of the Small Council later on the episode, Tyrion calls Bran 'King of the Six Kingdoms', indicating that, so far, only the North decided to secede.
{ "pile_set_name": "StackExchange" }
Q: python pandas, DF.groupby().agg(), column reference in agg() On a concrete problem, say I have a DataFrame DF word tag count 0 a S 30 1 the S 20 2 a T 60 3 an T 5 4 the T 10 I want to find, for every "word", the "tag" that has the most "count". So the return would be something like word tag count 1 the S 20 2 a T 60 3 an T 5 I don't care about the count column or if the order/Index is original or messed up. Returning a dictionary {'the' : 'S', ...} is just fine. I hope I can do DF.groupby(['word']).agg(lambda x: x['tag'][ x['count'].argmax() ] ) but it doesn't work. I can't access column information. More abstractly, what does the function in agg(function) see as its argument? btw, is .agg() the same as .aggregate() ? Many thanks. A: agg is the same as aggregate. It's callable is passed the columns (Series objects) of the DataFrame, one at a time. You could use idxmax to collect the index labels of the rows with the maximum count: idx = df.groupby('word')['count'].idxmax() print(idx) yields word a 2 an 3 the 1 Name: count and then use loc to select those rows in the word and tag columns: print(df.loc[idx, ['word', 'tag']]) yields word tag 2 a T 3 an T 1 the S Note that idxmax returns index labels. df.loc can be used to select rows by label. But if the index is not unique -- that is, if there are rows with duplicate index labels -- then df.loc will select all rows with the labels listed in idx. So be careful that df.index.is_unique is True if you use idxmax with df.loc Alternative, you could use apply. apply's callable is passed a sub-DataFrame which gives you access to all the columns: import pandas as pd df = pd.DataFrame({'word':'a the a an the'.split(), 'tag': list('SSTTT'), 'count': [30, 20, 60, 5, 10]}) print(df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()])) yields word a T an T the S Using idxmax and loc is typically faster than apply, especially for large DataFrames. Using IPython's %timeit: N = 10000 df = pd.DataFrame({'word':'a the a an the'.split()*N, 'tag': list('SSTTT')*N, 'count': [30, 20, 60, 5, 10]*N}) def using_apply(df): return (df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()])) def using_idxmax_loc(df): idx = df.groupby('word')['count'].idxmax() return df.loc[idx, ['word', 'tag']] In [22]: %timeit using_apply(df) 100 loops, best of 3: 7.68 ms per loop In [23]: %timeit using_idxmax_loc(df) 100 loops, best of 3: 5.43 ms per loop If you want a dictionary mapping words to tags, then you could use set_index and to_dict like this: In [36]: df2 = df.loc[idx, ['word', 'tag']].set_index('word') In [37]: df2 Out[37]: tag word a T an T the S In [38]: df2.to_dict()['tag'] Out[38]: {'a': 'T', 'an': 'T', 'the': 'S'} A: Here's a simple way to figure out what is being passed (the unutbu) solution then 'applies'! In [33]: def f(x): ....: print type(x) ....: print x ....: In [34]: df.groupby('word').apply(f) <class 'pandas.core.frame.DataFrame'> word tag count 0 a S 30 2 a T 60 <class 'pandas.core.frame.DataFrame'> word tag count 0 a S 30 2 a T 60 <class 'pandas.core.frame.DataFrame'> word tag count 3 an T 5 <class 'pandas.core.frame.DataFrame'> word tag count 1 the S 20 4 the T 10 your function just operates (in this case) on a sub-section of the frame with the grouped variable all having the same value (in this cas 'word'), if you are passing a function, then you have to deal with the aggregation of potentially non-string columns; standard functions, like 'sum' do this for you Automatically does NOT aggregate on the string columns In [41]: df.groupby('word').sum() Out[41]: count word a 90 an 5 the 30 You ARE aggregating on all columns In [42]: df.groupby('word').apply(lambda x: x.sum()) Out[42]: word tag count word a aa ST 90 an an T 5 the thethe ST 30 You can do pretty much anything within the function In [43]: df.groupby('word').apply(lambda x: x['count'].sum()) Out[43]: word a 90 an 5 the 30
{ "pile_set_name": "StackExchange" }
Q: How do I convert an environment variable to an object in JS? I'm trying to convert an environment variable into an object of values for configuration in JavaScript but I don't know the best way to achieve this. The idea would be to output SAMPLE_ENV_VAR=value as: { sample: { env: { var: value } } } What I have so far: const _ = require('lodash'); const process = require('process'); _.each(process.env, (value, key) => { key = key.toLowerCase().split('_'); // Convert to object here } A: Here's a more complete solution based on yours: const _ = require('lodash'); const result = {}; // We'll take the following as an example: // process.env = { HELLO_WORLD_HI: 5 } // We'll expect the following output: // result = { hello: { world: { hi: 5 } } } _.each(process.env, (value, key) => { // We'll separate each key every underscore. // In simple terms, this will turn: // "HELLLO_WORLD_HI" -> ['HELLO', 'WORLD', 'HI'] const keys = key.toLowerCase().split('_'); // We'll start on the top-level object let current = result; // We'll assign here the current "key" we're iterating on // It will have the values: // 'hello' (1st loop), 'world' (2nd), and 'hi' (last) let currentKey; // We'll iterate on every key. Moreover, we'll // remove every key (starting from the first one: 'HELLO') // and assign the removed key as our "currentKey". // currentKey = 'hello', keys = ['world', 'hi'] // currentKey = 'world', keys = ['hi'], and so on.. while ( (currentKey = keys.shift()) ) { // If we still have any keys to nest, if ( keys.length ) { // We'll assign that object property with an object value // result =// { HELLO: {} } current[currentKey] = {}; // And then move inside that object so // could nest for the next loop // 1st loop: { HELLO: { /*We're here*/ } } // 2nd loop: { HELLO: { WORLD: { /*We're here*/ } } } // 3rd loop: { HELLO: { WORLD: { HI : { /*We're here*/ } } } } current = current[currentKey]; } else { // Lastly, when we no longer have any key to nest // e.g., we're past the third loop in our example current[currentKey] = process.env[key] } } }); console.log(result); To simply put: We'll loop through every environment variable (from process.env) Split the key name with an underscore, and, again, loop each key (['HELLO', 'WORLD', 'HI']) Assign it to an object ({ hello: {} } -> { hello: { world: {} } } -> { hello: world: { hi: ? } } }) When we no longer have any keys left, assign it to the actual value ({ hello: { world: { hi: 5 } } })
{ "pile_set_name": "StackExchange" }
Q: Reading Multidimensional arrays I am building a cypher program which uses a matrix of numbers and letters. A message is encoded according to the row and column each letter of the message is found in the matrix. I am trying to find a nice way of iterating over the 2D matrix (6*6). for char in range (0, len(message), 1): for i in range(0, len(rows), 1): for y in range(0, len(cols), 1): if matrix[i][y] == message[char]: cyphermessage.append(i) cyphermessage.append(y) cyphermessage.append(" ") But this method uses a 3-tier for loop which makes it \$\mathcal{O}((N)*3)\$, plus the the cypher append messages are quite ugly. A: Don't search – find. Specifically, don't iterate through all matrix entries for each character. Instead, build a dictionary that maps the characters in the matrix to a pair of indices. Also, don't loop over indices (in message) unless you have to. Now we have: position_lookup = dict() for x in range(len(matrix)): for y in range(len(matrix[x])): position_lookup[matrix[x][y]] = (x, y) for char in message: if char in position_lookup: x, y = position_lookup[char] cyphermessage.extend([x, y, " "]) Technically, this behaves different from the code you wrote: consider what happens when one character occurs multiple times in the matrix – I only use the last occurrence, while you append all possibilities.
{ "pile_set_name": "StackExchange" }
Q: How to write a Makefile in Windows to compile a Latex document using a loop I need to write several documents that are fairly close to each other, i.e.same structure of header/footer, call a common set of forms. I wrote a Main.tex document with a set of \if\x 1 { my document content}\fi to control the content of each document. My variable "x" is also used as information in the header. Minimal example: \documentclass[a4paper,10pt, ,landscape]{article} \usepackage{fancyhdr} \usepackage{lastpage} %\newcommand\x{1} \rhead{My document \x} \lhead{Left header} \chead{version:1.0} \lfoot{\thepage\ ~of~\pageref{LastPage}} \cfoot{} \begin{document} \if\x 1 { \include{FrontPage} \include{FormA} \include{FormB} \include{FormC} }\fi \if\x 2 { \include{FrontPage} \include{FormA} \include{FormB} \include{FormB} }\fi \if\x 3 { \include{FrontPage} \include{FromA} \include{FromC} \include{FormC} }\fi \end{document} On Linux (Ubuntu), I wrote a makefile: SHELL = /bin/sh all: make tex make clean tex: for number in 1 2 3; do \ echo $$number ; \ pdflatex -no-pdf --jobname=Mydocument-No-$$number "\newcommand\x{$$number} \input{main.tex}" ; \ pdflatex --jobname=Mydocument-No-$$number "\newcommand\x{$$number} \input{main.tex}" ; \ done;\ help: echo "USAGE: make [all/tex/clean]" clean: rm -f *.aux *.dvi *.idx *.ilg *.ind *.log *.nav *.out *.snm *.xdv *.toc *~ Which call my main.tex file 3 times, sending the value of x to my latex document, and also renaming the output. At the end I get 3 pdf. I only have to write "make" in the Konsole of Kile to make it work. Unfortunately, I now have to transfer this process under Windows - Any idea on how to write the equivalent of my makefile in Windows ? I have TeXnicCenter and Texmaker installed. A: I solved this, by writing a makefile.bat for Windows as suggested by David Carlisle: FOR %%i IN (1,2,3) DO ( echo %%i pdflatex --jobname=Mydocument-No-%%i "\newcommand\x{%%i} \input{main.tex}" pdflatex --jobname=Mydocument-No-%%i "\newcommand\x{%%i} \input{main.tex}" ) DEL *.aux *.log *.backup I run it by double clicking on the file.
{ "pile_set_name": "StackExchange" }
Q: Were Alexander the Great and Hephaestion lovers? Were Alexander the Great and Hephaestion lovers? Since there are no historical shreds of evidence that Alexander regarded Hephaestion as someone more than a friend, are the modern claims only based on the fact that said he was only "defeated by Hephaestion's thighs"? Edit: I'd be glad to know the reason behind down-voting this question. A: The author of that particular claim appears to have been Diogenes the Cynic. This is the same man who was said to carry around a lantern in broad daylight, claiming to be (futilely) looking for an honest man to anyone who asked about it. He was also known to heckle Plato and other philosophers, as well as political leaders, and just generally seems to have delighted in antagonizing people. In modern terms, we'd say he was a troll. That doesn't mean what he said about Hephaestion was false. But it does mean he probably cared less about its veracity than about the reaction he'd get by saying it. This doesn't make him a particularly reliable source, so I wouldn't take anything he said as an actual historical event unless it was also related by some other independent source. I believe the only good independent (from Diogenes) source we have is Arrian who lived about 300 years later (rather a long time, really). The thing people key off here is an incident Arrian relates where the friends themselves compared their relationship to that of Achilles and Patroclus. Now the relationship between those two Homeric figures really could be a whole other answer. Homer himself just cast them as really close friends. However, the portrayal of their relationship in Greek sources over the centuries gradually started to become more sexual in nature. The result of this is that there's a big dispute among modern historians about what exactly Arrian (or Alexander's contemporaries who indirectly related it to him, or the two friends themselves...) meant to be implying about the men's relationship with this story. All of which is to say we really don't know. Or perhaps even worse, there are a lot of historians who will insist we do know, but they disagree strongly with each other. A: We do not know and cannot be sure. But it seems neither likely nor unlikely, but quite possible. It seems as if many would like to get an answer that either gives the most intimate biographical details about the bedroom behaviour of two concrete ancient persons that are dead for over 2300 years while information on both were quickly enshrouded in myths. Or an answer that simplifies things to "yeah, those Greeks did that, typical". But for the latter case we should observe that Athens had different customs than Sparta or Thebes or Macedon, and those could change according to fashion. And the analysis of former case is hampered precisely because the story of Alexander was much more prone to be distorted because of his fame. We cannot know for sure when looking at biographies of both party involved. But we can look at the circumstantial data of Greek/Macedon society. The sexual behaviour reported for Alexander's father Philipp may be more directly trustworthy than anything relayed to for Alexander. And Philipp was infamous in antiquity for having had a verocious appetite in all directions. The first thing to observe is that our concept of homosexuality is very different from how the Greeks classified sexual behaviour between for example erastes–eromenos. This ranged from something described as ritualised pederasty with clear age-limits (or, well, beard growing limits?) to genuine partnership as seen in the Sacred Band of Thebes with no such limits in age or directions of activity . The next important clue is the specifity with which Diogenes alludes to "thighs", as in such relationships the vase paintings we have primarily show us intercrural copulation. What he might have meant by that, exactly, is object of speculation, of course. But there are a few possibilities hinted at. We must remember the two of them had been friends at least nineteen years, if we accept Mieza as a terminus ante quem for their meeting. During much of this, they would have lived in close quarters on campaign and no doubt seen one another daily when not away on independent missions. Nineteen years is longer than many modern marriages. In terms of affectional attachment, Hephaistion-not any of Alexander's three wives-was the king's life partner. Whatever the truth of any sexual involvement, their emotional attachment has never been seriously questioned. No doubt as teenagers, both had learned from Aristotle some version of what he would later write in his Nikomachean Ethics-that perfect love was the highest friendship (1156b), and that friendship was a state of being, not a feeling (1157b). Moreover, Aristotle speaks of the friend as the 'second self (117ob) and indicates that there is only one special friend (1171a). Thus, given the evidence for same-age homoerotic affairs in Macedonia and the weight of circumstantial testimony – even if it violates Dover's model – I do think it quite possible that Alexander and Hephaistion were physically intimate at some point. I do not necessarily think, however, that they were still physically intimate in their latter years, though they may have been. Mostly, I don't think it greatly significant to the affection they held for one another. While they may indeed have been lovers, I think it reductive to characterize their relationship solely in this way. Nussbaum (1986: 354) contrasts Greek philia with modern concepts of friendship and says that philia 'includes the vel)' strongest affective relationships that human beings form... English 'love' seems more appropriately wide­ ranging.'60 Greek philia could include a sexual component but extended far beyond that.61 Similarly, and though speaking of Achilles and Patrokios, Van Nortwick (1995: 17­ 18) offers an observation it would do us well to keep in mind: We need to be careful not to misunderstand this intimacy.... Friendship in general is a difficult relationship to fix. seen in our modern cultures as existing on the boundaries of other bonds, familial or sexual, which provide the categories through which friendship itself is defined. The poems we will read here offer another model for friendship, one accommodating a greater degree of intimacy than is often accorded to nonsexual friendship these days. The first and second selves are intimate because they compose, together, a single entity... – at this level of intensity, sexual love is sometimes inadequate as a model because it may not be intimate enough. [Italics mine] Van Nortwick's observation is a shrewd one. Our model of friendship is not consonant with theirs. Within these ancient societies where homoerotic desire was freely, sometimes emphatically, expressed, intense friendship might well develop a sexual expression even while that expression was not the focus of the friendship, or even thought of as particularly characteristic of it. 'The ancient Greeks, perhaps because their societies were so highly militarized... simply assumed the centrality of philia' (Shay 1994: 41). It would be inappropriate to refer to the friend as lover (except in very specific circumstances), as such would fall far short of encompassing the whole relationship. Alexander's choice of 'philalexandros' for Hephaistion said more about the nature of his affection than calling him merely erastes or eromenos. Conclusion Was the relationship of Alexander and Hephaistion an atypical affair? I do not believe that it was. We have shown that Macedonian society allowed same-age partnerships and seems to have accepted them without comment. Among the Pages, it was not only possible, but perhaps even to be expected that young men would form friendships with one another that included a sexual aspect, but was not limited to it. What, then, might we gather from this detailed look at one example? Simply that models – even good ones based on careful analysis of the evidence – can put blinders on subsequent scholarship – if we are not careful. Without the cognitive dissonance created by the sheer bulk of circumstantial testimony in the case of Alexander and Hephaistion, it would be easy to overlook a relationship like theirs. Even with the circumstantial evidence, we still cannot be at all certain they were lovers. Because such relationships are not atypical for their societies, sly insinuations – such as those made about Agathon the Tragedian – are absent. It does cause one to wonder how many other such relationships may have existed between less famous philoi. While the Dover Model describes the most common-and least ambiguous-form for homoerotic expression in ancient Greece, it was not the only one. There were other options, particularly in military contexts. In short, a confusion of terms may make it difficult for us to pinpoint other such typical 'atypical' affairs, and we should take this into account when employing our models. All such models are to some degree artificial constructs; we should expect them, then, to be ultimately inadequate. Jeanne Reames: "An atypical affair? Alexander the Great, Hephaistion Amyntoros and the nature of their relationship", History Faculty Publications, 17,, The Ancient History BulletinVolume 13, Issue 3, 81–96, 1999. (PDF) A: As the author of the long quotation, let me address the issue of whether they remained lovers later. I say they may not, not because Alexander got married (he was almost 30 by the first marriage!), but because for two adult men to continue a sexual affair when both could grow a beard began to stray beyond the accepted patterns. While as I note, ancient Macedon was NOT ancient Athens, and shared much more in common with Doric states such as Thebes and Sparta, even there, young men in their 20s were expected to "phase out" of relationships with older (or similar-age) lovers, in favor of teen boys, and by about 30, to marry. Alexander generally seemed to follow that pattern, so while they may well have maintained a sexual relationship (assuming they had one in the first place, which I find if not certain, at least probable) into their early 20s, I think by their late 20s, they may each have turned to others, sexually, even if their primary emotional attachment remained to each other. I would also note that some scholars believe the entire Achilles-Patroklos pastiche to be Arrian's later attempt to flatter his patron Hadrian (who had Antinoos as a boyfriend), and it was not something Alexander and Hephaistion employed themselves. That Alexander compared himself to Achilles is fairly well-established in other historians (not least Plutarch), but it's really only in Arrian that we get Hephaistion as Patroklos. So the dismissal of Hephaistion as Patroklos is not without scholarly merit, but I tend to think Arrian simply exaggerated something Alexander used. I would also note that historians no longer elevate Arrian as the most trustworthy of our ancient sources. The so-called "vulgate" (Curtius, Plutarch, and Diodoros) must also be weighed. And EVERYone must remember these are sources two or three times removed from what they're writing about. Sources who wrote about Alexander and knew Alexander (such as Ptolemy, Marsyas, Aristobulos, and Kallisthenes) are now lost.
{ "pile_set_name": "StackExchange" }
Q: Is instance URL globally unique? I'm writing an application that works with salesforce. Is it safe to consider an instance URL globally unique per instance/organization? (Example: https://na136.salesforce.com/) For example each user should connect their salesforce instance to my application and to differentiate users I need something unique to identify them, this would be instance URL? A: No. The generic instance URLs are shared across many organizations. This cluster is known as a "pod." If you want a unique identifier for a given user, use the Identity URL you get when you log in via OAuth (it looks like /id/00Dxxx/005xxx). This is a globally unique identifier for a given user that will never change, even if they change their username or password. If the user exists in different orgs (e.g. with Sandboxes), the 00D part will still be unique for that user, so you can tell different instances apart.
{ "pile_set_name": "StackExchange" }
Q: setting a minimum allowed size for the panels of SplitterContainer Greeting, in C# WinForms: I have a splitterContainer. and lets sat there is Docked to Fill TableLayout in SplitterContainer.Panel1 now when I move the Splitter bar, it can cover the area of each of its panels. so it can even hide one of its panels when we move the splitter bar. But I do not want it! I want to have a limit for that. the minimum size I want to always be available for the panels of the SplitteRContainer is the size that is necessary for the contents that are already inside each panel of it. I do not want to be able to hide one panel and its contents by moving the splitter bar, so when it gets to that point I want it to stop moving and resizing the panels. Can you please help me on how to make this happen? A: Set the Panel1MinSize property.
{ "pile_set_name": "StackExchange" }
Q: JasperReportBuilder HTML row height I am building a report with JasperReportBuilder from a JDBC data source and afterward I export it to HTML by calling the toHtml method with a JasperHtmlExporterBuilder object parameter. I have been trying to get rid of extra space that exists above the text in each of my rows, column header row, and even my title. I have tried everything I can think of and have been searching online to no avail. It seems most people have the opposite problem: they need to grow their rows to fit their text. I would like to force my rows to be the height of their contents. If that's not possible, I would be happy with restricting the height of my rows. The HTML exporter appears to be controlling the height of my rows by inserting an image and setting its height. Any help would be appreciated. Thanks! Edit: Here is my code. String imageServletUrl = "images?image="; StringWriter writer = new StringWriter(); JasperHtmlExporterBuilder htmlExporter = Exporters.htmlExporter(writer); htmlExporter.setImagesURI(imageServletUrl); SqlRowSet rowSet = getData(databaseIpAddr, portNumber, databaseName, databaseUser, databasePassword); JRDataSource ds = createDataSource(rowSet); JasperReportBuilder builder = DynamicReports.report(); IntegerType intType = DynamicReports.type.integerType(); DateType dateType = DynamicReports.type.dateType(); int rowHeightPx = 20; TextColumnBuilder<Integer> col1 = col .column(COL_TITLE_RESULT_NUM, RESULTS_COL_TITLE_RESULT_NUM, intType) .setWidth(35) .setFixedHeight(rowHeightPx) .setStretchWithOverflow(true); ... create other eight columns ... StyleBuilder titleStyle = stl.style() .bold() .setFontSize(22) .setHorizontalAlignment(HorizontalAlignment.CENTER); StyleBuilder columnTitleStyle = stl.style() .bold() .setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE) .setBorder(stl.pen1Point()); StyleBuilder columnStyle = stl.style() .setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE) .setLineSpacing(LineSpacing.SINGLE) .setBorder(stl.pen1Point()); TextFieldBuilder<String> titleBuilder = DynamicReports.cmp .text(selectedAgency) .setStyle(titleStyle) .setFixedHeight(20); TextFieldBuilder<String> subtitleBuilder = DynamicReports.cmp .text("Start Time: " + startDate + " " + getStartTime() + ", End Time: " + endDate + " " + getEndTime()) .setFixedHeight(20); TextFieldBuilder<String> noDataMsgBuilder = DynamicReports.cmp .text(NO_DATA_MSG) .setStyle(columnStyle); builder .title(titleBuilder) .addPageHeader(subtitleBuilder) .setColumnTitleStyle(columnTitleStyle) .columns(col1, col2, col3, col4, col5, col6, col7, col8, col9) .setColumnStyle(columnStyle) .highlightDetailOddRows() .noData(titleBuilder, subtitleBuilder, noDataMsgBuilder) .setWhenNoDataType(WhenNoDataType.NO_DATA_SECTION); String reportHtml; try { // this seems to be required to get to the DynamicReports images getContext().getRequest().getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, builder.toJasperPrint()); builder.toHtml(htmlExporter); reportHtml = writer.toString(); } catch (DRException e) { e.printStackTrace(); reportHtml = "There was an error generating the report"; } A: Edit: Below solution works fine only with DynamicJasper library rather than DynamicReports. There must be similar operations in DR API as well i believe (not sure though - my exposure with DR is only very limitted :(). A combination of DynamicReportBuilder::setHeaderHeight(..), setDetailHeight(..) and JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN parameter setting must do it? // build dynamicreport instance DynamicReportBuilder dynamicReportBuilder = new DynamicReportBuilder(); dynamicReportBuilder.setHeaderHeight(50); //sets the column header height dynamicReportBuilder.setDetailHeight(50); //sets the detail band rows height DynamicReport dynamicReport = dynamicReportBuilder.build(); // build jasperprint.. JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint( dynamicReport, new ClassicLayoutManager(), dataSource, new HashMap<String, Object>()); // export as html JRExporter exporter = new JRHtmlExporter(); // tell jasper not to use images for aligning exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, targetFile); exporter.exportReport();
{ "pile_set_name": "StackExchange" }
Q: php mail bcc multiple recipients How do I make a bcc mail? If I send that mail, It shows me all the recipients! $to=array(); $members_query = mysql_query("select email from members"); while( $row = mysql_fetch_array($members_query) ) { array_push($to, $row['email']); } // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n"; // Additional headers //$headers .= 'To: '.$newName.' <'.$newEmail.'>' . "\r\n"; $headers .= 'From: SmsGratisan.com <[email protected]' . "\r\n"; mail(implode(',', $to), $title, $content, $headers); Thanks! A: Set your mail to field to null, and then implode your $to array in your headers $headers .= 'From: SmsGratisan.com <[email protected]' . "\r\n"; $headers .= 'BCC: '. implode(",", $to) . "\r\n"; mail(null, $title, $content, $headers);
{ "pile_set_name": "StackExchange" }
Q: Android BOOT_COMPLETED I have a question concerning the BOOT_COMPLETED event. I need a service to be running at all time (done via AlarmManager) but I wonder if I have to start the service manually the first time the application is installed as the BOOT_COMPLETED event is sent only after the device is restarted. How is this commonly handled, it seems like no one is having this problem, am I getting something wrong here? A: the user should be the one deciding on if the service is running or not when its first installed and not you, so yes it should be started manually when they launch the app for the first time
{ "pile_set_name": "StackExchange" }
Q: How to process specific rows in a two dimensional array public class OutputRowsandColumns { public static void main(String[] args) { int cols = 10; int rows = 10; int[][] myArray = new int[cols][rows]; // Two nested loops allow us to visit every spot in a 2D array. // For every column I, visit every row J. for (int i = 0; i < cols; i++) for (int j = 0; j < rows; j++) myArray[i][j] = 0; } } Here is the code I have so far, My question is; How do I process specific even and odd rows to set all even rows to 0 and all odd rows to 1. A: All the solutions suggest you to use the modulus operator. This can be useful for certain cases, but knowing the fact that the default value for an int is 0, you can avoid unnecessary computations here. All you have to do is to modify the parameters of your for loop to only take in account the odd rows. int[][] myArray = new int[rows][cols]; for (int i = 1; i < rows; i+=2) for (int j = 0; j < cols; j++) myArray[i][j] = 1; Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
{ "pile_set_name": "StackExchange" }
Q: Best compression tool for full disk imaging that can saturate a USB 3 connection on low-powered machines? I often work on full disk images, I often need to read and write full disk images on not so capable laptops using a USB-3 disk as my temporary medium. Duplicating a raw image is probably the fastest way, but I have to deal with limited storage space available. What I need is high throughput and low CPU usage - compression ratio is not that important for me. I'd like to have a tool that can very lightly compress the images created - mostly encoding empty space on the disk so that I can only store useful data, while making it as fast as possible - hopefully almost as fast as a raw dd duplication. I tied to use pxz -1, as it can use multiple CPU cores to speed up the compression, hoping for the fastest compression to still be useful. That doesn't however seem to be as fat as I'd like. Compressing a 500 GB disk image was estimated to take 21 hours: mint Backup # dd if=/dev/sda bs=100M | pv -ptera -s500G | pxz -1 > Lenovo-Win8-sda.dd.xz 0:09:21 [9.26MiB/s] [6.54MiB/s] [> ] 0% ETA 21:34:46 No compression at all predicted 3 hours to complete the imaging: mint Backup # dd if=/dev/sda bs=100M | pv -ptera -s500G > Lenovo-Win8-sda.dd 0:00:20 [80.2MiB/s] [49.8MiB/s] [> ] 0% ETA 2:50:20 Using lbzip2 -1 for compresson seems to be slightly faster than pxz -1 with ETA at 15 hours, which is still very slow. mint Backup # dd if=/dev/sda bs=100M | pv -ptera -s500G | lbzip2 -1 > Lenovo-Win8-sda.dd.bz2 0:00:22 [9.07MiB/s] [9.76MiB/s] [> ] 0% ETA 14:33:38 Are there any faster compression tools for Linux? A: LZ4 apt install liblz4-tool Then you can compress with lz4 command and decompress with lz4 -d. It defaults to the fastest compression mode. 500 GB from internal hard drive to an external drive over USB 3.0 is estimated to take between 2 and 3 hours: mint Backup # dd if=/dev/sda bs=100M | pv -ptera -s500G | lz4 > Lenovo-Win8-sda.dd.lz4 0:02:47 [97.5MiB/s] [58.1MiB/s] [> ] 1% ETA 2:24:11 A: So, this won't be the absolute fastest (It's slower than LZ4, LZOP, and Snappy), but might be fast enough for your usage and will get way better ratios than LZ4 (and transferring less data will save you time too). ZStandard Official website: https://facebook.github.io/zstd/ The Debian package is called zstd Unlike LZ4, it's multi-threaded (for both compression and decompression), and with the lowest compression settings it can easily saturate a USB 3.0 link (which your test with LZ4 is probably already doing), while getting compression ratios on par with the default settings in Gzip. A: This sounds like an XY Problem.  A generic compression tool isn’t particularly likely to do a good job on a disk image, because unused space is not guaranteed to be empty.  (Admittedly, there are ways to zero out unused space in a filesystem.) You might be better off using a backup tool — such as rsync, Clonezilla, Time Machine, Duplicity, dump, or even tar, to name a few — that understands the filesystem format and backs up only the portions that are used.  See this question for a discussion of some of them.  Such an approach would have the advantage that it becomes much easier to restore the backup to a disk of a different size.
{ "pile_set_name": "StackExchange" }
Q: Why do I keep getting ArrayIndexOutOfBoundsException? I know that the ArrayIndexOutOfBoundsException means that you're trying to access something not defined in the array, and tried to look up solutions. All the solutions say that you need to use < rather than =<, but that's about it. I don't understand why my loop below keeps giving me ArrayIndexOutOfBoundsException erros. for (int i=0; i < myMessage.length(); ){ eInteger = eNumbers[i]; myInteger = numbers[i]; System.out.println(eInteger + " " + myInteger); character = myInteger - eInteger; stringCharacter = Integer.toString(character); //decryptedMessage = decryptedMessage + " " + stringCharacter; System.out.println(character); i++; } I've tried int i=0, int i = 1, myMessage.length() - 1. It shouldn't be attempting to give me something further than the array, but I don't know. Full code: public class Decrypt { private String myMessage; private String e = "2718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035402123407849819334321068170121005627880235193033224745015853904730419957777093503660416997329725088687696640355570716226844716256079882651787134195124665201030592123667719432527867539855894489697096409754591856956380236370162112047742722836489613422516445078182442352948636372141740238893441247963574370263755294448337"; private String stringCharacter; private int character; private int myInteger; private int eInteger; private String decryptedMessage = ""; public Decrypt(String myMessage){ this.myMessage = myMessage; } public String Decryption(){ String[] splitMessage = myMessage.split(" "); int[] numbers = Arrays.stream(splitMessage) .mapToInt(Integer::parseInt).toArray(); String[] eMessage = e.split(""); int[] eNumbers = Arrays.stream(eMessage) .mapToInt(Integer::parseInt).toArray(); for (int i=0; i < myMessage.length(); ){ eInteger = eNumbers[i]; myInteger = numbers[i]; System.out.println(eInteger + " " + myInteger); character = myInteger - eInteger; stringCharacter = Integer.toString(character); //decryptedMessage = decryptedMessage + " " + stringCharacter; System.out.println(character); i++; } return stringCharacter; } public String toString(){ return "Message: " + Decryption(); } } When I run my program (the extra code is in a driver) I get the following: Welcome to this cryptographic program! Would you like to encrypt or decrypt a message? Please enter 1 to encrypt, and 2 to decrypt. 2 Thank you! Please type the message you would like to encrypt or decrypt. 22 12 20 28 2 22 Exception in thread "main" 20 7 12 5 1 20 19 8 28 20 java.lang.ArrayIndexOutOfBoundsException: 4 at Program4.Decrypt.Decryption(Decrypt.java:30) at Program4.Decrypt.toString(Decrypt.java:42) at java.lang.String.valueOf(Unknown Source) at java.io.PrintStream.println(Unknown Source) at Program4.Driver.main(Driver.java:28) A: The problem is that myMessage.length() is the number of characters in myMessage, whereas numbers.size is the number of integers represented in myMessage. In your example run, myMessage is "22 12 20 28", which has 11 characters so you are iterating from 0 to 10; but numbers is an array of just four numbers (0 through 3), so numbers[i] will raise this exception for any i greater than 3. If I'm understanding correctly what you are trying to do, you just need to change this: for (int i=0; i < myMessage.length(); ){ to this: for (int i=0; i < numbers.size; ){
{ "pile_set_name": "StackExchange" }
Q: PHP loop new tr after every 3 loops I have a table with a PHP loop. I want it to create a new row after every 3 loops. I've got the following code. However, seems to not be working correctly. The first new row gets created after the 4th loop and every loop after that works fine. And also it seems to create a blank at the end. Any ideas how I can get this to work? <table cellpadding="20"> <tr> <?php $counter=0; foreach ($links as $key){ echo '<td align="center">'.$links[$key].'</td>'; echo "\n"; if ($counter % 3 == 0 && $counter !== 0) { echo '</tr><tr>'; } $counter++; } ?> </tr> </table> A: Move $counter++; before if or set $counter=1; before for
{ "pile_set_name": "StackExchange" }
Q: What is the probability that the digit $0$ will appear at least once and the digit $2$ will appear at least once? Choosing a 6 digit random number, what is the probability that the digit $0$ will appear at least once and the digit $2$ will appear at least once? Using complement, we have the digits two or zero won't appear at all: Zero will not appear at all: $9^6$ Two will not appear at all: $8\cdot9^5$ Finally, the general case minus the sum of the above two yields a negative number: $9\cdot10^5-(9^6+8\cdot9^5)=-103833$ But I don't see where's my error... A: You are counting numbers where zero and two don't appear twice when summing $9^6$ and $8\cdot 9^5$. To fix this, count the numbers without both, those are $8^6$. Hence, inclusion-exclusion yields $$ 9\cdot 10^5 - (9^6 + 8\cdot 9^5) + 8^6 = 158311. $$ The main idea here is that for two sets $A$ and $B$ we have $\left|A\cup B\right| = \left|A\right|+\left|B\right|-\left|A\cap B\right|$. Here $A$ consists of numbers with no $0$-digit and $B$ consists of numbers with no $2$-digit.
{ "pile_set_name": "StackExchange" }
Q: Using JPA without Cascade Persist I have two Classes Error and MainError (* - * association with MainError is the owner of the association) I want to persist the data in my database and I cannot use Persist Cascade because I have many duplicate objects and I want to recognize the duplicate objects and associate them with the persisted ones (The name of Error and MainError is unique) Error error1 = new Error ("ERR1"); Error error2 = new Error ("ERR2"); Error error3 = new Error ("ERR3"); Error error4 = new Error ("ERR4"); Error error5 = new Error ("ERR5"); Error error6 = new Error ("ERR1"); MainError mainError1 = new MainError("MAIN1"); MainError mainError2 = new MainError("MAIN2"); MainError mainError3 = new MainError("MAIN2"); mainError1.addError(error1); mainError1.addError(error2); mainError1.addError(error3); mainError1.addError(error6); mainError2.addError(error1); mainError2.addError(error4); mainError3.addError(error5); //persisting Error and MainError for example if I already persisted Error error1 = new Error ("ERR1") in my database and then I want to persist Error error6 = new Error ("ERR1"); I want that my application recognize that this is already persisted and associate "ERR1" to the corresponding MainError. I guess I will need to create a method findByName to know if the name of Error/MainError is already persisted and if so, returning this object, working with it and merge it ? I hope that my question is not confusing Thank you very much A: As you mentioned in your question, you can manually check for data exist in DB or not? For that you can also set that column as a uniq constraint. Alternative solution : In your case, the database design should be something like this : error : id varchar (PK) mainerror : id varchar (PK) error_id varchar (FK) and the entity classes should be something like this : Error.java @Entity public class Error { @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) @Column(nullable = false, length = 2147483647) private String id; @OneToMany(mappedBy = "errorId", fetch = FetchType.LAZY) private Collection<MainError> mainErrorCollection; public Error() { } public Error(String id) { this.id = id; } //getter and setter methods } MainError.java @Entity @Table(name = "main_error") public class MainError { @Id @Basic(optional = false) @NotNull @Size(min = 1, max = 2147483647) @Column(nullable = false, length = 2147483647) private String id; @JoinColumn(name = "error_id", referencedColumnName = "id") @ManyToOne(fetch = FetchType.LAZY) private Error errorId; public MainError() { } public MainError(String id) { this.id = id; } //getter and setter methods } You should prevent adding duplicate record by making joint PK of id and error_id for main_error table.
{ "pile_set_name": "StackExchange" }
Q: NN for fuzzy classification What loss-function / optimizer to use for fuzzy classification problems? E.g: Four categories hot, mild, cold, freezing. Edit: I use one-hot encoding and have ~ 60 datapoints. A: Adding to J.C. answer, please note that you don't have to stick with one-hot encoding. For your hot-mild-cold-freezing a target could also be 0,0.3,0.5,0.2.
{ "pile_set_name": "StackExchange" }
Q: Doc conversion using OpenOffice SDK I have a need to be able to allow users to export their .doc files (which they upload) to a variety of formats. I got started on using OO SDK, and I set-up some custom filters using XSLT also. Everything works good and I am able to export word docs to pdf etc. However I want to run this as a web service. I wish to run this conversion service on a dedicated node, so all file uploads by users wanting to convert their document will reach this dedicated node. My web app itself is PHP based. What is the best way to perform the conversion using OO SDK? I will have to store the resultant file in DB as well. Do I need to run multiple instances of OO and feed each file to be converted to a specific instance? And, do I need to write a custom server to handle this, as I don't know if OO is multithreaded. Any advice greatly appreciated. A: Using the cli dlls try with the following code public conversion() { unoidl.com.sun.star.uno.XComponentContext localContext =uno.util.Bootstrap.bootstrap(); unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory =(unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager(); XComponentLoader componentLoader =(XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop"); XComponent xComponent = componentLoader.loadComponentFromURL(PathConverter(FileName1),"_blank", 0,new PropertyValue[] {MakePropertyValue("Hidden", true)}); unoidl.com.sun.star.beans.PropertyValue [] propertyValues; propertyValues = new unoidl.com.sun.star.beans.PropertyValue[2]; // Setting the flag for overwriting propertyValues[0] = new unoidl.com.sun.star.beans.PropertyValue(); propertyValues[0].Name = "Overwrite"; propertyValues[0].Value = new Any(true); // Setting the filter name propertyValues[1] = MakePropertyValue("FilterName", "HTML (StarWriter)"); /*propertyValues[1] = new unoidl.com.sun.star.beans.PropertyValue(); propertyValues[1].Name = "FilterName"; propertyValues[1].Value = new uno.Any("HTML (StarWriter)"); // writer_pdf_Export , swriter: MS Word 97 , HTML (StarWriter) ,*/ XStorable xStorable = xComponent as XStorable;xStorable.storeToURL(PathConverter(FileName),propertyValues); } For a complete list of filternames to exports look into another answer I gave before. A: Have you looked into using JODConverter? It does all the heavy lifting for you.
{ "pile_set_name": "StackExchange" }
Q: Responsive max-width for div containers I've a few tags and would like to get them responsive (maximum browser width) in case of two divs are not placed in one row. <div> <div class="card" style="cursor:pointer;"> <img class="card-img-top" src="" width=100 alt="logo" /> <div class="card-block"> <h4 class="card-title">Test1</h4> <p class="card-text"> Status: <span class="label label-success">Active</span> </p> <p class="card-text">Created: 2017-05-12</p> <a href="javascript:void(0);" class="btn btn-primary">Edit</a> </div> </div> <div class="card" style="cursor:pointer;"> <img class="card-img-top" src="" width=100 alt="logo" /> <div class="card-block"> <h4 class="card-title">Test sdf ;ljkgwe;o k5l4j ;l2k54k j9rjg </h4> <p class="card-text"> Status: <span class="label label-success">Active</span> </p> <p class="card-text">Created: 2017-05-12</p> <a href="javascript:void(0);" class="btn btn-primary">Edit</a> </div> </div> <div class="card" style="cursor:pointer;"> <img class="card-img-top" src="" width=100 alt="logo" /> <div class="card-block"> <h4 class="card-title">Test deg sdkjf glkjsdhg lkjdshfglk jhdsfkg dfg </h4> <p class="card-text"> Status: <span class="label label-success">Active</span> </p> <p class="card-text">Created: 2017-05-13</p> <a href="javascript:void(0);" class="btn btn-primary">Edit</a> </div> </div> </div> http://jsfiddle.net/m1L6pfwm/182/ So all is OK in my JSFiddle example except https://gyazo.com/f5ae57b4969fd55a43e276eaf9429be7 - in this case div's width should be 100%. In other words I won't see huge white gaps in the right of each div. Is it possible? Please advice. A: You can use flex like this: [edit]Add this to the end of the CSS: @media (max-width: 700px) { .card { flex: 0 0 1; float:none;} .card-block {float:left;} } http://jsfiddle.net/m1L6pfwm/184/ To fill the height try: @media (max-width: 700px) { .card { flex: 0 0 1; float:none; flex-direction: column;} .card-block {float:left;} } http://jsfiddle.net/m1L6pfwm/185/ (sorry it looks like it's also stretching the content and not the surrounding div) More on stretching vertically here
{ "pile_set_name": "StackExchange" }
Q: Installer for ASP.NET project I have an ASP.NET project in VS2012. I'd like to publish an "offline" version of this site. I'd like the installer, to: Enable (or install) the IIS on Windows (if necessary) Install the MS SQLExpress (if necessary) Install the .NET (if necessary) Install the project's files, and start the site on localhost. Can you help me, how to start? A: MSI packages (digitally signed) are the standard way of deploying Windows applications. You can use a tool like Advanced Installer, such tools offer predefined support to install Windows Features, prerequisites (SQLExpress or .NET Framework), install IIS web apps and of course copy your files and create the corresponding folders structure. This application has a free edition, but for what you need you have to purchase a Pro license. It also has a full 30 days trial. (disclaimer: I work on it)
{ "pile_set_name": "StackExchange" }
Q: How to import a text file as a dictionary python I have a text file of the looks like this: 0 1 0 2 0 3 2 3 3 4 4 1 .. .. I'd like to make it a dictionary looking like this graph = { "0" : ["1", "2", "3"], "1" : ["4", "0"], "2" : ["0", "1", "3"], "3" : ["0", "2", "4"], "4" : ["1", "3"] } the file text list is a list of edges for a graph. I need to make a graph out of it without using any package. My final aim is to calculate the diameter and clustering coefficient. However, before starting I need to create the graph. My attempt so far was: d = {} with open("/Volumes/City_University/data_mining/Ecoli.txt") as f: for line in f: (key, val) = line.split() d[int(key)] = val for x in d: print (x) Outcome: 471 472 474 475 476 477 478 479 480 481 483 484 485 486 487 Thanks A: As one other possible option, you can also use defaultdict here: from collections import defaultdict d = defaultdict(list) with open("/Volumes/City_University/data_mining/Ecoli.txt") as f: for line in f: key, val = line.split() d[key].append(val) for k, v in d.items(): print(k, v) This saves you from having to check whether a key is already in d or not, and it also saves you a couple of lines.
{ "pile_set_name": "StackExchange" }
Q: How do you implement __str__ for a function? Given a function foo: def foo(x): pass Printing its representation by invoking str or repr gives you something boring like this: str(foo) '<function foo at 0x119e0c8c8>' I'd like to know if it is possible to override a function's __str__ method to print something else. Essentially, I'd like to do: str(foo) "I'm foo!' Now, I understand that the description of a function should come from __doc__ which is the function's docstring. However, this is merely an experiment. In attempting to figure out a solution to this problem, I came across implementing __str__ for classes: How to define a __str__ method for a class? This approach involved defining a metaclass with an __str__ method, and then attempting to assign the __metaclass__ hook in the actual class. I wondered whether the same could be done to the class function, so here's what I tried - In [355]: foo.__class__ Out[355]: function In [356]: class fancyfunction(type): ...: def __str__(self): ...: return self.__name__ ...: In [357]: foo.__class__.__metaclass__ = fancyfunction --------------------------------------------------------------------------- TypeError Traceback (most recent call last) I figured it wouldn't work, but it was worth a shot! So, what's the best way to implement __str__ for a function? A: A function in Python is just a callable object. Using def to define function is one way to create such an object. But there is actually nothing stopping you from creating a callable type and creating an instance of it to get a function. So the following two things are basically equal: def foo (): print('hello world') class FooFunction: def __call__ (self): print('hello world') foo = FooFunction() Except that the last one obviously allows us to set the function type’s special methods, like __str__ and __repr__. class FooFunction: def __call__ (self): print('hello world') def __str__ (self): return 'Foo function' foo = FooFunction() print(foo) # Foo function But creating a type just for this becomes a bit tedious and it also makes it more difficult to understand what the function does: After all, the def syntax allows us to just define the function body. So we want to keep it that way! Luckily, Python has this great feature called decorators which we can use here. We can create a function decorator that will wrap any function inside a custom type which calls a custom function for the __str__. That could look like this: def with_str (str_func): def wrapper (f): class FuncType: def __call__ (self, *args, **kwargs): # call the original function return f(*args, **kwargs) def __str__ (self): # call the custom __str__ function return str_func() # decorate with functool.wraps to make the resulting function appear like f return functools.wraps(f)(FuncType()) return wrapper We can then use that to add a __str__ function to any function by simply decorating it. That would look like this: def foo_str (): return 'This is the __str__ for the foo function' @with_str(foo_str) def foo (): print('hello world') >>> str(foo) 'This is the __str__ for the foo function' >>> foo() hello world Obviously, doing this has some limitations and drawbacks since you cannot exactly reproduce what def would do for a new function inside that decorator. For example, using the inspect module to look at the arguments will not work properly: For the callable type, it will include the self argument and when using the generic decorator, it will only be able to report the details of wrapper. However, there might be some solutions, for example discussed in this question, that will allow you to restore some of the functionality. But that usually means you are investing a lot of effort just to get a __str__ work on a function object which will probably very rarely be used. So you should think about whether you actually need a __str__ implementation for your functions, and what kind of operations you will do on those functions then. A: If you find yourself wrapping functions, it's useful to look at functools.partial. It's primarily for binding arguments of course, but that's optional. It's also a class that wraps functions, removing the boilerplate of doing so from scratch. from functools import partial class foo(partial): def __str__(self): return "I'm foo!" @foo def foo(): pass assert foo() is None assert str(foo) == "I'm foo!"
{ "pile_set_name": "StackExchange" }
Q: Realm writes make NSColorPanel lag In my Catalyst app, I'm spawning an NSColorPanel with a callback using code from the Mac Helpers repository. @interface IPDFMacColorPanel : NSObject + (void)showColorPanelWithColorChangeHandler:(void(^)(UIColor *color))colorChangeHandler; /// Hides the color picker panel and removes the colorChangeHandler observer + (void)hide; + (void)removeColorChangeHandlerObserver; @end @interface NSColorPanel_Catalyst : NSObject + (instancetype)sharedColorPanel; - (void)makeKeyAndOrderFront:(id)sender; - (void)orderFront:(id)sender; - (void)orderOut:(id)sender; - (void)setTarget:(id)target; - (void)setAction:(SEL)action; - (UIColor *)color; @end @interface IPDFMacColorPanel () @property (nonatomic,copy) void(^colorChangeHandler)(UIColor *color); @end @implementation IPDFMacColorPanel + (instancetype)sharedPanel { static IPDFMacColorPanel *panel = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ panel = [IPDFMacColorPanel new]; }); return panel; } + (NSColorPanel_Catalyst *)colorPanel { return [NSClassFromString(@"NSColorPanel") performSelector:@selector(sharedColorPanel)]; } + (void)showColorPanelWithColorChangeHandler:(void(^)(UIColor *color))colorChangeHandler { IPDFMacColorPanel *observer = [IPDFMacColorPanel sharedPanel]; observer.colorChangeHandler = colorChangeHandler; NSColorPanel_Catalyst *colorPanel = [self colorPanel]; [colorPanel setTarget:observer]; [colorPanel setAction:@selector(colorChange:)]; [colorPanel orderFront:nil]; } + (void)hide { [[self colorPanel] orderOut:nil]; [self removeColorChangeHandlerObserver]; } + (void)removeColorChangeHandlerObserver { [IPDFMacColorPanel sharedPanel].colorChangeHandler = nil; } - (void)colorChange:(NSColorPanel_Catalyst *)colorPanel { if (self.colorChangeHandler) self.colorChangeHandler(colorPanel.color); } @end I spawn it like this: IPDFMacColorPanel.show { (color) in if let color = color { self.saveColor(color) } } And then write it to Realm: public func saveColor(_ color: UIColor) { try! realm.write { let converted = ColorUtility.convert(color: color) if let green = converted["green"] { self.restaurant.green = green } if let red = converted["red"] { self.restaurant.red = red } if let blue = converted["blue"] { self.restaurant.blue = blue } if let alpha = converted["alpha"] { self.restaurant.alpha = alpha } } } However, what happens is, because I get so many callbacks, Realm is writing a lot of colors, making the color panel lag. Any ideas how I can solve this? A: Coalesce the writes on the Objective-C side. // new property - add after `@interface IPDFMacColorPanel` line @property (nonatomic,copy) UIColor *pendingNewColor; - (void)colorChange:(NSColorPanel_Catalyst *)colorPanel { if (self.pendingNewColor) { self.pendingNewColor = colorPanel.color; } else { self.pendingNewColor = colorPanel.color; [self performSelector:@selector(doUpdateColor:) withObject:nil afterDelay:0.4]; } } - (void)doUpdateColor:(id)ignore { UIColor *color = self.pendingNewColor; self.pendingNewColor = nil; if (self.colorChangeHandler) self.colorChangeHandler(color); } When the color is changed, if a pending color exists, it assumes that the doUpdateColor: message will be sent within 0.4 seconds and just updates the pending color, otherwise it sets the pending color and schedules the doUpdateColor: message to be sent. This solution trades away some apparent responsiveness. You can also do something similar on the receiving Swift side, by storing the color somewhere and just not writing it to Realm for a short while, which would maintain immediate responsiveness, but if something was using the color through reading the just-written values from Realm, there would still be a delay there.
{ "pile_set_name": "StackExchange" }
Q: AWS CloudFormation environmental conditional for ses role I'm trying to make a reusable CloudFormation template and would like to do some kind of conditional where if the Environment parameter is "test" (or any other environment other than "prod"), then send SES emails to only gmail accounts (i.e., corporate accounts), but for "prod", send SES emails anywhere. Would I have to do two different roles and have conditions on each one? Or is there a way to do this inside of just the one role below? Thanks for any help! Parameters: Environment: Description: Environment, which can be "test", "stage", "prod", etc. Type: String Resources: Role: Type: AWS::IAM::Role Properties: RoleName: myRole Path: / AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Principal: Service: - "ecs.amazonaws.com" Action: - "sts:AssumeRole" Policies: - PolicyName: "ses-policy" PolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Action: - "ses:SendEmail" - "ses:SendRawEmail" Resource: "*" Condition: "ForAllValues:StringLike": "ses:Recipients": - "*@gmail.com" A: Conditions are perfectly suited for adding this sort of conditional logic to CloudFormation Resource Properties. In your example, you could use the Fn::If Intrinsic Function to include the existing Policy Condition (not to be confused with the CloudFormation Condition!) if the environment is not prod, and AWS::NoValue otherwise (removing the Policy Condition entirely when environment is prod): Parameters: Environment: Description: Environment, which can be "test", "stage", "prod", etc. Type: String AllowedValues: [test, stage, prod] Conditions: IsProdEnvironment: !Equals [ !Ref Environment, prod ] Resources: Role: Type: AWS::IAM::Role Properties: RoleName: myRole Path: / AssumeRolePolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Principal: Service: - "ecs.amazonaws.com" Action: - "sts:AssumeRole" Policies: - PolicyName: "ses-policy" PolicyDocument: Version: "2012-10-17" Statement: - Effect: "Allow" Action: - "ses:SendEmail" - "ses:SendRawEmail" Resource: "*" Condition: !If - IsProdEnvironment - !Ref AWS::NoValue - "ForAllValues:StringLike": "ses:Recipients": - "*@gmail.com"
{ "pile_set_name": "StackExchange" }
Q: DB2: Using DATE Functions to get Month or Day names in another Language (German) I want to build a Time Dimension in a Data Warehouse. Some fileds should show the name of the month or the week. With the Functions TO_CHAR(loaddate,'MONTH') or TO_CHAR(loaddate,'DAY') I do get the names, but they are in English. In my case I need them in German. Is there a way to get them directly in the necessary language or do I have to work with CASE and translate it in a custom function? Thanks TO_CHAR(loaddate,'MONTH') Returns JANUARY expected JANUAR TO_CHAR(loaddate,'DAY') Returns Monday expected Montag A: Try setting special register CURRENT LOCALE LC_TIME appropriately before running the SQL. Reference The supported locale names are listed here. For example de_DE or de_CH. Here is an example, using the command line, and you can also set the special register on the fly, or inside stored procedures: $ db2 "values monthname(current date)" 1 ---------------------------------------------------------------------------------------------------- February 1 record(s) selected. $db2 "set current locale lc_time = 'de_DE'" DB20000I The SQL command completed successfully. $ db2 "values monthname(current date)" 1 ---------------------------------------------------------------------------------------------------- Februar 1 record(s) selected.
{ "pile_set_name": "StackExchange" }
Q: Positioning 3 divs absolutely inside a container left, center, right I have been trying to center a logo div inside a header that has 3 total divs. The positioning I am going for is left, center, right. The problem is that the left and right div will push the center div depending on the length of the content on either side. I want the center div to not be affected by the left and right divs. Here is my code example: http://codepen.io/anon/pen/KDhou <header> <div class="left">LEFT ALSO PUSHES CENTER DIV</div> <div class="right"> RIGHT PUSHES CENTER DIV</div> <div class="center">CENTER</div> </header> and the css header{ color:white; position: absolute; text-align: center; left: 0; width:100%; top: 0; background-color: #2995f3;} .center{ position: absolute; display: inline-block; background:green; } .left{ float: left; background:grey } .right{ float: right; background:red } A: See here-> http://jsfiddle.net/KLXPL/1/. Your center div remains in the center when the browser size is changed. This is the HTML and CSS I used: HTML: <header> <div class="left">LEFT ALSO PUSHES CENTER DIV</div> <div class="right">RIGHT PUSHES CENTER DIV</div> <div class="center">CENTER</div> </header> CSS: header { color:white; position: absolute; text-align: center; left: 0; width:100%; top: 0; background-color: #2995f3; } .center { clear:both; display: inline-block; background:green; } .left { float: left; background:grey; display:inline-block; } .right { float: right; background:red; display:inline-block; } Hope this helps!!!
{ "pile_set_name": "StackExchange" }
Q: Trying to remove an HTML element with JS I'm trying to create an image rotator in JS. The fade animation I'm applying in CSS only works on element creation, so I'm having to remove the element on each iteration through the loop. The problem I'm facing is in the title - I can't seem to remove the clientImg, and I can't figure out why... Can anyone help? The error I'm getting is: Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. JS function clientRotator(){ var section = document.getElementById("clients"); var clientImg = document.createElement("img"); clientImg.setAttribute("id", "rotator"); section.appendChild(clientImg); clientImg.src = "assets/exxon-mobil.png"; var imgArray = ["assets/shell.png", "assets/bp.png", "assets/talisman.png", "assets/cnr-international.png", "assets/exxon-mobil.png"]; var delaySeconds = 3; var iteration = 0; setInterval(function(){ console.log(imgArray[iteration]); section.removeChild(clientImg); var clientImg = document.createElement("img"); clientImg.setAttribute("id", "rotator"); section.appendChild(clientImg); clientImg.src = imgArray[iteration]; if (iteration < imgArray.length-1){ iteration += 1; } else { iteration = 0; } }, delaySeconds * 1000) } window.addEventListener("load", clientRotator()); HTML <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/style.css"> <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet"> </head> <body> <section id="header"> <img id="logo" src="assets/logo-new.png" alt="Logo"> </section> <section id="clients"> <!-- Rotating images go here --> </section> <footer> </footer> </body> <script src="scripts/main.js"></script> </html> A: The var keyword was the culprit, making it limited to the scope inside the function. The second iteration has totally a new function, where the clientImg doesn't even exist. function clientRotator() { var section = document.getElementById("clients"); var clientImg = document.createElement("img"); clientImg.setAttribute("id", "rotator"); section.appendChild(clientImg); clientImg.src = "assets/exxon-mobil.png"; var imgArray = ["assets/shell.png", "assets/bp.png", "assets/talisman.png", "assets/cnr-international.png", "assets/exxon-mobil.png"]; var delaySeconds = 3; var iteration = 0; setInterval(function() { console.log(imgArray[iteration]); if (!!clientImg); section.removeChild(clientImg); clientImg = document.createElement("img"); clientImg.setAttribute("id", "rotator"); section.appendChild(clientImg); clientImg.src = imgArray[iteration]; if (iteration < imgArray.length - 1) { iteration += 1; } else { iteration = 0; } }, delaySeconds * 1000) } window.addEventListener("load", clientRotator()); <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet"> <section id="header"> <img id="logo" src="assets/logo-new.png" alt="Logo"> </section> <section id="clients"> <!-- Rotating images go here --> </section> <footer> </footer>
{ "pile_set_name": "StackExchange" }
Q: What is the default namespace what is the default namespace in c++? #include<iostream> class B{ ..... } int main(){ ..... } so what namespace is class B in? A: B is in the global namespace. It can be referred to unambiguously as ::B. Eric Z provides an excerpt from C++03 here: https://stackoverflow.com/a/10269085
{ "pile_set_name": "StackExchange" }
Q: The smallest possible value of $x^2 + 4xy + 5y^2 - 4x - 6y + 7$ I have been trying to find the smallest possible value of $x^2 + 4xy + 5y^2 - 4x - 6y + 7$, but I do not seem to have been heading in any direction which is going to give me an answer I feel certain is correct. Any hints on how to algebraically approach finding this value would be appreciated. I prefer not to be told what the value is. A: $$x^2 + 4xy + 5y^2 -4x -6y + 7 = (x+2y-2)^2 + (y+1)^2 + 2$$ A: Note that $x^2 + 4xy + 5y^2 - 4x - 6y + 7=(x+2y)^2+y^2-4x-6y+7$. Let $u=x+2y$. Write our expression in terms of $u$ and $y$, and complete the squares. Remark: The approach may have looked a little ad hoc, but the same basic idea will work for any quadratic polynomial $Q(x,y)$ that has a minimum or maximum. For quadratic polynomials $Q(x_1,x_2,\dots, x_n)$, one can do something similar, but it becomes useful to have more theory. You may want to look into the general diagonalization procedure.
{ "pile_set_name": "StackExchange" }
Q: How to call an img from html in javascript? It is possible to put multiple images in js array and when the function is call, one of the image(random) will pop up to the screen? If not, how can I use .innerHTML to put the image url to <img src="">? A: Sure: // Store the image sources in an array: var imgs = ["http://logok.org/wp-content/uploads/2014/03/abc-gold-logo.png", "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/NBC_logo.svg/779px-NBC_logo.svg.png", "https://s-media-cache-ak0.pinimg.com/originals/96/e6/d9/96e6d9e141ac42bf9aad1aaae0a15c61.jpg", "http://fontmeme.com/images/CNN-Logo.jpg", "http://logok.org/wp-content/uploads/2014/12/TBS-logo-blue.png", "http://www.doddlenews.com/wp-content/uploads/2012/05/fox-tv-logo.jpg"]; // Get reference to the img element var img = document.getElementById("myImage"); function getRandomImage(){ // Get random number between 0 and 3 (the length of the array) var rnd = Math.floor(Math.random() * imgs.length); // Set the src and the alt to a random image from the array img.src = imgs[rnd]; img.alt = imgs[rnd]; } // Get reference to the button var btn = document.getElementById("getImage"); // When button is clicked, run function btn.addEventListener("click", getRandomImage); img { width:75px; } <button id="getImage">Click to get random image</button> <br> <img src="https://pisces.bbystatic.com/BestBuy_US/en_US/images/abn/2014/tvv/cat/tv/tv_size4a.jpg;maxHeight=333;maxWidth=333" id="myImage"> Also FYI, .innerHTML is only for elements that have "content". An img element doesn't have a closing tag and therefore, it can't "contain" anything between its opening and closing tags.
{ "pile_set_name": "StackExchange" }
Q: How do you select the last group in this regex? I want to select the last group enclosed in {} but once I start typing \s at the end of the regex, it doesn't select the second line anymore. Could someone explain this to me? Regular Expression: \s*(.{10})\s*(\d*)\s*(.{3})\s*(.*?)(\((?>\((?<c>)|[^()]+|\))\))\s\{(.*)\} Test Strings: 0.00002211 55 7.7 "'Allo 'Allo!" (1982) {A Bun in the Oven (#8.0)} 0...222.02 14 6.7 "$100 Taxi Ride" (2001) Here's a link to what I'am trying to do: https://regex101.com/r/8qrKxq/2 Thanks! Update What I expect is what happens here: https://regex101.com/r/8qrKxq/6 At "$#*! My Dad Says" then the first 2 series names, it grabs the right groups. But then after that somehow it screws up, I don't know how to fix this.. A: Your regex expression does not include the 2nd line because it does not contain something of type {.*}. If you try your regex with this eg: 0.00002211 55 7.7 "'Allo 'Allo!" (1982) {A Bun in the Oven (#8.0)} 0...222.02 14 6.7 "$100 Taxi Ride" (2001) {9} It will take the 9 enclosed in {}. If you want your selection of {} optional then you should use \s*(.{10})\s*(\d*)\s*(.{3})\s*(.*?)(\((?>\((?<c>)|[^()]+|\))\))(?:\s(\{(.*)\}))? demo
{ "pile_set_name": "StackExchange" }
Q: Иконки программы в зависимости от ОС Доброго времени суток! Хотелось бы научится изменять иконку программы в зависимости от операционной системы... По типу как папки, скинул на флешку, а отображается под разными ОС по-своему... Нет идей как это запрограммировать до запуска программы? A: Простого решения, разумеется нет, поскольку ваше приложение при открытии папки проводником должно автоматически предоставить ему некоторую иконку, которая будет им отрисована. Соответственно, простой способ - до первого запуска хранить любую иконку, а после первого запуска патчить свой фрагмент .exe, куда и зашит ресурс иконки, заменяя ее на необходимую. Сложный способ - вешать глобальный хук на соответствующий вызов получения иконки (готов допустить, что его, может быть, придется перехукивать и на уровне Native API) и опять же, на лету патчить ресурс, демонстрируя ту иконку, которая вам нужна. В этом способе даже в первый раз иконка будет показана правильная. В общем, задачка интересная, но, естественно, ни один человек в здравом уме таким заниматься не станет :) A: Можно воспользоваться тем, что иконку ищет проводник в ресурсах приложения. И для висты/7 поддерживаются большие иконки большого размера 256 на 256. А ХР их ещё не поддерживает. Конечно, это грязный хак, но по другому - только патчить проводник. Но пользователь может зайти с TotalCommander или другой программы и приплыли... а вот картинки папок отображаются по разному, потому что картинки для папок хранятся не на флешке, а в системных каталогах.
{ "pile_set_name": "StackExchange" }
Q: How to find the minimum set of vertices in a Directed Graph such that all other vertices can be reached Given a directed graph, I need to find the minimum set of vertices from which all other vertices can be reached. So the result of the function should be the smallest number of vertices, from which all other vertices can be reached by following the directed edges. The largest result possible would be if there were no edges, so all nodes would be returned. If there are cycles in the graph, for each cycle, one node is selected. It does not matter which one, but it should be consistent if the algorithm is run again. I am not sure that there is an existing algorithm for this? If so does it have a name? I have tried doing my research and the closest thing seems to be finding a mother vertex If it is that algorithm, could the actual algorithm be elaborated as the answer given in that link is kind of vague. Given I have to implement this in javascript, the preference would be a .js library or javascript example code. A: From my understanding, this is just finding the strongly connected components in a graph. Kosaraju's algorithm is one of the neatest approaches to do this. It uses two depth first searches as against some later algorithms that use just one, but I like it the most for its simple concept. Edit: Just to expand on that, the minimum set of vertices is found as was suggested in the comments to this post : 1. Find the strongly connected components of the graph - reduce each component to a single vertex. 2. The remaining graph is a DAG (or set of DAGs if there were disconnected components), the root(s) of which form the required set of vertices.
{ "pile_set_name": "StackExchange" }
Q: L'expression « un fossé qui se creuse » Que veut dire cette phrase ? J’imagine que c’est quand quelque chose devient de pire en pire non ? A: De manière générale, c'est la combinaison entre la notion d'écart important (le fossé), lié à une augmentation (qui se creuse). Une différence qui s'accentue. Un désaccord, qui augmente. Une inégalité (salaire, soins, ...), qui empire. Un éloignement (entre personnes, entreprises, états), qui augmente sur certains sujets (économie, politique, ...).
{ "pile_set_name": "StackExchange" }