prompt
stringlengths
66
13.6k
chosen
stringlengths
40
27.8k
rejected
stringlengths
16
13.3k
Suppose I have a `WeakReference` of a target strong reference. I'd like to be informed when the target object itself is being collected by the GC. Is it possible? EDIT: Adding code to the finalizer/destructor is not an option here. I need something that is not dependent on class code.
What about `Object.Finalize()` method? Won't that be invoked upon finalization?
You may use interception to catch Finalize for each classes which is inherited from a custom interface/class. I think, this is what you want to try to achieve, right? You can use Unity for that. [Here](http://litemedia.info/aop-in-net-with-unity-interception-model) is a very short example how to do interception with Unity.
I have a cell block with 25 cells but none of my prisoners will move there from the holding cell. I have working power and water beds and toilets they are separate from each other it has all the requirements why wont it work? Any ideas?
This behavior is caused by cell quality : some prisoners do not diserve any cell based on cell quality and their behavior. When you go to "Policy" tab you can choose to enable or disable the cell quality ratings. [![enter image description here](https://i.stack.imgur.com/dmQwH.png)](https://i.stack.imgur.com/dmQwH.png) This is the description on hoover : > > ### Use Cell Quality > > > If enabled, Prisoners will only be assigned to a cell of a quality they deserve, based on their behavior. **Poorly behaved prisoners will never be assigned to a high quality cell, even if there are no other cells available**. > > If disabled, prisoners will be assigned to any cell regardless of quality, but but prisoners in cells of lower quality than average will be more resentful. Prisoners will still be upgraded to higher quality cells if they behave well. > > > You have a few solutions : * Disable the Cells Quality Ratings * Build new low quality cells * Downgrade you cells quality (remove windows, TV, bookshelves, chairs...) * Wait until you prisoners behave better and deserve a better room (bad idea, they will fight a lot if they are unhappy in an holding cell).
Cancelling the holding cell room designation will force the prisoners out of the holding cell and allocate them a free cell each. Once you have more prisoners arriving than you have cells for you can mark the room as a holding cell again.
In Windows 7 I tried setting my MAC address by changing it via adapter properties (Locally Administered MAC Address), but ipconfig /all still shows the old address, even after rebooting. Any hints?
It's possible your card does not support changing your mac address. You may also have more luck with a [mac address changing utility](http://www.klcconsulting.net/smac/). Edit: It seems things are slightly different on Windows 7 (Taken from a forum post); 1. Go to Control Panel->Device Manage->Network Adapter->Advanced->Network Address 2. Change the value here. **Ensure the first two digits are not the same**. 3. Change the registry key value. ([Guide here](http://www.windowsreference.com/networking/how-to-change-mac-address-in-windows-registry/)).
<http://devices.natetrue.com/macshift/> will succeed where others have failed. Though sometimes the MAC address is burned into the EEEPROM of the card.
I have this on my console on firebug, ``` [Object { fa_id="1167535", f_id="1000", loc_type="6", more...}, Object { fa_id="1167535", f_id="1000", loc_type="6", more...}] ``` it is data from the server side. Now, how would I convert this into array such that this data can be used on another file. I tried `JSON.parse` and `jQuery.parseJSON` but both did not work.
That isn't JSON it's a Javascript array of objects, not a string. My guess is that you've received this from a jQuery ajax call and you had the `dataType : 'json'` set so that jQuery has automatically parsed the JSON into this array. To send it to a PHP script you can convert it back to JSON using: ``` var myString = JSON.stringify(data); ``` and then fire off an ajax call to the PHP script with that as the POST data: ``` var myString = JSON.stringify(data); $.post('page.php', { data : myString }, function(){ console.log( "sent" ); }); ``` In PHP you can decode it using: ``` $data = json_decode($_POST['data']); // <-- or whatever your post variable is named foreach($data as $obj) { echo $obj->fa_id; } ```
if you want to get an php array use this <http://php.net/manual/en/function.json-decode.php>
I have been using `Regex.Match` function to match two string using following code ``` bool contains = Regex.Match(highlightedText, searchText, RegexOptions.IgnoreCase).Success; ``` Here this code working fine but if i set `highlightedText` as say 'Rajeev' and `searchText` set to '.' i.e dot. It still returns me `true`. If i search for `.` in any string it gives me `true` wheather or not `highlightedText` contains '.' or not. Why it is giving me false value ?
Regex `"."` is any symbol. Your string contains any symbol? Yes. Use `@"\."` (escape dot) for find string contains dot. For simple search substring in a string use `string.IndexOf` like this: ``` string text = "some kind of text"; Console.WriteLine("'{0}' contains '{1}'? {2}", text, "some", text.IndexOf("some", StringComparison.InvariantCultureIgnoreCase) >= 0); Console.WriteLine("'{0}' contains '{1}'? {2}", text, "pleasure", text.IndexOf("pleasure", StringComparison.InvariantCultureIgnoreCase) >= 0); ``` Result: ``` 'some kind of text' contains 'some'? True 'some kind of text' contains 'pleasure'? False ```
The [dot](https://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx) matches every single character. To match the dot itself, use `"\."`.
This is function but when executes this gave me just 1. ```js (function(n, m) { // body... if (n <= m) { console.log(n); n++; (n, m); } })(1, 10); ```
You can't recursively call an anonymous function; you have to give it a name instead (in which case it is no longer considered 'anonymous'): ```js (function name(n, m) { // body... if (n <= m) { console.log(n); n++; name(n, m); } })(1, 10); ```
This is an anonymous function without a "loop" and displays numbers `n` to `m` ```js (function(n, m) { Array.from({length:m}, (v,i) => console.log(i + n)); })(1, 10); ```
I'm trying to debug someone else's SQL reports and have placed the underlying reports query into a query windows of SQL 2012. One of the parameters the report asks for is a list of integers. This is achieved on the report through a multi-select drop down box. The report's underlying query uses this integer list in the `where` clause e.g. ``` select * from TabA where TabA.ID in (@listOfIDs) ``` I don't want to modify the query I'm debugging but I can't figure out how to create a variable on the SQL Server that can hold this type of data to test it. e.g. ``` declare @listOfIDs int set listOfIDs = 1,2,3,4 ``` There is no datatype that can hold a list of integers, so how can I run the report query on my SQL Server with the same values as the report?
[Table variable](http://technet.microsoft.com/en-us/library/ms175010.aspx) ``` declare @listOfIDs table (id int); insert @listOfIDs(id) values(1),(2),(3); select * from TabA where TabA.ID in (select id from @listOfIDs) ``` or ``` declare @listOfIDs varchar(1000); SET @listOfIDs = ',1,2,3,'; --in this solution need put coma on begin and end select * from TabA where charindex(',' + CAST(TabA.ID as nvarchar(20)) + ',', @listOfIDs) > 0 ```
In the end i came to the conclusion that without modifying how the query works i could not store the values in variables. I used SQL profiler to catch the values and then hard coded them into the query to see how it worked. There were 18 of these integer arrays and some had over 30 elements in them. I think that there is a need for MS/SQL to introduce some aditional datatypes into the language. Arrays are quite common and i don't see why you couldn't use them in a stored proc.
The term is [妖精](https://zh.wikipedia.org/wiki/%E5%A6%96%E7%B2%BE), which can be translated into English as "fairy", "elf", "goblin". As noted, the Japanese literature uses 妖精 to describe the European fairy. The English translation of 白骨精 in 西游记 (Journey to the West) is "white bone demon". So, this word can be translated into English as fairy, elf, goblin, or demon. Let's say an author is writing a fantasy story in Chinese first, using terms that are understood in a Chinese society. Then, the same author translates his/her own story into English and faces a problem. Which term should 妖精 be translated into (fairy, elf, goblin, or demon)? Or are the differences between the terms negligible, so the author can just pick a random one and go with it?
Does it have to be an actual translation? Translations don't always work, as synonyms get lost in translation. As you mentioned, there is no English word that can mean "fairy", "elf" **and** "goblin". Translating to any of the options will mean that you lose out some of the ambiguity. Maybe it's important in your story that the creature's alignment is unknown. If you translate it to "fairy", readers will interpret it as good. If you translate it to "goblin", readers are liable to interpret it as conniving or evil. You can't retain the ambiguity. Instead, you can simply pick a name without any inherent meaning (or suggestion about alignment), and then define the creature through observation rather than naming. The Wikipedia page you linked has an English variant, where the chosen name seems to be [**Yōsei**](https://en.wikipedia.org/wiki/Y%C5%8Dsei). Why not use that, so you don't bias your readers and are actually able to assume direct control over steering the viewer's observation; as opposed to relying on existing words with Western connotations? * **Fairy** = small and benevolent. Has a physical shape but they are inherently magic. * **Spirit** = ghost or ethereal entity, lacks physical shape. * **Elf** = humanoid creature with magical affinity and often has an expanded lifespan. Often acts as a counterpart to the human race. Alternatively (but less commonly), very similar to a fairy but not *as* magical in nature. * **Goblin** = Conniving, tinkerer, likely evil (or at least lacks moral principles). Humanoid, but lesser to elves and humans. * **Demon** = almost definitively evil. Possible religious connotation (demons are to the Devil what angels are to God; henchmen). Known to possess humans. These are in no way guaranteed traits, but if the reader reads the word, they are liable to make inferences as to what the creature is like. Because 妖精 can mean all of these things *at the same time*, the reader is therefore unable to make a choice between the listed interpretations. They must assume a generalized shape. But as English lacks a word that encompasses all definitions, you're much more likely to have your English readers pidgeon hole your creature by the common definition of the word you chose to use.
It depends on whether you want to maintain a feel of Chinese culture and mythology in your story (which can be very effective but involves a lot more than just translating the story), or you want to adapt the storyline into something that feels more familiar to Western readers. **If you want to maintain a Chinese feel** then you may want to introduce the entity as "yāojing—a mischievous fairy-like creature without wings" or "a malevolent elf-like creature with powers of enchantment" or whatever is appropriate for the nature of your creature. There is nothing wrong with showing the reader that there is no sufficient word for the creature—in fact, that makes your story more interesting. **If you want to adapt the story to something more familiar,** and there is just one such creature, give it a name, refer to it by its name, and readers will learn about it as you describe its appearance, history and behaviour. If there are many such creatures, all alike, you certainly can "shoehorn" them into an existing concept like goblin, demon, devil, imp, spirit, shade, ghost, ghoul, spectre, witch, or [familiar](https://en.wikipedia.org/wiki/Familiar_spirit). Alternative spellings like daemon, faerie can help emphasise that the creature is a little different to the established concept. Or, you can name your "species" (think of the *Ents* in Lord of the Rings, *dementors* in Harry Potter, or the *Ogier* in Wheel of Time), and describe them as I have suggested above.
> > **Possible Duplicate:** > > [How do i “echo” a “Resource id #6” from a MySql response in PHP?](https://stackoverflow.com/questions/4290108/how-do-i-echo-a-resource-id-6-from-a-mysql-response-in-php) > > > I am new at php and SQL and I'm trying to make the php page list the numbers of enries in the table. I'm using this code but it returns Resource id #2: ``` $rt=mysql_query("SELECT COUNT(*) FROM persons"); echo mysql_error(); echo "<h1>Number:</h1>".$rt; ```
Because you get a mysql ressource when you do a [`mysql_query()`](http://ch2.php.net/manual/en/function.mysql-query.php). Use something like [`mysql_fetch_assoc()`](http://ch2.php.net/mysql_fetch_assoc) to get the next row. It returns an array with the column names as indices. In your case it's probably `COUNT(*)`. Here's a fix and some minor improvements of your snippet: ``` $rt = mysql_query("SELECT COUNT(*) FROM persons") or die(mysql_error()); $row = mysql_fetch_row($rt); if($row) echo "<h1>Number:</h1>" . $row[0]; ``` If you need to get all rows of the resultset use this snippet: ``` while($row = mysql_fetch_assoc($rt)) { var_dump($row); } ```
`mysql_query` returns a resource object. You need to fetch rows from it first (`mysql_fetch_row`).
Our site works fine for 90% of the day, then during our peak hours when traffic is about twice as heavy as normal, everything slows down to a crawl. Page load times that are normally 1 second take 30 seconds. Checking our error logs, it looks like it may be a connection pool issue. We have 3 web servers connected to 1 sql server db. The SQL server is flying under 25% utilization on all cores. I look at the User Connections counter on our SQL server and see that during our peak we have 400+ User Connections, but off-hours it is around 120+. I am pretty sure we are just using whatever default settings MS comes with to deal with our app pool. What can I do to test to see if is an app pool issue? What are the negatives of increasing the app pool size to 1000 (and how do I do this?). Thanks!
This could be related to sql connections not being properly disposed (returned to the pool). Make sure you are calling `SqlConnection.Dispose`.
I had this issue with Powershell and back to back queries (**invoke-sqlcmd** followed by another **invoke-sqlcmd**). Both queries involved data modifications. Resolved by adding **-connectiontimeout 1** to the parameter call. Example: ``` invoke-sqlcmd "insert into testdb..tab1 (cname) select 'x'" -connectiontimeout 1 invoke-sqlcmd "update testdb..tab1 set ctr=ctr+1 where cname='aaa'" ``` Length of timeout may vary depending on number of rows affected.
> > **Possible Duplicate:** > > [How to detect if JavaScript is disabled?](https://stackoverflow.com/questions/121203/how-to-detect-if-javascript-is-disabled) > > > My first web application relies heavily on Javascript and AJAX application. Other than my Login Page, majority of the pages relies on Javascript and Ajax when submitting data to the server. I have been thinking about this, if user disables his/her javascript then my app does not behave accordingly. I used this code in my Login page ``` <NOSCRIPT> Javascript is required to run this pages. Please turn it on or ask help from techsupport if you dont know how to enable it </NOSCRIPT> ``` Although I think not relevant, I used Spring MVC 2.5 and Jquery for the sake of information to all. Any thoughts how others are able to handle in scenario such as this?
I think it's fine to require JavaScript to run your application. All mainstream web browsers have it today, and have had it for the last 10 years. Using a `<noscript>` tag is an acceptable way of showing to the user that they need JavaScript. I don't understand what you meant about disabling the login button though... You used JavaScript to detect if JavaScript was disabled ("I used jquery to check for the presence of this tag")? What you should do is to have the login button disabled by default, then use JavaScript (jQuery) to enable it. That way it will only be enabled if the user has JavaScript enabled.
What you should do is something like so ``` <noscript> <meta http-equiv="refresh" content="url=/?nojs=true"> </noscript> ``` This will do a html immediate refresh as soon as the headers are parsed allowing you to do something a little different. Server Side: (PHP in my case) ``` if(isset($_GET['nojs']) && !isset($_SESSION['no_script'])) { $_SESSION['no_script'] = true; //Or cookie } ``` Then as you have the variable locked in session / cookie you can throw out different pages for non JavaScript users.
I installed the gnome panel: <https://extensions.gnome.org/extension/17/dock/> but its on the right side, which is quite annoying becaus it alway popps up when using the scrollbar. How can I move it to the left?
Open a terminal and type: ``` gsettings set org.gnome.shell.extensions.dock position left ``` For 3.2 users, here is another way: Type in a terminal: ``` gedit ~/.local/share/gnome-shell/extensions/dock@gnome-shell-extensions.gcampax.github.com/extension.js ``` About line 44 find: ``` const DOCK_POSITION = PositionMode.RIGHT; ``` change to ``` const DOCK_POSITION = PositionMode.LEFT; ``` Save, exit, refresh gnome-shell (hit [Alt+F2] followed by r) and enjoy!
1. Open `dconf-editor` 2. Go to `/org/gnome/shell/extensions/dock` 3. Toggle `autohide` and left/right position from there Source: [Ubuntu Forums](http://ubuntuforums.org/showthread.php?t=2055526)
I am trying to learn network analysis, so I am using Hillary Clinton’s emails online to see who emailed who. My data is in a dictionary called hrc\_dict. I have a tuple of the sender and receiver followed by the frequency of the emails. This is part of the dictionary: > > {('Hillary Clinton', 'Cheryl Mills'): 354, ('Hillary Clinton', 'l'): 1, ('Linda Dewan', 'Hillary Clinton'): 1, ('Hillary Clinton', 'Capricia Marshall'): 9, ('Phillip Crowley', 'Hillary Clinton'): 2, ('Cheryl Mills', 'Anne-Marie Slaughter'): 1} > > > I am using Networkx in Jupyter to create a graph. My code is below: ``` import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_nodes_from(hrc_dict) for s, r in hrc_dict: G.add_edge((s,r), hrc_dict[(s,r)]) G.add_edge((s,r), hrc_dict[(s,r)]) ``` When I call nx.Graph(), nothing prints out and when I call G.nodes(), not all the nodes are showing up. I have pasted some of the output here: > > [1, > 2, > 3, > 4, > 5, > 6, > 7, > 8, > 'Mark Penn', > 10, > ('Todd Stern', 'Hillary Clinton'), > 12,] > > > When I call G.edges(), I get the below, which seems right > > [(1, ('Hillary Clinton', 'l')), (1, ('Linda Dewan', 'Hillary Clinton')), (1, ('Hillary Clinton', 'Thomas Shannon')), (1, ('Cheryl Mills', 'Anne-Marie Slaughter')), (1, ('Christopher Butzgy', 'Hillary Clinton’))] > > > Does anyone know how I can add nodes correctly to my graph. I assume that each person needs to be a node, so how do I break up the tuple and add the names separately? Are the edges showing correctly or do I need to enter them differently?
To add each person as a node, you also need to change the use of `add_nodes_from`. Something like this: ``` srcs, dests = zip(* [(fr, to) for (fr, to) in hrc_dict.keys()]) G.add_nodes_from(srcs+dests) ``` now means that the list of nodes from `G.nodes()` will be: ``` ['Cheryl Mills', 'Capricia Marshall', 'Anne-Marie Slaughter', 'Phillip Crowley', 'Hillary Clinton', 'l', 'Linda Dewan'] ``` (you don't get any duplicates because networkx stores graphs as a dictionary). Note: if you use the method below for adding the edges, there isn't any need to add the nodes first -- but in case there is some reason why you might have nodes that have no neighbours (or another reason why nodes only is important), this code will do it. Then add the edges basically as per Joel's answer; but also note the use of the attribute "weight", so the layout can make use of information directly. ``` import networkx as nx import matplotlib.pyplot as plt hrc_dict = {('Hillary Clinton', 'Cheryl Mills'): 355, ('Hillary Clinton', 'l'): 1, ('Linda Dewan', 'Hillary Clinton'): 1, ('Hillary Clinton', 'Capricia Marshall'): 9, ('Phillip Crowley', 'Hillary Clinton'): 2, ('Cheryl Mills', 'Anne-Marie Slaughter'): 1} G = nx.Graph() # To add the a node for each of the email parties: srcs, dests = zip(* [(fr, to) for (fr, to) in hrc_dict.keys()]) G.add_nodes_from(srcs + dests) # (but it isn't needed IF the following method is used # to add the edges, since add_edge also creates the nodes if # they don't yet exist) # note the use of the attribute "weight" here for (s,r), count in hrc_dict.items(): G.add_edge(s, r, weight=count) # produce info to draw: # a) if weight was used above, spring_layout takes # into account the edge strengths pos = nx.spring_layout(G) # b) specifiy edge labels explicitly # method from https://groups.google.com/forum/#!topic/networkx-discuss/hw3OVBF8orc edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)]) # draw it plt.figure(1); nx.draw_networkx(G, pos, with_labels=True) nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) plt.axis('equal') # spring weighting makes more sense this way plt.show() ``` And this is what we might see: [![Example output - note that because the HC/A-MS edge is so strong it is very short](https://i.stack.imgur.com/3a27s.png)](https://i.stack.imgur.com/3a27s.png)
Your problem is basically in this bit: ``` G.add_edge((s,r), hrc_dict[(s,r)]) ``` networkx interprets this as "add an edge between the first argument `(s,r)` and the second argument `hrc_dict[(s,r)]`." So for example `('Hillary Clinton', 'Cheryl Mills'): 354` becomes an edge between the node `('Hillary Clinton', 'Cheryl Mills')` and the node `354`. Instead try ``` G.add_edge(s, r, count = hrc_dict[(s,r)]) ```
I'm New in .Net MVC4 and i have some problem.... Example : In view i have 2 textbox ``` <input type="text" name="tax1" style="width:20px" maxlength="1" /> <input type="text" name="tax2" style="width:60px" maxlength="4" /> ``` After I push Submit Button I want to keep both data from textbox. ``` Ex : string value = textbox1 + textbox2 ``` Can I do my Requirement following this Example(in View). If OK : Please tell me about Solution. of If not OK : Please tell me about Solution and Which File to Resolve its(ex.controller, etc.).
It appears the issue is as Stober described. You can set a cookie to expire at the end of the browser session by setting the `HttpCookie.Expires` property to `DateTime.MinDate`, or not setting the property at all. However, at least with Chrome's *pick up where you left off* settings, it appears that the browser session does not necessarily end when the browser closes. When closed and then reopened, the Chrome browser picks up right where it left off, as if the session never ended. This includes continuing to use cookies set expire at the end of the session. I tried my same code on FireFox. Closing and reopening the browser caused the cookie to expire, exactly as expected. So while there are some general rules, in the end this behavior is totally up to the browser.
Just set the `Expires` property of your `HttpCookie` instance to `DateTime.MinDate` and it will expire after the browser session ends. **However**, this is actually **not a safe way** of protecting something with cookies, because the cookies are in fact valid for ever. It depends on the client implementation if the cookies are thrown away or not. If some bad person intercepts your cookies they will have access for ever. See also: [MSDN - `Cookie.Expires` Property](https://msdn.microsoft.com/en-us/library/System.Net.Cookie.Expires)
i have the following code below (i have stuck in xxx to not publish the real name). this code works fine when i upload to the server and will send out emails perfectly. ``` MailMessage msg = new MailMessage(); msg.From = new MailAddress(fromEmailAddress_); msg.To.Add(new MailAddress(toEmailAddress_)); msg.Subject = subject_; msg.Body = body_; msg.IsBodyHtml = true; msg.Priority = MailPriority.High; NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("xxx@xxxx.org", "password"); try { SmtpClient c = new SmtpClient("mail.xxx.org"); c.UseDefaultCredentials = false; c.Credentials = basicAuthenticationInfo; c.Send(msg); } catch (Exception ex) { throw ex; Console.Write(ex.Message.ToString()); } ``` but when i test locally on my machine in visual studio, i get an error: [SocketException (0x274d): **No connection could be made because the target machine actively refused it** 66.226.21.251:25] System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239 System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35 System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224 [WebException: **Unable to connect to the remote server**] System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +5420699 System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +202 System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21 System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +332 System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +160 System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +159 any suggestions of why this wouldn't work
The first thing I'd do to run this down is to see whether the target machine is, as the error message says, actually refusing the connections. I can connect to port 25 on that IP address from here, so it's possible that your error message is misleading. These are all possible causes of a failure to connect: * there's some problem in your code * there's some problem in the library you're using * you have a local firewall preventing outbound mail from strange programs * your ISP does not permit outbound SMTP connections except to their own servers * some intermediate network is blocking things * the mail server's ISP is blocking SMTP connections from your network * the mail server really is rejecting you, perhaps because you're on a blocklist To get more detail, download and install [Wireshark](http://www.wireshark.org/). It's like a debugger for networks. Start a capture between your system and the target network and then run your code. Interpreting the captured packets takes some experience, so if you get stuck feel free to post more data here.
You asked for an XP Mail Server. Try [hMailServer](http://www.hmailserver.com/)
I am having issues running makecat.exe on Windows 8.1 (Enterprise/Pro). I am trying to generate a .cat file for a Windows Troubleshooting Platform .diagcab and getting the error below. > > opened: ..\DiagPackage.cdf > > > > ``` > attribute: OSAttr > > ``` > > Failed: No members found. Last Error: 0x00000000 > > > Failed 0x00000000 (0) > > > This was definitely working for me in January this year running Windows 8.1. However now even using the same .cdf file (and script) that I previously used to generate the .cat file returns this error for no apparent reason. The result is a .cat file with no file hashes. The contents of the .cdf file is listed below. Also noting that there is an extra carriage return/new line at the end of the file as per the sdk documentation. ``` [CatalogHeader] Name=DiagPackage.cat PublicVersion=0x0000001 EncodingType=0x00010001 CATATTR1=0x10010001:OSAttr:2:6.1 [CatalogFiles] <hash>DiagPackage.diagpkg=DiagPackage.diagpkg <hash>DiagPackage.diagpkgATTR1=0x10010001:Filename:DiagPackage.diagpkg <hash>D_Main.ps1=D_Main.ps1 <hash>D_Main.ps1ATTR1=0x10010001:Filename:D_Main.ps1 <hash>R_ECP.Diagnostic.UserUpdate.ps1=R_ECP.Diagnostic.UserUpdate.ps1 <hash>R_ECP.Diagnostic.UserUpdate.ps1ATTR1=0x10010001:Filename:R_ECP.Diagnostic.UserUpdate.ps1 ``` I have tried the makecat.exe from most recent SDK for 8.1 (last updated May 13, 2014) and the version in the archive (last updated April 2, 2014) no luck for either. Has any one had this issue and solved it?
Apart from time travel which is already mentioned in the comments I think there is no other way to recover your code. But you can avoid this in the future by installing [DDevExtensions](http://andy.jgknet.de/blog/ide-tools/ddevextensions/ "DDevExtensions download page"). This extension creates backups of your files after every successful compile. Or you can check Autosave in the Editor Options, which saves your files after every successful compile.
In the source folder, Delphi will keep track of the history of your files. Maybe it is in there though I believe you will need to have auto save enabled for this. After all, it is the saved history...
This is an example in the ade4 package in R <http://pbil.univ-lyon1.fr/ade4/ade4-html/dudi.fca.html> in the value section of "dudi.fca" of this paragraph is written: > > Value > > The function prep.fuzzy.var returns a data frame with the attribute col.blocks. The function dudi.fca returns a list of class fca and dudi (see dudi) containing also > cr a data frame which rows are the blocks, columns are the kept axes, and values are the correlation ratios. > > > when I run the example, below, I only receive two graphs and no data frame for cr. I mean where could I find the defined cr i.e. correlation ratios, since it should be the output of whole command below? ``` #### needs ade4 package###### data(bsetal97) w <- prep.fuzzy.var(bsetal97$biol, bsetal97$biol.blo) scatter(dudi.fca(w, scann = FALSE, nf = 3), csub = 3, clab.moda = 1.5) scatter(dudi.fpca(w, scann = FALSE, nf = 3), csub = 3, clab.moda = 1.5) ```
Use [`.data()`](http://api.jquery.com/data/) to get data attributes. Try this: ``` alert($(this).data('test')); ``` **[DEMO](http://jsfiddle.net/kunknown/7etzas0m/2/)**
Try your **[UPDATED FIDDLE](http://jsfiddle.net/7etzas0m/5/) :** ``` $(function(){ $('form').submit(function(){ alert(this.action); alert($(this).attr('data-test')); return false; }); }); ```
I want to change UIButton color from brown color to darkbrown color. How i can do that ``` myButton.backgroundColor = [UIColor brownColor]; ``` Any ideas that how to change this brown color to darkbrown color. Thanks for help.
If you just want a darker brown specifically, you can manually specify it: ``` myButton.backgroundColor = [UIColor colorWithHue:1.0/12 saturation:2.0/3 brightness:4.0/10 alpha:1]; ``` (The default brown color has brightness 6.0/10.) If you want to be able to darken a color in general, you can do it like this: ``` UIColor *color = UIColor.brownColor; CGFloat hue, saturation, brightness, alpha; [color getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]; brightness *= .8; UIColor *darkerColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha]; ```
There's no darkBrownColor predefined, but you can create a UIColor with RGB values like so: ``` UIColor *myColor = [UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:1.0f]; ```
Due to technical reasons I just have to downgrade, mainly because I am more used to 5.2 than the newest version.
To downgrade from 5.4 to 5.2 it will take **A LOT** of time, is much faster and easier to create a new Laravel project. In case you want to install a specific Laravel version you can create the project with --prefer-dist on console: ``` composer create-project --prefer-dist laravel/laravel projectname "5.2.*" ``` More info on the docs: <https://laravel.com/docs/5.2/installation#installing-laravel>
since [laravel 5.4.x](https://github.com/laravel/laravel/blob/v5.4.0/composer.json) require specific version of php : ``` ... "require": { "php": ">=5.6.4", ... ``` and [laravel 5.2.x](https://github.com/laravel/framework/blob/v5.2.0/composer.json) require a lower version of php ``` ... "require": { "php": ">=5.5.9", ... ``` and according to [the major changes](http://php.net/manual/en/migration56.php) between php 5.5.x and php 5.6.x which may be used in laravel 5.4 , it will be not wise to downgrade .
How to get the 'clipboard' content in cypress. I have a button in my web application, on click of button system will perform 'copy to clipboard' and a message will get displayed. Below is an example of the url content that is copy to clipboard ( *this url content is different from web site url*) <https://someurl.net/machines/0c459829-a5b1-4d4b-b3c3-18b03c1c969a/attachments/a30ceca7-198e-4d87-a550-04c97fbb9231/download> I have double check that there is no `href` attribute in that button tag. So I have use a plugin called clipboardy and I have added `plugins/index.js` file ``` const clipboardy = require('clipboardy'); module.exports = ( on ) => { on('task', { getClipboard () { return clipboardy.readSync(); } }); }; ``` In my test I have used cy.task() to get the clipboard content, but this is not printing the actual url content ``` cy.get('td').find('div').find('span').find('button').find('i').eq(0).click().then(()=>{ cy.task('getClipboard').then((data)=>{ console.log("Helloooo:"+data); }) }) ``` ```html <td class="sc-hgRTRy duUdhJ"> <div> <span class="sc-bYwvMP jTmLTC"> <span class="sc-jzJRlG iVpVVy"> <span role="button" aria-expanded="true" aria-haspopup="true" aria-owns="5aa03785-1370-455e-a838-4154f7481a7b"> <button class="sc-feJyhm cJOKrG"> <i class="icon fas fa-link sc-htpNat cQABgO" aria-hidden="true" data-component-type="icon"> </i> </button> </span> </span> </span> </div> </td> ``` [![enter image description here](https://i.stack.imgur.com/523LH.png)](https://i.stack.imgur.com/523LH.png)
Reading this really helped me solve my own issue, I had to use a mixture from the OP and the first comment. This is what worked for me: ``` cy.get(':nth-child(2) > .mat-card > .row > .col-sm-3 > .mat-focus-indicator').click().then(() => { cy.task('getClipboard').then(($clip) => { const url = $clip; cy.log('this is what was in clipboard', url); cy.visit(url); }); }); ``` This gave me the URL i wanted from the button I clicked. I then just passed that right into cy.visit to visit the url i just copied. Worked great.
Note: Above usage of window.navigator <https://stackoverflow.com/a/68871590/5667941> , only works for Electron. For Chrome user permisson would be required [![User permission request](https://i.stack.imgur.com/XQTpu.png)](https://i.stack.imgur.com/XQTpu.png)
Quick and easy question that I can't find a good solution to: What's a simple loop that will give the processor something to "chew on" for at least ten seconds? I've tried things like this but they finish in the blink of an eye: ``` int max = 300000; for (int i = 0; i < max; i++) { //do some random math here } ``` Is there some kind of calculation or other operation that can go in there to take up more time and use a bit of processor power? Or another way of accomplishing this?
According to your requirements: > > Is there some kind of calculation or other operation that can go in > there to take up more time and use a bit of processor power? > > > You can use DateTime and a while loop: ``` var start = DateTime.Now(); var end = start.AddSeconds(10); while (DateTime.Now() != end) {} ```
Try using a time based physical equation. For example: the distance travelled by a free falling object in a certain period of time (in seconds) until it reaches X distance. ``` private float Gety(float t){float V=t*9.8f; return ((V*V)/19.6f);} ``` You can set this in a loop where your exit point will be when the return is equal or greater then a chosen distance. By increasing and decreasing the time step you will perform more and more calculations until that distance or greater is reached. F.e: setting initial time to 0.0f and goal distance to 500, increasing the time step from 0.01f every iteration to 0.001f will perform more calculations accordingly until the break distance is reached. If looped within a loop and with a step of 0.0000000000001f you will do fine.
I use a Navbar as a component on page, which uses Router to change the content. Everything is working fine, so far. But I can´t figure out, how I can set the state of the links in the Navbar to active, when they are clicked. I think, I have to bind the activeKey of the Nav element to the location.pathname of the active content. This is my Navbar component: ``` import React from 'react'; import { Navbar, Nav } from 'react-bootstrap'; class Navbar extends React.Component{ constructor() { super(); this.state = { show: false }; } render(){ return( <div> <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark"> <Navbar.Brand >Filmmusic</Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav activeKey="/" className="mr-auto"> <Nav.Link href="/">Home</Nav.Link> <Nav.Link href="/about">About</Nav.Link> <Nav.Link onClick = {()=>{this.handleModal()}}>Contact</Nav.Link> </Nav> <Nav> <Nav.Link href="/impressum">Impressum</Nav.Link> <Nav.Link href="/datenschutzerklaerung">Datenschutzerklärung</Nav.Link> </Nav> </Navbar.Collapse> </Navbar> </div> ) } } export default Navbar; ```
Thanks a lot! Everything is working fine now :) I wrote the Navbar code into the index.js, instead of using a component. And I put all components below the Router element. Here is the final code of my index.js: ``` import React from 'react'; import ReactDOM from 'react-dom'; import './App.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import { BrowserRouter as Router, Route, Switch} from 'react-router-dom'; import { Home } from './components/Home'; import { About } from './components/About'; import { Contact } from './components/Contact'; import { NoMatch } from './components/NoMatch'; import { Impressum } from './components/Impressum'; import { Datenschutzerklaerung } from './components/Datenschutzerklaerung'; import { Layout } from './components/Layout'; import { Jumbotron } from './components/Jumbotron'; import Footer from './components/Footer'; import './fontawesome'; import { Navbar, Nav } from "react-bootstrap"; import { withRouter } from "react-router"; const Header = props => { const { location } = props; return ( <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark"> <Navbar.Brand >Filmmusic</Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav activeKey={location.pathname} className="mr-auto"> <Nav.Link href="/">Home</Nav.Link> <Nav.Link href="/about">About</Nav.Link> <Nav.Link href="/contact">Contact</Nav.Link> </Nav> <Nav activeKey={location.pathname}> <Nav.Link href="/impressum">Impressum</Nav.Link> <Nav.Link href="/datenschutzerklaerung">Datenschutzerklärung</Nav.Link> </Nav> </Navbar.Collapse> </Navbar> ); }; const HeaderWithRouter = withRouter(Header); class MyHeader extends React.Component { render() { return ( <React.Fragment> <Router> <HeaderWithRouter /> <Jumbotron /> <Switch> <Route exact path="/" component={Home} /> <Layout> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> <Route path="/impressum" component={Impressum} /> <Route path="/datenschutzerklaerung" component={Datenschutzerklaerung} /> </Layout> <Route component={NoMatch} /> </Switch> </Router> <Footer /> </React.Fragment> ); } } ReactDOM.render(<MyHeader />, document.getElementById('root')); ```
`withRouter` is deprecated since `react-router` v5.1 So you can just use location hook. ``` const location = useLocation(); ... <Nav activeKey={location.pathname} className="mr-auto"> ... ```
I am trying to use Visual Studio Code to Debug a MSTest unit test project. But the tests just run and the breakpoint is never reached. Here is my launch.json: ``` { "version": "0.2.0", "configurations": [ { "name": ".NET Core Test (console)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", "program": "C:\\Program Files\\dotnet\\dotnet.exe", "args": ["test"], "cwd": "${workspaceRoot}", "console": "internalConsole", "stopAtEntry": false, "internalConsoleOptions": "openOnSessionStart" }, { "name": ".NET Core Attach", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" } ] } ``` How can I debug a unit test (MSTest)? This same problem exists for XUnit.
Try <https://github.com/Microsoft/vstest-docs/blob/master/docs/diagnose.md#debug-test-platform-components> (assumes you're using dotnet-cli tools 1.0.0) ``` > set VSTEST_HOST_DEBUG=1 > dotnet test # Process will wait for attach # Set breakpoint in vscode # Use the NETCore attach config from vscode and pick the dotnet process ```
Before building, remember to include in your .csproj file `<GenerateProgramFile>false</GenerateProgramFile>` or else it will not know what to run... ``` Program.cs(160,21): error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point. [/Users/.../Fraction.csproj] ```
I am trying to fill in the blank in this sentence: "There is a(n) \_\_\_ of research on this topic." Using the word paucity would imply, to me, that I feel there is definitely not enough research and more needs to be done. However, what I am trying to say is that I know some amount of research has been done on the topic, and while there are certainly gaps in the knowledge yet to be filled, there is enough to justify a systematic review of the literature on the topic. The best word I've been able to come up with is abundance, but I don't think it's quite what I am looking for because I feel it implies that the topic is very well understood and further research is not necessary. Another possible answer would be "good amount". I think this fits my needs, but doesn't sound formal enough, as this is for an academic paper. A practical example of what I mean is this: Suppose you are driving on the highway with about 1/8 a tank of gas left and approaching an exit that has a gas station but no restaurant. Your passenger asks if you should stop for gas at this exit or wait for the next one so you can get lunch at the same time. Being away from home, you don't actually know how far the next exit with a gas station is, but because your car gets pretty good mileage and the area isn't extraordinarily rural you assume you have enough gas to get to the next exit and decide to stay on the highway. How could you describe this amount of fuel?
**substantial** or **significant** means more than a little but not necessarily enough. **non-trivial** is an even more direct antonym of 'sparse/ity' or 'little' or 'paucity', but slightly arch. But I do not agree with your highway example for 'more than a little but not necessarily enough'. If I think I have enough fuel, even if it's only a little, I'll stay on. If I think I don't have enough fuel, it's not safe to continue, regardless of how small or large that amount is. Plus, with GPS nav I *do* know both how far the next exit is *and* whether there's a restaurant -- and maybe even if it's a good one :-)
A plain **some**, as JeffUK suggested in a comment, would fit very well. It acknowledges existence without qualification, perhaps with a hint that it is not complete: "While there is **some [existing] research** on this topic more work needs to be done." "Some" can be accompanied to further describe the nature or amount of the research. Some of these examples are from other answers: some ***initial* or *basic*** research, some ***substantial* or *considerable*** research. If it is unsystematic, one could call it some ***scattered* or *haphazard*** research. A small, uncoordinated effort one could call "a **[*smattering*](https://www.merriam-webster.com/dictionary/smattering) of research".**
В интернете встретил задание: В русском языке существует слово, которое часто входит в состав лингвистических терминов. У этого слова в составе терминов есть два антонима. При этом у этих антонимов одна и та же приставка, а корни имеют противоположное значение. Что это за слово? Ответ мне неизвестен. Может, вы знаете?
Я думаю, это термин **ассимиляция** (уподобление): оглушение, озвончение. Если это задание для старшеклассников, они должны знать этот термин.
Я согласен с Людмилой, задание надо понимать именно так, речь идет о поиске двух антонимов друг к другу, а не двух антонимов к одному исходному термину ("слову"), как можно подумать из-за безобразной формулировки. Но фокус-то в том, что подобных терминов можно найти если не вагон с тележкой, то уж явно не один. Помимо ***озвончающей-оглушающей ассимиляции*** вспомнились: ***повышающая-понижающая интонация*** ***уменьшительный-увеличительный суффикс*** и несколько менее очевидных. (+) Посмотрел по второй ссылке от Людмилы (<https://www.liveexpert.ru/topic/view/3240117-zadanie-v-russkom-yazike-sushestvuet-slovo-kotoroe-chasto-vhodit-v-sostav-lingvisticheskih-terminov-u-etogo-slova-v-sostave-terminov-est>). Если считать, что приведенные там три задания из одного источника, то есть основания считать, что мы наговариваем на автора. Два других задания вполне разумно составлены. Следовательно, надо искать именно одно слово, у которого есть два антонима с указанными признаками. Хотя такое и крайне маловероятно. Я даже вне лингвистики не могу придумать примера двух слов с одинаковыми приставками и противоположными корневыми морфами - по сути антонимами друг к другу! - которые были бы еще антонимами к третьему слову. Невероятное сочетание трех попарно антонимичных слов. Вот что-то такое: ***стоять - пойти/положить?*** Но это весьма слабые антонимы.
Lets say I have a table with the following rows/values: [![[1]](https://i.stack.imgur.com/b1jpS.png)](https://i.stack.imgur.com/b1jpS.png) I need a way to select the values in amount but only once if they're duplicated. So from this example I'd want to select A,B and C the amount once. The SQL result should look like this then: [![enter image description here](https://i.stack.imgur.com/Jipg2.png)](https://i.stack.imgur.com/Jipg2.png)
Use LAG() function and compare previous amount with current row amount for name. ``` -- MySQL (v5.8) SELECT t.name , CASE WHEN t.amount = t.prev_val THEN '' ELSE amount END amount FROM (SELECT * , LAG(amount) OVER (PARTITION BY name ORDER BY name) prev_val FROM test) t ``` Please check from url <https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8c1af9afcadf2849a85ad045df7ed580>
If you are using mysql 8 you can use `row_number` for this: ``` with x as ( select *, row_number() over(partition by name order by amount) rn from t ) select name, case when rn=1 then amount else '' end amount from x ``` See [example Fiddle](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e976e655ff0625069e4be6d2abbf7f5b)
I use DevExpress Spreadsheet in my own project. I created a button in the ribbon for doing some calculation over cells. It gets information from cells of a sheet and creates a new sheet and calculation results are written into its rows and cells. Those calculations are done over more than 5000 rows. The UI freezes for about 10 seconds. I don't want to use progress bar, but I'd use a progress animation comes with DevExpress (it's called progress panel and is like Windows 10 loading dots). I tried to use BackGroundWorker to avoid UI freeze. Because of cross-thread nature of my operations (creating sheet, writing data in cells ...) I cannot use them directly in DoWork section. So, I use Invoke and Delegation. But my UI and progress animation is still non-responsive during process. ``` private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e) { if (!backgroundWorker1.IsBusy) { backgroundWorker1.RunWorkerAsync(); } } private void FillCell(string _sheetName) { IWorkbook workbook = spreadsheetControl.Document; Worksheet worksheet = workbook.Worksheets["DataSet1"]; CellRange range = worksheet.GetDataRange(); int LastRow = range.BottomRowIndex; var keys = new List<string>(); var values = new List<int>(); for (int i = 0; i < LastRow + 1; i++) { if (worksheet.Cells[i, 10].DisplayText == "خاتمه یافته") { keys.Add(string.Join(",", worksheet.Cells[i, 28].DisplayText, worksheet.Cells[i, 0].DisplayText, worksheet.Cells[i, 9].DisplayText, worksheet.Cells[i, 15].DisplayText, worksheet.Cells[i, 31].DisplayText)); values.Add((int)worksheet.Cells[i, 32].Value.NumericValue); } } var mydic = new Dictionary<string, int>(); for (int i = 0; i < keys.Count; i++) { if (mydic.ContainsKey(keys[i])) { mydic[keys[i]] += values[i]; } else { mydic.Add(keys[i], values[i]); } } foreach (var item in mydic.Keys) { keys.Add(item); } foreach (var item in mydic.Values) { values.Add(item); } for (int i = 0; i < mydic.Count; i++) { string text = keys[i]; string[] rewrite = text.Split(','); workbook.Worksheets[_sheetName].Cells[i, 0].SetValue(rewrite[0]); workbook.Worksheets[_sheetName].Cells[i, 1].SetValue(rewrite[1]); workbook.Worksheets[_sheetName].Cells[i, 2].SetValue(rewrite[2]); workbook.Worksheets[_sheetName].Cells[i, 3].SetValue(rewrite[3]); workbook.Worksheets[_sheetName].Cells[i, 4].SetValue(rewrite[4]); } for (int i = 0; i < mydic.Count; i++) { int text = values[i]; workbook.Worksheets[_sheetName].Cells[i, 5].SetValue(text); } } private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { IWorkbook workbook = spreadsheetControl.Document; Worksheet worksheet = workbook.Worksheets["DataSet1"]; if (worksheet.HasData) { if (spreadsheetBarController1.Control.InvokeRequired) { //***Instead of (Action), we can use (MethodInvoker)*** spreadsheetBarController1.Control.Invoke((Action)delegate { CreateSheet("Summarized"); }); spreadsheetBarController1.Control.Invoke((MethodInvoker)delegate { ClearSheet("Summarized"); }); spreadsheetBarController1.Control.Invoke((Action)delegate { FillCell("Summarized"); }); } } else { MessageBox.Show("خطای داده ورودی", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { progressPanel1.Visible = false; } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressPanel1.Visible = true; } } ```
First of all try to use `workbook.BeginUpdate()` at the begin of your `FillCell` method to suppress the `SpreadsheetControl`'s visual updates and improve its performance when you perform multiple changes to a spreadsheet document. Also use `workbook.EndUpdate()` at the end of your `FillCell` method to unlocks the control and enable all the changes to take effect.
I used DevExpress.Docs assembly that works very faster than filling the cells manually. My calculated data are put into a DataTable and then are brought to the cells in less than a second.
I am rendering a form in Asp.net MVC with a submit button. The page redirects after successful record addition into the database. Following is the code :- ``` [HttpPost] public ActionResult Create(BrandPicView brandPic) { if (ModelState.IsValid) { if (!String.IsNullOrEmpty(brandPic.Picture.PictureUrl)) { Picture picture = new Picture(); picture.PictureUrl = brandPic.Picture.PictureUrl; db.Pictures.Add(picture); brandPic.Brand.PictureId = picture.Id; } db.Brands.Add(brandPic.Brand); db.SaveChanges(); return RedirectToAction("Index"); } return View(); } ``` But, while testing, I saw that if the form is clicked again and again, the multiple entries are submitted and saved into the database. How can i make sure that if the form has been submitted once to the server, then no duplicates are submitted.
The solution for mvc applications with mvc client side validation should be: ``` $('form').submit(function () { if ($(this).valid()) { $(':submit', this).attr('disabled', 'disabled'); } }); ```
``` window.onload = function () { $("#formId").submit(function() {// prevent the submit button to be pressed twice $(this).find('#submitBtnId').attr('disabled', true); $(this).find('#submitBtnId').text('Sending, please wait'); }); } ```
I'm using PuTTY on Ubuntu 14.04 (Trusty Tahr) to connect to a serial port. I need to copy text from a PuTTY window to another window (for example, [gedit](https://en.wikipedia.org/wiki/Gedit)). **UPDATE** I can copy by selecting text with the mouse and paste it by mouse middle click. But it does not work when I paste from another window. **UPDATE1** I haven't succeeded to fix this issue, but I've switched to the Ubuntu-native application GtkTerm which can copy-paste as usual from the Ubuntu terminal.
I've copied from the [PuTTY manual](http://the.earth.li/~sgtatham/putty/0.52/htmldoc/Chapter3.html#3.1.1): > > PuTTY's copy and paste works entirely with the mouse. In order to copy text to the clipboard, you just click the left mouse button in the terminal window, and drag to select text. When you let go of the button, the text is automatically copied to the clipboard. You do not need to press `Ctrl`-`C` or `Ctrl`-`Ins`; in fact, if you do press `Ctrl`-`C`, PuTTY will send a `Ctrl`-`C` character down your session to the server where it will probably cause a process to be interrupted. > > >
Simple; just highlight the text in putty and right click. Note, though, that this will also paste the text into whatever you are working on in Putty. For example, if you are copying text from Vim or Nano, highlight the text you want to copy, right click it, and then quit without saving.
I want get two element from page and put into one object ``` const entryElements = await page.$$('div.kpi-entry'); const contents = await Promise.all( entryElements.map(async (element) => { const objValue= await (await element.$('span.text-xl'))?.innerText(); const objKey= await (await element.$('eui-base-v0-tooltip'))?.innerText(); const kpiObject = {objValue,objKey,}; return obj; }) ``` ); obj returns ``` { objValue: '1', objKey: 'A' }, { objValue: '2', objKey: 'B' }, { objValue: '3', objKey: 'C' }, { objValue: '4', objKey: 'D' }, { objValue: '5', objKey: 'E' } ``` but I expected ``` { A: '1', B: '2', C: '3', D: '4', E: '5', } ``` what is the best wat to do this
Just exclude the first entry and then sort the remaining, later just append the first country to the result ``` lista = [['countries', 2019, 2020, 2025],['aruba', 2,2,1],['barbados', 2,2,2],['japan', 2,2,3]] sortedout = sorted(lista[1:],key=lambda x:x[-1], reverse=True) out = [lista[0]]+sortedout print(out) ``` output will be ``` [['countries', 2019, 2020, 2025], ['japan', 2, 2, 3], ['barbados', 2, 2, 2], ['aruba', 2, 2, 1]] ```
Only sort the list starting at the element at index 1 and use a key function that retrieves the last element of the inner list. Then add this new sorted list to the element at index 0. ``` lista = [['countries', 2019, 2020, 2025],['japan', 2,2,3],['barbados', 2,2,2],['aruba', 2,2,1]] result = lista[0] + sorted(lista[1:], key=lambda x: x[-1]) print(result) ``` This will give you `['countries', 2019, 2020, 2025, ['aruba', 2, 2, 1], ['barbados', 2, 2, 2], ['japan', 2, 2, 3]]`
I have some dates that look like this: > > 20160517124945-0600 > > > 20160322134822.410-0500 > > > 20160322134822-0500 > > > I used [RegexMagic](http://www.regexmagic.com/) to find this regex: ``` (?:[0-9]+){14}\.?(?:[0-9]+){0,3}-(?:[0-9]+){4} ``` The problem is it also accepts things like this: > > 20160322134822-05800 > > > or > > 20160323542352352352134822-0500 > > > Apparently `{}` doesn't mean what I thought it did. How can I ensure I can only enter 14 digits before the `-` (or optional `.`) and 4 after?
Here's my version: ``` ^[0-9]{14}(\.[0-9]{1,3})?-[0-9]{4}$ ``` For some reason I always like using [0-9] instead of \d * So we're doing the start of the string with: ^ * Then 14 numbers 0-9 * Then an optional group starting with a period and then up to three numbers (I'm assuming a period and then no numbers after wouldn't be acceptable. This is in contrast to what you posted) * A hyphen * Four numbers * Then the end of the string with: $
I suppose you could simplify your regexp like this: ``` ^(\d{14})(\.\d{3})?(-\d{4})$ ``` test <https://regex101.com/r/lF9gX0/1>
I am using this code to load a url in `UIWebView`. A white screen appears only ``` - (void)viewDidLoad { [super viewDidLoad]; NSString *link = @"http://www.apple.com/"; NSURL *url = [[NSURL alloc] initWithString:link]; NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url]; [webView loadRequest:req]; } ```
Does your HTML contain `<hr>` tag? It's not supported in HTMLworker.
I have similar problem. I can find myself that giving HTMLTagProcessors to HTMLWorker solves this problem. ``` HTMLWorker htmlworker = new HTMLWorker(document, new HTMLTagProcessors(), null); ``` Now some HTML tags are supported by HTMLWorker.
I use python Appengine. I'm trying to create a link on a webpage, which a user can click to download a csv file. How can I do this? I've looked at csv module, but it seems to want to open a file on the server, but appengine doesn't allow that. I've looked at remote\_api, but it seems that its only for uploading or downloading using app config, and from account owner's terminal. Any help thanks.
Pass a `StringIO` object as the first parameter to `csv.writer`; then set the content-type and content-disposition on the response appropriately (probably "text/csv" and "attachment", respectively) and send the `StringIO` as the content.
I used this code: ``` self.response.headers['Content-Type'] = 'application/csv' writer = csv.writer(self.response.out) writer.writerow(['foo','foo,bar', 'bar']) ``` Put it in your handler's get method. When user requests it, user's browser will download the list content automatically. Got from: [generating a CSV file online on Google App Engine](https://stackoverflow.com/questions/11164686/generating-a-csv-file-online-on-google-app-engine)
in my query here <https://www.db-fiddle.com/f/nfJzZoYC5gEXLu8hrw4JT2/1> ``` SELECT id, COUNT(DISTINCT tc1.co_id), COUNT(DISTINCT tc2.co_id) FROM test t INNER JOIN test_corelation_1 tc1 ON tc1.test_id = t.id AND tc1.co_id IN ( SELECT co_id FROM test_corelation_1 WHERE test_id IN (1, 2, 5) GROUP BY co_id ) INNER JOIN test_corelation_2 tc2 ON tc2.test_id = t.id AND tc2.co_id IN ( SELECT co_id FROM test_corelation_2 WHERE test_id IN (1, 2, 5) GROUP BY co_id ) GROUP BY t.id ORDER BY (COUNT(DISTINCT tc1.co_id) + COUNT(DISTINCT tc2.co_id)) ASC; ``` i am trying getting all the ids from table `test` that shares similar ids corelated to the `ids 1, 2, 3` then sorting it by the least similar by counting it which results in this | id | COUNT(DISTINCT tc1.co\_id) | COUNT(DISTINCT tc2.co\_id) | | --- | --- | --- | | 3 | 1 | 3 | | 2 | 3 | 7 | | 1 | 5 | 6 | but it gets very very slow the more ids i am checking for its similarities and i do not know how to optimize it further from this and i thought of using CTE but it had same results in the optimizer explain
You can use this version of [reduce](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-U-java.util.function.BiFunction-java.util.function.BinaryOperator-) : ``` public static String pointUnderlineRunnables(String line, String regex) { String underline = Pattern.compile(regex) .matcher(line) .results() .filter(mRes -> ProgramHelper.isRunnableCode(mRes.start(), line)) .reduce("", (str,mr) -> str.concat(" ".repeat(mr.start() - str.length()) + "^".repeat(mr.end() - mr.start())), String::concat); return line.strip() + "\n" + underline; } ``` To make it somehow readable you could extract the BiFunction: ``` public static String pointUnderlineRunnables(String line, String regex) { BiFunction<String,MatchResult,String> func = (str,mr) -> str.concat(" ".repeat(mr.start() - str.length()) + "^".repeat(mr.end() - mr.start())); String underline = Pattern.compile(regex) .matcher(line) .results() .filter(mRes -> ProgramHelper.isRunnableCode(mRes.start(), line)) .reduce("",func::apply, String::concat); return line.strip() + "\n" + underline; } ```
Based on your original question and subsequent comments, I would just use a regular loop to accomplish it. In this version I don't remove anything from the original string. ``` String line = " to be or not to be that is the question. "; String regex = "to\\s+be"; String result = pointUnderlineRunnables(line, regex); System.out.println(result); ``` prints ``` to be or not to be that is the question. ^^^^^ ^^^^^^^^ ``` * first establish a [Matcher](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Matcher.html) with the provided arguments. * instantiate a [StringBuilder](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuilder.html#StringBuilder()) to hold the underline. * the iterate over the matches using `Matcher.find()` * The operation is: + append blanks up to the start of the match. + now append "^" for a length of match using `Matcher.group().length()` * return the original and underline separated by a new line. ``` public static String pointUnderlineRunnables(String line, String regex) { Matcher m = Pattern.compile(regex).matcher(line); StringBuilder sb = new StringBuilder(); while (m.find()) { sb.append(" ".repeat(m.start()-sb.length())); sb.append("^".repeat(m.group().length())); } return line + "\n" + sb.toString(); } ``` Note that since `StringBuilder` returns its own reference via append I could have combined the two appends. But I think the above is clearer.
I have created an `EditText` for search, which contains on the left side a search icon and on the right side of icon: ``` <EditText android:id="@+id/Search" android:layout_width="250dp" android:layout_height="wrap_content" android:drawableLeft="@android:drawable/ic_menu_search" android:drawableRight="@android:drawable/ic_delete" android:hint="Search Product .." > </EditText> ``` I want to know how can I clear the content of `EditText` when I click the cross button. Thank you in advance.
Try this: activity\_main.xml ``` <FrameLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="9dp" android:padding="5dp"> <EditText android:id="@+id/Search" android:layout_width="250dp" android:layout_height="wrap_content" android:drawableLeft="@android:drawable/ic_menu_search" android:hint="Search Product .." > </EditText> <Button android:id="@+id/clearText" android:layout_width="23dp" android:layout_height="23dp" android:layout_marginRight="10dp" android:layout_gravity="right|bottom" android:layout_marginBottom="10dp" android:background="@android:drawable/ic_delete" android:onClick="clear"/> </FrameLayout> ``` MainActivity.java ``` public class MainActivity extends AppCompatActivity { EditText mEditText; Button mClearText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mEditText = (EditText) findViewById(R.id.Search); mClearText = (Button) findViewById(R.id.clearText); //initially clear button is invisible mClearText.setVisibility(View.INVISIBLE); //clear button visibility on text change mEditText.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { //do nothing } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { //do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() != 0) { mClearText.setVisibility(View.VISIBLE); } else { mClearText.setVisibility(View.GONE); } } }); } //clear button onclick public void clear(View view) { mEditText.setText(""); mClearText.setVisibility(View.GONE); } } ```
Exemple I made: ``` mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_UP){ // 100 is a fix value for the moment but you can change it // according to your view if (motionEvent.getX()>(view.getWidth()-100)){ ((EditText)view).setText(""); } } return false; } }); mPasswordView.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.toString().trim().length()==0){ mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } else { mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_black_24dp, 0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub if (s.toString().trim().length() == 0) { mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } else { mPasswordView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_close_black_24dp, 0); } } }); ```
There's a multiple-night company retreat involving travel taking place that I have no interest in attending (for family reasons). It was stated that anyone who chooses not to attend must use PTO for the workdays missed if not attending the retreat, with the reasoning that the office will be closed for the retreat. Myself and others however have been working from home consistently, so I see no reason why I couldn't work the handful of days from home and save my PTO. I'll have a chance to discuss this idea with my manager in the next couple of weeks; however, I'm not sure I should bother in the first place, as I have a feeling they won't be able to budge on the PTO usage. A part of me feels like I should just be thankful for the time off and take it... Any advice on how to approach the situation would be appreciated.
If you're in the USA, most employers are legally allowed to require employees to take vacation time on specific days (forced vacation). Your state may have laws governing vacation time, so you should check what your state laws allow. That being said, if your state doesn't have specific laws regarding this then you're best bet is to take the PTO time as directed and not make an issue of it.
You can of course go to the retreat. The company pays for it as work, you don’t lose any money, you don’t lose any holiday entitlement. This seems the better of your two alternatives. Choice A: Sit at home for three days and three days holiday entitlement gone. Choice B: Go to the retreat, and have three days holiday at a time it suits you.
This [question](https://academia.stackexchange.com/questions/9706/journalscomputer-science-that-are-suitable-for-low-impact-publications) and this [question](https://academia.stackexchange.com/questions/9651/professor-withholding-course-grade-until-submission-of-conference-paper) suggest that it is not uncommon/unheard of for departments to require publication by students (generally masters and doctoral) either to get credit for a course or graduate. This seems to me like a way of off loading the assessment of students to peer reviewer, and therefore it seems ethically questionable. Is there a pedagogical reason to require externally peer-reviewed publication?
First things first: a doctoral student *should* be expected to publish something other than a thesis. Even if she has no desire to enter into a research profession after the PhD, publication of scholarly articles should be an important milestone in the process. Beyond that, however, expecting that a student—whether a master's student or a PhD student, or even worse, an undergraduate—publish a paper as part of a single "course"—is absurd for a multitude of reasons. First, in the context of a single educational course, the time spent will almost certainly be unsuitable for the preparation of a manuscript; moreover, given the lag times in between submission of an article to a journal or conference and its acceptance, it is unlikely that it can be completed within either a trimester or even a semester, which means that incomplete grades will likely be par for the course. Thus, since it serves no real valid educational purpose for the students—since the work isn't being evaluated by the educational staff whose job it is to provide instruction—such behavior is extremely questionable, and very likely unethical. This is doubly so if the only criterion for grading is the acceptance of the paper in an external journal, particularly since there are so many "pay-to-publish" journals out there that will publish anything, given the page charges. Now, I *do* require that students prepare something like a research article for one of the courses I teach. However, I do that as an exercise in *preparing* them for writing research articles. I have *no* expectation that they would bother to submit these papers to actual journals—the material just isn't sufficient for that. However, in terms of learning how to write a paper—mentioning relevant literature, explaining their methodology, clearly demonstrating and illustrating their results, there is nothing comparable. You learn to be a researcher by *doing research*—and that includes writing about research!
The problem certainly seems fishy and whether it is unethical or not probably depends on what the (local) rules and regulations governing courses will be as well as the possible ramafications of the process relative to those regulations. The main issue for me is what will be the purpose of having publications as a requirement for students (not at graduate level). There is of course nothing wrong if undergraduate papers can be published, and experiencing the publication process can be valuable. But as one of the posts referred to in the question states, it seemed as if the requirement was to submit, not to publish. I do not see any particular value in that experience that could not be replicated within the department itself. Since any publication process requires quite a chunk of time I can see a major problem in the timing. In my system, a course should be possible to complete within the stipulated time (corresponding to the number of credits). Imposing a system where publication is part could (really would) clearly violate such limitations. So, a follow-up question would be "are there systems where courses can be open ended?" or "can courses be required to last until an un-controllable goal is achieved?". If the system allows such cases, then the requirement would be ok from a legal point of view. I would still think it is in a grey zone. Your point of off-loading the assessment is part of the shady picture. I would have thought that each university regulatory system would have some, at least, recommendations on how quickly assessments must be done and, again, assessing through journal peer review would require at least as much time as the length of a typical course itself. So as a whole, I think that using paper submission and/or publication as part of course requirements can be violations of local assessment regulations and very poor behaviour. I would call it unethical if it means unnecessarily prolonging the students graduation or impacting on their ability to get student's loans (equivalent) due to not getting credits in time (impacting their ability to take responsibility for their timing).
I started a blank tvOS project and created the following code: ``` - (void)viewDidLoad { [super viewDidLoad]; AVPlayer *avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.myurl.com/myvideo.mp4"]]; AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer]; avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height); [self.view.layer addSublayer:avPlayerLayer]; [avPlayer play]; } ``` Nothing happens in the simulator though once the app loads. No video, nothing, just a blank translucent screen in my Apple TV simulator. What's the proper way to play a sample video on app launch for an Apple TV app from an HTTP source?
I just pasted your code in my tvOS sample project, replaced the URL and ran it. Nothing happened. Well, except for the fact that there's a log entry telling me that App Transport Security has blocked my URL request. So I headed to the Info.plist, [disabled ATS](https://stackoverflow.com/a/31808859/1025706) and upon next launch the video showed up just fine. So if you're also using a non-HTTPS URL you're very likely running into this issue which is easily fixed by either using an HTTPS URL, disabling ATS completely or allowing specific non-HTTPs URLs in your Info.plist. P.S.: I used [this video](http://techslides.com/demos/sample-videos/small.mp4) for testing.
You could also use TVML and TVMLJS <https://developer.apple.com/library/prerelease/tvos/documentation/TVMLJS/Reference/TVJSFrameworkReference/> Adhere to the 'TVApplicationControllerDelegate' protocol and add some properties. **AppDelegate.h** ``` @interface AppDelegate : UIResponder <UIApplicationDelegate, TVApplicationControllerDelegate> ``` ... ``` @property (strong, nonatomic) TVApplicationController *appController; @property (strong, nonatomic) TVApplicationControllerContext *appControllerContext; ``` Then add the following to 'didFinishLaunchingWithOptions' **AppDelegate.m** ``` #define url @"http://localhost:8000/main.js" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.appControllerContext = [[TVApplicationControllerContext alloc] init]; NSURL *javascriptURL = [NSURL URLWithString:url]; self.appControllerContext.javaScriptApplicationURL= javascriptURL; for (id key in launchOptions) { id val=[launchOptions objectForKey:key]; NSLog(@"key=%@ value=%@", key, val); if([val isKindOfClass:[NSString class]]) [self.appControllerContext.launchOptions objectForKey:val]; self.appController = [[TVApplicationController alloc] initWithContext:self.appControllerContext window:self.window delegate:self]; } return YES; } ``` create a folder and add the following files * main.js * index.tvml **main.js** ``` function launchPlayer() { var player = new Player(); var playlist = new Playlist(); var mediaItem = new MediaItem("video", "http://trailers.apple.com/movies/focus_features/9/9-clip_480p.mov"); player.playlist = playlist; player.playlist.push(mediaItem); player.present(); //player.play() } //in application.js App.onLaunch = function(options) { launchPlayer(); } ``` *careful with this **url** in the mediaItem* Set up a [template](https://developer.apple.com/library/prerelease/tvos/documentation/LanguagesUtilities/Conceptual/ATV_Template_Guide/TextboxTemplate.html#//apple_ref/doc/uid/TP40015064-CH2-SW8) of your choice. **index.tvml** ``` <document> <alertTemplate> <title>…</title> <description>…</description> <button> <text>…</text> </button> <text>…</text> </alertTemplate> </document> ``` open terminal and navigate to this folder then run ``` python -m SimpleHTTPServer 8000 ``` make sure the port here is the port in your ObjC url. The Apple examples use 9001. See these tutorials for more info <http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-with-swift/> <http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-part-2/> One issue I ran into was trying to play a local video file. It wouldn't work and there were constraint issues etc. It looks like you can't use python to play the videos so either try apache or link to a video on the web. This [SO](https://stackoverflow.com/questions/32518673/setting-up-apple-tv-video-javascript) answer pointed me there.
i'm trying to develop a simple file encrypter-decrypter app. on android devices.user picks whichever file he/she wants and encrypt or decrypt it using aes.this process is allowed for internal storage but when i choose a file in sd card it causes an error i can't find a solution for a long time. i have permissions in manifest.xml: ``` <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/> ``` also i ask user for runtime permissions(despite user allows permissions the result is "permission denied" error). the error generated in th log is: ``` W/System.err: java.io.FileNotFoundException: storage/3962-3235/Download/dummyFileEncrypted.txt: open failed: EACCES (Permission denied) ``` where the error occurs in the encrypt function while the output file is being created, with line: ``` FileOutputStream outputStream=new FileOutputStream(outputFile); ``` as i said process works perfectly when i pick a file from internal storage. any advice would be welcome. thanks in advance. as of 22.04.22 here is my trial to delete a file in sd card: this is my file picker: ``` btnFileCh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //TODO buraya ipaul file chooser shower // Create the ACTION_GET_CONTENT Intent Intent getContentIntent = FileUtils.createGetContentIntent(); Intent intent = Intent.createChooser(getContentIntent, "Select a file"); startActivityForResult(intent, REQUEST_CHOOSER); } }); public static Intent createGetContentIntent() { // Implicitly allow the user to select a particular kind of data final Intent intent = new Intent(Intent.ACTION_GET_CONTENT); // The MIME data type filter intent.setType("*/*"); // Only return URIs that can be opened with ContentResolver intent.addCategory(Intent.CATEGORY_OPENABLE); return intent; } public static final int READ_WRITE_PERMISSIONS = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION; public static void grantFileReadWritePermissions(Context targetUi, Intent intent, Uri uri) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { List<ResolveInfo> resInfoList = targetUi.getApplicationContext() .getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; targetUi.getApplicationContext().grantUriPermission(packageName, uri, READ_WRITE_PERMISSIONS); } } } ``` and onActivityResult event: ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //TODO buraya ipaul file chooserdan dönen değerler ile işlemler switch (requestCode) { case REQUEST_CHOOSER: if (resultCode == RESULT_OK) {// if (data != null) { final Uri uri = data.getData();// Get the URI of the selected file try {//trial deletion FileUtils.grantFileReadWritePermissions(getApplicationContext(),data,uri); DocumentsContract.deleteDocument(getApplicationContext().getContentResolver(),uri); return; } catch (FileNotFoundException e) { e.printStackTrace(); } ... ``` but no deletion occurs and causes error: ``` 2022-04-22 11:29:37.636 8288-8341/? E/DatabaseUtils: Writing exception to parcel java.lang.SecurityException: Permission Denial: writing com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/document/3962-3235%3ADownload%2FdummyFile.txt from pid=8960, uid=10256 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission() at android.content.ContentProvider.enforceWritePermissionInner(ContentProvider.java:824) at com.android.externalstorage.ExternalStorageProvider.enforceWritePermissionInner(ExternalStorageProvider.java:149) at android.provider.DocumentsProvider.callUnchecked(DocumentsProvider.java:1163) at android.provider.DocumentsProvider.call(DocumentsProvider.java:1067) at com.android.externalstorage.ExternalStorageProvider.call(ExternalStorageProvider.java:611) at android.content.ContentProvider.call(ContentProvider.java:2173) at android.content.ContentProvider$Transport.call(ContentProvider.java:477) at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:277) at android.os.Binder.execTransactInternal(Binder.java:1056) at android.os.Binder.execTransact(Binder.java:1029) 2022-04-22 11:29:37.646 8960-8960/com.example.basiccryptor E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.basiccryptor, PID: 8960 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/3962-3235:Download/dummyFile.txt flg=0x1 }} to activity {com.example.basiccryptor/com.example.basiccryptor.ActivityFilePicker}: java.lang.SecurityException: Permission Denial: writing com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/document/3962-3235%3ADownload%2FdummyFile.txt from pid=8960, uid=10256 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission() at android.app.ActivityThread.deliverResults(ActivityThread.java:5230) at android.app.ActivityThread.handleSendResult(ActivityThread.java:5271) at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2216) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:237) at android.app.ActivityThread.main(ActivityThread.java:7948) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075) Caused by: java.lang.SecurityException: Permission Denial: writing com.android.externalstorage.ExternalStorageProvider uri content://com.android.externalstorage.documents/document/3962-3235%3ADownload%2FdummyFile.txt from pid=8960, uid=10256 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission() at android.os.Parcel.createException(Parcel.java:2088) at android.os.Parcel.readException(Parcel.java:2056) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140) at android.content.ContentProviderProxy.call(ContentProviderNative.java:658) at android.content.ContentResolver.call(ContentResolver.java:2049) at android.provider.DocumentsContract.deleteDocument(DocumentsContract.java:1422) at com.example.basiccryptor.ActivityFilePicker.onActivityResult(ActivityFilePicker.java:247) at android.app.Activity.dispatchActivityResult(Activity.java:8292) at android.app.ActivityThread.deliverResults(ActivityThread.java:5223) at android.app.ActivityThread.handleSendResult(ActivityThread.java:5271)  at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2216)  at android.os.Handler.dispatchMessage(Handler.java:107)  at android.os.Looper.loop(Looper.java:237)  at android.app.ActivityThread.main(ActivityThread.java:7948)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)  ``` i guess i miss something in this mechanism but what?any suggestion?
Yes, micro sd cards are read only since Android KitKat. Only one app specific directory is writable for your app. Have a look at the second item returned by getExternalFilesDirs() for writable location. Or use Storage Access Framework if you wanna write at other locations.
You should check they, I recommend using framework. * <https://developer.android.com/about/versions/11/privacy/storage> * <https://medium.com/swlh/sample-for-android-storage-access-framework-aka-scoped-storage-for-basic-use-cases-3ee4fee404fc>
I am new to python and I'm trying to understand how to click on a dropdown menu where I select it through the name and not the value even though the name is shown multiple times throughout the code because each shirt has a different value where a jacket can have `14123` and a shirt has `14133` as the value. Here is My Code: ``` browser = webdriver.Chrome() Size=browser.find_element_by_xpath("//select[@name='X-Large']/option[@value='12218866729085']").click() ``` HTML Code EX for one shirt: ``` select id="product-select" name="id" class=""> option value="12218866630781">Small</option> option value="12218866663549">Medium</option> option value="12218866696317">Large</option> option value="12218866729085">X-Large</option> ``` Gives this error: > > ("//select[@name='X-Large']/option[@value ='12218866729085']").click() > AttributeError: 'str' object has no attribute 'click' > > >
pq.Array was the answer: ``` somevars := []int{1, 2, 3, 4} rows, err = db.Query("SELECT c1,c2 FROM table"+tid+" WHERE c1 = any($1);", pq.Array(somevars)) ```
An alternative solution is ``` somevars := []interface{}{1, 2, 3, 4} rows, err = db.Query( "SELECT c1,c2 FROM table"+tid+" WHERE c1 IN($1,$2,$3,$4);", somevars...) ``` Here the `...` expands a slice to multiple arguments, similar to the python `*args`. It's documented [in the language spec](https://golang.org/ref/spec#Passing_arguments_to_..._parameters). The `db.Query` API supports this so called variadic parameter. ``` func (db *DB) Query(query string, args ...interface{}) (*Rows, error) ``` Here `interface{}` is known as the empty interface, and it can hold values of any type. See the [Go tour example here](https://tour.golang.org/methods/14). So one can use it like `db.Query(stmt, var1, var2)` where `var1` `var2` could be of different types. In your case, you can also pass the slice elements explicitly ``` db.Query(stmt, somevars[0], somevars[1], somevars[2], somevars[3]) ``` But it is rather verbose and requires extra work when the slice length changes. Note that if instead of the `interface` slice `somevars`, we use `intvars := []int {1, 2, 3, 4}` and expand `intvars` in `db.Query()`, the compiler will complain on `intvars...` > > cannot use []int literal (type []int) as type []interface {} in assignment > > > Type conversion `intvars.([]interface{})` doesn't work either. This is documented in the [language spec FAQ](https://golang.org/doc/faq#convert_slice_of_interface). And there is also a [dedicated wiki page for it](https://github.com/golang/go/wiki/InterfaceSlice) > > It is disallowed by the language specification because the two types do not have the same representation in memory. > > > The intuitive picture of golang `interface` is an object with two fields, one field stores a type, and the other stores a pointer.
I have HTML page which have multiple check boxes and individually they can be checked. I have button select, so what I am suppose to do is. When I click on select all the check boxes should get selected, thousands record. **This is my page** ```html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>monitoring</title> <script src="jquery.js"></script> </head> <table id="example" class="myclass"/> <thead> <tr> <th> <button type="button" id="selectAll" class="main"> <span class="sub"></span> Select </button></th> <th>Name</th> <th>Company</th> <th>Employee Type</th> <th>Address</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox"/> </td> <td>varun</td> <td>TCS</td> <td>IT</td> <td>San Francisco</td> <td>US</td> </tr> <tr> <td><input type="checkbox"/> </td> <td>Rahuk</td> <td>TCS</td> <td>IT</td> <td>San Francisco</td> <td>US</td> </tr> <tr> <td><input type="checkbox"/> </td> <td>johm Doe</td> <td>TCS</td> <td>IT</td> <td>San Francisco</td> <td>US</td> </tr> <tr> <td><input type="checkbox"/> </td> <td>Sam</td> <td>TCS</td> <td>IT</td> <td>San Francisco</td> <td>US</td> </tr> <tr> <td><input type="checkbox"/> </td> <td>Lara</td> <td>TCS</td> <td>IT</td> <td>San Francisco</td> <td>US</td> </tr> <tr> <td><input type="checkbox"/> </td> <td>Jay</td> <td>TCS</td> <td>IT</td> <td>San Francisco</td> <td>US</td> </tr> <tr> <td><input type="checkbox"/> </td> <td>Tom</td> <td>TCS</td> <td>IT</td> <td>San Francisco</td> <td>US</td> </tr> </tbody> </table> </body> </html> ```
``` $(document).ready(function () { $('body').on('click', '#selectAll', function () { if ($(this).hasClass('allChecked')) { $('input[type="checkbox"]', '#example').prop('checked', false); } else { $('input[type="checkbox"]', '#example').prop('checked', true); } $(this).toggleClass('allChecked'); }) }); ``` [Example on jsFiddle](http://jsfiddle.net/tb8cm760/21/) This will add a class, *allChecked*, on the "Select All" button when all items have been checked (and remove it when all are unchecked). Also, it will only look within the `#example` (your table with id *example*) context. This can be tweaked to your liking of course, as with anything. Edit: And to make sure that your jQuery is loaded. Try this script tag instead (replace your current): ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> ``` Edit: Just updated the syntax in fiddle for `<table>` tag as it was not the self closing tag
You can try this: ``` $('#selectAll').click(function(e){ $(this).toggleClass('clicked'); $(this).closest('table').find('input[type="checkbox"]').prop('checked', $(this).hasClass('clicked')) }); ``` --- In this code what happening is: 1. First you bind the click on the button. 2. After click toggle a dummy classname to the button. 3. Then traverse up the the table and find all the checkboxes. 4. then change the property `checked` to `true/false` which depends on the class added to the button.
There is a famous example of a function that has no derivative: the Weierstrass function: [![enter image description here](https://i.stack.imgur.com/puevr.png)](https://i.stack.imgur.com/puevr.png) But just by looking at this equation - I can't seem to understand why exactly the Weierstrass Function does not have a derivative? I tried looking at a few articles online (e.g. <https://www.quora.com/Why-isnt-the-Weierstrass-function-differentiable>), but I still can't seem to understand what prevents this function from having a derivative? For example, if you expand the summation term for some very large (finite) value of $n$: $$ f(x) = a \cos(b\pi x) + a^2\cos(b^2\pi x) + a^3\cos(b^3\pi x) + ... + a^{100}\cos(b^{100}\pi x) $$ What is preventing us from taking the derivative of $f(x)$? Is the Weierstrass function non-differentiable only because it has "infinite terms" - and no function with infinite terms can be differentiated? For a finite value of $n$, is the Weierstrass function differentiable? Thank you!
In order to calculate the derivative of a function at a given point (e.g. $x=0$), you just need to [keep zooming](https://math.stackexchange.com/a/2833438/386794) on this point until the curve gets smooth: ![https://download.ericduminil.com/weierstrass_zoom.gif](https://download.ericduminil.com/weierstrass_zoom.gif) Oh, wait...
While others have given answers saying that a pointwise limit of differentiable functions needn’t be differentiable, *here is a simple example explaining why that is true*. One can find a limit of smooth functions which converge to the absolute value function which is not differentiable at $0$, as shown by the following image:[![enter image description here](https://i.stack.imgur.com/8RJoo.jpg)](https://i.stack.imgur.com/8RJoo.jpg)
What is the life cycle of an Android activity? Why are so many similar sounding methods (`onCreate()`, `onStart()`, `onResume()`) called during initialization, and so many others (`onPause()`, `onStop()`, `onDestroy()`) called at the end? When are these methods called, and how should they be used properly?
**Activity has six states** * *Created* * *Started* * *Resumed* * *Paused* * *Stopped* * *Destroyed* **Activity lifecycle** has seven methods * `onCreate()` * `onStart()` * `onResume()` * `onPause()` * `onStop()` * `onRestart()` * `onDestroy()` ![activity life cycle](https://i.stack.imgur.com/2CP6n.png) **Situations** * **When open the app** ``` onCreate() --> onStart() --> onResume() ``` * **When back button pressed and exit the app** ``` onPaused() -- > onStop() --> onDestory() ``` * **When home button pressed** ``` onPaused() --> onStop() ``` * **After pressed home button when again open app from recent task list or clicked on icon** ``` onRestart() --> onStart() --> onResume() ``` * **When open app another app from notification bar or open settings** ``` onPaused() --> onStop() ``` * **Back button pressed from another app or settings then used can see our app** ``` onRestart() --> onStart() --> onResume() ``` * **When any dialog open on screen** ``` onPause() ``` * **After dismiss the dialog or back button from dialog** ``` onResume() ``` * **Any phone is ringing and user in the app** ``` onPause() --> onResume() ``` * **When user pressed phone's answer button** ``` onPause() ``` * **After call end** ``` onResume() ``` * **When phone screen off** ``` onPaused() --> onStop() ``` * **When screen is turned back on** ``` onRestart() --> onStart() --> onResume() ```
I run some logs as per answers above and here is the output: **Starting Activity** ``` On Activity Load (First Time) ———————————————————————————————————————————————— D/IndividualChatActivity: onCreate: D/IndividualChatActivity: onStart: D/IndividualChatActivity: onResume: D/IndividualChatActivity: onPostResume: Reload After BackPressed ———————————————————————————————————————————————— D/IndividualChatActivity: onCreate: D/IndividualChatActivity: onStart: D/IndividualChatActivity: onResume: D/IndividualChatActivity: onPostResume: OnMaximize(Circle Button) ———————————————————————————————————————————————— D/IndividualChatActivity: onRestart: D/IndividualChatActivity: onStart: D/IndividualChatActivity: onResume: D/IndividualChatActivity: onPostResume: OnMaximize(Square Button) ———————————————————————————————————————————————— D/IndividualChatActivity: onRestart: D/IndividualChatActivity: onStart: D/IndividualChatActivity: onResume: D/IndividualChatActivity: onPostResume: ``` **Stopping The Activity** ``` On BackPressed ———————————————————————————————————————————————— D/IndividualChatActivity: onPause: D/IndividualChatActivity: onStop: D/IndividualChatActivity: onDestroy: OnMinimize (Circle Button) ———————————————————————————————————————————————— D/IndividualChatActivity: onPause: D/IndividualChatActivity: onStop: OnMinimize (Square Button) ———————————————————————————————————————————————— D/IndividualChatActivity: onPause: D/IndividualChatActivity: onStop: Going To Another Activity ———————————————————————————————————————————————— D/IndividualChatActivity: onPause: D/IndividualChatActivity: onStop: Close The App ———————————————————————————————————————————————— D/IndividualChatActivity: onDestroy: ``` In my personal opinion only two are required onStart and onStop. onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).
I'm having problems doing a For Each loop on a "List(Of KeyValuePair(Of" collection. I'm passing a ParamArray to a Function ``` ParamArray args() As List(Of KeyValuePair(Of String, Integer)) ``` I'm then trying to do a For Each on the Collection ``` For Each arg As KeyValuePair(Of String, Integer) In args ``` The error I'm getting is: > > Value of type 'System.Collections.Generic.List(Of System.Collections.Generic.KeyValuePair(Of String, Integer))' cannot be converted to 'System.Collections.Generic.KeyValuePair(Of String, Integer)' > > > I just can't figure out how to do this, and I can't find any examples of how to do this. My only thought right now is to do ``` For Each arg As Object In args ``` Then converting the object to a KeyValuePair, but there must be a neater way of doing this...
`args` is an array. That means that you have an array of `List(Of KeyValuePair(Of String, Integer))`. To access each item in a for each you will need to do this (untested): ``` For Each arg As List(Of KeyValuePair(Of String, Integer)) In args For Each kvp as KeyValuePair(Of String, Integer) In arg ' Do Stuff Next Next ``` As per my comment above: you'd probably be better off using a `Dictionary(Of String, Integer)` and some Linq statements. Edit: Also, depending on what you're trying to do with each item, modifying the item in any way will result in an exception because you can't modify a collection you're iterating over.
This declares an array of lists: ``` ParamArray args() As List(Of KeyValuePair(Of String, Integer)) ``` You probably meant an array of KVP (option #1): ``` ParamArray args As KeyValuePair(Of String, Integer) ``` Or (option #2): ``` args() As KeyValuePair(Of String, Integer) ``` Or (option #3): ``` args As List(Of KeyValuePair(Of String, Integer)) ```
The problem: ![Math problem](https://i.stack.imgur.com/jpWKB.png) My work: ![My work](https://i.stack.imgur.com/Fbbc5.png) I found the two integrals to be equal to each other, which is clearly not the desired result. Any suggestions/pointers? Thanks!
Yes. For instance, > > There exists a non-measurable subset of $\mathbb{R}$ (with respect to Lebesgue measure). > > > It requires the [axiom of choice](https://mathoverflow.net/questions/42215/does-constructing-non-measurable-sets-require-the-axiom-of-choice); so we could claim that it can't *really* be found. Any non-constructive proof would be another possible answer. See [Wikipedia on constructive proofs](http://en.wikipedia.org/wiki/Constructive_proof). --- Note the interesting, related question on MO: [Are there non-constructive existence proofs without the axiom of choice?](https://mathoverflow.net/questions/123608/non-constructive-existence-proofs-without-ac)
There are two opposite answers, both correct on their own terms. One is that in most situations that have distinct concepts of "finding an example" and "existence of an example", for which finding an example always implies an example exists (but no assumption is made about the reverse implication being valid or not in general), concrete instances can be shown where something "exists" but cannot be "found". For example: * seeing a dead body in some unusual place and circumstance, it might be easy to demonstrate with at least 99.9% certainty that there exists a murderer of that person, but finding the murderer with 99.9% certainty of the identification is far more difficult both logically and practically. * a prime factorization of a large number "exists", in the sense that theories of arithmetic have that statement and its generalizations as provable theorems, but one might not be able to "find" the prime factorization if that means writing it down, or computing it efficiently, from the description of the number. Tables of factorizations of special large numbers (such as Mersenne numbers, repunits, Fibonaccis, etc) include entries like C307 to mean a 307-digit factor that is known to be composite number but without a known factorization. * there "exists" a first-player win in finite two-player games such as $30 \times 30$ Tic Tac Toe or Chomp that are amenable to strategy-stealing arguments, but the resources to "find" and describe the winning strategy are vast compared to the resources needed to find the existence proof, and the strategy is not known. * there "exists" an optimal strategy for chess, or any finite two-player game with rules that forbid unlimited repetition of positions, but to "find" the strategy requires impossibly large resources compared to what is needed to show "existence". * the "exists" a shortest length of LISP computer code that will print out the *Baghavadad Gita*, but if that length is more than $1000$, no proof system that currently exists, such as formalized Zermelo-Fraenkel set theory, could "find" that program. Doing so would require writing down a program code, proving that it works by running it until termination, and a proof that the program is minimal-length, but no such proof exists in the proof system. --- The other point of view, which is approximately the "intuitionist" or "constructivist" position, is that: * the idea of existence proofs without any power to construct examples, is meaningless, and * any healthy notion of proof will either define existence proof to mean finding an example, or have the property that an abstract existence proof can always be materialized into a proof that a specific example exists (e.g., Numerical Existence Property in intuitionistic proof systems). In the finite examples, the supposed separation appears when there is an ability to efficiently describe and operate upon *elements* of a data structure (such as the positions and moves in the game tree of chess), and then extrapolating from that to an imaginary superpower to exhaustively search through the whole structure, and larger structures constructed from it (such as the space of strategies for black and for white). The problem in the infinite case is similar, where it is assumed that one can casually perform an infinite search to decide questions such as whether there "exists" a largest Fermat prime. If you reject the extrapolated abilities as no more than a pleasant fairy tale, it makes sense to reject the distinction between existence and the ability to find witnesses.
After importing View, and Button. I have created an object for Button, in this case "thomasButton". But error stated the field 'thomasButton" is not used even though I have called it at the next line. After awhile, I found that the field can be recognized if I put it in another scope. like this, but still the program wont run (crash when started). Do you guys know what is the correct way to setOnLongClickListener for a button? ``` package com.example.thoma.event; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void displayMessage(View v){ TextView thomasText = (TextView)findViewById(R.id.txt_View); thomasText.setText(R.string.rsc_Text2);x } Button thomasButton = (Button)findViewById(R.id.btn_Change); // weird but I can only use Button object within an inner scope { thomasButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { TextView thomasText = (TextView) findViewById(R.id.txt_View); thomasText.setText("Artificial"); // it will return false if long click wasnt long enough // and normal click will be called return true; } }); } } ``` Crash: Unfortunately, App has stopped
button initialize in `onCreate()` check below code. findViewById is costly so it will be better if you find those ids as minimum as possible ``` package com.example.thoma.event; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button thomasButton = (Button)findViewById(R.id.btn_Change); TextView thomasText = (TextView) findViewById(R.id.txt_View); thomasButton.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { thomasText.setText("Artificial"); // it will return false if long click wasnt long enough // and normal click will be called return true; } }); } public void displayMessage(View v){ TextView thomasText = (TextView)findViewById(R.id.txt_View); thomasText.setText(R.string.rsc_Text2); } } ```
Try this ``` import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button thomasButton = (Button)findViewById(R.id.btn_Change); thomasButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { TextView thomasText = (TextView) findViewById(R.id.txt_View); thomasText.setText("Artificial"); return false; } }); } } ```
I know there is a better way to do this but I can't seem to find it. As you can see below I am getting the longest and shortest results but only because I know what the longest and shortest words are and I then input a condition....but what if I didn't know the longest and shortest words... hope I am making myself clear. Just started with programming so have no prior experience. Many thanks for any help! ``` names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"] long = [] short = [] for name in names: if len(name) <= 4: short.append(name) print "Short names: ", short for name in names: if len(name) >=6: long.append(name) print "long names: ", long ```
You can find the len of the shortest and longest name with ``` len_short = min([len(x) for x in names]) len_long = max([len(x) for x in names]) ``` These variables can then replace `4` and `6` in your code --- ``` names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"] long = [] short = [] len_short = min([len(x) for x in names]) # this will be 4 len_long = max([len(x) for x in names]) # this will be 6 for name in names: if len(name) <= len_short: short.append(name) print "Short names: ", short for name in names: if len(name) >= len_long: long.append(name) print "long names: ", long ```
You can use [max](https://docs.python.org/2/library/functions.html#max) and [min](https://docs.python.org/2/library/functions.html#min) built-in function with `len` as `key` argument. ``` >>> names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"] >>> max(names, key=len) 'Stevie' >>> min(names, key=len) 'jake' >>> len(max(names, key=len)) 6 >>> len(min(names, key=len)) 4 ```
I'm trying to understand how to fully understand the decision process of a decision tree classification model built with sklearn. The 2 main aspect I'm looking at are a graphviz representation of the tree and the list of feature importances. What I don't understand is how the feature importance is determined in the context of the tree. For example, here is my list of feature importances: Feature ranking: 1. FeatureA (0.300237) 2. FeatureB (0.166800) 3. FeatureC (0.092472) 4. FeatureD (0.075009) 5. FeatureE (0.068310) 6. FeatureF (0.067118) 7. FeatureG (0.066510) 8. FeatureH (0.043502) 9. FeatureI (0.040281) 10. FeatureJ (0.039006) 11. FeatureK (0.032618) 12. FeatureL (0.008136) 13. FeatureM (0.000000) However, when I look at the top of the tree, it looks like this:[![Tree Snippet](https://i.stack.imgur.com/yJ2xy.png)](https://i.stack.imgur.com/yJ2xy.png) In fact, some of the features that are ranked "most important" don't appear until much further down the tree, and the top of the tree is FeatureJ which is one of the lowest ranked features. My naive assumption would be that the most important features would be ranked near the top of the tree to have the greatest impact. If that's incorrect, then what is it that makes a feature "important"?
Just because a node is lower on the tree does not necessarily mean that it is less important. The feature importance in sci-kitlearn is calculated by how purely a node separates the classes (Gini index). You will notice in even in your cropped tree that A is splits three times compared to J's one time and the entropy scores (a similar measure of purity as Gini) are somewhat higher in A nodes than J. However, if you could only choose one node you would choose J because that would result in the best predictions. But if you were to have the option to have many nodes making several different decisions A would be the best choice.
Variable importance is measured by decrease in model accuracy when the variable is removed. The new decision tree created with the new model without the variable could look very different to the original tree. Splitting decision in your diagram is done while considering all variables in the model. What variable to split at the root (and other nodes) is measured by impurity. Good purity (e.g: everything in the left branch has the same target value) is not a guarantee for good accuracy. You data might be skewed, your right branch have more responses than your left branch. Therefore, it's no good just correctly classify the left branch, we also need to consider the right branch as well. Therefore, the splitting variable might or might not be an important variable for overall model accuracy. Variable importance is a better measure for variable selection.
What are the main benefits of using Exchange over Gmail? I currently use Gmail and sync my Outlook calendar via ActiveSync to phone and to Google Calendar via Google Calendar Sync. **Does Exchange offer any benefits in synchronization of e-mails and calendar?**
The benefits of Exchange are primarily seen in the Enterprise where the ability to centrally manage accounts is useful. It also provides a more integrated experience with Outlook of course.
To be honest with you I would prefer an Exchange server period! I am an avid Linux user and support the Open Source realm; however, you cannot come close to the capabilities that Exchange can give you (hosted or in house) with Google apps. Also, who are you going to call if something goes wrong with Google? Just imagine that you are one email away from closing a deal and your email no longer works? I guess you have to wait on that email from Google! With Exchange (hosted or in house) you have a support mechanism, the phone! For small businesses that cannot afford the cost of an in house server that has Exchange (I.E. SBS 2008) hosted exchange is the way to go! You pay a flat fee and get ALL the features you normally would receive with an in house server without the hassle of setup, support and maintenance (or especially licenses). For the small guy who doesn't really care about having a shared calendar, synchronized communications, and complete control of their company data and policies then I guess Google is your thing because it's free. Just remember that in the long run you do get what you pay for!
Is anybody else having problems with <https://stackoverflow.com/> when browsing the site through Linux Google Chrome? It appears that some (most?) JavaScript driven buttons do not work. Examples: * Incorrectly reports that the email address is invalid * Upvote button has no effect * Favorite button has no effect.
The moderator / offensive / spam flags are indeed currently capped, and I have openly supported raising this limit for trusted users (like [this near-dup](https://meta.stackexchange.com/questions/8935/increase-the-number-of-daily-spam-flags-with-reputation)); but we don't want a rogue low-level account spamming the system with flags etc (grudge settling, or just to be obnoxious for the sake of being obnoxious).
Flag for moderator attention, or email the team. They can clear out all the comments and warn/suspend the offending users.
I am wondering what experiences people are having using the ASP.NET MVC Framework? In particular I am looking for feedback on the type of experience folks are having using the framework. What are people using for their view engine? What about the db layer, NHibernate, LINQ to SQL or something else? I know stackoverflow uses MVC, so please say this site. Thank you. --- Why the choice of NHibernate over anything else? I am not against NHibernate, just wondering the rational.
I have used ASP.NET MVC for a few projects recently and its like a breath of fresh air compared to WebForms. It works *with* the web rather than against it, and feels like a much more natural way to develop. I use SubSonic rather than NHibernate, and find it fits very nice within the MVC architecture. The building blocks I commonly use for a website are:- Asp.net mvc Subsonic SQL Server Lucene JQuery
I've just been recently turned on to MVC and Linq to Sql for Asp.Net. I'm still learning both, and I'm really enjoying them both. There are quite a few screen casts on <http://www.asp.net/learn/>.
For a conference I have to put the references in `\bibitem` format. After, Googling I came up with this solution by [Web page](http://echorand.me/2010/12/03/2-cent-tip-bibtex-to-bibitem-format/): > > Create a `refs.bib` file with all the BibTeX entries, which are easily available from Google Scholar or similar > > > Create a “dummy” `.tex` file with the following entries: > > > > ``` > \documentclass{article} > \begin{document} > \nocite{*} > \bibliography{refs} > \bibliographystyle{plain} > \end{document} > > ``` > > Now, do the following: > > > > ``` > $ latex dummy > $ bibtex dummy > $ bibtex dummy > $ latex dummy > > ``` > > You will see a `dummy.bbl` file containing all your BibTeX entries in \bibitem format. > > > but, the expected results was not observed for me. Any other solution or the problem with the mentioned process.
I agree whith the general process explained in the comments, but i think that they don't fully address the final task that you must do you for the conference, which very likely want a single self contained `.tex` file. Let's assume that you have `mypaper.tex` which is your text with some `\cite{<key>}` and a `refs.bib` file. Then : 1. Firstly, put in `mypaper.tex` the two lines : \bibliography{refs} \bibliographystyle{plain} 2. Secondly run (instead of using the `\nocite` which has two drawbacks: (1) ordering as in `refs.bib` and (2) cites refs. that are not `\cite`-d in your paper) : (pdf)latex mypaper bibtex mypaper If this step is successful you will get `mypaper.bbl` containing the `bibitem`-s and a `mypaper.blg` which is BiBTeX's log file. (Nota : `latex` reads the `mypaper.tex` -- and when present the `mypaper.bbl` file -- but `bibtex` reads the `mypaper.aux` created by `latex`). 3. Thirdly, (optional but recommended) make sure that all the reference are correctly inserted and displayed in the file with : (pdf)latex mypaper 4. Fourthly, open `mypaper.tex`, comment out or discard the two `\biblio...` lines and paste the whole content of `mypaper.bbl` at the place where you want to get the bibliography. You then have the final self-contained file. You can run `(pdf)latex mypaper` at least two times to get the final `.dvi` or `.pdf`. **Edit:** This copy-paste holds if he `.bbl` file content start with the regular `\begin{thebibliography}`. If it starts by loading packages with `\usepackage{<name>}` or even by `\input{<name>.sty}` (where `<name>`= csquote, url, etc.) you must move them in your preamble. If it starts by defining commands, your can keep them at this place or move them to the preamble. Note for the OP: you use `plain` as the format, which looks strange for me. Actually each conference/organization generally has its own `.bst` style file which produces `\bibitem` formated accordingly to their editorial rules. More specifically, make sure that you need an alphabetical-ordered or a citation-ordered bibliography. In the later case, you must use the `unsrt.bst` (or a variant) in place of `plain.bst`.
Well, I used this matlab function to convert it automatically one by one, its more easy to get the job done. You can download it from [GitHub](https://github.com/eng-suhail/Bibtex2bibitem), and here is the matlab function as the following. ``` function [bibitem] = bibtex2bibitemtv(bibtexpath) path = bibtexpath; cells = importdata(path); A = string(cells); n = length(cells); K_name = strings(n,1); citecode = extractBetween(A(1),'{',','); SVacI = zeros(9,1); % Substyle Vacation Indicator. for i = 2:1:n-1 rawleft = extractBefore(A(i),'='); K_name(i) = strtrim(rawleft); % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(K_name(i),"author") SVacI(1) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) author = strtrim(extractBetween(A(i),'{','}')); else author = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(K_name(i),"title") SVacI(2) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) title = strtrim(extractBetween(A(i),'{','}')); else title = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(K_name(i),"journal") SVacI(3) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) journal = strtrim(extractBetween(A(i),'{','}')); else journal = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(K_name(i),"volume") SVacI(4) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) volume = strtrim(extractBetween(A(i),'{','}')); else volume = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif (strcmp(K_name(i),"number"))||(strcmp(K_name(i),"issue")) SVacI(5) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) number = strtrim(extractBetween(A(i),'{','}')); else number = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(K_name(i),"pages") SVacI(6) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) pages = strtrim(extractBetween(A(i),'{','}')); else pages = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(K_name(i),"month") SVacI(7) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) month = strtrim(extractBetween(A(i),'{','}')); else month = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(K_name(i),"year") SVacI(8) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) year = strtrim(extractBetween(A(i),'{','}')); else year = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif strcmp(K_name(i),"publisher") SVacI(9) = 1; rawright = extractAfter(A(i),'='); ccb = regexp(rawright,'}'); % ccb = [check curly bracket] if (ccb~=0) publisher = strtrim(extractBetween(A(i),'{','}')); else publisher = strtrim(extractBetween(A(i),'=',',')); end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % For adding new references sections. else msg = join(["Sorry!","[", K_name(i), "]","is not being handled by the program."]); disp(msg) end end % @-> Style reference term code varifications. % msg = join(["author","=",SVacI(1);... % "title","=",SVacI(2);... % "journal","=",SVacI(3);... % "volume","=",SVacI(4);... % "number","=",SVacI(5);... % "pages","=",SVacI(6);... % "month","=",SVacI(7);... % "year","=",SVacI(8);... % "publisher","=",SVacI(9)]); % disp(SVacI) if (SVacI(1)==0)||(SVacI(2)==0)||(SVacI(3)==0)||(SVacI(8)==0) bibitem = sprintf('THE ARTICLE IS NOT CORRECT. THE AUTHOR, TITLE, JOURNAL AND YEAR SECTIONS ARE COMPULSORY! PLEASE INCLUDE THEM AND RE-RUN THE SOFTWARE:)'); elseif all(SVacI == [1 1 1 0 0 0 0 1 0]) bibitem = sprintf(' \n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s},(%s). \n',citecode,author,title,journal,year); elseif all(SVacI == [1 1 1 0 0 0 0 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s},(%s). %s.\n',citecode,author,title,journal,year,publisher); elseif all(SVacI == [1 1 1 0 0 0 1 1 0]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s},(%s %s). \n',citecode,author,title,journal,month,year); elseif all(SVacI == [1 1 1 0 0 0 1 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s},(%s %s). %s.\n',citecode,author,title,journal,month,year,publisher); elseif all(SVacI == [1 1 1 0 0 1 0 1 0]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, pp. %s,(%s).\n',citecode,author,title,journal,pages,year); elseif all(SVacI == [1 1 1 0 0 1 0 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, pp. %s,(%s). %s.\n',citecode,author,title,journal,pages,year,publisher); elseif all(SVacI == [1 1 1 0 0 1 1 1 0]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, pp. %s,(%s %s).\n',citecode,author,title,journal,pages,month,year); elseif all(SVacI == [1 1 1 0 0 1 1 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, pp. %s,(%s %s). %s.\n',citecode,author,title,journal,pages,month,year,publisher); elseif all(SVacI == [1 1 1 0 1 0 0 1 0]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s,(%s).\n',citecode,author,title,journal,number,year); elseif all(SVacI == [1 1 1 0 1 0 0 1 1]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s,(%s). %s.\n',citecode,author,title,journal,number,year,publisher); elseif all(SVacI == [1 1 1 0 1 0 1 1 0]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s,(%s %s).\n',citecode,author,title,journal,number,month,year); elseif all(SVacI == [1 1 1 0 1 0 1 1 1]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s,(%s %s). %s.\n',citecode,author,title,journal,number,month,year,publisher); elseif all(SVacI == [1 1 1 0 1 1 0 1 0]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s, pp. %s,(%s).\n',citecode,author,title,journal,number,pages,year); elseif all(SVacI == [1 1 1 0 1 1 0 1 1]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s, pp. %s,(%s). %s.\n',citecode,author,title,journal,number,pages,year,publisher); elseif all(SVacI == [1 1 1 0 1 1 1 1 0]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s, pp. %s,(%s %s). %s.\n',citecode,author,title,journal,number,pages,month,year); elseif all(SVacI == [1 1 1 0 1 1 1 1 1]) disp("Attention! THE VOLUME HAS TO BE ASSOCIATED WITH NUMBER, PLEASE CHECK!") bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s, pp. %s,(%s %s). %s.\n',citecode,author,title,journal,number,pages,month,year,publisher); elseif all(SVacI == [1 1 1 1 1 0 0 1 0]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s),(%s).\n',citecode,author,title,journal,volume,number,year); elseif all(SVacI == [1 1 1 1 1 0 0 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s),(%s). %s.\n',citecode,author,title,journal,volume,number,year,publisher); elseif all(SVacI == [1 1 1 1 1 0 1 1 0]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s),(%s %s).\n',citecode,author,title,journal,volume,number,month,year); elseif all(SVacI == [1 1 1 1 1 0 1 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s),(%s %s). %s.\n',citecode,author,title,journal,volume,number,month,year,publisher); elseif all(SVacI == [1 1 1 1 1 1 0 1 0]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s), pp. %s,(%s).\n',citecode,author,title,journal,volume,number,pages,year); elseif all(SVacI == [1 1 1 1 1 1 0 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s), pp. %s,(%s). %s.\n',citecode,author,title,journal,volume,number,pages,year,publisher); elseif all(SVacI == [1 1 1 1 1 1 1 1 0]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s), pp. %s,(%s %s). %s.\n',citecode,author,title,journal,volume,number,pages,month,year); elseif all(SVacI == [1 1 1 1 1 1 1 1 1]) bibitem = sprintf('\n \\bibitem{%s}\n %s.\n \\newblock {%s.} \n \\newblock {\\emph %s}, %s(%s), pp. %s,(%s %s). %s.\n',citecode,author,title,journal,volume,number,pages,month,year,publisher); end ``` end **Sample input:** ``` @article{thompson1990home, title={In-home pasteurization of raw goat's milk by microwave treatment}, year={1990}, author={Thompson, J Stephen and Thompson, Annemarie}, journal={International journal of food microbiology}, volume={10}, number={1}, pages={59--64}, publisher={Elsevier} } ``` Sample Output: ``` \bibitem{lewis2009heat} Lewis, MJ and Deeth, HC. \newblock {Heat treatment of milk.} \newblock {\emph Milk processing and quality management}, 3(193), pp. 168--204,(Jan. 2009). Wiley Online Library. ```
I'm doing a module of prestashop (I posted other question yesterday). Now I'm having a problem with PHP, I think. Everytime it's says me that the line `if($same_puente === false OR $same_patilla === false)...` Parse error: syntax error, unexpected T\_STRING in that line. ``` <?php if (!defined('_PS_VERSION_')) exit; class glassOptics extends Module { /* @var boolean error */ protected $_errors = false; /* @var boolean puente */ public $same_puente = false; /* @var boolean patilla */ public $same_patilla = false; /* @var boolean altura cristal */ public $same_altura_cristal = false; /* @var boolean ancho cristal */ public $same_ancho_cristal = false; public function __construct() { $this->name = 'glassOptics'; $this->tab = 'front_office_features'; $this->version = '1.0'; $this->author = 'Víctor Martín'; $this->need_instance = 0; parent::__construct(); $this->displayName = $this->l('glassOptics'); $this->description = $this->l('Módulo para Ópticas, de filtrado de gafas compatibles para cada cliente.'); } public function install() { if (!parent::install() OR !$this->glopticasCustomerDB('add') OR !$this->glopticasProductDB('add') OR !$this->glopticasProductLangDB('modify') OR !$this->registerHook('hookActionProductListOverride') OR !$this->registerHook('DisplayAdminProductsExtra') OR !$this->registerHook('ActionProductUpdate')) return false; return true; } public function uninstall() { if (!parent::uninstall() OR !$this->glopticasCustomerDB('remove') OR !$this->glopticasProductDB('remove')) return false; return true; } public function glopticasCustomerDB($method) { switch ($method) { case 'add': $decimal_zero = '0.000000'; $decimal_zero = mysql_real_escape_string($decimal_zero); $sql = 'CREATE TABLE IF EXISTS `'._DB_PREFIX_.'customer_optics_data` ( `id_customer` int(10) UNSIGNED NOT NULL, `dioptrias_izquierdo` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `dioptrias_derecho` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `puente` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `patilla` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `altura_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `ancho_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.' ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8'; break; case 'remove': $sql = 'DROP TABLE IF EXISTS `'._DB_PREFIX_ . 'customer_optics_data`'; break; } if(!Db::getInstance()->Execute($sql)) return false; return true; } public function glopticasProductDB($method) { switch ($method) { case 'add': $decimal_zero = '0.000000'; $decimal_zero = mysql_real_escape_string($decimal_zero); $sql = 'CREATE TABLE IF EXISTS `'._DB_PREFIX_.'product_optics_data` ( `id_product` int(10) UNSIGNED NOT NULL, `dioptrias_izquierdo` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `dioptrias_derecho` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `puente` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `patilla` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `altura_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.', `ancho_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.' ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8'; break; case 'remove': $sql = 'DROP TABLE IF EXISTS `'._DB_PREFIX_ . 'product_optics_data`'; break; } if(!Db::getInstance()->Execute($sql)) return false; return true; } public function glopticasProductLangDB($method) { switch ($method) { case 'modify': $decimal_zero = '0.000000'; $decimal_zero = mysql_real_escape_string($decimal_zero); $sql = 'ALTER TABLE ' . _DB_PREFIX_ . 'product_lang ' .'ADD `dioptrias_izquierdo` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `dioptrias_derecho` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `puente` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `patilla` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `altura_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `ancho_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.'' .') ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8'; break; } if(!Db::getInstance()->Execute($sql)) return false; return true; } public function hookActionProductListOverride($params) { $customer_settings = glassOpticsHelperClass::getCustomerSettings($this->context->customer); if (!is_null($customer_settings)) { // Inform the hook was executed $params['hookExecuted'] = true; // Filter products here, you are now overriding the default // functionality of CategoryController class. // You can see blocklayered module for more details. if ((isset($this->context->controller->display_column_left) && !$this->context->controller->display_column_left) && (isset($this->context->controller->display_column_right) && !$this->context->controller->display_column_right)) return false; global $smarty; if (!Configuration::getGlobalValue('PS_LAYERED_INDEXED')) return; $sql_cat = 'SELECT COUNT(*) FROM '._DB_PREFIX_.'layered_category WHERE id_category = '.(int)Tools::getValue('id_category', Tools::getValue('id_category_layered', Configuration::get('PS_HOME_CATEGORY'))).' AND id_shop = '.(int) Context::getContext()->shop->id; $categories_count = Db::getInstance()->getValue($sql_cat); if ($categories_count == 0) return; // List of product to overrride categoryController $params['catProducts'] = array(); $selected_filters = $this->getSelectedFilters(); $filter_block = $this->getFilterBlock($selected_filters); $title = ''; if (is_array($filter_block['title_values'])) foreach ($filter_block['title_values'] as $key => $val) $title .= ' > '.$key.' '.implode('/', $val); $smarty->assign('categoryNameComplement', $title); $this->getProducts($selected_filters, $params['catProducts'], $params['nbProducts'], $p, $n, $pages_nb, $start, $stop, $range); // Need a nofollow on the pagination links? $smarty->assign('no_follow', $filter_block['no_follow']); filterProductsByConditions($customer_settings, $params['nbProducts']); } } private static function filterProductsByConditions($customer_settings, $product_collection) { if(!is_null($product_collection)){ foreach ($product_collection as $product){ $product_settings = glassOpticsHelperClass::getProductSettings($product); if(!is_null($product_settings)){ if(!is_null($product_settings->puente) AND !is_null($customer_settings->puente)){ $same_puente = (($product_settings->puente == $customer_settings->puente) ? true : false); }else{ $same_puente = false; } if(!is_null($product_settings->patilla) AND !is_null($customer_settings->patilla)){ $same_patilla = (($product_settings->patilla == $customer_settings->patilla) ? true : false); }else{ $same_patilla = false; } if(!is_null($product_settings->altura_cristal) AND !is_null($customer_settings->altura_cristal)){ $same_altura_cristal = (($product_settings->altura_cristal == $customer_settings->altura_cristal) ? true : false); }else{ $same_altura_cristal = false; } if(!is_null($product_settings->ancho_cristal) AND !is_null($customer_settings->ancho_cristal)){ $same_ancho_cristal = (($product_settings->ancho_cristal == $customer_settings->ancho_cristal) ? true : false); }else{ $same_ancho_cristal = false; } if($same_puente === false OR $same_patilla === false){ unset($product_collection[$product]); } } } return $product_collection; }else{ return $product_collection; } } } ``` What I'm doing wrong? Thank you.
You have a extra closing bracket in your `$sql` statement: `.') ENGINE='._MYSQL_ENGINE_.'` ``` $sql = 'ALTER TABLE ' . _DB_PREFIX_ . 'product_lang ' .'ADD `dioptrias_izquierdo` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `dioptrias_derecho` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `puente` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `patilla` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `altura_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.',' .'ADD `ancho_cristal` decimal(20,6) NOT NULL DEFAULT '.$decimal_zero.'' .') ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8'; ```
Your problem is here: ``` foreach ($product_collection as $product){ ... unset($product_collection[$product]); } ``` You must use `$key` for get element of array: ``` foreach ($product_collection as $key => $product){ ... unset($product_collection[$key]); } ``` because `$product` is value of array element, but not key.
I know that we use *might have* to show that something has possibly happened now or happened at some time in the past. But can we use it for future? For example: Just imagine there is a person who is 40 years old and he loves a girl who is 18 years old... For teasing him I say: > > "You are too old, when she will come to your age you **might have** died" > > > Is it a correct sentence? I don't know...I'm a learner, please help.
"She will come to your age" sounds a bit awkward. Maybe something like "When she turns your age" or even "When she turns 40" would work better so that it doesn't sound ambiguous. After that you could say "you may/might have already died" though I would prefer "you may/might already be dead". So your full sentence could be: > > "When she turns 40, you may/might already be dead." > > > Other ways to say this same thing are: > > "By the time she turns 40, you may already be dead." > > > or > > "You may be dead by the time she turns 40." > > > In essence, I think the "have" is awkward and there are better ways to get your intentions across. Adding "already" helps buffer that. I would have preferred to ask questions in the comments but I don't have the rep. I'm by no means an English expert - just your average native speaker - so take this with a grain of salt. Looking @SovereignSun's answer will give you more technical reasoning that I couldn't give you.
"**might have + past participle**" is used only in the past and present: * I might have said something bad. * I might have been given this letter but I don't remember. * They might have come already. In the future we can either use "**might + present participle**": * Tomorrow I might be at home. * In an hour I might leave. Or "**might + have to + present participle**": * In half an hour I might have to leave. * She might have to take her papers with her today. Nothing like "**will might**" or "**will might have to**" is possible. So your sentence can be: * You might be dead by the time time she turns 40.
**Javascript:** ``` var str = 'som\\//kdshn/jasdj/\akdjsl/kas\asd'; var newstr = str.replace(/(\\|\/)/g,function(a, m) { return m == "/" ? "\\" : "//"; }); ``` > > Result: `som//\\kdshn\jasdj\akdjsl\kasasd`. > > > In the result backslash is getting escaped. How to handle?
Use the method [**`setChipBackgroundColorResource`**](https://developer.android.com/reference/com/google/android/material/chip/Chip#setchipbackgroundcolorresource): ``` chip.setChipBackgroundColorResource(R.color.chip_selector_color); ``` Otherwise use the method [`setChipBackgroundColor`](https://developer.android.com/reference/com/google/android/material/chip/Chip#setchipbackgroundcolor) ``` chip.setChipBackgroundColor(AppCompatResources.getColorStateList(context, R.color.chip_selector_color)); ```
use backgroundTint in xml ``` <com.google.android.material.chip.Chip android:id="@+id/timetext_id" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginHorizontal="40dp" android:layout_weight="1" android:backgroundTint="#39b8db" android:gravity="center" android:padding="5dp" android:text="Time" android:textAlignment="center" android:textColor="@color/white" /> ```
Most **Turkic languages** use the Arabic words for greeting, namely *salam*/*selam*/*merhaba* etc. The exceptions are Tatar *isänmesez* and Uighur *yakhshimusiz*, the origin of which I do not know. Are they Turkic? What did **Turkic** people say to greet each other before those Arabic words entered their vocabulary?
I think the (modern) Uyghur word is cognate with Old Turkish yakış, Turkey-Turkish yahşı “good, pretty”.
Ar(y)ma - meaning "don't get tired".
I'm trying to load a .json file present in my local project workspace using jQuery and I get the error - "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." ``` <html lang="en"> <head> <meta charset="utf-8"> <title>TEST</title> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $.getJSON('phones.json',function(data){ console.log('It Worked!') }); </script> </body> </html> <!-- end snippet --> <html lang="en"> <head> <meta charset="utf-8"> <title>TEST</title> </head> <body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $.getJSON('phones.json',function(data){ console.log('It Worked!') }); </script> </body> </html> ```
Use a web server and serve this page via http. That will eliminate the issue.
This can be Googled. Chrome security is not allowing you to do local AJAX calls to your local directory. If the file will always be in your local file directory, include it with your `<script src="phones.json"></script>`. Note, this will cause the json variable to be global. Alternatively, you can run your page on a local server to continue programming locally. This, too, can be googled on how to do this.
I have a web page with "C++" in its title generated by `asciidoctor`. In the source, I use `{cpp}` character-replacement attribute, but in the resulting HTML file, asciidoctor renders it into `C&#43;&#43;` instead of plain `C++`. I just wonder about web search engine indexing, whether there is any difference between those two variants. (For instance, Google HTML Style Guide recommends [avoiding HTML entities](https://google.github.io/styleguide/htmlcssguide.html#Entity_References)). Or, if there is possibly any option to force asciidoctor to produce `C++`?
You seem to be overcomplicating this. Starting from your existing `join` query, you can aggregate, order the results and keep the top row(s) only. ``` select s.country, count(*) cnt from sportsman s inner join result r using (sportsman_id) group by s.country order by cnt desc fetch first 1 row with ties ``` Note that this allows top ties, if any.
``` SELECT country FROM (SELECT country, COUNT(country) AS highest_participation FROM (SELECT competition_id, country FROM result INNER JOIN sportsman USING (sportsman_id) ) GROUP BY country order by 2 desc ) where rownum=1 ```
There's a caveat, which is often ignored, to the "easy" equation for parallel plate capacitors $C = \epsilon A / d$, namely that $d$ must be much smaller than the dimensions of the parallel plate. Is there an equation that works for large $d$? I tried finding one and could not. (These two papers talk about fringing fields for disc-shape plates but don't seem to have a valid equation for $ d \to \infty$: <http://www.santarosa.edu/~yataiiya/UNDER_GRAD_RESEARCH/Fringe%20Field%20of%20Parallel%20Plate%20Capacitor.pdf> and <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.167.3361&rep=rep1&type=pdf>) My hand-waving intuition is that as $ d \to \infty$, $C$ should decrease to a constant value (which is the case for two spheres separated by a very large distance, where $C = 4\pi\epsilon\_0/\left(1/R\_1 + 1/R\_2\right)$ ), because at large distances from each plate, the electric field goes as $1/R$, so the voltage line integral from one plate to the other will be a fixed constant proportional to charge $Q$.
Your intuition is pretty solid. You can calculate the capacitance of an isolated sphere of radius $R$ relative to infinity from the fact that the potential at the surface of a sphere carrying charge $Q$ is $V=Q/(4\pi\epsilon\_0R)$ and the definition of capacitance $Q=CV$. It's $$C=4\pi\epsilon\_0R.$$ Capacitance is always $\epsilon$ times a length scale that corresponds to the size of the conductor and some unitless factor that depends on the geometry of the plates. In this particular case, as $d\gg a$, where $a$ is the widest dimension of the (assumed identical) capacitor plates, the capacitance will go like $$C=g\epsilon\_0 a,$$ with $g$ the geometric factor that tends to some constant as $d/a\rightarrow\infty$ and to $\infty$ as $d/a\rightarrow 0$.
As distance between plates increases, capacitance will decrease and , if it become infinitive the capacitance will become zero
I am using the following code to prevent page scroll on a DIV element ``` <script> $(document).ready(function(){ $('#stop-scroll').on( 'mousewheel DOMMouseScroll', function (e) { var e0 = e.originalEvent; var delta = e0.wheelDelta || -e0.detail; this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30; e.preventDefault(); }); }); </script> ``` But I want to enable scrolling again if a counter reaches to a certain value say 4, the counter will keep increase by 1 on mouse scroll. And the counter will decrease by 1 if mouse scroll up and when the counter reaches 0 the scroll disable will be enabled again and the user can scroll the page up.
The solution was incredibly simple: I had the **offline mode** enabled. Without offline mode, Cargo downloaded the `cargo-core-container-tomcat` artifact, and apparently this artifact contains the definition of the `tomcat8x` configuration. Then, the container start was successful! I had started the Maven build from Eclipse, so I didn't notice that the offline mode was enabled. I'm aware that this situation is quite special, but maybe someone else still benefits from my insight. It took me a while to solve, so I'm sharing problem and solution here. (After all, this is encouraged :-) I got the key hint from a [mailing list post](https://groups.google.com/d/msg/codehaus-cargo/KAYsK774Y7k/UP4PIelHEAAJ), where the`cargo-core-container-tomcat` artifact was not downloaded due to a Nexus repository configuration.
This error is sometimes due to the cargo plugin version. Update your cargo plugin to the higher or latest version. In my case, I updated from cargo 1.4.8 to cargo 1.7.0. check this link,its may help: [click here](https://stackoverflow.com/questions/28432626/cargo-cannot-deploy-to-remote-tomcat-8-with-using-cargo-maven-plugin)
I have a HashMap that keeps references to my applications modules. ``` HashMap<String, Module> modules; ``` When I do this: ``` for(String key:modules.keySet()){ modules.remove(key); } ``` There should be no more reference to the objects hence they should be removed by the GC at some point. Am I right or did I miss something? Is this secure or is it possible to regain access to the objects somehow? Is this the same that happens when doing: ``` modules.clear(); ``` ? In the end a more complicated question: When doing this with GWT, how much can I be sure, that the objects are gone in the browser? I would like to do this on user logout to prevent someone who uses the computer next to retrieve any information from the previous user. Of course most modules do "forget" their data an unDetach(), but I am not sure, all of them do. This information is a plus of course, if someone happens to know I would be thankful =)
The first method could cause problems as you iterate over the keySet and remove elements at the same time. The second methods should do the right thing. And if you have no other references to the modules they should be garbage collected.
The question rather is who and what else has access to your modules. If there is any chance that some other part of your program might have gotten a reference to one of your modules, you cannot be sure that the GC will remove the module. In any case, you should not rely on the GC to do anything. It will only run if more space is required and is a system to handle memory cleanup after an application finished executing. If you want to be sure that no sensible information is accessible, remove it explicitly.
``` #include<stdio.h> #include<stdlib.h> int main() { int t,k,n,i; int height[20000]; scanf("%d",&t); while(t--) { scanf("%d%d",&k,&n); for(i = 0; i < n; i++) scanf("%d",&height[i]); for(i = 0; i < n; i++) printf("%d\n",height[i]); } return 0; } ``` For input: 1 3 1 2 5 4 I am expecting an output of 2 5 4 but I am getting an output of 2 please help
In your input you set `t` to 1, `k` to 3 and **`n` to 1**. So your `for`s perform only one loop afterwards. '5' and '4' are not even scanned from the input.
change you code like this : ``` while(t--) { scanf("%d%d",&k,&n); for(i = 0; i < k; i++) scanf("%d",&height[i]); for(i = 0; i < k; i++) printf("%d\n",height[i]); } ``` and it will work as your expected. By the way , why you only use n but get k and n both? It is no sense.
I have a class with a static non-primitive member. For example: ``` class SomeObject { ... // something that will be destroyed in destructor, // like an array pointer. public: SomeObject(); ~SomeObject(); }; class MyClass { static SomeObject m_object; public: MyClass(); ~MyClass(); // this will access m_object static bool SetupStaticMember(); }; /// Implementation of SomeObject and MyClass /// SomeObject MyClass::m_object; bool dummy = MyClass::SetupStaticMember(); // Setup the values in m_object, for example, // allocate memory that will be released in ~SomeObject(). MyClass g_my_global_class; ``` g\_my\_global\_class is declared as global variable, so it's destructor is called after leaving main(). However, MyClass::m\_object is static, so it will also be destroyed after main(). Is there any guarantee that ~MyClass() will execute before ~SomeObject() from MyClass::m\_object? In other words, when the destructor of a global class instance is called, can I assume that the static members of this class are still there to be accessed, or does this depend on construction/destruction orders? If the codes are written in this order, I think that g\_my\_global\_class is constructed later, so it should be destructed first. Do things change if the line ``` MyClass g_my_global_class; ``` moves to another .cpp file and its file name causes the order to change?
Check this out if you're using visual studio - windows: otherwise you may have to use something similar such as `__PRETTY_FUNCITON__`, etc. ``` class SomeObject { public: SomeObject() { std::cout << __FUNCTION__ << " was called: SomeObject created." << std::endl; } ~SomeObject() { std::cout << __FUNCTION__ << " was called: SomeObject destroyed." << std::endl; } }; class MyClass { public: static SomeObject m_object; MyClass() { std::cout << __FUNCTION__ << " was called: MyClass created." << std::endl; } ~MyClass() { std::cout << __FUNCTION__ << " was called: MyClass destroyed." << std::endl; } static bool setupStaticMember() { std::cout << __FUNCTION__ << " was called... " << std::endl; return true; } }; SomeObject MyClass::m_object; bool dummy = MyClass::setupStaticMember(); MyClass gMyClass; int main() { _getch(); return 0; } ``` Output in debugger console while waiting for key press: ``` SomeObject::SomeObject was called: SomeObject created. MyClass::setupStaticMember was called... MyClass::MyClass was called: MyClass created. ``` Then as key press is entered and console from debugger closes (visual studio 2017)... ``` MyClass::~MyClass was called: MyClass destroyed. SomeObject::~SomeObject was called: SomeObject destroyed. ``` To test this out fully just go to the `*.exe`'s path in the console directly and call the executable. You will see the same lines above while the application is running but after you press a key and enter to finish the application the last 2 lines are then called in that order. These are all in the main.cpp file (same translation unit). This does show the order that objects are created. Now if you are in a class hierarchy then you need to make sure you are virtualizing your classes for proper construction - destruction order.
Static member of a class is a class level variable and under the class scope. As a static member is under the scope of class only it is accessible from all the object instantiated from that class with `::` (classname::static\_variable) operator. As it is not a object variable you can not release from destructor of the class. Suppose you have created ten objects from that class in various location in your codes and one object is going out of its scope and will call its destructor and if you release the static variable from that destructor what would happened in other objects? As they are all sharing the same static member. That is the reason a static member never initialized in a constructor. Hence a static member will be release from the memory only when program exit.
I am trying to re-write the value of *CLOSED* to *TESTING*. It is noted that the select box is populated dynamically. My code is below but it doesn't produced desired results. ``` <html> <head> <script type="text/javascript"> window.onload = function() { loadit() } function loadit(){ var x = new Array() x[0] = "" x[1] = "ACTIVE" x[2] = "ON HOLD" x[3] = "CLOSED" for (i=0; i<x.length; i++) { document.getElementById('d1').options[i]=new Option(x[i], i) } } function changeit() { var el = document.getElementById("d1"); for(var i=0; i < el.options.length; i++) { if(el.options[i].value == "CLOSED") { el.options[i].value = "TESTING"; el.options[i].innerText = "TESTING"; } } } </script> </head> <body> <select name="d1" id="d1" style="width: 200px;"></select> <p><a href="javascript:changeit()">change</a></p> </body> </html> ```
Look how you are creating the option ``` document.getElementById('d1').options[i] = new Option(x[i], i) ``` The value is a number so the following check will never be true ``` if(el.options[i].value == "CLOSED"){ ``` You can change it to .text ``` if (el.options[i].text== "CLOSED") { ``` or you can change the poulating of the select ``` document.getElementById('d1').options[i] = new Option(x[i], x[i]); ```
Your values are 0,1,2,3 not the text, so in your loop it should be: ``` for(var i=0; i < el.options.length; i++){ if(el.options[i].value == "3"){ el.options[i].value = "3"; el.options[i].innerText = "TESTING"; } } ```
Define 2 power series over the field $\mathbb Z/2\mathbb Z$ by $f=1+x+x^3+x^6+\dots$, the exponents being the triangular numbers, and $g=1+x+x^4+x^9+\dots$, the exponents being the squares. Write $f/g$ as $c\_0+c\_1x+c\_2x^2+\dots$ with each $c\_n$ in $\mathbb Z/2\mathbb Z$. **Question.** Is it true that when $n$ is even then $c\_n$ is 1 precisely when $n$ is in the set of even triangular numbers $\lbrace 0,6,10,28,36,\dots\rbrace$? [Kevin O'Bryant](https://mathoverflow.net/users/935/kevin-obryant) has verified that this holds when $n$ is 512 or less. **Remark.** If one writes $1/g$ as $b\_0+b\_1x+b\_2x^2+\dots$, then $n\mapsto b\_n$ is the characteristic function $\bmod 2$ of the set $B$ studied by O'Bryant, Cooper and Eichhorn (see [this](https://mathoverflow.net/questions/26839/) and [this](https://mathoverflow.net/questions/28462/) questions of O'Bryant on MO); they show that when $n$ is even then $b\_n$ is 1 precisely when $n$ is twice a square. A positive answer to my question would give a nice characterization of those elements of $B$ that are congruent to $7 \bmod 16$. (I've used the modular forms tag because of the formal similarity of $f$ and $g$ to Jacobi theta functions, and the motivation of O'Bryant, Cooper and Eichhorn in looking at $B$).
The coming below is nothing else but thinking loudly. The differential operator $$ D=\operatorname{id}+x\frac d{dx}\colon h\mapsto (xh)' $$ "kills" the unwanted odd powers modulo 2. Indeed, if $$ h=\sum\_{n=0}^\infty a\_nx^n=a\_0+a\_1x+a\_2x^2+\dots, $$ then $$ Dh=\sum\_ {n=0}^\infty (n+1)a\_nx^n \equiv\sum\_ {k=0}^\infty a\_ {2k}x^{2k}\pmod 2 $$ where the congruence is applied to all coefficients in the power series expansions. Therefore, the OP asks for the congruence $$ D\biggl(\frac fg\biggr)\overset?\equiv D(f)\pmod 2 $$ to be true, which after multiplication by $g^2$ becomes (modulo 2) the congruence $$ D(fg)\overset?\equiv D(f)g^2\equiv D(fg^2)\pmod{2}, $$ equivalently, $$ \frac{d}{dx}\bigl(xf(x)g(x)\bigr) \overset?\equiv\frac{d}{dx}\bigl(xf(x)g(x)^2\bigr)\pmod{2}.\qquad\qquad\qquad(\*) $$ The function $f(x)$ can be in a certain sense eliminated from the required formula by using $$ g(x)=\sum\_{n=0}^\infty x^{n^2} =\sum\_{m=0}^\infty x^{(2m+1)^2} +\sum\_{m=0}^\infty x^{(2m)^2} =xf(x^8)+g(x^4) $$ which implies $$ f(x)=\frac{g(x^{1/8})-g(x^{1/2})}{x^{1/8}}. $$ In addition, we can use repeatedly $$ h(x^2)\equiv h(x)^2\pmod{2}. $$ **Edit.** Following the clear criticism from Paul, I will only indicate the obvious restatement of ($ \* $): $$ \frac{d}{dx}\bigl(x^7(g(x)-g(x^4))g(x^8)(1-g(x^8))\bigr) \overset?\equiv0\pmod{16}.\qquad\qquad\qquad(\*\*) $$ This new one does not look specially nice but involves a single series, $g(x)=1+x+x^4+x^9+\dots$.
Part 2--the curious fact The theory of quadratic fields tells us that I is the sum of the Jacobi symbols (-1/d) and J is the sum of the (-2/d) where d divides n. Write n as a product of powers of distinct primes, and let a(p) be the exponent to which p appears. Multiplicativity of the Jacobi symbol shows that I is a product of contributions, one from each p; the same holds for J. The contribution is even when a(p) is odd and vice versa. Several cases arise. If 2 or more a(p) are odd, 4 divides I and J Suppose a single a(p) is odd. Since n=8m+1, p=1 (8), (-1/p)=(-2/p)=1 and the contribution of p to each of I and J is 1+a(p). Since all other contributions are odd, I=J=0 (4) or I=J=2 (4) according as a(p) is 3 or 1 (4). Suppose n is a square so that m is triangular. Write n=s^2. Let p\_i be the primes =5 (8) that divide s, and d\_i be the exponents. Let q\_i be the primes =3 (8) that divide s and e\_i be the exponents. If m is even, n=1 (16), so s=1 or 7 (8), while if m is odd n=9 (16) and s= 3 or 5 (8). In the multiplicative group of Z/8, all the (-3)^d\_i together with all the 3^e\_i multiply to s or -s. It follows that the sum of all the d\_i and all the e\_i is even for even m and odd for odd m. p\_i makes contributions of 1+2d\_i and 1 to I and J, while q\_i makes contributions of 1 and 1+2e\_i. And every other prime makes the same (odd) contribution to I as it does to J. Also, mod 4, the product of the 1+2d\_i is 1+twice the sum of the d\_i, while the product of the 1+2e\_i is 1+twice the sum of the e\_i. Combining this with the result of the last paragraph we see that I=J mod 4 precisely when m is even. This concludes the proof of the curious fact.
i make my apps in Symfony 1.4 on localhost. Here is OK, but if i upload all files in www server then if i open: **www.mysite.com/** then i have error: > > symfony PHP Framework page not found Oops! An Error Occurred The > server returned a "500 Internal Server Error". > > > Something is broken > Please e-mail us at [email] and let us know what you were doing > when this error occurred. We will fix it as soon as possible. Sorry > for any inconvenience caused. What's next > > > > ``` > Back to previous page > Go to Homepage > > ``` > > but if i open **www.mysite.com/frontend\_dev.php** then all is good. where i must search error? how can i fix it?
In your config file change the envirment to Live currently you are on development envirment
If you have ssh access to your web server type: ``` php symfony cc ``` If not make sure to clear your cache folder. Then everything will be gone well.
Its been couple of days since i have not found the solution for this. As there is an option for mat-menu that is overlaptrigger property but there is no property to perform this in mat select dropdown. Is there any way to customize the mat-select dropdown position by overriding the css or any better solution.
``` <mat-select placeholder="Language" disableOptionCentering panelClass="myPanelClass"> <mat-option *ngFor="let locale of locales" [value]="locale"> {{locale}} </mat-option> </mat-select> ``` Utilize **disableOptionCentering** and **panelClass** like I have above. Then within your **styles.scss** reference your panelClass and do ``` .myPanelClass{ margin-top: 30px !important; } ``` This worked for me. Note that the scss **must be in your styles.scss not your component's scss file**. You might not need to use important here, I have other classes around this so I did use it.
I've found the solution as **disableOptionCentering** direcrive for **mat-select**, so after using this dropdaown can be customized. from timmoy: <https://github.com/angular/material2/pull/9885> Example usage: ``` <mat-select [(ngModel)]="currentPokemon" [required]="pokemonRequired" [disabled]="pokemonDisabled" #pokemonControl="ngModel" disableOptionCentering> <mat-option *ngFor="let creature of pokemon" [value]="creature.value"> {{ creature.viewValue }} </mat-option> </mat-select> ```
Let $n \in \mathbb{Z}$. If $n^2 \not\equiv n\pmod 3$, then $n\not\equiv 0\pmod 3$ and $ n \not\equiv 1\pmod 3$. State and prove the converse. So I know the converse statement is: If $n\not\equiv 0\pmod 3$ and $n\not \equiv 1\pmod 3$, then $n^2\not\equiv n\pmod 3$. To solve the converse, first I thought to prove the contrapositive of the converse. I did: If $n^2\equiv n\pmod 3$, then $n\equiv 0\pmod 3$ or $n\equiv 1\pmod 3$. From here we would write the proof: Assume $n^2 \equiv n\pmod 3$. This means $3\mid n^2-n$. We can then write this as $n^2-n=3k$ for $k \in\mathbb{Z}$. So, $n=3k-n^2$. I'm not sure if this is correct so far, but I know we need cases because of the or statement and I'm not sure how to do that.
> > keep in mind *exactly* one and *only* one of the following must be true. $n=0\pmod 3; n=1\pmod 3; n\pmod 3$. So $[n\not\equiv 1\pmod 3$ and $n\not\equiv 0\pmod 3]\iff n\equiv 2\pmod 3$. > > > So the converse is $n\not \equiv 0\pmod 3$ and $n\not \equiv 1\pmod 3 \implies n^2 \not \equiv n\pmod 3$. And to prove it. $n\not\equiv 1\pmod 3$ and $n\not\equiv 0\pmod 3$ implies $n \equiv 2\pmod 3$. And $n^2 \equiv 2^2 \equiv 4\equiv 1 \not \equiv 1 \equiv n\pmod 3$. That's it.
The converse is: > > If $n \not\equiv\_3 1$ and $n \not \equiv\_3 0$ then $n^2 \not \equiv\_3 n$. > > > This is equivalent to > > If $n \equiv\_3 2$ then $n^2 \not \equiv\_3 2$. > > > What is $2^2$ mod 3? Isn't $2^2 \equiv\_3 1 \not =2$? We do note that if $n \equiv\_3 2$ then $n=3y+2$ for some integer $y$. But then $(3y+2)^2 = 9y^2+12y+4 \equiv\_3 ?$
I'm taking a course in differential geometry this semester and I'm stuck with one of my first exercises. Let $\alpha(s)=(x(s),y(s))$ be a curve such that $|\alpha'(s)|=1$. Prove that the curvature is given by $k(s)=|x'(s)y''(s)-x''(s)y'(s)|$. So far we defined the curvature of such curves as $k(s)=|\alpha''(s)|$, but this doesn't really get me to the formula I'm supposed to prove. Since we haven't really done anything in the course yet, I don't think that I have to do anything really complicated here, but still I don't know what to do. Anyone who can help me with this? Thanks.
Since $|\alpha'|^2=(x')^2+(y')^2$ is constant, $\alpha''$ is orthogonal to $\alpha'$. But $(-y',x')$ is also orthogonal to $\alpha'=(x',y')$, so it is parallel to $\alpha''=(x'',y'')$. What does that tell you about the inner (or dot) product between the two vectors?
Besides to descriptive @Harald post, we know that $v=d\alpha/dt=v\mathbf{T}$ and so $a=(dv/dt)\mathbf{T}+v^2\kappa\mathbf{N}$ and so $|v\times a|=\kappa v^3$. I assume you know the cross product which is used here.
My website has a folder called uploads and inside there is a folder for each client. My question is, what's the best practice to deny the user A to see the uploads from user B?
You could do this with web.config changes. See documentation here: <http://support.microsoft.com/kb/815151> Basically your web.config will look like: ``` <?xml version="1.0"?> <configuration> <location path="uploads/UserA"> <system.web> <authorization> <allow users="UserA"/> <deny users="*"/> </authorization> </system.web> </location> <location path="uploads/UserB"> <system.web> <authorization> <allow users="UserB"/> <deny users="*"/> </authorization> </system.web> </location> </configuration> ```
You could use NTFS permissions on the folders, forcing the user to authenticate. I did this for a website in 2000. Although in this case that's like using a cannon to kill a mosquito.
Is there a way to sanitize sql in rails method `find_by_sql`? I've tried this solution: [Ruby on Rails: How to sanitize a string for SQL when not using find?](https://stackoverflow.com/questions/2497757/ruby-on-rails-how-to-sanitize-a-string-for-sql-when-not-using-find) But it fails at ``` Model.execute_sql("Update users set active = 0 where id = 2") ``` It throws an error, but sql code is executed and the user with ID 2 now has a disabled account. Simple `find_by_sql` also does not work: ``` Model.find_by_sql("UPDATE user set active = 0 where id = 1") # => code executed, user with id 1 have now ban ``` **Edit:** Well my client requested to make that function (select by sql) in admin panel to make some complex query(joins, special conditions etc). So I really want to find\_by\_sql that. **Second Edit:** I want to achieve that 'evil' SQL code won't be executed. In admin panel you can type query -> `Update users set admin = true where id = 232` and I want to block any UPDATE / DROP / ALTER SQL command. Just want to know, that here you can ONLY execute SELECT. After some attempts I conclude `sanitize_sql_array` unfortunatelly don't do that. Is there a way to do that in Rails?? Sorry for the confusion..
``` User.find_by_sql(["SELECT * FROM users WHERE (name = ?)", params]) ``` Source: <http://blog.endpoint.com/2012/10/dont-sleep-on-rails-3-sql-injection.html>
I prefer to do it with key parameters. In your case it may looks like this: ``` Model.find_by_sql(["UPDATE user set active = :active where id = :id", active: 0, id: 1]) ``` Pay attention, that you pass ONLY ONE parameter to `:find_by_sql` method - its an array, which contains two elements: string query and hash with params (since its our favourite Ruby, you can omit the curly brackets).
I have a large text file I am reading from and I need to find out how many times some words come up. For example, the word `the`. I'm doing this line by line each line is a string. I need to make sure that I only count legit `the`'s--the `the` in `other` would not count. This means I know I need to use regular expressions in some way. What I was trying so far is this: ``` numSpace += line.split("[^a-z]the[^a-z]").length; ``` I realize the regular expression may not be correct at the moment but I tried without that and just tried to find occurrences of the word `the` and I get wrong numbers too. I was under the impression this would split the string up into an array and how many times that array was split up was how many times the word is in the string. Any ideas I would be grateful. Update: Given some ideas, I've come up with this: ``` numThe += line.split("[^a-zA-Z][Tt]he[^a-zA-Z]", -1).length - 1; ``` Though still getting some strange numbers. I was able to get an accurate general count (without the regular expression), now my issue is with the regexp.
To get the number of occurrence of a specific word use the below code ``` Pattern pattern = Pattern.compile("Thewordyouwant"); Matcher matcher = pattern.matcher(string); int count = 0; while(matcher.find()) count++; ```
I think this is an area where unit tests can really help. I had a similar thing some time ago where I wanted to break a string up in a number of complex ways and create a number of tests, each of which tested against a different source string, helped me to isolate the regex and also quickly see when I got it wrong. Certainly if you gave us an example of a test string and the result it would help us to give you better answers.
this is my original string: ``` NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 ``` I want to only add back slash to all the spaces before ':' so, this is what I finally want: ``` NetworkManager/system\ connections/Wired\ 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 ``` I need to do this in bash, so, sed, awk, grep are all ok for me. I have tried following sed, but none of them work ``` echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/ .*\(:.*$\)/\\ .*\1/g' echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/\( \).*\(:.*$\)/\\ \1.*\2/g' echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/ .*\(:.*$\)/\\ \1/g' echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/\( \).*\(:.*$\)/\\ \1\2/g' ``` thanks for answering my question. I am still quite newbie to stackoverflow, I don't know how to control the format in comment. so, I just edit my original question my real story is: when I do grep or use cscope to search keyword, for example "address1" under /etc folder. the result would be like: ``` ./NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 ``` if I use vim to open file under cursor, suppose my vim cursor is now at word "NetworkManager", then vim will understand it as "./NetworkManager/system" that's why I want to add "\" before space, so the search result would be more vim friendly:) I did try to change cscope's source code, but very difficult to fully achieve this. so have to do a post replacement:(
An idea for a [perl one liner](https://www.rexegg.com/regex-perl-one-liners.html) in bash to use [`\G`](https://www.regular-expressions.info/continue.html) and [`\K`](http://www.rexegg.com/regex-php.html#K) (similar [@CarySwoveland's comment](https://stackoverflow.com/questions/70444758/how-to-regex-replace-before-colon#comment124526940_70444758)). ``` perl -pe 's/\G[^ :]*\K /\\ /g' myfile ``` [See this demo at tio.run](https://tio.run/##RcixCsIwEIDhV7ktIJrzpCAUnB1EVwejEJOjLbVJuQuI4LtHF3H54fvvXvtaOfQZzInLM8t49Ml3LKgvLTxByClxKENOiudBOALZNP1vSw34GIVVaUdrS/abLeGmWf5EBt4wszxgNTMYRbe/3KC9LtwB0DnAztT6AQ) or a [pattern demo at regex101](https://regex101.com/r/L3ozMV/1).
My answer is ugly and I think [RavinderSingh13's answer](https://stackoverflow.com/a/70444917/11261546) is THE ONE, but I already took the time to write mine and it works (It's written step by step, but it's a one line command): I got inspired by [HatLess answer](https://stackoverflow.com/a/70445805/11261546): first get the text before the `:` with `cut` (I put the string in a file to make it easy to read, but this works on `echo`): ``` cut -d':' -f1 infile ``` Then replace spaces using `sed`: ``` cut -d':' -f1 infile | sed 's/\([a-z]\) /\1\\ /g' ``` Then `echo` the output with no new line: ``` echo -n "$(cut -d':' -f1 infile | sed -e 's/\([a-z]\) /\1\\ /g')" ``` Add the missing `:` and what comes after it: ``` echo -n "$(cut -d':' -f1 infile | sed -e 's/\([a-z]\) /\1\\ /g')" | cat - <(echo -n :) | cat - <(cut -d':' -f2 infile) ```
In order to do K-fold validation I would like to use slice a numpy array such that a view of the original array is made but with every nth element removed. For example: ``` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` If `n = 4` then the result would be ``` [1, 2, 4, 5, 6, 8, 9] ``` Note: the numpy requirement is due to this being used for a machine learning assignment where the dependencies are fixed.
**Approach #1 with `modulus`** ``` a[np.mod(np.arange(a.size),4)!=0] ``` Sample run - ``` In [255]: a Out[255]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [256]: a[np.mod(np.arange(a.size),4)!=0] Out[256]: array([1, 2, 3, 5, 6, 7, 9]) ``` --- **Approach #2 with `masking` : Requirement as a `view`** Considering the views requirement, if the idea is to save on memory, we could store the equivalent boolean array that would occupy `8` times less memory on Linux system. Thus, such a mask based approach would be like so - ``` # Create mask mask = np.ones(a.size, dtype=bool) mask[::4] = 0 ``` Here's the memory requirement stat - ``` In [311]: mask.itemsize Out[311]: 1 In [312]: a.itemsize Out[312]: 8 ``` Then, we could use boolean-indexing as a view - ``` In [313]: a Out[313]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [314]: a[mask] = 10 In [315]: a Out[315]: array([ 0, 10, 10, 10, 4, 10, 10, 10, 8, 10]) ``` --- **Approach #3 with `NumPy array strides` : Requirement as a `view`** You can use [`np.lib.stride_tricks.as_strided`](https://github.com/numpy/numpy/blob/master/numpy/lib/stride_tricks.py) to create such a view given the length of the input array is a multiple of `n`. If it's not a multiple, it would still work, but won't be a safe practice, as we would be going beyond the memory allocated for input array. Please note that the view thus created would be `2D`. Thus, an implementaion to get such a view would be - ``` def skipped_view(a, n): s = a.strides[0] strided = np.lib.stride_tricks.as_strided return strided(a,shape=((a.size+n-1)//n,n),strides=(n*s,s))[:,1:] ``` Sample run - ``` In [50]: a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # Input array In [51]: a_out = skipped_view(a, 4) In [52]: a_out Out[52]: array([[ 1, 2, 3], [ 5, 6, 7], [ 9, 10, 11]]) In [53]: a_out[:] = 100 # Let's prove output is a view indeed In [54]: a Out[54]: array([ 0, 100, 100, 100, 4, 100, 100, 100, 8, 100, 100, 100]) ```
[numpy.delete](https://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html) : ``` In [18]: arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [19]: arr = np.delete(arr, np.arange(0, arr.size, 4)) In [20]: arr Out[20]: array([1, 2, 3, 5, 6, 7, 9]) ```
```css .container { /* Container's width can be dynamically resized. I put width = 300px in the example to demonstrate a case where container's width couldn't hold second msg */ width: 300px; display: flex; flex-direction: column; align-items: flex-start; padding: 1em; background-color: blue; } .parent{ display:flex; flex-direction:row; flex-wrap:nowrap; padding:1em; background-color:red; box-sizing:border-box; margin-bottom: 1em; } .name{ background-color:mistyrose; width: 70px; padding: 1em; } .msg{ background-color:powderblue; max-width: 30vw; padding:.5em; word-wrap:break-word; } ``` ```html <div class='container'> <div class="parent"> <div class="name"> David </div> <div class="msg"> How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? </div> </div> <div class="parent"> <div class="name"> Hannah </div> <div class="msg"> somethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomething </div> </div> </div> ``` Ideally , I want each `msg` to have max-width of `30vw`, but at the same time respect parent's width. The **first** row behaves correctly, but the **second** row doesn't. If parent's width is resized to some value smaller than 30vw, the **second** msg will overflow. I want something like `max-width = min(30vw, parent's width)` **NOTE**: Container's width can be dynamically resized. I put width = 300px in the example to demonstrate a case where container cannot hold the second msg which somehow has width = it's max-width = 30vw. **You can also see the example at** <http://jsfiddle.net/vbj10x4k/231/>
Simply set `max-width:100%` to `.parent` so this one respect the width of `.container` then rely on flex and your element will shrink by default. Also don't forget `min-width:0` on the element itself [to enable the element to shrink](https://stackoverflow.com/questions/36247140/why-dont-flex-items-shrink-past-content-size). ```css .container { width: 300px; display: flex; flex-direction: column; align-items: flex-start; padding: 1em; background-color: blue; } .parent{ display:flex; flex-direction:row; flex-wrap:nowrap; padding:1em; background-color:red; box-sizing:border-box; margin-bottom: 1em; max-width:100%; /*Added this */ } .name{ background-color:mistyrose; width: 70px; padding: 1em; } .msg{ background-color:powderblue; max-width:30vw; min-width:0; /*addedd this*/ padding:.5em; word-wrap:break-word; } ``` ```html <div class='container'> <div class="parent"> <div class="name"> David </div> <div class="msg"> How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? How are you? </div> </div> <div class="parent"> <div class="name"> Hannah </div> <div class="msg"> somethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomethingsomething </div> </div> </div> ```
If you do not need to support IE11 or safari, a simple solution would be to switch your `word-wrap:break-word;` with `word-wrap: anywhere` ([working example](http://jsfiddle.net/xs2dbtL8/)) If you need to support safari (but still not IE11), then instead replace `word-wrap:break-word;` with `word-break: break-word`. Note that `word-break: break-word` is [deprecated](https://developer.mozilla.org/en-US/docs/Web/CSS/word-break) in favour of `word-wrap: anywhere`. I would also recommend switching `word-wrap` for its more commonly used alias: `overflow-wrap`. It will be more effective when used in a search term. Also see: [Difference between overflow-wrap and word-break?](https://stackoverflow.com/questions/17259916/difference-between-overflow-wrap-and-word-break)
hope you are doing great. So, for one of my recent projects I need to do something really similar to the page apple built for comparing iPad models. (<https://www.apple.com/la/ipad/compare/>) the web needs to be accessible and, unfortunately, this part has already been built but a11y wasn't really taken into account and now we need to refactor it. So I went through the apple web an saw that their layout is somehow similar to ours. Also, I tested using NVDA and I think this is what I need. Every time, before reading the column value, NVDA reads the column header that is set to the selected product. That way, the user can know what product has that feature. Then I tested on Jaws and found that it is not reading the headers every time before the value. That is not good because the user is not able to know the product that has the feature being read. Is there a configuration that needs to be activated to have the same behavior from NVDA into JAWS? Jaws is important for the client. Thanks
See the code if this is what you're looking for: ``` List=[1,2,3] avg=[0]*len(List) for i in range(len(List)-1): avg[i]=(List[i]+List[i+1])/2 print(avg) ``` Hope you got the code. Output: [1.5,2.5,0]
I guess you want to do the following: ``` listOfNumbers = [1,2,3] averagesOfNumbers = [0,0,0] for i in range(len(listOfNumbers)-1): averagesOfNumbers[i] = (listOfNumbers[i] + listOfNumbers[i+1]) / 2 ```
I have seen people/articles/SO posts who say they have designed their own "lock-free" container for multithreaded usage. Assuming they haven't used a performance-hitting modulus trick (i.e. each thread can only insert based upon some modulo) how can data structures be multi-threaded but also lock-free??? This question is intended towards C and C++.
For locks, the idea is that you acquire a lock and then do your work knowing that nobody else can interfere, then release the lock. For "lock-free", the idea is that you do your work somewhere else and then attempt to atomically commit this work to "visible state", and retry if you fail. The problems with "lock-free" are that: * it's hard to design a lock-free algorithm for something that isn't trivial. This is because there's only so many ways to do the "atomically commit" part (often relying on an atomic "compare and swap" that replaces a pointer with a different pointer). * if there's contention, it performs worse than locks because you're repeatedly doing work that gets discarded/retried * it's virtually impossible to design a lock-free algorithm that is both correct and "fair". This means that (under contention) some tasks can be lucky (and repeatedly commit their work and make progress) and some can be very unlucky (and repeatedly fail and retry). The combination of these things mean that it's only good for relatively simple things under low contention. Researchers have designed things like lock-free linked lists (and FIFO/FILO queues) and some lock-free trees. I don't think there's anything more complex than those. For how these things work, because it's hard it's complicated. The most sane approach would be to determine what type of data structure you're interested in, then search the web for relevant research into lock-free algorithms for that data structure. Also note that there is something called "block free", which is like lock-free except that you know you can always commit the work and never need to retry. It's even harder to design a block-free algorithm, but contention doesn't matter so the other 2 problems with lock-free disappear. *Note: the "concurrent counter" example in Kerrek SB's answer is not lock free at all, but is actually block free.*
The new C and C++ standards (C11 and C++11) introduced threads, and thread shared atomic data types and operations. An atomic operation gives guarantees for operations that run into a race between two threads. Once a thread returns from such an operation, it can be sure that the operation has gone through in its entirety. Typical processor support for such atomic operations exists on modern processors for compare and swap (CAS) or atomic increments. Additionally to being atomic, data type can have the "lock-free" property. This should perhaps have been coined "stateless", since this property implies that an operation on such a type will never leave the object in an intermediate state, even when it is interrupted by an interrupt handler or a read of another thread falls in the middle of an update. Several atomic types may (or may not) be lock-free, there are macros to test for that property. There is always one type that is guaranteed to be lock free, namely `atomic_flag`.
I'm trying to build a simple checklist to determine the quality of a datacenter... where and what should I look for and how can I determine if what the owners say (e.g. "our UPS keep the data center up for 100 days without power") is true or not? What are typical signs or good or bad data centers?
Excellent as always Kyle, A couple of things I've learned from experience: * Ask if there are generators to backup the UPS's, if so have the generators been tested, how often? * What physical locks and checks do they have in place to prevent electricians from killing the power? * What liability/insurance coverage do they have? * How do they deal with situations when they don't meet their SLA? * How often have they not met an SLA? * How much power do they provide to each rack/cage/etc.? (Will you be power constrained and need another rack/cage just for the extra power?) * Ask for References, in your industry would be good. Funny stories that weren't funny at the time: 1. There was a fire in Vancouver in an underground electrical compartment, 4 blocks from my DC, the fire took out the power for a 10 block radius. The UPS' kept the lights on until the Gen-set came online. Gen-set stayed online for about an hour before over-heating. UPS's were able to keep the lights on for another 30 minutes after the gen-set did a safety shut down. Gen-set belonged to the building, IIRC the DC was able to blame them and washed their hands. 2. An electrician killed the power to a couple rows of racks at the DC because the panel some how fell and knocked all the breakers open. I've also heard about an electrician at another DC going to work on a UPS, not putting it into bypass mode and taking down the whole DC.
I work in a small data center in Silicon Valley. I'm the sysadmin on the managed-server side of the business. Bad signs: * Lack of redundant monitoring and alerting for power, temperature, humidity * Lack of monitoring for network devices, colos, servers and other equipment * Clutter and not using cable-ties or other cable management to keep clean, organized racks Good signs: - Onsite diesel generator with automatic failover - Backup chillers and air handlers with automatic failover - Plenty of bandwidth on major carrier backbones (AT&T, XO Comm) - Redundant network providers - Redundant core routers, firewalls, load balancers and switches - Running memory check and hardware diagnostics before deploying servers Name brand servers are fine, but if they're old and have been around the block a bunch of times, you'd better make sure they're passing hardware diagnostics before using them. A good data center should provide its customers with a website where they can monitor their bandwidth consumption and uptime. They should also answer any questions. Ask them the make and model of their UPS. Ask them to see the current load on the UPS. With this information you can verify how long it can go without power. But honestly, the UPS should not be your concern. A UPS only provides a brief uptime (30 minutes or so). A much better concern is if the DC has a backup generator. It's also worthwhile to ask which grid the DC is on. In terms of brownouts and blackouts, different priorities are assigned to different grids. Guess what? Hospitals and fire stations are high priority (power is never cut). If the Data Center is on the same grid, its guaranteed reliable power. Ask them how much power available per rack. Where I work we provide each rack with 3x 25amp circuits. A typical 1u server consumes 1-3 amp.
I want to increase readability of my jtable , here is MyTableModel.java class below , how to make each row with 2 different color [shown in this picture](http://www.microsoft.com/library/media/1033/athome/images/tiptalk/table.jpg) . What should be the specific method that I can give different color to each row to increase readability of the user. ``` public class MyTableModel extends AbstractTableModel{ String [] columnNames; Vector<Vector<Object>> data; public DataAccessObject ObjDb = new DataAccessObject (); public MyTableModel(String [] coln , Vector<Vector<Object>> data) { columnNames = coln; this.data =data; } @Override public int getColumnCount() { return columnNames.length; } @Override public int getRowCount() { return data.size(); } @Override public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data.get(row).get(col); } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int col) { if (col <= 0) { return true; } else { return true; } } public void setValueAt(Object value, int row, int col) { data.get(row).set(col, value); fireTableCellUpdated(row, col); } private class RowListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { return; } // output.append("ROW SELECTION EVENT. "); // outputSelection(); } } private class ColumnListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { return; } // output.append("COLUMN SELECTION EVENT. "); // outputSelection(); } } } ``` Netbeans automatically created my jtable with variable name I set is mytable then I have problem with defining prepareRenderer below , do I miss step here ? I wanna make each row with different color Here is my sample code below. ``` mytable.prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); // Alternate row color if (!isRowSelected(row)) c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY); return c; } }; ``` I have also use this one but this sets 5 columns i have 7 columns remaining two is not colored at the end , when I click the white colored row the text color disappears. ``` mytable.setDefaultRenderer(Object.class, new TableCellRenderer() { private DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); System.out.println(column); if (row % 2 == 0) { c.setBackground(Color.WHITE); } else { c.setBackground(Color.LIGHT_GRAY); } return c; } }); ```
You could... ------------ Use `JXTable` from [SwingLabs, SwingX library](https://java.net/projects/swingx) which has functionality which could do this...this would be my preferred solution if you can use 3rd party libraries... You could... ------------ Use Nimbus look and feel which does this...but this precludes you from using other look and feels (like the system look and feel) You could... ------------ Create your own series of custom `TableCellRenderer`s which color their background based on the current row...this is tedious as EVERY cell renderer you might need, needs to be able to perform this operation... You could... ------------ Override the `prepareCellRenderer` method of the `JTable` and forcefully set the background of the cell renderer yourself, based on the row...I'm not a fan of this solution, as it's forcing a design choice onto the renderer which might not fit it's requirements (overriding values the cell renderer might want) and locks you into a particular implementation of the table... You could... ------------ Create a `JViewport` which was capable of talking with the `JTable` and rendered the candy stripping underneath the table, but the table and renderers would need to be transparent...I've done this, it's...complicated...but allowed me to continue the candy stripping the full length of the view port (beyond the renderable area of the table)... **Updated with `JViewport` example** This is an example of a concept I implemented a while ago for a project (it is actually managed by an `interface` so I could include `JList` and `JTextArea` as well, but that's another question)... Basically, it makes the `JViewport`, which appears below the `JTable`, responsible for rendering the actual candy stripping. But "why?" you ask...because it doesn't affect the table or cell renderer. The only requirement that this makes is that both the table and cell renderers are transparent (unless they have to be otherwise). This means, you don't need to put candy stripping logic in your renderers, this means you don't need to override `prepareRenderer` of every table you create and mangle the requirements of the cell renderers... It's far from perfect, but demonstrates the basic idea... ![CandyStripped](https://i.stack.imgur.com/llgrw.gif) Okay, but why bother? Well, basically, this approach allows you to paint beyond the area painted by the table... ![CandyStripping](https://i.stack.imgur.com/WR2Ui.png) ``` import java.awt.Color; import java.awt.Component; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class CandyStrippedTable { public static void main(String[] args) { new CandyStrippedTable(); } public CandyStrippedTable() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } Object[] columns = new Object[10]; for (int col = 0; col < columns.length; col++) { columns[col] = (char) (65 + col); } Object[][] data = new Object[10][10]; for (int row = 0; row < data.length; row++) { for (int col = 0; col < data[row].length; col++) { data[row][col] = row + "x" + col; } } DefaultTableModel model = new DefaultTableModel(data, columns); JTable table = new JTable(model); table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setOpaque(isSelected); return this; } }); table.setFillsViewportHeight(true); table.setOpaque(false); JScrollPane sp = new JScrollPane(); sp.setViewport(new CandyStrippedViewPort(new Color(255, 0, 0, 128))); sp.setViewportView(table); JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(sp); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class CandyStrippedViewPort extends JViewport { private Color candyStrippedColor; public CandyStrippedViewPort(Color color) { candyStrippedColor = color; } public Color getCandyStrippedColor() { return candyStrippedColor; } public void setCandyStrippedColor(Color candyStrippedColor) { this.candyStrippedColor = candyStrippedColor; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(getCandyStrippedColor()); Component view = getView(); if (view instanceof JTable) { JTable table = (JTable) view; Rectangle viewRect = getViewRect(); int y = 0; int row = 0; if (table.getRowCount() > 0) { row = table.rowAtPoint(viewRect.getLocation()); while (row < table.getRowCount()) { int rowHeight = table.getRowHeight(row); Rectangle cellRect = table.getCellRect(row, 0, true); if (row % 2 == 0) { g2d.fillRect(0, cellRect.y - viewRect.y, getWidth(), cellRect.height); } y = cellRect.y + cellRect.height; row++; } } int rowHeight = table.getRowHeight(); while (y < getHeight()) { if (row % 2 == 0) { g2d.fillRect(0, y, getWidth(), rowHeight); } row++; y += rowHeight; } } g2d.dispose(); } } } ``` **Formatting numbers in cell renderers** You could start with something like... ``` obj.table.setDefaultRenderer(Double.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value instanceof Number) { value = NumberFormat.getNumberInstance().format(value); } super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setOpaque(isSelected); return this; } }); ``` If, for some reason, the default format instead suitable, you could do something like... ``` obj.table.setDefaultRenderer(Double.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value instanceof Number) { NumberFormat ni = NumberFormat.getNumberInstance(); ni.setMaximumFractionDigits(2) value = ni.format(value); } super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); setOpaque(isSelected); return this; } }); ``` Instead
long time ago, i had the same problem. In this case i use the JXTable from the swingX library instead of the JTable. This componenet has a great method: ``` addHighlighter(HighlighterFactory.createSimpleStriping()); ``` good luck
There is a long history of Christian philosophy† drawing a distinction between knowledge gained from rational/empirical sources and knowledge from divine revelation. It seems Tertullian was one of the earliest authors supporting this idea, followed later by Locke, Martin Luther, Calvin, and more recently, Swinburne. The common theme is that there are different sources of knowledge (divine, natural), and some authors even say when the two conflict, the rational one must go. It varies by author, but there is also some kind of [reflective equilibrium](https://en.wikipedia.org/wiki/Reflective_equilibrium) that occurs, that divine revelation is only actually knowledge if it doesn't contradict other existing divine and rational knowledge. But I think asserting that there is some source of knowledge outside of the rational means that "[anything goes](https://en.wikipedia.org/wiki/Principle_of_explosion)." How then is it possible to justify divine knowledge with consistency (a consistent belief system)? --- † I am not as familiar with other religious philosophies, other examples are welcome.
I prefer to refer to 'belief'. Since knowledge is necessarily true, and all truths are consistent, I can't see how logically there could be an inconsistency between rational and revealed knowledge. Also I always thought that the proper response to revelation is faith. We believe on faith, not from knowledge, that X has been revealed and X is true. Those points aside ... Because beliefs have two or more sources doesn't mean that they - the beliefs - conflict. When they do, I suppose the primacy of revelation could be grounded on the infallibility of revelation as the Word of God. What God reveals cannot be wrong or false but what we imperfectly rational epistemic agents take to be rational and true may be wrong or false and very often is. This is not my view; I am simply scouting conceptual possibilities. I think it is a weakness in the 'What God reveals cannot be wrong or false' view that while it may be true, even definitionally true, it does not entail that we imperfect epistemic agents understand and interpret revelation correctly.
The other answers here don't seem to take into account what kinds of things divine revelations tend to actually be. The vast majority of them are *directives*, be that "Don't kill innocent people." or "Take over these three countries.", "Marry only one person.", "Don't have these three specific kinds of gay sex." or "Always carry a comb." How do those 'mean *anything goes?*'. How would you rationally decide whether or not to have the kinds of sex banned (because there are plenty), or whether it is silly or essential for some guys to always know where they can get ahold of a comb (even though nobody can see their hair)? How can such a directive contradict other knowledge? So why focus on that possibility as the central question? Some of the rest of them appear to be facts, but are wholly untestable "Mary died a Virgin." "I am Led to accomplish X and Way will be open." "Jesus (or The Last Imam) will come back some day and save us." "We will be the last generation born to our people." These might somehow contradict scientific knowledge or common sense, but they *intend* to do so. Things like Creationism, the Platonic layout of the solar system, numerological prophesies like Millennialism and other major traditional clashes with science or common sense that can be proven wrong *have not been divine revelations*. They have significance because other stories are embedded in traditions that assume them, and the context has attached significance to them. Reiterations of them are not the kind of revelations that many traditions tend to accord the honor of trumping rational observations. The 'factual' content is arbitrary and untraceable, so the disproof is always open to doubt. And once it is interpreted and communicated, and the originator is dead, the content and interpretation are open to doubt. [Even the most ardent fundamentalist has to admit that some deductions from scriptural content involve more arrogance than inspiration. (The televangelist in the Christal Spire didn't die.) That is a totally different argument.] What this kind of 'knowledge' does is provide markers of a faith tradition, and the sacrifice involved or the judgment evaded provides a cognitive dissonance tradeoff that solidifies tribal identity. That value *may very well* always trump behaving rationally. Because tribal solidarity itself is rational: it creates more effective placebos, it makes people less neurotic, it creates boundaries between nations that can never be expanded by war, and it does a few other things we could really use in the modern world, as our modern attempts at tribal solidarity seem to be failing as badly as our attempts to do away with it.
No matter what I try, I can't solve this problem. I'm almost done but I need to get just one more thing to be able to finish it. > > **Problem** > > > The first, second and fourth term of the arithmetic and of the geometric sequence are equal, respectively. The third term of the arithmetic sequence is by $18$ greater than the third term of the geometric sequence. Determine both sequences. > > > --- *My attempt* I first wrote down the relationships between the terms. $$a\_1=b\_1$$ $$a\_2=b\_2$$ $$a\_3=b\_3+18$$ $$a\_4=b\_4$$ We can rewrite the last three relationships as $$a\_1+d=b\_1r$$ $$a\_1+2d=b\_1r^2+18$$ $$a\_1+3d=b\_1r^3$$ Then we can square $a\_2=b\_2$ $$a^2\_2=(a\_1+d)^2=b^2\_2=(b\_1r)^2$$ Rewrite $(b\_1r)^2$ $$(b\_1r)^2=b^2\_1r^2=b\_1b\_1r^2=b\_1b\_3$$ So, we now know that $a^2\_2=b\_1b\_3$. Based on that, we can write $$(a\_1+d)^2=b\_1b\_3$$ And since $b\_1=a\_1$ $$(a\_1+d)^2=a\_1b\_3$$ We also know that $a\_3=b\_3+18 \leftrightarrow b\_3=a\_3-18$ $$(a\_1+d)^2=a\_1(a\_3-18)$$ Which gives $$(a\_1+d)^2=a\_1(a\_1+2d-18)$$ Now, let's rewrite that as $$a^2\_1+d^2+2a\_1d=a^2\_1+2a\_1d-18a\_1$$ From that we have $$d^2+18a\_1=0$$ *Now I just need to get another equation to form a system of equations. From that, I can get $d$ or $a\_1$, and then I can use the variable that I've got to get the second variable (i.e. the one I did not got). When I get $a\_1$, I also get $b\_1$ since $a\_1=b\_1$. Then I'll have $d$, $a\_1$ and $b\_1$. If I know these variables, I can easily get $r$. And then I can finally write out both sequences.* --- Of course, I also have the solution. It is > > Arithmetic sequence: $$\langle-2,4,10,16,...\rangle$$ > Geometric sequence: $$\langle-2,4,-8,16,...\rangle$$ > > >
One more way, if you use Stirling's approximation for $2n$: $$ (2n)! \sim \bigg(\frac{2n}{e} \Bigg)^{2n} 4 \sqrt{\pi n} $$ then $n^{2n}$ term cancels out and you are left with (set $\frac{4}{e^2} = x <1$) $$ 4 \sqrt{\pi} \sum\_{k=1}^{n} \bigg(\frac{4}{e^2}\bigg)^k \sqrt{k} < 4 \sqrt{\pi} \sum\_{k=1}^{n}k x^k \to \frac{ 4 \sqrt{\pi} x}{(1-x)^2} $$ this convergence works since $\frac{4}{e^2} <1$. Since the original sum is upper-bounded by the convergent sum, it converges too.
$$\frac{(2n+2)!}{(n+1)^{2(n+1)}}\frac{n^{2n}}{(2n)!}=\frac{(2n)!(2n+1)(2n+2)}{(n+1)^{2n}(n+1)^2}\frac{n^{2n}}{(2n)!}=\frac{2(2n+1)}{n+1}(\frac{n}{n+1})^{2n}$$ $$\lim\_{n\to+\infty}\frac{2(2n+1)}{n+1}=4$$ $$\lim\_{n\to+\infty}(\frac{n}{n+1})^{n}=\lim\_{n\to+\infty}(\frac{n+1-1}{n+1})^{n}=\lim\_{n\to+\infty}((1+\frac{-1}{n+1})^{-(n+1)})^{-\frac{n}{n+1}}=\lim\_{n\to+\infty}e^{-\frac{n}{n+1}}=\frac{1}{e}$$ therefore $$\frac{2(2n+1)}{n+1}(\frac{n}{n+1})^{2n} = \frac{4}{e^2} < 1$$ So the sum converges.
I have an ArrayList of custom FlightData objects within the intent. I load the intent and get the arraylist as null, and the foreach loop also forces me to use `Object` as type. Saving arraylist into intent: ```java intent.putParcelableArrayListExtra("FlightDataList", (ArrayList<? extends Parcelable>) flightDataList); ``` Loading of intent: ```java Intent intent = getIntent(); LinearLayout layout_datasheet = findViewById(R.id.layout_datasheet); List flightDataList = intent.getParcelableArrayListExtra("FlightDataList"); if (flightDataList == null){ Log.d("flightDataList_size", "FlightDataList is null"); // this fires } assert flightDataList != null; for (Object data : flightDataList){ data = (FlightData) data; // items in list are of type FlightData TextView tv = new TextView(this); tv.setText(data.toString()); layout_datasheet.addView(tv); } ``` My custom class' parcelable functions (x,y,time, has getters-setters): ```java @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeDouble(x); dest.writeDouble(y); dest.writeDouble(time); } public static final Creator<FlightData> CREATOR = new Creator<FlightData>() { @Override public FlightData createFromParcel(Parcel in) { return new FlightData(in); } @Override public FlightData[] newArray(int size) { return new FlightData[size]; } }; ```
I'm not exactly sure why you call this a merge function. You don't really need to define a custom function. You can do this with a simple lambda function. Here's my solution. ``` import tensorflow as tf from tensorflow.keras.layers import Lambda import tensorflow.keras.backend as K a = tf.constant([[1,2,3]]) b = tf.constant([[1,1,2,2,3,3]]) a_res = tf.reshape(a,[-1,1]) # make a.shape [3,1] b_res = tf.reshape(b,[-1,2]) # make b.shape [3,2] layer = Lambda(lambda x: K.sum(x[0]*x[1],axis=1)) res = layer([a_res,b_res]) with tf.Session() as sess: print(res.eval()) ```
You can do something following: ``` a = tf.constant([[1,2,3]]) # Shape: (1, 3) b = tf.constant([[1,1,2,2,3,3]]) # Shape: (1, 6) def customMergeFunct(x): # a_ = tf.tile(x[0], [2, 1]) # Duplicating 2 times (Original) # Update: No need of doing this as tf.multiply will use Broadcasting b_ = tf.transpose(tf.reshape(x[1], [-1, 2])) # reshaping followed by transpose to make a shape of (2, 3) to serve the purpose + multiplication rule return tf.reduce_sum(tf.multiply(x[0], b_), axis=0) # Element-wise multiplication followed by sum # Using function c = Lambda(customMergeFunct)([a,b]) # OR in a reduced form c = Lambda(lambda x: tf.reduce_sum(tf.multiply(x[0], tf.transpose(tf.reshape(x[1], [-1, 2]))), axis=0))([a,b]) ``` Output: ```py with tf.Session() as sess: print(c.eval()) # Output: [2 8 18] # OR in eager mode print(c.numpy()) # Output: [2 8 18] ``` Updated solution is computationally efficient than the original solution as we don't actually need to apply tile on `x[0]`
Let say I have 2 classes: ``` public class Person { private String name; private int age; private Contact contact; //getter & setter } public class Contact { private String phone; private String email; //getter & setter } ``` With the classes above, I want to create 2 instances of `Person` class, with different field value. Then I want to compare some fields of 2 objects with their getter function, but I don't want to compare all fields. For example, I want to compare the field `name` and `phone`, then I will store this 2 getter method to a list like something below: ``` List<WhatShouldBeTheDataType> funcList = new ArrayList<>(); funcList.add(MyClass::getName); funcList.add(MyClass::getContact::getPhone) //I know this won't work, what should be the solution? ``` then loop through the `funcList`, pass the 2 objects I want to compare into the function, if the value not same, write something into the database. This can be easily done with ordinary `if...else...` way, but is it possible to do in Java 8 way? Below is what I want to achieve in `if...else...` way: ``` if(person1.getName() != person2.getName()) { //message format basically is: "fieldName + value of object 1 + value of object 2" log.append("Name is different: " + person1.getName() + ", " + person2.getName()); } if(person1.getContact.getPhone() != person2.getContact().getPhone()) { log.append("Phone is different: " + person1.getContact.getPhone() + ", " + person2.getContact.getPhone()); } //other if to compare other fields ```
It looks like `Person` and `MyClass` refer to the same thing in your question. You need a `Function<Person,String>`, since your functions accept a `Person` instance and return a `String`: ``` List<Function<Person,String>> funcList = new ArrayList<>(); funcList.add(Person::getName); funcList.add(p -> p.getContact().getPhone()); ``` For the second function, you can't use a method reference, but you can use a lambda expression instead. Given an instance of `Person`, you can apply your functions as follows: ``` Person instance = ...; for (Function<Person,String> func : funcList) { String value = func.apply(instance); } ```
to complete Eran's code: ``` boolean isEqual(Person person1, Person person2){ for (Function<Person,String> function:functionList) { if (!function.apply(person1).equals(function.apply(person2))) return false; } return true; } ``` then use the returned boolean to check and update your database.
How I can hide variable from using when it is not defined with bash command with this situation: ``` EXCLUDE_PORTS="--exclude-ports $2" if [ "${EXCLUDE_PORTS:-}" == "" ]; then EXCLUDE_PORTS='' fi ``` I need to hide also --exclude-ports, when $2 it is not specified. Actually when I don't specified $2 at script startup, script take only first part empty "--exclude-ports", and this is ruining my script.
There is a shorthand for this: ``` EXCLUDE_PORTS=${2:+--exclude-ports $2} ``` The shorthand is `${var:+ <alternate value>}` which is empty if `var` is unset or empty, and else is substituted by the alternate value. Now, if you combine this with [Léa's answer](https://stackoverflow.com/a/63220480/7233423): ``` EXCLUDE_PORTS=( ${2:+--exclude-ports "$2"} ) ```
Use Built-In Conditional Expressions; Verify with Parameter Expansion --------------------------------------------------------------------- You can refactor this to a single line using the built-in [conditional expressions](https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions) and the Boolean `&&` [conditional construct](https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs). It's also a good idea to use proper quoting. For example: ``` [[ -n "$2" ]] && EXCLUDE_PORTS="--exclude-ports '$2'" ``` You can verify the logic here with the `:-` [parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) like so: ``` # make sure your environment is clean for testing unset EXCLUDE_PORTS # set exactly two positional arguments set -- one two # set variable if $2 zero length when expanded [[ -n "$2" ]] && EXCLUDE_PORTS="--exclude-ports '$2'" # print variable if set, or message to aid debugging echo "${EXCLUDE_PORTS:-variable is empty}" ``` > > > ``` > # --exclude-ports 'two' > > ``` > > When you only have one positional parameter: ``` unset EXCLUDE_PORTS set -- one [[ -n "$2" ]] && EXCLUDE_PORTS="--exclude-ports '$2'" echo "${EXCLUDE_PORTS:-variable is empty}" ``` > > > ``` > variable is empty > > ``` > >
Are there really such thing as sheidim? If so, what are they? Please include sources.
The gemara clearly mentions sheidim, and there were certainly Rishonim (e.g. Rashi) and Acharonim who took these mentions literally. The Rambam takes them non-literally, as he writes in Moreh Nevuchim 1:7 and in his perush haMishnayot to Avodah Zarah 4:7. The Kotzker Rebbe has a famous elu veElu in which he explains that the Rambam effectively paskened sheidim out of existence. However, if one looks at the actual words of the Rambam, it seems rather unlikely that the Rambam would agree to this harmonization. I discuss this in depth, giving the text of the actual sources, in [this parshablog post](http://parsha.blogspot.com/2010/10/demons-on-ark-and-kotzkers-famous-elu.html): <http://parsha.blogspot.com/2010/10/demons-on-ark-and-kotzkers-famous-elu.html>
It is true that the Talmud Bavli clearly mentions shedim in many places. As in other areas, they followed the science of the time, so something that seems unscientific now was a reasonable belief back then. However, that doesn't mean they were completely wrong. They felt there were certain harmful invisible forces that existed in the world and that one must protect himself from. Although we wouldn't call these forces 'demons' nowadays, we do know of other microscopic forces that can cause harm. So if they said one should wash his hands to get rid of "ruach rah" or "bad spirits", it wasn't exactly wrong. Washing hands does help get rid of the "bad spirits" of bacteria. While its true not all cases can be explained like this, the overall belief in 'demons' can often be connected to many real phenomena.
I try to do this: ``` <div id="{{mystring.replace(/[\s]/g, \'\')}}"></div> ``` but its not working. "mystring" is an object on `$scope` with string like "my string is this" with spaces I want to remove from the view.
If you simply need it in one or two places it may be easier to split and join: ``` $scope.boundString = 'this is a string with spaces' ``` with that you could do in your template: ``` <span>my string is: {{ boundString.split(' ').join('') }}</span> ``` and you would get: ``` my string is: thisisastringwithoutspaces ``` another approach that has been mentioned is the regex version ('g' is for global): ``` <span>my string is: {{ boundString.replace(/ /g, '') }}</span> ``` I guess the point is that you can do whatever you want to a string within an expression. These examples are bad convention with respect to Angular dirty-checking. In Angular, bound functions (string.replace, string.split) get evaluated differently opposed to a specified value (string, boolean) when bound to a template's expression. The result of a bound function must be evaluated before Angular knows whether or not to update the DOM. This can be costly over a large app. I would suggest using another variable to track the un-spaced value: ``` $scope.noSpaces = $scope.boundString.replace(/ /g, ''); ``` HTML: ``` <span>{{ noSpaces }}</span> ``` This way, when a digest loop is triggered, Angular will check if noSpaces has changed as opposed to evaluating boundString.replace(/ /g, ''). What if you are ng-repeating? Good question. ``` for (var idx = 0, idx < $scope.boundIterable.length, i++) { $scope.boundIterable[i].noSpaces = $scope.boundIterable[i].boundString.replace(/ /g, ''); } ``` HTML: ``` <ul ng-repeat="iterable in boundIterable"> <li>{{ iterable.noSpaces }}</li> </ul> ```
You can do it by using `replace()`: ``` {{mystring.replace(" ","")}} ``` that's it I hope so.
I'm running XP Pro, and I have a XAMPP setup. I'm learning Zend Framework, and I'm trying to use Zend\_Mail. I guess I need to setup or configure my SMTP on my machine for this to work? Can anyone tell me how to do this and most importantly how to test this to know if it's working (maybe an easier way than zend\_mail because I'm a newbie there too and I may be doing other things wrong there). So in short, I just want to set up SMTP and mail from localhost just to be sure things are set up correctly. PS: so far, I have turned on (installed) the IIS from the windows components.
Given you already have AD in house I recommend considering freeipa/Redhat IDM set up as a trusted domain of active directory. Besides being free, this allows you to use all existing user & group information in AD, while setting access controls and policies in ipa. You also get kerberos & sso potential. Ipa in this setup presents ad groups as netgroups (like nis). It comes with a nice web gui, and internal role based access control (eg who can join hosts to the kerberos realm, who can manage sudo etc). Any client should be able to authenticate against either ipa or AD. QAS (either version) is an ideal solution in my opinion except for the cost, which can be insane. It also requires a schema change to AD, which itself is fine but your AD guys might not like that. The newer versions of winbind are much more stable than 3.x, but require you to have access policies (sudo, ssh) configured on each host. I can't speak for centrify.
Winbind works fine especially with the RID option. Use the AD servers as the NTP maters for the unix boxes, it makes thing a little easier and it works fine. Get kerberos working with AD next, it's very simple, just make sure ntp is working and the clients are using ad for dns. The RID option in winbind will produce a predictable uid for users and gid for your groups. The samba/winbind config will let you pick a shell that all the users will get, I'm not sure if you can config to have individual users have different shells, the user can always start up whatever shell they want when they login. The login restrictions can be maintained through the sshd\_config, restricting based on groups. You'll have to start with the older machines and the Netapp to see if the version of samba/winbind you install supports the backend RID option.
I got a simple task: Setup a ToD server... It is not NTP. It runs on port 37. It seems to be bundled with inetd or xinetd. Shall be installed on Debian or CentOS. Alternatively FreeBSD (pfsense router). Any hint on how to proceed? Two starter links where after I got stuck: * <http://www.linuxquestions.org/questions/linux-server-73/tod-server-641674/> * <http://en.wikipedia.org/wiki/Time_Protocol> Also very much apreciated if if a way to test if the ToD-server is running allready. I have quite a few servers running but are not aware if any of them allready have the ToD-service running Reason: I am about to setup a solution with broadband over COAX cables using a CMTS and cable modems using a standard called DOCSIS 3. To do so the cable modems needs to receive a time from a ToD-server (Time of day). **UPDATE / Solution** The Time is [RFC 868](https://www.rfc-editor.org/rfc/rfc868) and hardly used any more since NTP and others are better. But the old RFC 868 Time over port 37 is needed for some systems - e.g. Internet over COAX using CMTS and cable modems need a working time server (in DOCSIS documentation called Time of Day server = ToD server). The xinetd that can be installed for Debian includes a time server. It just has to be enabled in etc/xinetd.d/time (disable=no for TCP and/or UDP)
If you're using Debian, xinetd comes with a ToD daemon. If you change the "disable = yes" like in /etc/xinetd.d/time to "disable = no" and then restart xinetd, you should be able to telnet to the server on port 37 and check that you get something returned. You can use something like: ``` nc $IP 37 | hexdump ``` and you'll see that the hex value increases every second.
A "Time of Day" server is a pretty vague term - I'm not clear if that is referring to an an actual service named "ToD", or is just poor documentation. The Time protocol (RFC 868) is so old that very few things use it, except for a small number of embedded firmwares (such as [OpenWRT](http://wiki.openwrt.org/doc/howto/ntp.client)), devices and appliances with little memory. NTP requires more memory than the Time protocol. Nearly all modern appliances can use the Network Time Protocol (NTP) which has replaced the older Time protocol, which is better and probably *more secure* than the ancient time protocol. So spend some time now to see if your device uses NTP support. Believe it or not, the Wikipedia article for `xinetd` contains a single configuration example, and it's for an RFC 868 time server. See <http://en.wikipedia.org/wiki/Xinetd#Configuration> > > An example configuration file for the [RFC 868 time server](http://en.wikipedia.org/wiki/Time_Protocol): > > > > ``` > # default: off > # description: An RFC 868 time server. This protocol provides a > # site-independent, machine readable date and time. The Time service sends back > # to the originating source the time in seconds since midnight on January first > # 1900. > # This is the tcp version. > service time > { > disable = yes > type = INTERNAL > id = time-stream > socket_type = stream > protocol = tcp > user = root > wait = no > } > > # This is the udp version. > service time > { > disable = yes > type = INTERNAL > id = time-dgram > socket_type = dgram > protocol = udp > user = root > wait = yes > } > > ``` > >
I am trying to open up a Word 2007 document (docx), I unzip it successively but I am having an issue with the xPath portion of the code. I want to iterate each element and grab the text within the element. In the current example below I am trying to get the first element's text to get used to the xPath system. document.xml ``` <w:document> <w:body> <w:p> <w:r> <w:t>Testing</w:t> </w:r> </w:p> </w:body> </w:document> ``` PHP ``` $dom = new DOMDocument(); $dom->loadXML($string); $xpath = new DomXPath($dom); $textNodes = $xpath->query("/w:document/w:body/w:p[1]/w:r[1]/w:t[1]"); var_dump($textNodes->item(1)->textContent); ```
So I assume that the missing namespace is only because of the shorten example xml. The original document will provide the namespace. If this is true the xpath query will work. The problem here is, that query is a **DOMNodeList**. var\_dump seens not to work for that. You can use something like: ``` $textNodes = $xpath->query("/w:document/w:body/w:p[1]/w:r[1]/w:t[1]"); foreach ($textNodes as $entry) { echo "node: {$entry->nodeName}," . "value: {$entry->nodeValue}\n"; } ``` Which generate this output (after adding a namespace to your input xml): ``` node: w:t,value: Testing ```
You have got an invalid xpath query which needs to be fixed because an invalid xpath query will always result in an error. You can not use the outcome of it to get nodes out of it. Unfortunately the xpath query is invalid because the XML is invalid. So you can not use the xpath query (or further test it / continue to write it) without fixing the XML first. From the XML you've provided in your question it's apparently missing the namespace declaration of the w-prefix. You need to enable error reporting to the highest level (`E_ALL`), display of errors in your development environment and generally the error logging. You then can follow the error log: ``` Warning: DOMDocument::loadXML(): Namespace prefix w on document is not defined in Entity, line: 1 in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 15 Warning: DOMDocument::loadXML(): Namespace prefix w on body is not defined in Entity, line: 2 in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 15 Warning: DOMDocument::loadXML(): Namespace prefix w on p is not defined in Entity, line: 3 in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 15 Warning: DOMDocument::loadXML(): Namespace prefix w on r is not defined in Entity, line: 4 in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 15 Warning: DOMDocument::loadXML(): Namespace prefix w on t is not defined in Entity, line: 5 in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 15 Warning: DOMXPath::query(): Undefined namespace prefix in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 17 Warning: DOMXPath::query(): Invalid expression in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 17 Fatal error: Call to a member function item() on a non-object in /tmp/execpad-1d8a88cab4fd/source-1d8a88cab4fd on line 18 ``` As these show, there are many problems with the XML which in the end renders the xpath query invalid and finally bring your whole script to halt.
**I have this code:** ``` <?php $files = glob("notes/last.*.*/table.php"); rsort($files); foreach($files as $tables) {include $tables;} ?> ``` **with output:** ``` tables tables tables ``` This will include many php's files from starting from last to the older post. I want to include only the first **10** of the output. (that is the last 10 added) how to do it?
Test this: ``` $i= 0; foreach($files as $tables) { $i++; include $tables; if($i == 10) break; } ```
Try with: ``` $limitedArray = array_slice($files, count($files) - 10); ```
> > I begin on the fifth floor > > and end on floor ninety-nine. > > Made by rounds of four > > and bland bits of design. > > > Here its value's its description > > advance of being digested. > > Some checks confused with encryption. > > Has your security been tested? > > > What's the word? What's it for? How's it stored? What is yours?
you are a > > 1. Hash algorithm > > 2. Used for checking validity without storing the original > > 3. Stored as one of the valid hash values (or buckets). > > 4. you want my name hashed? So it sounds like you are describing a hash algorithm that goes from 5 to 99, so adding up Ascii values of my name (SteveV) mod 94 +5 would do that, which is 83+116+101+118+101+86 mod 94 + 5 = 40 > > > I begin on the fifth floor and end on floor ninety-nine. > > When you hash something you put it the results in buckets or floors? > > > Made by rounds of four and bland bits of design. > > This sounds like it may be describing a hash technique > > > Here its value's its description advance of being digested. > > hash is food before it is eaten/digested > > > Some checks confused with encryption. Has your security been tested? > > Hash is confused with encryption. But encryption can be decrypted, hash is one way. > > > Oh and > > your anagram spells "I am a Hash" > > >
Are you a > > Password > > > I begin on the fifth floor and end on floor ninety-nine. > > It can have 5 characters, but I an not sure about the 99 > > > Made by rounds of four > > A metal lock can have 4 spinning number circles for the combination. > > > and bland bits of design. > > Some passwords can look like this if you type them in \*\*\*\*\*\*. > > > Here its value's its description advance of being digested. > > They are codes that can be cracked. > > > Some checks confused with encryption. Has your security been tested? > > You need to have a strong password. > > >
I am very new to JS & Jquery. I am building a scheduling app. I am storing appointments in a model called "Event". I am using a helper to build the multi-dimensional array from values in columns called "event.time\_start" and "event.time\_end" for a given day that a user might make an appointment. When a user picks a start\_time and end\_time from the dropdown menu, times that already have appointments will be grayed out/"disabled". I am using jquery.timepicker by <http://jonthornton.github.io/jquery-timepicker/> with rails to blocks certain time values in a given array of time pairs ( [8am, 6pm], [1pm, 2pm]). I am finding the "other" events on a given day (the ones that inform which times are taken) using the variable @other\_events. this is the helper that pairs the event.start\_time and event.end\_time events\_helper.erb ``` module EventsHelper def taken_times(other_events) other_events.map { |event| [event.time_start, event.time_end] } @taken_times = taken_times(other_events) end end ``` I can get the array to work like this in the view: ``` <% taken_times(@other_events).each do |taken_time| %> <%= taken_time.first.strftime("%l:%M %P")%> <%= taken_time.last.strftime("%l:%M %P")%>, <% end %> ``` But I can't get it to work in the JS. I am now trying to use the Gon Gem What I need to out put to is this: events/show.html.erb view ``` <script> $('#jqueryExample .time').timepicker({ 'timeFormat': 'g:ia', 'disableTimeRanges': [ // start dynamic array ['10:00am', '10:15am'], ['1:00pm', '2:15pm'], ['5:00pm', '5:15pm'] ] //end dynamic array }); $('#jqueryExample').datepair(); </script> ``` so I've tried application.html.erb ``` <%= Gon::Base.render_data({}) %> ``` events\_controller.erb ``` def show @event = Event.new @other_events = Event.where(date_id: params[:id]) gon.taken_times = @taken_times end ``` with the JS ``` <script> $('#jqueryExample .time').timepicker({ 'timeFormat': 'g:ia', 'disableTimeRanges': [ // start dynamic array gon.taken_times //end dynamic array }); $('#jqueryExample').datepair(); </script> ``` but this doesn't work. it just kills the dropdown function of the textfields. I'd love to know what these comma separated objects like "'timeFormat': 'g:ia'," and "disableTimeRanges: [....]" are called so I can better search SO for javascript answers. I am very new to JS & JQuery.
Gon seems the right way to handle this but there are various errors in your code: Where do you write `<%= Gon::Base.render_data({}) %>` ? It should be in the `<head>` tag, before any javascript code Your `event_helper.rb` is wrong: ``` def taken_times(other_events) # Map returns a **copy**, if you don't assign it to anything, it's just lost other_events.map { |event| [event.time_start, event.time_end] } # This has **completely no sense**, this method will throw a stack level too deep error **every time you call it**, you should read a book about programming before trying to use rails @taken_times = taken_times(other_events) end ``` If you want to use that, go for something like ``` def taken_times(other_events) other_events.map { |event| [event.time_start, event.time_end] } end ``` The controller has the same problem of previous code ``` def show @event = Event.new @other_events = Event.where(date_id: params[:id]) # @taken_times is not assigned, gon.taken_times will always be `null` in JS gon.taken_times = @taken_times end ``` You should rewrite it like: ``` helper :taken_times def show @event = Event.new @other_events = Event.where(date_id: params[:id]) gon.taken_times = taken_times(@other_events) end ``` And finally, you have a big syntax error in your javascript code, that's why everything disappear. Also you are using gon if it's something special. Gon just creates a plain **javascript object**, you can access it in javascript like you would do with anything else. ``` <script> $('#jqueryExample .time').timepicker({ 'timeFormat': 'g:ia', // Here you have an opening square brackets, which is never closed // Also, there is no point in having a square brackets here or you'll have an array of array of array, while you want an array of array 'disableTimeRanges': [ // start dynamic array gon.taken_times //end dynamic array }); $('#jqueryExample').datepair(); </script> ``` Which instead should be ``` <script> $('#jqueryExample .time').timepicker({ 'timeFormat': 'g:ia', 'disableTimeRanges': gon.taken_times }); $('#jqueryExample').datepair(); </script> ``` My main suggestion is, **read a Ruby book first**, not one with Ruby and Rails merged, you clearly need to improve your programming skills before doing anything. Start with something like [The Well Grounded Rubyist](https://rads.stackoverflow.com/amzn/click/com/1933988657) and follow up with a good book about javascript (which I have yet to find, comments about it are well appreciated). Then go for [Rails 4 in Action](http://www.manning.com/bigg2/) and at this point you probably understand better what's going on. [This is my recipe to become a good rails developer](http://www.quora.com/Whats-the-best-way-for-a-beginner-to-start-learning-Ruby-on-Rails/answer/Francesco-Belladonna)
Big thanks to Fire-Dragon-Dol. I had to do a few more tweaks...I had to change the helper and add strftime to make it work. I also had to call the helper in a different way...In case anyone should like to see the working code: ``` module EventsHelper def taken_times(other_events) other_events.map { |event| [event.time_start.strftime("%l:%M %P"), event.time_end.strftime("%l:%M %P")] } end end ``` events\_controller.rb ``` include EventsHelper def show @event = Event.new @other_events = Event.where(date_id: params[:id]) gon.taken_times = taken_times(@other_events) show ``` the view ``` <script> $('#jqueryExample .time').timepicker({ 'timeFormat': 'g:ia', 'disableTimeRanges': // start dynamic array gon.taken_times // end dynamic array }); $('#jqueryExample').datepair(); </script> ```
The question is clear, my google- and cplusplus.com/reference-fu is failing me.
[`std::set_union`](https://en.cppreference.com/w/cpp/algorithm/set_union) will contain those elements that are present in both sets only once. [`std::merge`](https://en.cppreference.com/w/cpp/algorithm/merge) will contain them twice. For example, with `A = {1, 2, 5}; B = {2, 3, 4}`: * union will give `C = {1, 2, 3, 4, 5}` * merge will give `D = {1, 2, 2, 3, 4, 5}` Both work on sorted ranges, and return a sorted result. Short example: ``` #include <algorithm> #include <iostream> #include <set> #include <vector> int main() { std::set<int> A = {1, 2, 5}; std::set<int> B = {2, 3, 4}; std::vector<int> out; std::set_union(std::begin(A), std::end(A), std::begin(B), std::end(B), std::back_inserter(out)); for (auto i : out) { std::cout << i << " "; } std::cout << '\n'; out.clear(); std::merge(std::begin(A), std::end(A), std::begin(B), std::end(B), std::back_inserter(out)); for (auto i : out) { std::cout << i << " "; } std::cout << '\n'; } ``` Output: ``` 1 2 3 4 5 1 2 2 3 4 5 ```
To add to the previous answers - beware that the complexity of `std::set_union` is twice that of `std::merge`. In practise, this means the comparator in `std::set_union` may be applied to an element *after* it has been dereferenced, while with `std::merge` this is never the case. Why may this be important? Consider something like: ``` std::vector<Foo> lhs, rhs; ``` And you want to produce a union of `lhs` and `rhs`: ``` std::set_union(std::cbegin(lhs), std::cend(lhs), std::cbegin(rhs), std::cend(rhs), std::back_inserter(union)); ``` But now suppose `Foo` is not copyable, or is very expensive to copy and you don't need the originals. You may think to use: ``` std::set_union(std::make_move_iterator(std::begin(lhs)), std::make_move_iterator(std::end(lhs)), std::make_move_iterator(std::begin(rhs)), std::make_move_iterator(std::end(rhs)), std::back_inserter(union)); ``` But this is undefined behaviour as there is a possibility of a moved `Foo` being compared! The correct solution is therefore: ``` std::merge(std::make_move_iterator(std::begin(lhs)), std::make_move_iterator(std::end(lhs)), std::make_move_iterator(std::begin(rhs)), std::make_move_iterator(std::end(rhs)), std::back_inserter(union)); union.erase(std::unique(std::begin(union), std::end(union), std::end(union)); ``` Which has the same complexity as `std::set_union`.
I was (and still am) looking for an embedded database to be used in a .net (c#) application. The caveat: The Application (or at least the database) is stored on a Network drive, but only used by 1 user at a time. Now, my first idea was [SQL Server Compact edition](http://www.microsoft.com/sql/editions/compact/default.mspx). That is really nicely integreated, but it can not run off a network. [Firebird](http://web.archive.org/web/20100615004036/http://firebirdsql.org/dotnetfirebird/) seems to have the same issue, but the .net Integration seems to be not really first-class and is largely undocumented. [Blackfish SQL](http://web.archive.org/web/20150510070451/http://www.codegear.com/products/blackfish) looks interesting, but there is no trial of the .net Version. Pricing is also OK. Any other suggestions of something that works well with .net **and** runs off a network without the need of actually installing a server software?
Check out [VistaDB](http://www.gibraltarsoftware.com/VistaDB). They have a very good product, the server version (3.4) is in Beta and is very close to release.
Have you considered an OODB? From the various open sources alternatives I recommend [db4o](http://www.db4o.com) (sorry for the self promotion :)) which can run either embedded or in client/server mode. Best Adriano
If I am in a directory called /usr/share/tcl8.3/encoding, what command would copy all files begining "cp" that also contain an even number (from the following list): ``` cp1250.enc cp1255.enc cp737.enc cp857.enc cp864.enc cp932.enc cp1251.enc cp1256.enc cp775.enc cp860.enc cp865.enc cp936.enc cp1252.enc cp1257.enc cp850.enc cp861.enc cp866.enc cp949.enc cp1253.enc cp1258.enc cp852.enc cp862.enc cp869.enc cp950.enc cp1254.enc cp437.enc cp855.enc cp863.enc cp874.enc ```
Have you tried this? ``` cp cp*[24680].enc destination ```
### Command ``` find . -maxdepth 1 | grep -P "/cp\d*[02468]\.enc$" | xargs -I '{}' cp '{}' destination ``` ### How it works * `find . -maxdepth 1` non-recursively (`-maxdepth 1`) lists all files in the current directory (`.`) * `grep -P "..."` matches each line against the [regular expression](http://www.regular-expressions.info/) `...` + `/` and `\.enc` are the strings `/` and `.enc`. + `\d*` is any number of digits. + `[02468]` is exactly one even digit. + `$` signals the end of a line. * `xargs -I '{}' cp '{}' destination` executes the command ``` cp '{}' destination ``` where `'{}'` gets substituted by each line piped from the previous command.
I open file with notepad, write there: "ą" save and close. I try to read this file in two ways First: ``` InputStream inputStream = Files.newInputStream(Paths.get("file.txt")); int result = inputStream.read(); System.out.println(result); System.out.println((char) result); ``` > > 196 > Ä > > > Second: ``` InputStream inputStream = Files.newInputStream(Paths.get("file.txt")); Reader reader = new InputStreamReader(inputStream); int result = reader.read(); System.out.println(result); System.out.println((char) result); ``` > > 261 > ą > > > **Questions:** 1) In binary mode, this letter is saved as 196? Why not as 261? 2) This letter is saved as 196 in which encoding? I try to understand why there are differences
Because you read these two letters in different encodings, you can check your encoding via `InputStreamReader::getEncoding`. ``` String s = "ą"; char iso_8859_1 = new String(s.getBytes(), "iso-8859-1").charAt(0); char utf_8 = new String(s.getBytes(), "utf-8").charAt(0); System.out.println((int) iso_8859_1 + " " + iso_8859_1); System.out.println((int) utf_8 + " " + utf_8); ``` The output is ``` 196 Ä 261 ą ```
Try using an `InputStreamReader` with UTF-8 encoding, which matches the encoding used to write the file from Notepad++: ``` // this will use UTF-8 encoding by default BufferedReader in = Files.newBufferedReader(Paths.get("file.txt")); String str; if ((str = in.readLine()) != null) { System.out.println(str); } in.close(); ``` I don't have an exact/reproducible answer for why you are seeing the output you see, but if you are reading with the wrong encoding, you won't necessarily see what you saved. For example, if the single character `ą` were encoded with two bytes, but you read as ASCII, then you might get back two characters, which would not match your original file.
``` myList = [[0, 0, 0], #0 [6.888437030500963, 5.159088058806049, -1.5885683833831], #1 [2.0667720363602307, 5.384582486178219, -3.4898856343748133], #2 [7.742743817055683, 1.4508370077567676,-3.957946551327696],#3 [9.410384606156306, 9.613094711663472, -3.864209434979891],#4 [5.047141494150383, 14.72917879480795, -1.4968295014732576],#5 [0.05726832139919402,22.924103914172754, 8.158880019279806],#6 [6.261613041330982, 30.96742292296441,4.361831405666459], #7 [10.858248006533554, 38.94418868232428, 8.041510043975286],#8 [10.30110231558782, 30.958212843691598, 6.724946753050958],#9 [12.518841784463852,39.21843390844956, 16.057074108466132]]#10 import math def distance (myList): dist = math.sqrt ((xa-xb)**2 + (ya-yb)**2 + (za-zb)**2) return dist print("Distance:",(distance(myList))) ``` How can I calculate the distance of all that points but without NumPy? I understand how to do it with 2 but not with more than 2
We can find the euclidian distance with the equation: d = sqrt((px1 - px2)^2 + (py1 - py2)^2 + (pz1 - pz2)^2) Implementing in python: ``` import math def dist(list): cummulativeDist = 0 # iterate over sets of points for i in range(len(list) - 1): coordInit = list[i] coordFinal = list[i+1] # distance from one pt to the next dist = math.sqrt(((coordInit[0] - coordFinal[0]) ** 2) + ((coordInit[1] - coordFinal[2]) ** 2) + ((coordInit[2] - coordFinal[2]) ** 2)) cummulativeDist += dist return cummulativeDist print(f"Distance: {dist(myList)}") ``` This will take the 3 dimensional distance and from one point to the next and return the total distance traveled.
``` import math def distance (myList): distlist=[] for a in myList: for b in myList: dist = math.sqrt ((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2) distlist.append(dist) return distlist print("Distance:",(distance(myList))) ``` You have to append each result to a list you previously generated or you will store only the last value
I just noticed that some of my new Delphi controls get installed in the Public Documents folder in windows 7 (TMS Smooth controls and Virtual Treeview). Is there a reason for this, is this a convention or a few way of doing things or something that the operating system does. Is there a place where I can set the root of my Source control to so that it integrates with RAD studio and windows 7 easier?
As for your "root of source control", Windows 7 does not require that you put it in any particular place, although some people may prefer to hold their source code in their user home folder (C:\Users[Your User Name]), I personally prefer to use something SHORT, like C:\DEV and this works great for me.
Its really a matter of taste...just be wary of storing lots of data in your user directory... especially if your using roaming profiles, as this data will get shipped around to each machine you login to (and maintain a copy on the network). Good for backups, bad for login/logout times. Since your using source control, for your projects, your better off creating a new directory off the root, and placing the source there. It won't be protected by UAC (other than initial directory creation of the first directory). I tend to create a C:\DEV directory on my machines, and then create subdirectories C:\DEV\3RDPARTY and C:\DEV\SANDBOX, all of my 3rd party components go into subdirectorys in C:\DEV\3RDPARTY and my "default" directory for Delphi points to the sandbox, where I create my "test" projects. If your developing a 3rd party library for public consumption, then your going to want to use something like public documents, but give the user the ability to change the directory to match their preferences.
I am having a hard time declaring a Map using Generics. I'd like to declare a Map with the following properties: * The key is a Class object of any Type T derived from a particular Interface (IFoo) * The value of the Map is another Map whose key is an String and whose value is of the Type T I thought I can do it like this: ``` public static Map<Class<T extends IFoo>, Map<String, T>> valueCache = new HashMap<Class<T extends IFoo>, Map<String, T>>(); ``` I get a syntax error on "extends" If I replace the T Types with wildcards (?) like this it seems to be syntactically correct: ``` public static Map<Class<? extends Typ>, Map<Integer, ?>> valueCache= new HashMap<Class<? extends Typ>, Map<Integer, ?>>(); ``` But I don't think this is what I want since I want to be exactly the type of the Class object to be the value in the second map. Any help appreciated.
Move the extends into your class's generic definition: ``` public class ClassWithGeneric<T extends IFoo> { Map<Class<T>, Map<String, T>> valueCache = new HashMap<Class<T>, Map<String, T>>(); } ```
since you Declaring a Map you should Specify all types it helps a lot and should be always Correct so it should be like T should be a type and not Generic since you declare it so java wants to know the type in the newer Versions of java you dont need to declare the second <> generics so i dont know the second type of your inner map so i used Object ``` public static Map<IFoo,Map<String,Object>valueChache=new Hashmap<>(); ``` Both should be Correct ``` public static Map<IFoo,Map<String,Object>valueChache=new Hashmap<IFoo,Map<String,Object>(); ```
I created my project in react native by CLI: ``` _npm install -g create-react-native-app _create-react-native-app AwesomeProject _cd AwesomeProject _npm start ``` Then I installed `expo` in my Android phone, and scanned a QR code on my computer screen. However, my phone can't connect to project, and I don't know why. It just loads and fails. This is error message: > > Could not load exp:// 192.168.56.1:19000. Network response timed out. > > > This is view error: > > "Uncaught Error: java,not.SocketTimeoutException: faild to connect to/192.168.56.1 (port 19000) after 10000 ms. > > > I'm trying to fix it, but still can't get it working. My phone and my laptop are on the same network. What can I do now?
If you are using windows 10 do the following. It worked for me ``` 1. Check if your phone and pc are sharing the same router/hotspot/wifi connection. better still you can connect your pc to your phone hotspot. 2. Configure the network you are using as private. you can do so using this link https://www.digitalcitizen.life/how-set-your-networks-location-private-or-public-windows-10/ 3. Off your windows defender and any other antivirus. The windows and other antivirus defender acts as a firewall and prevents expo client from working. It will work I assure you ```
I was having the same issue, the solution is easy just make a **Firewall rule** that allows connection from your mobile device to your PC. open **port number 19000** and in the IP put your phone IP address then allow the connection **TCP/UDP** in both directions, and everything will be OK. Usually, you can edit the Firewall rules through your antivirus installed on your PC. **Careful don't disable your firewall, it will hurt you a lot.**