text
stringlengths
64
89.7k
meta
dict
Q: Update image after Src Attribute change Hello wonderful people, I'm trying to get the image to update after I change the 'src' attribute. I've tried appending the url with a date stamp, but that doesn't seem to work. Can someone show me where I'm going wrong, or just suggest a better way to do it all together? I've included my entire code to date, as I'm not sure where the problem is. I'm a bit of a noob I'm afraid. The first three lines in the 'displayOut' function are most likely where the problem lies though. Thank you in advance for your help. var db = [{ // ROOMS rooms: [{ // Room 0 - North room description: "You awake to find yourself in a dank smelling old room, plaster and smashed glass litters the floor. To the North is a broken window, beyond which you can only see a thick grey mist. There is one door by which to exit, to the South.", roomImg: "images/room_0.jpg", exits: { north: false, south: 1, east: false, west: false, up: false, down: false }, roomInvent: ["a Box of Matches", "a Glass Shard"] }, { // Room 1 - Corridor description: "You are in a short, dark corridor, a single tungsten bulb hangs stiffly from the ceiling. There is a light switch on the wall.", roomImg: "images/room_1.jpg", exits: { north: 0, south: 4, east: 3, west: false, up: 5, down: false }, roomInvent: [] }, { // Room 2 - West Room - Locked room description: "", roomImg: "images/room_2.jpg", exits: { north: false, south: false, east: false, west: false, up: false, down: false }, roomInvent: [] }, { // Room 3 - East room - Bedroom description: "You are in the Bedroom", roomImg: "images/room_3.jpg", exits: { north: false, south: false, east: false, west: 1, up: false, down: false }, roomInvent: [] }, { // Room 4 - South room - kitchen description: "You are in a small kitchen. There is an old log fire on the East wall, and a door leading outside to the South.", roomImg: "images/room_4.jpg", exits: { north: 1, south: false, east: false, west: false, up: false, down: false }, roomInvent: [] }, { // Room 5 - Attic description: "You are in the Attic.", roomImg: "images/room_5.jpg", exits: { north: false, south: false, east: false, west: false, up: false, down: 1 }, roomInvent: [] }] }, // End Rooms { // ITEMS items: [{ itemIndex: 0, name: "a Box of Matches", useWith: null, examine: "There is only a single match inside." }, { itemIndex: 1, name: "a Glass Shard", useWith: null, examine: "It looks sharp" }, { itemIndex: 2, name: "a Mallet", useWith: null, examine: "It is old and rusty, but otherwise uninteresting." }] } ]; //End db var inventory = []; var inputTextBox = document.getElementById("inputTextBox"); var diologueBox = document.getElementById("diologueBox"); var strOut = ""; var roomLoc = 0; function displayOut() { // images let dt = new Date; document.getElementById("imgBox").setAttribute("src", db[0].rooms[roomLoc].roomImg + "?dt=" + dt.getTime()); // Diologue box diologueBox.innerHTML = db[0].rooms[roomLoc].description + (function() { // Check if room has items in inventory, if so, list them. if (db[0].rooms[roomLoc].roomInvent != "") { return "<br><br> The room contains " + (function() { let items = ""; for (let i = 0; i < db[0].rooms[roomLoc].roomInvent.length; i++) { items += db[0].rooms[roomLoc].roomInvent[i] + ", "; }; items = items.slice(0, items.length - 2); return items; })(); } else { return "<br><br> The room is empty "; }; })(); }; // Function for changing room location function navigateTo(direction) { if (db[0].rooms[roomLoc].exits[direction] === false) { outputBox.innerHTML = "You cannot go " + direction + " from here." } else { roomLoc = db[0].rooms[roomLoc].exits[direction]; displayOut(); } } inputTextBox.addEventListener("keypress", function(event) { let x = event.which || event.keyCode; if (x === 13) { // 13 is the Return key switch (inputTextBox.value.toLowerCase()) { //Diologue Navigation case "": // Nothing happens break; case "north": case "n": navigateTo("north"); break; case "south": case "s": navigateTo("south"); break; case "east": case "e": navigateTo("east"); break; case "west": case "w": navigateTo("west"); break; case "up": case "u": navigateTo("up"); break; case "down": case "d": navigateTo("down"); break; //Dioogue Help case "help": outputBox.innerHTML = " Here is a list of useful commands: North, South, East, West, Up, Down, Look, Examine, Inventory, Take, Use"; break; // default: outputBox.innerHTML = " I have no idea what " + "'" + inputTextBox.value.bold() + "'" + " means..."; } // End switch //Clear InputTextBox inputTextBox.value = ""; inputTextBox.setAttribute("placeholder", ""); } // End KeyPress }); // End Event listener displayOut(); @charset "utf-8"; @font-face { font-family: 'Terminal'; /*a name to be used later*/ src: url(lcd_solid.ttf); /*URL to font*/ } * { font-family: Terminal; font-size: 18px; margin: 0; border: 0; } body, html { font-family: helvetica; font-size: 12px; background: #282828; } #imgBox { margin: 0px auto 0px auto; background-image: url("../images/room_0.jpg"); background-repeat: no-repeat; height: 600px; width: 1024px; } #conBox { margin: 0px auto 0px auto; position: relative; width: 1024px; height: 300px; } #diologueBox { background: #CCC; height: 200px; clear: both; padding: 1px 0px 1px 3px; overflow: none; position: relative; } #diologueBox p { margin: 5px; left: 0px; bottom: 0px; } #outputBox { background: #CCC; height: 50px; clear: both; padding: 1px 0px 1px 3px; overflow: none; position: relative; } #inputBox { position: relative; height: 20px; background: #C1C1C1; } #inputTextBox { height: 18px; padding: 1px; float: right; width: 1004px; background: #C1C1C1; } ::-webkit-input-placeholder { color: red; } :-moz-placeholder { /* Firefox 18- */ color: red; } ::-moz-placeholder { /* Firefox 19+ */ color: red; } :-ms-input-placeholder { color: red; } #inputTextBox.focus, input:focus { outline: none; } #bullet { width: 15px; float: left; padding: 4px 0px 1px 3px; } <!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="styles/style.css"> <meta charset="utf-8"> <title>Untitled</title> </head> <body> <div id="imgBox"></div> <div id="conBox"> <div id="diologueBox"></div> <div id="outputBox"></div> <div id="inputBox"> <div id="bullet">></div> <input id="inputTextBox" type="text" maxlength="60" placeholder="Type commands here, type 'Help' at any time for list of commands" autofocus></input> </div> </div> <script src="script2.js"></script> </body> </html> A: Quick solution : use background-image as you've done in your css. edit : however changing the src attribute should work, I'm not sure how jquery handle it. If using the background isn't an option, you could : have all your <img> in your html and hide/show them (fast but it need to load everything upfront) create img elements on the fly with $("<img/>") and replace the old one. Given your use case, it's quite cheap ressource-wise. use a canvas to paint your images (but then why not use background-image?)
{ "pile_set_name": "StackExchange" }
Q: EF4.1/MVC3 Database First: How to remove password from connection string I'm building a website with EF4.1 and MVC3 (C#). Trying to find out what the proper way to remove the password from the connection string is. I've done some searching and can't seem to find anything that tells how to remove the password from the connection string. I'm actually working on two different sites at the moment. One is hosted on GoDaddy and is using their SQL Server db. The other is hosted here at work and will be using SQL Server 2005. Lastly, is it possible to do the database first code generation with a MySQL database? I'm personally more comfortable with MySQL and prefer it to SQL Server, but have had issues getting this to work. If you should need any additional information please let me know. A: You should probably encrypt your web.config connection strings before deploying it to the server. AFAIK, if you connect to your server using SQL Server Authentication, the connection string needs the username and password. If your app and db servers had domain trust, you can use integrated mode / windows authentication / identity impersonate to have a password-less connection string. But most service providers don't let you do this -- they use SQL Server Authentication to keep customers out of their domain. Either way, there is more sensitive information in the connection string than just the password. You should encrypt the whole <connectionStrings> node.
{ "pile_set_name": "StackExchange" }
Q: Programmatically Remove Associated Products From Grouped Product I have a grouped product and am looking to remove all associated products from it programmatically. I tried using a similar method as one would use for a configurable product found here: How to remove associated products from configurable product? But there is no comparable saveProducts() method for grouped products because there is no resource 'catalog/product_type_grouped'. I've tried to follow the saveAction method used in Adminhtml/controllers/catalog/product/ProductController, but haven't found the piece of code that saves the associated products selected in the admin form. Could anyone point me in the right direction? A: Figured it out. This is a variation of some code in the _initProductSave() method of the same controller: $groupedProduct->setGroupedLinkData(array()); $groupedProduct->save();
{ "pile_set_name": "StackExchange" }
Q: How to replace all the print() calls by a LineEdit.setText() so the user only has to look at the application GUI and not the IDE's console? I wrote a program to perform measurements and currently I launch it via the Spyder IDE. The program is written in Python 3.6.3. The GUI was made using PyQt5 and it should be the main focus of the user, but I also print() many informations in Spyder's console. In preparation for switching to an .exe instead of a .py, since there will be no console anymore, I would like to add a LineEdit to my interface where all the printing would occur. Ideally it would display both my print()s and the various error messages generated during execution. How do I redirect those prints to a LineEdit? Most of the information I found during my research was about making a LineEdit some kind of Windows cmd equivalent but examples were overkill compared to what I'm trying to do. Thanks in advance. A: A quick and dirty method is to just redefine the builtin print function. from PyQt5 import QtWidgets IS_EXE = True # There is probably a way to detect this at runtime class Window(QtWidgets.QPlainTextEdit): def __init__(self): super(Window, self).__init__() self.setReadOnly(True) if __name__ == '__main__': app = QtWidgets.QApplication([]) win = Window() win.show() # Replace the builtin print function if IS_EXE: print = win.appendPlainText # Print some stuff print('foo') print('bar') app.exec_()
{ "pile_set_name": "StackExchange" }
Q: How can I fix the Slaying Stone's premise? I'd like to know how people have fixed the Slaying Stone premise hole: You have to go find a stone in a town overrun with orcs, goblins and a dragon, but: It only works near Gorizbadd It disintegrates after one use It can't be duplicated (using a ritual?) What answers can I give my players if/when they point out the obvious fact that the stone is mostly useless, and the best thing to do is leaving it alone? A: The fact that it can kill any one single person without exception (from my understanding by reading a little about the adventure), the best way to prove that this stone has significance is give them a vision that the target of the stone (the count, duke or whatever) has both reasons he cannot leave the area, but also is destined to have a great importance to the world at large. And if the Stone of Slaying is found and used against him, it would stop him from fulfilling that destiny. This way, just ignoring the stone would have world reaching consequences and can incentive them into taking the contract and finding and destroying the stone. A: One solution is to have an enemy – the biggest, baddest, evilest guy – who can only be slain by whittling him down/taking out his protections, and then using the Stone of Slaying on him. Makes for a pretty epic quest to get the stone, get to the boss, and use it when the time is right. A pretty obvious candidate for this, depending on the players’ level, would be the Tarrasque. Traditionally, the Tarrasque is ridiculously difficult to actually kill; originally, no actual way to kill it was offered. AD&D suggested that wish might work; 3.5 made that official, but that could easily be undone. Elsewise, just any cosmic evil. Your setting’s Ganon. A: It could also be one of the means of killing anyone permanently -- that is, he can't be resurrected, contacted via spells or such. In a high magic world where resurrections can be easily arranged, this could be one way to remove a paranoid villain with several backup plans.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to verify the integrity of javascript files at the client? I'm working on what aims to be a secure method of user registration and authentication using php and javascript but not ssl/tls. I realise this may well be considered an impossible task that's been tried 1000 times before but I'm going to give it a go anyway. Every example I see online that claims to do it seems to have some huge fatal flaw! Anyway, my current problem is verifying javascript at the client. The problem being that if my sha1 implementation in javascript is modified by some man-in-the-middle it's not secure at all. If I could just verify that the received javascript has not been tampered with then I think I can pull this off. The real problem though, is that the only way to do things on the client side is javascript. Simple: write a javascript to verify the integrity of the other javascript files. Nope! Man-in-the-middle can just modify this file too. Is there a way around this? A: To secure your JavaScript, you must examine it in an guaranteed untampered environment. Since you can't create such an environment in the browser this is not possible. Your best option is to download the JavaScript via HTTPS. That isn't safe but better. Possible attack vectors left: A virus can modify the browser to load some malicious JavaScript for every page A keylogger can monitor what the user is typing A proxy can act as a man-in-the-middle for an HTTPS connection. The proxy will actually decode what you send via HTTPS and encode it again (with a different certificate) for the browser. A proxy can add iframes to the pages you send
{ "pile_set_name": "StackExchange" }
Q: In C# 3.0 we use "var" what is its alternative in C# 2.0? I am learning plug able architecture in .Net using Managed Extensibility Framework (MEF.) I saw sample code on the net, but when I tried to implement it I got stuck at one point. The code was using: var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog.CreateResolver()); This var is available on C# 3.0 where as I am coding in C# 2.0. What is the alternative of above two statements? How can I make them work in c# 2.0 using VS 2005? i tried this bt its saying now Error 1 The type or namespace name 'AttributedAssemblyPartCatalog' could not be found (are you missing a using directive or an assembly reference?) C:\Documents and Settings\test\Desktop\MEFDemo\MEFDemo\Program.cs 31 13 MEFDemo where as i have added referance to SystemComponentModel.Composition A: Basically, var forces the compiler to determine (infer) the compile-time type of a variable based on it's "initializer" -- effectively, an expression to the right from = sign. Here the types are obvious: AttributedAssemblyPartCatalog catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog.CreateResolver()); And make sure you add using System.ComponentModel.Composition; statement. Plus, be advised that AttributedAssemblyPartCatalog was renamed to AssemblyCatalog. A: This is the use of type inference in C# 3.0. When using the keyword var in c# 3.0 the compiler infers the type. See scott guthries explanation In c# 2.0 you have to declare the type of the variable the same as c# 1.1 e.g. Type variableName = new Type(); Making you above code example AttributedAssemblyPartCatalog catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog.CreateResolver()); HTH
{ "pile_set_name": "StackExchange" }
Q: AngularJS - Broadcasting across controllers Am trying a scenario where i Login, and, on success, want to store that LoginID and pass it to all other controllers for navigation/user management. Similar to a global variable set up, store once use everywhere concept. Been using angularjs shared Services technique but its not picking the braodcaster LoginID in other controllers. High level details: 1) Login HTML calls Login Controller from where i call back end server for user authentication 2) On success, broadcasted LoginID via shared service 3) from Login HTML, page navigates to OrderMenu Html and calls OrderMenu controller where am trying to fetch the User id which was broadcasted via the shared service. 4) but in the Order Menu controller the UserID shown is the initialized value i.e looks like app.factory is being called again and initializing the Broadcasted value. I want to stop the reloading of app.factory. Looks like am missing something here.Any thoughts would be really helpful here. A: Here is a quick implemention example of what you described. And it seems to be working. http://plnkr.co/edit/SPAB4W My service is defined as follows: app.factory('UserAuth', function() { return { userId: 'unknown', authenticate: function( name ) { // do server side authentication here... this.userId = 'authenticatedUserId_Of_' + name; } }; }); In this example, when second controller (OrderCtrl) is getting called, UserAuth.userId does not get re-initialized and keeps the obtained userId of what authentication gives. You may want to share your code.
{ "pile_set_name": "StackExchange" }
Q: How to select records in a track with gaps not greater than 5 minutes between each record? I'm having a lot of records from a GPS device, which I need to show as an route on a map. Records combine a route when the time between them records is not greater than 5 minutes. Lets say my database looks like: id date ------- --------------------- 1 2013-01-10 11:00:00.0 2 2013-01-10 11:01:15.0 3 2013-01-10 11:02:15.0 4 2013-01-10 11:03:15.0 5 2013-01-10 11:04:45.0 6 2013-01-10 11:15:00.0 7 2013-01-10 12:00:00.0 8 2013-01-10 12:00:50.0 In this case records 1-5 and 7-8 need to form a route. I'm trying to write a query for this, but I'm stuck. I managed to perform the operation after the database, but that is something you should not want (you have to retrieve ALL the records etc.) Has someone have a solution for this? A: You can get individual segements by simply comparing each entry with its successor SELECT f.ID AS from_ID, t.ID AS to_ID FROM GPSTable AS f JOIN GPSTable AS t ON f.ID = t.ID-1 WHERE TIMESTAMPDIFF(SECOND, f.Date, t.Date) < 300 ; If there exists an entry (A,B) and another entry (B,C), you know that you have a path from (A->B->C). The next step would then be to collect all those path segments. This could be done by a recursive query, but I am not familiar with mySQL.
{ "pile_set_name": "StackExchange" }
Q: How to get empty ol inside li when li is in sub-level of list item in Jquery? The following code snippet, I tried to get and highlight every li that contain empty ol element (ol without any li element) regardless of number of sub-level. $(document).ready(function() { var Text = ''; var emptyLiText = ''; $('ol#myUL > li').each(function() { lenOl = $(this).find('ol').length; if (lenOl > 0) { lenOlLi = $(this).find('ol').children('li').length; if (lenOlLi == 0) { $(this).addClass('error_item'); emptyLiText = $(this).clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text(); emptyLiText = $.trim(emptyLiText); Text += ' ' + emptyLiText; $('.message').html('<div class="alert alert-danger">' + '<button type="button" class="close" data-dismiss="alert">&times;</button><b>Unable to Save:</b> Menu item <b>' + Text + '</b> is parent item but does not has sub-item inside.</div>'); breakout = true; // return false; } else { ($(this).hasClass('error_item') == true) ? $(this).removeClass('error_item'): ''; } } }) }) .error_item { border: 1px solid red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js" crossorigin="anonymous"></script> <div class="message"></div> <ol id="myUL"> <li>Sample Item 1 <ol> <li>Sample Item 2 <ol></ol> </li> <li>Account</li> </ol> </li> <li>Sample Item 3 <ol></ol> </li> <li>Sample Item 4</li> <li>Sample Item 5 <ol> <li>Sample Item 6 <ol> <li>Sample Item 7 <ol></ol> </li> </ol> </li> </ol> </li> </ol> However, currently my trying could only get first level of li that has empty ol inside. When empty ol is in second or third level of list, it get ignore, ex. Sample Item 2 and Sample Item 7. My question is how can I get empty ol inside li regardless of how many sub-level it is? Because my project is related to this. Thanks. A: You're using $('ol#myUL > li') selector where > means immediate child. Replace > with a space to get list of all <li> elements inside parent <ol> something like this $('ol#myUL li')
{ "pile_set_name": "StackExchange" }
Q: graphicx using placeholder image with \graphicspath \documentclass{article} \usepackage{graphicx} \graphicspath{{./figs/}} \begin{document} \includegraphics{example-image.png} \end{document} The above successfully compiles, however the output PDF contains a placeholder image instead of the actual example-image.png. It works fine (displaying the expected image) if the above code is changed to remove the \graphicspath{{./figs/}} line: \documentclass{article} \usepackage{graphicx} \begin{document} \includegraphics{figs/example-image.png} \end{document} Why is this happening? A: Imho you can prevent that kpathsea looks for the images in the texmf tree if you add ./ to the path. For me (on windows) it works: \documentclass{article} \usepackage{graphicx} \graphicspath{{./figs/}} \begin{document} \includegraphics{./example-image.png} \end{document}
{ "pile_set_name": "StackExchange" }
Q: group of order $p^n$ If $p$ is any prime number and $G$ is a group of order $p^2$, then $G$ is abelian, and either $G\cong \mathbb Z_{p^2}$ or $G\cong \mathbb Z_p \times \mathbb Z_p$. How about order $p^n$ where $n$ is any integer? Is there similar conclusion, i.e. If $p$ is any prime number, $n$ is an integer, and $G$ is a group of order $p^n$, then $G$ is abelian; either $G\cong \mathbb Z_{p^n}$ or $G=H \times K$, where $H$ and $K$ are subgroups of $G$, $H$ is a group of order $p^i$, $K$ is a group of order $p^j$ and $i+j=n$? A: The classification of $p$-groups is considered a very hard problem. “Most” groups are $p$-groups, in a precise sense that would take too long to explain (in fact, it is conjectured that if you take the number of isomorphism classes of order $2^k\leq n$, and divide by the number of isomorphism classes of groups of order at most $n$, the limit as $n\to\infty$ will be $1$.) A $p$-group must have nontrivial center. If $G$ is a $p$-group, we let $Z_0(G)=\{e\}$, and let $Z_{i+1}(G)$ be the subgroup of $G$ such that $Z_{i+1}(G)/Z_i(G)$ is the center of $G/Z_i(G)$. The least value of $c$ such that $Z_c(G)=G$ is called the “class of $G$” (so abelian groups are class $1$, center-by-abelian are class $2$, etc). The coclass of a group of order $p^n$ is $n-c$. The analysis of $p$-groups by co-class is relatively recent, as these things go. They also informed a series of important conjectures about $p$-groups that, in a way, brought order out of the chaos. The Co-class Theorems that give some unifying structure. The strongest one is: Theorem. There is a function $f(p,r)$ such that every finite $p$-group of coclass $r$ has a normal subgroup $K$ of class at most $2$ and index at most $f(p,r)$. If $p=2$, one may require $K$ to be abelian. There is some work on the finer structure, but this gives you an idea of how far the state of the art is from something like what you were hoping for.
{ "pile_set_name": "StackExchange" }
Q: Generate a CSS file from HTML markup I create a lot of html and css pages. Is there a way to markup an html file, than generate a css file from the markup. Here's what i'm thinking: Example Markup <body id="home"> <section id="main"> <article> <p>Some content</p> </article> </section> <aside> <article> <p>Some more content</p> </article> </aside> </body> Example of generated CSS #home { } #home #main { } #home #main article { } #home #main article p { } #home aside { } #home aside article { } #home aside article p { } A: Yes, there is: parse the HTML and walk the DOM tree to generate your skeleton CSS file. PS: that IS very impractical CSS.
{ "pile_set_name": "StackExchange" }
Q: How do I inject user so I do not have to look him up in Laravel request? I am following a tutorial on Laravel signed routes: https://dev.to/fwartner/laravel-56---user-activation-with-signed-routes--notifications-oaa To create the signed route author does this: $url = URL::signedRoute('activate-email', ['user' => $this->user->id]); notice that to the 'user' he only assigned the id... Later when user in question clicks the generated link and another part of code does this: Route::get('/activate-email/{user}', function (Request $request) { if (!$request->hasValidSignature()) { abort(401, 'This link is not valid.'); } $request->user()->update([ 'is_activated' => true ]); return 'Your account is now activated!'; })->name('activate-email'); I am confused by this part: $request->user()->update([ 'is_activated' => true ]); Author accesses user() directly and runs the update on him? When I in my own code tried this: dd($request->user()) I got null and if I tried dd($request->user) I got user id number. How is author able to call user()->update without looking up the user. I do not see where he does inject the User object, so it seems like magic to me or perhaps the author did not test his own code fully, which is on GitHub: https://github.com/fwartner/laravel-user-activation So how do I inject the user into the route so I do not have to explicitly look him up with $user = User::find($request->user); A: There is a difference between $request->user and $request->user() $request->user() is the same as auth()->user(), so it is getting the authenticated user. The $request->user just get the param user in the Request Object. If you want to get a user directly without making a query to retreive it from the database you have to inject it directly in the route (or method) like this (assuming your user model is User.php): Route::get('/activate-email/{user}', function (User $user, Request $request) { if (!$request->hasValidSignature()) { abort(401, 'This link is not valid.'); } $request->user()->update([ 'is_activated' => true ]); return 'Your account is now activated!'; })->name('activate-email'); Notice that $user match with {user} in the Route (this will make automatically model binding)
{ "pile_set_name": "StackExchange" }
Q: Can I use an array to compare multiple criteria using the like operator? Can I use Array to compare multiple criteria using Like statement Example: LCase(Cells(lig, 2)) Like Array("object**", "**cash**", "lobby**") A: Or you can use following syntax with Or (LCase(Cells(lig, 2)) Like "object**") Or (LCase(Cells(lig, 2)) Like "**cash**") Or (LCase(Cells(lig, 2)) Like "lobby**") And so on
{ "pile_set_name": "StackExchange" }
Q: Is $(-\infty, \alpha)$ closed in the topological space $\mathbb{R}_k$? BACKGROUND Let $$K := \left\{\frac{1}{n} \mid n \in \mathbb{Z}_{+}\right\} = \left\{\frac{1}{1}, \frac{1}{2}, \frac{1}{3}, \ldots\right\},$$ where $\mathbb{Z}_{+}$ is the set of all positive integers. Let $$\mathscr{B}_k = \left\{(a,b) \subseteq \mathbb{R} \mid a, b \in \mathbb{R}, a < b\right\} \cup \left\{(c,d)-K \mid c, d \in \mathbb{N}, c < d\right\}.$$ Then $\mathscr{B}_k$ is a basis for a topology on $\mathbb{R}$, and this is called the $K$-topology on $\mathbb{R}$ and is denoted as $\mathbb{R}_k$. Now, a subset $C$ of the topological space $X$ is said to be closed if $X - C$ is open. QUESTION In the topological space $\mathbb{R}_k$, is $(-\infty, \alpha)$ closed? ATTEMPT $$(-\infty, \alpha) \text{ closed in } \mathbb{R}_k \iff {\mathbb{R}_k} \setminus (-\infty, \alpha) \text{ open in } \mathbb{R}_k \iff \mathbb{R}_k \setminus (-\infty, \alpha) = \bigcup_{i \in I}{\mathscr{B}_k}$$ Therefore, there exists an $i_0 \in I$ such that $$\mathbb{R}_k \setminus (-\infty, \alpha) = \mathscr{B}_{k_{i_0}}.$$ This is true if and only if $(-\infty, \alpha) \notin \mathscr{B}_{k_{i_0}}$. But $$\mathscr{B}_{k_{i_0}} = \left\{(a_0,b_0) \subseteq \mathbb{R} \mid a_0, b_0 \in \mathbb{R}, a_0 < b_0\right\} \cup \left\{(c_0,d_0)-K \mid c_0, d_0 \in \mathbb{N}, c_0 < d_0\right\}.$$ At this point, I am stuck. I am not sure if what I am doing is even correct. Any hints that you can provide will be appreciated. ADDED August 27 2017 The existing answers are inadequate, as we have not yet covered limit points (i.e., the derived set) nor connectedness for $\mathbb{R}$ and $\mathbb{R}_k$. A: No. $(-\infty, \alpha) =: A$ is closed only if $A' \subseteq A$, but $\alpha \in A'$ and $\alpha \notin A$.
{ "pile_set_name": "StackExchange" }
Q: Excel VBA error 91, trying to export certain sheets' data to text file I am trying to write a macro whereby it checks all sheetnames for certain criteria (specifically here the inclusion of 'TUBA' in the name) and, if met, exports a range on those sheets to text files with the sheet name as filename. I am getting error 91: object variable or With block variable not set, and on debugging the If WS.name Like "TUBA*" Then line is highlighted. How can I fix this? The problematic code is below. I previously had success with almost the same code but without the If statement (shown in the second block below), so I assume its the way I am adding this in. If i need to set a variable, which one have i missed? Sub ExportTubatoText() Dim c As Range, r As Range Dim output As String Dim lngcount As Long Dim WS As Worksheet Dim Name As String Dim strFolder As String strFolder = GetFolder("L:TUBA\") '\ dialog box opens in that folder as default 'strFolder = GetFolder("L:TUBA\") If strFolder <> "" Then MsgBox strFolder End If For Each sh In ThisWorkbook.Worksheets 'if worksheet has 'TUBA' in the title, then it is exported to text If WS.Name Like "TUBA*" Then output = "" For Each r In sh.Range("F3:F200").Rows For Each c In r.Cells output = output & c.Value Next c output = output & vbNewLine Next r Name = sh.Name Open strFolder & "\" & Name & ".txt" For Output As #1 Print #1, output Close End If Next End Sub Successful code: For Each sh In ThisWorkbook.Worksheets output = "" For Each r In sh.Range("O2:O500").Rows For Each c In r.Cells output = output & c.Value Next c output = output & vbNewLine Next r Name = sh.Name Open strFolder & "\" & Name & ".txt" For Output As #1 Print #1, output Close Next A: Try changing If WS.Name Like "TUBA*" Then to If sh.Name Like "TUBA*" Then Or change your For Each to WS in...
{ "pile_set_name": "StackExchange" }
Q: How can i display a nested list in a multiple select or with checkboxes in Rails? How can i display a nested list in a multiple select or with checkboxes in Rails? My table looks like this: | id | parent_id | name | lft | rgt | Thanks... A: You can try this link http://code.google.com/p/checkboxtree/ For demo http://checkboxtree.googlecode.com/svn/tags/checkboxtree-0.4.3/index.html
{ "pile_set_name": "StackExchange" }
Q: How to compile play-services:11.2.0 I want to get current place of my device, and I follow this link:google And this tutorial requires Google Play services version 11.2.0 or later. But when I compile 'com.google.android.gms:play-services:11.2.0', I get : Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:26.0.0 here is my build.gradle(Module:app): apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion "26.0.1" defaultConfig { applicationId "com.example.administrator.googlemap" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:26.+' compile 'com.google.android.gms:play-services:11.2.0' compile 'com.google.android.gms:play-services-maps:11.0.2' compile 'com.google.android.gms:play-services-places:11.0.2' compile 'com.google.android.gms:play-services-location:11.0.2' testCompile 'junit:junit:4.12' } And here is my build.grandle(Project) buildscript { repositories { jcenter() maven { url "https://maven.google.com/"} } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } How can I resolve this Error.? A: Instead of variable version name compile 'com.android.support:appcompat-v7:26.+' Use constant version, latest is 26.1.0 compile 'com.android.support:appcompat-v7:26.1.0' You've google maven repo link in buildscript repository list, You should also add google maven repo in project dependencies repository list of your root build.gradle file allprojects { repositories { jcenter() maven { url "https://maven.google.com/"} } } Selective compile is better option instead of complete play-services artifacts, you should choose what you needed in your project. compile 'com.google.android.gms:play-services:11.2.0' // -> latest is 11.4.0 break it into your required artifact, like compile 'com.google.android.gms:play-services-maps:11.4.0' compile 'com.google.android.gms:play-services-places:11.4.0' compile 'com.google.android.gms:play-services-location:11.4.0' If you're using Android Plugin for Gradle 3.0.0 or latter version repositories { mavenLocal() mavenCentral() google() //---> Add this } replace compile with implementation, More about this replacement here
{ "pile_set_name": "StackExchange" }
Q: Percentage does not work with FlatList render item when horizontal is true I would like to use the screen's width on the render item of the horizontal FlatList. However, it does not work as expected. When the horizontal is false, the percentage value works. But when the horizontal is true, the percentage value does not work. class App extends React.Component { _renderItem = ({ item }) => { return ( <View style={{ width: '100%', height: 100, }}> <Text>{item.key}</Text> </View> ); }; render() { return ( <View style={styles.container}> <FlatList data={[{ key: 1 }, { key: 2 }, { key: 3 }]} renderItem={this._renderItem} horizontal={true} /> </View> ); } } Snack link when the FlatList is horizontal Snack link when the FlatList is NOT horizontal A: I think I remember someone mentionning something like that. Using Dimensions works here. See here: https://snack.expo.io/H1-wnC5HM I rather solve it with flex or percentage but well.
{ "pile_set_name": "StackExchange" }
Q: Prove an inequality involving a norm We define the following inner product on intergrable, $2\pi$ periodic functions from $\mathbb{R}$ to $\mathbb{C}$: $$\langle f,g\rangle = \frac{1}{2\pi} \int_{-\pi}^\pi f(t)\overline{g(t)}\ dt$$ I need to prove that: $$\int_{-\pi}^\pi \left|f(t)\right| dt \le \sqrt{2\pi}\sqrt{\int_{-\pi}^\pi \left|f(t)\right|^2\ dt} = 2\pi \|f\|$$ Now, Cauchy-Schwarz inequality seemed to me perfect for this: $$2\pi\|f\| =\|2\pi\|\|f\| \ge |\langle f, 2\pi \rangle| = \left| \int_{-\pi}^\pi f(t)\ dt\right|$$ but of course, we need the absolute value for the integrand. I've also tried to use the fact that $f$ is bounded but that didn't yield anything useful. A: Your are almost done, just note that $$ \def\norm#1{\left\|#1\right\|}\def\abs#1{\left|#1\right|}\norm{\abs f} = \norm{f}, $$ now start your calculations with $$ 2\pi\norm f = \cdots = \abs{\left<\abs f, 2\pi\right>} = \int_{-\pi}^\pi \abs{f(t)}\, dt $$ and you are done.
{ "pile_set_name": "StackExchange" }
Q: If $f$ is the limit of polynomials with only real zeros, then all zeros of $f$ are real Problem Let $f$ be a non-constant entire function. Suppose that there is a sequence of polynomials ${P_n(z)}$, $n=1,2,...$ such that $P_n(z)$ converges uniformly to $f$ on every bounded set in $\mathbb{C}$ All zeros of $P_n$ are real. Prove that all zeros of $f$ are real Progress I have tried Hurwitz's theorem but I could not figure out how to go after that. By Hurwitz, I know that the sequence and $f $ have the same number of zeros in $B(a;R)$. But that's about it. Also, I think the sequence of zeros of $P_n$ converge to the zeros of $f$, with respect to their magnitude and multiplicity. But I really do not know how to show it. A: Suppose $u$ is a non real zero of $f$. There exists $R>0$ such that the closed disk with center $u$ and radius $R$ do not intersect the real line, and such that $f(z)\not =0$ on the circle $C$ centered at $u$ and of radius $R$. Then there exists $m>0$ such that $|f(z)|\geq m$ on $C$. Now there exists a large integer $N$ such that $\displaystyle |f(z)-P_N(z)|<\frac{m}{2}<m\leq |f(z)|$ on the circle $C$. By Rouché's theorem, $f$ and $P_N$ have the same number of zeroes in the disk $D(u,R)$. As $f$ have at least $u$ as zero, $P_N$ has a zero in $D(u,R)$, hence non real, contradiction.
{ "pile_set_name": "StackExchange" }
Q: How can I get the path to the current target directory in my build.sbt In my build.sbt I want to know the current target file. Something like this: val targetFile = ??? // /home/fbaierl/Repos/kcc/scala/com.github.fbaierl/target/scala-2.12/myapplication_2.12-1.2.3-SNAPSHOT.jar With target.value I only get the directory up until /target. Is there any way to get the full path to the resulting jar? A: What you need is the return value of compile:package. Run sbt "show compile:package" to see that it prints full path to the artifact you are building. If you just need the path without building the artifact, do sbt "show Compile / packageBin / artifactPath" In order to use this value in build.sbt, you have to define a task or setting like this val targetFile = taskKey[File]("shows target file") targetFile := { val path = artifactPath.in(packageBin).in(Compile).value //same as val path = (Compile / packageBin / artifactPath).value streams.value.log.info(path.toPath.toString) path } A value of any task in sbt cannot be directly assigned to a val like val someFile: File. You have to write your custom logic in terms of settings and tasks.
{ "pile_set_name": "StackExchange" }
Q: How to delete files from a folder which is placed in documents folder I want to delete the files which are placed in a folder(inside documents folder) of documents directory. I just listed or displayed all those files on the table view , can anybody tell me how can i do this using commitEditingStyle: method. Please help me how can i achieve this.Thanks in advance. A: You can use the below code to delete the file from document directory: NSError *error; NSFileManager *fileMgr = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *documents= [documentsDirectory stringByAppendingPathComponent:@"YourFolder"]; NSString *filePath = [documents stringByAppendingPathComponent:@"file2.txt"]; [fileMgr removeItemAtPath:filePath error:&error]
{ "pile_set_name": "StackExchange" }
Q: Is it possible to use custom icon with reactjs? I want to use my own designed custom icons in react which I have in both formats SVG and TTF. How can I do that? I want to put those icons in my navbar like a custom home icon for home button. A: I'm not sure how is you webpack configured to resolve svg and include them in your build, But I can give you two different approaches here: You can make separate SVG files generated from some tool in xml myIcon.svg <?xml version="1.0" encoding="UTF-8"?> <svg width="26px" height="26px" viewBox="0 0 26 26" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 50.2 (55047) - http://www.bohemiancoding.com/sketch --> <title>bus-start</title> <desc>Created with Sketch.</desc> <defs></defs> <g id="Booking-a-trip" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Verify" transform="translate(-113.000000, -312.000000)"> <g id="Group-3" transform="translate(63.000000, 144.000000)"> <g id="bus-start" transform="translate(51.000000, 169.000000)"> <circle id="Oval" stroke="#606C74" fill="#FFFFFF" cx="12" cy="12" r="12"></circle> <path d="M6,15.0585702 C6,15.6952627 6.2925,16.2668389 6.75,16.6647717 L6.75,17.952627 C6.75,18.3505599 7.0875,18.6761413 7.5,18.6761413 L8.25,18.6761413 C8.6625,18.6761413 9,18.3505599 9,17.952627 L9,17.2291128 L15,17.2291128 L15,17.952627 C15,18.3505599 15.3375,18.6761413 15.75,18.6761413 L16.5,18.6761413 C16.9125,18.6761413 17.25,18.3505599 17.25,17.952627 L17.25,16.6647717 C17.7075,16.2668389 18,15.6952627 18,15.0585702 L18,7.82342808 C18,5.29112834 15.315,4.92937123 12,4.92937123 C8.685,4.92937123 6,5.29112834 6,7.82342808 L6,15.0585702 Z M8.625,15.7820844 C8.0025,15.7820844 7.5,15.2973299 7.5,14.6968131 C7.5,14.0962963 8.0025,13.6115418 8.625,13.6115418 C9.2475,13.6115418 9.75,14.0962963 9.75,14.6968131 C9.75,15.2973299 9.2475,15.7820844 8.625,15.7820844 Z M15.375,15.7820844 C14.7525,15.7820844 14.25,15.2973299 14.25,14.6968131 C14.25,14.0962963 14.7525,13.6115418 15.375,13.6115418 C15.9975,13.6115418 16.5,14.0962963 16.5,14.6968131 C16.5,15.2973299 15.9975,15.7820844 15.375,15.7820844 Z M16.5,11.4409991 L7.5,11.4409991 L7.5,7.82342808 L16.5,7.82342808 L16.5,11.4409991 Z" id="Shape" fill="#606C74" fill-rule="nonzero"></path> </g> </g> </g> </g> </svg> Later in your component you can import it like : import myIcon from 'assets/myIcon.svg' // depending on your folder structure in render method: render(){ return ( <img src={myIcon} /> ) } Second approach you can make your svg in react using <svg>: here is the working codesandbox: Svg Icon + React
{ "pile_set_name": "StackExchange" }
Q: Create individual schemas for each complex type from large schema file using XSL Can we create multiple schemas ( One for each complex type) from a large xsd using xsl. Thanks in advance. I am able to create only one complextype output schema and I want the file name of the output to be the name of the complextype only. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> <xsl:template match="xsd:complexType"> <xsl:result-document method="xml" href="{local-name()}.xsd"> <test> <xsl:copy-of select="../@* | ."/> </test> </xsl:result-document> </xsl:template> A: The problem is in the use of local-name() to generate the name of the file. This will be the local name of the context element, which is in this case always "complexType". If the input has more than one complexType element this will actually cause an error while processing, as it is not allowed to generate more than one output using xsl:result-document with the same URI. From the spec: [ERR XTDE1490] It is a non-recoverable dynamic error for a transformation to generate two or more final result trees with the same URI. You probably want to use the name attribute of the element instead: <xsl:result-document method="xml" href="{@name}.xsd"> <!-- ... --> </xsl:result-document>
{ "pile_set_name": "StackExchange" }
Q: Error ClassCastException: java.net.Socket can not be cast to javax.net.ssl.SSLSocket in the getPage method of the WebClient object (HtmlUnit) I found the following error when trying to use the getPage method of the HtmlUnit WebClient object: java.lang.ClassCastException: java.net.Socket cannot be cast to javax.net.ssl.SSLSocket My Code: BrowserVersion firefox17WithUptoDateFlash = new BrowserVersion(BrowserVersion.FIREFOX_17.getApplicationName(), BrowserVersion.FIREFOX_17.getApplicationVersion(), BrowserVersion.FIREFOX_17.getUserAgent(), BrowserVersion.FIREFOX_17.getBrowserVersionNumeric(), new BrowserVersionFeatures[] { BrowserVersionFeatures.JS_FRAME_RESOLVE_URL_WITH_PARENT_WINDOW, BrowserVersionFeatures.STYLESHEET_HREF_EXPANDURL, BrowserVersionFeatures.STYLESHEET_HREF_STYLE_NULL }); PluginConfiguration plugin = new PluginConfiguration("Shockwave Flash", "Shockwave Flash 14.0 r0", "NPSWF32_14_0_0_145.dll"); plugin.getMimeTypes() .add(new PluginConfiguration.MimeType("application/x-shockwave-flash", "Adobe Flash movie", "swf")); firefox17WithUptoDateFlash.getPlugins().add(plugin); webClient = new WebClient(firefox17WithUptoDateFlash); webClient.getOptions().setJavaScriptEnabled(false); webClient.getOptions().setThrowExceptionOnScriptError(false); // Get the first page final HtmlPage page1 = webClient.getPage("https://www.example.com/login.html"); Note 1: I am trying to execute this code from an Action in Struts. Note 2: To put it here in the stack, I changed the url. But I'm trying to access a page login using https. Stack Trace: java.lang.ClassCastException: java.net.Socket cannot be cast to javax.net.ssl.SSLSocket at com.gargoylesoftware.htmlunit.HtmlUnitSSLSocketFactory.createSocket(HtmlUnitSSLSocketFactory.java:116) at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:168) at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:326) at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:610) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:445) at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72) at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:167) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1281) at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1198) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:307) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:376) at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:361) at br.com.yyyyy.xxxxx.integracao.LeitorAtendimento.<init>(LeitorAtendimento.java:58) at br.com.yyyyy.xxxxx.action.caldario.obrig.AbrirAct.executar(AbrirAct.java:122) at br.com.yyyyy.xxxxx.action.AjaxAction.execute(AjaxAction.java:61) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414) at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.ajaxanywhere.AAFilter.doFilter(AAFilter.java:46) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) I would just like to solve this. Can someone help me? A: The error has been resolved while updating the project dependencies.
{ "pile_set_name": "StackExchange" }
Q: Set the angle of a sprite in SpriteKit How would I set the angle of a sprite to 45 degrees? SKAction *rotate = [SKAction rotateByAngle: M_PI/4.0 duration:1]; only increases the angle by 45 degrees, what I want to do is have to SKSprite rotate however long it takes to get to 45 and then stop. Is there a method for that or will I have to hard code it? Thanks! A: The method you’re looking for is +rotateToAngle:duration:shortestUnitArc:, as in: SKAction *rotate = [SKAction rotateToAngle:M_PI_4 duration:1 shortestUnitArc:YES]; You can also just use +rotateToAngle:duration:, but that always rotates counterclockwise; this variant goes in whichever direction requires the least rotation. (also note that π/4 is already defined as a constant, M_PI_4; see usr/include/math.h)
{ "pile_set_name": "StackExchange" }
Q: Can't find certain function when calling R within java I'm trying to use R within Java, specifically within Processing. I want to use the readPNG function, but when I try to, R displays an error readPNG function can't be found. This is extremely weird because I have the png library active and if I try to use it directly from R this workouts just fine. I'm using the Rservepackage to connect java and R. Any advise would be very much appriciated. Here's part of the code I'm using if it helps. import org.rosuda.REngine.Rserve.*; import org.rosuda.REngine.*; double[] data; void setup() { size(300,300); try { RConnection c = new RConnection(); // generate 100 normal distributed random numbers and then sort them data= c.eval("readPNG('juego-11932.png')").asDoubles(); } catch ( REXPMismatchException rme ) { rme.printStackTrace(); } catch ( REngineException ree ) { ree.printStackTrace(); } } void draw() { background(255); for( int i = 0; i < data.length; i++) { line( i * 3.0, height/2, i* 3.0, height/2 - (float)data[i] * 50 ); } } A: Your Java code connects to a fresh R session so no packages are loaded. Hence you have to either use png::readPNG() or load the png package explicitly.
{ "pile_set_name": "StackExchange" }
Q: Why did the gods send the flood in The Epic of Gilgamesh? A previous question asks about the comparative timescale of the flood story that appears in the Book of Genesis and the one that appears in the Epic of Gilgamesh. An interesting apparent difference is that Noah was told to save himself by the same God who sent the flood, while Utnapishtim was told by Enki (Ea) who was only one of many gods. In the Biblical flood, God wishes to destroy both humanity and the earth, because of the corruption and violence that had engulfed both due to the evil of humans (Genesis 6:9). Was there a similar motivation for the Mesopotamian flood myth? Did the gods (presumably plural) wish to destroy both humanity and the earth, or only the former, and was it because of the evil of people? Did they all sanction Utnapishtim's survival as a "good man", or was he more of a "rebel" against the will of the gods? A: In the "standard version" of the Babylonian epic (see the translation by Andrew George, Penguin, 1999), it is not very clear. After the gods discover that Uta-napishti has survived the flood, Ea upbraids Enlil for sending the flood without first talking to the other gods (emphasis mine): Instead of your causing the Deluge, a lion could have risen, and diminished the people! Instead of your causing the Deluge, a wolf could have risen, and diminished the people! Instead of your causing the Deluge, a famine could have happened, and slaughtered the land! Instead of your causing the Deluge, the Plague God could have risen, and slaughtered the land! Apparently, Enlil send the flood to "diminish the people". But this raises another question: Why did Enlil want to "diminish" the people in the first place? The standard version of the epic keeps silent on this matter, so we need to turn to another Babylonian story, namely the The Epic of Atraḥasis (sometimes spelled Atram-hasis). This story tells us that the gods created man in order to delegate the hard work to them: "Create a human being, that he bear the yoke". Andrew George writes in the introduction to his Gilgamesh edition (page xliii - xliv): But the human race had another defect: it bred with great ease and rapidly became too numerous. As the poem of Atram-hasis relates, three times, at intervals of 1,200 years, the god Enlil tired of the relentless hubbub of the new creation, which kept him awake in his chamber. Each time he resolved to reduce the human population, first by plague, then by drought and finally by famine. Each time he was successful at first, so that the number of man were considerably diminished. In other words, the Deluge is Enlil's final solution to man's "relentless hubbub".
{ "pile_set_name": "StackExchange" }
Q: How can I change the default animation for a WinJS Flyout? I'd like for my winJS Flyout to slide rather than fade in. How can I modify the default animation? A: All the animation codes for the FlyOut lies in the js Ui.js in the javascript library which is actually not editable. Instead of creating a flyout you can always go for a div and animate it accordingly. On the other hand, Microsoft also provides the css class for different controls including flyout so you can add your css. A better option would be to use the Placement property of flyout and after show animate is say margin the way you would like for a slide animation. This is just a work around see if it can help you.
{ "pile_set_name": "StackExchange" }
Q: Android - Google Map API Key doesn't work I have a Google Map API Key (for Android app) and I restrainted the key as Android Apps. I want to use it this link: https://maps.googleapis.com/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=MY_API_KEY But I am getting error like this: { "error_message" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address 176.233.211.37, with empty referer", "results" : [], "status" : "REQUEST_DENIED" } I am researching this error for hours but I couldn't solve it. Thanks in advance. A: Keys with Android application restrictions are only used to authorize the use of native Google APIs for Android, such as those in Google Play Services, e.g., Maps Android API and Places API for Android, whereas the Elevation API web service, which you just access over HTTP(S), is not considered to be one of these. Just follow the Get a Key workflow to create a key that works together with the Elevation API, but as explained on the page and the best practices for securely using API keys, you should take care to protect your API key against abuse. As explained in the Get a Key article and the Google Maps APIs FAQ, web services allow setting IP address restrictions on API keys. However, if you intend to call the Elevation API directly from your Android app, you can't know the used IP addresses, so you must leave the key unrestricted. A safer approach would be to make the calls via your own proxy server, which allows you to set IP address restrictions on the key, and completely eliminates the need for including the API key in your mobile app, as you only need to configure it on the server.
{ "pile_set_name": "StackExchange" }
Q: How to deal with circle degrees in Numpy? I need to calculate some direction arrays in numpy. I divided 360 degrees into 16 groups, each group covers 22.5 degrees. I want the 0 degree in the middle of a group, i.e., get directions between -11.25 degrees and 11.25 degrees. But the problem is how can I get the group between 168.75 degrees and -168.75 degrees? a[numpy.where(a<0)] = a[numpy.where(a<0)]+360 for m in range (0,3600,225): b = (a*10 > m)-(a*10 >= m+225).astype(float) c = numpy.apply_over_axes(numpy.sum,b,0) A: If you want to divide data into 16 groups, having 0 degree in the middle, why are you writing for m in range (0,3600,225)? >>> [x/10. for x in range(0,3600,225)] [0.0, 22.5, 45.0, 67.5, 90.0, 112.5, 135.0, 157.5, 180.0, 202.5, 225.0, 247.5, 270.0, 292.5, 315.0, 337.5] ## this sectors are not the ones you want! I would say you should start with for m in range (-1125,36000,2250) (note that now I am using a 100 factor instead of 10), that would give you the groups you want... wind_sectors = [x/100.0 for x in range(-1125,36000,2250)] for m in wind_sectors: #DO THINGS I have to say I don't really understand your script and the goal of it... To deal with circle degrees, I would suggest something like: a condition, where you put your problematic data, i.e., the one where you have to deal with the transition around zero; a condition where you put all the other data. For example, in this case, I am printing all the elements from my array that belong to each sector: import numpy def wind_sectors(a_array, nsect = 16): step = 360./nsect init = step/2 sectores = [x/100.0 for x in range(int(init*100),36000,int(step*100))] a_array[a_array<0] = a_arraya_array[a_array<0]+360 for i, m in enumerate(sectores): print 'Sector'+str(i)+'(max_threshold = '+str(m)+')' if i == 0: for b in a_array: if b <= m or b > sectores[-1]: print b else: for b in a_array: if b <= m and b > sectores[i-1]: print b return "it works!" # TESTING IF THE FUNCTION IS WORKING: a = numpy.array([2,67,89,3,245,359,46,342]) print wind_sectors(a, 16) # WITH NDARRAYS: b = numpy.array([[250,31,27,306], [142,54,260,179], [86,93,109,311]]) print wind_sectors(b.flat[:], 16) about flat and reshape functions: >>> a = numpy.array([[0,1,2,3], [4,5,6,7], [8,9,10,11]]) >>> original = a.shape >>> b = a.flat[:] >>> c = b.reshape(original) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> b array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) >>> c array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
{ "pile_set_name": "StackExchange" }
Q: R DT datatable - conditional colour format for continuous value I would like to apply conditional formatting using the datatable function in R. Consider the following scenario: test <- data.frame( var1 = sapply(1:L, function(x) paste("<X>",paste0(x, letters, LETTERS, "\n", collapse=" "))), var2 = round(rnorm(L),2) ) test$var2 <- ifelse(test$var2 > 1, 1, test$var2) test$var2 <- ifelse(test$var2 < -1, -1, test$var2) test$tmp <- test$var2*255 test$R <- test$G <- 0 test$R <- ifelse(test$tmp < 0, round(abs(test$tmp)), test$R) test$G <- ifelse(test$tmp > 0, round(test$tmp), test$G) test$col <- paste0("rgb(",test$R,",",test$G,",0)") test <- test[,c("var1","var2","col")] datatable(test) I would like to font colour of var1 to take values from the col variables (which I don't actually need in the final data table). Is this possible to achieve? Many thanks in advance. A: Take a look to the DT doc 2.9 Escaping table content You will see that you can put HTML content to your table and by using escape=Fmake it readable in HTML. and you can do something like this on the varibles of your dataframe. apply(yourMatrix,2,function(x) ifelse(x>value, paste0('<span style="color:red">',x,'</span>'), paste0('<span style="color:blue">',x,'</span>') ) For example if you have a vector x <- c(1,2,3,4) and want value higher than 0 be red you will have [1] "<span style=\"color:red\">1</span>" [2] "<span style=\"color:red\">2</span>" [3] "<span style=\"color:red\">3</span>" [4] "<span style=\"color:red\">4</span>" and then datatable(yourMatrix, escape = FALSE)
{ "pile_set_name": "StackExchange" }
Q: I made a special store front for a mobile version of my site. How to redirect mobile devices there and also link back to the desktop site? I've setup a special mobile store/store front under a subdomain - www.m.mydomain.com according to this tutorial. I was going to put this code in the Miscellaneous scripts to make the system detect that a customer is connecting from a mobile device and forward the traffic to www.m.mydomain.com: I have a special responsive mobile store at m.MYdomain.com - how to make Magento detect mobile devices and forward the traffic to m.Mydomain.com? But now I'm thinking a better solution might just be through changing the .htaccess file as explained here. But I don't understand where to put that code into? Also - that post is from 2010. Is there something newer to go with given the development in the mobile devices and tablets? I also need to place a large button on the mobile site (at www.m.mydomain.com ) that would re-direct customers to the desktop version of the site (www.mydomain.com) if they choose to. What is the best way to do that? I mean - How can this work? Will it not be stuck in a loop? When the customer clicks the button that will send it to www.mydomain.com, won't the script once again detect that it is a mobile device and transfer the traffic back to www.m.mydomain.com ? I read about doing it with cookies but how exactly? And how would I set that button up? I am looking for a simple solution as in: take this code and put it here. Change this code here and you are done! :o) In my example my desktop site is: www.mydomain.com and my mobile is at: www.m.mydomain.com while my desktop store name and store front name is: mydomain.com and my mobile store name and store front name is: mmydomaincom Updated December 12th: Please don't tell me to load a different theme. I already have a nice responsive theme! This is not the problem. The reason I want to redirect to my mobile site (located at www.m.mysite.com) is that I have around 50 products on my desktop front page and a lot of things (such as text put on there by the SEO company) that are just taking up space and I don't need to display that clutter on mobile devices. I think that ordering on a mobile device should be fast and easy without unnecessary junk. That said - I am not trying to reinvent the wheel here. I need 2 things. 1. Detect the mobile device and if that is so - load www.m.mysite.com instead of www.mysite.com 2. Add a button for people who for whatever reason (maybe they are connected to a fast wifi connection) decide they want the desktop version instead and make it work when they click it to display www.mysite.com If you go to www.ebay.com on your mobile phone - it redirects to "m.ebay.com" Same with YouTube, Facebook, Twitter, LinkedIn...So don't tell me this is an old age approach. If these multi-billion dollar companies are doing it - it has some logic behind it.... A: https://stackoverflow.com/questions/3680463/mobile-redirect-using-htaccess http://wpandsuch.com/redirect-to-a-mobile-site-with-htaccess-and-set-a-cookie-to-break-redirect/ Magento Redirect to mobile website when on Smart Devices https://github.com/LimeSoda/LimeSoda_MobileRedirect https://github.com/sebarmeli/JS-Redirection-Mobile-Site https://github.com/vkathirvel/Magento-Extension-MobileDetect http://mobiledetect.net/ Multi store magento redirects to main store https://www.cloudways.com/blog/create-and-configure-multistore-magento-2/ Magento 2 with multiple domain names This is the best article so far: https://www.forgeonline.co.nz/magento-multistore-website-shopfront/ U need to set Cookie & Flag then it will work out. U can also refer to Magento Default .htaccess which provides already
{ "pile_set_name": "StackExchange" }
Q: Is it possible to use Ansible fetch and copy modules for SCPing files Im trying to SCP a .sql file from one server to another, and I am trying to use an Ansible module to do so. I stumbled across the fetch and copy modules, but I am not sure how to specify which host I want to copy the file from. This is my current Ansible file: firstDB database dump happens on seperate host - hosts: galeraDatabase become: yes remote_user: kday become_method: sudo tasks: - name: Copy file to the galera server fetch: dest: /tmp/ src: /tmp/{{ tenant }}Prod.sql validate_checksum: yes fail_on_missing: yes Basically, I want to take the dump file from the firstDB host, and then get it over to the other galeraDatabase host. How would I do this? Im order to use fetch or copy, I would need to pass it the second hostname to copy the files from, and I don't see any parameters to do that inside of the documentation. Should I be using a different method altogether? Thanks A: Try using the synchronize module with delegate_to, or if you don't have rsync then use the copy module. Some good answers relating to this topic already on stackoverflow. Also, check the ansible documentation for more info on the copy and synchronize modules along with the delegate_to tasks parameter. hth.
{ "pile_set_name": "StackExchange" }
Q: pass variables to a bootstrap modal I have a javascript confirm / cancel pop up box that dynamically unchecks a checkbox and also dynamically hides or shows a menu_entry that is part of a list that appears on the form, only when the user selects the ok button on the js confirm pop up box. I am now trying to change the js confirm to a bootstrap modal, but I am uncertain how to pass the variables to the bootstrap modal code and get the same functionality of the js confirm pop up box. Here is my working html code that has the call to the javascript confirm pop up box: {% for id, menu_entry, selected, item_count in menu_entries %} <div class="available_resume_details_height"> <input type="checkbox" style="width:1.5em; height:1.5em;" name="selected_items" value="{{ id }}" {% if selected %}checked="checked"{% endif %} onclick="checkboxUpdated(this, {{ item_count }}, '{{ menu_entry.label }}', {{ id }});" /> <span style="cursor: pointer;" rel="popover" data-content="{{ menu_entry.tooltip }}" data-original-title="{{ menu_entry.label }}" {{ menu_entry.label }} </span> </div> {% endfor %} Here is my javascript code to display the confirm pop up and uncheck the checkbox and show/hide the list entry: function checkboxUpdated(checkbox, count, label, id) { if (checkbox.checked) { $('#menu_entry_' + id).show(); } else { if (count > 0) { if (! confirm('{% trans "You have '+ count +' saved '+ label +'.\n\nAre you sure you want to delete your ' + count + ' saved ' + label +'?" %}')) { checkbox.checked = true; return; } } $('#menu_entry_' + id).hide(); } } Here is the new html code that has the call to the bootstrap modal. This does make the bootstrap modal appear: {% for id, menu_entry, selected, item_count in menu_entries %} <div class="available_resume_details_height"> <input type="checkbox" style="width:1.5em; height:1.5em;" name="selected_items" value="{{ id }}" {% if selected %}checked="checked"{% endif %} {% if selected %} data-confirm="{% blocktrans with entry_label=menu_entry.label %}Are you sure you want to remove your {{ item_count }} selected {{entry_label}} Resume Details?{% endblocktrans %}" {% endif %} /> <span style="cursor: pointer;" rel="popover" data-content="{{ menu_entry.tooltip }}" data-original-title="{{ menu_entry.label }}" {{ menu_entry.label }} </span> </div> {% endfor %} Here is my bootstrap modal code that is not working. I am unsure how to pass the variables and get the same functionality of the js confirm pop up: $(document).ready(function() { $('input[data-confirm]').click(function(ev) { var href = $(this).attr('href'); if (!$('#dataConfirmModal').length) { $('body').append('<div id="dataConfirmModal" class="modal modal-confirm-max-width" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true"><icon class="icon-remove"></icon></button><h4 class="modal-title" id="dataConfirmLabel">{% trans "Confirm" %} - {{ resume_detail_temp_value }}</h4></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">{% trans "Cancel" %}</button>&nbsp;&nbsp;<a class="btn-u btn-u-blue" id="dataConfirmOK">{% trans "Confirm" %}</a></div></div>'); } $('#dataConfirmModal').find('.modal-body').html($(this).attr('data-confirm')); $('#dataConfirmModal').modal({show:true}); $('#dataConfirmOK').click(function() { // handle checkbox function here. }); return false; }); }); The bootstrap modal should show/hide the list entry and only uncheck the checkbox when the confirm button is selected. EDIT: ADDED CHECKBOX CODE: <input type="checkbox" style="width:1.5em; height:1.5em;" name="selected_items" value="{{ id }}" {% if selected %}checked="checked"{% endif %} onclick="checkboxUpdated(this, {{ item_count }}, '{{ menu_entry.label }}', {{ id }});"/> A: Data attributes may help you pass the data you need in the function in a seamless manner and also help you avoid maintenance unfriendly inline JavaScript. Set up three event listeners as follows: function checkboxUpdated(checkbox, count, label, id) { var checkbox = this, count = $(checkbox).data('count'), label = $(checkbox).data('label'), id = checkbox.value; if(checkbox.checked) { $('#menu_entry_' + id).show(); } else { if (count > 0) { $('#confirm_modal').data('element', checkbox).find('div.modal-body p:first') .html( 'You have ' + count + ' saved ' + label + '. Are you sure you want to delete your ' + count + ' saved ' + label + '?' ).end() .modal('show'); return; } $('#menu_entry_' + id).hide(); } } $(function() { $(':checkbox').on('change', checkboxUpdated).change(); $('.confirm-no').on('click', function() { var element = $('#confirm_modal').data('element'); element.checked = true; }); $('.confirm-yes').on('click', function() { var element = $('#confirm_modal').data('element'), id = element.value; $('#menu_entry_' + id).hide(); }); }); DEMO
{ "pile_set_name": "StackExchange" }
Q: Programmatically accessing power Button android? Is there any way to programmatically access power button in android and even on IOS. A: Yes there is a way you can detect the press of power Button in android. Use this code public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) //KEYCODE.POWER determines the press of power Button { // do what you want with the power button return true; } return super.onKeyDown(keyCode, event); } A: Apple is not allowing you to use hardware components completely. They have added some restrictions. They provided the method in the app delegate i.e. applicationDidEnterBackground can catch the home button press .Also they has provided the the API's to access the camera,bluetooth etc .At least this much of API's I know which provided by apple publicly to access the hardware. You cannot access the other hardware elements in your application which not provided publicly by apple .If you are able to do this by any way then also your application will not approved by apple .
{ "pile_set_name": "StackExchange" }
Q: Python POST request can't find data attribute I'm trying to write a POST request to my Django REST API in Python, but it can't seem to find an attribute in the data section of the request. Here's the function that handles the request: def post(self, request, id, format=None): obj = self.get_object_or_404(id) operation = request.POST.get('operation', None) if operation == None: print "Operation was none, uh oh." return Response() else: print "It worked!" return Response() Now here's a POST ajax call in jquery. This one works. (Prints "It worked!") $.ajax({ method: 'POST', beforeSend: function(xhr) { xhr.setRequestHeader('Authorization', 'Token ' + token)}, url: url, data: { 'operation':-1, }, success: callback, error: function (jqXHR, textStatus, errorThrown) { console.log(textStatus); console.log(errorThrown); } }); Now here's the POST call in Python, or my attempt at it. The "url" and "token" variables are exactly the same: import json import requests url = <Same URL as above> token = <same token as above> data = { 'operation' : -1, } headers = { "Authorization": "Token " + token, } response = requests.post(url, data=json.dumps(data), headers=headers) This python requests does not work -- the app api prints "Operation was none, uh oh." Why would this happen? Am I not passing my data parameter correctly in the request? EDIT: Solved. Don't call json_dumps on the data, just pass it in as is. A: You don't need your data to be JSON encoded, as you're not doing anything with JSON in your view. Simply pass your dictionary directly to data: response = requests.post(url, data=data, headers=headers)
{ "pile_set_name": "StackExchange" }
Q: What windows SDK parts are needed to run sn.exe I want to run sn.exe in order to be able to run a delayed signed project in a server. If I install the whole windows SDK everything runs smoothly, but which exact part of SDK is needed? I am asking since the whole downloading is 460Mb and probably installs stuff that I don't need. A: After trial & error I found out that the only part needed is .net Development -> Tools.
{ "pile_set_name": "StackExchange" }
Q: What are the best practices of updating multiple divs with ActionCable in Ruby on Rails? I have a Ruby on Rails site. One of the index pages has a table with multiple rows. I also have a background job that does certain operations on each row, which takes about 5-10 seconds each. I would like to update the status for each row from 'Processing...' to 'Done' when the processing in the background job has completed. I was thinking to use Action Cable to do the update, but to date I only used Action Cable to update only one element on a page, never multiple elements. I was wondering what the correct way is to set-up my code to update the status in each row. Do I have to open a channel for each row separately? A: Definitely You can do so. And you don't have to open channel for each row. Just use the job id whose status has been changed and id corresponding row in table with same id. ActionCable.server.broadcast "job_status_update", job_id: 'xxxxx', status: 'complete' .html <table> <% jobs.each do |job|%> <tr> <td id="<%= job_id %>"> <%= job.status %> </td> </tr> <% end %> </table> .coffee App.chatChannel = App.cable.subscriptions.create { channel: "JobChannel" }, received: (data) -> $(data.job_id).innerText(data.status)
{ "pile_set_name": "StackExchange" }
Q: java.lang.IndexOutOfBoundsException: setSpan (118 ... 119) ends beyond length 118 I searched different questions but found nothing specific about my problem. I am changing text color by selecting color and works successfully however when I start deleting my edit text after typing a color text I get this error. myedittext.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { spannableString.setSpan(new ForegroundColorSpan(Color.parseColor(txtColor)), start, start+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } @Override public void afterTextChanged(Editable s) { } }); } I get the following error java.lang.IndexOutOfBoundsException: setSpan (118 ... 119) ends beyond length 118 at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1309) at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:680) at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:672) at com.apps.primalnotes.Fragments.EditorFragment$16.onTextChanged(EditorFragment.java:842) at android.widget.TextView.sendOnTextChanged(TextView.java:10611) at android.widget.TextView.handleTextChanged(TextView.java:10715) at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:14057) I am writing in two colors now like this now when i save it. it saves in pink color only and shows me like this but now when i save it again without any changes it save in the colors i wrote it A: The onTextChanged method is invoked to tell you that within CharSequence s, number of character count beginning at start have just replaced old text that had length before. What is happening is that when user presses backspace, start is at the upper limit of your charsequence i.e. If you had seven character before, start is 6 which is the same as the last element. You are doing start+1 which is always a number out of index range. myedittext.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(start < s.length() - 1 || count > before){ spannableString.setSpan(new ForegroundColorSpan(Color.parseColor(txtColor)), start, start+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } @Override public void afterTextChanged(Editable s) { } }); } Didn't get to try that code but it should work. It's just to show you an idea of what you are doing wrong and what you should be doing. A: When you delete text from the end of the string, the onTextChanged() method will be invoked with values representing the fact that the string is now shorter. It looks like you've written your code to always assume that the length will be longer; you're coloring in the just-typed character. But if you delete a character instead, you probably don't want to do this. You could add a check to make sure that count is greater than before, this at the very least will indicate that text was added to the string. if (count > before) { spannableString.setSpan(...); }
{ "pile_set_name": "StackExchange" }
Q: Jquery traversing and using selectors I'm reading a book and they show a couple of examples of how to select elements on the DOM, but they advise to always use Jquery trasversing methods over the selectors, for example if you have a list inside a div instead of using $("#myList > li") You should use $("#myList").children("li") Most of the time I use the first over the latter, the author says the 2nd is prefered and more efficient but he does not address why, can anyone explain the reason behind this? A: I think the difference in performance in that particular case comes down to this: document.querySelectorAll('#myList > li'); // VS document.getElementById('myList').children; And the performance test here: http://jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74 jQuery might check to see if it's a li given the selector but that's still going to be faster than querySelectorAll or Sizzle.
{ "pile_set_name": "StackExchange" }
Q: Bash. Create var with name of parameter and clean its value I want to create a var with a name of the param passed to the function. Is possible? And then filter it's content to remove possible spaces and single quotes before and after the data asked while read. Not working example: function test() { read $1 [[ ${1} =~ ^\'?(.*)(\'.*)?$ ]] && 1="${BASH_REMATCH[1]}" } test "testingvar" #At this point, the user sent some data to the read statement echo $testingvar For the data received in the read statement, we can receive some different strings. Let's check this 3 examples: /path/file '/path/file' /path/file' <-notice a space after the quote In all examples, the regexp must clean and let /path/file without possible quotes and spaces.... and as I said, all in a var called as the param of the function. Is a dream or can be done in bash? Thanks in advance. A: Here's one way to do it: fun(){ read -r "$1" declare -n var="$1" #use a nameref -- see `help declare` var=${var//[\' ]/} #clean the contents with string substitution } fun testingvar <<<"/path/file"; echo "$testingvar" fun testingvar <<<"'/path/file'"; echo "$testingvar" fun testingvar <<<" /path/ file'"; echo "$testingvar" This outputs: /path/file /path/file /path/file I.e., all the inputs got cleaned up and put into the variable whose named was passed via $1. Namerefs: Basically, namerefs are like auto-dereferenced pointers except they point to variables instead of addresses. They can be used as both l-values and r-values, and they are always autodereferenced after they're created. You can use namerefs to get around the fact that you can't assign to a variable variable, i.e. you can't do: foo=bar and then $foo=42 #illegal to assign 42 to bar, but you can do: declare -n foo=bar foo=42 #now bar is 42 Edit: If you want to remove all single quote and spaces but only at the beginning and end, you can use extglob: fun(){ local settings="$(shopt -p extglob)" #save extglob settings shopt -s extglob #set extglob read -r "$1" declare -n var="$1" #use a nameref -- see `help declare` var=${var##+([ \'])}; var=${var%%+([ \'])} eval "$settings" #restore extglob settings } fun testingvar <<<"/path/file"; echo "$testingvar" fun testingvar <<<"'/path/file'"; echo "$testingvar" fun testingvar <<<" /pa'th/ f'ile'"; echo "$testingvar" Edit 2 -- nameref-less version with eval: fun(){ local settings="$(shopt -p extglob)" #save extglob settings shopt -s extglob #set extglob local var read -r var; var=${var##+([ \'])}; var=${var%%+([ \'])} eval "$1=\$var" #avoids interpolating the var value for eval to avoid code injections via stdin eval "$settings" #restore extglob settings } fun testingvar <<<"/path/file"; echo "$testingvar" fun testingvar <<<"'/path/file'"; echo "$testingvar" fun testingvar <<<" /pa'th/ f'ile'"; echo "$testingvar"
{ "pile_set_name": "StackExchange" }
Q: bootstrap 3 thumbnail not repeating across the page I know I have done something silly, but still learning BS3, can anybody tell me why this page does not go across in three rows, but shows only one per row? I am using data driven information, code is below, and my problem can be viewed at http://ncpeachrecipes.com/index.php (I know this is usually frowned upon, hope this is ok) <div class="container-fluid"> <div class="row"> <div class="col-sm-6 col-md-4"> <div data-binding-id="repeat1" data-binding-repeat="DETAILS.data"> <div class="thumbnail"> <img class="img-circle" src="" data-binding-src="images/th_{{IMAGE}}" /> <div class="caption" align="center"> <h5><strong>{{NAME}}</strong></h5> <p><a href="show_recipe.php?ID={{ID}}" class="btn btn-primary" role="button">View the Recipe</a> </p> </div> </div> </div> </div> </div> </div> A: Its because you create a row and 1 column this means it will only create 1 colum. If you put the repeat in the column block it will create them alongside each other instead of underneath.
{ "pile_set_name": "StackExchange" }
Q: how to generate the "exchange" map a.k.a. "swap" map I am looking for an easy way to generate a simple linear map in Octave. The matrix I need, call it sigma(n), is defined by the following property: for all matrices A and B (both of dimension n) we have the equation: sigma(n) * kron(A,B) = kron(B,A) * sigma(n) For example, sigma(2) = [1,0,0,0; 0,0,1,0; 0,1,0,0; 0,0,0,1]. Is there a simple function for sigma(n)? For my purposes n will be fairly small, less than 50, so efficiency is not a concern. EDIT: now with the correct defining equation A: I realise it's bad form to answer one's own question, but with a small amount of head scratching I managed to generate the matrix explicitly: function sig = sigma_(n) sig = zeros(n^2,n^2); for i = 0:(n-1) for j = 0:(n-1) sig(i*n + j + 1, i+ (j*n) + 1) = 1; endfor endfor endfunction If anyone has a neater way to do this, I'm still interested.
{ "pile_set_name": "StackExchange" }
Q: php json decode a txt file I have the following file: data.txt {name:yekky}{name:mussie}{name:jessecasicas} I am quite new at PHP. Do you know how I can use the decode the above JSON using PHP? My PHP code var_dump(json_decode('data.txt', true));// var_dump value null foreach ($data->name as $result) { echo $result.'<br />'; } A: json_decode takes a string as an argument. Read in the file with file_get_contents $json_data = file_get_contents('data.txt'); json_decode($json_data, true); You do need to adjust your sample string to be valid JSON by adding quotes around strings, commas between objects and placing the objects inside a containing array (or object). [{"name":"yekky"}, {"name":"mussie"}, {"name":"jessecasicas"}] A: As I mentioned in your other question you are not producing valid JSON. See my answer there, on how to create it. That will lead to something like [{"name":"yekky"},{"name":"mussie"},{"name":"jessecasicas"}] (I dont know, where your quotes are gone, but json_encode() usually produce valid json) And this is easy readable $data = json_decode(file_get_contents('data.txt'), true);
{ "pile_set_name": "StackExchange" }
Q: How can I form dynamic navigation in my site I have a numerous amount of routes a user could take in my site, for example if they are one particular user, they get different navigation compared to another user. Dependant on what sector a user is, I have created a switch statement to capture these id's and construct their unique navigation titles: switch($sector_id){ /*chefs case 'f8721714d845eaa5222dcdb4dd642ceb29a280bc': $key_array= array('menus','news','staff','directory'); $url_array = array('/dashboard/menus/','/dashboard/news2/','/dashboard/staff2/','/dashboard/directory2/'); $name_array = array('Menus2','News2','Staff2','Directory2');'Recipe Stories', 'Blog', 'Events'); break;*/ //restaurants, pubs case 'c835ff2d2838b3ea45bdb729c641b73b4fa0098d': case '378ee5253530d7d02cea3012966deab24bcc5da2': $key_array= array('menus','news','staff','directory'); $url_array = array('/dashboard/menus/','/dashboard/news/','/dashboard/staff/','/dashboard/directory/'); $name_array = array('Menus','News','Staff','Directory'); break; So for example this is what I already have (hard coded): array( 'key' => 'profile', 'url' => '/dashboard/profile/', 'name' => 'Profile'), array( 'key' => 'picture', 'url' => '/dashboard/picture/', 'name' => 'Profile Picture'), array( 'key' => 'cv', 'url' => '/dashboard/cv/', 'name' => 'CV'). How can I dynamically construct the arrays above? I could use a for each statement, but their would have to be nested right? Any help would be appreciated. Thanks A: have you thought about creating static navigation html for each user type and just including the file base on user type? This would may be easier for you if you don't want to go "All Out" on dynamic navigation. Your hard coding your navigation anyway... or If you want to be truly dynamic, store all of your navigation items in a table (id, key, url, name) and create a join table for user type and navigation items. Join Table Columns: (usertype, navigation_id) Join Table SQL (not tested) SELECT * FROM usertype_navigation un JOIN navigation_items ni on un.navigation_id = ni.id WHERE un.usertype = "c835ff2d2838b3ea45bdb729c641b73b4fa0098d" This will return all the navigation items, loop through each record and spit out the html for the navigation item.
{ "pile_set_name": "StackExchange" }
Q: Django Admin form - How to override MultiSelectField class? I'm struggling with a rendering issue using Django Grappelli and Django Multiselectfield together in the admin-site. The checkbox labels are misaligned: Grappelli defines two CSS classes: .aligned label { display: block; float: left; padding: 0 10px 6px 0; width: 120px; } .aligned .vCheckboxLabel { display: inline; float: none; clear: both; margin: 0 0 0 10px; padding: 0; } If I change the checkbox class to ".vCheckboxLabel" in the browser console, the labels are aligned correctly and there's no issue. However, I can't for the life of me find how to set the class in the admin template. Using {% if field.is_checkbox %} in the Django admin template doesn't work because it's a multiselectfield, which is instead rendered as a list of checkboxes in {{ field.field }}. How can I specify or override the class for MultiSelectField checkboxes in the template or elsewhere? A: Add vCheckboxLabel in Model or Form class where you are defining that form. If you are defining form using Form class then use: myfield = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'vCheckboxLabel'})) If you are using models then add widget to the column. https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#specifying-widgets-to-use-in-the-form-with-widgets Alternate: For simplicity you can use java script on that page. Select checkbox class and change it to vCheckboxLabel. But it is not recommended.
{ "pile_set_name": "StackExchange" }
Q: How do I select records by comparing values in columns B, C among records with same value in column A? I want to select rows from my Postgres database that meet the following criteria: There are other rows with the same value in column A Those other rows have a specific value in column B Those other rows have a larger value in column C So if I had a table like this: User | Item | Date -----+------+------ Fred | Ball | 5/1/2015 Jane | Pen | 5/7/2015 Fred | Cup | 5/11/2015 Mike | Ball | 5/13/2015 Jane | Ball | 5/18/2015 Fred | Pen | 5/20/2015 Jane | Bat | 5/22/2015 The search might be "what did people buy after they bought a ball?" The output I would want would be: User | Item | Date -----+------+------ Fred | Cup | 5/11/2015 Fred | Pen | 5/20/2015 Jane | Bat | 5/22/2015 I've gotten as far as SELECT * FROM orders AS or WHERE or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);, which gives me all of Fred's and Jane's orders (since they ordered multiple things). But when I try to put additional limitations on the WHERE clause (e.g. SELECT * FROM orders AS or WHERE or.item = 'Ball' AND or.user IN (SELECT or2.second_id FROM orders AS or2 GROUP BY or2.user HAVING count(*) > 1);, I get something that isn't what I expect at all -- a list of records where item = 'Ball' that seems to have ignored the second part of the query. Thanks for any help you can provide. Edit: Sorry, I misled some people at the end by describing the bad approach I was taking. (I was working on getting a list of the Ball purchases, which I could use as a subquery in a next step, but people correctly noted that this is an unnecessarily complex/expensive approach.) A: I think this might give the result you are looking for: SELECT orders.user, orders.item, orders.date FROM orders, (SELECT * FROM orders WHERE item = 'ball') ball_table WHERE orders.user = ball_table.user AND orders.date > ball_table.date;
{ "pile_set_name": "StackExchange" }
Q: Transforming hash keys to an array I have a hash(%hash) with the following values test0 something1 test1 something test2 something I need to build an array from the keys with the following elements @test_array = part0_0 part1_0 part2_0 Basically, I have to take testx (key) and replace it as partx_0 Of course, I can easily create the array like the following my @test_array; foreach my $keys (keys %hash) { push(@test_array,$keys); } and I will get @test_array = test0 test1 test2 but what I would like is to get part0_0 instead of test0, part1_0 instead of test1 and part2_0 instead of test2 A: why not do easier my @array = ( keys %hash ) A: Looks like a good time to use the non-destructive /r option for substitutions. my @array = map s/^test(\d+)/part${1}_0/r, keys %a; For perl versions that do not support /r: my @array = map { s/^test(\d+)/part${1}_0/; $_ } keys %a: A: my @a; for (keys %hash) { push @a, 'part' . ( /^test([0-9]+)/ )[0] . '_0'; } But that just begs for map to be used. my @a = map { 'part' . ( /^test([0-9]+)/ )[0] . '_0' } keys %hash;
{ "pile_set_name": "StackExchange" }
Q: Parse limits uploads to 1MB. Looking for a workaround or an alternative platform I'm using Parse to host the backend for a mobile app that I am writing for Android and ios. I'm running into a major roadblock when trying to send data from the phone to a Parse cloud function that I've written, because Parse limits these requests to 1MB in size, which is not suitable for uploading images, etc. Basically, I'd have to make several requests to send the data, which would start to rack up charges. I've tried contacting the Parse community directly to see if there is a way around this, either by purchasing a paid account or programmatically, and no one has responded to me. So, does anyone here know of a workaround? Or, can anyone recommend a mobile app hosting provider other than Parse? I'm currently using them only because they make it so easy to get a prototype up and running, but I'm starting to have serious concerns about long-term use and scalability. Thanks for your help, really starting to pull out my hair on this one :| A: What are you trying to upload? I had issues uploading images taken with the phone, so I use a compression ratio of .25, which cut the file size down by about 1/8th, and I was able to upload.
{ "pile_set_name": "StackExchange" }
Q: How to use NSPredicate to filter NSMutableSet which contains composite object from other Class? Newbie Questions, I have 3 Class, 3 of them are subclass from NSOBject. Collection Class, have 2 properties, masterSong as NSMutableSet (strong, nonatomic) and listOfPlaylists as NSMutableArray (strong, nonatomic) Playlist Class Have 2 properties, playListName as NSString (copy, nonatomic) and songList as NSMutableArray (strong, nonatomic) 3 . Song Class Have 4 properties: title,artist,album, playtime as NSString (copy, nonatomic). masterSong will contain Song object, and listOfPlaylist will contain Playlist Object. while songList only store reference to Song Object. I want to create removeSong method for Collection Class by looking up Song for title,artist,or album inside masterSong. if looking up find 1, it will return NSSet, returned NSSet will take place as parameter in minusSet: method to remove the song from masterSong and all Playlist.songList. but, I can't figure out how to write down NSPredicate syntax to filter out .title or .album or .artist from masterSong which contain Song Object. here is what I got so far, for Collection.m - (void) removeSong: (NSString *)zSong{ //remove from reference playlist NSSet *targets = [self lookUpTitle:zSong]; if ([targets count]>0) { [self.masterSongs minusSet:targets]; for (Playlist *playlist in listOfPlaylists) { // -all objects converts the set into array. [playlist.songList removeObjectsInArray:[targets allObjects]]; } } else ; } Xcode throw exception when executing lookUpTitle method by saying that Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't look for value (title:Whole point of no return ,artist: Cafe Bleu ,album: CBSB ,playtime: 3:56) in string (What Do You Know); value is not a string - (NSSet *) lookUpTitle: (NSString *)aName { NSString *filters = @"%K CONTAINS [cd] %@"; NSPredicate *filter = [NSPredicate predicateWithFormat:filters, @"title", aName]; NSSet *result = [masterSongs filteredSetUsingPredicate:filter]; if ([result count] == 0) { NSLog(@"not found"); return nil; } else{ return result; } } I know that the main problem is at lookUpTitle method NSPredicate *filter = [NSPredicate predicateWithFormat:filters, @"title", aName]; NSSet *result = [masterSongs filteredSetUsingPredicate:filter]; the filter is filtering in a wrong way, while it should filtering NSString object (title, artist, or album) but masterSong is containing Song Object, how do I access title,artist,album in Song Object placed inside masterSong with NSPredicate? any other effective way for this condition? Predicate Programming Guide only show example set/array containing string I found other thread which has similar topic, but block is quite confusing to read, and still won't work in my case. Edit : additions to the partial code (Class.m method) as requested by responder #1 . here are some method in .m files related to my questions Main.m #import <Foundation/Foundation.h> #import "MusicCollection.h" #import "Playlist.h" #import "Song.h" int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... // NSLog(@"Hello, World!"); //create Songs Song *aSong = [[Song alloc]initWithTitle:@"Whole point of no return" withArtist:@"Cafe Bleu" withAlbum:@"CBSB" withPlaytime:@"3:56"]; Song *bSong = [[Song alloc]initWithTitle:@"Council Meetin'" withArtist:@"Cafe Bleu" withAlbum:@"CBSB" withPlaytime:@"4:00"]; Song *cSong = [[Song alloc]initWithTitle:@"Hayate" withArtist:@"Spitz" withAlbum:@"Indigo Chiheisen" withPlaytime:@"4:21"]; Song *dSong = [[Song alloc]initWithTitle:@"I have a Dreams" withArtist:@"WestLife" withAlbum:@"Season" withPlaytime:@"4:11"]; Song *eSong = [[Song alloc]initWithTitle:@"What Do You Know" withArtist:@"David Choi" withAlbum:@"Tomorrow" withPlaytime:@"3:46"]; //create playList Playlist *playlistA = [[Playlist alloc]initWithName:@"Playlist A"]; Playlist *playListB = [[Playlist alloc]initWithName:@"Playlist B"]; //store Song A & B to Playlist A and Song A,B,C to playlist B [playlistA addSong:aSong]; [playlistA addSong:bSong]; [playListB addSong:aSong]; [playListB addSong:bSong]; [playListB addSong:cSong]; // [playListB removeSong:eSong]; //Creating Master Collection MusicCollection *myCollection = [[MusicCollection alloc]initWithName:@"Library"]; [myCollection addPlaylist:playlistA]; [myCollection addPlaylist:playListB]; [myCollection addSong:eSong]; [myCollection addSong:dSong]; [myCollection removePlaylist:playListB]; [myCollection removeSong:aSong]; NSSet *container2 = [myCollection lookUpTitle:@"What"]; NSLog(@"%@",container2); // NSLog(@"%@",myCollection); } return 0; } Collection.m -(instancetype) initWithName: (NSString *)aName{ self = [super init]; if (self) { self.name = [NSMutableString stringWithString:aName]; self.listOfPlaylists = [NSMutableArray array]; self.masterSongs = [NSMutableSet set]; } return self; } -(instancetype) init{ return [self initWithName:@""]; } -(void) addPlaylist: (Playlist *)aPlayList{ if ([listOfPlaylists containsObject:aPlayList]==YES) { } else [listOfPlaylists addObject:aPlayList]; } -(void) removePlaylist: (Playlist *)aPlayList{ if ([listOfPlaylists containsObject:aPlayList]) { [listOfPlaylists removeObjectIdenticalTo:aPlayList]; } else{ ; } } - (void) displaySong{ NSLog(@"displaying all song in Collection"); NSLog(@" %@",self.masterSongs); } - (void) addSong :(Song *)aSong{ if (![masterSongs containsObject:aSong]) { [masterSongs addObject:aSong]; } } - (void) removeSong: (NSString *)zSong{ //remove from reference playlist NSSet *targets = [self lookUpTitle:zSong]; if ([targets count]>0) { [self.masterSongs minusSet:targets]; for (Playlist *playlist in listOfPlaylists) { // -all objects converts the set into array. [playlist.songList removeObjectsInArray:[targets allObjects]]; } } else ; } - (NSSet *) lookUpTitle: (NSString *)aName { NSString *filters = @"%K CONTAINS [cd] %@"; NSPredicate *filter = [NSPredicate predicateWithFormat:filters, @"title", aName]; NSSet *result = [masterSongs filteredSetUsingPredicate:filter]; if ([result count] == 0) { NSLog(@"not found"); return nil; } else{ return result; } } Playlist.m - (void) addSong :(Song *)aSong{ if (![songList containsObject:aSong]) { [songList addObject:aSong]; } } - (void) removeSong: (Song *)aSong{ if ([songList containsObject:aSong]){ [self.songList removeObjectIdenticalTo:aSong]; } } - (instancetype) initWithName: (NSString *)aPLName{ self = [super init]; if (self) { self.songList = [NSMutableArray array]; self.playlistName = aPLName; } return self; } - (instancetype)init{ return [self initWithName:@""]; } Song.m - (instancetype) initWithTitle: (NSString *)aTitle withArtist: (NSString *)anArtist withAlbum: (NSString *)aAlbum withPlaytime: (NSString *)playingTime{ self = [super init]; if (self) { self.artist = [NSMutableString stringWithString:anArtist]; self.album = [NSMutableString stringWithString:aAlbum]; self.title = [NSMutableString stringWithString:aTitle]; self.playtime = [NSMutableString stringWithString:playingTime]; } return self; } -(instancetype) init{ return [self initWithTitle:@"null" withArtist:@"null" withAlbum:@"null" withPlaytime:@"null"]; } A: You have overloaded the meaning of -removeSong: and it has caused you confusion. In Playlist, -removeSong: takes a Song instance, but in Collection, -removeSong: takes a NSString instance for the song title. The problem is you pass an instance of a Song to the version which expects an NSString. - (void)removeSong:(NSString *)zSong { NSSet *targets = [self lookUpTitle:zSong]; // … } Should either be - (void)removeSong:(Song *)aSong { NSSet *targets = [self lookUpTitle:aSong.title]; // … } or - (void)removeSongWithTitle:(NSString *)aTitle { NSSet *targets = [self lookUpTitle:aTitle]; // … } I changed the name of the second version of the method to clearly show what the expected parameter is. When you want to use the second version, you would pass the message [myCollection removeSongWithTitle:aSong.title]
{ "pile_set_name": "StackExchange" }
Q: Exact Same Script Works On One Page But Not Another I am building an iOS7 WebApp with a template that I found here: http://c2prods.com/2013/cloning-the-ui-of-ios-7-with-html-css-and-javascript/ I have written some JavaScript/jQuery that fades a picture out and fades a toolbar in, toolbar first. I have a blank test page where I tested the script. It works perfectly. Then I copy and paste the EXACT SAME code into the real page and the jQuery never seems to load for whatever reason. It gives me an error saying the following: Uncaught TypeError: Object # has no method 'fadeOut' The fading is supposed to occur after 3 seconds. The idea is that this is a splash screen. Here is my JS/jQuery: $(document).ready(function() { fadeAwaySplash(); navFadeIn(); //Insert More Functions Here }); function fadeAwaySplash() { //setTimeout(function() { $("#splash-screen").fadeOut(); //}, 3000); } function navFadeIn(){ setTimeout(function() { $("nav").fadeIn(); }, 3000); } Here is my CSS: nav { position: fixed; bottom: 0; width: 100%; height: 49px; text-align: center; background-color: rgba(248, 248, 248, 0.9); background-image: linear-gradient(180deg, rgb(200, 199, 204), rgb(200, 199, 204) 50%, transparent 50%); background-size: 100% 1px; background-repeat: no-repeat; background-position: top center; z-index: 100; display: none; } #splash-screen { position: absolute; z-index: 999999; width: 100%; height: 100%; min-width: 100%; min-height: 100%; max-width: 100%; max-height: 100%; } Here is my HTML: <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> <img src="/img/ipadSplash.png" id="splash-screen"> Any help is greatly appreciated. Thanks in advance, Emanuel A: Great! scragar's answer worked! All I had to do is replace the $'s with "jQuery" (without the quotation marks). Although I had to replace the setTimeout with .delay(3000) Thanks!
{ "pile_set_name": "StackExchange" }
Q: How to search the Play Store by permissions? How do I specify that I do not wish to see apps that require for example internet access? Or to only show apps that use a specific permission? A specific repository with search on its webpage? An app that provides searching the Play Store? A: How it currently CAN be done During my morning routine reading my RSS feeds, I stumbled on a review at N-Droid, discussing an app named APEFS. This app is developed by German students (hence its description on the Playstore is in German, even if you set the language to English). But for our non-German readers, a short description here: Basically, APEFS is an alternative front-end to the Google Playstore. You browse the playstore as you do with the original app, and search it the same. But when on the results list1, an advanced filter2 comes into play: As the second screenshot shows, you can select what permissions your wanted app is permitted to have (checkbox marked), and what permission it should not have (checkbox unchecked). However: While this can be used to filter out apps with unwanted permissions (e.g. show only apps whitout the Internet permission), you can not restrict your results to the opposite (e.g. show only apps with Internet permission). The app clearly targets at users concerned about their privacy/security -- and according to the review (I just found it a couple of minutes ago, so I could not test it yet) it does a very good job. EDIT: As it's already a year ago, and the promise on the APEFS Homepage (GTransed to English, as their own English version doesn't have that statement in the first paragraph) seems not to be fulfilled anytime soon (the app is still offline): Please consider the web-based solution from my other answer as an alternative meanwhile. A: More than two years have passed since this question was asked. Still, there's no „official solution” available. Despite its promises, APEFS (introduced in my previous answer over a year ago) has not returned. So I decided to create my own solution: For almost 4 years now, I maintain listings of „Android apps by purpose”, i.e. grouped by their use cases. In march, I started moving them to my own server. All MetaData are stored in a database on that server, and so finally I was able to setup a search by permissions. Search Mask to find "apps by category and permission" (click image for larger variant) You can select between 1 and 5 categories here (note that selecting a „parent category” automatically includes all its „children”), plus one or more permissions. Default presets are for finding „permission-friendly apps” – so if you're after such a candidate, you can simply submit the form after having made described selections. This should make it easy to e.g. find a PIM app which does not request the Internet permission (to keep your personal data on your device). However, the opposite is possible as well: If you e.g. want to investigate what good NFC can do for you, select the up to 5 categories you're interested in, then the NFC permission, switch the „Permissions” dropbox to „include”, and optionally the sorting to „by rating, descending” (to get the best-rated apps first). When in doubt, there's that little question-mark icon in the top-right corner, providing you with some „online help”. But that's not all. As I've explained in the second paragraph, apps in my lists are grouped by their „purpose”, i.e. what you need them for. So apps with comparable functionality should appear next to each other: Category with app details (source: the help page (hence the „red numbers”); click image for larger variant) So you can compare them not only by rating, but also pick the one requesting less permissions (number in the box; in above image indicated by a „red 6”) or, if possible, without any concerns (no red border around the box). Clicking the app's name reveals some more details, as shown. And there are many „easter-eggs” (i.e. MouseOver events) – again, be pointed to the help page. Full disclosure: As initially indicated, the described site was designed by me, built by me, filled by me with its content, and is further maintained by me. It's available bi-lingual (English/German), free of any charge (this includes: no cookies, Flash-cookies, whatever), etc. This question here at Android.SE was one of the reasons I've set it up. Further be aware of the fact that this doesn't cover the entire „playstore collection”. As of today, there are a little over 10,000 apps recorded in the database (which is probably a little less than 1% of what's on Play – unless you don't count the crap, fakes, and useless apps on Play, then my records might cover about 10% ☺). Still I hope (and think) it's already a useful resource you'll enjoy. A: Why currently  this can't be done When a developer performs the upload of his application to Google Play, the application manifest file gets read to a database, from where the search for apps is performed. To allow searching for applications based on their permissions, one would have to access the database and collect data that concerns the application manifest node <uses-permission>, previously read from the AndroidManifest.xml file, where the developer has declared his application permissions. While this seems quite straightforward, Google API does not provide means to this end: Strictly, Google Play does not filter based on <uses-permission> elements. From the Filters on Google Play Filtering based on Manifest Elements - <uses-permission>. Elaborating Essentially, Google Play Store uses the application manifest file to automatically apply filters based on the user's device, hardware specifications, country, carrier, etc. All of this is done silently without the intervention of any search parameters. A user either from Google Play or third party search engines, can limit the results after they get automatically filtered by Google, based on personal preferences like excluding paid apps; limit the results to apps that are compatible with the user devices, among others. But there's no way to interfere with the filters applied by Google. Even if, some how, we get to that part, the API essentially isn't prepared/designed to filter based on permissions as mentioned above.
{ "pile_set_name": "StackExchange" }
Q: Java8: how to copy values of selected fields from one object to other using lambda expression I'm trying to understand new functions of java8: forEach and lambda expressions. Trying to rewrite this function: public <T extends Object> T copyValues(Class<T> type, T source, T result) throws IllegalAccessException { for(Field field : getListOfFields(type)){ field.set(result, field.get(source)); } return result; } using lambda. I think it should be something like this but can't make it right: () -> { return getListOfFields(type).forEach((Field field) -> { field.set(result, field.get(source)); }); }; A: The loop can be replaced by getListOfFields(type).forEach((field) -> field.set(result, field.get(source))); However, that forEach method call has no return value, so you still need to return result; separately. The full method: public <T extends Object> T copyValues(Class<T> type, T source, T result) throws IllegalAccessException { getListOfFields(type).forEach((field) -> field.set(result, field.get(source))); return result; } EDIT, I didn't notice the issue with the exception. You'll have to catch the exception and throw some unchecked exception. For example: public <T extends Object> T copyValues(Class<T> type, T source, T result) { getListOfFields(type).forEach ( (field) -> { try { field.set(result, field.get(source)); } catch (IllegalAccessException ex) { throw new RuntimeException (ex); } }); return result; } A: You could use functions in the following way: @FunctionalInterface interface CopyFunction<T> { T apply(T source, T result) throws Exception; } public static <T> CopyFunction<T> createCopyFunction(Class<T> type) { return (source, result) -> { for (Field field : getListOfFields(type)) { field.set(result, field.get(source)); } return result; }; } And then: A a1 = new A(1, "one"); A a2 = new A(2, "two"); A result = createCopyFunction(A.class).apply(a1, a2); The CopyFunction functional interface is pretty much the same as BinaryOperator except that BinaryOperator doesn't throw an exception. If you want to handle exceptions within a function, you can use the BinaryOperator instead.
{ "pile_set_name": "StackExchange" }
Q: Groovy: Plucking values out of a Map and into a Set Groovy here. I have a class Fizz: @Canonical class Fizz { Integer id String name } In my program, I compose a map of them by their integral id field: // Here, each key of the map corresponds to the Fizz#id of its value // example: // allFizzes[1] = new Fizz(1, 'Foobar') // allFizzes[3004] = new Fizz(3004, 'Wakka wakka') Map<Integer,Fizz> allFizzes = getSomehow() I would know like to obtain a set of "bad" Fizzes whose name equals the string 'Sampson'. My best attempt: Set<Fizz> badFizzes = allFizzes.find { k,v -> v.equals('Sampson') } However this gives me runtime errors: Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '24={ "id": 24, "name": "Sampson" }, ' with class 'java.util.LinkedHashMap$Entry' to class 'java.util.Set' So it looks like even though I'm specifying v.equals('Sampson') that Groovy is strill trying to save a Map key,value pair into a Set. What's the Grooviest solution here? A: You'll want to use findAll (which returns a Collection) in place of find (which returns an Object). findAll applies the passed in closure to each EntrySet in the Map and returns a new collection with elements that satisfied your closure's criteria. You can then call values() on this newly returned collection. Map<String, Integer> myMap = ["fizzStrength":29, "fizzQuality": 123, "fizzFizziness":3] Set<Integer> found = myMap.findAll { k,v -> v > 4 }.values() // returns [29, 123]
{ "pile_set_name": "StackExchange" }
Q: Degrees of comparison I believe, both variants are possible: friendlier / more friendly; and the friendliest / the most friendly. I'd like to know what is used in every day speech more often and which is more formal. A: Though grammatically both friendlier and more friendly are correct. But formally since friendly is a 2- syllable word, more friendly is more acceptable. However, if we go by figures, Google's survey for published works can help you. https://books.google.com/ngrams/graph?content=friendlier%2Cmore+friendly&year_start=1800&year_end=2008&corpus=6&smoothing=3&share=&direct_url=t1%3B%2Cfriendlier%3B%2Cc0%3B.t1%3B%2Cmore%20friendly%3B%2Cc0 According to this survey, friendlier has become more popular after mid-80s
{ "pile_set_name": "StackExchange" }
Q: Why doesn't my code write to a text file? I want to know why my code doesn't write to a text file, JVM doesn't throw any exceptions... public class AlterData { Data[] information; File informationFile = new File("/Users/RamanSB/Documents/JavaFiles/Information.txt"); FileWriter fw; public void populateData(){ information = new Data[3]; information[0] = new Data("Big Chuckzino", "Custom House", 18); information[1] = new Data("Rodger Penrose", "14 Winston Lane", 19); information[2] = new Data("Jermaine Cole", "32 Forest Hill Drive", 30); } public void writeToFile(Data[] rawData){ try{ fw = new FileWriter(informationFile); BufferedWriter bw = new BufferedWriter(fw); for(Data people : rawData){ bw.write(people.getName()+ ", "); bw.write(people.getAddress() + ", "); bw.write(people.getAge() +", |"); } }catch(IOException ex){ ex.printStackTrace(); } } public static void main(String[] args){ AlterData a1 = new AlterData(); a1.populateData(); a1.writeToFile(a1.information); } } A: Try calling bw.flush() after writing the data and then you have to close the stream with bw.close() after flushing. When closing the BufferedWriter it would be best to put the close statement into a finally block to ensure that the stream is closed, no matter what. You should also look into using a try with resource. This makes use of the AutoCloseable feature of BufferedWriter as follows: try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("path/to/file")))) { // Do something with writer } catch (IOException e) { e.printStackTrace(); } That way java will make sure that the stream is closed for you when leaving the try body, no matter what happens.
{ "pile_set_name": "StackExchange" }
Q: Getting into android networking, HTTP library preference? I'm finding at least 3 different ways to submit an HTTP request from an Android application. They are: The obvious Android.net.http AndroidHttpClient The Apache library org.apache.http.client.HttpClient The Java.net URLConnection Which one should I use for an application that wants to get JSON server database results for later parsing? Is any one faster? What are the advantages to each? Thanks in advance! A: You should use HttpUrlConnection. The android team plans to support it better in the future. But don't just take my word for it: http://android-developers.blogspot.com/2011/09/androids-http-clients.html A: My advice would be to use the Android option. The Android developers made things like that to try to simplify tasks that would normally be more difficult than needed if you used the Apache and Java options. That's just what I would do though. If you're more comfortable with something else you can always try that out? Up to you though. Just my two cents.
{ "pile_set_name": "StackExchange" }
Q: Compile time default values for static members of static struct defined inside classes I would like to have a design suggestion from you. I have a set of classes in C++, every class has a bunch of variables (double and int) which determines the behavior of the algorithms they implement. Something like this: class Foo { private: double value1, value2, etc...; public: void setOptions(double val1, double val2); /* and here other methods... */ }; class Bar { private: double value1, value2, etc...; public: void setOptions(double val1, double val2); /* and here other methods... */ }; I would like to group all these option variables in a single class, so that is possible to dynamically change the variables of the options in the instances of the classes, but I would also like to give the value variables a default value as initialization. I would like that the options variables are different and set with a default value at compile time for every class. I adopted the following approach: // Options.h class Options { public: Options(); static struct FooOptions { static double option1; static double option2; } fooOptions; static struct BarOptions { static double option1; static double option2; // etcetera } barOptions; }; and then in the Foo and Bar classes I use the value Options::FooOptions::option1 and so on. The problem here is that I can't initialize those value statically. I'm used to initialize static member outside in the .cpp file, but in my .cpp // Options.cpp Options::FooOptions::option1 = 1.0; I get the following compiler error: error: expected constructor, destructor, or type conversion before ‘=’ token On other hand if I initialize them inside the constructor: // Options.cpp Options::Options() { FooOptions::option1=1.0; } I get undefined reference error when I try to access it from my main. I think the problem here is that I have two nested static structures. What can be here an optimal solution for this kind of design? How would you implement a class that acts only as container of double and int values to use inside classes as parameters of algorithms? A: // Options.cpp Options::FooOptions::option1 = 1.0; Add the missing "double" :-) double Options::FooOptions::option1 = 1.0; should do it.
{ "pile_set_name": "StackExchange" }
Q: Sql Server Performance Degradation in moving from 2005 to 2008 I have sql server 2005 setup for my performance bench marking exercise and I have put same database on another server which has sql server 2008 and exact replica in terms of hardware configuration. Sql server memory allocation is also same in both servers. But my benchmarking results are worse on 2008 than 2005. Will somebody help me to find the reasons for performance degradation in sql server 2008. What are the thing I need to take care, or parameters to set for getting the better or same result sets. A: Did you rebuild indexes and statistics after setting up the database on SQL Server 2008? It's mentioned on MSDN (see "Next steps") ... Next Steps After you upgrade to SQL Server ... Update statistics — To help optimize query performance, we recommend that you update statistics on all databases following upgrade. Use the sp_updatestats stored procedure to update statistics in user-defined tables in SQL Server databases. ...
{ "pile_set_name": "StackExchange" }
Q: Replacing fragment does not work properly I am replacing an fragment with the following code. Why isn't onCreateView invoked immediately after the commit? I am executing a Async task after this, however I get a nullpointerexception since the references in ResultListFragment is not resolved yet since the OnCreateView method hasn't been runned. Why? and how could I fix this? if (mResultListFragment == null) { mResultListFragment = new ResultListFragment<Question>(); } getFragmentManager() .beginTransaction() .addToBackStack("result") .replace(R.id.someContainer, mResultListFragment) .commit(); // AsyncTask stuff here A: Call FragmentManager's executePendingTransaction to block the main thread until your fragment has been committed, without calling this the commit is done asynchronously
{ "pile_set_name": "StackExchange" }
Q: Auto eager load navigation property in the DbContext Is there a way to tamper with the DbContext in order to auto eager load a specific Navigation property when the entity is requested in a query? (no lazy loading). Entity Framework 5 Example: var supremeEmployee = context.Employees.FirstOrDefault(x => x.EmployeeId == 42); and the returned model would come back pre-populated with the "Department" navigation property. A: Depends on what your model looks like. If you're using interfaces or inheritance you could add a function to your DbContext class with a generic constraint on that type that always includes the navigation property. In my experience though you're usually better off not doing that, performance wise. I prefer to load into anonymous types just the fields i need in the moment. In the most basic way you could do this: public class Department { public int Id { get; set; } } public class Employee { public int Id { get; set; } public Department Department { get; set; } } public class MyContext : DbContext { protected DbSet<Employee> Employees { get; set; } public IQueryable<Employee> LoadEmployees() { return Employees.Include(p => p.Department); } }
{ "pile_set_name": "StackExchange" }
Q: sending script files through json format in Python I'm working on IMB IOT application.It basically allow to sends command or data from one device to another in json format. I have developed python script which sends an string from one system and gets received on another system. And it's working well. Now I want to deal with script file in place of string. But the thing is IBM IOT supports only json format to dump payloads. Is there any way to convert files to json format ? i wrote a script which tries converting files to json format, doesn't work that perfect ! is there any other way to do that? code to convert a script file to json code output of code Is there any way to make it work better? here is the code which try sending the file to another system through json format act =input("Enter the key->") file_path = input("\nPlease enter the file path->") payload1 ={"computer1" : act} update_file= open(file_path,'rb') payload ={} payload['context'] = base64.b64decode( update_file.read()) client.publishEvent("status",json,payload1,payload) print(act) print("command sent") time.sleep(2) and on the other another computer def commandcallback(event): filename = payload['recieved_one] filedata = base64.base64decode(payload['context']) update_file =open(filename,'wb') update_file.write(filedata) update_file.close() A: You can implement a custom message codec to transmit the file content in any way you choose. See the doc topic covering use of custom message formats. https://ibm-watson-iot.github.io/iot-python/custommsg/ ... Bear in mind these docs are for the pending 1.0 release (wiotp-sdk rather than ibmiotf), but this aspect it works pretty much the same in the 0.4 release of ibmiotf. It depends what you want to get out of this how I would recommend handling this: Are you only interested in simple text files? You can write a simple codec that will send data as a simple string in utf-8 (or whatever your choice of encoding be), register the codec for format string utf8 And use that as the format string when sending events so that the clients know this is how you want to encode and decide the message payload, which means the event.data you get on the application would be the UTF-8 encoded string of the file content. Do you want to use this as a way to transmit any file, regardless of content-type? You could write the codec such that it simply passes a raw bytearray suitable for writing direct to file on the application processing the event (e.g using the format string raw), in this case event.data would give you a bytearray that can be easily used to write to file on the receiving application. Hopefully that gives you some ideas of what you can do with the custom message support built into the client library. I’ll have a look at adding these as examples in the repo when I’m back in the office on Monday.
{ "pile_set_name": "StackExchange" }
Q: Какие объекты можно помещать в сессию? Может ли помещаемый в HttpContext.Current.Session объект содержать в себе вложенные объекты? Какие еще накладываются ограничения? Что с конструкторами классов, они вызываются при извлечении из сессии? A: Объекты, помещаемые в сессию должны реализовать интерфейс ISerializable, то есть обычно достаточно просто пометить соответствующим атрибутом (Serializable) ваши классы, которые будут храниться в сессии. При извлечении объектов из сессии используется механизм десериализации.
{ "pile_set_name": "StackExchange" }
Q: How to start a block scalar with a blank line? When I try and start a block scalar in YAML with a blank line, it complains when it gets to the next line that has the same indentation as the empty line, "syntax error: expected <block end>, but found '<scalar>'" (but curiously, not about lines that are further indented). What am I missing here? Complains (about done): - | export $e done Works: - | # export $e done I've tried leaving the spaces out of the first line, adding 4 additional spaces to the first line (so it aligns with export), and adding 4 additional spaces and including an indentation indicator (- |4), all to no avail. Backstory This is for an AWS CloudFormation template, and the previous line is part of a !Join and I need a newline before export $e. If there are other ways to address this than putting the blank line at the start of the block scalar, that would be fine too, but I'm still curious. A: You should use a block indentation indicator to explicitly indicate how much the data is indented. In your case this indentation is two (2): the start of the line with done relative to the column in which the item indicator (-) is located. - |2 export $e done Normally the parser calculates the indentation based on the first non space on the first line of the literal (or folded) scalar, if this line has more whitespace that others, or has no non-space text at all, you need to "help" the parser with the block indentation indicator.
{ "pile_set_name": "StackExchange" }
Q: Explicit Casting operator and Polymorphism I have a small issue with polymorphism and explicit casting. Here is the problem: I have 3 public classes: package x; public class Shape { public void draw(){ System.out.println("draw a Shape"); } } package x; public class Circle1 extends Shape { } package x; public class Circle2 extends Circle1 { @Override public void draw () { System.out.println("draw Circle2"); } } And my Demo class is: package x; public class Demo { public static void main (String[] args) { Shape s1=new Circle2(); s1.draw(); ((Shape)s1).draw(); } } The output of this code is: draw Circle2 draw Circle2 I understand the polymorphic behavior of s1.draw() that invokes the draw() method on Circle2. The last line confuses me, when I do explicit casting on s1 like so: ((Shape)s1), it means that the expression ((Shape)s1) is a reference of type Shape because of the explicit casting,right? And if that is so, why then the code ((Shape)s1).draw(); invokes the draw() method in Circle2 and not the one in Shape? Thanks :) A: Casting does not change what the object is, it simply changes how the compiler should look at that object. So even if you "think" of a Circle to be "just a shape" it still stays a Circle. The only way for a Circle1 to call Shape's draw would be from within Circle1 by a call to super.draw()
{ "pile_set_name": "StackExchange" }
Q: Two sub query with one common column I change the original question to be more specific. I have two parameters that I want to get as output after running this query. The two parameters requires different criteria. So to do that I built this kind of query: SELECT m.count, ytd.count FROM ( SELECT COUNT( id ) count FROM table WHERE date BETWEEN BETWEEN '2010-06-01' AND '2010-06-30' ) m, (SELECT COUNT( id )count FROM table WHERE date BETWEEN BETWEEN '2010-01-01' AND '2010-06-30' ) ytd This kind of query returns the count and work well. but now i want to dig a little bit more in and to see those two parameter by dep. Now i get the total : Param1 Param2 39 85 I wish to get this table : Dep Param1 Param2 1 5 7 2 34 78 and so on.. Hope that now its more clear. Thanks! A: SELECT m.dep, m.count, ytd.count FROM ( SELECT COUNT( id ) count, Dep FROM table WHERE date BETWEEN BETWEEN '2010-06-01' AND '2010-06-30' group by dep ) m, Join ( SELECT COUNT( id )count, dep FROM table WHERE date BETWEEN BETWEEN '2010-01-01' AND '2010-06-30' group by dep ) ytd ON ytb.dep=m.dep Thanks for the help
{ "pile_set_name": "StackExchange" }
Q: Python Pandas groupBy condition I have a dataframe from a CSV file with the following format: "name";"elapsed" "etl_A";6.13e-05 "stl_A";0.0001 "etl_B";0.001 "stl_B";0.0003 "etl_C";23.2e-06 ... With Python Pandas, I would like to convert the dataframe to the following format: benchmark_name;etl_elpased;stl_elapsed A;6.13e-05;0.0001 B;0.001;0.0003 C;23.2e-06;... I've done simmilar such things in other languages using the respective groupBy method combined with a regex expression to extract the benchmark name, however I'm new to Python as well as Pandas. From my understanding, Pandas groupBy function behaves diferently than other languages and I haven't been able to figure it out. I've tried something like this: def extract_benchmark_name(full_name: str) -> str: return regex.match(full_name).groups()[1] df = pandas.read_csv(source, header=0, sep=';') etl_df = df['etl' in df['name']] stl_df = df['stl' in df['name']] etl_df['name'] = etl_df['name'].apply(extract_benchmark_name) stl_df['name'] = stl_df['name'].apply(extract_benchmark_name) however this doesn't look right and also gives me various errors. Ultimately, I want to combine this with matplotlib to generate a bar chart like this with normalized values comparing etl and stl: Any help to do either of these two tasks would be greatly appreciated, thank you! A: Try (updated with @TrentonMcKinney improvement): df[['Benchmark', 'Type']] = df.name.str.split('_', expand=True) ax = df.pivot('Type','Benchmark','elapsed').plot.bar(color=['b','r'], width=.95, edgecolor='w', alpha=.8) ax.legend(loc='lower center', bbox_to_anchor=(.5,1.01), ncol=2, frameon=False) Output:
{ "pile_set_name": "StackExchange" }
Q: REST Web Service with Netty Is there any recommended way to implement REST Web Service with Netty? I am a RESTEasy user, is there a way to use Netty and RESTEasy together? A: Looks like since version 2.3.4 of RESTEasy it supports an embedded Netty container: http://docs.jboss.org/resteasy/docs/2.3.4.Final/userguide/html/RESTEasy_Embedded_Container.html#d0e2690
{ "pile_set_name": "StackExchange" }
Q: How to set the Ripple effect I am working on an app which has a minSdkVersion = 16, and I need to use the ripple effect in Lollipop and above and some other effect on lower version. Is there any way to do this using XML? A: No need to design any other layout just for specific version just Use this library for ripple effect https://github.com/traex/RippleEffect compile line for this library dependencies { compile 'com.github.traex.rippleeffect:library:1.3' }
{ "pile_set_name": "StackExchange" }
Q: CSS appears different on Windows than Mac When I view the site in Windows then most of the site, like the top text, right contact details, nav text and welcome text appear lower than they do on the mac. Mac browsers show the CSS as it should be. Please help me out... Mac screenshot Windows screenshot HTML <body> <div id="wholepage"> <header> <div id="nav_top"> <nav> <h1 class="slogan">Steel & Fabrication Specialists</h1> </nav> </div> <a href="index.html"><img class="kks_logo" src="KKSLogo.png" border="0" alt="KKS Services Ltd logo"></a> <h1 class="logo">KKS</h1> <h2 class="logosub">Services Ltd</h2> <h3 class="head_contact">0113 2826946</h3> <h3 class="head_contact"><a href="contact.html">[email protected]</a></h3> <nav id="main_nav"> <ul id="nav_main"> <li><a class="current_index" href="index.html">HOME</a></li> <li><a class="domestic" href="domestic.html">DOMESTIC</a></li> <li><a class="automation" href="automation.html">AUTOMATION</a></li> <li><a class="commercial" href="commercial.html">COMMERCIAL</a></li> <li><a class="contact" href="contact.html">CONTACT</a></li> </ul> </nav> <img class="rivot" src="rivot.png" alt="KKS Services Ltd Rivot"/> <img class="rivot2" src="rivot.png" alt="KKS Services Ltd Rivot"/> <img class="rivot3" src="rivot.png" alt="KKS Services Ltd Rivot"/> <img class="rivot4" src="rivot.png" alt="KKS Services Ltd Rivot"/> </header> <section> <article> <img class="railings" src="index_rail.png" alt="KKS Services Gates and Railings"/> <div id="welcome"> <h1 class="welcome">Welcome</h1> CSS .slogan{ position: relative; width: 960px; margin-left: auto; margin-right: auto; left: 10px; top: -5px; color: white; font-size: 1.3em; font-family: 'Aldrich', cursive; } .kks_logo{ position: relative; top: 50px; } .head_contact{ font-family: 'Aldrich', sans-serif; position: relative; left: 10px; top: -175px; font-size: 1.5em; text-align: right; } ul#nav_main li{ display: inline; padding: 26px; } ul#nav_main li a{ text-decoration: none; color: white; font-family: 'Aldrich', sans-serif; font-size: 1.4em; position: relative; top: 13px; } #welcome{ position: relative; top: -267px; left: 70px; width: 840px; height: 35px; background-color: rgba(0,0,0,0.6); border-radius: 5px; } #welcome h1{ color: white; font-family: 'Aldrich', sans-serif; padding: 10px; font-size: 200%; position: relative; top: -5px; left: 10px; } Thank You! A: The problem is the different default styles that browsers have. Neither way of displaying your page is wrong, they are just different. You have compensated for the default styles of one browser, which makes it look quite different in all other browsers. As long as you compensate for the default styles instead of overriding them, you will have that problem. For example, for the .slogan style you should set the top and bottom margin to zero, instead of using relative positioning to compensate for the default margin. You can use line-height to center the text vertically in the element, instead of moving it up or down to place it in the center. Example: .slogan{ width: 960px; line-height: 30px; margin: 0 auto; color: white; font-size: 1.3em; font-family: 'Aldrich', cursive; }
{ "pile_set_name": "StackExchange" }
Q: OrderBy on a Nullable with a default value in Entity Framework We are migrating some code to use Entity Framework and have a query that is trying to sort on a Nullable field and provides a default sort value is the value is null using the Nullable.GetValueOrDefault(T) function. However, upon execution it returns the following error: LINQ to Entities does not recognize the method 'Int32 GetValueOrDefault(Int32)' method, and this method cannot be translated into a store expression. The query looks like: int magicDefaultSortValue = 250; var query = context.MyTable.OrderBy(t => t.MyNullableSortColumn .GetValueOrDefault(magicDefaultSortValue)); From this answer I can see that there is a way to provide "translations" within your EDMX. Could we write a similar translation for this coalescing function? NOTE: When I tried, the ?? coalescing operator instead of GetValueOrDefault in the query it does work. So perhaps whatever makes that work could be leveraged? A: I believe you found your answer. When you use ??, EF generates SQL using a CASE to select your sort value if the value is null, and then sorts on that. MyTable.OrderBy (t => t.MyNullableSortColumn ?? magicDefaultSortValue).ToArray(); will generate the following sql: -- Region Parameters DECLARE p__linq__0 Int = 250 -- EndRegion SELECT [Project1].[MyColumn1] AS [MyColumn1], [Project1].[MyNullableSortColumn] AS [MyNullableSortColumn] FROM ( SELECT CASE WHEN ([Extent1].[MyNullableSortColumn] IS NULL) THEN @p__linq__0 ELSE [Extent1].[MyNullableSortColumn] END AS [C1], [Extent1].[MyColumn1] AS [MyColumn1], [Extent1].[MyNullableSortColumn] AS [MyNullableSortColumn] FROM [dbo].[MyTable] AS [Extent1] ) AS [Project1] ORDER BY [Project1].[C1] ASC As an aside, I would recommend getting LINQPad which will let you work with your EF models and view the sql being generated. Also, it is helpful to know about the EntityFunctions class and SqlFunctions class as they provide access to several useful functions.
{ "pile_set_name": "StackExchange" }
Q: How to repeat each element in a list and the whole list as well? Consider a list as list={1,2,3,4}; I can repeat the list n times in this way listRepeated=Flatten@Table[list, n]; Question 1: Can it be done in a faster way? I also want to repeat each element n times. For example, for n=3 the above list should become listElementRepeated={1,1,1,2,2,2,3,3,3,4,4,4}; I can do this in this way listElementRepeated=Flatten@Gather[listRepeated]; Question 2: Can it be done in a better and faster way? A: Repeated list: SeedRandom[666]; list = RandomInteger[{1, 100000}, 1000000]; n = 3; akglr = Join @@ {list}[[ConstantArray[1, n]]]; // RepeatedTiming // First aCE = PadRight[list, n Length[list], list]; // RepeatedTiming // First aCarl = Flatten[Outer[Times, ConstantArray[1, n], list]]; // RepeatedTiming // First aMajis = Flatten@Developer`ToPackedArray[Table[list, n]]; // RepeatedTiming // First aHenrik = Flatten[ConstantArray[list, n]]; // RepeatedTiming // First aMajis0 = Flatten@Table[list, n]; // RepeatedTiming // First aMajis0 == aMajis == aCE == aCarl == aHenrik == akglr1 == akglr2 0.0050 0.0059 0.0087 0.011 0.010 0.21 Duplicating list elements: bkglr = Flatten@Transpose[{list}[[ConstantArray[1, 3]]]]; // RepeatedTiming // First bHenrik = Flatten[Transpose[ConstantArray[list, 3]]]; // RepeatedTiming // First bCarl = Flatten@Outer[Times, list, ConstantArray[1, 3]]; // RepeatedTiming // First bJason = Fold[Riffle[#1, list, {#2, -1, #2}] &, list, Range[2, n]]; // RepeatedTiming // First bkglr == bHenrik == bCarl == bJason 0.016 0.016 0.017 0.022 True Tests ran on a Intel 4980HQ, 16 GB 1600 MHz DDR3L SDRAM. A: Here's my suggestion: list = {1, 2, 3, 4}; repeat[list_, n_] := PadRight[list, n Length[list], list] repeat[list, 3] {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4} repeat2[list_, n_] := Sequence @@ ConstantArray[#, n] & /@ list repeat2[list, 3] {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4} repeat solves the first question, and repeat2 solves the second question. Performance-wise repeat is quite a bit slower than Flatten@ConstantArray[list, n], as suggested by Henrik. repeat2 I think should be rather fast. It also has the advantage that I don't apply Flatten or do any such thing at the end, so it will work even if the list elements are themselves lists. A: f1 = Join @@ {#}[[ConstantArray[1, #2]]] &; f1[Range[4], 3] {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4} f2 = Flatten@Transpose[{#}[[ConstantArray[1, #2]]]] &; f2[Range[4], 3] {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4}
{ "pile_set_name": "StackExchange" }
Q: question about continuous function everyone I have question can any one answer prove that $f(x)= |x|$ is continuous on $\Bbb R$? by using the definition of continuous. Thank you A: By definition, $f$ is continuous at $x_0$ if for every $ \epsilon>0$ there exists $\delta > 0$ such that $|x-x_0| < \delta \implies |f(x)-f(x_0)| < \epsilon$. So take any $\epsilon >0$, let $\delta=\epsilon$ and suppose $|x-x_0| < \delta$. Then $|f(x)-f(x_0)| =||x|-|x_0|| \le |x-x_0| < \epsilon$, by the reverse triangle inequality.
{ "pile_set_name": "StackExchange" }
Q: VMware tools ported for Fedora 11 VM? With Fedora 11 being so new and using a newer Linux kernel, the VMware tools don't compile so can't be directly used in an F11 VM. I can get around to porting them myself, but has anyone else run into this and fixed it yet? A: There is a patch available for vmware for Fedora11
{ "pile_set_name": "StackExchange" }
Q: Obtain the first entry of JSON I have this JSON in a URL: {"success":true,"rgInventory":{"6073259621":{"id":"6073259621","classid":"1660549198","instanceid":"188530139","amount":"1","pos":1}}} I need obtain the first entry after rgInventory. The problem is the problem is that suppose that I don't know that there are "6073259621". How I can obtain it without know what there? I try this but don't work: $obj = json_decode(file_get_contents($url), true); $obj2 = json_decode(json_encode($obj['rgInventory']), true); $obj3 = json_decode(json_encode($obj2), true); echo $obj3; A: Here's a simple way to get the key and the value (array) using each(): $data = json_decode(file_get_contents($url), true); list($key, $val) = each($data['rgInventory']); echo $key; print_r($val); Yields: 6073259621 Array ( [id] => 6073259621 [classid] => 1660549198 [instanceid] => 188530139 [amount] => 1 [pos] => 1 ) But I just noticed that the id is the same as the key, so not really needed.
{ "pile_set_name": "StackExchange" }
Q: is there a way to have make always perform an action when a Makefile exits? How can I ensure that make performs an action when the Makefile exits, even if a target rule fails? I'm hoping for something like Perl's END capabilities. My Makefile needs to do this get a signing ticket compile code, sign some release the signing ticket So my Makefile looks like this: TICKET=$(shell get-ticket) all: somerule anotherrule lastrule somerule: compile foo sign foo --ticket $(TICKET) anotherrule: more deps etc compile bar lastrule: release --ticket $(TICKET) but lastrule won't do. The problem is that I can't use a final target rule to release the ticket, because if there's an error the rule won't be made. A: You'll have to use recursion. Something like this: ifndef TICKET .DEFAULT: @ ticket=`get-ticket` || exit 1; \ $(MAKE) $@ TICKET="$$ticket"; ret=$$?; \ release --ticket "$$ticket"; \ exit $$ret else all: somerule anotherrule ...etc... endif
{ "pile_set_name": "StackExchange" }
Q: Playing media from ftp server I have a question re access to ftp server from a media player (hardware, not the windows media player). I think about buying a router with ftp server function to take the load off from my quite old pc. However I am concerned that my media player which gets access to the same ftp folders via samba (running on the same veteran pc) will not be able to access the ftp directly. So as a result of my upgrade I will end up having to mount the ftp folders from router to my old pc and sharing these folders again via samba with the media player... Which does not look like a good idea to me as my motivation is to offload my pc first... However that makes me think that the router producers should have had in mind media sharing so there should be an easy and conventional option of setting the ftp router speak to the media player. Can someone please enlighten me how to do this? A: Most home gateway routers that support drive sharing do support SMB. Some also support AFP for Macs and DLNA for media streaming. The ones that support FTP usually have it for WAN file transfers when the ISP blocks SMB. Are you sure your router only supports FTP? What is the make and model? Sounds like you just need to upgrade to a decent router instead of a bargain-basement model. Or maybe see if an open source firmware distro supports it, like DD-WRT, OpenWrt, or Tomato.
{ "pile_set_name": "StackExchange" }
Q: Ring of order $n$ is isomorphic to $\Bbb Z/n\Bbb Z$, with $n$ square-free Let $R$ be a ring of order $n$ and suppose $n$ has no square in its prime decomposition. How do I see that $R$ is isomorphic to $\Bbb Z/n\Bbb Z$? I bet that the map $\Bbb Z \to R, \, 1\mapsto 1_R$ descends to an iso $\Bbb Z/n\Bbb Z \to R$ but I don't see how $n$ having no squares implies the desired descent. A: Reduce the problem to the following lemma If $p \mid n$, $\mathbb{Z} / p \mathbb{Z} \to R / pR$ is well-defined an isomorphism Since all of the ideals $pR$ and $qR$ are coprime, the Chinese remainder theorem asserts $$ R = R / nR \cong \prod_{p \mid n} \mathbb{Z} / p \mathbb{Z} \cong \mathbb{Z} / n \mathbb{Z} $$ If $n$ is not squarefree, there are examples where $\mathbb{Z} / p^2 \mathbb{Z} \to R / p^2 R $ is not an isomorphism.
{ "pile_set_name": "StackExchange" }
Q: Gerbes on the multiplicative group Let $k$ be an arbitrary field with absolute Galois group $\Gamma$. The group $\text{Hom}(\Gamma,\mathbb{Q}/\mathbb{Z})$ injects into $H^2(\mathbb{A}^1 \setminus \{ 0 \},\mathbb{G}_m)$, as one can see e.g. by computing $\text{Ext}^2(\mathbb{G}_m,\mathbb{G}_m) = H^2(\Gamma,\mathbb{Z})$. If such a gerbe coming from $\Gamma \to \mathbb{Q}/\mathbb{Z}$ extends to $\mathbb{A}^1$, is it necessarily trivial? It's not clear to me because there are some weird gerbes on $\mathbb{A}^1$ if $k$ is not perfect. A: I believe the answer is "yes, such a gerbe is necessarily trivial". We first note that for any field $K$ and open subscheme $U$ of $\mathbb{A}^{1}_{K}$, the inclusion $\operatorname{Br}(U) \subseteq \mathrm{H}_{et}^{2}(U,\mathbb{G}_{m}) $ is an isomorphism. Also the coboundary $\operatorname{Hom}(\Gamma,\mathbb{Q}/\mathbb{Z}) \simeq \mathrm{H}^{1}(\Gamma,\mathbb{Q}/\mathbb{Z}) \to \mathrm{H}^{2}(\Gamma,\mathbb{Z})$ is an isomorphism since $\mathrm{H}^{i}(\Gamma,\mathbb{Q}) = 0$ for $i \ge 1$. The Leray spectral sequence for $\mathbb{A}^{1}_{k} \to \operatorname{Spec} k$ is \begin{align} \mathrm{E}_{2}^{p,q} = \mathrm{H}^{p}(\Gamma,\mathrm{H}_{et}^{q}(\mathbb{A}^{1}_{k^{\mathrm{sep}}},\mathbb{G}_{m})) \implies \mathrm{H}_{et}^{p+q}(\mathbb{A}^{1}_{k},\mathbb{G}_{m}) \end{align} with differentials $\mathrm{E}_{2}^{p,q} \to \mathrm{E}_{2}^{p+2,q-1}$. This and the analogous spectral sequence for $\mathbb{A}^{1}_{k} \setminus \{0\} \to \operatorname{Spec} k$ gives a commutative diagram $\require{AMScd}$ \begin{CD} 0 @>>> \operatorname{Br}(k) @>\xi_{1}>> \operatorname{Br}(\mathbb{A}^{1}_{k}) @>\xi_{2}>> \mathrm{H}^{0}(\Gamma,\operatorname{Br}(\mathbb{A}^{1}_{k^{\mathrm{sep}}})) \\ @. @V\rho_{1}VV @V\rho_{2}VV @V\rho_{3}VV \\ 0 @>>> \operatorname{Br}(k) \oplus \mathrm{H}^{2}(\Gamma,\mathbb{Z}) @>>\xi_{1}'> \operatorname{Br}(\mathbb{A}^{1}_{k} \setminus \{0\}) @>>\xi_{2}'> \mathrm{H}^{0}(\Gamma,\operatorname{Br}(\mathbb{A}^{1}_{k^{\mathrm{sep}}} \setminus \{0\})) \\ \end{CD} where the $\rho_{i}$ are induced by restriction along the open immersion $\mathbb{A}^{1}_{k} \setminus \{0\} \subset \mathbb{A}^{1}_{k}$. Here both rows are exact because $\operatorname{Pic}(\mathbb{A}^{1}_{k^{\mathrm{sep}}}) = 0$ and $\operatorname{Pic}(\mathbb{A}^{1}_{k^{\mathrm{sep}}} \setminus \{0\}) = 0$ (so that $\mathrm{E}_{2}^{p,1} = 0$ for $p \ge 0$ for both spectral sequences). With respect to the above commutative diagram, the question may be rephrased as follows: Suppose $\alpha_{1}' \in \mathrm{H}^{2}(\Gamma,\mathbb{Z})$ is such that $\xi_{1}'(\alpha_{1}') = \rho_{2}(\alpha_{2})$ for some $\alpha_{2} \in \operatorname{Br}(\mathbb{A}^{1}_{k})$. Is $\xi_{1}'(\alpha_{1}')$ necessarily $0$? For such $\alpha_{1}',\alpha_{2}$ we have $\rho_{3}(\xi_{2}(\alpha_{2})) = \xi_{2}'(\rho_{2}(\alpha_{2})) = \xi_{2}'(\xi_{1}'(\alpha_{1}')) = 0$. Since $\mathbb{A}_{k}^{1}$ and $\mathbb{A}_{k^{\mathrm{sep}}}^{1}$ are regular Noetherian (and also since $\mathrm{H}^{0}(\Gamma,-)$ is left exact), the restriction maps $\rho_{2}$ (and hence also $\rho_{1})$ and $\rho_{3}$ are injective. Thus $\xi_{2}(\alpha_{2}) = 0$, thus there exists some $\alpha_{1} \in \operatorname{Br}(k)$ such that $\xi_{1}(\alpha_{1}) = \alpha_{2}$; then $\xi_{1}'(\rho_{1}(\alpha_{1})) = \rho_{2}(\xi_{1}(\alpha_{1})) = \rho_{2}(\alpha_{2}) = \xi_{1}'(\alpha_{1}')$, but injectivity of $\xi_{1}'$ implies $\alpha_{1}' = \rho_{1}(\alpha_{1})$; thus both $\alpha_{1} = 0$ and $\alpha_{1}' = 0$ since $\alpha_{1}',\rho_{1}(\alpha_{1})$ are in different summands of $\operatorname{Br}(k) \oplus \mathrm{H}^{2}(\Gamma,\mathbb{Z})$; thus $\xi_{1}'(\alpha_{1}') = 0$ as well.
{ "pile_set_name": "StackExchange" }
Q: Is it necessary to dispose variables in finally block in static methods? This example below I found while looking answer to another quiestion. Here that guy disposes response in finally block. Is it really necessary? Is it a GC's work in this case? public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response) { try { if (response.IsSuccessStatusCode) return; var content = await response.Content.ReadAsStringAsync(); throw new SimpleHttpResponseException(response.StatusCode, content); } finally { response.Content?.Dispose(); } } A: The whole point of using IDisposable is to clean up unmanaged resources that the GC can't clean up on its own. So no, you can't just let the GC clean it up because, by definition, it can't.
{ "pile_set_name": "StackExchange" }
Q: BeautifulSoup + xlwt : Put the content of a HTML table in Excel I am trying (with a little python script) to put the content of a HTML table from a online webpage in an Excel sheet. All is working well, except the "Excel thing". #!/usr/bin/python # --*-- coding:UTF-8 --*-- import xlwt from urllib2 import urlopen import sys import re from bs4 import BeautifulSoup as soup import urllib def BULATS_IA(name_excel): """ Function for fetching the BULATS AGENTS GLOBAL LIST""" ws = wb.add_sheet("BULATS_IA") # I add a sheet in my excel file Countries_List = ['United Kingdom','Albania','Andorra'] Longueur = len(Countries_List) number = 1 print("Starting to fetch ...") for Countries in Countries_List: x = 0 y = 0 print("Fectching country %s on %s" % (number, Longueur)) number = number + 1 htmlSource = urllib.urlopen("http://www.cambridgeesol.org/institutions/results.php?region=%s&type=&BULATS=on" % (Countries)).read() s = soup(htmlSource) **tableauGood = s.findAll('table') try: rows = tableauGood[3].findAll('tr') for tr in rows: cols = tr.findAll('td') y = 0 x = x + 1 for td in cols: hum = td.text ws.write(x,y,td.text) y = y + 1 wb.save("%s.xls" % name_excel)** except (IndexError): pass print("Finished for IA") name_doc_out = raw_input("What do you want for name for the Excel output document ? >>> ") wb = xlwt.Workbook(encoding='utf-8') print("Starting with BULATS Agents, then with BULATS IA") #BULATS_AGENTS(name_doc_out) BULATS_IA(name_doc_out) -- So anything is going in the Excel Sheet, but when I print the content of the var ... I see what I should see ! I'm trying to fix it since one hour but I still don't understand what's going one. If some of you can give me a hand, It should be VERY nice. A: I have try your application. And I am very sure that the output of td.text is same as the excel file. So what's your question? If the content is not what you want, you should check the usage of BeautifulSoap. Further more, you may need to do following: for td in cols: hum = td.text.replace("&nbsp;", " ") print hum ws.write(x,y,hum)
{ "pile_set_name": "StackExchange" }
Q: Distinct all columns in a datatable and store to another datatable with LINQ I have a datatable with more than 10 columns and I would like to distinct all columns and then store a result to another datatable. Is there any way to distinct all columns in a datatable by using LINQ without naming all ones? I've tried as the code below but it just give one row. Please give me any advice for this case. DataTable dtPurchaseOrder = new DataTable(); DataTable dt = new DataTable(); dt.Columns.Add("PONumber"); dt.Columns.Add("Customer"); dt.Columns.Add("Address"); dt.Rows.Add("PO123456", "MH", "123"); dt.Rows.Add("PO123456", "MH", "123"); dt.Rows.Add("PO654321", "AB", "123"); dt.Rows.Add("PO654321", "AB", "123"); foreach (DataRow r in dt.Rows) { var lstPO = (from row in dtPurchaseOrder.AsEnumerable() select row.Field<string>("PONumber")).Count(); if (lstPO == 0) dtPurchaseOrder.Rows.Add(r.ItemArray); } dtPurchaseOrder.AcceptChanges(); A: Solution 1: Simplest solution would be DefaultView.ToTable. dt.DefaultView.ToTable(true, "PONumber", "Customer", "Address"); Solution 2 : Another alternative would be using Linq statement to filter distinct rows and then looping them as required. var result = dt.AsEnumerable() .Select(row => new { PONumber = row.Field<string>("PONumber"), Customer = row.Field<string>("Customer"), Address = row.Field<string>("Address") }).Distinct(); Solution 3 : Traditional way of checking existence with PrimaryKey defined. var ponum = dtPurchaseOrder.Columns.Add("PONumber"); var cust = dtPurchaseOrder.Columns.Add("Customer"); var address = dtPurchaseOrder.Columns.Add("Address"); dtPurchaseOrder.PrimaryKey = new[] {ponum, cust, address}; dt.Rows.Add("PO123456", "MH", "123"); dt.Rows.Add("PO654321", "AB", "123"); dt.Rows.Add("PO654321", "AB", "123"); foreach (DataRow r in dt.Rows) { var exisiting = dtPurchaseOrder.Rows.Find(r.ItemArray); if (exisiting == null) { dtPurchaseOrder.Rows.Add(r.ItemArray); } } Working Sample
{ "pile_set_name": "StackExchange" }
Q: Need help understanding how my app starts I have an app that plays Tic-Tac-Toe and Connect Four in the command line. Some of the code is boilerplate that I didn't write, and I'm having trouble understanding how it works. When I run npm start, Connect Four plays as expected, but there is no way to play Tic-Tac-Toe. I want the user to choose to play either game. Ideally I would prompt the user, but having a command for each game would be fine. There's a short server.js file that looks like this: require('babel-polyfill'); require('babel-register'); require('.'); And in my package.json, I have main: "./connect4/index.js". As far as I can tell, this is all of the code relevant to starting the app. I apologize for the vague question. But the app isn't very complicated, so hopefully it makes some sense. A: There's two ways you could do this. The first is by using the npm package inquirer which will allow you to prompt the user in the command line. The alternative would be to use nodes built-in process.argv which is a property that will return an array with all the command line arguments you passed. Note that when using this, position [0] will default to the location of node on your machine, and position [1] will default to the current file location. To access custom arguments you will have to start at position [2] etc. So you could write logic that will run tic-tac-toe or connect 4 based on the value of argv at position 2. so somewhere in your code you would something like if (process.argv[2] === "tick-tack-toe") { console.log("do tick tack toe logic"); }else if (process.argv[2] === "connect-4") { console.log("do connect 4 logic"); } Hope this helps. You can read more about process.argv here https://nodejs.org/docs/latest/api/process.html#process_process_argv and here's a link to inquirer on github https://github.com/SBoudrias/Inquirer.js#readme
{ "pile_set_name": "StackExchange" }
Q: What's the difference between globals $base_root and $base_url Can't seem to find the difference between these. D6 is what I need to know, but would love to know how those looks into 7 and even 8. A: $base_root is: The root URL of the host, excluding the path. e.g. http://localhost $base_url is: The base URL of the drupal installation. again, e.g. http://localhost The only situation I can think of where these would be different is if your Drupal installation is in a sub-folder of the web root. In that case $base_url would also contain the sub-folder in the path, e.g. http://localhost/drupal The descriptions in the documentation are exactly the same for both across versions 6, 7 and 8.
{ "pile_set_name": "StackExchange" }
Q: Django pre-fill a form drop down box based on url request I would like to pre-fill a drop down box based on a URL request from a URL tag. I'm trying to get it where the site is a list of books, and when you're on a book page, if you want to take some notes on that book, then you would hit the "take notes" button, and it would take you to a note form page where the drop down box at the top for the name of the book would be pre-filled from the title of the book page that you just came from. My url on the "book/detail.hmtl" page looks like this: {% url 'books:take_notes' book.id %} view.py - then for the take notes page I tried to prefill the NoteForm() like this: def take_notes(request, book_id): mybook = Book.objects.get(pk=boo_id) form = NoteForm(initial={'book':mybook.title}) urls.py - url(r'^take_notes/(?P<book_id>\d+)/$', views=take_notes, name='take_notes'), The NoteForm() has 3 fields class NoteForm(forms.ModelForm): class Meta: model = Note fields = ('book', 'title', 'note',) widgets = { 'note': forms.Textarea, } When I use initial for "title" it will prepopulate, but it won't for 'book' because it is a drop down box. Any ideas? Thanks. A: Try setting book_id instead of book in the view as form = NoteForm(initial={'book_id':book_id})
{ "pile_set_name": "StackExchange" }
Q: Cannot get Kendo own sample to work with remote code I am new to Kendo and just trialing it. I am looking at the group binding on a line chart sample that is provided in the demos. I linked the remote json in the demo but cannot get the chart to work. if I navigate to the json link, the json displays fine. Any help would be greatly appreciated. Link to Demo: http://demos.kendoui.com/dataviz/line-charts/remote-data.html Link to my Code: http://jsfiddle.net/Grjsn/3/ Code Text: <div id="example" class="k-content absConf"> <div class="chart-wrapper" style="margin: auto;"> <div id="chart"></div> </div> <script> function createChart() { $("#chart").kendoChart({ dataSource: { transport: { read: { url: "http://demos.kendoui.com/content/dataviz/js/spain-electricity.json", dataType: "json" } }, sort: { field: "year", dir: "asc" } }, title: { text: "Spain electricity production (GWh)" }, legend: { position: "top" }, seriesDefaults: { type: "line" }, series: [{ field: "nuclear", name: "Nuclear" }, { field: "hydro", name: "Hydro" }, { field: "wind", name: "Wind" }], categoryAxis: { field: "year", labels: { rotation: -90 } }, valueAxis: { labels: { format: "N0" }, majorUnit: 10000 }, tooltip: { visible: true, format: "N0" } }); } $(document).ready(function() { setTimeout(function() { // Initialize the chart with a delay to make sure // the initial animation is visible createChart(); $("#example").bind("kendo:skinChange", function(e) { createChart(); }); }, 400); }); </script> A: Loading the JSON throws the error: XMLHttpRequest cannot load http://demos.kendoui.com/content/dataviz/js/spain-electricity.json. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin. This is due to same-origin security for AJAX requests in browsers. http://en.wikipedia.org/wiki/Same_origin_policy
{ "pile_set_name": "StackExchange" }
Q: Update float column but retain its decimal - resequence an index to remove gaps I have a table like this: name | index item A | 1 item B | 3 item C | 3.2 item D | 3.3 item E | 30 item F | 30.1 How can I resequence the index column using either mysql or php to remove all gaps in the integer sequence so that the table looks like this: name | index item A | 1 item B | 2 item C | 2.2 item D | 2.3 item E | 3 item F | 3.1 I have tried using SUBSTRING to replace the first digit in the index only but this doesn's allow for items E and F A: You can use user-defined variables to keep track both of the last major part seen, and also of the current major-part with which to replace: SET @new:=0, @old:=0; UPDATE myTable SET `index` = (@new := @new + (@old < (@old := `index` DIV 1))) + `index` MOD 1 ORDER BY `index`; Explaining this from the inside out: The variables to be used are first initialised to zero. `index` DIV 1 gives the integer part of the current index value; this is assigned to @old so that it is available for the next record. It is compared against the current value of @old (i.e. from the previous record) using the < less-than operator; since MySQL does not have true boolean types, this expression evaluates to 1 if true and 0 if false—thereby providing a handy shortcut for incrementing @new. @new is updated with its new (i.e. incremented, if appropriate) value. index is updated with this value of @new plus the result of `index` MOD 1, which is the fractional part of the original index value. The ORDER BY clause ensures that the updates are performed in the correct order. However, given the nature of the task you're attempting to perform, it would appear that these values are not really fractional numbers at all—rather that they consist of two integers delimited by a . character, and just happen to be rendered like a fraction for display. If so, you would probably be wise to store the value across two separate integer columns (combining together into a string, if so desired, at the presentation layer of your application). One can provide a migration path without causing much interruption to the existing codebase by using a view to simulate the old table structure: CREATE TABLE myNewTable LIKE myTable; ALTER TABLE myNewTable ADD COLUMN index_major INT UNSIGNED NOT NULL, ADD COLUMN index_minor INT UNSIGNED NOT NULL; INSERT INTO myNewTable SELECT myTable.*, @new := @new + (@old < (@old := `index` DIV 1)), CAST(SUBSTRING_INDEX(`index`, '.', -1) AS UNSIGNED) FROM myTable, (SELECT @new:=0, @old:=0) init ORDER BY `index`; ALTER TABLE myNewTable DROP COLUMN `index`; ALTER TABLE myTable RENAME TO archived_myTable; CREATE VIEW myTable AS SELECT ..., CONCAT(index_major, '.', index_minor) AS `index` FROM myNewTable; The application can then read (and update, except for the synthesized index column) this myTable view as if it were the original myTable—i.e. without any knowledge of the underlying change that has taken place. INSERT statements, however, will need to be modified to work with the new underlying myNewTable instead.
{ "pile_set_name": "StackExchange" }
Q: Only push certain files once I have a git repository for a server. That server needs some files, but these files only have to be pushed once. So when someone edits it, then it doesn't have to be pushed to github, but when someone downloads the repository they should get the unedited file. The server needs these files to run, but for every person are these files different, that's why I don't want it to be pushed again. How can I do this? A: If you haven't committed the files yet, i'd say add the filename to your .gitignore file like: <filename>.<extension> So in case the file is package.json: package.json Wildcards can be made by using the * *.json or as AoeAoe remarked: you can add the file later using git add --force to overrule the .gitignore file. Now if the content of your file is merely 10 rules of config, i'd say: create a mock-up out of it and write it down in your readme.md and instruct your colleagues to create their own, otherwise, you should follow the advice in the update section. Update: as Edward Thompson stated: .gitignore doesn't apply to uploaded files you'll be forced to use git update-index To force the file from not updating: git update-index --assume-unchanged path/to/file To enable updating again: git update-index --no-assume-unchanged path/to/file
{ "pile_set_name": "StackExchange" }
Q: CRON - PHP - file_get_contents to run PHP page and email with CRON I am trying to setup an end-of-day automated email using a CRON job. I can get the CRON job to send out a static email, however I am having trouble when trying to use file_get_contents and a php page that then uses mysql queries to get the data from a database and builds the email body. Need help! *NOTE- I use a special php mailer for SMTP. This mailer works 100% FINE when sending any static email or sending dynamic emails manually (not CRON). Just having trouble getting the CRON job to actually access the PHP file and get the data. Mailer file being run by CRON: #!/usr/bin/php <?php set_include_path('/Library/WebServer/Documents/pbhsadmin/'); include '_classes/class.phpmailer.php'; $email = 'EMAIL'; try { $mail = new PHPMailer(true); //New instance, with exceptions enabled $mail->Subject = "PBHS Administration - Changes Department Daily Report"; $body = file_get_contents('http://localhost/pbhsadmin/_mail/changes_daily.php'); //$body = 'Testing no get file'; $body = preg_replace('/\\\\/','', $body); //Strip backslashes $mail->From = "[email protected]"; $mail->FromName = "PBHS Support"; $mail->IsSMTP(); // tell the class to use SMTP $mail->SMTPAuth = true; // enable SMTP authentication $mail->Port = 25; // set the SMTP server port $mail->Host = "mail.SERVER.com"; // SMTP server $mail->Username = "EMAIL" // SMTP server username $mail->Password = "PASSWORD"; // SMTP server password $mail->IsSendmail(); // tell the class to use Sendmail $mail->AddReplyTo("[email protected]","PBHS Support"); $mail->AddAddress($email); $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->WordWrap = 80; // set word wrap $mail->MsgHTML($body); $mail->IsHTML(true); // send as HTML $mail->Send(); echo 'message sent!'; } catch (phpmailerException $e) { echo $e->errorMessage(); } ?> PHP Page using mysql to query database and create email: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Changes Department - Daily Report</title> </head> <body> <?PHP set_include_path('/Library/WebServer/Documents/pbhsadmin/'); include 'SQL CONNECTION FILE'; $query = "QUERY"; $result = mysql_query($query)or die(mysql_error()); while($row=mysql_fetch_array($result)){ if($row['userid']==0) $username = 'Unassigned'; else $username = $row['username']; $userid = $row['userid']; //GET ALL PROJECTS WORKED ON FOR THIS USER $query2 = "QUERY"; $result2 = mysql_query($query2)or die(mysql_error()); echo ' <div class="employee"> <h1>'.$username.'</h1> <table><tr><th>Site</th><th>Hours Worked</th><th>Total Hours</th><th>Status</th></tr>'; while($row2=mysql_fetch_array($result2)){ $domain = $row2['domain']; $hours = $row2['hours']; if($row2['completed']!='0000-00-00 00:00:00') $status = 'Completed'; else $status = 'Incomplete'; $total_hours = $row2['act_hours']; echo '<tr><td class="center">'.$domain.'</td><td class="center">'.$hours.'</td><td class="center">'.$total_hours.'</td><td class="center '.$status.'">'.$status.'</td></tr>'; } if(mysql_num_rows($result2)==0) echo '<tr><td colspan="4" style="text-align:center;"><i>No Projects Worked On</i></td></tr>'; echo '</table></div>'; } ?> </body> </html> A: I actually figured it out. The error was in my declaration in the html email. It has to be <style type="text/css">
{ "pile_set_name": "StackExchange" }
Q: Previous and Next Button to load String out of Array in WebView I have an Array of Websites in my code. I added 2 buttons with the id button1 and button2. They shall be used to navigate between the sites in Array. private WebView webv; private SeekBar seitenSwitcher; private String[] websites = { "000.htm", "001.htm", "002.htm", "003.htm", "004.htm", "005.htm", "006.htm", "007.htm", "008.htm", "009.htm", "010.htm", "011.htm", "012.htm", "013.htm", "014.htm", "015.htm", "016.htm", }; public int pRog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webv = (WebView)findViewById(R.id.Viewing); webv.setWebViewClient(new WebViewClient()); webv.getSettings().setJavaScriptEnabled(true); webv.loadUrl(websites[0]); pRog = 0; Button button1= (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webv.loadUrl(websites[pRog--]); pRog = pRog--; /** I can also leave this out and it works **/ } }); Button button2= (Button) findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webv.loadUrl(websites[pRog++]); } }); The idea was that the int pRog is used to have the value of the string out of the array websites, which is currently shown. And then with "pRog = pRog--" or "pRog = pRog++" change the value, to fit the currently shown string in the array. It is working, but not as it should. I can go forward and backward, but the first touch of the button in the other way is not working. Example: I start at 000.htm, as you can see in the code. First touch of button2. (nothing happens) Second touch of button2. (webView loads 001.htm) Third touch of button2. (webView loads 002.htm) Fourth touch of button2. (webView load 003.htm) First touch of button1. (webView loads 004.htm ! Instead of 002.htm) Second touch of button1. (webView loads 003.htm ! now it is working.) Touch of button2. (web View loads 002.htm ! Down instead of up) Afterwards it also works again.) It also works if i leave out pRog = pRog++ or --. A: You should do webv.loadUrl(websites[++pRog]) not webv.loadUrl(websites[pRog++]) Same for the other button with --
{ "pile_set_name": "StackExchange" }
Q: How to Call SQLite database delete column ("db.delete") from outside the class the database was created I am required to use a Button defined in fragment 'CheckInFragment.java' to delete data from the database defined outside the fragment. Currently, the deleteCheckIn method is located in CheckInList.java which needs to be called on the delete button defined in the fragment using an OnClickListener. Currently, I am unable to reference or use / create this method inside the fragment. I've tried referencing the method inside the fragment but since it requires arguments only stored in CheckInList.java it was unsuccessful. I've tried directly calling the mDataBase.delete without using a method however as the previous attempt it cannot be called without those arguments. CheckInList.java ... public class CheckInList { private static CheckInList sCheckInList; private Context mContext; public SQLiteDatabase mDataBase; public static CheckInList get(Context context) { if (sCheckInList == null) { sCheckInList = new CheckInList(context); } return sCheckInList; } public CheckInList(Context context) { mContext = context.getApplicationContext(); mDataBase = new CheckInBaseHelper(mContext).getWritableDatabase(); } //REQUIRED METHOD TO BE CALLED public void deleteCheckIn(CheckIn c) { mDataBase.delete(DATABASE_NAME, CheckInTable.Cols.UUID + "=" + c, null); } ... //CheckInFragment.java @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_checkin, container, false); ... mDeleteButton = (Button) getView().findViewById(R.id.checkin_delete); mDeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //call delete method here } }); return v; } ... //CheckIn.java (as per comments) public class CheckIn { private UUID mId; private String mTitle; private String mPlace; private String mDetails; private Date mDate; private double mLatitude; private double mLongitude; ... public UUID getId() { return mId; } ... public CheckIn() { this(UUID.randomUUID()); } public CheckIn(UUID id) { mId = id; mDate = new Date(); } ... I would like to find a way to use deleteCheckIn when the mDeleteButton button is clicked. Any help is appreciated! A: public class CheckInList { ... // While implementing Singleton, the constructor must be private private CheckInList(Context context) { mContext = context.getApplicationContext(); mDataBase = new CheckInBaseHelper(mContext).getWritableDatabase(); } ... } mDeleteButton = (Button) getView().findViewById(R.id.checkin_delete); mDeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckInList.get(v.getContext()).deleteCheckIn(/* Send the parameter here */); } }); return v; }
{ "pile_set_name": "StackExchange" }
Q: Adjust table with images in every row inside a div I have defined a layout which has many elements. One of these element is a grey box (a div) in which I place a table. That table has rows and it contains small images. What I want to achieve is to adjust the table inside it parents. I want the images to be loaded automatically depending on how many they are (quantity of images is variable)... so when reaching the grey box max size the line should break and send the images to the next row. Is this possible? Furthermore I try to make it resizable to different screen sizes. Here Css and Html snippet: body { background-color: #141414; margin-top:3%; margin-left: 2%; margin-right: 2%; } .video-item { width: 30%; float: left; margin-bottom: 5px; } .video-item-2 { width: 66%; float: left; margin-bottom: 20px; } .video-display { background-color: #1F1F1F; height: 450px; } p { color: white; text-align: center; } #thumbs { word-wrap: break-word; table-layout:fixed; width: 100%; } #thumbnail-grid { background-color: #1F1F1F; height: 450px; } .video-spacer { width: 2%; float: left; min-height: 200px; } #arrow_up, #arrow_down { display: block; margin: 0 auto; } #arrow_down { -ms-transform: rotate(180deg); /* IE 9 */ -webkit-transform: rotate(180deg); /* Chrome, Safari, Opera */ transform: rotate(180deg); } <body> <div class="video-item"> <p class="font-semibold">Something else</p> <div class="video-display"></div> </div> <div class="video-spacer"></div> <div class="video-item-2"> <p class="font-semibold">THUMBNAIL PREVIEW</p> <div id="thumbnail-grid"> <img id="arrow_up" src='http://www.pngdot.com/wp-content/uploads/2015/11/Png_Up_Arrow_01.png' alt="arrow" height="25" width="45"> <table id="thumbs"> <tr> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> <td tabindex="3"><img id="arrow_up" src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"></td> </tr> </table> <img id="arrow_down" src='http://www.pngdot.com/wp-content/uploads/2015/11/Png_Up_Arrow_01.png' alt="arrow" height="25" width="45"> </div> </div> </body> I would like to solve this with css only but if js or jquery is necessary, then I accept it. Thanks! A: Here is a solution which, when reaches the width, break into new lines. body { background-color: #141414; margin-top:3%; margin-left: 2%; margin-right: 2%; } .video-item { width: 30%; float: left; margin-bottom: 5px; } .video-item-2 { width: 66%; float: left; margin-bottom: 20px; } .video-display { background-color: #1F1F1F; height: 450px; } p { color: white; text-align: center; } #thumbs { text-align: center; max-height: 400px; overflow: auto; } #thumbnail-grid { background-color: #1F1F1F; height: 450px; } .video-spacer { width: 2%; float: left; min-height: 200px; } #arrow_up, #arrow_down { display: block; margin: 0 auto; } #arrow_down { -ms-transform: rotate(180deg); /* IE 9 */ -webkit-transform: rotate(180deg); /* Chrome, Safari, Opera */ transform: rotate(180deg); } <body> <div class="video-item"> <p class="font-semibold">Something else</p> <div class="video-display"></div> </div> <div class="video-spacer"></div> <div class="video-item-2"> <p class="font-semibold">THUMBNAIL PREVIEW</p> <div id="thumbnail-grid"> <img id="arrow_up" src='http://www.pngdot.com/wp-content/uploads/2015/11/Png_Up_Arrow_01.png' alt="arrow" height="25" width="45"> <div id="thumbs"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> <img src='http://oleaass.com/wp-content/uploads/2014/10/Random-truths18.jpg' alt="arrow" height="40" width="60"> </div> <img id="arrow_down" src='http://www.pngdot.com/wp-content/uploads/2015/11/Png_Up_Arrow_01.png' alt="arrow" height="25" width="45"> </div> </div> </body>
{ "pile_set_name": "StackExchange" }
Q: Minimum fields to Maximize Payment Conversions? I took a look at Bluesnap's Auth Capture API - https://developers.bluesnap.com/v8976-XML/docs/auth-capture specifically the "card-holder-info" element. What minimum fields needs to be passed to maximize payment conversions? I want to map these fields to my checkout UI page where I would like to have my customers enter minimum number of fields to strike a balance between being frictionless vs maximize conversions. Thanks. A: The minimal details of the card holder are first name, last name and zip code. That's all the information BlueSnap requires to process the purchase. The process is already pretty streamlined. From the optional fields you may add, adding country and state might have some effect as some processors use this information to validate the shopper.
{ "pile_set_name": "StackExchange" }
Q: complex series expansion for $f(z)=\frac{1}{z-1}$ Expand the function $f(z)=\frac{1}{z-1}$ as as a series around $z_{0}$ in two regions a) $$|z-z_{0}| < |1-z_{0}|$$ b) $$|z-z_{0}| > |1-z_{0}|$$ and find coefficient $a_{n}$ is each case. I found radius of convergence to be $|1-z_{0}|$ , so for $|z-z_{0}| < |1-z_{0}|$ I found $$f(z)= -\sum \frac{(z-z_{0})^n}{(1-z_{0})^{n+1}}$$ But what happens for case b) $|z-z_{0}| > |1-z_{0}|$, doesn't it diverge? Can we still find series expansion for it? Will that be a Laurent or Taylor? A: The two cases are very similar. In case (a), you write $${1\over z-1}={1\over (z-z_0)-(1-z_0)}={-1\over 1-z_0}\cdot {1\over 1-{z-z_0\over 1-z_0}}$$ and expand the last factor as a geometric series $\sum_{n=0}^\infty w^n$ with $w={z-z_0\over 1-z_0}$. Note that $|w|<1$ in case (a). In case (b), you need to pull out the larger term $z-z_0$ instead, obtaining $${1\over z-1}={1\over (z-z_0)-(1-z_0)}={1\over z-z_0}\cdot {1\over 1-{1-z_0 \over z-z_0}}$$ Similarly as above, let $w={1-z_0\over z-z_0}$, and observe that $|w|<1$ in case (b), so we can use the same trick again. Since $z-z_0$ now appears in the denominator of $w$, the Taylor series in $w$ will give rise to a Laurent series in $z-z_0$.
{ "pile_set_name": "StackExchange" }
Q: Add a people group attribute in list programatically I want to add a attribute (Person or Group) in List through coding, does any one know how to do it. thanks A: [Saboor's comment re-posted as an answer, with minor modifications] SPSite site = SPContext.Current.Site; using (SPWeb web = site.OpenWeb()) { SPListCollection lists = web.Lists; SPList list = lists['Guid for List']; list.Fields.Add("people", SPFieldType.User, false); list.Update(); }
{ "pile_set_name": "StackExchange" }
Q: What is the ideal number of farms and wine fields? What is the ideal number of corn fields ( squares) that the farmer can farm to maximize production? What is the maximum number of grape fields that a wine farmer can collect from? A: I believe your question is about optimal field count, not a maximum one ;) The number can be checked quite easily by making a test map with only a Store, Inn and a Farm/Winefarm. Start the game and wait till production begins/stabilizes, then make a sample for a 5-10 minutes, by counting corn/wine in the Store. Repeat the sample for different number of fields. Vanilla game answer: Farm - 15-16 fields Wineyard - ~12 fields KaM Remake: Farm - 15-16 fields Wineyard - 8-9 fields (wine was buffed to make it more competitive strategy) Note that making a giant field between several farms will generally lower your corn/wine production because farmers will stumble into one another from time to time, when going to cut/sow/collect their crops.
{ "pile_set_name": "StackExchange" }
Q: App Engine + Webmaster Tools I've been trying for a while now to get my Python App Engine app onto the Chrome Web Store, however, when I try to upload, Google tells me I need to confirm that its my domain (I'm on an appspot.com domain). I have tried the first 3 methods (meta tag, file, and analytics) in several different ways but they haven't worked. Is there any way around this? Or, rather, how can I verify an App Engine domain? A: When I go to http://book-tracker.appspot.com/ it asks me for my Google Account. Try disabling login required before trying activation.
{ "pile_set_name": "StackExchange" }