date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/17
602
2,308
<issue_start>username_0: So in my class I want to select a function to use as my activation function as an argument. Currently I do this through ``` class NeuralNetworks: def __init(self, n_inputs, layer_vector, func='sig'): (...) self.func = func def sigmoid(self, x): (...) def reLu(self, x): (...) def propagate(...): (...) if self.func == 'sig': (...) else: (...) (...) if self.func == 'sig': (...) else: (...) (and so on...) ``` All the if/else statements end up making the code pretty verbose, is there a neater way to select the function?<issue_comment>username_1: Make sure you're using Facebook SDK 5.6.2. There was an important fix. Upvotes: 0 <issue_comment>username_2: Facebook announced in Dec 2017 that in March 2018 they would change the settings for Oauth redirects: <https://developers.facebook.com/blog/post/2017/12/18/strict-uri-matching/> In a nutshell, you can only redirect to explicit, precise pre-determined URIs now. Which is annoying if (like me) you want to pass URI parameters back as well... Upvotes: 3 [selected_answer]<issue_comment>username_3: Since this March (started running a couple of days ago), [strict mode is now enabled by default](https://developers.facebook.com/blog/post/2017/12/18/strict-uri-matching/). This means you now need to have the exact redirect URLs you're using marked as such in the app configuration. You can see more [here](https://developers.facebook.com/docs/facebook-login/security#strict_mode) about what this entails and how to get on with the change. Further, you **need** to update your dependency to version 5.6.2, as there's a bug in the previous version that wouldn't work with strict URI matching (yes, the one that is now enabled by default), so the login would break. You can see more about the fix [in the pull request that fixed it](https://github.com/facebook/php-graph-sdk/pull/913). I can confirm that updating to 5.6.2 (PHP) fixed the issue. To update your version in PHP, it depends on which expression you have in your `composer.json`, but if you have `"facebook/graph-sdk": "^5.6"`, for example, a simple `composer update` will suffice. Upvotes: 0
2018/03/17
613
2,113
<issue_start>username_0: Assume that I have a matrix `A = rand(n,m)`. I want to compute matrix B with size n x n x m, where `B(:,:,i) = A(:,i)*A(:,i)';` The code that can produce this is quite simple: ``` A = rand(n,m); B = zeros(n,n,m); for i=1:m B(:,:,i) = A(:,i)*A(:,i)' end ``` However, I am concerned about speed and would like to ask you help to tell me how to implement it without using loops. Very likely that I need to use either `bsxfun`, `arrayfun` or `rowfun`, but I am not sure. All answers are appreciated.<issue_comment>username_1: Make sure you're using Facebook SDK 5.6.2. There was an important fix. Upvotes: 0 <issue_comment>username_2: Facebook announced in Dec 2017 that in March 2018 they would change the settings for Oauth redirects: <https://developers.facebook.com/blog/post/2017/12/18/strict-uri-matching/> In a nutshell, you can only redirect to explicit, precise pre-determined URIs now. Which is annoying if (like me) you want to pass URI parameters back as well... Upvotes: 3 [selected_answer]<issue_comment>username_3: Since this March (started running a couple of days ago), [strict mode is now enabled by default](https://developers.facebook.com/blog/post/2017/12/18/strict-uri-matching/). This means you now need to have the exact redirect URLs you're using marked as such in the app configuration. You can see more [here](https://developers.facebook.com/docs/facebook-login/security#strict_mode) about what this entails and how to get on with the change. Further, you **need** to update your dependency to version 5.6.2, as there's a bug in the previous version that wouldn't work with strict URI matching (yes, the one that is now enabled by default), so the login would break. You can see more about the fix [in the pull request that fixed it](https://github.com/facebook/php-graph-sdk/pull/913). I can confirm that updating to 5.6.2 (PHP) fixed the issue. To update your version in PHP, it depends on which expression you have in your `composer.json`, but if you have `"facebook/graph-sdk": "^5.6"`, for example, a simple `composer update` will suffice. Upvotes: 0
2018/03/17
326
1,049
<issue_start>username_0: ``` @IBAction func endEditingText(_ sender: Any) { let baseURL = "http://api.openweathermap.org/data/2.5/forecast?q" let APIKeysString = "&appid=14b92e1046c4b6e4f4d5adda8259131b" guard let cityString = sender.text else {return} if let finalURL = URL (string:baseURL + cityString + APIKeysString) { requestWeatherDate(url: finalURL) } else { print("error") } } ```<issue_comment>username_1: The error is pretty clear. The `sender` is declared as `Any` so the compiler does not know the actual static type. Change it to `UITextField`: ``` @IBAction func endEditingText(_ sender: UITextField) { ... ``` Upvotes: 2 <issue_comment>username_2: You can type cast sender to UITextField. ``` @IBAction func endEditingText(_ sender: Any) { let textFieldObject = sender as! UITextField .... } ``` or at the time of creating IBAction you can use UITextField in place of Any. ``` @IBAction func endEditingText(_ sender: UITextField) { .... } ``` Upvotes: 3 [selected_answer]
2018/03/17
291
902
<issue_start>username_0: I need to write a function in pandas which gets two series as arguments: one is the grades of several students, another is their gender. As a return I need to get a dictionary with keys "male" or "female" and values which are the means of the grades over gender... As an example,if ``` grades = pd.Series([5, 4, 3, 5, 2]) ``` and ``` genders = pd.Series(["female", "male", "male", "female", "male"]) ``` the function must return a dictionary ``` {'male': 3.0, 'female': 5.0} ``` I know that I may create a data frame with columns which are these two series and then use groupby and to\_dict() but have no idea how..<issue_comment>username_1: Use ``` grades.groupby(genders).mean().to_dict() ``` Upvotes: 2 <issue_comment>username_2: Use ``` In [96]: grades.groupby(genders).mean().to_dict() Out[96]: {'female': 5L, 'male': 3L} ``` Upvotes: 2 [selected_answer]
2018/03/17
419
1,546
<issue_start>username_0: It's been a pain to type code in eclipse, sublime text makes everything much more easy. I can't seem to find anything. I can only find "How to add eclipse-like key bindings for sublime". I doesn't seem possible can anyone help?<issue_comment>username_1: `Eclipse` doesn't provide all the same features as `sublimetext`, so you might not be able to map everything you want. There are, however, a couple of things you might try: * [eclipse-multicursor](https://github.com/caspark/eclipse-multicursor): A (somehow) abandoned plugin. From the project: > > implemented under the covers by using Eclipse linked mode editing (similar to existing "rename in file" functionality), so you can't move the cursors outside the initial selection areas, and all multiple-cursor-edited-text must be the same string. > > > * `alt` + `shift/cmd` + `A` to *Toggle block selection* * Create a key-binding configuration, according to [the docs](https://wiki.eclipse.org/FAQ_How_do_I_create_my_own_key-binding_configuration%3F), setting o whatever you are used to. Upvotes: 1 <issue_comment>username_2: Use [IntelliJ IDEA](https://www.jetbrains.com/idea/) IDE instead. I have been using this IDE for over 2 years, before that around 4 years on Eclipse. You can change your key-map to various options already exist there. Even you can multi-mix various keytabs to make your own, say mixture of Eclipse and sublime. Here is the full guide for migrating: [Eclipse to Intellij](https://www.jetbrains.com/help/idea/eclipse.html) Upvotes: 0
2018/03/17
417
1,533
<issue_start>username_0: In my Ionic 3 application, I want to submit a form when I click on the **go button** from my mobile keyboard. I want to trigger an event or call a function when I click on the **go button** on my mobile keyboard.<issue_comment>username_1: `Eclipse` doesn't provide all the same features as `sublimetext`, so you might not be able to map everything you want. There are, however, a couple of things you might try: * [eclipse-multicursor](https://github.com/caspark/eclipse-multicursor): A (somehow) abandoned plugin. From the project: > > implemented under the covers by using Eclipse linked mode editing (similar to existing "rename in file" functionality), so you can't move the cursors outside the initial selection areas, and all multiple-cursor-edited-text must be the same string. > > > * `alt` + `shift/cmd` + `A` to *Toggle block selection* * Create a key-binding configuration, according to [the docs](https://wiki.eclipse.org/FAQ_How_do_I_create_my_own_key-binding_configuration%3F), setting o whatever you are used to. Upvotes: 1 <issue_comment>username_2: Use [IntelliJ IDEA](https://www.jetbrains.com/idea/) IDE instead. I have been using this IDE for over 2 years, before that around 4 years on Eclipse. You can change your key-map to various options already exist there. Even you can multi-mix various keytabs to make your own, say mixture of Eclipse and sublime. Here is the full guide for migrating: [Eclipse to Intellij](https://www.jetbrains.com/help/idea/eclipse.html) Upvotes: 0
2018/03/17
437
1,563
<issue_start>username_0: Prestashop 1.6 has some strange functions. One of them is: ``` \themes\my_theme\js\autoload\15-jquery.uniform-modified.js ``` Which add span to radio, input button. For example: ``` ``` If this span has class checked then checkbox is checked. the problem is when quest user want buy products without create a account. The user need to provide some information about his self. In the end click on "save" button ``` Zapisz ``` When I click this button the html is change to: ``` ``` the question is. How can I call function which add span to input field after click on this button. For now I have something like this: ``` $('#submitGuestAccount').click(function () { }); ``` Below I past all content from: [view-source:https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js](https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js) Thanks for any help.<issue_comment>username_1: If you want to get the same checkbox like with uniform you just need to invoke method bindUniform() after your button was handled. I assume that you get an answer after form handling with an ajax response, so you need to add `if (typeof bindUniform !=='undefined') { bindUniform(); }` after you get response and DOM was done. Upvotes: 2 [selected_answer]<issue_comment>username_2: @username_1 Thanks again. To fix this issues You need to add this code to any js file. ``` $("select.form-control,input[type='radio'],input[type='checkbox']").uniform(); ``` Upvotes: 0
2018/03/17
1,864
7,285
<issue_start>username_0: I have the following code in ASP.Net Generic handler to download the file. ``` // generate you file // set FilePath and FileName variables string stFile = FilePath + FileName; try { response.Clear(); response.ContentType = "application/pdf"; response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); response.TransmitFile(stFile); } catch (Exception ex) { // any error handling mechanism } finally { response.End(); } ``` it works fine with local path - like "D:\Files\Sample.pdf" or "\localserver\Files\Sample.pdf". but it throws and access denied error while trying to access the Network file share like "\anotherServer\Files\Sample.pdf". Does it related to double hopping? If can I use spsecurity.runwithelevatedprivileges to fix this issue? or what are the other options? As per this article <https://weblogs.asp.net/owscott/iis-windows-authentication-and-the-double-hop-issue> it seems to be a double hopping issue. How do I address this? All I want is that end user should be able to download remote resources by using asp.net generic handler.<issue_comment>username_1: You need to provide the file permissions through and once your work is done you need to revoke them. better to use try finally block in finally block you can revoke permissions For file permissions example you can find in [MSDN Link](https://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol(v=vs.110).aspx) File name should not contain spaces because it will corrupt download in mozilla browser Upvotes: 0 <issue_comment>username_2: I have to deal with something similar once and to get this to work by mapping network share to specific drive. Solution to add credentials to your network share before trying to access it didn't work (but you can try it as a first attempt) ``` NetworkCredential nc = new NetworkCredential("", ""); CredentialCache cache = new CredentialCache(); cache.Add(new Uri(""), "Basic", nc); ``` If this doesn't work use the combined solution with mapping network share to drive. Use class `NetworkDrive` to make WinApi calls to `WNetAddConnection2` and `WNetCancelConnection2`: ``` public class NetworkDrive { public enum ResourceScope { RESOURCE_CONNECTED = 1, RESOURCE_GLOBALNET, RESOURCE_REMEMBERED, RESOURCE_RECENT, RESOURCE_CONTEXT } public enum ResourceType { RESOURCETYPE_ANY, RESOURCETYPE_DISK, RESOURCETYPE_PRINT, RESOURCETYPE_RESERVED } public enum ResourceUsage { RESOURCEUSAGE_CONNECTABLE = 0x00000001, RESOURCEUSAGE_CONTAINER = 0x00000002, RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004, RESOURCEUSAGE_SIBLING = 0x00000008, RESOURCEUSAGE_ATTACHED = 0x00000010, RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED), } public enum ResourceDisplayType { RESOURCEDISPLAYTYPE_GENERIC, RESOURCEDISPLAYTYPE_DOMAIN, RESOURCEDISPLAYTYPE_SERVER, RESOURCEDISPLAYTYPE_SHARE, RESOURCEDISPLAYTYPE_FILE, RESOURCEDISPLAYTYPE_GROUP, RESOURCEDISPLAYTYPE_NETWORK, RESOURCEDISPLAYTYPE_ROOT, RESOURCEDISPLAYTYPE_SHAREADMIN, RESOURCEDISPLAYTYPE_DIRECTORY, RESOURCEDISPLAYTYPE_TREE, RESOURCEDISPLAYTYPE_NDSCONTAINER } [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public ResourceScope dwScope = 0; public ResourceType dwType = 0; public ResourceDisplayType dwDisplayType = 0; public ResourceUsage dwUsage = 0; public string lpLocalName = null; public string lpRemoteName = null; public string lpComment = null; public string lpProvider = null; } [DllImport("mpr.dll")] private static extern int WNetAddConnection2(NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags); [DllImport("mpr.dll")] static extern int WNetCancelConnection2(string lpName, Int32 dwFlags, bool bForce); private const int CONNECT_UPDATE_PROFILE = 0x1; private const int NO_ERROR = 0; public int MapNetworkDrive(string unc, string drive, string user, string password) { NETRESOURCE myNetResource = new NETRESOURCE(); myNetResource.lpLocalName = drive; myNetResource.lpRemoteName = unc; myNetResource.lpProvider = null; int result = WNetAddConnection2(myNetResource, password, user, 0); if (result == 0) return result; else throw new Win32Exception(Marshal.GetLastWin32Error()); } public int UnmapNetworkDrive(string drive) { int result = WNetCancelConnection2(drive, CONNECT_UPDATE_PROFILE, true); if (result != NO_ERROR) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return result; } } ``` And use it like this: ``` NetworkDrive nd = new NetworkDrive(); try { if (nd.MapNetworkDrive("", "Z:", "", "") == 0) { NetworkCredential nc = new NetworkCredential("", ""); CredentialCache cache = new CredentialCache(); cache.Add(new Uri(""), "Basic", nc); // access network share using UNC path (not your drive letter) } } finally { nd.UnmapNetworkDrive("Z:"); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: I ran into the same problem before, your code seems fine to me, what you need to check is the security and file permissions. let's say that your handler is hosted under IIS, your application pool identity have to be set to a domain user, to run IIS process with that user's privileges. so you have to give permission for that user to read/write the content of your Shared folder. I normally do that to access the database and SAN storage for simple apps. Upvotes: 0 <issue_comment>username_4: If you are using the default generated IIS app pool identity, your worker process will attempt to access network resources as the domain-registered machine account (Example: yourdomain\machinename$). More details about how IIS operates in these situations can be found [here](https://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities). As long as the server you are attempting to access is on the same domain, you just need to set both the "Share" permissions and the NTFS permissions (under Security for the shared folder) to allow this domain machine account to access the share. NOTE: Machine accounts are not listed by default when selecting an account in the Security dialogue- you need to click "Object Types" when in the "Select Users and Groups" dialogue and add "Computers". More details about how IIS operates in these situations can be found [here](https://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities). Upvotes: 0 <issue_comment>username_5: In my case it (finally) worked adding this line in the download procedure: Response.AddHeader("Transfer-Encoding", "identity"); In my web application i also did this: * i download files using UNC path * i impersonated the web application to work under my user, i am admin * i also set for the app's pool my user Upvotes: 0
2018/03/17
1,498
4,751
<issue_start>username_0: I want to retrieve the customers who have made a total of at least 2 transactions based on three columns. Y - Successful Transaction EX: ``` Customer_Name Col1 Col2 Col3 Customer1 Y Y N Customer2 N N Y Customer3 Y Y N ``` For the above table, I want to show as below output(Want to exclude the customer who did only one transaction) ``` Customer1 - 2 Customer3 - 2 ```<issue_comment>username_1: You can combine SUM() and HAVING() clause. ``` SELECT Customer_Name, SUM(CASE WHEN Col1='Y' then 1 else 0 end)+ SUM(CASE WHEN Col2='Y' then 1 else 0 end)+ SUM(CASE WHEN Col3='Y' then 1 else 0 end) as total FROM myTable GROUP BY Customer_Name HAVING SUM(CASE WHEN Col1='Y' then 1 else 0 end)+ SUM(CASE WHEN Col2='Y' then 1 else 0 end)+ SUM(CASE WHEN Col3='Y' then 1 else 0 end)=2 Result: CUSTOMER_NAME TOTAL Customer3 2 Customer1 2 ``` Upvotes: 0 <issue_comment>username_2: Somewhat similar to @anonyXmous' code, but using DECODE and not that many (unnecessary?) SUMs: ``` SQL> with test (cname, col1, col2, col3) as 2 (select 'cust1', 'y', 'y', 'n' from dual union 3 select 'cust2', 'n', 'n', 'y' from dual union 4 select 'cust3', 'y', 'n', 'y' from dual 5 ) 6 select cname, 7 sum(decode(col1, 'y', 1, 0) + 8 decode(col2, 'y', 1, 0) + 9 decode(col3, 'y', 1, 0)) sumc 10 from test 11 group by cname 12 having sum(decode(col1, 'y', 1, 0) + 13 decode(col2, 'y', 1, 0) + 14 decode(col3, 'y', 1, 0)) >= 2 15 order by cname; CNAME SUMC ----- ---------- cust1 2 cust3 2 SQL> ``` Upvotes: 0 <issue_comment>username_3: I see that two individuals answered your question using aggregate examples. As in they are both using GROUP BY and the HAVING Clause. You don't necessarily need to use any sort of Grouping to get your desired output here. See below an alternate solution. It may be simply an opinion however I prefer this solution: ``` WITH demo_data (cname, col1, col2, col3) AS ( /* Using CTE to produce fake table with data */ SELECT 'cust1', 'Y', 'Y', 'N' FROM dual UNION ALL SELECT 'cust2', 'N', 'N', 'Y' FROM dual UNION ALL SELECT 'cust3', 'Y', 'N', 'Y' FROM dual UNION ALL SELECT 'cust4', 'Y', 'Y', 'Y' FROM dual UNION ALL SELECT 'cust5', 'Y', 'Y', 'N' FROM dual UNION ALL SELECT 'cust6', 'Y', 'N', 'N' FROM dual ) , transform_data AS ( /* Using decode to convert all 'Y' and 'N' to numbers */ SELECT cname , decode(col1, 'Y', 1, 0) AS col1 , decode(col2, 'Y', 1, 0) AS col2 , decode(col3, 'Y', 1, 0) AS col3 FROM demo_data ) /* Now we created our SUM column using the columns 1 thru 3 */ SELECT cname, col1, col2, col3 /* I didn't need to create the sum_col however I added it for visual purposes */ , col1 + col2 + col3 AS sum_col FROM transform_data WHERE col1 + col2 + col3 > 1 ; ``` Screenshot of the output for each of the tables produced by the WITH Clause and actual desired Output. [![enter image description here](https://i.stack.imgur.com/QdYLG.png)](https://i.stack.imgur.com/QdYLG.png) Upvotes: 1 <issue_comment>username_4: From what you are showing it seems: * You have a table with three boolean columns. As the Oracle DBMS still doesn't feature the boolean data type, you used `col1 CHAR(1) NOT NULL, CONSTRAINT chk_customers_bool_col1 CHECK (col1 in ('Y','N'))` etc. instead. (A pity that Oracle forces us to apply such workarounds.) * You are showing a customer table with one record per customer and three attributes, that you call `col1`, `col2`, `col3` in your example, but which are real attributes in real life, such as `quick`, `friendly`, `rich`, and you want to select customers for which at least two of the attributes are true. One simple way to do this would be to concatenate the three letters, remove the Ns and count the remaining Ys. ``` select Customer_Name, length(replace(col1 || col2 ||| col3 ,'N','')) from customers where length(replace(col1 || col2 ||| col3 ,'N','')) >= 2; ``` This query still works for three-state booleans (i.e. null allowed), but not if the columns can contain other charaters (such as 'M' for "maybe" or 'S' for "sometimes"). In that case you'd have to use a `CASE` expression or Oracle's `DECODE` to check for Ys. --- Many people prefer the numbers 0 and 1 to emulate boolean false and true in Oracle. One advantage over 'N' and 'Y' is that you can quickly add them up to count how many are true, which is exactly your case. (In MySQL where a boolean data type exists, they even go so far as to allow math with them substituting false with 0 and true with 1, so true + false + true = 2.) Upvotes: 0
2018/03/17
632
2,093
<issue_start>username_0: I have a Javascript Web application. I trying to read or write to the Cloud Firestore database but it returns this error in the browser console. **THE ERROR:** > > Failed to load <https://firestore.googleapis.com/google.firestore.v1beta1.Firestore/Write/channel?VER=8&RID=21505&CVER=21&X-HTTP-Session-Id=gsessionid&%24httpHeaders=X-Goog-Api-Client%3Agl-js%2F%20fire%2F4.8.2%0D%0Agoogle-cloud-resource-prefix%3Aprojects%2FProjectName%2Fdatabases%2F(default)%0D%0A&zx=v9xcdtq156tr&t=1>: > > The 'Access-Control-Allow-Origin' header has a value 'null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access. > > > The Security Rules were set to **Public read/write** ``` service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write; } } } ``` Here is my test code ``` var config = { apiKey: "<KEY>", authDomain: "XXXXXXXXXXXX", databaseURL: "XXXXXXXXXXXX", projectId: "XXXXXXXXXXXX", storageBucket: "XXXXXXXXXXXX", messagingSenderId: "XXXXXXXXXXXX" }; firebase.initializeApp(config); // Firebase Variables var db = firebase.firestore(); db.collection("cities").doc("LA").set({ name: "Los Angeles", state: "CA", country: "USA" }).then(function () { console.log("Document successfully written!"); }).catch(function (error) { console.error("Error writing document: ", error); }); ```<issue_comment>username_1: Google Chrome Version 65.0.3325.162 is the problem. Tested with Microsoft Edge and it worked Upvotes: 3 <issue_comment>username_2: Based on the CORS error it seems to be you are running the test code without using any kind of development server (e.g. [Nodemon][1], [webpack-dev-server][2] or [SimpleHTTPServer][3]). In the past, I also got the similar error when open the index.html file directly using a browser without any HTTP server. If you have python installed on your computer, try to run the HTTP server inside the directory where it contains the index HTML file. ``` python -m SimpleHTTPServer 8000 ``` Upvotes: 1
2018/03/17
336
1,251
<issue_start>username_0: When trying to add a new EF Connection to a SQL Server I get this exception: > > Failed to retrieve data for this request. > Method not found: 'Void Microsoft.SqlServer.Management.Sdk.Sfc.EnumResult.set\_CommandElapsedTime(System.TimeSpan) > > > Facts: * "Test Connection" works fine * It does not matter which database I try to connect (tried different sources, on premises and SQL Azure) * It used to work before * Reinstalling EF SDK did not help * The error message appears immediately after clicking "OK" (no delay) Does anybody have an idea how to fix this?<issue_comment>username_1: Google Chrome Version 65.0.3325.162 is the problem. Tested with Microsoft Edge and it worked Upvotes: 3 <issue_comment>username_2: Based on the CORS error it seems to be you are running the test code without using any kind of development server (e.g. [Nodemon][1], [webpack-dev-server][2] or [SimpleHTTPServer][3]). In the past, I also got the similar error when open the index.html file directly using a browser without any HTTP server. If you have python installed on your computer, try to run the HTTP server inside the directory where it contains the index HTML file. ``` python -m SimpleHTTPServer 8000 ``` Upvotes: 1
2018/03/17
937
2,505
<issue_start>username_0: This is the image: [![tax invoice](https://i.stack.imgur.com/RPxcb.jpg)](https://i.stack.imgur.com/RPxcb.jpg) I have to use echo inside a `td` element of an HTML table. When I am trying this, it is showing an angle bracket error. How can I avoid that error? Below is my code. ``` | Net Amount | **'.$order\_data['net\_amount'].'** | | $number = $order\_data['net\_amount']; $no = round($number); $point = round($number - $no, 2) \* 100; $hundred = null; $digits\_1 = strlen($no); $i = 0; $str = array(); $words = array('0' => '', '1' => 'One', '2' => 'Two', '3' => 'Three', '4' => 'Four', '5' => 'Five', '6' => 'Six', '7' => 'Seven', '8' => 'Eight', '9' => 'Nine', '10' => 'Ten', '11' => 'Eleven', '12' => 'Twelve','13' => 'Thirteen', '14' => 'Fourteen', '15' => 'Fifteen', '16' => 'Sixteen', '17' => 'Seventeen','18' => 'Eighteen', '19' =>'Nineteen', '20' => 'Twenty','30' => 'Thirty', '40' => 'Forty', '50' => 'Fifty','60' => 'Sixty', '70' => 'Seventy', '80' => 'Eighty', '90' => 'Ninety'); $digits = array('', 'Hundred', 'Thousand', 'Lakh', 'Crore'); while ($i < $digits\_1) { $divider = ($i == 2) ? 10 : 100; $number = floor($no % $divider); $no = floor($no / $divider); $i += ($divider == 10) ? 1 : 2; if ($number) { $plural = (($counter = count($str)) && $number > 9) ? 's' : null; $hundred = ($counter == 1 && $str[0]) ? ' and ' : null; $str [] = ($number < 21) ? $words[$number] . " " . $digits[$counter] . $plural . " " . $hundred : $words[floor($number / 10) \* 10] . " " . $words[$number % 10] . " " . $digits[$counter] . $plural . " " . $hundred; } else $str[] = null; } $str = array\_reverse($str); $result = implode('', $str); $points = ($point) ? "." . $words[$point / 10] . " " . $words[$point = $point % 10] : ''; echo ' INR '.$result.' '.$points.'Only |'; ```<issue_comment>username_1: Google Chrome Version 65.0.3325.162 is the problem. Tested with Microsoft Edge and it worked Upvotes: 3 <issue_comment>username_2: Based on the CORS error it seems to be you are running the test code without using any kind of development server (e.g. [Nodemon][1], [webpack-dev-server][2] or [SimpleHTTPServer][3]). In the past, I also got the similar error when open the index.html file directly using a browser without any HTTP server. If you have python installed on your computer, try to run the HTTP server inside the directory where it contains the index HTML file. ``` python -m SimpleHTTPServer 8000 ``` Upvotes: 1
2018/03/17
296
1,128
<issue_start>username_0: How to implement an `onItemClickListener()` on a custom `listView` in kotlin?\_ ``` title_list_view.setOnItemClickListener{ adapterView: AdapterView<*>?, view: View?, position: Int, l: Long -> } ``` what to do to start a new activity after clicking an item of a Custom `ListView`?<issue_comment>username_1: Try this ``` title_list_view.setOnItemClickListener { parent, view, position, id -> Toast.makeText(this, "Clicked item :"+" "+position,Toast.LENGTH_SHORT).show() Intent intent = new Intent(CurrentActivity.this, NextActivity.class); intent.putExtra("position", position); this.startActivity(intent); } ``` Upvotes: 4 <issue_comment>username_2: You are using kotlin right? use **NextActivity::class.java** in Intent ``` title_list_view.setOnItemClickListener { parent, view, position, id -> Toast.makeText(this, "Clicked item : $position",Toast.LENGTH_SHORT).show() Intent intent = new Intent(CurrentActivity.this, NextActivity::class.java) intent.putExtra("position", position) this.startActivity(intent) } ``` Upvotes: 1
2018/03/17
674
2,629
<issue_start>username_0: I have a question about default arguments in c++. If I a have a function like this: ``` int foo(int* obj = new Int(4)) { /* Stuff with obj. */ } ``` Now, of course, the integer is here just used as an example, but the question is if I were to provide a value for the argument like this: ``` int x = 2; foo(&x); ``` will the expression `obj = new Int(4)` still be evaluated even though I provided a value for the argument and therefore allocated memory which I then can't read from anymore?<issue_comment>username_1: No, default arguments are only used when there is no argument passed to them. `new` won't be invoked and thus there will be no memory allocation. Also, as Some programmer dude said you have a memory leak if you do not clean up at some point either inside (or outside) the function body. Upvotes: 3 [selected_answer]<issue_comment>username_2: Using a `new` expression as a default value for an argument, as in ``` int foo(int *obj = new int(4)); ``` is an extremely bad idea, since there are possible use cases that behave inconsistently with each other, and a number of bad possible outcomes. Let's say, for sake of discussion that the implementation of `foo()` does ``` delete obj; ``` That is okay if the caller does either of ``` foo(); // default argument is a new expression foo(new int(2)); ``` but causes undefined behaviour if the caller does one or more of; ``` foo(&some_int); // some_int is a variable local to the caller foo(new int[2]); // dynamically allocates an array ``` Conversely, let's say that `foo()` does NOT do `delete obj`. In this case, either of these statements ``` foo(); foo(new int(3)); foo(new int [2]); // dynamically allocates an array ``` cause a memory leak, and ``` foo(&some_int); ``` will probably work correctly (assuming `foo()` does not invoke undefined behaviour in other ways). The real problem is that `foo()` has no way (within bounds of standard C++) of detecting which of the above the caller does. So there is a real risk of either undefined behaviour or a memory leak, unless the caller does EXACTLY the "right thing" (where "right thing" means not causing a memory leak or undefined behaviour). And, since there are more options to do the wrong thing, odds are the caller will NOT do exactly the right thing. Bear in mind that programmers are notoriously terrible at reading documentation, so relying on documentation is a poor way to ensure the caller (or the programmer writing code in the caller) does what is needed to avoid problems like the above. Upvotes: 2
2018/03/17
666
2,563
<issue_start>username_0: I tried so many ways but could not find a way to add at least four paths to the Firestore. My JSON tree is as follows: `ActiveTrades -> Userid -> autogeneratedId -> data fields` I've tried as follows: ``` var ref = firebase.firestore(); var addOrder = ref.collection("ActiveTrades").doc(userId).add({ orderId: 1234 }); var ref = firebase.firestore(); var addOrder = ref.doc("ActiveTrades/"+userid).add({ orderId: 1234 }); ```<issue_comment>username_1: No, default arguments are only used when there is no argument passed to them. `new` won't be invoked and thus there will be no memory allocation. Also, as Some programmer dude said you have a memory leak if you do not clean up at some point either inside (or outside) the function body. Upvotes: 3 [selected_answer]<issue_comment>username_2: Using a `new` expression as a default value for an argument, as in ``` int foo(int *obj = new int(4)); ``` is an extremely bad idea, since there are possible use cases that behave inconsistently with each other, and a number of bad possible outcomes. Let's say, for sake of discussion that the implementation of `foo()` does ``` delete obj; ``` That is okay if the caller does either of ``` foo(); // default argument is a new expression foo(new int(2)); ``` but causes undefined behaviour if the caller does one or more of; ``` foo(&some_int); // some_int is a variable local to the caller foo(new int[2]); // dynamically allocates an array ``` Conversely, let's say that `foo()` does NOT do `delete obj`. In this case, either of these statements ``` foo(); foo(new int(3)); foo(new int [2]); // dynamically allocates an array ``` cause a memory leak, and ``` foo(&some_int); ``` will probably work correctly (assuming `foo()` does not invoke undefined behaviour in other ways). The real problem is that `foo()` has no way (within bounds of standard C++) of detecting which of the above the caller does. So there is a real risk of either undefined behaviour or a memory leak, unless the caller does EXACTLY the "right thing" (where "right thing" means not causing a memory leak or undefined behaviour). And, since there are more options to do the wrong thing, odds are the caller will NOT do exactly the right thing. Bear in mind that programmers are notoriously terrible at reading documentation, so relying on documentation is a poor way to ensure the caller (or the programmer writing code in the caller) does what is needed to avoid problems like the above. Upvotes: 2
2018/03/17
803
3,530
<issue_start>username_0: Recently I have been following some tutorials on Unity, wanting to get into some game programming. Now, I noticed that the guy in the tutorial does the following to copy a parameter to a variable: ``` private Dictionary inventoryRequirements; public Job ( Dictionary inventoryRequirements) { this.inventoryRequirements = new Dictionary(inventoryRequirements); } ``` and of course this works fine and all but I was just wondering about what the difference is between this and the following: ``` private Dictionary inventoryRequirements; public Job ( Dictionary inventoryRequirements) { this.inventoryRequirements = inventoryRequirements; } ```<issue_comment>username_1: In the first case, you intialize an instance of a dictionary that contains elements copied from the dictionary you pass to the constructor and you make use of the default equality comparer for the key type. For further info please have a look [here](https://msdn.microsoft.com/en-us/library/et0ke8sz(v=vs.110).aspx). Then you assign a reference to the newly created dictionary to the `inventoryRequirements` field. Whereas in the second case you just assign a copy of the reference to the original dictionary to the `inventoryRequirements` field. Upvotes: 2 <issue_comment>username_2: In the first example code snippet, you're cloning the dictionary instance passed in as a parameter using the copy constructor. Whereas the second approach, you're simply assigning the dictionary reference passed in to the current objects dictionary instance. The first approach is an effective way to clone a given dictionary's data. This means when the original dictionary is modified, the copy is not affected. That said, if `Inventory` is a reference type (Which I'd assume it's) then it's important to note that you've cloned the dictionary but if you haven't cloned the `Inventory` values in the dictionary instance, any modifications to the `Inventory` will still be seen through on a given `Job` instance dictionary. Upvotes: 2 [selected_answer]<issue_comment>username_3: Well, to really understand what exactly is going on, let's have a look at a quick code snippet. * [Your first snippet](https://repl.it/repls/FeistyModernRadius) * [Your second snippet](https://repl.it/repls/LateSlightTransformations) Observing the outputs you can see that in the second case, your original dictionary was actually modified, and the value mapped to the key "test" was re-assigned to 0. As you may have figured out, when you use `new Dictionary(inventoryRequirements);` you actually create a *clone* of your original dictionary, so the instantiated class can modify its copy all it wants without affecting your copy. Whereas, when you directly pass the *same* dictionary, any modifications made by the instantiated class will be visible in your class, and you lose control over your dictionary as you've essentially given the instantiated class complete control over it. Now, as a general rule of OOP, you should keep your fields (that aren't required by other classes/objects) to yourself. By that logic, you should pass your object (not a copy) if: 1. You will not need the object again or 2. Your object is very large and can't be cloned reasonably **Keep in mind that the GC will automatically delete your object if it goes out of scope immediately** or 3. The object is a primitive (you'll get a deep copy, so it will already be a clone.) Now, if you don't need any of the above you should probably be passing a copy. Upvotes: 0
2018/03/17
1,727
7,018
<issue_start>username_0: In my activity there's a RecyclerView and a button to add items to the RecyclerView. Each item has two EditTexts. [Here's a Screenshot](https://i.stack.imgur.com/8bL1J.png) When i scroll down and up, the EditTexts get empty. and sometimes the value entered in the EditText changes it's position! How can i solve this problem? Here are the codes: **Adapter :** ``` public class VoltageAdapter extends RecyclerView.Adapter { private List datas = new ArrayList<>(); public List getDatas() { return datas; } @Override public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.item\_voltage, parent, false); return new DataViewHolder(view); } @Override public void onBindViewHolder(DataViewHolder holder, int position) { holder.bindData(datas.get(position)); } @Override public int getItemCount() { return datas.size(); } public static class DataViewHolder extends RecyclerView.ViewHolder { private EditText vOnEditText; private EditText vOffEditText; public DataViewHolder(View itemView) { super(itemView); vOnEditText = itemView.findViewById(R.id.et\_ItemVoltage\_Von); vOffEditText = itemView.findViewById(R.id.et\_ItemVoltage\_Voff); } public void bindData(final Voltage voltage) { vOnEditText.setText(voltage.getVon()); vOffEditText.setText(voltage.getVoff()); vOnEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { voltage.setVon(s.toString()); } @Override public void afterTextChanged(Editable s) { vOnEditText.setSelection(vOnEditText.getText().length()); } }); vOffEditText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { voltage.setVoff(s.toString()); } @Override public void afterTextChanged(Editable s) { } }); } } public void addData(Voltage voltage) { datas.add(voltage); notifyItemInserted(datas.size() - 1); } } ``` **Activity Class :** ``` public class VoltageActivity extends AppCompatActivity { private VoltageAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_voltage); setupViews(); } private void setupViews() { Button calcucalteButton = findViewById(R.id.btn_voltage_calculate); Button addDataButton = findViewById(R.id.btn_voltage_addData); adapter = new VoltageAdapter(); RecyclerView recyclerView = findViewById(R.id.rv_voltage_voltages); recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); recyclerView.setAdapter(adapter); addDataButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Voltage voltage = new Voltage(); adapter.addData(voltage); } }); calcucalteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List datas = adapter.getDatas(); float DeltaVoltages[] = new float[datas.size()]; for (int i = 0; i < datas.size(); i++) { Voltage voltage = datas.get(i); float res = Float.parseFloat(voltage.getVon()) - Float.parseFloat(voltage.getVoff()); DeltaVoltages[i] = res; } float minDelta = DeltaVoltages[0]; for (int i = 0; i < DeltaVoltages.length; i++) { if (DeltaVoltages[i] < minDelta) minDelta = DeltaVoltages[i]; } Log.i("VoltageActivity", Arrays.toString(DeltaVoltages)); Log.i("Min is ", String.valueOf(minDelta)); Toast.makeText(VoltageActivity.this, "Min Delta V is " + String.valueOf(minDelta), Toast.LENGTH\_SHORT).show(); } }); } } ```<issue_comment>username_1: In the first case, you intialize an instance of a dictionary that contains elements copied from the dictionary you pass to the constructor and you make use of the default equality comparer for the key type. For further info please have a look [here](https://msdn.microsoft.com/en-us/library/et0ke8sz(v=vs.110).aspx). Then you assign a reference to the newly created dictionary to the `inventoryRequirements` field. Whereas in the second case you just assign a copy of the reference to the original dictionary to the `inventoryRequirements` field. Upvotes: 2 <issue_comment>username_2: In the first example code snippet, you're cloning the dictionary instance passed in as a parameter using the copy constructor. Whereas the second approach, you're simply assigning the dictionary reference passed in to the current objects dictionary instance. The first approach is an effective way to clone a given dictionary's data. This means when the original dictionary is modified, the copy is not affected. That said, if `Inventory` is a reference type (Which I'd assume it's) then it's important to note that you've cloned the dictionary but if you haven't cloned the `Inventory` values in the dictionary instance, any modifications to the `Inventory` will still be seen through on a given `Job` instance dictionary. Upvotes: 2 [selected_answer]<issue_comment>username_3: Well, to really understand what exactly is going on, let's have a look at a quick code snippet. * [Your first snippet](https://repl.it/repls/FeistyModernRadius) * [Your second snippet](https://repl.it/repls/LateSlightTransformations) Observing the outputs you can see that in the second case, your original dictionary was actually modified, and the value mapped to the key "test" was re-assigned to 0. As you may have figured out, when you use `new Dictionary(inventoryRequirements);` you actually create a *clone* of your original dictionary, so the instantiated class can modify its copy all it wants without affecting your copy. Whereas, when you directly pass the *same* dictionary, any modifications made by the instantiated class will be visible in your class, and you lose control over your dictionary as you've essentially given the instantiated class complete control over it. Now, as a general rule of OOP, you should keep your fields (that aren't required by other classes/objects) to yourself. By that logic, you should pass your object (not a copy) if: 1. You will not need the object again or 2. Your object is very large and can't be cloned reasonably **Keep in mind that the GC will automatically delete your object if it goes out of scope immediately** or 3. The object is a primitive (you'll get a deep copy, so it will already be a clone.) Now, if you don't need any of the above you should probably be passing a copy. Upvotes: 0
2018/03/17
889
2,646
<issue_start>username_0: I am working on a website and I want the navigation (only home the homepage) to be transparent and the image to cover the full screen. This is what I have so far: [![enter image description here](https://i.stack.imgur.com/RchgS.jpg)](https://i.stack.imgur.com/RchgS.jpg) The nav-bar is styled in this way because that's how it is on the other pages. This is my HTML: ``` [![bunk](app/assets/images/bunklogo.png) Bunk.](#page-top) Menu * [TENANT](#tenant) * [LANDLORD](landlord.html) * [BUNK FAQs](#bunkfaqs) * [BLOG](#blog) * [TEAM](#team) * [LOG IN](#login) * SIGN UP ``` and my css: ``` #mainNav { background-image: linear-gradient(90deg, #439EE0 0%, #26ADE6 100%); /*margin-top: -0.5%;*/ padding-top: 1rem; padding-bottom: 3rem; margin-bottom: 0; } .navbar-toggler.navbar-toggler-right { color:white; border: 1px solid white; font-size: 1.2rem; padding: 1rem; } .navbar-light .navbar-nav .nav-link { font-size: 1.2rem; color: #ffffff; letter-spacing: 0.8px; text-align: center; padding-right: 5rem; } .navbar-brand.js-scroll-trigger { color: #ffffff; font-size: 2rem; } ``` Any suggestions?<issue_comment>username_1: Ok, first of all you need to **separate** the home page from the other pages. To do this just insert an ID on your body section like **#home**. So, in this scenario you will add the following: ``` body#home #mainNav { background:transparent; background-image:none; position:absolute; width:100%; left:0px; right:0px; top:0px; } ``` Don't forget that your Slider (or w/e you have after #mainNav), maybe will need some padding-top equals to the #mainNav height, for example (in case that your #mainNav height is 50px): ``` .slider { padding-top:50px; } ``` Upvotes: 0 <issue_comment>username_2: You can give an extra class to your navbar on your index.html only. (or your homepage html file name.) ``` ``` Then you can select this class like : ``` #mainNav.navbar--home{ background:transparent; } ``` Upvotes: 0 <issue_comment>username_3: There's no need for any custom css hacks here. To make your Bootstrap navbar transparent, all you need is to **remove the class `bg-light`**. That's it! The `bg` in `bg-light` stands for "background". So, if you leave out the class for background color, you automatically have a transparent navbar. Upvotes: 4 [selected_answer]<issue_comment>username_4: Use home page body class, for ex.: ".home / .home-index / .index-page" as a parent of ".nav.fixed-top" container. CSS:: ``` .home .nav.fixed-top{ background:rgba(0, 0, 0, 0) none repeat scroll 0 0; } ``` Upvotes: 0
2018/03/17
625
1,985
<issue_start>username_0: I am trying to install pythonmagick on OSX (High Sierra). I followed DwishR's instructions here: <https://gist.github.com/tomekwojcik/2778301> Downloaded pythonmagick from here: <http://www.imagemagick.org/download/python/> Modified BOOST\_ROOT=/usr/local/Cellar/boost/1.66.0/ and the make files. See my install procedure here: <https://gist.github.com/anonymous/d2eab85b89fd7be33efa40bf3cb1015e> However, you can see that pythonmagick is not working at the end. What did I do wrong?<issue_comment>username_1: Ok, first of all you need to **separate** the home page from the other pages. To do this just insert an ID on your body section like **#home**. So, in this scenario you will add the following: ``` body#home #mainNav { background:transparent; background-image:none; position:absolute; width:100%; left:0px; right:0px; top:0px; } ``` Don't forget that your Slider (or w/e you have after #mainNav), maybe will need some padding-top equals to the #mainNav height, for example (in case that your #mainNav height is 50px): ``` .slider { padding-top:50px; } ``` Upvotes: 0 <issue_comment>username_2: You can give an extra class to your navbar on your index.html only. (or your homepage html file name.) ``` ``` Then you can select this class like : ``` #mainNav.navbar--home{ background:transparent; } ``` Upvotes: 0 <issue_comment>username_3: There's no need for any custom css hacks here. To make your Bootstrap navbar transparent, all you need is to **remove the class `bg-light`**. That's it! The `bg` in `bg-light` stands for "background". So, if you leave out the class for background color, you automatically have a transparent navbar. Upvotes: 4 [selected_answer]<issue_comment>username_4: Use home page body class, for ex.: ".home / .home-index / .index-page" as a parent of ".nav.fixed-top" container. CSS:: ``` .home .nav.fixed-top{ background:rgba(0, 0, 0, 0) none repeat scroll 0 0; } ``` Upvotes: 0
2018/03/17
734
2,337
<issue_start>username_0: I have a SSL-certificate Comodo PositiveSSL. There are files: ``` AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt domain.com.key domain_com.crt ``` Requirements vendor: ``` The certificate, private key, and certificate chain must be PEM-encoded /ssl/test1.bx.key.pem /ssl/test1.bx.cert.pem /ssl/test1.bx.ca-chain.cert.pyem ``` Do I create PEM files correctly? ``` cat COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt AddTrustExternalCARoot.crt > domain.com.ca-chain.cert.pem cat domain_com.crt COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > domain.com.cert.pem cat domain.com.key domain_com.crt COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > domain.com.key.pem ```<issue_comment>username_1: Ok, first of all you need to **separate** the home page from the other pages. To do this just insert an ID on your body section like **#home**. So, in this scenario you will add the following: ``` body#home #mainNav { background:transparent; background-image:none; position:absolute; width:100%; left:0px; right:0px; top:0px; } ``` Don't forget that your Slider (or w/e you have after #mainNav), maybe will need some padding-top equals to the #mainNav height, for example (in case that your #mainNav height is 50px): ``` .slider { padding-top:50px; } ``` Upvotes: 0 <issue_comment>username_2: You can give an extra class to your navbar on your index.html only. (or your homepage html file name.) ``` ``` Then you can select this class like : ``` #mainNav.navbar--home{ background:transparent; } ``` Upvotes: 0 <issue_comment>username_3: There's no need for any custom css hacks here. To make your Bootstrap navbar transparent, all you need is to **remove the class `bg-light`**. That's it! The `bg` in `bg-light` stands for "background". So, if you leave out the class for background color, you automatically have a transparent navbar. Upvotes: 4 [selected_answer]<issue_comment>username_4: Use home page body class, for ex.: ".home / .home-index / .index-page" as a parent of ".nav.fixed-top" container. CSS:: ``` .home .nav.fixed-top{ background:rgba(0, 0, 0, 0) none repeat scroll 0 0; } ``` Upvotes: 0
2018/03/17
257
1,124
<issue_start>username_0: I want to send a template email to perform email verification of our users. The template email should contain a link which need to call http POST request to somewhere. And than from third party API (ex. elasticemail) handle that request via JavaScript and do another POST request to the actual server. My question is: How can I do this? We need this kind of step in email verification process, because otherwise we have to expose private data inside email template.<issue_comment>username_1: I advice that you just create a simple email that has a link to the page with the functionalities you outlined. Append the url with a random or jwt string that you can use to identify which user has arrived to the page. Upvotes: 0 <issue_comment>username_2: > > The template email should contain a link which need to call http POST request to somewhere > > > Sorry, this is not possible. When a user clicks on any link the browser will always do a HTTP GET request. But you can assign tokens (or random strings) to uniqly identify the email address. So there is no private data leaked. Upvotes: 2
2018/03/17
516
1,985
<issue_start>username_0: I am trying to write cursor that would insert into table, but I am receiving error, need help with this. Error that I am receiving is ORA-06550. ``` DECLARE CURSOR cur_rating IS SELECT bc.name, bc.title, bc.checkoutdate, bc.returneddate, b.categoryname,b.publisher, ba.authorname FROM bookshelf_checkout bc INNER JOIN bookshelf b ON bc.title = b.title INNER JOIN bookshelf_author ba ON bc.title = ba.title FOR UPDATE NOWAIT; lv_totdays_num NUMBER(4) := 0; lv_rating_txt VARCHAR2(2); BEGIN FOR rec_rating IN cur_rating LOOP lv_totdays_num := rec_rating.returneddate - rec_rating.checkoutdate; IF lv_totdays_num <= 10 THEN lv_rating_txt := 'DR'; ELSIF lv_totdays_num <= 25 THEN lv_rating_txt := 'CR'; ELSIF lv_totdays_num <= 35 THEN lv_rating_txt := 'BR'; ELSE lv_rating_txt := 'A'; END IF; INSERT INTO bookshelf_audit (title, publisher, categoryname, new_rating, auditdate) VALUES (rec_rating.title, rec_rating.publisher, rec_rating.categoryname, lv_rating_txt, sysdate) WHERE CURRENT OF cur_rating; END LOOP; COMMIT; END; ```<issue_comment>username_1: I advice that you just create a simple email that has a link to the page with the functionalities you outlined. Append the url with a random or jwt string that you can use to identify which user has arrived to the page. Upvotes: 0 <issue_comment>username_2: > > The template email should contain a link which need to call http POST request to somewhere > > > Sorry, this is not possible. When a user clicks on any link the browser will always do a HTTP GET request. But you can assign tokens (or random strings) to uniqly identify the email address. So there is no private data leaked. Upvotes: 2
2018/03/17
319
1,368
<issue_start>username_0: I've searched about this a lot. In keras documentation it says that model.save() saves all the relevant info, i.e. model architecture, weights, optimizer state,... Some other posts here on stackoverflow, mentioned saving the weights and loading them in the future to resume training, but the answers said that it's wrong, because it's not saving the optimizer state. I use callbacks to save best model base om validation accuracy, and it only save weights. If weights aren't enough to resume training, why does call backs only save weights? Just for evaluating on the test set? How can I properly save the best model then? Why doesn't call backs use model.save() to store all the info? How can i achieve this?<issue_comment>username_1: I advice that you just create a simple email that has a link to the page with the functionalities you outlined. Append the url with a random or jwt string that you can use to identify which user has arrived to the page. Upvotes: 0 <issue_comment>username_2: > > The template email should contain a link which need to call http POST request to somewhere > > > Sorry, this is not possible. When a user clicks on any link the browser will always do a HTTP GET request. But you can assign tokens (or random strings) to uniqly identify the email address. So there is no private data leaked. Upvotes: 2
2018/03/17
507
2,019
<issue_start>username_0: I have published an app to Google Play and I would like to add a leaderboard to it now. I followed some tutorials about it (on GitHub) but I still can't sign in: ``` void SignIn() { Social.localUser.Authenticate ((bool success) => { if(success) GameObject.Find("UI_TXT_NAME").GetComponent().text = Social.localUser.userName; else { GameObject.Find("UI\_TXT\_NAME").GetComponent().text = "Inconnu"; Debug.Log("Fail to authenticate"); } }); } ``` When I build and run my app on my Android Phone, this code always ends in the "else{}" statement. Yet, after trying to Sign In, I can see the green pop-up frame from Google Play Games but authentication doesn't seem to work. And of course I can't show the Leaderboard. I found lots of thread on various forums about this issue but none of the answers works with me. * I do have downloaded the latest Android packages (yesterday). * I have no errors nor error messages. * I do have registered my app and copied the resources in the unity Window->Google Play Games->Setup->Android Setup. * I do have created the leaderboard in Google Play. * I do have allowed my two mail addresses to test my apps. I must be missing something... Subsidiary question: Is it possible to Sign In Google Play Games in Unity play mode or do I have to run it on my mobile phone every time?<issue_comment>username_1: I advice that you just create a simple email that has a link to the page with the functionalities you outlined. Append the url with a random or jwt string that you can use to identify which user has arrived to the page. Upvotes: 0 <issue_comment>username_2: > > The template email should contain a link which need to call http POST request to somewhere > > > Sorry, this is not possible. When a user clicks on any link the browser will always do a HTTP GET request. But you can assign tokens (or random strings) to uniqly identify the email address. So there is no private data leaked. Upvotes: 2
2018/03/17
666
2,395
<issue_start>username_0: I want my `label2.Text` to display each concecutive result of the multiplication table, but only the last result gets displayed. I made that each checkbox equals only one math table. checkbox1 = multiplication table 1, checkbox2 = multiplication table 2 and so on... Why is only the last result being displayed in my `label2.Text` property in my Windows Form? P.S. I am working through an introduction course of C#. ``` int multiplyWith; int multiplyNumber; for (multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++) { if (checkBox1.Checked == true) { multiplyWith = 1; int sum = multiplyNumber * multiplyWith; label2.Visible = true; label2.Text = sum + "\n"; } else if (checkBox2.Checked == true) { multiplyWith = 2; int sum = multiplyNumber * multiplyWith; label2.Visible = true; label2.Text = sum + "\n"; } } ```<issue_comment>username_1: You are not concatenating the result but only setting the current value. This would work but is not the most clean/efficient way to do it: ``` label2.Text += sum + "\n"; ``` Try using a `StringBuilder` to generate the result first and at the end assign the text box the `StringBuilder` value. ``` StringBuilder sum = new StringBuilder(); int multiplyWith = checkBox1.Checked ? 1 : 2; for (int multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++) { sum.AppendLine(multiplyNumber * multiplyWith); } label2.Visible = true; label2.Text = sum.ToString(); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: If you want you could change it to something like: ``` int multiplyWith; int multiplyNumber; var results = string.Empty; for (multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++) { if (checkBox1.Checked == true) { multiplyWith = 1; int sum = multiplyNumber * multiplyWith; label2.Visible = true; results += sum + "\n" } else if (checkBox2.Checked == true) { multiplyWith = 2; int sum = multiplyNumber * multiplyWith; label2.Visible = true; results += sum + "\n" } } ``` Then **after your loop exits**: ``` label2.Text = results; ``` Upvotes: 0 <issue_comment>username_3: you could just edit this line from ``` label2.Text = sum + "\n"; ``` to ``` label2.Text += sum + "\n"; ``` Upvotes: 0
2018/03/17
573
2,013
<issue_start>username_0: I'd like to send output of shell command to client. Here is the code snippet which handles POST request: ``` app.post('/', function(req, res) { console.log("request is received"); const ps = spawn('sh', ['test.sh', req.body.code]); ps.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ps.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); ps.on('close', (code) => { console.log(`child process exited with code ${code}`); }); // echo incoming data to test whether POST request works res.status(200).json({ myReply: req.body.code }); }); ``` How can I send stdout to client in such a case?<issue_comment>username_1: First it should be noted that what you about to do is dangerous. Very dangerous. Blindly executing a command from a client is not wise, you should sanitize both your ingress and egress data from untrusted sources. While I am indeed making an assumption that this is not happening based on your provided example I just firmly believe you should rethink your design if this is the case. Now that I have spoken up you should capture `stdout` to any array or object during the `on('data', (data) => {` and send it to the client on `close`. `let results =[]; const ps = spawn('sh', ['test.sh', req.body.code]); ps.stdout.on('data', (data) => { console.log(`stdout: ${data}`); results.push(${data}); }); ``` ps.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); ps.on('close', (code) => { console.log(`child process exited with code ${code}`); res.status(200).json(results); }); // echo incoming data to test whether POST request works res.status(200).json({ myReply: req.body.code });` ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can stream the `stdout` from the child process back to `res`. This works because `ps.stdout` is a readable stream and `res` is a writable stream. ``` ps.stdout.pipe(res) ``` Upvotes: 2
2018/03/17
521
1,730
<issue_start>username_0: Given two *sorted* arrays of integers A1, A2, with the same length `n` and an integer `x`, I need to write an algorithm that runs in O(nlog(n)) that determines whether there exist two elements `a1, a2` (one element in each array) that make `a1+a2=x`. At first I thought about having two index iterators `i1=0, i2=0` (one for each array) that start from 0 and increase one at a time, depending on the next element of A1 being bigger/smaller than the next element of A2. But after testing it on two arrays I found out that it might miss some possible solutions...<issue_comment>username_1: This is a strange question because there is an inelegant solution in time `O(N Lg N)` (for every element of A1, lookup A2 for `x-a1` by dichotomic search), and a nice one requiring only `O(N)` operations. Start from the left of A1 and the right of A2 and move left in A2 as long as `a1+a2≥x`. Then move right one position in A1 and update in A2 if needed... Upvotes: 1 <issue_comment>username_2: Well, as they are both sorted already, the algorithm should be O(n) (sorting would be O(n \* log(n))): ``` i1 = 0 i2 = A2.size - 1 while i1 < A1.size and i2 >= 0 if A1[i1] + A2[i2] < x ++i1 else if A1[i1] + A2[i2] > x --i2 else success!!!! ``` Upvotes: 4 [selected_answer]<issue_comment>username_1: You start one array from index = 0 = i and the other in reverse other = j. First step you know you have the smallest in the list A and the biggest in the list B so you subtract i from x, then move the j index down until the value =< X Basically you have 2 indexes moving towards the middle If value of index i > value of index j then there is no such sum that match x. Upvotes: 1
2018/03/17
521
2,041
<issue_start>username_0: I thought I knew how to declare variables until I just saw this example. In the example a constant is declared. ``` let timeOfDay: String ``` I thought you could not declare a variable/constant without initializing it unless you declared it as an Optional? Of course the program bombs when I go to print the constant. How is it the compiler allowed this? I entered this into a Playground. A full example: ``` let hourOfDay = 12 let timeOfDay: String if hourOfDay < 6 { timeOfDay = "Early morning" } else if hourOfDay < 12 { timeOfDay = "Morning" } else if hourOfDay < 17 { timeOfDay = "Afternoon" } else if hourOfDay < 20 { timeOfDay = "Evening" } else if hourOfDay < 24 { timeOfDay = "Late evening" } else { timeOfDay = "INVALID HOUR!" } print(timeOfDay) ```<issue_comment>username_1: The compiler is smart enough to figure out that on every possible code path that leads to the first read access of `timeOfDay`, it is in fact initialized exactly once. Try leaving out one of the assignments as an experiment. Upvotes: 2 <issue_comment>username_2: The compiler let's you declare a let variable without value, but it expects you to set a value for it later. It's possible to not enter on any of the `if` statements in your example, so the compiler knows that you're trying to read a value that may not exists. You can try a simple `if` `else` statement and try to run, just to check :D Upvotes: 1 <issue_comment>username_3: Yes, we can declare a Constant without an initial value in Swift. But we need to assign a value later so we can use that Constant, otherwise there would be a compile error. It is also important to note that while we can change the value multiple times in Variables, we can assign a value to a Constant only ONCE. In the given example above, the if-else statements can only assign a value to the Constant timeOfDay only once. After that, we cannot assign a new value or even create a new if-else statements to change the value of timeOfDay anymore. Upvotes: 0
2018/03/17
740
2,575
<issue_start>username_0: I have a problem with following 16-bit TASM program which evaluates the expression (a*b+c*d)/(a-d): ``` MyCode SEGMENT ORG 100h ASSUME CS:SEGMENT MyCode, DS:SEGMENT MyCode, SS:SEGMENT Start: jmp Beginning a DB 20 b EQU 10 c DW 5 d = 3 Result DB ? Beginning: mov al, a mov bl, b mov dx,ax mov al, BYTE PTR c mov bl, d mul bl add dx,ax mov al, a sub al,bl mov bl,al mov ax,dx div bl mov Result, al mov ax, 4C00h int 21h MyCode ENDS END Start ``` The compilation errors I get in DOSBox console state that there's an undefined symbol (SEGMENT) and that the compiler can't address with currently ASSUMEd segment registers. It seems to me that that I'm missing the definition of a block, but I have no idea how to proceed further. What's wrong with this code?<issue_comment>username_1: I won't fix the logical errors for you, but the syntax in the top of this code is incorrect: ``` MyCode SEGMENT ORG 100h ASSUME CS:SEGMENT MyCode, DS:SEGMENT MyCode, SS:SEGMENT Start: ``` You don't use the directive `SEGMENT` in the assume, they have to be removed. When removed the segments have to have a name applied to them. One is missing on `SS:`. It should look like: ``` MyCode SEGMENT ASSUME CS:MyCode, DS:MyCode, SS:MyCode ORG 100h Start: ``` In DOS COM program all the segments for DATA, CODE, and the STACK are in the same segment. You can also achieve the same by replacing it with: ``` .model tiny .code ORG 100h Start: ``` The TINY model is designed to work for DOS COM program creation. The `ORG 100h` directive has to be preceded by the `.code` directive. With this modification you have to **remove** this line: ``` MyCode ENDS ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: L1: .model small L2: .stack L3: .data L4: printStr db "Pangasinan State University" L5: .code L6: BEGIN: L7: mov dx,OFFSET printString L8: mov ax,SEG printStr L9: mov ds,ax L10: mov ah,9H L11: int 21H L12: mov ah, 4ch L13: int 21D L14: END BEGIN Upvotes: 0
2018/03/17
824
3,047
<issue_start>username_0: In Woocommerce, I have created a custom product type `live_stream`. But when I create a new product within this custom type and I publish it, the product remains a "simple product" and doesn't get the `live_stream` custom type set for it. What I am doing wrong? How to make that custom product type functional? Here is my code ``` function wpstream_register_live_stream_product_type() { class Wpstream_Product_Live_Stream extends WC_Product { public function __construct( $product ) { $this->product_type = 'live_stream'; parent::__construct( $product ); } public function get_type() { return 'live_stream'; } } } add_action( 'init', 'wpstream_register_live_stream_product_type' ); function wpstream_add_products( $types ){ $types[ 'live_stream' ] = __( 'Live Channel','wpestream' ); return $types; } add_filter( 'product_type_selector', 'wpstream_add_products' ); ```<issue_comment>username_1: Since Woocommerce 3 `$this->product_type = 'live_stream';` is deprecated and not needed in the constructor. It has to be replaced by defining the function `get_type()` outside the constructor in the Class for this custom product type. So your code will be: ``` add_action( 'init', 'new_custom_product_type' ); function new_custom_product_type(){ class WC_Product_Live_Stream extends WC_Product{ public function __construct( $product ) { parent::__construct( $product ); } // Needed since Woocommerce version 3 public function get_type() { return 'live_stream'; } } } add_filter( 'product_type_selector', 'custom_product_type_to_type_selector' ); function custom_product_type_to_type_selector( $types ){ $types[ 'live_stream' ] = __( 'Live Channel', 'wpestream' ); return $types; } ``` Code goes in function.php file of your active child theme (or active theme). Tested and works. This should solve your issue. Upvotes: 3 [selected_answer]<issue_comment>username_2: I was debugging this as well. I use namespaces, so I was considering that this is part of the problem. It is not. So for future (and other people's) reference. The class lookup happens in `wp-content/plugins/woocommerce/includes/class-wc-product-factory.php`: ``` /** * Create a WC coding standards compliant class name e.g. WC_Product_Type_Class instead of WC_Product_type-class. * * @param string $product_type Product type. * @return string|false */ public static function get_classname_from_product_type( $product_type ) { return $product_type ? 'WC_Product_' . implode( '_', array_map( 'ucfirst', explode( '-', $product_type ) ) ) : false; } ``` You can use this snippet (or set a breakpoint on debugging) to determine why your `$product-type`does not resolve to the correct classname. In my case I had a product name like `my_class` and thought mistakenly it would resolve to `My_Class`, which it does not, it resolves to `My_class`. Upvotes: 0
2018/03/17
1,315
4,892
<issue_start>username_0: I'm building my own custom input fields. I want to use `ControlValueAccessor` to make use of `FormGroup` with `FormControlName` as well as `ngModel`. Problem is when I have two input fields in one form. Those inputs are out of sync but `FormGroup` value is in sync. Here is sample app: <https://stackblitz.com/edit/angular-9krudy> If You change value in input field, it does not reflect on component's value but reflects in `FormGroup` value. If You change value using `my-input` component ("Change value randomly" button) it changes value in component but not in input. As previous, value in `FormGroup` is changing. When I change `FormGroup` value using `patchValue` all works as it should. How to fix my code to always be in sync?? I want to be able to use `my-input` with `ngModel` so passing `FormGroup` and depending on it is not an option. **EDIT:** I've discovered that in `Angular` **You cannot have two input fields with the same `formNameControl`**: <https://stackblitz.com/edit/angular-y2sj5g> (Ok, You can but they are not in sync). So this question is invalid. **EDIT: code** AppComponent: ``` import { Component } from '@angular/core'; import {FormControl, FormGroup} from "@angular/forms"; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { formGroup: FormGroup = new FormGroup({ text: new FormControl('text') }); constructor() { } ngOnInit() { } onChange() { this.formGroup.get('text') .patchValue('New value'); } } ``` AppComponentHtml ``` ``` MyInputComponent: ``` import {Component, forwardRef, OnInit} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; @Component({ selector: 'my-input', template: ` --- In component [Change value randomly](javascript:void(null)) Value in component: **{{value}}** --- `, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyInputComponent), multi: true } ] }) export class MyInputComponent implements ControlValueAccessor, OnInit { protected _value: any; constructor() { } ngOnInit() { } onChange() { this.value = Math.random(); } get value(): any { return this._value; } set value(value: any) { this._value = value; this.propagateChange(this._value); } writeValue(value: any) { console.log('Out from component', value); if (value !== undefined) { this._value = value; } } propagateChange = (_: any) => { }; registerOnChange(fn) { this.propagateChange = fn; } registerOnTouched() { } } ```<issue_comment>username_1: Since Woocommerce 3 `$this->product_type = 'live_stream';` is deprecated and not needed in the constructor. It has to be replaced by defining the function `get_type()` outside the constructor in the Class for this custom product type. So your code will be: ``` add_action( 'init', 'new_custom_product_type' ); function new_custom_product_type(){ class WC_Product_Live_Stream extends WC_Product{ public function __construct( $product ) { parent::__construct( $product ); } // Needed since Woocommerce version 3 public function get_type() { return 'live_stream'; } } } add_filter( 'product_type_selector', 'custom_product_type_to_type_selector' ); function custom_product_type_to_type_selector( $types ){ $types[ 'live_stream' ] = __( 'Live Channel', 'wpestream' ); return $types; } ``` Code goes in function.php file of your active child theme (or active theme). Tested and works. This should solve your issue. Upvotes: 3 [selected_answer]<issue_comment>username_2: I was debugging this as well. I use namespaces, so I was considering that this is part of the problem. It is not. So for future (and other people's) reference. The class lookup happens in `wp-content/plugins/woocommerce/includes/class-wc-product-factory.php`: ``` /** * Create a WC coding standards compliant class name e.g. WC_Product_Type_Class instead of WC_Product_type-class. * * @param string $product_type Product type. * @return string|false */ public static function get_classname_from_product_type( $product_type ) { return $product_type ? 'WC_Product_' . implode( '_', array_map( 'ucfirst', explode( '-', $product_type ) ) ) : false; } ``` You can use this snippet (or set a breakpoint on debugging) to determine why your `$product-type`does not resolve to the correct classname. In my case I had a product name like `my_class` and thought mistakenly it would resolve to `My_Class`, which it does not, it resolves to `My_class`. Upvotes: 0
2018/03/17
916
3,606
<issue_start>username_0: I am learning Python through a project and am running into an issue with subclassing. Based on everything I have read the process is pretty straightforward, but calls from the sub class to methods from the base class result in attribute not found errors. My code sample includes the pertinent parts of the base class(Player), the subclass(Roster) and the setup and calls to the base and sub classes. What am I missing? Also is it necessary to create an **init** method in the subclass if it really isn't needed? main script: ``` from battleship.player import Player, Roster player=Player() roster=Roster() player.register() roster.load_other_players() ``` Classes: ``` class Player: def __init__(self): .... self.getOtherPlayers = {} def register(self): ... return def get_other_players (self): return self.getOtherPlayers def gameFlow(self): if self.currentFlow != undefined: self.currentFlow+=1 else: self.currentFlow = 0 def setMove(self, m): return move.setMove(m); class Roster(Player): def __init__(self): super().__init__() def load_other_players(self): print("Roster!!!") print("Other players: ", super.get_other_players()) ``` Return: ``` Roster!!! Traceback (most recent call last): File "player.py", line 23, in roster.load\_other\_players() File "/home/jspooner/projects/battleship/BotPlayer/battleship/player.py", line 152, in load\_other\_players print("Other players: ", super.get\_other\_players()) AttributeError: type object 'super' has no attribute 'get\_other\_players' ``` **Edit** If anyone references this question in the future my actual problem was a design issue where I created an instance of the base class as well as an instance of the sub class. As a result I had 2 instances of related classes that weren't tied to each other. To fix this I swapped the hierarchy so that Roster is the parent class and Player is the child. My **main** creates an instance of Player which naturally creates a related Roster class.<issue_comment>username_1: this is very easy, you forget the () in super. You should call the function like so: `super().get_other_players()` and not `super.get_other_players()` since super is a function. Also, it is defenitly not necesercy to use a constructor in your subclass (defining an `__init__()` method in the subclass) if you just dont need to. Upvotes: 1 <issue_comment>username_2: To address your primary question/issues: `super` is not a valid entity, it would be the function `super()`. Alternatively, since `Roster` inherits from `Player`, `self.get_other_players()` would also be an acceptable way of referencing this, since all of the superclass's properties are incorporated as the subclass. `__init__` does not need to be explicitly created if it isn't necessary, but it IS necessary if you want to perform some initialization. It's worth reading [THIS](https://stackoverflow.com/a/3782877/4822348) answer to get more in-depth information about what is actually going on with `__init__` and why it is necessary. To answer a question that you didn't ask: Python is different than some other languages in a few ways, most notably the usage of getters and setters isn't necessary. Rather than `super().get_other_players()` or equivalent, just access the `getOtherPlayers` property directly. It is more elegant, makes for less lines of code and is easier to read/debug when you're maintaining your code (it's more 'pythonic') Upvotes: 3 [selected_answer]
2018/03/17
675
1,854
<issue_start>username_0: I have a function func() definition which contains a for() cycle. Can I then pass func() to lsode() to be resolved as an ODE? Update: Example of the code. ``` int = [0; 0]; slp = [0; 1]; x = [1:10]; r = zeros(1,10); for id = 1 : 2; r = r + int(id) + slp(id)*x; end plot(x,r); function ydot = fnc(y, t, int, slp) ydot = zeros(1,10); for jd = 1 : 2; ydot = ydot + int(jd) + slp(jd)*t; end end p = lsode(@(y,t) fnc(y,t,int,slp), 1, x); ``` error: lsode: inconsistent sizes for state and derivative vectors error: called from: error: /path$/test\_for\_function.m at line 15, column 3<issue_comment>username_1: The error message has nothing to do with the computations inside the ODE functions. It is telling you that the shape of `ydot` is incompatible with the shape of the state vector that is established by the initial value vector. First I can not identify in your code example the initial value vector. You seem to construct the array `r` for that, but you pass the scalar constant `1`. And then it could be as simple as switching the shape dimensions in the construction of `ydot`. Or use `ỳdot = zeros_like(y)` or similar if available. Upvotes: 2 [selected_answer]<issue_comment>username_2: After some debugging, tinkering and thinking about how `lsode` works, I found how to make my code work as intended: ``` %Start code int = [0; 0]; slp = [0; 1]; x = [1:10]; for id = 1 : 2; r = int(id) + slp(id)*x; end %A complicated way to draw a line figure(1); clf(1); plot(x,r); hold on; function ydot = fnc(y, t, int, slp) for jd = 1 : 2; ydot = [int(jd) + slp(jd)*t]; end end p = lsode(@(y,t) fnc(y,t,int,slp), 1, x); plot(x, p, '-r'); %EOF ``` And the result is: [![enter image description here](https://i.stack.imgur.com/cbxSE.jpg)](https://i.stack.imgur.com/cbxSE.jpg) As it should be. Upvotes: 0
2018/03/17
507
1,515
<issue_start>username_0: I have script in which I want to replace a set of strings indicated by ## ``` script <- c("This is #var1# with a mean of #mean1#") ``` My key value list is: ``` pairs <- list( list("#var1#", "Depression"), list("#mean1#", "10.1") ) ``` My loop looks like this and does its job. ``` for (pair in pairs) { script <- gsub(pair[[1]], pair[[2]], script) } ``` However, does anybody know a way to solve this **without** using a loop?<issue_comment>username_1: I think with a few changes, you could use the [**`glue`**](https://github.com/tidyverse/glue) package. The changes involve using a `data.frame` to store your key values, and slightly tweaking the formatting of your text. ``` library(glue) tt <- 'This is {var1} with a mean of {mean1}' dat <- data.frame( 'var1' = c('Depression', 'foo'), 'mean1' = c(10.1, 0), stringsAsFactors = FALSE ) glue(tt, var1 = dat$var1, mean1 = dat$mean1) This is Depression with a mean of 10.1 This is foo with a mean of 0 ``` Upvotes: 1 <issue_comment>username_2: You could use **stringr**. As mentioned in `?str_replace`: > > To perform multiple replacements in each element of string, pass a > named vector (`c(pattern1 = replacement1)`) to `str_replace_all`. > > > So in your case: ``` library(stringr) str_replace_all(script, setNames(sapply(pairs, "[[", 2), sapply(pairs, "[[", 1))) # [1] "This is Depression with a mean of 10.1" ``` Upvotes: 3 [selected_answer]
2018/03/17
636
2,480
<issue_start>username_0: While implementing a unit test using JMockit with a `@Capturing` annotation and a Verification block for the "captured" variable I have 2 outcomes: 1. IntelliJ: I can run and debug successfully, validating that the verification behaves correctly. 2. Executing same test code with command line (cmd) using `mvn test` throws 'Missing invocation'. It seems `@Capturing` behaves like `@Mocked` if using the cmd. As it is the exact behavior if I change the `@Capturing` to a `@Mocked`. What would be the cause of this? Settings: IntelliJ: 2017.3.4 Java 8 JMockit 1.35<issue_comment>username_1: In general, these kind of issues are usually due to maven running multiple tests in a single execution of the jvm. When you run a single unit test in IntelliJ, the test is well isolated, but when running with maven, any change of global variables in one test might have unexpected effects on the execution of other tests. This is why one should avoid mutating (and even using) static variables in unit tests, use `@DirtiesContext` if you have spring-enabled tests that change your context, etc. I don't have enough concrete information to pinpoint the exact problem in your case, but I would recommend that you start looking for something that would potentially change the behaviour of other tests. It's also possible to run multiple test classes at once with IntelliJ, doing this might be closer to how maven runs the tests. Upvotes: -1 <issue_comment>username_2: Reference: ``` @Test public void test(final @Mocked ProfileMgr profileMgr, final @Capturing Manager manager) throws Exception { final String id = “1234”; Final String modelId = “567”; final Map effectiveProps = ImmutableMap.of("test.key", "test.value", "ppp.key", "ppp.value" ); final Optional option = Optional.of("123"); new Expectations() {{ profileMgr.mergedProperties( id,IMPL\_1, (Map) any, option ); result = effectiveProps; }}; this.mainManager .run( id, modelId, new JobRequestWrapper<>(config, IMPL\_1, option); ); new Verifications() {{ final Map params; manager.execute( anyString, anyString, (CalculationConfig) any, params = withCapture() ); times = 1; assertThat(params) .withFailMessage("params must have content.") .isNotNull() .isNotEmpty(); assertThat(params) .withFailMessage("params must have same injected entry.") .isEqualTo(effectiveProps); }}; } ``` Upvotes: 0
2018/03/17
899
2,934
<issue_start>username_0: I am using the following code: ``` #!/usr/bin/python3 # -*- coding: utf-8 -*- import serial import serial.tools.list_ports import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk, Gdk class SerialComm(Gtk.Window): glade = "serial_comm.glade" builder = Gtk.Builder.new_from_file(glade) builder.add_from_file(glade) comboPorts = builder.get_object("comboPorts") comboBauds = builder.get_object("comboBauds") btn_conectar = builder.get_object("btnConectar") textbuffer = builder.get_object("textbuffer") textview = builder.get_object("textview") def get_ports(self): ports = list(serial.tools.list_ports.comports()) for p in ports: self.comboPorts.append_text(p[0]) self.comboPorts.set_active(1) print(p[0]) ``` **try open a port and get arduino data** ``` def open_port(self, widget): port = self.comboPorts.get_active_text() baud = self.comboBauds.get_active_text() arduino = serial.Serial(port, baud) temp = arduino.readline() self.textbuffer.set_text(temp) self.textview.set_buffer(self.textbuffer) arduino.close() def __init__(self): window = self.builder.get_object("window") window.connect("destroy", Gtk.main_quit) self.btn_conectar.connect("clicked", self.open_port) self.get_ports() window.show_all() if __name__ == '__main__': application = SerialComm() Gtk.main() ``` But I have to click on a button to get the data (temperature of a sensor, read every second). ``` self.btn_open.connect("clicked", self.openport) ``` How to update textview content automatically, after clicking the button?<issue_comment>username_1: A better way would be to open the port and read from it as the information comes in. Example: ``` from gi.repository import GLib #include this import with the rest of your imports def open_port(self, widget): port = self.comboPorts.get_active_text() baud = self.comboBauds.get_active_text() self.textview.set_buffer(self.textbuffer) arduino = serial.Serial(port, baud) GLib.timeout_add_seconds(1, self.read_info, arduino) def read_info (self, arduino) temp = arduino.readline() self.textbuffer.set_text(temp) return True ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Solution from @username_1 isn't really ideal. By using `g_timeout_add_seconds` isn't great, you're adding 1 second of latency on data reception. Using `g_timeout_add` would only hide the real problem: you're doing polling. Instead, [`g_io_add_watch`](https://developer.gnome.org/glib/stable/glib-IO-Channels.html#g-io-add-watch) should be used to call a callback when data really arrives. However, this would require having a `GIOChannel` that can be used by `pyserial`. The `GIOChannel` can be created from on a file descriptor, I just don't see how to get the file descriptor from a pyserial object, but that should be doable... Upvotes: 0
2018/03/17
659
2,282
<issue_start>username_0: I have an SVG image, in which there are individual circles that I want to rotate about their own center (the center of the circles). However when I set `transform-origin:center`, and then apply a transform, it starts rotating about the center of the whole SVG image. Is there any way to set the transform origin such that the circles rotate about their own center? Here is the original svg image (I cannot paste the original code here so this): [SVG image](https://swachhcoin.com/media/token%20economy.svg) Here is a jsfiddle for this: <https://jsfiddle.net/g9zfcdm3/3/> There are 4 circles in the image. Achieving this with any one cirlce would be good enough. What I actually want to achieve is to animate these circles so that they rotate indefinitely around their own center.<issue_comment>username_1: See this (resolved as invalid) bug report in Firefox about your problem: <https://bugzilla.mozilla.org/show_bug.cgi?id=1209061> Normally, CSS transforms on SVG elements are relative to the viewport and not to the element itself. This can be changed by adding `transform-box: fill-box`: ``` svg .rotate { animation: rotate 5s linear infinite; transform-box: fill-box; transform-origin: center; } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ``` Working fiddle: <https://jsfiddle.net/g9zfcdm3/10/> Background ---------- From the [MDN docs about `transform-box`](https://developer.mozilla.org/de/docs/Web/CSS/transform-box): > > The transform-box CSS property defines the layout box to which the transform and transform-origin properties relate. > > > **border-box** (default) > > > The border box is used as the reference box. The reference box of a is the border box of its table wrapper box, not its table box. > > > **fill-box** > > > The object bounding box is used as the reference box. > > > Note that it's an experimental feature and probably won't work in IE and Edge. Upvotes: 6 [selected_answer]<issue_comment>username_2: An example of animation directly in the SVG file without CSS ``` xml version="1.0" encoding="iso-8859-1"? ``` You can change the animation config at ``` ``` For references: <https://css-tricks.com/guide-svg-animations-smil/> Upvotes: 0
2018/03/17
384
1,294
<issue_start>username_0: For example, before: ``` Titles Description ``` After: ``` Titles Description ```<issue_comment>username_1: Use the `Emmet: Remove Tag` command: [![enter image description here](https://i.stack.imgur.com/JjAyc.gif)](https://i.stack.imgur.com/JjAyc.gif) Setup a keybinding for this with `editor.emmet.action.removeTag`: ``` { "key": "ctrl+shift+k", "command": "editor.emmet.action.removeTag" } ``` Upvotes: 7 [selected_answer]<issue_comment>username_2: Just a note that there is an improvement in vscode v1.63 to also (as the OP requested) remove the lines on which the removed tags reside. It works now in the Insiders Build. See > > ### Emmet Remove Tag command improvement > > > The "Emmet: Remove Tag" command now removes empty lines around tags if > they are the only tags on the line. It also now does not take into > account empty lines when calculating the amount to reindent the lines. > > > See [release notes: emmet remove tag improvements](https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_63.md#emmet-remove-tag-command-improvement) ```html <- this entire line will be removed sonce only the tag on the line Titles Description <- this entire line will be removed ``` Upvotes: 2
2018/03/17
557
1,723
<issue_start>username_0: My goal is to get a list which has the same structure as the two initial lists, the difference being that each element is necessarily a logical vector. Consider two lists: ``` mlist <- rep(list(rep(c(0,2,4),68),c(1), sample(x = c("a","b"),size = 1, prob = c(.5,.5))),200) klist <- rep(list(rep(c(0,2,3),68), c(0), sample(x = c("a","b"),size = 1, prob = c(.5,.5))),200) ``` Notice that in a given list, each element is a vector, either string or numeric, and they aren't necessarily the same length. However, both lists have the exact same structure. The list I am looking for has the same structure and indicates equality for each element within each vector of both lists. For loops provide an unpalatable solution: ``` hon <- as.list(rep(NA ,length(mlist))) for(i in seq(length(mlist))){ for (m in seq(length(mlist[[i]]))){ hon[[i]][[m]] <- mlist[[i]][[m]]==klist[[i]][[m]] } } ``` Another solution, using the purrr package, slightly more elegant, but slower, is ``` han <- map2(klist, mlist, map2_lgl, identical) ``` Time elapsed is 0.054 for the for loop method, and 0.129 for the purr method. Are there more efficient alternatives?<issue_comment>username_1: Have you always vectors as elements of your lists? If so, you can use the vectorized `==`. Just do ``` hin <- lapply(seq_along(mlist), function(i) { mlist[[i]] == klist[[i]] }) all.equal(hin, hon) [1] TRUE ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You could consider ``` unlist(klist) == unlist(mlist) ``` but this will discard the list format. You could determine the original index of each result by comparing to ``` cumsum(lengths(mlist)) ``` Upvotes: 0
2018/03/17
568
2,131
<issue_start>username_0: I am wanting to update an @Input property from a child and for the changes to take effect on the parent. Parent TS (document-details): ``` export class DocumentDetailsComponent implements OnInit { view: string = 'editor'; } ``` Parent HTML (document-details): ``` ``` Child TS (document-content): ``` export class DocumentContentComponent implements OnInit, OnChanges { @Input() view: string; ngOnChanges(changes: SimpleChanges) { if (changes.version) { this.view = 'editor'; } } } ``` When the view property inside the child component gets set top 'editor' it doesn't seem to reflect these changes inside the parent component. I know I could use an @Ouput event emitter but I feel like this should work fine.<issue_comment>username_1: When angular bootstraps it builds a component tree.[![Component](https://i.stack.imgur.com/7DDrY.png)](https://i.stack.imgur.com/7DDrY.png) A component has input and output properties, which can be defined in the component decorator or using property decorators. Data flows into a component via `@input` properties(Parent to child ). Data flows out of a component via `@output`(child to parent) properties. with `@input` property data flows down the tree.It doesn't flow upwards. if you want data flow in the opposite direction i.e Upwards you need to use `@Output` decorator and Event emitter. Upvotes: 2 <issue_comment>username_2: If you want changes from an `@Input` to affect the parent that means you want your `@Input` to also be an `@Output`, this is called `two-way binding` to which you can find the documentation [here](https://angular.io/guide/two-way-binding). But in summary what happens is that in angular this: ``` ``` Is syntactic sugar for this: ``` ``` So in order for your code to work you need to create the viewChange output and call emit() whenever your code changes the view property. ``` @Input() view: string; @Output() viewChange = new EventEmitter(); ngOnChanges(changes: SimpleChanges) { if (changes.version) { this.view = 'editor'; this.viewChange.emit(this.view); } } ``` Upvotes: 0
2018/03/17
455
1,522
<issue_start>username_0: I can't find what's wrong in my code and tried everything. It's my first time working with maps so I'm not sure this is how I get the value of the second key. This is my code: ``` bool DeleteConnection(ServerData &sd, ServerName sn, UserName un){ if(sd.find(sn) == sd.end()){ return false; } else{ auto search = sd.find(sn); if(search != sd.end()) { std::set users = search->second; } const bool is\_in = users.find(un) != users.end(); if(is\_in){ //un connected users.erase(un); sd[sn] = users; return true; } else{ //un not connected return false; } } } ```<issue_comment>username_1: The scope of the object `users` is the sub-statement of the if statement. ``` if(search != sd.end()) { std::set users = search->second; } ``` Outside the scope of the if statement the name `users` is undefined. In fact the function design is wrong. You should rewrite the function body. Upvotes: 2 <issue_comment>username_2: As username_1 pointed out, once the `if` scope ends, your `users` variable cease to exist, therefore you get the error when you are trying to use it outside of `if` scope. I would rewrite your function to make it more clear: ``` bool DeleteConnection(ServerData &sd, ServerName sn, UserName un) { auto search = sd.find(sn); if (search == sd.end()) return false; std::set users = search->second; if (users.find(un) == users.end()) return false; users.erase(un); sd[sn] = users; return true; } ``` Upvotes: 3 [selected_answer]
2018/03/17
650
2,416
<issue_start>username_0: Basically I have 2 csv file as below: ``` File 1: File 2: Current output: Num Num2 Num 1 1 1 2 2 2 3 3 3 4 4 4 Num2 1 2 3 4 ``` I want to merge them into a single csv file as below: ``` Expected File 3: Num Num2 1 1 2 2 3 3 4 4 ``` However when I merge the file, it starts at the bottom of File 1 data. How to make them start at the column 2 row 1, instead of starting at the below. ``` inputs = ["asd.csv", "b.csv"] # etc # First determine the field names from the top line of each input file # Comment 1 below fieldnames = [] for filename in inputs: with open(filename, "r", newline="") as f_in: reader = csv.reader(f_in) headers = next(reader) for h in headers: if h not in fieldnames: fieldnames.append(h) # Then copy the data with open("out.csv", "w", newline="") as f_out: # Comment 2 below writer = csv.DictWriter(f_out, fieldnames=fieldnames) for filename in inputs: with open(filename, "r", newline="") as f_in: reader = csv.DictReader(f_in) # Uses the field names in this file for line in reader: # Comment 3 below writer.writerow(line) ```<issue_comment>username_1: The scope of the object `users` is the sub-statement of the if statement. ``` if(search != sd.end()) { std::set users = search->second; } ``` Outside the scope of the if statement the name `users` is undefined. In fact the function design is wrong. You should rewrite the function body. Upvotes: 2 <issue_comment>username_2: As username_1 pointed out, once the `if` scope ends, your `users` variable cease to exist, therefore you get the error when you are trying to use it outside of `if` scope. I would rewrite your function to make it more clear: ``` bool DeleteConnection(ServerData &sd, ServerName sn, UserName un) { auto search = sd.find(sn); if (search == sd.end()) return false; std::set users = search->second; if (users.find(un) == users.end()) return false; users.erase(un); sd[sn] = users; return true; } ``` Upvotes: 3 [selected_answer]
2018/03/17
839
3,105
<issue_start>username_0: How do I create a Timer? For my project I have to create a Timer, which is counting down, but ```cs Task.Delay(); System.Threating.Threat.Sleep(); ``` is not working, because it stops the whole application and I need it to stay responsive, for my timer to visually decrease. The Timer seems to also not to work, because when I use the Example from [<NAME>](https://stackoverflow.com/questions/12535722/what-is-the-best-way-to-implement-a-timer), then I get an error, that the namespace "Forms" is not present. The Timer Code -------------- ```cs System.Windows.Forms.Timer t = new System.Windows.Forms.Timer(); t.Interval = 15000; // specify interval time as you want t.Tick += new EventHandler(timer_Tick); t.Start(); void timer_Tick(object sender, EventArgs e) { //Call method } ```<issue_comment>username_1: Use a DispatcherTimer: ``` using System.Windows.Threading; ... var t = new DispatcherTimer(); t.Interval = TimeSpan.FromSeconds(15); t.Tick += timer_Tick; t.Start(); void timer_Tick(object sender, EventArgs e) { } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: There is over a half dozen Timer classes in .NET. Some are for specific Environments (like WebDevelopment). And most are different in where the counting is done (UI or Worker Thread) and thus if they have "Metronome Quality" and where the Tick event is raised (UI Thread or worker thread) and thus if you ahve to deal with Invocation and if their processing can be delayed by a busy UI Thread. System.Windows.Forms.Timer is specificall Designed for Windows Forms and one of the Simpler ones. As the name implies, it is part of hte Windows Forms related .DLL's and namespaces. As you work with WPF, you do not have those avalible by default (but can add them). The primary Timer for WPF is the Dispatcher Timer, wich works pretty similar to the WindowsForms one (counting and Tick Raise on UI thread). See username_1 Answer or the example for it. Task.Delay and Thread.Sleep are not timers per say. They deal with adding a Delay to a Multitasking or Multithreading approaches Respectively. But if you do not ahve Multitasking or -Threading, you only end up stoppin your main thread. What Gusman wrote is adding Multitasking to the whole thing. Multitasking however is a tricky area you might not yet be ready for. While they are very important to learn, tehy are not beginners topics. You should propably stay at timers for now. Upvotes: 2 <issue_comment>username_3: If you use **System.Timers.Timer**, then here's an example ``` System.Timers.Timer t = new System.Timers.Timer(); t.Elapsed += new ElapsedEventHandler(Work); t.Interval = 10; t.Enabled = true; private void Work(object sender, ElapsedEventArgs e) { //[Thread safety] if (!Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke((ElapsedEventHandler)Work, sender, e); return; } Task task = Task.Run(() => { // Your non UI work Dispatcher.BeginInvoke((Action)delegate () { // Your UI work }); }); } ``` Upvotes: -1
2018/03/17
1,062
3,194
<issue_start>username_0: I've been working on a single line of code for three days and I found out it seems the memory allocated not as I supposed. I have a `Buffer` class which owns two `int` variables and a `*float` pointer, which I think takes up 16 bytes in memory. I also have a `Film` class which holds two `int` variables, two `Vec3f` variables, and a `Buffer*` pointer. `Vec3f` is a class which holds three `float` variables. Class definitions are as follows: ``` class Buffer { public: int _width; int _heigth; Vec3f *_data; Buffer(int w, int h) : _width(w), _height(h) { _data = new Vec3f(_width*_heigth); } ~Buffer(); }; struct Film { int _width; int _height; Vec3f _left_bottom_corner; Vec3f _left_up_corner; Buffer *_cbuffer; Film(int w, int h, Buffer *cbuffer) : _width(w), _height(h), _cbuffer(cbuffer) {} }; template class Vector { private: std::array \_v; }; typedef Vector Vec3f; ``` And I initialize them like this: ``` int w = 5; int h = 5; Buffer *b = new Buffer(w, h); Film *film = new Film(w, h, b); ``` Something weird happened when I tried to assign values to `film->_cbuffer->data[i]` so I debugged the program ``` std::cout << b << std::endl; std::cout << b->_data << std::endl; std::cout << film << std::endl; ``` and the output is ``` 0x7fa500500000 0x7fa500600000 0x7fa500600010 ``` I think a `Buffer` instance should take up 16 bytes and a `Film` instance should take up to **4\*2 + 4\*3\*2 + 8** bytes. But what really matters is the size of `Buffer._data` array, which I allocated manually with `new` operator. From the given result the array takes up to 16 bytes and this is fixed for all `w` and `h` I've tested and this is not what I suppose. Take `w=5, h=5` for example, the size of the array should be **5 \* 5 \* 8** . For the memory allocated like this, `film._width` would be modified when When `w` and `h` are both set to `1`, the memory is allocated "right" accidentally: ``` 0x7f90b9d00000 0x7f90b9d00010 0x7f90b9d00020 ```<issue_comment>username_1: Do you not see a problem here? ``` Buffer(int w, int h) { _data = new Vec3f(_width*_heigth); } ``` Is it not strange that uninitialized `_width` and `_heigth` used? Probably you want: ``` Buffer(int w, int h): _width(w), _heigth(h) { _data = new Vec3f[_width*_heigth]; } ``` The line below outputs the address of `Vec3f` array pointed by `_data`. ``` std::cout << b->_data << std::endl; ``` If you are going to look at the address of `_data` within the `Buffer` object, it should be ``` std::cout << &b->_data << std::endl; ``` Upvotes: 3 <issue_comment>username_2: `new Vec3f(_width*_heigth)` doesn't initialize any array of variable length. The size of `Vec3f` array field is always 3, and this is probably not what you want in your buffer constructor. BTW, you don't have any `Vector::Vector(some_kind_of_int)` constructor at all. Probably you want to use (runtime-known size) `std::vector` in your buffer instead of something based on (compiletime-known constant (AKA `constexpr`) length) `std::array`. Upvotes: 3 [selected_answer]
2018/03/17
628
2,154
<issue_start>username_0: I'm learning Python (3.6.3) and making a silly (and very linear) chatbot to get started. At one point the chatbot asks you to guess its age, I used randint to generate a number between 1-1000 and want to use the outputted random integer in an if statement (so the chat bot is either happy or upset by your answer, depending on whether you thought it was older than it really is). The user's input is a var called guess and I assumed (as I cannot find a similar example online) that I could just reference guess and the randint in an if statement to print the desired output, but I get an error advising radint is not defined when I run the prog - ``` print('guess how old I am') guess = input() import random for x in range(1): time.sleep(0.4) print ('nope, I\'m ' + (str(random.randint(1,1000))) + ' actually') time.sleep(0.88) if randint <= guess print('(so rude...)') else: print('aw thanks') ``` Apologies if my StackExchange syntax is broken too, any help appreciated, thanks<issue_comment>username_1: Do you not see a problem here? ``` Buffer(int w, int h) { _data = new Vec3f(_width*_heigth); } ``` Is it not strange that uninitialized `_width` and `_heigth` used? Probably you want: ``` Buffer(int w, int h): _width(w), _heigth(h) { _data = new Vec3f[_width*_heigth]; } ``` The line below outputs the address of `Vec3f` array pointed by `_data`. ``` std::cout << b->_data << std::endl; ``` If you are going to look at the address of `_data` within the `Buffer` object, it should be ``` std::cout << &b->_data << std::endl; ``` Upvotes: 3 <issue_comment>username_2: `new Vec3f(_width*_heigth)` doesn't initialize any array of variable length. The size of `Vec3f` array field is always 3, and this is probably not what you want in your buffer constructor. BTW, you don't have any `Vector::Vector(some_kind_of_int)` constructor at all. Probably you want to use (runtime-known size) `std::vector` in your buffer instead of something based on (compiletime-known constant (AKA `constexpr`) length) `std::array`. Upvotes: 3 [selected_answer]
2018/03/17
1,988
6,944
<issue_start>username_0: Is there a way to import a CSS file into a styled component? One of my dependencies, [React Quill Editor](https://github.com/zenoamaro/react-quill), is themeable by importing their CSS as a base and applying changes on top of it. All of my components are styled components, and I'd like to keep the CSS localized to the JS component rather than import the CSS as a 'global' style. Right now I've take to copying their CSS into my own file in the following form. I've written a brief example below. ``` /** editorCSS.js **/ import { css } from 'styled-components'; export default css` /* copied CSS here */ .class-to-extend { color: green; } ` /** EditorComponent.js **/ import styled from 'styled-components'; import ReactQuill from 'react-quill'; import editorCSS from './editorCSS'; const StyledReactQuill = styled(ReactQuill)` ${editorCSS} /** Additional customization if necessary (e.g. positioning) */ ` export default StyledReactQuill; ` ``` I'd much rather import reference their css file in the scope of the styled component vs copying it. If I do `import ReactQuillCSS from 'react-quill/dist/quill.snow.css';` it will still apply my css globally due to the `css-loader` plugin. Best, Daniel<issue_comment>username_1: As far as I know there is no way to import regular CSS just in scope. The way I have combined styled-components with CSS from libraries so far is to give your own styled component a className in the jsx. ```js const MyStyledComponent = styled(ComponentFromLibrary)` color: red; `; // and in the render function return ( ); ``` Another example can be found in the official documentation: <https://www.styled-components.com/docs/advanced#existing-css> What you are proposing would work if editorCSS is just a string of the styles you want to apply to the component. Upvotes: -1 <issue_comment>username_2: This is how I did: Code ---- ``` import React, { Component } from "react"; import ReactDOM from "react-dom"; import Styled from "styled-components"; const fetchStyles = () => fetch( "https://gist.githubusercontent.com/bionicvapourboy/61d3d7a8546cb42e0e3194eb9505f48a/raw/5432218dd83320d53d1cbc2f230b81c765183585/style.css" ).then(response => response.text()); class App extends Component { state = { style: "" }; componentDidMount() { fetchStyles().then(data => this.setState({ style: data })); } Wrapper = () => Styled.div` ${this.state.style} `; render() { const Wrapper = this.Wrapper(); return ( Styled ====== Not Styled ========== Start editing to see some magic happen! --------------------------------------- ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement); ``` Demo ---- <https://codesandbox.io/s/yw7xmx6x3x> Upvotes: 0 <issue_comment>username_3: From my understanding styled-components is just essentially template literals anyways. Your only issue should be that the imported css is defined as an object when you try to place it into your components css. Have you tried typecasting it to a string first? ``` /** EditorComponent.js **/ import styled from 'styled-components'; import ReactQuill from 'react-quill'; import editorCSS from './editorCSS'; const newCSS = editorCSS.toString(); export default Styled(ReactQuill)` ${newCSS} `; ``` Upvotes: -1 <issue_comment>username_4: In order to achieve that you would need to use a different loader than `css-loader`. You could write an different loader which prepares it for `styled-components` rather than adding it to the global style sheet. If you need `css-loader`, you would however need to define which css files are handled by it and which ones are loaded for styled-components, which makes it not really practical imho. Upvotes: 1 <issue_comment>username_5: You could use [raw-loader](https://github.com/webpack-contrib/raw-loader) to load the `quill.snow.css` stylesheet and then include it in your styled component. ``` /** EditorComponent.js **/ import styled from 'styled-components'; import ReactQuill from 'react-quill'; import quillCSS from '!!raw-loader!react-quill/dist/quill.snow.css'; const StyledReactQuill = styled(ReactQuill)` ${quillCSS} /** Additional customization if necessary (e.g. positioning) */ ` export default StyledReactQuill; ``` Per the `raw-loader` docs, you can use `!!` to prevent the styles being added globally via `css-loader` > > Adding `!!` to a request will disable all loaders specified in the configuration > > > Upvotes: 3 <issue_comment>username_6: You can add a [module rule](https://webpack.js.org/configuration/module/#modulerules) to import styles locally from a CSS file into a styled component. E.g. import all third party `.css` files from `node_modules` as [raw string](https://webpack.js.org/loaders/css-loader/#tostring), others as usual: ``` // webpack.config.js const config = { module: { rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"], // load project styles via style-loader exclude: /node_modules/, }, { test: /\.css$/, use: ["to-string-loader", "css-loader"], // use to-string-loader for 3rd party css include: /node_modules/, }, // ... ], }, // ... } ``` Usage: ``` import styled from 'styled-components'; import ReactQuill from 'react-quill'; import ReactQuillCSS from 'react-quill/dist/quill.snow.css' // no custom webpack syntax const StyledReactQuill = styled(ReactQuill)` ${ReactQuillCSS} // ... other styles ` ``` Don't forget to install `to-string-loader`, if not used yet. --- This has some advantages over @username_5's [solution](https://stackoverflow.com/a/58983746/5669456): * One central config file determines, how to process `.css` files * Follow Webpack recommendations: > > Use **module.rules** whenever possible, as this will reduce boilerplate in your source code and allow you to debug or locate a loader faster if something goes south. ([docs](https://webpack.js.org/concepts/loaders/#inline)) > > > * Avoid ESLint errors - take a look at the [Codesandbox](https://codesandbox.io/s/so-49337702-n3og3?file=/src/App.js) demo * `css-loader` can still resolve `@import` and `url()` for external CSS files, `raw-loader` won't Upvotes: 3 <issue_comment>username_7: The simplest solution I used in my case without extra loaders is to go to the CSS file and copy past the beautified version. For example, you have `lib/dit/lib.min.css` with `body{background:red}` Then just copy all CSS to your styled component or global styled component styles: ``` styled.div` body{ background: red; } ` ``` > > ❗️ Disadvantages: a new version of package can have modified lib.css so you will have to repeat the operation; lib CSS complexity. > > > > > ✅ Advantages: no extra loaders; you can refactor lib.css directly. > > > Upvotes: 0
2018/03/17
1,899
6,563
<issue_start>username_0: So far I can only manage to delete the first id (in this case the id with "12345"). Im trying to delete the row with `id` 2 within `books`-array ``` Libary Table: { "_id": { "$oid": "12345" }, "libaryName": "A random libary", "Books": [ { "_id": { "$oid": "1" } "bookTitle": "Example", "TotalPages": "500" }, { "_id": { "$oid": "2" } "bookTitle": "Delete Me", "TotalPages": "400" } ] } ``` My delete code: ``` router.delete('/:id', (req, res) => { Libary.remove({ _id: req.params.id }) .then(() => { //redirect }); }); ``` How can I reach and delete the book row where the `id` is 2?<issue_comment>username_1: As far as I know there is no way to import regular CSS just in scope. The way I have combined styled-components with CSS from libraries so far is to give your own styled component a className in the jsx. ```js const MyStyledComponent = styled(ComponentFromLibrary)` color: red; `; // and in the render function return ( ); ``` Another example can be found in the official documentation: <https://www.styled-components.com/docs/advanced#existing-css> What you are proposing would work if editorCSS is just a string of the styles you want to apply to the component. Upvotes: -1 <issue_comment>username_2: This is how I did: Code ---- ``` import React, { Component } from "react"; import ReactDOM from "react-dom"; import Styled from "styled-components"; const fetchStyles = () => fetch( "https://gist.githubusercontent.com/bionicvapourboy/61d3d7a8546cb42e0e3194eb9505f48a/raw/5432218dd83320d53d1cbc2f230b81c765183585/style.css" ).then(response => response.text()); class App extends Component { state = { style: "" }; componentDidMount() { fetchStyles().then(data => this.setState({ style: data })); } Wrapper = () => Styled.div` ${this.state.style} `; render() { const Wrapper = this.Wrapper(); return ( Styled ====== Not Styled ========== Start editing to see some magic happen! --------------------------------------- ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement); ``` Demo ---- <https://codesandbox.io/s/yw7xmx6x3x> Upvotes: 0 <issue_comment>username_3: From my understanding styled-components is just essentially template literals anyways. Your only issue should be that the imported css is defined as an object when you try to place it into your components css. Have you tried typecasting it to a string first? ``` /** EditorComponent.js **/ import styled from 'styled-components'; import ReactQuill from 'react-quill'; import editorCSS from './editorCSS'; const newCSS = editorCSS.toString(); export default Styled(ReactQuill)` ${newCSS} `; ``` Upvotes: -1 <issue_comment>username_4: In order to achieve that you would need to use a different loader than `css-loader`. You could write an different loader which prepares it for `styled-components` rather than adding it to the global style sheet. If you need `css-loader`, you would however need to define which css files are handled by it and which ones are loaded for styled-components, which makes it not really practical imho. Upvotes: 1 <issue_comment>username_5: You could use [raw-loader](https://github.com/webpack-contrib/raw-loader) to load the `quill.snow.css` stylesheet and then include it in your styled component. ``` /** EditorComponent.js **/ import styled from 'styled-components'; import ReactQuill from 'react-quill'; import quillCSS from '!!raw-loader!react-quill/dist/quill.snow.css'; const StyledReactQuill = styled(ReactQuill)` ${quillCSS} /** Additional customization if necessary (e.g. positioning) */ ` export default StyledReactQuill; ``` Per the `raw-loader` docs, you can use `!!` to prevent the styles being added globally via `css-loader` > > Adding `!!` to a request will disable all loaders specified in the configuration > > > Upvotes: 3 <issue_comment>username_6: You can add a [module rule](https://webpack.js.org/configuration/module/#modulerules) to import styles locally from a CSS file into a styled component. E.g. import all third party `.css` files from `node_modules` as [raw string](https://webpack.js.org/loaders/css-loader/#tostring), others as usual: ``` // webpack.config.js const config = { module: { rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"], // load project styles via style-loader exclude: /node_modules/, }, { test: /\.css$/, use: ["to-string-loader", "css-loader"], // use to-string-loader for 3rd party css include: /node_modules/, }, // ... ], }, // ... } ``` Usage: ``` import styled from 'styled-components'; import ReactQuill from 'react-quill'; import ReactQuillCSS from 'react-quill/dist/quill.snow.css' // no custom webpack syntax const StyledReactQuill = styled(ReactQuill)` ${ReactQuillCSS} // ... other styles ` ``` Don't forget to install `to-string-loader`, if not used yet. --- This has some advantages over @username_5's [solution](https://stackoverflow.com/a/58983746/5669456): * One central config file determines, how to process `.css` files * Follow Webpack recommendations: > > Use **module.rules** whenever possible, as this will reduce boilerplate in your source code and allow you to debug or locate a loader faster if something goes south. ([docs](https://webpack.js.org/concepts/loaders/#inline)) > > > * Avoid ESLint errors - take a look at the [Codesandbox](https://codesandbox.io/s/so-49337702-n3og3?file=/src/App.js) demo * `css-loader` can still resolve `@import` and `url()` for external CSS files, `raw-loader` won't Upvotes: 3 <issue_comment>username_7: The simplest solution I used in my case without extra loaders is to go to the CSS file and copy past the beautified version. For example, you have `lib/dit/lib.min.css` with `body{background:red}` Then just copy all CSS to your styled component or global styled component styles: ``` styled.div` body{ background: red; } ` ``` > > ❗️ Disadvantages: a new version of package can have modified lib.css so you will have to repeat the operation; lib CSS complexity. > > > > > ✅ Advantages: no extra loaders; you can refactor lib.css directly. > > > Upvotes: 0
2018/03/17
1,761
6,053
<issue_start>username_0: I ran this code and I don't understand how the output is `2`? As far as I'm concerned the output should always be `1`? Code: ``` (define (count p l) (if (empty? l) 0 (if (p (first l)) (+l (count p (rest l))) (count p (rest l))))) (define (ident x) x) (count ident '(#true #true #false)) ```<issue_comment>username_1: As far as I know there is no way to import regular CSS just in scope. The way I have combined styled-components with CSS from libraries so far is to give your own styled component a className in the jsx. ```js const MyStyledComponent = styled(ComponentFromLibrary)` color: red; `; // and in the render function return ( ); ``` Another example can be found in the official documentation: <https://www.styled-components.com/docs/advanced#existing-css> What you are proposing would work if editorCSS is just a string of the styles you want to apply to the component. Upvotes: -1 <issue_comment>username_2: This is how I did: Code ---- ``` import React, { Component } from "react"; import ReactDOM from "react-dom"; import Styled from "styled-components"; const fetchStyles = () => fetch( "https://gist.githubusercontent.com/bionicvapourboy/61d3d7a8546cb42e0e3194eb9505f48a/raw/5432218dd83320d53d1cbc2f230b81c765183585/style.css" ).then(response => response.text()); class App extends Component { state = { style: "" }; componentDidMount() { fetchStyles().then(data => this.setState({ style: data })); } Wrapper = () => Styled.div` ${this.state.style} `; render() { const Wrapper = this.Wrapper(); return ( Styled ====== Not Styled ========== Start editing to see some magic happen! --------------------------------------- ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement); ``` Demo ---- <https://codesandbox.io/s/yw7xmx6x3x> Upvotes: 0 <issue_comment>username_3: From my understanding styled-components is just essentially template literals anyways. Your only issue should be that the imported css is defined as an object when you try to place it into your components css. Have you tried typecasting it to a string first? ``` /** EditorComponent.js **/ import styled from 'styled-components'; import ReactQuill from 'react-quill'; import editorCSS from './editorCSS'; const newCSS = editorCSS.toString(); export default Styled(ReactQuill)` ${newCSS} `; ``` Upvotes: -1 <issue_comment>username_4: In order to achieve that you would need to use a different loader than `css-loader`. You could write an different loader which prepares it for `styled-components` rather than adding it to the global style sheet. If you need `css-loader`, you would however need to define which css files are handled by it and which ones are loaded for styled-components, which makes it not really practical imho. Upvotes: 1 <issue_comment>username_5: You could use [raw-loader](https://github.com/webpack-contrib/raw-loader) to load the `quill.snow.css` stylesheet and then include it in your styled component. ``` /** EditorComponent.js **/ import styled from 'styled-components'; import ReactQuill from 'react-quill'; import quillCSS from '!!raw-loader!react-quill/dist/quill.snow.css'; const StyledReactQuill = styled(ReactQuill)` ${quillCSS} /** Additional customization if necessary (e.g. positioning) */ ` export default StyledReactQuill; ``` Per the `raw-loader` docs, you can use `!!` to prevent the styles being added globally via `css-loader` > > Adding `!!` to a request will disable all loaders specified in the configuration > > > Upvotes: 3 <issue_comment>username_6: You can add a [module rule](https://webpack.js.org/configuration/module/#modulerules) to import styles locally from a CSS file into a styled component. E.g. import all third party `.css` files from `node_modules` as [raw string](https://webpack.js.org/loaders/css-loader/#tostring), others as usual: ``` // webpack.config.js const config = { module: { rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"], // load project styles via style-loader exclude: /node_modules/, }, { test: /\.css$/, use: ["to-string-loader", "css-loader"], // use to-string-loader for 3rd party css include: /node_modules/, }, // ... ], }, // ... } ``` Usage: ``` import styled from 'styled-components'; import ReactQuill from 'react-quill'; import ReactQuillCSS from 'react-quill/dist/quill.snow.css' // no custom webpack syntax const StyledReactQuill = styled(ReactQuill)` ${ReactQuillCSS} // ... other styles ` ``` Don't forget to install `to-string-loader`, if not used yet. --- This has some advantages over @username_5's [solution](https://stackoverflow.com/a/58983746/5669456): * One central config file determines, how to process `.css` files * Follow Webpack recommendations: > > Use **module.rules** whenever possible, as this will reduce boilerplate in your source code and allow you to debug or locate a loader faster if something goes south. ([docs](https://webpack.js.org/concepts/loaders/#inline)) > > > * Avoid ESLint errors - take a look at the [Codesandbox](https://codesandbox.io/s/so-49337702-n3og3?file=/src/App.js) demo * `css-loader` can still resolve `@import` and `url()` for external CSS files, `raw-loader` won't Upvotes: 3 <issue_comment>username_7: The simplest solution I used in my case without extra loaders is to go to the CSS file and copy past the beautified version. For example, you have `lib/dit/lib.min.css` with `body{background:red}` Then just copy all CSS to your styled component or global styled component styles: ``` styled.div` body{ background: red; } ` ``` > > ❗️ Disadvantages: a new version of package can have modified lib.css so you will have to repeat the operation; lib CSS complexity. > > > > > ✅ Advantages: no extra loaders; you can refactor lib.css directly. > > > Upvotes: 0
2018/03/17
768
2,491
<issue_start>username_0: Trying to learn 3D programming, I am currently implementing a class which batch-renders cubes with OpenGL by pushing them to the GPU each frame. I tried to implement some crude lighting by 1) Sending each face normal to the GPU as part of the vertex attributes 2) Checking the direction of said normal and darken each fragment arbitrarily, like so: **Fragment Shader** ``` #version 330 in vec2 ex_TexCoord; in vec3 ex_Normal; out vec4 out_Color; uniform sampler2D textureSampler; void main(void) { float lightAmplifier = 1.0; if (ex_Normal.z == 1.0) { lightAmplifier = .8; } else if (ex_Normal.x == 1.0) { lightAmplifier = .65; } else if (ex_Normal.x == -1.0) { lightAmplifier = .50; } out_Color = vec4(texture2D(textureSampler, ex_TexCoord).rgb * lightAmplifier, 1.0); } ``` Resulting in this: [![Screenshot](https://i.stack.imgur.com/grRfS.png)](https://i.stack.imgur.com/grRfS.png) While not being very good at GLSL, my intuition says this is not correct behaviour. But a number google searches later, I'm still not sure what I'm doing wrong.<issue_comment>username_1: This is a floating point precision issue. Note the vertex coordinates are interpolated when for each fragment. It may always lead to issues, when comparing floating point numbers on equality. On possible solution would be to use an epsilon (e.g. 0.01) and to change the comparison to `< -0.99` and `> 0.99`: ``` if (ex_Normal.z > 0.99) { lightAmplifier = .8; } else if (ex_Normal.x > 0.99) { lightAmplifier = .65; } else if (ex_Normal.x < -0.99) { lightAmplifier = .50; } ``` Another possibility would be to use the [`flat`](https://www.khronos.org/opengl/wiki/Type_Qualifier_(GLSL)#Shader_stage_inputs_and_outputs) interpolation qualifier, which causes the value not to be interpolated: Vertex shader: ``` flat out vec3 ex_Normal; ``` Fragment shader: ``` flat in vec3 ex_Normal; ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: username_1 is (probably) right about the erroneous appearance being a result of floating point accuracy/precision. What I'd like to add is that setting a constant value based on testing an interpolated value is rarely a good idea (some algorithms do depend on it though, e.g. shadow mapping). Changing the test from `==1` to `>=0.99` just puts the error at 0.99 intead of at 1.0. It is more likely you want to interpolate the value when it enters a certain range, e.g. by using `mix`. Upvotes: 2
2018/03/17
1,137
4,054
<issue_start>username_0: There are two `QListWidget` with the same number of the items. How can synchronize their scrolling? I mean when I scroll one of them, the other one should get same scrolling.<issue_comment>username_1: You must use the `valueChanged()` signal from the `verticalScrollBar()` of `QListWidget`, since the connection is bidirectional, it will cause unnecessary tasks to be executed for it using `blockSignals()`: In the next section I show an example: ``` #include #include #include #include class Widget: public QWidget{ Q\_OBJECT QListWidget w1; QListWidget w2; public: Widget(QWidget \*parent=Q\_NULLPTR):QWidget(parent){ auto layout = new QHBoxLayout{this}; layout->addWidget(&w1); layout->addWidget(&w2); connect(w1.verticalScrollBar(), &QScrollBar::valueChanged, [this](int value){ w2.verticalScrollBar()->blockSignals(true); w2.verticalScrollBar()->setValue(value); w2.verticalScrollBar()->blockSignals(false); }); connect(w2.verticalScrollBar(), &QScrollBar::valueChanged, [this](int value){ w1.verticalScrollBar()->blockSignals(true); w1.verticalScrollBar()->setValue(value); w1.verticalScrollBar()->blockSignals(false); }); for(int i=0; i<100; i++){ w1.addItem(QString("item %1 of 1").arg(i)); w2.addItem(QString("item %1 of 2").arg(i)); } } }; int main(int argc, char \*argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); } #include "main.moc" ``` Upvotes: 2 <issue_comment>username_2: Suppose you have two `QListWidget` elements `listWidget_1` and `listWidget_2` in your `UI`, then you can use `valueChanged`/`setValue` signal/slot pair to connect vertical sliders of both listwidgets, indeed, I didn't find any issue of signals re-bouncing in this "two way" connection because eventually both values will be same and I think no more signals would be emitted, thus you can set such sufficient connections: ``` connect(this->ui->listWidget_1->verticalScrollBar(), &QScrollBar::valueChanged, this->ui->listWidget_2->verticalScrollBar(), &QScrollBar::setValue); connect(this->ui->listWidget_2->verticalScrollBar(), &QScrollBar::valueChanged, this->ui->listWidget_1->verticalScrollBar(), &QScrollBar::setValue); // test lists: QList lw11, lw22; for (int x=0; x <200; x++){ lw11.append("ListWidget1\_" + QVariant(x).toString()); lw22.append("The Other lw is at: " + QVariant(x).toString()); } this->ui->listWidget\_1->addItems(lw11); this->ui->listWidget\_2->addItems(lw22); ``` --- If signal rebounce should be blocked anyway, then the model can be adjusted by adding a single `slot` to handle scrolling for both widgets and connect both to that slot: ``` connect(this->ui->listWidget_1->verticalScrollBar(),&QScrollBar::valueChanged , this, &MainWindow::handleScroll); connect(this->ui->listWidget_2->verticalScrollBar(),&QScrollBar::valueChanged , this, &MainWindow::handleScroll); ``` and the slot logic can be : ``` void MainWindow::handleScroll(int value) { // Logic for detecting sender() can be used ... but I don't see it's important // fast way to check which listWidget emitted the signal ... if (this->ui->listWidget_1->verticalScrollBar()->value() == value){ qDebug() << "lw1 is in charge ..............."; disconnect(this->ui->listWidget_2->verticalScrollBar(), &QScrollBar::valueChanged,this, &MainWindow::handleScroll); // prevent signal rebounce from the other lw this->ui->listWidget_2->verticalScrollBar()->setValue(value); connect(this->ui->listWidget_2->verticalScrollBar(), &QScrollBar::valueChanged,this, &MainWindow::handleScroll); }else{ qDebug() << "lw2 is in charge ..............."; disconnect(this->ui->listWidget_1->verticalScrollBar(), &QScrollBar::valueChanged,this, &MainWindow::handleScroll); this->ui->listWidget_1->verticalScrollBar()->setValue(value); connect(this->ui->listWidget_1->verticalScrollBar(), &QScrollBar::valueChanged,this, &MainWindow::handleScroll); } } ``` Upvotes: 3 [selected_answer]
2018/03/17
578
2,188
<issue_start>username_0: I have the following tables: ``` Table "Staff" StaffID StaffName Table "AssignedStaff" StaffID EventID Table "Events" EventID Date ``` I want to display the details of all Staff members except those where there is an association with an Event with a specified Date value. I've tried the following: ``` SELECT Staff.StaffID, StaffName FROM Staff LEFT JOIN AssignedStaff ON Staff.StaffID = AssignedStaff.StaffID INNER JOIN Events ON AssignedStaff.EventID = Events.EventID WHERE NOT Date='xxx' ``` But this only selects staff members which have records in the AssignedStaff table, and not the entire list of staff. How might I fix this?<issue_comment>username_1: > > I want to display the details of all Staff members except those where there is an association with an Event with a specified Date value. > > > Use `LEFT JOIN`s all the way through and then check for a non-match. The key is moving the date condition to the `ON` clause: ``` SELECT s.StaffID, s.StaffName FROM Staff s LEFT JOIN AssignedStaff ast ON s.StaffID = ast.StaffID LEFT JOIN Events e ON ast.EventID = e.EventID AND e.DATE = ? WHERE e.EventID IS NULL; ``` Note: This removes *all* events on that date, so you may need more conditions to specify the exact event. Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` SELECT * from Staff, AssignedStaff, Events where Staff.StaffID = AssignedStaff.StaffID And AssignedStaff.EventID = Events.EvebtID And Events.Data <> XXX ``` Upvotes: -1 <issue_comment>username_3: This should work ``` SELECT Staff.StaffID, StaffName FROM Staff LEFT JOIN AssignedStaff ON Staff.StaffID = AssignedStaff.StaffID LEFT JOIN Events ON AssignedStaff.EventID = Events.EventID AND Date <> 'yyyy.mm.dd' ``` You may be looking for this ``` SELECT Staff.StaffID, StaffName FROM Staff where not exists ( select 1 from AssignedStaff JOIN Events ON AssignedStaff.EventID = Events.EventID AND Date = 'yyyy.mm.dd' where Staff.StaffID = AssignedStaff.StaffID ) ``` Upvotes: 0
2018/03/17
684
2,528
<issue_start>username_0: I have set up an Azure WebApp (Linux) to run a WordPress and an other handmade PHP app on it. All works fine but I get this weird CPU usage graph (see below). Both apps are PHP7.0 containers. SSHing in to the two containers and using top I see no unusual CPU hogging processes. When I reset both apps the CPU goes back to normal and then starts to raise slowly as shown below. The amount of HTTP requests to the apps has not relation to the CPU usage at all. I tried to use apache2ctl to see if there are any pending requests but that seems not possible to do inside a docker container. Anybody got an idea how to track down the cause of this? [![CPU usage](https://i.stack.imgur.com/BTWJB.png)](https://i.stack.imgur.com/BTWJB.png) This is the top output. The instance has 2 cores. Lots of idle time but still over 100% load and none of the processes use the CPU ... [![enter image description here](https://i.stack.imgur.com/Atldy.png)](https://i.stack.imgur.com/Atldy.png)<issue_comment>username_1: > > I want to display the details of all Staff members except those where there is an association with an Event with a specified Date value. > > > Use `LEFT JOIN`s all the way through and then check for a non-match. The key is moving the date condition to the `ON` clause: ``` SELECT s.StaffID, s.StaffName FROM Staff s LEFT JOIN AssignedStaff ast ON s.StaffID = ast.StaffID LEFT JOIN Events e ON ast.EventID = e.EventID AND e.DATE = ? WHERE e.EventID IS NULL; ``` Note: This removes *all* events on that date, so you may need more conditions to specify the exact event. Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` SELECT * from Staff, AssignedStaff, Events where Staff.StaffID = AssignedStaff.StaffID And AssignedStaff.EventID = Events.EvebtID And Events.Data <> XXX ``` Upvotes: -1 <issue_comment>username_3: This should work ``` SELECT Staff.StaffID, StaffName FROM Staff LEFT JOIN AssignedStaff ON Staff.StaffID = AssignedStaff.StaffID LEFT JOIN Events ON AssignedStaff.EventID = Events.EventID AND Date <> 'yyyy.mm.dd' ``` You may be looking for this ``` SELECT Staff.StaffID, StaffName FROM Staff where not exists ( select 1 from AssignedStaff JOIN Events ON AssignedStaff.EventID = Events.EventID AND Date = 'yyyy.mm.dd' where Staff.StaffID = AssignedStaff.StaffID ) ``` Upvotes: 0
2018/03/17
2,311
7,151
<issue_start>username_0: How to create directory tree in *Perl* to comply with *Fancytree* expected JSON [format](https://github.com/mar10/fancytree/wiki#define-the-tree-data)? This is the *Perl* part I came up with, that traverses through given path: ``` sub get_tree { my ($gpath) = @_; my %r; use File::Find; my $c = sub { my $dir = $File::Find::dir; my $r = \%r; my $tdir = $dir; $tdir =~ s|^\Q$gpath\E/?||; $r = $r->{$_} ||= {} for split m|/|, $tdir; }; find($c, $gpath); return \%r; } ``` It returns the following result after JSON encode: ``` { "dir3":{ }, "dir1":{ "sub-dir2":{ }, "sub-dir1":{ } }, "dir2":{ "sub-dir1":{ "sub-sub-dir1":{ "sub-sub-sub-dir1":{ } } } } } ``` The expected result for *Fancytree* to comply with its JSON [format](https://github.com/mar10/fancytree/wiki#define-the-tree-data) is: ``` [ {"parent": "dir3"}, {"parent": "dir2", "child": [ {"parent": "sub-dir1", "child": [ {"parent": "sub-sub-dir1", "child": [ {"parent": "sub-sub-sub-dir1"} ]} ]} ]}, {"parent": "dir1", "child": [ {"parent": "sub-dir1"}, {"parent": "sub-dir1"} ]} ] ``` The point is to do it in a single run, without post processing, which would be ideal. Any help of how to achieve that?<issue_comment>username_1: I guess the following would produce the structure you wanted. **test.pl** ``` use strict; use warnings; use JSON; sub get_json { return JSON->new->latin1->pretty->encode(@_); } sub get_tree { my ($gpath) = @_; my (%r,@rr); use File::Find; my $c = sub { my $dir = $File::Find::name; my $r = \%r; my $rr = \@rr; my $tdir = $dir; $tdir =~ s|^\Q$gpath\E/?||; my $previtem; for my $item(split m|/|, $tdir) { if ($previtem) { $rr=$r->{$previtem}[1]{child}//=[]; $r= $r->{$previtem}[0]{child}//={}; } $r->{$item} //= [ { }, $rr->[@$rr]= { parent=>$item } ]; $previtem = $item; } }; find($c, $gpath); return \%r,\@rr; } my ($r,$rr) = get_tree($ARGV[0]); print get_json($rr); ``` **output** ``` [ { "parent" : "test.pl" }, { "parent" : "dir1", "child" : [ { "parent" : "sub-dir1" }, { "parent" : "sub-dir2" } ] }, { "parent" : "dir2", "child" : [ { "parent" : "sub-dir1", "child" : [ { "parent" : "sub-sub-dir1" } ] } ] }, { "parent" : "dir3" } ] ``` --- I've run it: `perl test.pl .`. So you see 'test.pl' in the output In case you want to traverse only directories, change the find call to: ``` find({wanted=>$c, preprocess=> sub { grep { -d $_ } @_; } }, $gpath); ``` Upvotes: 1 <issue_comment>username_2: Using recursion instead of File::Find, using [Path::Tiny](http://p3rl.org/Path::Tiny) to handle paths: ``` #!/usr/bin/perl use warnings; use strict; use Path::Tiny; sub get_tree { my ($struct, $root, @path) = @_; for my $child (path($root, @path)->children) { if (-d $child) { my $base = $child->basename; push @$struct, { parent => $base }; my $recurse = get_tree($struct->[-1]{child} = [], $root, @path, $base); delete $struct->[-1]{child} unless @$recurse; } } return $struct } use Test::More tests => 1; use Test::Deep; my $expected = bag({parent => 'dir1', child => bag( {parent => 'sub-dir1'}, {parent => 'sub-dir2'})}, {parent => 'dir2', child => bag( {parent => 'sub-dir1', child => bag({ parent => 'sub-sub-dir1', child => bag({ parent => 'sub-sub-sub-dir1' })})})}, {parent => 'dir3'}); my $tree = get_tree([], 'paths'); cmp_deeply $tree, $expected, 'same'; ``` Upvotes: 2 <issue_comment>username_3: You can try, ``` use strict; use warnings; use Data::Dumper; sub get_tree { my ($gpath) = @_; my %r; my @root; use File::Find; my $cb = sub { my $tdir = $File::Find::dir; $tdir =~ s|^\Q$gpath\E/?||; return if $r{$tdir} or !$tdir; my ($pdir, $cdir) = $tdir =~ m|^ (.+) / ([^/]+) \z|x; my $c = $r{$tdir} = { parent => $cdir // $tdir }; if (defined $pdir) { push @{ $r{$pdir}{child} }, $c } else { push @root, $c } }; find($cb, $gpath); return \@root; } ``` It uses hash for fast lookup of nodes, and complete directory structure is built atop of `@root`. Upvotes: 3 [selected_answer]<issue_comment>username_4: Summarizing, here is the final code, that will produce valid *JSON* object expected by [Fancytree](https://github.com/mar10/fancytree) out of the box. Thanks to everyone, who was generous to spend time and provide help. **Perl:** ``` #!/usr/bin/perl use warnings; use strict; =head2 get_tree(path, [depth]) Build sorted directory tree in format expected by Fancytree =item path - The path from which to start searching. =item depth - The optional parameter to limit the depth. =cut use File::Find; use JSON; sub get_tree { my ( $p, $d ) = @_; my $df = int($d); my %r; my @r; my $wanted = sub { my $td = $File::Find::name; if ( -d $td ) { $td =~ s|^\Q$p\E/?||; if ( $r{$td} || !$td ) { return; } my ( $pd, $cd ) = $td =~ m|^ (.+) / ([^/]+) \z|x; my $pp = $p ne '/' ? $p : undef; my $c = $r{$td} = { key => "$pp/$td", title => ( defined($cd) ? $cd : $td ) }; defined $pd ? ( push @{ $r{$pd}{children} }, $c ) : ( push @r, $c ); } }; my $preprocess = sub { my $dd = ( $df > 0 ? ( $df + 1 ) : 0 ); if ($dd) { my $d = $File::Find::dir =~ tr[/][]; if ( $d < $dd ) { return sort @_; } return; } sort @_; }; find( { wanted => $wanted, preprocess => $preprocess }, $p ); return \@r; } # Retrieve JSON tree of `/home` with depth of `5` JSON->new->encode(get_tree('/home', 5)); ``` **JavaScript:** ``` $('.container').fancytree({ source: $.ajax({ url: tree.cgi, dataType: "json" }) }); ``` --- I'm using it in [Authentic Theme](https://github.com/qooob/authentic-theme) for [Webmin](https://github.com/webmin/webmin/)/[Usermin](https://github.com/webmin/usermin/) for File Manager. [![enter image description here](https://i.stack.imgur.com/0LSlS.png)](https://i.stack.imgur.com/0LSlS.png) Try it on the best server management panel of the 21st Century ♥️ Upvotes: 1
2018/03/17
1,497
4,726
<issue_start>username_0: We're using flake8 and pylint to do our code style checks on a project. But the problem is, none of those do any checks for how lines are split. Since consistency is nice in a project it looks really weird that we find ``` foo = long_function_name(var_one, var_two, var_three, var_four) foo = long_function_name( var_one, var_two, var_three, var_four) foo = long_function_name( var_one, var_two, var_three, var_four ) foo = { a, b} foo = { a, b, } ``` in our codebase. Sometimes different ways of closing a thing is right next to each other like in the example above. Now is there a checker or a rule for pylint or flake or special checker that would just ensure: * if you have a hanging indent, that the closing bracket, curly brackets or parentheses are always in a new line, and that we have a trailing comma above them. Consistency is key in a clean codebase, and we can't rely on devs to stick to rules if those aren't automatically checked. So I need a checker for the cases mentioned.<issue_comment>username_1: pylint will not do that. List of all pylint messages <http://pylint-messages.wikidot.com/all-codes> Upvotes: -1 <issue_comment>username_2: I'm also using flake8 and wasn't able to configure it to enforce consistency in your examples, because all of your examples are PEP8 compliant. To enforce consistency, I've found <https://github.com/python/black>: "The Uncompromising Code Formatter". Besides re-formatting code, it can act as a linter using the `--check` flag (see example usage below). When I invoke black on your examples, the first three are formatted to: ```py foo = long_function_name(var_one, var_two, var_three, var_four) ``` and the last two are formatted to: ```py foo = {a, b} ``` To demonstrate: 1) how black works when line-wraps are necessary; and 2) using black as a linter: ``` $ cat bar.py foo = long_function_name( var_one, var_two, var_three, var_four, var_five, var_six, var_seven) foo = long_function_name( var_one, var_two, var_three, var_four, var_five, var_six, var_seven, var_eight, var_nine ) $ black --check bar.py would reformat bar.py All done! 1 file would be reformatted. $ black bar.py reformatted bar.py All done! ✨ ✨ 1 file reformatted. $ cat bar.py foo = long_function_name( var_one, var_two, var_three, var_four, var_five, var_six, var_seven ) foo = long_function_name( var_one, var_two, var_three, var_four, var_five, var_six, var_seven, var_eight, var_nine, ) $ black --check bar.py All done! ✨ ✨ 1 file would be left unchanged. ``` Upvotes: -1 <issue_comment>username_3: You can use [`wemake-python-styleguide`](https://github.com/wemake-services/wemake-python-styleguide). It is a set of `flake8` plugins with lots of new rules. To install it run: `pip install wemake-python-styleguide` Running: `flake8 your_module.py` This is still just a `flake8` plugin! The specific rule you are interested in is [`consistency.ParametersIndentationViolation`](https://wemake-python-stylegui.de/en/latest/pages/usage/violations/consistency.html#wemake_python_styleguide.violations.consistency.ParametersIndentationViolation). Correct code samples: ``` # Correct: def my_function(arg1, arg2, arg3) -> None: return None print(1, 2, 3, 4, 5, 6) def my_function( arg1, arg2, arg3, ) -> None: return None print( 1, 2, 3, 4, 5, 6, ) def my_function( arg1, arg2, arg3, ) -> None: return None print( first_variable, 2, third_value, 4, 5, last_item, ) # Special case: print('some text', 'description', [ first_variable, second_variable, third_variable, last_item, ], end='') ``` Incorrect code samples: ``` call(1, 2, 3) print( 1, 2, 3, ) ``` Docs: <https://wemake-python-stylegui.de> Upvotes: 1 <issue_comment>username_4: Some of the checks that PEP8 does not enforce are therefore ignored by default by [pycodestyle](https://pycodestyle.pycqa.org/en/latest/intro.html) (which is one of the linters that [flake8](https://flake8.pycqa.org/en/latest/) wraps), but they can actually be made if selected. [Here](https://pycodestyle.pycqa.org/en/latest/intro.html#error-codes) you can check the error codes and change the default behaviour to select those you want to run. Example: ``` flake8 --select E123 ``` If you already have code with these styles that were not checked before, you could use [autopep8](https://github.com/hhatto/autopep8) formatter to reformat it: ``` autopep8 --select=E123 --in-place --recursive . ``` Upvotes: 0
2018/03/17
865
2,791
<issue_start>username_0: I have a html file where I have some variable like {Ticket}. In nodejs I am trying to replace that variable into an image what I have. So basically the output will be a pdf file. So far now my code looks like this ticket.html looks like this ``` | | | | --- | --- | | | {Ticket} | var html = fs.readFileSync('ticket.html', 'utf8'); //html file var GetImage = fs.readFileSync('QRTicket.png'); //image file var customHtml = customHtml.replace('{Ticket}', GetImage); pdf.create(customHtml, options).toFile('QRImage.pdf', function(err, res) { if (err) return console.log(err); console.log(res); }); ``` But its creating a blank pdf file. I am using [html-pdf](https://www.npmjs.com/package/html-pdf) to generate pdf file. I am struggling to get this done but its not working. So any help and suggestions will be really appreciable<issue_comment>username_1: You need to insert the image into the page differently (using the `file://` protocol). There is actually an example on the project's GitHub page that shows you how to do this [here](https://github.com/marcbachmann/node-html-pdf/blob/master/examples/businesscard/businesscard.html) and [here](https://github.com/marcbachmann/node-html-pdf/blob/master/examples/serve-http/index.js). In your case, this would translate to the following: ``` | | | | --- | --- | | | | ``` and the JS file: ``` const fs = require('fs'); const pdf = require('html-pdf'); const html = fs.readFileSync('./ticket.html', 'utf8'); const customHtml = html.replace('{Ticket}', `file://${require.resolve('./QRTicket.png')}`); pdf.create(customHtml).toFile('QRImage.pdf', (err, res) => { if (err) return console.log(err); console.log(res); }); ``` **Edit:** This example assumes the following folder structure. ``` . ├── index.js ├── node_modules ├── package.json ├── package-lock.json ├── QRTicket.png └── ticket.html ``` Run with the command `node index.js` and it will generate the desired PDF with the image. Upvotes: 2 <issue_comment>username_2: I have modified my ticket.html and now I want to search and replace multiple strings at a one place. So now my ticket.html is like this ``` | | | | --- | --- | | | | | asdf | tyui | ``` Now the express.js looks like this ``` const fs = require('fs'); const pdf = require('html-pdf'); const replaceOnce = require('replace-once'); const html = fs.readFileSync('ticket.html', 'utf8'); const image = 'file:///'+path.join(appRoot.path, 'file.png'); var find = ['{{Ticket}}', 'asdf', 'tyui']; var replace = [image, 'Wills', 'Smith']; const customHtml = replaceOnce(html, find, replace, 'gi') pdf.create(customHtml).toFile('QRImage.pdf', (err, res) => { if (err) return console.log(err); console.log(res); }); ``` Upvotes: 1 [selected_answer]
2018/03/17
1,524
4,444
<issue_start>username_0: I'm writing a Sudoku solving program and I'm a bit confused on using pointers with 2D arrays. Currently I am defining a `puzzle` like so: ``` int puzzle[9][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0} }; ``` and then I have a function called `backtrack` which will solve this recursively using backtracking. I need to pass `puzzle` to `backtrack` so I can modify it inside the function. Currently `backtrack` looks like ``` int backtrack(int (*p)[9][9]){ int puzzle[9][9] = *p; //actual logic is here return 0; } ``` but gcc gives an error saying that `int puzzle[9][9] = *p;` is an `invalid initializer` I am under the impression that `int (*p)[9][9]` is a pointer to a `9 x 9` int array, so I should be able to turn this into a `int puzzle[9][9]` by dereferencing `p`, but this doesn't seem to work.<issue_comment>username_1: Though the parameter declaration is correct but it seems you mean the following ``` int backtrack(int (*p)[9]){ ``` and the function is called like ``` backtrack( puzzle ); ``` When an array is used as an argument it is implicitly converted to pointer to its first element. In case of the array `puzzle` the first element of the array is the first "row" that is a one-dimensional array of the type `int[9]`. The syntax to access an element of the array is look like ``` p[i][j] ``` where `i` and `j` are some indices. Take into account that when the parameter is declared like ``` int backtrack(int p[9][9]){ ``` nevertheless the compiler adjusts it in any case like ``` int backtrack(int (*p)[9]){ ``` You could declare the parameter like ``` int backtrack(int (*p)[9][9] ){ ``` but in this case the function is called like ``` backtrack( &puzzle ); ``` and the body of the function would be too complicated. For example the syntax to access an element of the original array will look like ``` ( *p )[i][j] ``` Also this statement in the function ``` int puzzle[9][9] = *p; ``` does not make sense. You may not initialize an array such a way. I think this statement is redundant in implementation of the function. You already have the poinetr `p` that points to the first "row" of the array. And you can change the original array or traverse its elements using this pointer. In fact all elements of the array are passed by reference through the pointer p. Upvotes: -1 <issue_comment>username_2: It is not possible to assign to all elements of an array at once using an assignment expression, it is possible to initialize some or all elements of an array when the array is defined. A 1D array decays to a pointer. However, a 2D array does not decay to a pointer to a pointer. If you declare `backtrack` like this: ``` int backtrack(int arr[][9]); ``` or even better ``` int backtrack(int r, int c, int arr[][c]); ``` and call like: ``` int backtrack(puzzle); int backtrack(9,9, puzzle); ``` any modifications to the `arr[x][y`] element modify the original array `puzzle`. `arr`, the argument in `backtrack`, is of type `int (*)[c]`. Edit: The explicit use of pointers in the calling function is of course possible as shown: ``` #include #include #define NR\_OF\_ROWS 9 void backtrack1(int nr\_of\_columns, int \*array){ // access to // array[i][j] = // \*(array + i\*nr\_of\_columns + j) } void backtrack2(int nr\_of\_columns, int array[][nr\_of\_columns]){ //... } int main(void) { int nr\_of\_columns = 9; // number of columns int \*ptr1; // (to show how to init a pointer to puzzle1) int (\*ptr2)[nr\_of\_columns]; // (to show how to init a pointer to puzzle2) int puzzle1[NR\_OF\_ROWS][nr\_of\_columns]; // declare puzzle1 int puzzle2[NR\_OF\_ROWS][nr\_of\_columns]; // declare puzzle2 ptr1 = &puzzle1[0][0]; // pointer `ptr1` points to first element in the puzzle1 ptr2 = puzzle2; // pointer `ptr2` points to first element in the puzzle2 // 1a. call `backtrack1` function backtrack1(nr\_of\_columns, ptr1); // or `backtrack1(nr\_of\_columns, &table1[0][0]);` // 2a. call `backtrack2` function backtrack2(nr\_of\_columns, ptr2); // or simply `backtrack2(nr\_of\_columns, table2); return 0; } ``` Upvotes: 2 [selected_answer]
2018/03/17
1,112
4,377
<issue_start>username_0: I try to use Readmore.js, a jQuery plugin for collapsing and expanding long blocks of text with "Read more" and "Close" links, for the first time and can't really understand the reason why nothing changes. I try to get article contents collapsed and Read more button to appear. I checked twice if the source files are there for both jQuery and readmore. ```js $('article').readmore(); ``` ```html **Name Surname** celebrates **Event** in **5** days! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula. ```<issue_comment>username_1: Readmore doesn't initiate on a block unless its height is larger than the `collapsedHeight` plus `heightMargin`. Using no options this works out to be 216px. Upvotes: 0 <issue_comment>username_2: Your code works with an older version of jQuery (1.11.1): ```js $('article').readmore(); ``` ```html **Name Surname** celebrates **Event** in **5** days! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula. ``` It also works with 2.1.1 version: ```js $('article').readmore(); ``` ```html **Name Surname** celebrates **Event** in **5** days! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mattis consectetur nunc facilisis imperdiet. Donec sed arcu augue. Vestibulum tristique lobortis nulla eget pellentesque. Quisque consectetur vitae dui a porttitor. Suspendisse vel imperdiet dui, semper maximus sem. Aliquam in quam ornare, fringilla tellus sit amet, sodales ligula. ``` Upvotes: 2 [selected_answer]
2018/03/17
965
2,487
<issue_start>username_0: In My golden gate big data for kafka. when i try to update the record am getting only updated column and primary key column in after part in json file ``` {"table":"MYSCHEMATOPIC.PASSPORTS","op_type":"U","op_ts":"2018-03-17 13:57:50.000000","current_ts":"2018-03-17T13:57:53.901000","pos":"00000000030000010627","before":{"PASSPORT_ID":71541893,"PPS_ID":71541892,"PASSPORT_NO":"1234567","PASSPORT_NO_NUMERIC":241742,"PASSPORT_TYPE_ID":7,"ISSUE_DATE":null,"EXPIRY_DATE":"0060-12-21 00:00:00","ISSUE_PLACE_EN":"UN-DEFINED","ISSUE_PLACE_AR":"?????? ????????","ISSUE_COUNTRY_ID":203,"ISSUE_GOV_COUNTRY_ID":203,"IS_ACTIVE":1,"PREV_PASSPORT_ID":null,"CREATED_DATE":"2003-06-08 00:00:00","CREATED_BY":-9,"MODIFIED_DATE":null,"MODIFIED_BY":null,"IS_SETTLED":0,"MAIN_PASSPORT_PERSON_INFO_ID":34834317,"NATIONALITY_ID":590}, "after":{"PASSPORT_ID":71541893,"NATIONALITY_ID":589}} ``` In After part in my json out i want to show all columns How to get all columns in after part? ``` gg.handlerlist = kafkahandler gg.handler.kafkahandler.type=kafka gg.handler.kafkahandler.KafkaProducerConfigFile=custom_kafka_producer.properties #The following resolves the topic name using the short table name gg.handler.kafkahandler.topicMappingTemplate=passports gg.handler.kafkahandler.format=json gg.handler.kafkahandler.BlockingSend =false gg.handler.kafkahandler.includeTokens=false gg.handler.kafkahandler.mode=op #gg.handler.kafkahandler.format.insertOpKey=I #gg.handler.kafkahandler.format.updateOpKey=U #gg.handler.kafkahandler.format.deleteOpKey=D #gg.handler.kafkahandler.format.truncateOpKey=T #gg.handler.kafkahandler.format.includeColumnNames=TRUE goldengate.userexit.timestamp=utc goldengate.userexit.writers=javawriter javawriter.stats.display=TRUE javawriter.stats.full=TRUE gg.log=log4j gg.log.level=info gg.report.time=30sec ```<issue_comment>username_1: Try using the [Kafka Connect handler](https://docs.oracle.com/goldengate/bd123110/gg-bd/GADBD/using-kafka-connect-handler.htm#GADBD-GUID-22C9C4B2-48B0-4116-BD21-45D94F9296EC) instead - this includes the full payload. [This article](https://rmoff.net/2017/11/21/installing-oracle-goldengate-for-big-data-12.3.1-with-kafka-connect-and-confluent-platform/) goes through the setup process. Upvotes: 1 <issue_comment>username_2: Hi This issue is fixed by added below change in golden gate side ADD TRANDATA table\_name ALLCOLS Upvotes: 0
2018/03/17
457
945
<issue_start>username_0: I have a log of security cameras. I need only the IP addresses and date How do I get out. ``` Logon admin 07/03/2016 21:55:50 125.035.058.002 Logoff admin 07/03/2016 21:50:02 125.035.058.002 ```<issue_comment>username_1: The proper way (don't use awk, sed, regex etc...) using [xmlstarlet](/questions/tagged/xmlstarlet "show questions tagged 'xmlstarlet'") : (assuming ip starts with 1 or 2) ``` $ xmlstarlet sel -t -v '//Section[contains(text(), "/") or starts-with(text(), "1") or starts-with(text(), "2")]' file.xml ``` Output : -------- ``` 07/03/2016 21:55:50 125.035.058.002 07/03/2016 21:50:02 125.035.058.002 ``` Upvotes: 0 <issue_comment>username_2: The right way with **`xmlstarlet`** tool: ``` xmlstarlet sel -t -v '//Section[position()=3 or position()=4]' -n input.xml ``` The output: ``` 07/03/2016 21:55:50 125.035.058.002 07/03/2016 21:50:02 125.035.058.002 ``` Upvotes: 2 [selected_answer]
2018/03/17
1,338
3,379
<issue_start>username_0: Currently, i have a list containing: ``` table = [[3, 'AVENGERS',PACIFIC'],[1, 'A WALK,DRAGONBALL'],[2, 'A WALK,DRAGONBALL'],[5, 'A WALK,DRAGONBALL'],[6, 'JAMES BOND,MISSION'],[7,'JAMES BOND,MISSION']] ``` and I'm writing a program **to extract the numeric value** from each list within the table, if the **string element is found in other lists too.** For example, the string **'A WALK,DRAGONBALL'** is found in **list 2,3 and 4** and the string **'JAMES BOND,MISSION'** is found in **list 5 and 6** respectively. For every similar occurrences, i want to **extract the numeric value at index 0** and append into a list. For 'A WALK,DRAGONBALL' and 'JAMES BOND,MISSION' i will append: ``` movieName = ['A WALK,DRAGONBALL','JAMES BOND,MISSION'] movieNum = [[1,2,5],[6,7]] ``` where in the list movieNum, the first list represents the number for 'A WALK,DRAGONBALL' and the second list for 'JAMES BOND,MISSION'. Here's what I did: ``` movie = [] movieNum = [] movielst = [] for i in range(len(table)-1): if table[i][1] == table[i+1][1]: movie.append(table[i][1]) movieNum.append([table[i][0],table[i+1][0]]) print(movieNum) for i in movie: if i not in movielst: movielst.append(i) print(movielst) ``` I was able to print out the movielst correctly but I'm having issue with the **movieNum** list as instead of getting a **list of non duplicates**, ``` [[1,2,5],[6,7]] ``` I'm getting: ``` [[1,2],[2,5],[6,7]] ``` What should i do in order to resolve the duplicate number?<issue_comment>username_1: You can use `itertools.groupby`: ``` import itertools table = [[3, 'AVENGERS','PACIFIC'],[1, 'A WALK,DRAGONBALL'],[2, 'A WALK,DRAGONBALL'],[5, 'A WALK,DRAGONBALL'],[6, 'JAMES BOND,MISSION'],[7,'JAMES BOND,MISSION']] new_table = [list(b) for a, b in itertools.groupby(sorted(table, key=lambda x:x[1:]), key=lambda x:x[1:])] last_results = [[b for b, _ in i] for i in new_table if len(i) > 1] ``` Output: ``` [[1, 2, 5], [6, 7]] ``` Upvotes: 1 <issue_comment>username_2: You can use `collections.defaultdict` for this. ``` from collections import defaultdict table = [[3, 'AVENGERS','PACIFIC'],[1, 'A WALK,DRAGONBALL'],[2, 'A WALK,DRAGONBALL'], [5, 'A WALK,DRAGONBALL'],[6, 'JAMES BOND,MISSION'],[7,'JAMES BOND,MISSION']] d = defaultdict(list) for num, *movies in table: for movie in movies: d[movie].append(num) d = {k: v for k, v in d.items() if len(v)>1} ``` **Result** ``` {'A WALK,DRAGONBALL': [1, 2, 5], 'JAMES BOND,MISSION': [6, 7]} ``` You can extract keys and values for the result dictionary: ``` keys, values = d.keys(), d.values() # dict_keys(['A WALK,DRAGONBALL', 'JAMES BOND,MISSION']) # dict_values([[1, 2, 5], [6, 7]]) ``` Upvotes: 2 <issue_comment>username_3: You can simply do : ``` final_dict={} table = [[3, 'AVENGERS PACIFIC'],[1, 'A WALK,DRAGONBALL'],[2, 'A WALK,DRAGONBALL'],[5, 'A WALK,DRAGONBALL'],[6, 'JAMES BOND,MISSION'],[7,'JAMES BOND,MISSION']] for i in table: if i[1] not in final_dict: final_dict[i[1]] = [i[0]] else: final_dict[i[1]].append(i[0]) print({i:j for i,j in final_dict.items() if len(j)>1}) ``` output: ``` {'A WALK,DRAGONBALL': [1, 2, 5], 'JAMES BOND,MISSION': [6, 7]} ``` if you want only names then: ``` print(list(filter(lambda x:len(final_dict[x])>1,final_dict.keys()))) ``` Upvotes: 0
2018/03/17
590
2,212
<issue_start>username_0: I am querying users created in Laravel by month, here is my code ``` $devlist = DB::table("users") ->select("id" ,DB::raw("(COUNT(*)) as month")) ->orderBy('created_at') ->groupBy(DB::raw("MONTH(created_at)")) ->get(); ``` This is giving me this ``` [{"id":1,"month":3},{"id":4,"month":4}] ``` How can I output the month as well instead of just the word month? So my expected result would be ``` [{"id":1,"january":3},{"id":4,"febuary":4}] ```<issue_comment>username_1: Hard to tell without seeing your DB structure, but something like this would be fine. As noted, the output you are showing doesn't line up with the groupBy clause, but assuming the groupBy is correct, this will restructure the way you need: ``` $devlist = DB::table("users") ->select("id" ,DB::raw("(COUNT(*)) as month")) ->orderBy('created_at') ->groupBy(DB::raw("MONTH(created_at)")) ->get() ->map(function($monthItems, $month) { return $monthItems->map(function($item) use ($month) { return [ 'id' => $item->id, $month => $item->month, ]; }); }); ``` Upvotes: 0 <issue_comment>username_2: It's difficult to answer this without seeing the database, but I hope this will help: ``` $devlist = DB::table("users") ->select(DB::raw('EXTRACT(MONTH FROM created_at) AS month, COUNT(id) as id')) ->orderBy('created_at') ->groupBy(DB::raw('month')) ->get(); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: ``` $statement = Purchase::selectRaw('monthname(purchase_date) month') ->groupBy('month') ->orderByRaw('min(purchase_date) asc') ->get(); echo " ``` "; print_r($statement); die; ``` ``` Upvotes: 2 <issue_comment>username_4: Simply use this ``` \App\Model::selectRaw('monthname(date) as month, sum(total_amount) as total_sale') ->groupBy('month') ->orderByRaw('min(date) desc') ->get(); ``` Upvotes: 0
2018/03/17
246
898
<issue_start>username_0: I need to use spring boot devtools to force reload of static resource during dev time. I added follow code to my pom ``` org.springframework.boot spring-boot-devtools true runtime ``` but maven did not found the dependecy, I need to add respoitory uri?<issue_comment>username_1: If you are not using a parent pom nor defined there, then you should identify the version of jar you want to use. likes: ``` org.springframework.boot spring-boot-devtools 1.5.9.RELEASE true runtime ``` You can check out <http://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools> to see which version you would like to use. Upvotes: 3 [selected_answer]<issue_comment>username_2: What worked in my project me was adding the dependency inside the tag `dependencyManagement` ``` org.springframework.boot spring-boot-devtools 3.1.2 ``` Upvotes: 0
2018/03/17
395
1,380
<issue_start>username_0: I have this problem with VueJS Laravel This is my Home.vue ``` | {{models.nom}} | | import axios from 'axios' export default{ data() { return { model: {} } }, created:function(){ this.fetchDataResto() }, methods: { fetchDataResto(){ var vm = this axios.get('/test') .then(function response(){ Vue.set(vm.$data, 'model', response.model.data) }) } } } ``` And this is my app.js ``` require("./bootstrap"); window.Vue = require("vue"); Vue.component('home', require('./components/Home.vue')); var app = new Vue({ el: "#app" }); ``` I have this message error after execute `Uncaught (in promise) TypeError: Cannot read property 'data' of undefined at response (app.js:47293)` I don't know why data is undefined Thanks<issue_comment>username_1: ``` fetchDataResto(){ var vm = this axios.get('/test') .then(function (response){ Vue.set(vm.$data, 'model', response.model.data) }) } ``` You forgot to set the `response` variable. ;) Upvotes: 0 <issue_comment>username_2: I solve with this ``` fetchDataResto(){ var vm = this axios.get('/test') .then(function (response){ Vue.set(vm.model, 'model', response.data) }) } ``` Upvotes: 1
2018/03/17
772
2,648
<issue_start>username_0: How to get the Object from a string? I written a localStorage util, in it there are `get` and `set` methods. in the set method: ``` function fnGet(name){ var getVal=storage.getItem(name); if(getVal==null){ return console.log('the localstorage did\'t have'+name); } if((getVal.split(':-:')).lenght>1){ return eval('('+getVal.split(':-:')[0]+')'); } return getVal.split(':-:')[0]; } ``` You can ignore the `:-:`, it is the separator of the saved data and timestamp. there is a problem, if the data is stored a JavaScript Object, such like this: `'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}:-:1521381469910'` when I use the get method, it will become like this: `'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}'` How can I get to the JavaScript Object? How to optimize my get method?<issue_comment>username_1: `JSON.parse` on your response from the store. localStorage stores everything as strings so you would need to stringify the object at first, as Im supposed you do as otherwise you wouldnt have been able to save it to the store. Then to retrieve it you would need to parse it to get the javascript object again. Upvotes: 1 [selected_answer]<issue_comment>username_2: LocalStorage saves the data stringified. So you should use `JSON.parse(yourVariable)` to get the data back as JSON Upvotes: -1 <issue_comment>username_3: ``` function fnGet(name) { var getVal = storage.getItem(name); if (getVal == null) { return console.log('the localstorage did\'t have' + name); } if ((getVal.split(':-:')).lenght > 1) { return eval('(' + JSON.parse(getVal.split(':-:')[0]) + ')'); } return getVal.split(':-:')[0]; } ``` all you needed was JSON.parse which takes a string as an argument and if its a valid object string ,returns an object else throws an error Upvotes: -1 <issue_comment>username_4: Two things: 1. Use `JSON.parse()` instead of `eval`; it's not only safer, but more descriptive as to what your intent is. Note: this requires using `JSON.stringify()` on the data being saved in localStorage 2. Correct your spelling errors; you would never get to the eval/parser block because your `length` was spelled "lenght" ```js function fnGet(name) { let getVal = storage.getItem(name) if (getVal == null) { return console.log(`the localstorage did't have: ${name}`); } let val = getVal.split(':-:'); // for performance cache the split if (val.length > 1) { // Spelling error: "lenght" -> length return JSON.parse(val[0]); } return val[0]; } ``` Upvotes: 0
2018/03/17
2,021
5,454
<issue_start>username_0: I have array like below: ``` Array( [top_menu] => Array( [li] => Array( [a] => Array( [clr] => #FF00FF ) [a:hover] => Array( [clr] => #FF6600 ) ) ) [wrap-zfcnt] => Array( [a] => Array( [clr] => #99CC00 ) [p] => Array( [ffam] => Comic Sans MS [clr] => #FF0000 [fsz] => 9px ) [a:hover] => Array( [clr] => #666699 [txtd] => underline ) ) [sidebar-zfcnt] => Array( [bgi] => url(/res/uploads/webist/0/3/6815/res/18291/logo.png?1) ) ) ``` I want to convert it to a single dimensional array like below: ``` [top_menu~li~a--clr] => #FF00FF [top_menu~li~a:hover--clr] => #FF6600 [wrap-zfcnt~a--clr] => #99CC00 [wrap-zfcnt~p--fsz] => 9px [wrap-zfcnt~p--ffam] => Comic Sans MS [wrap-zfcnt~p--clr] => #FF0000 [wrap-zfcnt~a:hover--txtd] => underline [wrap-zfcnt~a:hover--clr] => #666699 [sidebar-zfcnt--bgi] => url(/res/uploads/webist/0/3/6815/res/18291/logo.png?1) ``` Below is my function: ``` function m_dim_to_s_dim_css ($array, $el='') { $style = ''; $style_block = ''; $i=0; foreach ($array as $element => $styles ) { if ( is_array($styles) ) { if($el != '') { $element = $el.'~'.$element; } $cStyle = m_dim_to_s_dim_css($styles, $element); $style .= $cStyle; } else { if($i > 0) { } $style_block .= "--".$element; } $i++; } if (!empty($style_block)) { $style .= $el.$style_block."=>".$styles."|||"; } return $style; } ``` this is what it is returning: ``` Array ( [top_menu~li~a--clr] => #FF00FF [top_menu~li~a:hover--clr] => #FF6600 [wrap-zfcnt~a--clr] => #99CC00 [wrap-zfcnt~p--ffam--clr--fsz] => 9px [wrap-zfcnt~a:hover--clr--txtd] => underline [sidebar-zfcnt--bgi] => url(/res/uploads/webist/0/3/6815/res/18291/logo.png?1) [] => ) ``` Any help is appreciated<issue_comment>username_1: The function you are looking for is called `array_reduce`. You've got an array like `$a = array(array(1,2,3), array(4,5), array(6,7,8,9))` When you `print_r` that array it will give you such a multidimensional array structure: ``` Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 ) [2] => Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 ) ) ``` and you want to merge it to one single array to look like: ``` Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 ) ``` You simply have to make a new array `$a` is your old, multi-dimensional array. `$result` is your new, one-dimensional array. ``` $result = array_reduce($a, 'array_merge', array()); ``` Hope I was able to help you with your problem. Upvotes: 0 <issue_comment>username_2: Her you have correct recursive loop: ``` php $inArray = [ 'top_menu' = [ 'li' => [ 'a' => ['clr' => '#FF00FF'], 'a:hover' => ['clr' => '#FF6600'], ], ], 'wrap-zfcnt' => [ 'a' => ['clr' => '#99CC00'], 'p' => [ 'ffam' => 'Comic Sans MS', 'clr' => '#FF0000', 'fsz' => '9px', ], 'a:hover' => [ 'clr' => '#666699', 'txtd' => 'underline', ], ], 'sidebar-zfcnt' => ['bgi' => 'url(/res/uploads/webist/0/3/6815/res/18291/logo.png?1)',], ]; $reducedArray = []; function walkStyleArray($toWalk, $keyPrefix = "") { global $reducedArray; //need for access outside function definied array if(is_array($toWalk)) { foreach($toWalk as $key => $value) { if(is_array($value)) { walkStyleArray($value, $keyPrefix . ($keyPrefix === "" ?"":"~") . $key); } else { $newKey = $keyPrefix . ($keyPrefix === "" ?"":"--") . $key; $reducedArray[$newKey] = $value; } } } } walkStyleArray($inArray); // print_r($inArray); print_r($reducedArray); ``` And finally result: ``` Array ( [top_menu~li~a--clr] => #FF00FF [top_menu~li~a:hover--clr] => #FF6600 [wrap-zfcnt~a--clr] => #99CC00 [wrap-zfcnt~p--ffam] => Comic Sans MS [wrap-zfcnt~p--clr] => #FF0000 [wrap-zfcnt~p--fsz] => 9px [wrap-zfcnt~a:hover--clr] => #666699 [wrap-zfcnt~a:hover--txtd] => underline [sidebar-zfcnt--bgi] => url(/res/uploads/webist/0/3/6815/res/18291/logo.png?1) ) ``` --- **Edit 1 for the records:** Walk array deeper and deeper until value meet (it is recurrency break case), and then create element of reducedArray, no counting needed either any other. --- **Edit 2 walkStyleArray function without `global` statement** ``` $reducedArray = []; function walkStyleArray(&$resultArray, $toWalk, $keyPrefix = "") { if(is_array($toWalk)) { foreach($toWalk as $key => $value) { if(is_array($value)) { walkStyleArray($resultArray, $value, $keyPrefix . ($keyPrefix === "" ?"":"~") . $key); } else { $newKey = $keyPrefix . ($keyPrefix === "" ?"":"--") . $key; $resultArray[$newKey] = $value; } } } } walkStyleArray($reducedArray, $inArray); ``` Upvotes: 2 [selected_answer]
2018/03/17
480
1,754
<issue_start>username_0: I am trying to use the [convolutional residual network neural network architecture](https://en.wikipedia.org/wiki/Residual_neural_network) (ResNet). So far, I have implemented simple convolutions (conv1D) for time series data classification using Keras. Now, I am trying to build ResNet using Keras but I'm having some difficulties trying to adapt it to time series data. Most of the implementations of ResNet or Nasnet in Keras (such as [this one](https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py) or [that one](https://github.com/titu1994/Keras-NASNet/blob/master/nasnet.py)) use conv2D for their implementation (which makes sense for images). Could someone help me in implementing this for time series data?<issue_comment>username_1: Do you know about the paper "[Time Series Classification from Scratch with Deep Neural Networks: A Strong Baseline](https://arxiv.org/pdf/1611.06455)"? If not, you should check it out. The authors provide a very comprehensive overview of different models, including a ResNet implementation adjusted for time series classification. Their Keras/Tensorflow implementation of ResNet can be found [here](https://github.com/cauchyturing/UCR_Time_Series_Classification_Deep_Learning_Baseline/blob/master/ResNet.py). **Update:** A more recent version of ResNet (and other classifiers) for time series data can be found [here](https://github.com/hfawaz/dl-4-tsc). Upvotes: 5 [selected_answer]<issue_comment>username_2: [tsai](https://github.com/timeseriesAI/tsai) provides a range of SOTA methods, including [ResNet](https://github.com/timeseriesAI/tsai/blob/main/tsai/models/ResNet.py) ([doc](https://timeseriesai.github.io/tsai/models.resnet.html)) of course. Upvotes: 0
2018/03/17
452
1,572
<issue_start>username_0: I need to write a function on pandas which calculates the total yearly tax paid given monthly income on the following basis: the regular rate is *13%*, but when income for the year becomes larger than *1000* units, from the next month tax of *20%* is imposed. For example, `calculate_tax(pd.Series([150]*12)` should return 286.5. Here 150 is monthly income. This should be solved without using cycles I was able to write a code with the fixed *13%* of the income: ``` def calculate_tax(income): t=(income*0.13).cumsum() return(t.iloc[-1]) ```<issue_comment>username_1: Do you know about the paper "[Time Series Classification from Scratch with Deep Neural Networks: A Strong Baseline](https://arxiv.org/pdf/1611.06455)"? If not, you should check it out. The authors provide a very comprehensive overview of different models, including a ResNet implementation adjusted for time series classification. Their Keras/Tensorflow implementation of ResNet can be found [here](https://github.com/cauchyturing/UCR_Time_Series_Classification_Deep_Learning_Baseline/blob/master/ResNet.py). **Update:** A more recent version of ResNet (and other classifiers) for time series data can be found [here](https://github.com/hfawaz/dl-4-tsc). Upvotes: 5 [selected_answer]<issue_comment>username_2: [tsai](https://github.com/timeseriesAI/tsai) provides a range of SOTA methods, including [ResNet](https://github.com/timeseriesAI/tsai/blob/main/tsai/models/ResNet.py) ([doc](https://timeseriesai.github.io/tsai/models.resnet.html)) of course. Upvotes: 0
2018/03/17
537
1,917
<issue_start>username_0: i'm new to codeigniter i can't not get data from the controller using the ajax request i think i do mistake in writing the url of the controller function in ajax call **here is the code of my ajax call** ``` $(document).ready(function(){ $("#fname").focusout(function(){ // alert(); $.ajax({ url: "php echo base_url();?/proposal/ajax_load", type: 'POST', success: function(result){ $("#div1").html(result); } }); }); }); ``` **Here is my controller** ``` class Proposal extends CI_Controller { public function ajax_load() { return ("Hello"); } } ```<issue_comment>username_1: in **ajax\_load()** - Should be **echo** not **return** if you're getting a response via ajax. Upvotes: 1 <issue_comment>username_2: You are confuse between the meaning of `[Return, Echo]` in PHP, ### [Echo](http://php.net/echo) > > echo — Output one or more strings > > > ### [Return](http://php.net/return) > > return returns program control to the calling module. Execution > resumes at the expression following the called module's invocation. > > > and as long as the Ajax response callback is reading a server response [output], you must send an output to the server. ``` public function ajax_load() { echo "Hello"; } ``` Further reading :- * [What is the difference between PHP echo and PHP return in plain English?](https://stackoverflow.com/questions/9387765/what-is-the-difference-between-php-echo-and-php-return-in-plain-english) * [Difference between php echo and return in terms of a jQuery ajax call](https://stackoverflow.com/questions/10107144/difference-between-php-echo-and-return-in-terms-of-a-jquery-ajax-call) * a short and simple [answer](https://stackoverflow.com/a/2710117/2359679) Upvotes: 3 [selected_answer]
2018/03/17
1,162
4,507
<issue_start>username_0: I'm trying to set up some unit tests for a private project. Since I don't mind the exact runner, I tried NUnit, XUnit and MStest, but none worked so far. After some research, I cloned the official Microsoft repository here :<https://github.com/dotnet/docs/blob/master/samples/core/getting-started/unit-testing-using-nunit/PrimeService.Tests/PrimeService_IsPrimeShould.cs> But these tests can't be executed as well. When doing so, I get the following error in the output: > > System.ArgumentException: Illegal characters in path. at > System.IO.Path.CheckInvalidPathChars(String path, Boolean > checkAdditional) at System.IO.Path.Combine(String path1, String > path2) at > Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers.DotnetHostHelper.TryGetExecutablePath(String > executableBaseName, String& executablePath) at > Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers.DotnetHostHelper.GetDotnetPath() > at > Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager.GetTestHostProcessStartInfo(IEnumerable`1 > sources, IDictionary`2 environmentVariables, TestRunnerConnectionInfo > connectionInfo) at > Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1 > sources, CancellationToken cancellationToken) at > Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyDiscoveryManager.DiscoverTests(DiscoveryCriteria > discoveryCriteria, ITestDiscoveryEventsHandler2 eventHandler) > > > I also checked out several SO answers like [Unit Tests not discovered in Visual Studio 2017](https://stackoverflow.com/questions/42861930/unit-tests-not-discovered-in-visual-studio-2017) or [How to run NUnit tests in Visual Studio 2017?](https://stackoverflow.com/questions/43007761/how-to-run-nunit-tests-in-visual-studio-2017), but none of them fixed the problem. My Visual Studio 2017 Version is currently 15.6.0 and I'm also using ReSharper. It seems like this is a local environmental problem, unfortunately, I didn't find any hints regarding that problem. Has anyone a idea, how that problem could be solved?<issue_comment>username_1: I had exactly the same problem after moving from NUnit to XUnit on a large solution. I tried creating a new project that contained just a single dummy test. This also exhibited the problem, meaning it was environmental. I eventually discovered Git had placed double quotes around its entry in the PATH environment variable, like this: ...;"C:\Program Files (x86)\Git\bin";... Unfortunately, my path was very long (3600 chars), so the Windows GUI would not let me change it as it was more then 2047 chars. I was able to correct it by changing the Path stored in the Windows Registry at Computer\HKEY\_LOCAL\_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment I was able to reproduce the behaviour at will by re-adding the quotes to the Path environment variable. I think there was a bug with an older version of Git I had installed (long ago) which added the quoted locate to the path environment variable, and newer updates never changed it. I suspect the NUnit test runner was tolerant of the quotes, while the XUnit test runner is not. I hope my experience helps with your issue. Upvotes: 3 <issue_comment>username_2: In my case the problem disappeared when I updated VS2017 to version **15.6.4**. Upvotes: 2 [selected_answer]<issue_comment>username_3: Just in case someone still has the same issue of "0 Tests Found -- Invalid Character in path". I was experiencing it but I was able to solve it, however, it took me two days to find the solution. The solution is very simple but at the time it was not clear to the surface. Solution: (Windows - PCs) * Open This PC -> Properties -> Advanced system settings -> Environment Variable -> User variables * Scroll to the "path" and click Edit and then click "Edit text..." * check the whole text and remove any double quotes, <> if they are available and click OK. * Do the same with System variables path. * Head back to Visual Studio, build your solution and Run All tests. After these steps, the tests should be found this time. Upvotes: 2 <issue_comment>username_4: In my case VS 2019, there was no issue in Environment Path...so I had 2 options either reinstall (not sure whether it will work or not) or use VS on different machine, I used VS on different machine, it worked...its strange that VS IDE has some issue when run test cases... Upvotes: 1
2018/03/17
603
2,032
<issue_start>username_0: I'm working on parsing [this](https://www.arsenal.com/fixtures) web page. I've got `table = soup.find("div",{"class","accordions"})` to get just the fixtures list (and nothing else) however now I'm trying to loop through each match one at a time. It looks like each match starts with an article element tag However for some reason when I try to use `matches = table.findAll("article",{"role","article"})` and then print the length of matches, I get 0. I've also tried to say `matches = table.findAll("article",{"about","/fixture/arsenal"})` but get the same issue. Is BeautifulSoup unable to parse tags, or am I just using it wrong?<issue_comment>username_1: the reason is that findAll is searching for tag name. refer to [bs4 docs](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#calling-a-tag-is-like-calling-find-all) Upvotes: 0 <issue_comment>username_2: Try this: ``` matches = table.findAll('article', attrs={'role': 'article'}) ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: You need to pass the attributes as a dictionary. There are three ways in which you can get the data you want. ``` import requests from bs4 import BeautifulSoup r = requests.get('https://www.arsenal.com/fixtures') soup = BeautifulSoup(r.text, 'lxml') matches = soup.find_all('article', {'role': 'article'}) print(len(matches)) # 16 ``` Or, this is also the same: ``` matches = soup.find_all('article', role='article') ``` But, both these methods give some extra article tags that don't have the `Arsernal` fixtures. So, if you want to find them using `/fixture/arsenal` you can use [CSS selectors](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors). (Using `find_all` won't work, as you need a partial match) ``` matches = soup.select('article[about^=/fixture/arsenal]') print(len(matches)) # 13 ``` Also, have a look at [the keyword arguments](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments). It'll help you get what you want. Upvotes: 0
2018/03/17
650
2,479
<issue_start>username_0: I currently have a Custom map renderer in my Xamarin Forms that use for each platform the native Map renderer. For iOS, I'm trying to add a tracking button to come back to current position. I have the code to create the button : ``` var button = MKUserTrackingButton.FromMapView(Map); button.Layer.BackgroundColor = UIColor.White.CGColor; button.Layer.BorderColor = UIColor.FromRGB(211, 211, 211).CGColor; button.Layer.BorderWidth = 1; button.Layer.CornerRadius = 5; button.TranslatesAutoresizingMaskIntoConstraints = false; Map.AddSubview(button); ``` But I need to move it to the bottom right corner ( see image below ) [![enter image description here](https://i.stack.imgur.com/Xbs25.png)](https://i.stack.imgur.com/Xbs25.png) So I just need the line of code to move the button in the MAP View :)<issue_comment>username_1: If you want to use Frame to change a Control's position. You should delete `button.TranslatesAutoresizingMaskIntoConstraints = false;`. This code will disable the Frame, and use autoLayout to place your controls. Also you can try to use autoLayout: ``` button.TopAnchor.ConstraintEqualTo(Map.TopAnchor, 100).Active = true; button.LeadingAnchor.ConstraintEqualTo(Map.LeadingAnchor, 100).Active = true; button.WidthAnchor.ConstraintEqualTo(52).Active = true; button.HeightAnchor.ConstraintEqualTo(44).Active = true; ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: This will also give the tracking button on the bottom right. Note that this only works for iOS 11 and above, so be sure to put a device check in there also. ``` if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { var button = MKUserTrackingButton.FromMapView(map); button.Layer.BackgroundColor = UIColor.White.CGColor; button.Layer.BorderColor = UIColor.FromRGB(0, 0, 127).CGColor; button.Layer.BorderColor = UIColor.White.CGColor; button.Layer.BorderWidth = 1; button.Layer.CornerRadius = 5; button.TranslatesAutoresizingMaskIntoConstraints = false; View.AddSubview(button); NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{ button.BottomAnchor.ConstraintEqualTo(View.BottomAnchor, -10), button.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor, -10) }); } ``` Upvotes: 1
2018/03/17
896
3,007
<issue_start>username_0: I'm trying to implement building a singly-linked list from an `Iterator`, keeping the order of elements. The structure is defined as: ``` #[derive(Debug)] struct List { list: Node, } type Node = Option>>; #[derive(Debug)] struct Link { head: T, tail: Node, } ``` I was thinking of keeping a mutable reference to the end of the list and expanding it while iterating. However, I couldn't figure out how this could be done. The (non-working) idea was: ``` impl List { pub fn from\_iterator(i: &mut Iterator) -> Self { let mut list = List { list: None }; { let mut last: &mut Node = &mut list.list; for x in i { let singleton = Box::new(Link { head: x, tail: None, }); \*last = Some(singleton); // --> I aim for something like the line below. Of course // 'singleton' can't be accessed at this point, but even if I // match on \*last to retrieve it, still I couldn't figure out how // to properly reference the new tail. // last = &mut singleton.tail; } } list } } ``` It'd be possible to just build the list in reverse and then reverse it afterwards with the same time complexity, but I was curious if the above approach is ever possible in Rust.<issue_comment>username_1: I'm not sure you can do it in a loop. The borrow checker might not be smart enough. You can do it with recursion though. ``` impl List { pub fn from\_iterator(i: &mut Iterator) -> Self { let mut list = List { list: None }; Self::append\_from\_iterator(&mut list.list, i); list } pub fn append\_from\_iterator(list: &mut Node, i: &mut Iterator) { match i.next() { Some(x) => { let mut singleton = Box::new(Link { head: x, tail: None, }); Self::append\_from\_iterator(&mut singleton.tail, i); \*list = Some(singleton); }, None => (), } } } ``` [playground](https://play.rust-lang.org/?gist=df0f9bafca02357e30f11796cadaa069&version=stable) Upvotes: 0 <issue_comment>username_2: As described in [Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time](https://stackoverflow.com/q/37986640/155423), you can explicitly transfer ownership of the mutable reference using `{}`: ``` impl List { pub fn from\_iterator*(i: I) -> Self where I: IntoIterator, { let mut list = List { list: None }; { let mut last: &mut Node = &mut list.list; for x in i { let singleton = Box::new(Link { head: x, tail: None, }); \*last = Some(singleton); last = &mut {last}.as\_mut().unwrap().tail; } } list } }* ``` I also removed the trait object (`&mut Iterator`) in favor of a generic. This allows for more optimized code (although with a linked list it's probably not worth it). It's unfortunate that the `unwrap` is needed. Even though the `Link` is placed on the heap, making the address stable, the compiler does not perform that level of lifetime tracking. One *could* use `unsafe` code based on this external knowledge, but I don't know that it's worth it here. Upvotes: 3 [selected_answer]
2018/03/17
672
2,369
<issue_start>username_0: You have: 1. an Oracle database 2. an Oracle Client installation, including SQL\*Plus 3. the TNS information for #1 4. BUT NO TNSNames.ORA file or the desire to create and maintain one How can you get your SQL\*Plus connection going?<issue_comment>username_1: ``` sqlplus user/password@(description=(address_list=(address=.......ODS))) ``` The text in the () is the information you would see for your service in a TNSNames file. So you can simply use the TNS entry explicitly Note, use quotes if in Unix else the () are interpreted by the shell. Or you can use the EZconnect syntax (my preferred method) ``` sqlplus user/password@//hostname/service_name sqlplus user/password@//hostname:port/service_name ``` Note that for Oracle Database 12/18c multitenant architecture databases, you MUST use the /service\_name and not the /SID if you want to connect to a pluggable database. Note also that we have 2 command-line interfaces now. SQL\*Plus and SQLcl. [SQLcl](http://www.oracle.com/technetwork/developer-tools/sqlcl/overview/sqlcl-index-2994757.html) is java based, and a stripped down version of Oracle SQL Developer. It supports TNS based connections, and also supports the EZConnect syntax. One significant advantage it has over SQL\*Plus is that it does not require an Oracle Client installation. This question was originally answered by Tom on [AskTom](https://asktom.oracle.com/pls/apex/asktom.search?tag=how-to-connect-sqlplus-without-tnsnamesora). I've updated his answer here to address Oracle 12c Multitenant and SQLcl. Upvotes: 3 <issue_comment>username_2: Using a `tnsnames.ora` file is just one out of four different naming methods, see [Parameters for the sqlnet.ora File](https://docs.oracle.com/cd/E11882_01/network.112/e10835/sqlnet.htm#NETRF192) Usually `ldap` and `nis` are suitable only when you have many Oracle databases running in your premises. Other methods are already provided by @username_1 Upvotes: 0 <issue_comment>username_3: Assuming, `sqlcl` executable is present in the current directory, you can use `./sql user/password@host:port/service_name` Upvotes: 1 <issue_comment>username_4: If you don't want to leave password in bash history, use this: ```sh # connect sql user@host:port/database # will ask password later # then connect to your database sql > conn database ``` Upvotes: 1
2018/03/17
780
3,153
<issue_start>username_0: In jQuery Validation Plugin I have a rule for an input field that should be set to false if a hidden input has val equal to 1, and true if 2. I have made a function inside one of the rules for the input field, where I look for the hidden input val, and returning true or false based on the number. However, it is returning true no matter what, even though I can see it should be returning false. See [JSfiddle](https://jsfiddle.net/cempshb2/18/) HTML: ``` Username: ``` jQuery: ``` $('form').validate({ rules: { user: { required: true, email: function(){ if($('input[name="pick"]').val() == 1){ console.log('Email shold be false'); return false; }else{ return true; } } } } }); ``` Why is "return false" not working? I can see in the console that "Email should be set to false" Note: This is just an example of what I am trying to achieve. I am going to have a lot more inputs and rule-changes. Also, the hidden input field is generated by other measures (Not two buttons like in the example). I know I could just make 2 forms, but I rather want to do it with 1, because there is going to be a lot of changes and that would require a lot of forms / double js code.<issue_comment>username_1: You shouldn't set `email` to be a function (`email: function(){}`). You should set the properties of the `email` object so that the framework can read what it needs to. So to place your own function in `email` to validate (return true or false) you should do so like this: ``` $('form').validate({ rules: { user: { required: true, email: { depends: function () { var checkValue = $('input[name="pick"]').val() == 1; return checkValue; // Or this - depending on your requirements. // return !checkValue; } } } } }); ``` Upvotes: 1 <issue_comment>username_2: > > *"Why is my function inside a rule in jQuery Validation Plugin not returning false?"* > > > It's not. The `email` rule is seeing your function in place of a boolean and interpreting its mere existence as "not `false`", thereby enabling the rule. In order to use a function here, it needs to be inside of [the `depends` callback parameter](https://jqueryvalidation.org/validate/#rules). Also, since you need to get a boolean in the first place, there is no need for an if/else statement; just `return` the result of your conditional statement. Flip the conditional to a "not equals" (`!=`), so the `email` rule is not enforced when the hidden value is `1`. ``` rules: { user: { required: true, email: { depends: function(element) { return ($('input[name="pick"]').val() != 1); } } } } ``` **Working DEMO: [jsfiddle.net/v4bf1mvj/](https://jsfiddle.net/v4bf1mvj/)** Upvotes: 3 [selected_answer]
2018/03/17
760
2,991
<issue_start>username_0: I have the following 2 classes: ``` @Entity @Table(name = "TableA") public class EntityA { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Id") private final Integer id = null; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "BId") private EntityB b; public EntityA(EntityB b) { this.b = b; } } @Entity @Table(name = "TableB") public class EntityB { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "Id") private final Integer id = null; @OneToOne(mappedBy = "b") private final EntityA a = null; } ``` When I do ``` session.save(new EntityA(new EntityB()); ``` the database only inserts a record in TableA and leaves the column that references TableB as NULL If I first insert b, then a, it works, but it should work with a single call too. Other questions/answers mention that the annotations are not correct, but I see no difference between mine and the provided solutions. I also tried adding the CascadeType.PERSIST on both @OneToOne annotations, but that didnt work either.<issue_comment>username_1: You shouldn't set `email` to be a function (`email: function(){}`). You should set the properties of the `email` object so that the framework can read what it needs to. So to place your own function in `email` to validate (return true or false) you should do so like this: ``` $('form').validate({ rules: { user: { required: true, email: { depends: function () { var checkValue = $('input[name="pick"]').val() == 1; return checkValue; // Or this - depending on your requirements. // return !checkValue; } } } } }); ``` Upvotes: 1 <issue_comment>username_2: > > *"Why is my function inside a rule in jQuery Validation Plugin not returning false?"* > > > It's not. The `email` rule is seeing your function in place of a boolean and interpreting its mere existence as "not `false`", thereby enabling the rule. In order to use a function here, it needs to be inside of [the `depends` callback parameter](https://jqueryvalidation.org/validate/#rules). Also, since you need to get a boolean in the first place, there is no need for an if/else statement; just `return` the result of your conditional statement. Flip the conditional to a "not equals" (`!=`), so the `email` rule is not enforced when the hidden value is `1`. ``` rules: { user: { required: true, email: { depends: function(element) { return ($('input[name="pick"]').val() != 1); } } } } ``` **Working DEMO: [jsfiddle.net/v4bf1mvj/](https://jsfiddle.net/v4bf1mvj/)** Upvotes: 3 [selected_answer]
2018/03/17
487
1,553
<issue_start>username_0: `git diff --name-only` or `git diff --name-status` will list all files that have been changed, however there is no command to list all folder names that contain files changed. For example, with this directory tree: ``` test/ | |__B/ | |____b1.txt | |__C/ | |____c1.txt ``` If `b1.txt` and `c1.txt` have changed, I'd like to get `B` and `C` as the output.<issue_comment>username_1: Here's a way: ```sh git diff --name-only | xargs -L1 dirname | uniq ``` --- **Explanation** * `git diff --name-only`: list all changed files * `xargs -L1 dirname`: remove filenames to keep only directories * `uniq`: remove duplicates You can create [an alias](http://tldp.org/LDP/abs/html/aliases.html) so you don't have to type the whole command each time you need it: ```sh alias git-diff-folders="git diff --name-only | xargs -L1 dirname | uniq" ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: This command would give results of top level directories. `git status | cut -d'/' -f1` For a more in depth solution I am currently working with ${PWD##\*/} in bash to find a more correct solution to your problem. Trying to write a solution for you in git that is simular to this npm solution: [get the path where npm gulp called from](https://stackoverflow.com/questions/41366507/get-the-path-where-npm-gulp-called-from) im no longer searching for the answer on this one, `git diff --name-only | xargs -L1 dirname | uniq` was the correct answer provided by Pᴇʜ it works on my mac computer after his edit's Upvotes: 2
2018/03/17
573
1,800
<issue_start>username_0: > > I have the following code. > using the latest bootstrap version > > > ``` Bootstrap Grid System > > Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante. > > > Someone famous in Source Title > ``` > > And expecting the below result - > [![enter image description here](https://i.stack.imgur.com/Lyfta.png)](https://i.stack.imgur.com/Lyfta.png) > > > But it is producing this result > [![enter image description here](https://i.stack.imgur.com/3ZQi1.png)](https://i.stack.imgur.com/3ZQi1.png) > > > So what is the problem with the code ? > > ><issue_comment>username_1: Here's a way: ```sh git diff --name-only | xargs -L1 dirname | uniq ``` --- **Explanation** * `git diff --name-only`: list all changed files * `xargs -L1 dirname`: remove filenames to keep only directories * `uniq`: remove duplicates You can create [an alias](http://tldp.org/LDP/abs/html/aliases.html) so you don't have to type the whole command each time you need it: ```sh alias git-diff-folders="git diff --name-only | xargs -L1 dirname | uniq" ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: This command would give results of top level directories. `git status | cut -d'/' -f1` For a more in depth solution I am currently working with ${PWD##\*/} in bash to find a more correct solution to your problem. Trying to write a solution for you in git that is simular to this npm solution: [get the path where npm gulp called from](https://stackoverflow.com/questions/41366507/get-the-path-where-npm-gulp-called-from) im no longer searching for the answer on this one, `git diff --name-only | xargs -L1 dirname | uniq` was the correct answer provided by Pᴇʜ it works on my mac computer after his edit's Upvotes: 2
2018/03/17
659
2,113
<issue_start>username_0: I have the following link as a string in php: ``` $url = 'http://www.example.com/assets/images/temp/10.jpg'; ``` I am trying to add the word BIG before the number so at the end I will have: ``` $url = 'http://www.example.com/assets/images/temp/big10.jpg'; ``` I am currently accomplishing that by using explode on `/` then adding big to the last array. My only issue is that in the future, this link might have less `/` i.e.: `http://www.example.com/assets/10.jpg`. In this case, my explode statement will not work. Is there a better way to add the word big after the last occurance of `/`? I also came up with this method: ``` $url = 'http://www.example.com/assets/images/temp/10.jpg'; $filename = substr(strrchr($url, "/"), 1); // returns 10.jpg $newfilename = 'big'.substr(strrchr($url, "/"), 1); // returns big10.jpg $newurl = str_replace($filename,$newfilename,$url); // replaces 10.jpg with big.jpg ```<issue_comment>username_1: Here's a way: ```sh git diff --name-only | xargs -L1 dirname | uniq ``` --- **Explanation** * `git diff --name-only`: list all changed files * `xargs -L1 dirname`: remove filenames to keep only directories * `uniq`: remove duplicates You can create [an alias](http://tldp.org/LDP/abs/html/aliases.html) so you don't have to type the whole command each time you need it: ```sh alias git-diff-folders="git diff --name-only | xargs -L1 dirname | uniq" ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: This command would give results of top level directories. `git status | cut -d'/' -f1` For a more in depth solution I am currently working with ${PWD##\*/} in bash to find a more correct solution to your problem. Trying to write a solution for you in git that is simular to this npm solution: [get the path where npm gulp called from](https://stackoverflow.com/questions/41366507/get-the-path-where-npm-gulp-called-from) im no longer searching for the answer on this one, `git diff --name-only | xargs -L1 dirname | uniq` was the correct answer provided by Pᴇʜ it works on my mac computer after his edit's Upvotes: 2
2018/03/17
803
3,459
<issue_start>username_0: It says > > "Method must have a return type" > > > whenever I try to debug it. I don't know how to fix this class in this line i have an error , ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //btn_Submit Click event Form1_Load(object sender, System.EventArgs e) { // Do whatever } private void button1_Click(object sender, EventArgs e) { string d, y, z; d = (textBox1.Text); y = (textBox2.Text); if (d == "" || y == "") { MessageBox.Show("ERROR"); return; } try { //Create SqlConnection SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True;"); SqlCommand cmd = new SqlCommand("Select * from Table_1 where id=@d and password=@y", con); cmd.Parameters.AddWithValue("@username", d); cmd.Parameters.AddWithValue("@password", y); con.Open(); SqlDataAdapter adapt = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapt.Fill(ds); con.Close(); int count = ds.Tables[0].Rows.Count; //If count is equal to 1, than show frmMain form if (count == 1) { MessageBox.Show("Login Successful!"); this.Hide(); frmMain fm = new frmMain(); fm.Show(); } else { MessageBox.Show("Login Failed!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void label1_Click_1(object sender, EventArgs e) { } } } ``` i tried to change to class name and add some libary but i faild i think i forget something in the class can anybody help me please ?<issue_comment>username_1: change ``` Form1_Load(object sender, System.EventArgs e) { // Do whatever } ``` to ``` void Form1_Load(object sender, System.EventArgs e) { // Do whatever } ``` You are missing an important part of the method signature, the return type. Since the method should not return anything, use `void` Upvotes: 2 <issue_comment>username_2: Your event handler doesn't specify any return type and so the error. Since it's a event handler return type must be `void` like ``` private void Form1_Load(object sender, System.EventArgs e) ``` Upvotes: 2 <issue_comment>username_3: ``` Form1_Load is handler which you subscribed to Load event of form. public event EventHandler Load; ``` So your handler signature should match delegate `EventHandler` signature. According to which it should be `void` ``` delegate void EventHandler(object sender, EventArgs e); ``` Upvotes: 0
2018/03/17
606
2,542
<issue_start>username_0: I have the following protocols: ``` protocol MyDelegate: class { func closeViewController() } protocol MyProtocol: class { weak var delegate: SomeClass? {get set} } ``` And the following class: ``` class SomeClass: MyDelegate { var myViewController: UIViewController init(myViewController: UIViewController){ self.myViewController = myViewController self.myViewController.delegate = self } func closeViewController() { myViewController.dismiss(animated: true, completion: nil) } } ``` The idea here is that SomeClass takes a view controller and sets itself as the view controller's delegate. The View controller is defined like so: ``` class SomeViewController: UIViewController, MyProtocol { weak var delegate: SomeClass? ... @IBAction func close(_ sender: Any) { delegate?.closeViewController() } ... } ``` where the close function is mapped to a close button in storyboard. I initialize both SomeClass and my view controller inside another view controller. ``` var someViewController = // initialized here var someClass = SomeClass(myViewController: someViewController) self.present(someViewController, animated: true, completion: nil) ``` However, when I press the close button, nothing happens at all. The view controller does not dismiss. On the other hand, if I change the close() function in my ViewController to be: ``` @IBAction func close(_ sender: Any) { self.dismiss(animated: true, completion: nil) } ``` Then it dismisses itself as expected, showing that the function is correctly mapped to the button. How do I go about dismissing my view controller from another class?<issue_comment>username_1: You have declared `delegate` property as weak and there isn't any strong reference of `SomeClass` object. Object should be `nil` by the time close button callback and `closeViewController()` is never called. Upvotes: 2 [selected_answer]<issue_comment>username_2: If I may suggest that you've made this much more complicated than it needs to be. I would ditch the `protocol` altogether and just implement a simple delegate pattern. ``` class SomeViewController { func close() { print("did close") } } class SomeObject { weak var delegate: SomeViewController? func close() { delegate?.close() } } let viewController = SomeViewController() let object = SomeObject() object.delegate = viewController object.close() // prints "did close" ``` Upvotes: -1
2018/03/17
949
2,821
<issue_start>username_0: I'm struggling with multiple image uploads in [redactor](https://imperavi.com/redactor/). Specifically, creating the return JSON after uploading and saving the images. I have managed to do it using `StringBuilder`, but i would like to do it in a properly typed class if possible, using `return Json(redactorResult, JsonRequestBehavior.AllowGet);` --- **Desired Format** From the [redactor demo page](https://imperavi.com/redactor/), I can see the formatting I require is: ``` { "file-0": { "url":"/tmp/images/b047d39707366f0b3db9985f97a56267.jpg", " id":"70e8f28f4ce4a338e12693e478185961" }, "file-1":{ "url":"/tmp/images/b047d39707366f0b3db9985f97a56267.jpg", "id":"456d9b652c72a262307e0108f91528a7" } } ``` **C# Class** But to create this JSON from a c# class I think I would need something like this : ``` public class RedactorFileResult { public string url {get;set;} public string id {get;set;} } public class RedactorResult { public RedactorFileResult file-1 {get;set;} public RedactorFileResult file-2 {get;set;} // .. another property for each file... } ``` ... which seems impossible at worst (never know how many images will be uploaded), and a bit impractical at best. **Question** Am I approaching this correctly? Is there a way to do this that I'm not aware of? Or am I better just sticking with string builder on this occasion?<issue_comment>username_1: Define a class for single item: ``` public class File { public string Url { get; set; } public string Id { get; set; } } ``` Then create your files like this: ``` var files = new List(); files.Add(new File{Url = "tmp/abc.jpg", Id = "42"}); files.Add(new File {Url = "tmp/cba.jpg", Id = "24"}); ``` Now you are able to get desired json output with linq query: ``` var json = JsonConvert.SerializeObject(files.Select((f, i) => new {f, i}) .ToDictionary(key => $"file-{key.i}", value => value.f)); ``` In my example result would be: ``` { "file-0":{ "Url":"tmp/abc.jpg", "Id":"42" }, "file-1":{ "Url":"tmp/cba.jpg", "Id":"24" } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Define item: ``` class Item { public string Url { get; set; } public string Id { get; set; } } ``` Then you should use a dictionary instead of RedactorResult class, like this: ``` var redactorResult = new Dictionary(); redactorResult["file-1"] = new Item(){ Url = "...", Id = "..." }; redactorResult["file-2"] = new Item(){ Url = "...", Id = "..." }; ``` If you prefer RedactorResult class, you may extend the Dictionary: ``` class RedactorResult : Dictionary { private int count = 0; public void Add(Item item) { this[$"file-{count}"] = item; count++; } } ``` Upvotes: 2
2018/03/17
1,326
4,164
<issue_start>username_0: I have several objects and I want to create another one that will have keys from a particular array (`const props = []`), and values from those objects - if it only exists in those objects, but if not - I want to push `null` or some other fake values. My code: ```js const props = ["name", "price", "qty", "category"] let len = props.length; const obj_1 = { name: "Product_1", price: 120, category: 'phone' } const obj_2 = { name: "Product_2", price: 7893, category: 'program_eq', qty: 5 } const final_obj = { name: ["Product_1", "Product_2"], price: [120, 7893], category: ["phone", "program_eq"], qty: [null, 5] } ``` I have spent lots of time with this problem and have some solution - but it gives me only the first object. I am using lodash/map and it helps me to work with different type of collection. You can see my solution bellow: ```js const final_obj = {}; const props = ["name", "price", "qty", "category"]; let len = props.length; const obj = { c1s6c156a1cascascas: { item: { name: "Product_1", price: 120, category: "phone" } }, c454asc5515as41cas78: { item: { name: "Product_2", price: 7893, category: "program_eq", qty: 5 } } }; _.map(obj, (element, key) => { console.log(element.item); while (len) { let temp = props.shift(); let tempData = []; if (element.item.hasOwnProperty([temp])) { tempData.push(element.item[temp]); } else { tempData.push("---"); } final_obj[temp] = tempData; len--; } }); console.log(final_obj); // category:["phone"] name:["Product_1"], price:[120], qty:["---"], ```<issue_comment>username_1: You could do this with `reduce()` method that will return object and inside use `forEach()` loop. ```js const props = ["name", "price", "qty", "category"]; const obj = {"c1s6c156a1cascascas":{"item":{"name":"Product_1","price":120,"category":"phone"}},"c454asc5515as41cas78":{"item":{"name":"Product_2","price":7893,"category":"program_eq","qty":5}}} const result = Object.values(obj).reduce((r, e) => { props.forEach(prop => { if(!r[prop]) r[prop] = [] r[prop].push(e.item[prop] || null) }) return r; }, {}) console.log(result) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This is how I would handle it: ``` const final_obj = { }; const props = ["name", "price", "qty", "category"]; const obj = {"c1s6c156a1cascascas":{"item":{"name":"Product_1","price":120,"category":"phone"}},"c454asc5515as41cas78":{"item":{"name":"Product_2","price":7893,"category":"program_eq","qty":5}}} // set up each property as an empty array in the object props.forEach(item => { final_obj[item] = []; }); // this iterates over every property in the object _.forOwn(obj, value => { props.forEach(item => { // just push the values undefined or no into each property array final_obj[item].push(value.item[item]); }); }); console.log(final_obj); ``` Upvotes: 1 <issue_comment>username_3: You can do as well using some lodash functions. Transform the array of props into an object which keys are the values of props and which values are extracted from the object. If the property doesn't exist in the object, return null. ```js const getValFromObj = (obj, key) => _.map(obj, _.partial(_.get, _, key, null)); const setValInResult = (res, key) => _.set(res, key, getValFromObj(obj, 'item.' + key)); const groupByProps = (props, obj) => _.transform(props, setValInResult, {}); const props = ["name", "price", "qty", "category"]; const obj = { "c1s6c156a1cascascas": { "item": { "name": "Product_1", "price": 120, "category": "phone" } }, "c454asc5515as41cas78": { "item": { "name": "Product_2", "price": 7893, "category": "program_eq", "qty": 5 } } } console.log(groupByProps(props, obj)); ``` Upvotes: 0
2018/03/17
1,088
2,898
<issue_start>username_0: ``` #Basically, for the input number given, return results that are smaller #than it compared with the list. n = list(input('Please enter a Number: ')) #map(int, str(n)) newlist = [] a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for n in a: if n > a: newlist.append(a) print(newlist) ``` Not asking for the solution but just asking how n can work as a list since when I run my code, it says: ``` " if n > a: TypeError: '>' not supported between instances of 'int' and 'list' " ```<issue_comment>username_1: Here is what you need. You can use a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) to filter `a` for required elements. ``` x = int(input('Please enter a Number: ')) # Input 5 as an example a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] result = [i for i in a if i < x] print(result) # [1, 1, 2, 3] ``` Upvotes: 2 <issue_comment>username_2: because `a` is a list and your `n` in the iteration is an integer value inside of the list `a`. for example in the zeroth iteration n = 1 but `a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]` and saying `n > a` doesn't make sense, does it? Upvotes: 1 <issue_comment>username_3: Assuming you're using python3, the [input() method](https://www.programiz.com/python-programming/methods/built-in/input) returns a string. So if your user inputs the value `42`, `input()` will return `"42"`, (`type 'str')`. Then you are converting your string into a list, so going on with the 42 example, you'll have `list("42") == ["4", "2"]`, and you store this list in `n`. Anyway, you're not using your variable `n` anymore: The `for` loop that you wrote does not not refer to the `n` variable you previously created (see [namespaces](http://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html)), but creates a new variable which will contain each number in your `a` list. this means that you are comparing each number of the list to the whole list: ``` 1 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 1 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 2 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 3 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] ... ``` In python3 this will raise a TypeError, and in python2 the behaviour won't be what you expect. To have your code correctly working, you may take the user input and convert it in an integer, then compare this integer with each number inside your list and append the number to a new list if it is lower than the input integer: ``` myint = int(input('Please enter a Number: ')) # type(myint) == int newlist = [] a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # for each (n)umber in list (a): for n in a: # if the provided number is higher than the actual number in list (a): if myint > n: newlist.append(n) # print the new list once its fully filled print(newlist) ``` Upvotes: 3 [selected_answer]
2018/03/17
1,372
5,207
<issue_start>username_0: At this moment, I have a script that works correctly to list students of a class in Google Classroom, but it does NOT list ALL of the students, only the first 30. I need it to list ALL of the students, no matter how many there are. What I have now is the following: ``` function listStudents() { var s = SpreadsheetApp.getActiveSpreadsheet(); var sh = s.getSheetByName('CLASS'); var r = sh.getDataRange(); var n = r.getNumRows(); var d = r.getValues(); for (x = 0; x < n; x++) { var i = d[x][0]; if(i == ''){ continue; } else if (i == 'D') { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sh = ss.getSheetByName('LISTSTUDENTS'); var tea = Classroom.Courses.Students.list(d[x][8]); var t = tea.students; var arr = []; try { for (i = 0; i < t.length; i++) { var c = t[i]; var ids = c.profile; var em = ids.emailAddress; arr.push([em]); } } catch (e) { continue; } sh.getRange(d[x][14], d[x][15], arr.length, arr[0].length).setValues(arr); } } } ```<issue_comment>username_1: You receive only 30 students in the query because you are only accessing the first page of results. Almost every "advanced service" functions in a similar manner with regards to collections, in that they return a variable number of items in the call (usually up to a size that can be specified in the query, but there are limits). This is to ensure timely service availability for everyone who uses it. For example, consider Bob (from Accounting). This style of request pagination means he can't request a single response with 20,000 items, during which the service is slower for everyone else. He can, however, request the next 100 items, 200 times. While Bob is consuming those 100 items from his most recent query, others are able to use the service without disruption. To set this up, you want to use a code loop that is guaranteed to execute at least once, and uses the `nextPageToken` that is included in the response to the call to [`.list()`](https://developers.google.com/classroom/reference/rest/v1/courses.students/list) to control the loop. In Javascript / Google Apps Script, this can be a [`do .. while`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while) loop: ``` // Runs once, then again until nextPageToken is missing in the response. const roster = [], // The optional arguments pageToken and pageSize can be independently omitted or included. // In general, 'pageToken' is essentially required for large collections. options = {pageSize: /* reasonable number */}; do { // Get the next page of students for this course. var search = Classroom.Courses.Students.list(courseId, options); // Add this page's students to the local collection of students. // (Could do something else with them now, too.) if (search.students) Array.prototype.push.apply(roster, search.students); // Update the page for the request options.pageToken = search.nextPageToken; } while (options.pageToken); Logger.log("There are %s students in class # %s", roster.length, courseId); ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: for those who struggle with this, here's the code ``` function listStudent() { var pageSizeValue = 300; /*** change with numbers that you want*/ var nextPageToken = ''; var courseID = 1234; /*** change with numbers that you want*/ var ownerArray = []; do { var optionalArgs = { pageSize: pageSizeValue, pageToken: nextPageToken }; var cls = Classroom.Courses.Students.list(courseID, optionalArgs); var nextPageToken = cls.nextPageToken; const ssData = cls.students.map(c => { return [c.profile.id,c.profile.name.fullName,c.profile.emailAddress] }); Array.prototype.push.apply(ownerArray, ssData); } while (nextPageToken); const ss = SpreadsheetApp.openById("1234"); // <<< UPDATE THIS const sheet = ss.getSheetByName("Sheet1"); // <<< UPDATE THIS sheet.getRange(2,1,ownerArray.length,ownerArray[0].length).setValues(ownerArray); // <<< UPDATE THIS } ``` Upvotes: 1 <issue_comment>username_3: I modified the getRoster function in the example provided by Google (<https://developers.google.com/apps-script/add-ons/editors/sheets/quickstart/attendance>) as follows, and it worked for me. ``` function getRoster(courseId) { var studentNames = [] var studentEmails = [] var nextPageToken = '' do { var optionalArgs = { pageSize: 30, pageToken: nextPageToken }; var response = Classroom.Courses.Students.list(courseId, optionalArgs) var students = response.students nextPageToken = response.nextPageToken for (var i = 0; i <= students.length; i++) { try { studentNames.push(students[i].profile.name.fullName) studentEmails.push(students[i].profile.emailAddress) } catch (err) { } } } while (nextPageToken); return { "studentNames":studentNames, "studentEmails":studentEmails } } ``` Upvotes: 0
2018/03/17
844
2,421
<issue_start>username_0: I have a data frame with 19 variables, 17 of which are factors. Some of these factors contain missing values, coded as NA. I would like to recode missings as a separate factor level "to\_impute" using forcats::fct\_explicit\_na() for all factors in the data frame. A small example with two factor variables: ``` df <- structure(list(loc_len = structure(c(NA, NA, NA, NA, NA, NA, 1L, 1L, 3L, 1L), .Label = c("No", "< 5 sec", "5 sec - < 1 min", "1 - 5 min", "> 5 min", "Unknown duration"), class = "factor"), AMS = structure(c(1L, 2L, NA, 1L, 1L, NA, NA, NA, NA, NA), .Label = c("No", "Yes"), class = "factor")), .Names = c("loc_len", "AMS"), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame")) table(df$loc_len, useNA = "always") No < 5 sec 5 sec - < 1 min 1 - 5 min > 5 min Unknown duration 3 0 1 0 0 0 6 ``` The code below does this for two variables. I'd like to do this for all factor variables 'f\_names' in the data frame. Is there a way to 'vectorize' fct\_explicit\_na()? ``` f_names <- names(Filter(is.factor, df)) f_names [1] "loc_len" "AMS" ``` The code below does what I want, but separately for each factor: ``` df_new <- df %>% mutate(loc_len = fct_explicit_na(loc_len, na_level = "to_impute")) %>% mutate(AMS = fct_explicit_na(AMS, na_level = "to_impute")) ``` I'd like tables of this sort for all factors in the dataset, names in 'f\_names' : ``` lapply(df_new, function(x) data.frame(table(x, useNA = "always"))) ``` Now is: ``` $loc_len x Freq 1 No 3 2 < 5 sec 0 3 5 sec - < 1 min 1 4 1 - 5 min 0 5 > 5 min 0 6 Unknown duration 0 7 to_impute 6 8 0 $AMS x Freq 1 No 3 2 Yes 1 3 to\_impute 6 4 0 ```<issue_comment>username_1: After some trial and error, the code below does what I want. ``` library(tidyverse) df[, f_names] <- lapply(df[, f_names], function(x) fct_explicit_na(x, na_level = "to_impute")) %>% as.data.frame ``` Upvotes: 0 <issue_comment>username_1: Even better, the elegant and idiomatic solution provided by: <https://github.com/tidyverse/forcats/issues/122> ``` library(dplyr) df = df %>% mutate_if(is.factor, fct_explicit_na, na_level = "to_impute") ``` Upvotes: 2
2018/03/17
270
935
<issue_start>username_0: Code: ``` ` Bootstrap Welcome to Bootstrap 4.0 ! ========================== This is the platform that was created by twitter and is used in every website today Name Email Submit [Bootstrap 4.0](#) * [Home (current)](#) * [Link](#) * [Dropdown](#) [Action](#) [Another action](#) [Something else here](#) * [Disabled](#) Search ```<issue_comment>username_1: One vary basic and simple way to change a html tag to be in the center is to use align attribute: ``` This sentence will be in the center! ``` Please try and change this code: ``` Name Email Submit ``` To: ``` Name Email Submit ``` Another way is to add the `"text-align: center;"` in your CSS file. Upvotes: 0 <issue_comment>username_2: You can use below CSS to align form in the center with content. ``` form { display: block; margin: 0 auto; text-align: center; } ``` Upvotes: -1
2018/03/17
1,219
3,867
<issue_start>username_0: How can you compare two version numbers? I don't want the simple 1.0.0.0 but I'm looking for comparing these 1.0.0.1 1.0.0.1rc1 / 1.0.0.1-rc1 1.0.0.1b 1.0.0.1a / 1.0.0.1-a and so on They are ordered in the direction of what is newest. Quote from PHP.net from their function that does what I want > > version\_compare() compares two "PHP-standardized" version number strings. > The function first replaces \_, - and + with a dot . in the version strings and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: any string not found in this list < dev < alpha = a < beta = b < RC = rc < # < pl = p. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state. > > > How can this be done? Or is there something like this by default?<issue_comment>username_1: Use the [semantic version library for .Net](https://github.com/maxhauser/semver) To install the package: ``` Install-Package semver ``` You can parse /compare versions. **Example 1: Compare** ``` var v1 = new SemVersion(1, 0, 0, "rc1"); Console.WriteLine(v1); var v2 = new SemVersion(1, 0, 0, "rc2"); Console.WriteLine(v2); var r = SemVersion.Compare(v1,v2); //If v1 < v2 return -1 //if v1 > v2 return +1 //if v1 = v2 return 0 Console.WriteLine(r); // -1 ``` **Example2: Parse** ``` var version = SemVersion.Parse("1.2.45-alpha-beta+nightly.23.43-bla"); Console.WriteLine(version); Console.WriteLine( version.Major); //1 Console.WriteLine( version.Minor); //2 Console.WriteLine( version.Patch); //45 Console.WriteLine(version.Prerelease); //alpha-beta Console.WriteLine(version.Build); //nightly.23.43 ``` **Update:** Life demo in [fiddle](https://dotnetfiddle.net/UWmITT) Upvotes: 5 [selected_answer]<issue_comment>username_2: Rather than using a 3rd party's library it would be preferable to just reference **Nuget.Core** and utilize their **SemanticVersion** class. This class works very similarly to the standard Version object in .net but adheres to the Semantic Versioning spec (<https://semver.org>). It will parse your string into an IComparable and IEquatable object so you can compare multiple versions or sort them within a collection, etc. Nuget.Core: <https://www.nuget.org/packages/nuget.core/> (you can pull this library via nuget) <https://github.com/NuGet/NuGet2/blob/2.13/src/Core/SemanticVersion.cs> ``` var rawVersions = new [] {"v1.4.0", "v1.4.0-patch10", "v1.4.0-patch2"}; var versions = rawVersions.Select(v => new SemanticVersion(v)); var sorted = versions.ToList().Sort(); ``` Upvotes: 0 <issue_comment>username_3: My function to comparison two versions. Version example "1.22.333.4444" ``` static int CompareVersions(string First, string Second) { var IntVersions = new List { Array.ConvertAll(First.Split('.'), int.Parse), Array.ConvertAll(Second.Split('.'), int.Parse) }; var Cmp = IntVersions.First().Length.CompareTo(IntVersions.Last().Length); if (Cmp == 0) IntVersions = IntVersions.Select(v => { Array.Resize(ref v, IntVersions.Min(x => x.Length)); return v; }).ToList(); var StrVersions = IntVersions.ConvertAll(v => string.Join("", Array.ConvertAll(v, i => { return i.ToString($"D{IntVersions.Max(x => x.Max().ToString().Length)}"); }))); var CmpVersions = StrVersions.OrderByDescending(i => i).ToList(); return CmpVersions.First().Equals(CmpVersions.Last()) ? Cmp : CmpVersions.First().Equals(StrVersions.First()) ? 1 : -1; } ``` | | | | --- | --- | | First > Second | 1 | | First == Second | 0 | | First < Second | -1 | Upvotes: 0
2018/03/17
736
2,219
<issue_start>username_0: I have the following question. I try to calculate the Intersection over Union, which is the overlap of two components divided by the unioin of two components. Lets assume component1 is a matrix with ones where the first object is and component2 is a matrix with ones where the second object is. The Overlap i can caluclate with `np.logical_and(component == 1, component2 == 1)`. But how can I caclulate the Union? Im only interested in objects which are connected. ``` import numpy as np component1 = np.array([[0,1,1],[0,1,1],[0,1,1]]) component2 = np.array([[1,1,0],[1,1,0],[1,1,0]]) overlap = np.logical_and(component == 1, component2 == 1) union = ? IOU = len(overlap)/len(union) ```<issue_comment>username_1: If you're only dealing with `0` and `1`, it's easier to work with boolean arrays: ``` import numpy as np component1 = np.array([[0,1,1],[0,1,1],[0,1,1]], dtype=bool) component2 = np.array([[1,1,0],[1,1,0],[1,1,0]], dtype=bool) overlap = component1*component2 # Logical AND union = component1 + component2 # Logical OR IOU = overlap.sum()/float(union.sum()) # Treats "True" as 1, # sums number of Trues # in overlap and union # and divides >>> 1*overlap array([[0, 1, 0], [0, 1, 0], [0, 1, 0]]) >>> 1*union array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) >>> IOU 0.3333333333333333 ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: **Oleksii** has an answer for your question in [medium](https://towardsdatascience.com/intersection-over-union-iou-calculation-for-evaluating-an-image-segmentation-model-8b22e2e84686). Simply put: ``` intersection = numpy.logical_and(result1, result2) union = numpy.logical_or(result1, result2) iou_score = numpy.sum(intersection) / numpy.sum(union) print(‘IoU is %s’ % iou_score) ``` Also, he gives a very good explains of it. Take a look at the above link. Upvotes: 1 <issue_comment>username_3: just use dedicated numpy functions `intersect1d` and `union1d`: ``` intersection = np.intersect1d(a, b) union = np.union1d(a, b) iou = intersection.shape[0] / union.shape[0] ``` Upvotes: 1
2018/03/17
679
2,312
<issue_start>username_0: In `userInput.equals("0") ?` part both resulting expressions return void type. Why then it tells me that the expression returns String? ``` import java.util.Scanner; public class BaseConverter { private static final int SENTINEL = 0; public static void main(String args[]) { askInput(); } private static void askInput() { Scanner reader = new Scanner(System.in); String userInput; System.out.println("This is converter"); System.out.println("0 to stop"); while(true) { System.out.print("Enter hex: "); userInput = reader.nextLine(); userInput.equals("0") ? break : System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); } } } ```<issue_comment>username_1: You cannot use the ternary operator like that, instead do this: ``` if(userInput.equals("0")) break; System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); ``` Upvotes: 1 <issue_comment>username_2: You must switch from *ternary* operator to *if/else* statement ``` if(userInput.equals("0")) { break; } else { System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); } ``` This code can be reduced to: ``` if(userInput.equals("0")) { break; } System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); ``` Upvotes: 2 <issue_comment>username_3: In your case, it's better to use use `do{} while()` loop like this : ``` do { System.out.print("Enter hex: "); userInput = reader.nextLine(); System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); } while (!userInput.equals("0")); ``` --- Which mean, repeat until `userInput` should equal to `0`, you don't need to use `break` in this case. --- For a better solution, you still need to use `try` and `catch` to avoid `NumberFormatException` : ``` do { System.out.print("Enter hex: "); userInput = reader.nextLine(); try { System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); } catch (NumberFormatException e) { System.out.println("Incorrect Number"); } } while (!userInput.equals("0")); ``` Upvotes: 0
2018/03/17
734
2,486
<issue_start>username_0: I have some php script that is adding a new line to a string saved in MYSQL in a mychar field. When I look at the database using mysqladmin, I can see fields that have multiple lines. They do not show any characters. Whatever is creating the new line is invisible. [![enter image description here](https://i.stack.imgur.com/8b8nC.png)](https://i.stack.imgur.com/8b8nC.png) However, when I try to update an existing string with a string that includes an extra line, using \n, it updates the field as empty. I'm guessing this is because mysql does not accept \n in an update statement. Can anyone suggest how to prepare a string in PHP so that when updating a field in MYSQL it updates properly, ie with new line. \n does not seem to work. ``` $sql = "UPDATE comments SET comment = 'firstline\nsecondline\nthirdline' WHERE id = 23" ``` When you run the above statement, it does update the line but the comment field is empty. Thanks for any suggestions.<issue_comment>username_1: You cannot use the ternary operator like that, instead do this: ``` if(userInput.equals("0")) break; System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); ``` Upvotes: 1 <issue_comment>username_2: You must switch from *ternary* operator to *if/else* statement ``` if(userInput.equals("0")) { break; } else { System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); } ``` This code can be reduced to: ``` if(userInput.equals("0")) { break; } System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); ``` Upvotes: 2 <issue_comment>username_3: In your case, it's better to use use `do{} while()` loop like this : ``` do { System.out.print("Enter hex: "); userInput = reader.nextLine(); System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); } while (!userInput.equals("0")); ``` --- Which mean, repeat until `userInput` should equal to `0`, you don't need to use `break` in this case. --- For a better solution, you still need to use `try` and `catch` to avoid `NumberFormatException` : ``` do { System.out.print("Enter hex: "); userInput = reader.nextLine(); try { System.out.println(userInput + "hex = " + Integer.valueOf(userInput, 10) + " decimal"); } catch (NumberFormatException e) { System.out.println("Incorrect Number"); } } while (!userInput.equals("0")); ``` Upvotes: 0
2018/03/17
622
2,067
<issue_start>username_0: I am trying to write a unit test to a class init that reads from a file using readlines: ``` class Foo: def __init__(self, filename): with open(filename, "r") as fp: self.data = fp.readlines() ``` with sanity checks etc. included. Now I am trying to create a mock object that would allow me to test what happens here. I try something like this: ``` TEST_DATA = "foo\nbar\nxyzzy\n" with patch("my.data.class.open", mock_open(read_data=TEST_DATA), create=True) f = Foo("somefilename") self.assertEqual(.....) ``` The problem is, when I peek into f.data, there is only one element: ``` ["foo\nbar\nxyzzy\n"] ``` Which means whatever happened, did not get split into lines but was treated as one line. How do I force linefeeds to happen in the mock data?<issue_comment>username_1: This will not work with a class name ``` with patch("mymodule.class_name.open", ``` But this will work by mocking the builtin directly, `builtins.open` for python3 ``` @mock.patch("__builtin__.open", new_callable=mock.mock_open, read_data=TEST_DATA) def test_open3(self, mock_open): ... ``` or this without class by mocking the module method ``` def test_open(self): with patch("mymodule.open", mock.mock_open(read_data=TEST_DATA), create=True): ... ``` Upvotes: 3 <issue_comment>username_2: @username_1's answer pointed me to the right direction but it's not a complete working solution. I have added few details here which makes it a working code without any tinkering. ``` # file_read.py def read_from_file(): # Do other things here filename = "file_with_data" with open(filename, "r") as f: l = f.readline() return l ``` ``` # test_file_read.py from file_read import read_from_file from unittest import mock import builtins @@mock.patch.object(builtins, "open", new_callable=mock.mock_open, read_data="blah") def test_file_read(mock_file_open): output = read_from_file() expected_output = "blah" assert output == expected_output ``` Upvotes: 0
2018/03/17
688
2,321
<issue_start>username_0: I would like to delete a line containing `"electron-inspector": "0.1.4",` from .package.json The following is not working. `sed -i '' -e 'electron-inspector' ./package.json` What do I have to change?<issue_comment>username_1: You could do this, but **[sed](/questions/tagged/sed "show questions tagged 'sed'") in not a JSON parser !** [![warning](https://i.stack.imgur.com/jruz4.png)](https://i.stack.imgur.com/jruz4.png) ``` sed -i '' -e '/electron-inspector/d' file ``` (`-i ''` is required for macOS's sed) Imagine a simple (*inline*) case like this : ``` {"foo": 123, "electron-inspector": "0.1.4", "bar": 42 } ``` **BOOOM !** So : The proper way, using [jq](/questions/tagged/jq "show questions tagged 'jq'") : ------------------------------------------------------------------------------- ``` jq -r 'del(.["electron-inspector"])' file.json > _.json && mv _.json file.json ``` The dash `-` is a [special case for jq](https://github.com/stedolan/jq/issues/38) If instead you had a simple case, the command would be : ``` jq 'del(.electroninspector)' file.json ``` --- Check [JQ](https://stedolan.github.io/jq/) --- Another solution using [nodejs](/questions/tagged/nodejs "show questions tagged 'nodejs'") and... [javascript](/questions/tagged/javascript "show questions tagged 'javascript'") : ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ``` cat file.json {"foo": 123, "electron-inspector": "0.1.4", "bar": 42 } ``` ### Code : ``` $ node< \_.json && mv \_.json file.json var o = $(< file.json); delete o["electron-inspector"]; console.log(JSON.stringify(o, null, 4)); EOF ``` ### Edited file : ``` { "foo": 123, "bar": 42 } ``` --- Last but not least, to edit the file properly using `sponge` : -------------------------------------------------------------- Instead of : `> x.json && mv x.json file.json`, we can do : ``` command ...... file.json | sponge file.json ``` You need [moreutils](/questions/tagged/moreutils "show questions tagged 'moreutils'") installed. Upvotes: 5 [selected_answer]<issue_comment>username_2: I got it to work with: `sed -i '/electron-inspector/d' package.json` Upvotes: -1
2018/03/17
498
1,865
<issue_start>username_0: Im trying to get the headers from the server response after awaiting a jQuery post request. ``` var res = await $.post(GetUrl("/accounts"), JSON.stringify(acc)); ``` will return only the body, while ``` var accs = await $.get(GetUrl("/accounts")); ``` will return an object from which I can get some headers (not all) and the body. Is there any way to fix that?<issue_comment>username_1: The point of `$.post()` is to be a convenient shortcut. When you use it with `await`, you'll effectively get only the first parameter that would have been passed into the Promise resolution callback had you used traditional Promise coding: ``` $.post(GetUrl("/accounts"), JSON.stringify(acc)) .then(function(data, status, jqxhr) { // ... }); ``` You're only getting `data`. If you code it as above, then that third parameter will be your (jQuery extended) XHR object. Note that your use of `$.get()` will mean that `accs` will be the promise returned, and you don't know that the operation has completed. Upvotes: 0 <issue_comment>username_2: `await` uses `then` on the object it's given (somewhat indirectly). jQuery's `ajax` calls `then` callbacks with three arguments (whereas a normal promise calls `then` callbacks with exactly one argument). Because of that mis-match, you're only getting the *first* argument jQuery's `ajax` calls `then` with. You can convert the return value (these are promises, they're a pipeline) so you get all three things that jQuery's `ajax` calls the callback with: ``` const [data, textStatus, jqXHR] = await $.post("/echo/html/", {html: "Hi there", delay: 1}) .then((data, textStatus, jqXHR) => [data, textStatus, jqXHR]); ``` [Live Example on jsFiddle](https://jsfiddle.net/17m6241d/) This is only necessary because of jQuery's unusual implementation. Upvotes: 3 [selected_answer]
2018/03/17
613
2,266
<issue_start>username_0: I have a stored proc which looks like this: ``` create function search_contacts (_name text, _phone text, _email text, _address text, _threshold real) returns setof contact as $func$ declare _id uuid := uuid_generate_v4(); begin insert into _contact_index_tmp select...; insert into _contact_index_tmp select...; return query select c.* from _contact_index_tmp tmp left join contact c on tmp.guid = c.contact_guid and tmp.query_id = _id; delete from _contact_index_tmp tmp where tmp.query_id = _id; return; end $func$ language plpgsql; ``` I get the results I want (from the return query statement), but the final delete statement is not getting executed, which I use to clean up my temp table. How can I ensure this is executed?<issue_comment>username_1: The point of `$.post()` is to be a convenient shortcut. When you use it with `await`, you'll effectively get only the first parameter that would have been passed into the Promise resolution callback had you used traditional Promise coding: ``` $.post(GetUrl("/accounts"), JSON.stringify(acc)) .then(function(data, status, jqxhr) { // ... }); ``` You're only getting `data`. If you code it as above, then that third parameter will be your (jQuery extended) XHR object. Note that your use of `$.get()` will mean that `accs` will be the promise returned, and you don't know that the operation has completed. Upvotes: 0 <issue_comment>username_2: `await` uses `then` on the object it's given (somewhat indirectly). jQuery's `ajax` calls `then` callbacks with three arguments (whereas a normal promise calls `then` callbacks with exactly one argument). Because of that mis-match, you're only getting the *first* argument jQuery's `ajax` calls `then` with. You can convert the return value (these are promises, they're a pipeline) so you get all three things that jQuery's `ajax` calls the callback with: ``` const [data, textStatus, jqXHR] = await $.post("/echo/html/", {html: "Hi there", delay: 1}) .then((data, textStatus, jqXHR) => [data, textStatus, jqXHR]); ``` [Live Example on jsFiddle](https://jsfiddle.net/17m6241d/) This is only necessary because of jQuery's unusual implementation. Upvotes: 3 [selected_answer]
2018/03/17
1,902
7,459
<issue_start>username_0: From a quick read of the Kubernetes docs, I noticed that the kube-proxy behaves as a Level-4 proxy, and perhaps works well for TCP/IP traffic (s.a. typically HTTP traffic). However, there are other protocols like SIP (that could be over TCP or UDP), RTP (that is over UDP), and core telecom network signaling protocols like DIAMETER (over TCP or SCTP) or likewise M3UA (over SCTP). Is there a way to handle such traffic in application running in a Kubernetes minion ? In my reading, I have come across the notion of Ingress API of Kuberntes, but I understood that it is a way to extend the capabilities of the proxy. Is that correct ? Also, it is true that currently there is no known implementation (open-source or closed-source) of Ingress API, that can allow a Kubernetes cluster to handle the above listed type of traffic ? Finally, other than usage of the Ingress API, is there no way to deal with the above listed traffic, even if it has performance limitations ?<issue_comment>username_1: > > Also, it is true that currently there is no known implementation (open-source or closed-source) of Ingress API, that can allow a Kubernetes cluster to handle the above listed type of traffic ? > > > Probably, and this [IBM study on IBM Voice Gateway "Setting up high availability"](https://www.ibm.com/support/knowledgecenter/en/SS4U29/ha.html) [![https://www.ibm.com/support/knowledgecenter/SS4U29/images/ha.png](https://i.stack.imgur.com/2LWln.png)](https://i.stack.imgur.com/2LWln.png) (here with [SIPs (Session Initiation Protocol)](https://en.wikipedia.org/wiki/Session_Initiation_Protocol), [like OpenSIPS](https://www.opensips.org/About/About)) > > Kubernetes deployments > ---------------------- > > > In Kubernetes terminology, a single voice gateway instance equates to a single pod, which contains both a SIP Orchestrator container and a Media Relay container. > > The voice gateway pods are installed into a Kubernetes cluster that is fronted by an external SIP load balancer. > > Through Kubernetes, a voice gateway pod can be scheduled to run on a cluster of VMs. The framework also monitors pods and can be configured to automatically restart a voice gateway pod if a failure is detected. > > > Note: **Because auto-scaling and auto-discovery of new pods by a SIP load balancer in Kubernetes are not currently supported, an external SIP**. > > > And, to illustrate Kubernetes limitations: > > Running IBM Voice Gateway in a Kubernetes environment requires special considerations beyond the deployment of a typical HTTP-based application because of the protocols that the voice gateway uses. > > > **The voice gateway relies on the SIP protocol for call signaling and the RTP protocol for media, which both require affinity to a specific voice gateway instance. To avoid breaking session affinity, the Kubernetes ingress router must be bypassed for these protocols**. > > > **To work around the limitations of the ingress router, the voice gateway containers must be configured in host network mode.** > > In host network mode, when a port is opened in either of the voice gateway containers, those identical ports are also opened and mapped on the base virtual machine or node. > > This configuration also eliminates the need to define media port ranges in the kubectl configuration file, which is not currently supported by Kubernetes. Deploying only one pod per node in host network mode ensures that the SIP and media ports are opened on the host VM and are visible to the SIP load balancer. > > > --- That network configuration put in place for Kubernetes is best illustrated in [this answer](https://stackoverflow.com/a/48104579/6309), which describes the elements involved in pod/node-communication: [![https://i.stack.imgur.com/APpSf.png](https://i.stack.imgur.com/APpSf.png)](https://i.stack.imgur.com/APpSf.png) Upvotes: 4 [selected_answer]<issue_comment>username_2: It is possible to handle TCP and UDP traffic from clients to your service, but it slightly depends where you run Kubernetes. Solutions ========= A solution which working everywhere ----------------------------------- It is possible to use Ingress for both TCP and UDP protocols, not only with HTTP. Some of the Ingress implementations has a support of proxying that types of traffic. Here is an [example](https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/exposing-tcp-udp-services.md) of that kind of configuration for Nginx Ingress controller **for TCP**: `apiVersion: v1 kind: ConfigMap metadata: name: tcp-configmap-example data: 9000: "default/example-go:8080" here is a "$namespace/$service_name:$port"` **And UDP:** `apiVersion: v1 kind: ConfigMap metadata: name: udp-configmap-example data: 53: "kube-system/kube-dns:53" # here is a "$namespace/$service_name:$port"` So, actually, you can run your application which needs plain UDP and TCP connections with some limitations (you need somehow manage a load balancing if you have more than one pod etc). But if you now have an application which can do it now, without Kubernetes - I don't think that you will have any problems with that after migration to Kubernetes. **A Small example of a traffic flow** For SIP UDP traffic, for an example, you can prepare configuration like this: *Client -> Nginx Ingress (UDP) -> OpenSIPS Load balancer (UDP) -> Sip Servers (UDP).* So, the client will send packets to Ingress, it will forward it to OpenSIPS, which will manage a state of your SIP cluster and send clients packets to a proper SIP server. A solution only for Clouds -------------------------- Also, if you will run in on Cloud, you can use `ServiceType` [LoadBalancer](https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/) for your [Service](https://kubernetes.io/docs/concepts/services-networking/service/) and get TCP and UDP traffic to your application directly thru External Load Balancer provided by a cloud platform. About SCTP ========== What about **SCTP**, unfortunately, no, that is **not supported yet**, but you can track a progress [here](https://github.com/cloudnativelabs/kube-router/issues/266). Upvotes: 2 <issue_comment>username_3: With regard to SCTP support in k8s: it has been merged recently into k8s as alpha feature. SCTP is supported as a new protocol type in Service, NetworkPolicy and Pod definitions. See the PR here: <https://github.com/kubernetes/kubernetes/pull/64973> Some restrictions exist: * the handling of multihomed SCTP associations was not in the scope of the PR. The support of multihomed SCTP associations for the cases when NAT is used is a much broader topic which affects also the current SCTP kernel modules that handle NAT for the protocol. See an example here: <https://datatracker.ietf.org/doc/html/draft-ietf-tsvwg-natsupp-12> From k8s perspective one would also need a CNI plugin that supports the assignment of multiple IP addresses (on multiple interfaces preferably) to pods, so the pod can establish multihomed SCTP association. Also one would need an enhanced Service/Endpoint/DNS controller to handle those multiple IP addresses on the right way. * the support of SCTP as protocol for type=LoadBalancer Services is up to the load balancer implementation, which is not a k8s issue * in order to use SCTP in NetworkPolicy one needs a CNI plugin that supports SCTP in NetworkPolicies Upvotes: 2
2018/03/17
1,364
4,696
<issue_start>username_0: I am a newbie and I will try to be as clear as possible. This is about odersky scala course. I have this code below. I understand that this is an alias type to define a Scala Set differently that the traditional way you define a Set in Scala(i.e. a Scala collection). In this type alias, you give it a integer and returns true (somehow) if the item is contained in the Set. `type Set = Int => Boolean` Now I have this piece of code, which returns the result i am expecting. ``` val a = Set("element is contained in set") type Set = Int => Boolean a.contains("element is contained in set") a.contains("element IS NOT contained in set") ``` The result is: ``` a: scala.collection.immutable.Set[String] = Set(element is contained in set) defined type alias Set res0: Boolean = true res1: Boolean = false res2: scala.collection.immutable.Set[String] = Set(element is contained in set) ``` Great! Now i introduce a line in the code. ``` val a = Set("element is contained in set") type Set = Int => Boolean a.contains("element is contained in set") a.contains("element IS NOT contained in set") **def custom_fc(x:Double): Set[String] = Set(x.toString)** ``` I get the error: ``` Error:(8, 24) A$A235.this.Set does not take type parameters def custom_fc(x:Double): Set[String] = Set(x.toString) Error:(38, 97) inst$A$A.Set does not take type parameters println("custom_fc: " + MacroPrinter211.printGeneric({import inst$A$A._ ;def `custom_fc(x:Double): Set[String] = Set(x.toString) }).replace("inst$A$A.", ""))` ``` WHY? In this line i am just trying to define a regular fc (i.e. custom\_fc) taking Int as input and returning a traditional scala datastructure Set[String] ``` type Set = Int => Boolean **def custom_fc(x:Double): Set[String] = Set(x.toString)** ``` Why does my custom fc definition interfere with the alias before it? My custom\_fc is ``` custom_fc(x:Double): scala.collection.immutable.Set[String] = scala.collection.immutable.Set(x.toString) ``` thank you ps. a way to use `Type Set = Int => Boolean` ``` val belowNegFive: Set = (i) => i < -5 belowNegFive(10) ``` Return a bool dependinf if the elem 10 pertains to the set of numbers below -5.<issue_comment>username_1: So you're obviously overriding the Set alias that was already in place. You can fix this by as mentioned in the comments, specifying exactly which Set you mean. ``` def custom_fc(x:Int): scala.collection.immutable.Set[String] = Set(x.toString) ``` Also note your type alias is not doing anything. Your calls `a("element is contained in set") a("element IS NOT contained in set")` are just calling the apply method on a, which is the same thing as doing `a.apply(...)` and `a.contains(...)` In order to make it easier on yourself and less confusing overall, maybe change the name to `Contains`? To see an example of **your** set being used, here you go... ``` val setBeingUsed: Set = Set(1).contains setBeingUsed(1) // true ``` The method which takes in an Int and returns a boolean can be assigned the type `Set` because you aliased that type to it. Then we can call the val we made with type `Set` and essentially do the same thing as calling contains on the set. Upvotes: 0 <issue_comment>username_2: Here's what's going on. ``` val a = Set("element is contained in set") // a is old library Set() type Set = Int => Boolean // alias now hides library Set() a.contains("element is contained in set") // a is still old library a.contains("element IS NOT contained in set") // and works like it should def custom_fc(x:Double): Set[String] = Set(x.toString) // WRONG // new Set alias works different from old library Set() ``` The point of the class is to work with functions. The `Set` alias is a function definition: `Int => Boolean` i.e. takes an `Int` and returns a `Boolean`. The new `Set` alias is very different from the `Set` collection and can't be used the same way. The `Set` alias does appear to imitate the collection only in that you can query its "content" in the same way, but only when working with `Int` values. Even then, the means of initialization is different. ``` val libSet: collection.Set[Int] = Set(7) // initialize with a 7 type Set = Int => Boolean val newSet: Set = (x:Int) => x == 7 // initialize with a 7 libSet(7) // true libSet(4) // false newSet(7) // true newSet(4) // false ``` The library collection works with other types but the `Set` alias only takes an `Int` and returns a `Boolean`. The new `Set` is a type alias for a function definition. An instance of the new `Set` is a function that imitates only a small subset of what the real `Set` does. Upvotes: 1
2018/03/17
839
3,026
<issue_start>username_0: I have a dropdown that should display different things depending on the selected value: * When I select "test 1", it should display grid 1 * When I select "test 2", it should not display anything. Unfortunately, it's displaying the grid also from another dropdown value. Could you please tell me how to fix it? Providing my code below. <http://jsfiddle.net/950gacs0/> ``` if ($('#combo :selected').text() === "Test 1") { alert("test 1 selected"); $("#grid1").show(); } else { alert("test 2 selected"); } ```<issue_comment>username_1: So you're obviously overriding the Set alias that was already in place. You can fix this by as mentioned in the comments, specifying exactly which Set you mean. ``` def custom_fc(x:Int): scala.collection.immutable.Set[String] = Set(x.toString) ``` Also note your type alias is not doing anything. Your calls `a("element is contained in set") a("element IS NOT contained in set")` are just calling the apply method on a, which is the same thing as doing `a.apply(...)` and `a.contains(...)` In order to make it easier on yourself and less confusing overall, maybe change the name to `Contains`? To see an example of **your** set being used, here you go... ``` val setBeingUsed: Set = Set(1).contains setBeingUsed(1) // true ``` The method which takes in an Int and returns a boolean can be assigned the type `Set` because you aliased that type to it. Then we can call the val we made with type `Set` and essentially do the same thing as calling contains on the set. Upvotes: 0 <issue_comment>username_2: Here's what's going on. ``` val a = Set("element is contained in set") // a is old library Set() type Set = Int => Boolean // alias now hides library Set() a.contains("element is contained in set") // a is still old library a.contains("element IS NOT contained in set") // and works like it should def custom_fc(x:Double): Set[String] = Set(x.toString) // WRONG // new Set alias works different from old library Set() ``` The point of the class is to work with functions. The `Set` alias is a function definition: `Int => Boolean` i.e. takes an `Int` and returns a `Boolean`. The new `Set` alias is very different from the `Set` collection and can't be used the same way. The `Set` alias does appear to imitate the collection only in that you can query its "content" in the same way, but only when working with `Int` values. Even then, the means of initialization is different. ``` val libSet: collection.Set[Int] = Set(7) // initialize with a 7 type Set = Int => Boolean val newSet: Set = (x:Int) => x == 7 // initialize with a 7 libSet(7) // true libSet(4) // false newSet(7) // true newSet(4) // false ``` The library collection works with other types but the `Set` alias only takes an `Int` and returns a `Boolean`. The new `Set` is a type alias for a function definition. An instance of the new `Set` is a function that imitates only a small subset of what the real `Set` does. Upvotes: 1
2018/03/17
332
1,085
<issue_start>username_0: There is `QListWidget`. If I add an item with the text like "Line1\nLine2" I get an item containing a one string. How can I make this item containing two strings?<issue_comment>username_1: You could add two lines to `QListWidget` in two way: First: ``` listWidget->addItem(tr("Line1\nLine2")); ``` or ``` new QListWidgetItem(tr("Line4\nLine5"), listWidget); ``` and that should work as per common testing. Second, and the better way is to add multiple items using `addItems()` with `QStringList` ``` QStringList items; items << "Line1"; items << "Line2"; listWidget->addItems(items); ``` Upvotes: 0 <issue_comment>username_2: It seems that the editor adds one more backslash as the following image shows: [![enter image description here](https://i.stack.imgur.com/3facm.png)](https://i.stack.imgur.com/3facm.png) The solution is simple, you must edit the text in Object Inspector and add it there directly as I show below: [![enter image description here](https://i.stack.imgur.com/DNB6B.png)](https://i.stack.imgur.com/DNB6B.png) Upvotes: 1
2018/03/17
749
2,191
<issue_start>username_0: I'm trying to develop a simple program that finds decimal numbers that are equal to the average of their digits. Example 4.5 (4+5=9 / 2)= 4.5 In order to do this I need to take averages that have several decimal points and compare them to a big iterated list of decimal numbers (I'm using a nested loop to do this). When I use the Decimal library to do simple division, the answer comes out with four decimal points, like I want: 0.2727 But when I try to print the the averages of my loop. **(Decimal(i + y + z + q)) / Decimal(4))** the averages only come out to the hundredth decimal point **(0.25 0.5 0.75, etc)**. Why? I've tried converting into str() and int() before passing into Decimal() and it doesn't work. ``` from decimal import * getcontext().prec = 4 print(Decimal(3)/Decimal(9)) numbers1to10 = [0,1,2,3,4,5,6,7,8,9] for i in numbers1to10: for y in numbers1to10: for z in numbers1to10: for q in numbers1to10: if: (Decimal(i + y + z + q)) / Decimal(4)) == ((Decimal(i))+ (Decimal(y)/10) + (Decimal(z)/100)+ (Decimal(q)/1000)): print (((Decimal(i))+ (Decimal(y)/10) + (Decimal(z)/100) + (Decimal(q)/1000))) ```<issue_comment>username_1: Can't say for sure, but those numbers (0.25 0.5 0.75) look quite "round" to me, by that I mean that they are just 1/4, 2/4 and 3/4 and they don't have any other decimals to show. Then it's normal that you only get to the hundredth. 0.5 is 0.5, no need to show 0.5000. If you really want to show to 4 decimals with additional zeroes at the end, use the format functions. Example: ``` print("%.4f" % 0.5) ``` Displays `0.5000`. Upvotes: 0 <issue_comment>username_2: `0.5` is as precise as it can be. If you want to ensure a fixed width during printing, use [string formatting](https://docs.python.org/3/library/string.html#format-specification-mini-language) ``` a = decimal.Decimal(2)/decimal.Decimal(4) print(f'{a:1.4f}') #Python v3.6+ print('{:1.4f}'.format(a)) >>> 0.5000 0.5000 ``` --- [Formatted String Literals (new in version 3.6)](https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals) Upvotes: 1
2018/03/17
616
1,816
<issue_start>username_0: I am very new to HTML programming. I have created a webpage which will ask for password and then proceed to the next webpage, but my password is visible when i enter it in the webpage. how can i change it into bullets or \* ? This is the HTML code : ``` ![TCIL](logo page.jpg) Corporate Social Responsibility function passWord() { var testV = 1; var pass1 = prompt('Please Enter Your Password',' '); while (testV < 3) { if (!pass1) history.go(-1); if (pass1.toLowerCase() == "<PASSWORD>") { alert('password accepted'); window.open('E:/MyCSRAPP/expense statement/400140.htm'); break; } testV+=1; var pass1 = prompt('Access Denied - Password Incorrect, Please Try Again.','Password'); } if (pass1.toLowerCase()!="password" & testV ==3) history.go(-1); return " "; } ``` Please help me out if any option is there<issue_comment>username_1: Can't say for sure, but those numbers (0.25 0.5 0.75) look quite "round" to me, by that I mean that they are just 1/4, 2/4 and 3/4 and they don't have any other decimals to show. Then it's normal that you only get to the hundredth. 0.5 is 0.5, no need to show 0.5000. If you really want to show to 4 decimals with additional zeroes at the end, use the format functions. Example: ``` print("%.4f" % 0.5) ``` Displays `0.5000`. Upvotes: 0 <issue_comment>username_2: `0.5` is as precise as it can be. If you want to ensure a fixed width during printing, use [string formatting](https://docs.python.org/3/library/string.html#format-specification-mini-language) ``` a = decimal.Decimal(2)/decimal.Decimal(4) print(f'{a:1.4f}') #Python v3.6+ print('{:1.4f}'.format(a)) >>> 0.5000 0.5000 ``` --- [Formatted String Literals (new in version 3.6)](https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals) Upvotes: 1