text
stringlengths
70
452k
dataset
stringclasses
2 values
Request parameter in jsp As you know in asp, we can do Response.Write("page.aspx?id=3"); On the other page Request.QueryString["id"]; Well, i want to do samething in jsp using servlets through doGet() and do Post() method. I want to ask how it can be done? In the doGet or doPost you have access to the request object. So, you can do request.getParameter("id") can i pass multiple parameters at once.....? like in asp page.aspx?id=2&c_id=4 @user yes <!------------------->
common-pile/stackexchange_filtered
How can I show/hide points in OpenGL based on user input? I have a "draw" function which currently just uses an interaction file to draw points based on the left mouse click from the user. The drawing of the points works fine, but I can not figure out how to "hide" the points based on a user command. Currently, I have a menu setup which is activated by a middle mouse click, and one option is to "Show/Hide Control Points", but it will not work. I am drawing the points as follows: void draw(int mode) { unsigned int i; // The following lines draw all the points glColor3f (0.0, 1.0, 1.0); glPointSize(5.0); glBegin(GL_POINTS); for (i=0; i<C->B.size(); i++) glVertex2f(C->B[i].x, C->B[i].y); glEnd(); } Initially, I had tried to define an integer called showCtrlPts, which gloablly was set equal to 1. I set up a selectMessage function, which treated each selection from the middle button menu as a case. For the show/hide points case, I simply changed the value of the showCtrlPts integer and thought that that would do it (see below). Only it didn't work and now I'm somewhat lost as to how to proceed. void selectMessage(int msg) { switch (msg) { case 1: if (!C->B.empty()) C->B.clear(); glutPostRedisplay(); break; case 2: glutPositionWindow(50, 50); glutReshapeWindow(600, 400); break; case 3: glutFullScreen(); break; case 4: if (showCtrlPts == 1) { showCtrlPts = 0; glColor3f(0.0, 0.0, 0.0); } if (showCtrlPts != 1) { showCtrlPts = 1; glColor3f(0.0, 1.0, 1.0); } break; case 10: exit(0); break; default: break; } glutPostRedisplay(); } The showCtrlPts approach is the right way to go. Show how you used this variable. I have shown it in the code above, under case 4. I obviously am missing something but I haven't yet figured out what that something is. warning: you're trying to learn a very outdated version of OpenGL In function void draw(int mode) comment line glColor3f (0.0, 1.0, 1.0);
common-pile/stackexchange_filtered
Nginx serving css, but just half of it I just upload a website Django application on AWS using NGINX and uwsgi protocol. The website is running fine but only part of the minified version of CSS is loaded. More specificaly the part of the css which configures the footer section of the page doesn't load. But all the CSS is in the same file. NGINX conf file is something like this: `upstream django { server unix:///home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu /mysite.sock; } server { listen 8000; server_name example.com; charset utf-8; client_max_body_size 75M; location /media { alias /home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu/media; } location /static { alias /home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu/static; } location / { uwsgi_pass django; include /home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu/uwsgi_params; } } ` if its all in the same file, then you might have a caching problem., also check the file for EOF's If you made changes to the css file (or any modification inside your static directory), don't forget to run ./manage.py collectstatic again.
common-pile/stackexchange_filtered
javascript form.submit() losing querystring created by GA _linkByPost We have a booking form that POSTs to the parent company website. Because this is a different domain we need to implement the GA _linkByPost to pass the GA tracking cookie info across domains. As the booking form is in a .NET user control it does a postback. On postback we validate, wrap up the booking info, and write a form back to the client with hidden elements required by the target booking engine and add line of javascript to submit the form. Below is the javascript function I'm using to submit the form: function postBookingForm() { var thisForm = document.getElementById('PostForm'); _gaq.push(['_linkByPost', thisForm]); thisForm.submit(); } And the relevant form info: <form id="PostForm" name="PostForm" action="ClientBookingEngineUrl" method="post" > booking form info in here </form> The result is that we fill in the form, hit submit which does a round trip to the server generates a new form and POSTs the info. This all works fine apart from the URL loses the GA cookie info from the query string. If I comment out the form submit line and look at source code I can see the GA cookie info on the querystring - but when posting, I do not see the querystring (using Fiddler). To clarify: The above technique works and does what we want with regards to POSTing form data to the booking engine and taking the user there. If the submit line is commented out you can see the form with the modified action that has the GA stuff appended (using Firebug). If the form is submitted with the submit line, the querystring info is removed (confirmed by Fiddler). Am I missing something obvious? Are there some gotchas regarding JS submit, form POSTs and querystrings? Or is there a simple trick I'm missing? Cheers EDIT 1 An oddity has occured. If I alert the form action before and after the _gaqPush then we can see the URL in its before and after state and it's as expected. alert('1 form action = ' + thisForm.action); _gaq.push(['_linkByPost', thisForm]); alert('2 form action = ' + thisForm.action); Alert 1 shows the pre-modified action and alert 2 shows the action with the GA info. With the alerts in place it submits WITH the GA info in the query string. If I comment out the alerts the GA info is NOT in the query string... I'm starting to think the form or something is not ready so I'm trying it with JQuery's document ready. EDIT 2 Wrapping the method call in document ready doesn't help. I'm confused as to why action URL is correct AFTER displaying it in an alert but incorrect if I don't alert it. Thanks for typo corrections. I know the difference between loose and lose honest. I blame it on stress :) Answering this for posterity. The problem is the _qaq (Google Analytics Queue) hasn't had time to modify the form before the call to submit() the form. The solution is to push a function onto the _gaq object that submits the form so it will happen directly after the form modification is done. function postBookingForm() { var thisForm = document.getElementById('PostForm'); _gaq.push(['_linkByPost', thisForm]); _gaq.push(function() { thisForm.submit(); }); } Does this mean I can use this instead of a delay? That is correct - this will run correctly without resorting to delays or timeout functions since all things pushed to the queue run sequentially in the order they were pushed, one at a time. So the submit happens after modifying the form. I tried a simple HTML page that calls _gaqPush and submits immediately. This also fails. Adding a 1000ms delay works (for the most part) so I suspect the alerts just gave the GA script time to modify the form. I'm closing/accepting this as it seems down to submitting the form too quickly after the GA call.
common-pile/stackexchange_filtered
Why can't attribute names be Python keywords? There is a restriction on the syntax of attribute access, in Python (at least in the CPython 2.7.2 implementation): >>> class C(object): pass >>> o = C() >>> o.x = 123 # Works >>> o.if = 123 o.if = 123 ^ SyntaxError: invalid syntax My question is twofold: Is there a fundamental reason why using Python keyword attribute names (as in o.if = 123) is forbidden? Is/where is the above restriction on attribute names documented? It would make sense to do o.class = …, in one of my programs, and I am a little disappointed to not be able to do it (o.class_ would work, but it does not look as simple). PS: The problem is obviously that if and class are Python keywords. The question is why using keywords as attribute names would be forbidden (I don't see any ambiguity in the expression o.class = 123), and whether this is documented. Because parser is simpler when keywords are always keywords, and not contextual. So the code doesn't even get to the point where there's attribute access, it's simply a syntax error on the parsing level (because if is part of the grammar and it never appears in this place). It's the same in most languages, and language grammar is the documentation for that. Also, cls is usually used for names holding references to classes. Even if you have a parser that's can distinguish keywords from variables/function names, it's no guarantee that one might shadow the other in a corner case. It's much easier to maintain sanity if you just straight-out forbid the use of a few dozen names. @CatPlusPlus: Nice answer. Simply a design decision for efficiency of the parser. Python idiom is if_, while_, exec_, etc for keyword name conflicts. _foo is considered a pattern for protected attributes @CatPlusPlus: answer, not comment. You've actually answered it while the present answers don't answer at all. I came across this issue using argparse--one of my flags was '-or' and using 'args.or' caused a parsing error. I ran into the same problem as part of argparse. I had the argument "-or" but could only access the value by using getattr(). Because parser is simpler when keywords are always keywords, and not contextual (e.g. if is a keyword when on the statement level, but just an identifier when inside an expression — for if it'd be double hard because of X if C else Y, and for is used in list comprehensions and generator expressions). So the code doesn't even get to the point where there's attribute access, it's simply rejected by the parser, just like incorrect indentation (which is why it's a SyntaxError, and not AttributeError or something). It doesn't differentiate whether you use if as an attribute name, a variable name, a function name, or a type name. It can never be an identifier, simply because parser always assigns it "keyword" label and makes it a different token than identifiers. It's the same in most languages, and language grammar (+ lexer specification) is the documentation for that. Language spec mentions it explicitly. It also doesn't change in Python 3. Also, just because you can use setattr or __dict__ to make an attribute with a reserved name, doesn't mean you should. Don't force yourself/API user to use getattr instead of natural attribute access. getattr should be reserved for when access to a variable attribute name is needed. So it is how teacher tell us in compiler classes. This is how compilers are classically built. Tokens are split, classified into categories, and then analyzed if they make sense by the parser. Every special symbol like + or : has its own (unitary) category, as well as every reserved word ("if", "or", "class", "def", etc). Every other word belongs to a special category: the identifiers. Since "if" is not an identifier, it can not name an attribute, simple as that. I am not saying it is impossible to build a compiler/code analyzer in some other way, just this is how things are done these days... @Ivella: +1 for the very relevant comment. @CatPlusPlus: Agreed, about getattr and __dict__. I was just mentioning these because they show that attributes names can be keywords even though the usual object.attribute syntax forbids it. @EOL: It again comes down to syntax. 'if' is always a string literal, and never a keyword. And since attributes are kept in dicts, any string will do. Because if is a keyword. You have similar issues with o.while and o.for: pax> python >>> class C(object): pass ... >>> o = C() >>> o.not_a_keyword = 123 >>> o.if = 123 File "<stdin>", line 1 o.if = 123 ^ SyntaxError: invalid syntax >>> o.while = 123 File "<stdin>", line 1 o.while = 123 ^ SyntaxError: invalid syntax >>> o.for = 123 File "<stdin>", line 1 o.for = 123 ^ SyntaxError: invalid syntax Other keywords in Python can be obtained with: >>> import keyword >>> keyword.kwlist ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] You should not generally use a keyword as variable name in Python. I would suggest choosing a more descriptive name, such as iface if it's an interface, or infld for an input field and so forth. As to your question edit as to why keywords aren't allowed, it simplifies parsers greatly if the lexical elements are context free. Having to treat the lexical token if as a keyword in some places and an identifier in others would introduce complexity that's not really needed if you choose your identifiers more wisely. For example, the C++ statement: long int int = char[new - int]; could (with a little difficulty) be evaluated with a complex parser based on where those lexical elements occur (and what exists on either side of them). But, (at least partially) in the interests of simplicity (and readability), this is not done. Yes, indeed. I updated the title of the question so as to make explicit the fact that the question is why keywords would be forbidden as attribute names. In fact, in o.class = 123, it is obvious that class should be an attribute name; however, this is not valid (C)Python; there must be good reasons why this should not be obvious to the CPython interpreter: what are these reasons?
common-pile/stackexchange_filtered
prob with laravel input not found I am trying to take a variable from a textbox called 'skill' and dump whatever is typed but I get: HandymanController.php line 32: Fatal error: Class 'App\Http\Controllers\Input' not found How come? It's a built-in feature isn't it? $searchTerm = Input::get('skill'); var_dump($searchTerm); In Laravel 5.2, the Input alias was removed. You can still use it by adding it to your config/app.php file, but rather than doing that, the simplest way is probably to use the request() helper function: $searchTerm = request('skill'); You can also use the Request facade: use Request; $searchTerm = Request::input('skill'); You can even use method injection: use Illuminate\Http\Request; public function someControllerMethod(Request $request) { $searchTerm = $request->skill; } But in my opinion, the simplest way is the helper function (the first suggested method) since you don't need to "import" anything. Add use Input; to the top of your class or use it like this: $searchTerm = \Input::get('skill'); Alternatively, you could use $request->input: $searchTerm = $request->input('skill'); I did use Input; and now I get Fatal error: Class 'Input' not found Look carefully, you should add \ before Input. What error do you get? Did you try $request->input('skill');? If yes, what error does it creates? Or it's working?
common-pile/stackexchange_filtered
Eclipse does not show variable values on hover I remember, Eclipse was showing variable values during debug and on mouse hover. Unfortunately, currently it does not work for me. Instead of value, it shows FQN of the variable. How to fix? In Eclipse's Debug View (http://www.edu4java.com/_img/java/after-eclipse-debug-perspective.png), make sure your current thread and current class are selected. Sometimes (on my system anyway) Eclipse focuses a different class or thread to what my breakpoint actually hit. Then I can't hover over the variables until I select the right ones. You can select a variable --> right click --> Whatch
common-pile/stackexchange_filtered
Python: Division by larger numbers slower? Why does dividing by the larger factor pair result in slower execution? My solution for https://codility.com/programmers/task/min_perimeter_rectangle/ from math import sqrt, floor # This fails the performance tests def solution_slow(n): x = int(sqrt(n)) for i in xrange(x, n+1): if n % i == 0: return 2*(i + n / i)) # This passes the performance tests def solution_fast(n): x = int(sqrt(n)) for i in xrange(x, 0, -1): if n % i == 0: return 2*(i + n / i) It's not division that slows it down; it's the number of iterations required. Let L = xrange(0, x) (order doesn't matter here) and R = xrange(x, n+1). Every factor of n in L can be paired with exactly one factor of n in R. In general, x is much, much smaller than n/2, so L is much smaller than R. This means that there are far more elements of R that don't divide n than there are in L. In the case of a prime number, there are no factors, so the slow solution has to check every value of the much larger than instead of the much smaller set. That's obvious. The first function loops many more times. Note that sqrt(n) != n - sqrt(n)! in general sqrt(n) << n-sqrt(n) where << means much lesser than. If n=1000 the first function is looping 969 times while the second one only 32. I'd say the of iterations is the key which makes perfomance a little bit different between your functions as @Bakuriu already said. Also, xrange could be slightly more expensive than using a simple loop, for instance, take a look f3 will perform a little better than f1 & f2: import timeit from math import sqrt, floor def f1(n): x = int(sqrt(n)) for i in xrange(x, n + 1): if n % i == 0: return 2 * (i + n / i) def f2(n): x = int(sqrt(n)) for i in xrange(x, 0, -1): if n % i == 0: return 2 * (i + n / i) def f3(n): x = int(sqrt(n)) while True: if n % x == 0: return 2 * (x + n / x) x -= 1 N = 30 K = 100000 print("Measuring {0} times f1({1})={2}".format( K, N, timeit.timeit('f1(N)', setup='from __main__ import f1, N', number=K))) print("Measuring {0} times f1({1})={2}".format( K, N, timeit.timeit('f2(N)', setup='from __main__ import f2, N', number=K))) print("Measuring {0} times f1({1})={2}".format( K, N, timeit.timeit('f3(N)', setup='from __main__ import f3, N', number=K))) # Measuring 100000 times f1(30)=0.0738177938151 # Measuring 100000 times f1(30)=0.0753000788315 # Measuring 100000 times f1(30)=0.0503645315841 # [Finished in 0.3s] Next time, you got these type of questions, using a profiler is highly recommended :)
common-pile/stackexchange_filtered
How to convert fetch response to array buffer? Using a library like axios I can request data from a http request as an array buffer: async function get(url) { const options = { method: 'GET', url: url, responseType: "arraybuffer" }; const { data } = await axios(options); console.log(data) return data; } which prints: <Buffer 50 4b 03 04 14 00 00 00 08 00 3c ef bf bd ef bf bd 52 ef bf bd ef bf bd 3a ef bf bd 46 01 00 00 6f 03 00 00 14 00 00 00 45 43 5f 72 61 77 2f 76 61 72 ... 1740004 more bytes> Say I did't specify for data to come in as an array buffer or I used a simple fetch request: const response = fetch(url) How can I convert this response to an array buffer? I am trying to do this: const response = await this.get(test) const buffer = Buffer.from(response) console.log(buffer) Which is printing this: <Buffer 50 4b 03 04 14 00 00 00 08 00 3c ef bf bd ef bf bd 52 ef bf bd ef bf bd 3a ef bf bd 46 01 00 00 6f 03 00 00 14 00 00 00 45 43 5f 72 61 77 2f 76 61 72 ... 1740004 more bytes> The FetchAPI uses Response objects to represent the response to a request. To handle processing of the response body, there are several available methods. You may be familiar with Response.json as JSON is one of the most common ways to interpret the response Body, but there is also Response.arrayBuffer: async function get(url) { const response = await fetch(url); return response.arrayBuffer(); } Here is a clean way to achieve the same in vanilla js: const response = await fetch(url); const buffer = await response.arrayBuffer(); const bytes = new Uint8Array(buffer); console.log(bytes);
common-pile/stackexchange_filtered
php: looping thru results from mysql query to increment counter (associative array) I'm retrieving data from a MySQL db and creating reports from it. I need to get counts when certain conditions are met, and since db queries are rather expensive (and I will have a lot of traffic), I'm looping thru the results from a single query in order to increment a counter. It seems like it's working (the counter is incrementing) and the results are somewhat close, but the counters are not correct. At the moment, there are 411 records in the table, but I'm getting numbers like 934 from a ['total'] counter and 927 for ['males'], and that definitely can't be right. However, I get 4 from ['females'], which is correct… I'm pretty sure it was working last night, but now it's not—I'm quite baffled. (there are still just 411 records) $surveydata = mysql_query("SELECT `age`,`e_part`,`gender` FROM $db_surveydata;") or die(mysql_error()); $rowcount = mysql_num_rows($surveydata); $age=array('18+'=>0,'<18'=>0,'total'=>0); $e_part=array('yes'=>0,'no'=>0,'total'=>0); $genders=array('male'=>0,'female'=>0,'trans'=>0,'don\'t know'=>0,'total'=>0); while ($responses = mysql_fetch_assoc($surveydata)) { foreach ($responses as $response){ switch ($response){ case $responses['age']: if ($responses['age'] > 18) {$age['18+']++;$age['total']++;} // i tried putting the ['total'] incrementer in the if/else // just in case, but same result else {$age['<18']++;$age['total']++;} break; case $responses['e_part']: if ($responses['e_part']) {$e_part['yes']++;} else {$e_part['no']++;} $e_part['total']++; break; case $responses['gender']: switch ($responses['gender']){ case 1:$genders['male']++;break; case 2:$genders['female']++;break; case 3:$genders['trans']++;break; case 9:$genders['don\'t know']++;break; default:break; } $genders['total']++; break; default:break; } // end switch } //end for } // end while thanks! Try to insert some debugging statements in your code, to narrow down the problem. this is the problem: foreach ($responses as $response){ switch ($response){ case $responses['age']: switch $responses looks for match foreach ($responses as $k=>$v){ switch ($k){ case 'age': if ($v > 18) .... ahh! genius (and so much cleaner). Thanks!! 'Cleaner'? I'd argue that having $v be an age, an e_part, or a gender -- all in the same loop -- is pretty freaking messy. :P That said, it does solve the issue with the broken foreach. it's not a suggestion, just an error fix. i wouldn't iterate over $response since all cases are treated differently (hence it won't save up code). mysql_fetch_assoc() retrieves a single row from the table. You then loop over that row, processing each individual field. Then the long set of if() checks to determine which field you're on. That entire structure could be changed to: while($response = mysql_fetch_assoc($surveydata)) { if ($responses['age'] > 18) { $age['18+']++; } else { $age['<18']++; $age['total']++;} if ($responses['e_part']) { $e_part['yes']++; } else { $e_part['no']++; } $e_part['total']++; switch ($responses['gender']){ case 1:$genders['male']++;break; case 2:$genders['female']++;break; case 3:$genders['trans']++;break; case 9:$genders['don\'t know']++;break; default:break; } $genders['total']++; } Hi Marc, the placement of the ['total']s looks troublesome: won't they all increment every loop? Also, I try to avoid series of if-statements as I've had trouble with them not/activating inappropriately when there are "too many" (it's entirely possible the fault is mine, but nonetheless I try to avoid doing it). If they're activating when they shouldn't, or vice versa, the problem is almost certainly a misunderstanding of the condition and/or the values you're testing. switch looks plain odd when it's done when it doesn't have to be. Which is to say, whenever if and/or else would be more appropriate. Your query retrieves those age/e_part/gender fields for EVERY row. As such, the individual counts for age total/e_part total/gender_total would just equal the number of rows retrieved. If your allow questions to NOT be answered and want to count only filled-in answers, you'd have to do an if ($response['age'] !== '') { $age['total']++; } type thing. There's no need for the switch ($response); you can't really switch on an array like that. And even if you could, the 'values' you get wouldn't make any sense -- i'm thinking if it works at all, the value you're switching on would be either 'Array' or the length of the array. (I forget how PHP handles arrays-as-scalars.) You'll want something like this... $total = 0; while ($response = mysql_fetch_assoc($surveydata)) { if (isset($response['age'])) { ++$age[($response['age'] < 18) ? '<18' : '18+']; ++$age['total']; } if (isset($response['e_part'])) { ++$e_part[($responses['e_part']) ? 'yes' : 'no']; ++$e_part['total']; } if (isset($response['gender'])) { switch ($response['gender']) { case 1: ++$genders['male']; break; case 2: ++$genders['female']; break; case 3: ++$genders['trans']; break; case 9: ++$genders["don't know"]; break; } ++$genders['total']; } ++$total; } The benefit of the if (isset(...)) is that if 'age', 'e_part', or 'gender' is null, the corresponding code to count it won't get activated. It does about the same thing as your code, minus the embarrassing loop -- and minus the counting of the field even though it is null, because every row will have the same fields.
common-pile/stackexchange_filtered
How to make background color same as image? I'm trying to set an image center of the screen, and the dimension of the image is not as big as the entire screen. How can I make the background color seem like part of the image? Thus creating the illusion that the image is full screen? I tried using the color of the image and setting it as part of background color, but it still doesn't match. html <section class="container"> <img class="bg-img" src="../assets/beauty-bg-img.jpg" alt="background image"> </section> css .container { background-color: #F3D5DB; } As can be seen, the image is centered, but image and background color doesnt go hand in hand. How can this be done? The color of that image is gradient, not solid all the way through. I don't think you can fix that without a gradient background. Look at the top and bottom of the image to see this. The image is lighter than your background on top, and darker on the bottom of the screen. That's the issue @Cubemaster The image itself doesn't have a solid color, and your right, it's some gradient. So it isn't possible then after all. Another option if you can edit the original image is to change it to fade to transparent at the edges so that it will blend with your background colour better. Or if this isn't an option you may be able to do something similar by overlaying an image that is mostly transparent but fading to your background colour at the edges. Hmm interesting, let me edit my original image @Chris I may be able to make the edges fade Hey Dood - just following up. Was your question answered satisfactorily? If there is more we can help with, please add a comment below my answer, or edit your question to ask for more help. Otherwise, it would be great if you could choose a "best answer" (click the checkmark beside the answer) to close out the question. Also take a moment upvote (instead-of or in-addition-to) the checkmark, to reward answers that were also helpful - it costs nothing but helps us If no answer was helpful, please post your own and select it with the checkmark to close out the question. Thanks! You could try using 'mix-blend-mode', the background color of your image will match with the background color of it's parent. Please note that this might not work with your image since you are using a gradient or it could happen that your gradient will be replaced by only one color. It's also not compatible with some browsers. .container { background-color: #F3D5DB; } .bg-img { mix-blend-mode: darken; } Check this for more options. There are sooooo many ways at going with this. You could match the gradient perfectly, set the image as the background and make it cover the page. Gradients would be really hard to perfectly match up though, and you didn't ask for the second one. My solution is to use some simple css and a free photo editor. (You dont have to do any photo editing, I have the image). I took the colors from the top and bottom of the original image and then set a css gradient. background-image: linear-gradient(#F4DAE2, #EED5DC, #EED1D8); Super easy! Then you just set your body's min-height property to 100vh so nothing repeats. We use paint.net or photoshop to erase the edges of the image in a gradient pattern. Anyone can do this. You can get the gradient image file from https://i.ibb.co/0BbJ6bb/face.png. We put that image in the center of the page and everything blends nicely! It's been almost a year so please mark this answer or another as the solution to close the question. Thank you! Demo page here: https://stackoverflowanswer.glitch.me/ img { height: 100vh; position: fixed; top: 0px; bottom: 0px; left: 50%; transform: translate(-50%, 0%); opacity: 1; } body { overflow: hidden; background-image: linear-gradient(#F4DAE2, #EED5DC, #EED1D8); min-height: 100vh; background-repeat: no-repeat; background-attachment: fixed; } <!DOCTYPE html> <html lang="en"> <head> <title>html - How to make background line up with image</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <img src="https://i.ibb.co/0BbJ6bb/face.png"> </body> </html> The color of your background is solid, but the Image you have selected has a very slight gradient. To see this, Look at the top and bottom of the image to see this. The image is lighter than your background on top, and darker on the bottom of the screen. You could fix this using gradients, but that would require a fair bit of trial and error. There are a few ways to do this. You can set the image as background on the body, or on a wrapper div, and use background-size property to cover. Or, you can create a stand-alone div at the top of your code, make it position:fixed;top:0;left:0;width:100vw;height:100vh; (sets the image to full size of the viewport) and z-index:-1 (places it beneath the other divs). This is a nice effect because you can also add opacity:0.5 or some such to "dim" the image a little bit, and the rest of your webpage overlays the image. Here are some good articles on what you can do: https://www.smashingmagazine.com/2013/07/simple-responsive-images-with-css-background-images/ https://www.smashingmagazine.com/2009/03/backgrounds-in-web-design-examples-and-best-practices-2/ https://css-tricks.com/perfect-full-page-background-image/ https://www.webfx.com/blog/web-design/responsive-background-image/ https://www.taniarascia.com/background-position-fixed-and-cover-with-css/
common-pile/stackexchange_filtered
C# SqlReader issue I'am posting on this forum for the first time . and I really hope I can find some help . What I'am doing is load about ... 1000 Value (example) from SQL and I'am doing it just fine . the query for example is : Select Value from DatabaseA.dbo.Values that "Value" ==> decimal(10, 2) sqlConnection2.Open(); insertCommand2.ExecuteNonQuery(); SqlDataReader reader2 = insertCommand2.ExecuteReader(); if (reader2.HasRows) { while (reader2.Read()) { decimal Value = reader.GetDecimal(0); this propably should work fine . but What I want to do is to make + on all of them ... For example first value = 16 , second = 28 , third : 78 I want to make 16 + 28 + 78 ... but for all Values that Loaded them . How Can I do that please ? , thanks . The code makes no sense. You show us a SELECT query but you're using ExecuteNonQuery, then you're using ExecuteReader on the same command to get a SqlDataReader reader2 but you're using reader later which you haven't shown at all. Are you saying you want a total sum or a running total? Ie if the rows are 10/12/10 would you like just 32 or 10/22/32? Assuming you want to keep the original values as well, you could have a List<decimal> and accumulate the totals. List<decimal> totals = new List<decimal>(); Then in your while loop: totals.Add(Value); You can then return the running total via: var runningTotal = totals.Sum(); If you do not want the original values, you can just use: decimal value; while (reader2.Read()) { value += reader.GetDecimal(0); } Just take your variable outside of your loop and use the += operator decimal Value = 0; sqlConnection2.Open(); insertCommand2.ExecuteNonQuery(); SqlDataReader reader2 = insertCommand2.ExecuteReader(); if (reader2.HasRows) { while (reader2.Read()) { Value += reader.GetDecimal(0); } } change sql as Select Sum(Value) from DatabaseA.dbo.Values and then decimal Value = (decimal)insertCommand2.ExecuteScalar(); You could use the SQL SUM function. Take a look at http://technet.microsoft.com/en-us/library/ms187810.aspx
common-pile/stackexchange_filtered
How to use Flutter Bloc with Firebase Phone Auth I'm trying to implement Firebase phone authorization using Flutter Bloc pattern. I have the following code import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:firebase_auth/firebase_auth.dart'; import './bloc.dart'; class AuthBloc extends Bloc<AuthEvent, AuthState> { final FirebaseAuth _auth = FirebaseAuth.instance; @override AuthState get initialState => AuthNotStarted(); @override Stream<AuthState> mapEventToState( AuthEvent event, ) async* { if (event is VerifyPhone) { yield* _mapVerifyPhoneToState(event); } } Stream<AuthState> _mapVerifyPhoneToState(VerifyPhone event) async* { yield AuthStarted(); _auth.verifyPhoneNumber( phoneNumber: "+" + event.phoneNumber, timeout: Duration(seconds: 60), verificationCompleted: (AuthCredential authCredential) { print("verification completed: auth credential"); }, verificationFailed: (AuthException authException) { print("verification failed: auth exception"); print(authException.message); }, codeSent: (String verificationId, [int forceResendingToken]) { print("code sent verification id" + verificationId); }, codeAutoRetrievalTimeout: (String verificationId) { print("auto time" + verificationId); }); } } But i can't use yield inside verifyPhoneNumber callbacks. The question is how to yield different states inside of callback functions? You can add an event from your callback. For example, in verificationCompleted, you can do: verificationCompleted: (AuthCredential authCredential) { print("verification completed: auth credential"); add(AuthCompleted()); }, And you can handle the AuthCompleted() event on mapEventToState: @override Stream<AuthState> mapEventToState( AuthEvent event, ) async* { if (event is VerifyPhone) { yield* _mapVerifyPhoneToState(event); } if (event is AuthCompleted){ //Here you can use yield and whathever you want } } PhoneAuthenticationBloc class PhoneAuthenticationBloc extends Bloc<PhoneAuthenticationEvent, PhoneAuthenticationState> { final AuthRepository _authRepository; final AuthBloc _authBloc; @override Stream<PhoneAuthenticationState> mapEventToState( PhoneAuthenticationEvent event, ) async* { if (event is PhoneLoadingEvent) { yield PhoneLoadingState(); } else if (event is PhoneVerificationFailedEvent) { yield PhoneOTPFailureState(event.failure); } else if (event is PhoneSmsCodeSentEvent) { yield PhoneSmsCodeSentState( verificationId: event.verificationId, resendCode: event.resendId); } else if (event is PhoneVerifiedOtpEvent) { yield* _mapToVerifyOtp(event.smsCode, event.verificationId); } } void verifyPhoneNumber(String phoneNumber) async { try { add(PhoneLoadingEvent()); await _authRepository.verifyPhoneNumber(phoneNumber, onRetrieval: (String retrievalCode) { print("Time Out Retrieval Code: $retrievalCode"); }, onFailed: (Failure f) { print("OnFailed: ${f.message}"); add(PhoneVerificationFailedEvent(f)); }, onCompleted: (Map<String, dynamic> data) { print("verificationCompleted: $data"); }, onCodeSent: (String verificationId, int resendCode) { print("verificationId:$verificationId & resendCode: $resendCode"); add(PhoneSmsCodeSentEvent( verificationId: verificationId, resendId: resendCode)); }); } catch (e) { add(PhoneVerificationFailedEvent(Failure(message: e.toString()))); } }} UI Screen builder: (context, state) { return AppButton( isLoading: state is PhoneLoadingState, onPressed: () async { if (_formKey.currentState.validate()) { BlocProvider.of<PhoneAuthenticationBloc>(context) .verifyPhoneNumber(_phoneController.text); } }, title: "Continue", textColor: Colors.white, ); }
common-pile/stackexchange_filtered
QGIS 3.22 does not display Google Earth after added as a XYZ tile I am new to QGIS, I need to add Google Earth as an XYZ tile, I did this by clicking it, then hitting new connection then using the Google Earth link, and hitting okay. I then tried to view it but it does not display anything. I tried asking it to zoom into layers as that resolved a previous issue I had. Unsure where to go from here. This is the link I used: http://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z} this is for a lab I am working on so it was given to me. EDIT: This is what shows when I open the Logs EDIT: I noticed when I hover my mouse over the blank screen, coordinates will show at the bottom of the screen indicating that it is working I just cannot see it. What you did looks valid, I get a Sat view with your setup. Do you see anything unexpected if you open the Logs (icon at the bottom right of the QGIS window) I usually use Google Earth via the Quick Map Services plugin value added pack, but my xyz tile is slightly different from yours. Here's mine: https://mt1.google.com/vt/lyrs=s&x=%7Bx%7D&y=%7By%7D&z=%7Bz%7D
common-pile/stackexchange_filtered
immediate = true didn't work I am trying to create a row which includes Delete and Add Row buttons. When delete is clicked, it should ignore the validations on the inputs. So, I used immediate="true" to do it. But it doesn't seem to work. What might be wrong? This is my code... I omitted the other lines and focused on the lines that seems not working: <apex:variable var="cnt" value="{!0}" /> <apex:repeat id="sampleSection" value="{!someValue}" var="XY"> .... <div class="slds-button-group" role="group" style="height: 40px;"> <apex:commandButton value="Delete" id="delRowBTN" title="Delete" action="{!removerow}" reRender="outputTable" oncomplete="return false;" immediate="true"> <apex:param name="rowForDel" value="{!cnt}" assignTo="{!rowNumber}"/> </apex:commandButton> </div> .... <apex:variable var="cnt" value="{!cnt+1}"/> </apex:repeat> One other thing I just noticed, apex:variable in apex:repeat is unsupported. You may need to find an alternative way to write this code. Using immediate skips validations, but also skips the action method as well. Instead, surround your button with an apex:actionRegion, whose purpose is to limit the submitted data to just the data within it: <apex:actionRegion> <apex:commandLink value="Delete" action="{!removerow}" reRender="outputTable" oncomplete="return false;"> <apex:param name="rowForDel" value="{!cnt}" assignTo="{!rowNumber}"/> </apex:commandLink> </apex:actionRegion> Note also that you have to use apex:commandLink for apex:param to work; parameters are not supported on buttons, as per the documentation. If you still want a button, you'd have to restructure your code to use a wrapper class so you can delete the appropriate record. N.B. undocumented, but Params work on commandButton if you have reRender= @cropredy Interesting. I remember trying it once and it didn't work even with reRender. Generally, I tell people if it's not documented, it shouldn't be used. It might work, it might not, which is why it's not documented.
common-pile/stackexchange_filtered
Show userform on worksheet select I have three worksheets in a workbook. I want to show a specific user form when the user selects one of the worksheets. How can I achieve this in VBA? I have looked at your recent posts. You make no effort whatsoever to explain your problem in any detail and show us no evidence that you have tried anything yourself. Please stop posting duplicates and vague questions. We are willing to help you if you show us what you've got so far and add some detail. There are several ways to retrieve the current user name. If you want to retrieve the OS user then this is the best solution: Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, lpnSize As Long) As Long Public Function GetOSUser() As String Dim lpBuffer As String * 25 GetUserName lpBuffer, 25 GetOSUser = Left(lpBuffer, InStr(lpBuffer, vbNullChar) - 1) End Function Based on the return value of GetOSUser() you can then select the user form to display to the user. I get the impression its a different userform based on the selected sheet, rather than the user - It's extremely ambiguous but this is almost a duplicate of a previous question : http://superuser.com/questions/1073210/hide-user-form-on-non-active-workbook
common-pile/stackexchange_filtered
jQuery doesn't run in Safari on form submit I have a peculiar issue which is giving me headaches... The following code works perfectly in Firefox but not in Safari on Mac OS. I want to display a simple "Loading message" while files are being uploaded. So my page looks like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script> <script> $(document).ready(function () { $('#upload').on('submit', function () { $("#loading").fadeIn(); }); }); </script> </head> <body> <p id="loading" style="display:none">UPLOADING...</p> <form name="upload" id="upload" method="post" action="upload.php" enctype="multipart/form-data"> <input type='file' name='file[]' multiple/> <input type="submit" value="Upload..."/> </form> </body> </html> On Firefox, the "UPLOADING..." line shows up while the files are uploading before transfering me to upload.php. On Safari, the "UPLOADING..." line doesn't show and it transfers me to upload.php once the files are uploaded. If this is something not supported in Safari, how can I achieve exactly the same feature? Thank you for your help! is the binding syntax correct? so far I know it would be like $(document).on('submit', '#upload', function(){}) I've just noticed the exact same behaviour... sounds more like a bug with safari if you ask me. Encountered this just now too, sounds like a problem with Safari. Ok, I got it working... Instead of a 'submit' button, I changed it by a 'button' with id='send'. I modified the script to first show the p tag on click and then added the form submit in the callback like so: <script> $(document).ready(function () { $("#send").click(function () { $("#loading").fadeIn(function () { $("#upload").submit(); }); }); }); </script> And it works in all browsers now. Tested in IE, FF, Chrome and Safari. this is not the recommended way! but that's up to you :) Errr... fine but would you care to share the recommended way, then? that's your initial implementation. but just wondering about safari issue.
common-pile/stackexchange_filtered
In Sqlite3, how to use VACUUM to get more space I have a database that has been deleting records and adding records all the time. I only have 2MBytes memory that I can use for this database. I know that I should use VACUUM, but it doesn't work. Is there anything I missed? SQLite automatically reuses freed pages. The VACUUM process creates copies of the database file. The answer appears to be "don't". How did you know it didn't work? To verify how big your database is: $sqlite3 test.db //open the database $sqlite> PRAGMA page_size; // request database's page size configure. 1024 // test.db has page size 1024 bytes. $sqlite> PRAGMA page_count; // request database's page count. 677 // test.db has 677 pages. The size for test.db is 677*677 = 693248 bytes. To issue "VACUUM", DO NOT ADDING "PRAGMA", it is common mistake, just send "VACUUM" alone: $sqlite> VACUUM; //re-arrange database $sqlite> PRAGMA page_count; //check the new page count 674 //after clean up, the page count is reduced Now the database size is: 1024*674= 690176 bytes
common-pile/stackexchange_filtered
hdmi usb dongle macrosilicon 2109 rename device How can i change the product name|ID of hdmi usb dongle on the HDMI end? (how the device is named as HDMI. Currently (default) is recognized as "HDMI to USB". ) There are many similar devices based on "Macrosilicon 2109". for example: https://aliexpress.ru/item/4001058525465.html (maybe from the usb connection i can change something like EEPROM)
common-pile/stackexchange_filtered
why whereIn() is better than relations in laravel? The database of our Laravel application is increasing and query time is also increasing. One thing I have noticed about queries is whereIn() is way faster than the relations call. I need to get all consignments of the customer, so with Laravel relation, what I do is: $customers = Customer::with('consignments')->where('id','>',1)->get(); //and now I can access all consignments foreach($customers as $customer ){ $customer->consignments } but this is very slow even when I am using indexes. Maybe I am not using indexes properly? On the other hand, if I use whereIn(), it is much faster: $customer_ids = Customer::selct('id')->where('id','>',1)->pluck('id')->toArray(); $consignments = Consignment::whereIn('customer_id',$customer_ids)->get() This is very fast. Am I making any mistake here? Can we make Laravel relations faster? Install Laravel debugbar so that you can get to grips with the number of queries, the number of hydrated models and particularly, the amount of memory in use. Do you really have a use case where you need all customers and all consignments in memory at once? those 2 examples are doing different things as well, the first is getting all customer records (all fields) the second is only getting the ids ... if you don't need the customer records you can do the relationship from the other direction as well with a whereHas to only get consignment records ... though not saying that it would be quicker/more efficient You are mainly comparing eager loading vs lazy loading. In your first example, you are using eager loading. You are basically bringing everything at once. You execute one single query against your database. In your second example, you are using lazy loading. First, you are bringing the user's information. Second, you are bringing the related consignments. You execute two different queries against your database. Response times depend on different factors. Database data size Database structure such as data types and indexes Database server resources such as CPU and memory Response size Network bandwidth For example, if your resources of CPU and memory are limited, your database server might be having a difficult time trying to process the eager loading approach where you have one single but complex query. You can get the raw query using the toSql() method. You can then execute these queries directly in your database and use a query execution plan to detect which query suits better for your use case.
common-pile/stackexchange_filtered
NSData to NSString losing data I'm attempting to convert a binary file into text, the problem is that a large portion of the file was not encoded in ascii and ends up being special characters. I'm using [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; but am only getting a few characters back in a 20000 byte data block. What I would like to be able to see is all of the text (even if most is nonsense), which is what I get when I open the file using a binary editor. Pass the correct encoding? This sounds like an XY Problem. What are you trying to do with the string exactly? There isn't really a 'correct encoding' for the entire file. Portions of the file are readable with UTF8 or Ascii in a binary editor, but when I do a UTF8 or ascii encoding using the NSString methods I get very little or no data. I'd like to be able to view all of the characters to do some regex and pull out the pieces that make sense. It's a binary file. To read it, you find the documentation for the file format, then you parse it. Trying to throw it all into an NSString* seems absolutely pointless. There are applications in reverse engineering, which is why hex viewers exist. Is there no way to view the contents of the file, like this binary editor showing the file in UTF8 encoding? Of course. You'd use an encoding where every 8 bit character is valid. NSASCIIStringEncoding is no such encoding. UTF-8 is no such encoding. MacRoman or Windows1252 will do fine. Yep, using an arbitrary 8-bit encoding would do it. The other option is to loop through character-by-character, translating using a table you define. Fairly easy to do -- the hard part is defining the table. (Offhand, Windows1252 appears to match what's being displayed in the image above.)
common-pile/stackexchange_filtered
Make methods work independently without using a common method I am currently trying to separate out the method implementation so that they can work independently. The methods that I am trying to separate are store and checker. Both these methods require the traverse method. My current implementation has two method store and checker methods which I have separated them into different classes. They require to be called within the traverse method to work. This is the my current implementation. class Traverse { public void traversemethod() { Console.WriteLine("Traverse function"); Checker r = new Checker(); r.checkermethod(); Store s = new Store(); s.storemethod(); } } class Checker { public void checkermethod() { Console.WriteLine("Checker function"); } } class Store { public void storemethod() { Console.WriteLine("Store function"); } } class Compute { public static void Main() { Console.WriteLine("Main function"); Traverse v = new Traverse(); v.traversemethod(); Console.ReadLine(); } Is there any way by which I can implement them separately without declaring them together in traverse method and calling both store and checker method separately in the main function. I can implement the traverse method in both store and checker method, but i was wondering if there is any way to do it rather than duplicating the same code again. I'm not clear on what you're asking here. How do you want to change it? Please be more clear on what your need is. what is the problem of calling the store and checker method from your main function in your current implementation? @TimS.@Omribitan Both the store and checker method needs to traverse through an array, which makes traverse common to both. I can get it to work by including the traverse code in both store and checker to call both store and checker independently in main(). My query is there any other way that I can use to achieve the same result without copying the "traverse" code for every method I implement. I'm not about the relationship between Checker and Store so I'll show an example with an interface instead of a base class. However you could create a base class, possibly abstract, and have each child class implement their special method. interface IPerformMethod { void SpecialFunction(); } public class Store : IPerformMethod { public void SpecialFunction() { Console.WriteLine("Store function"); } } public class Checker : IPerformMethod { public void SpecialFunction() { Console.WriteLine("Checker function"); } } Then in your TraverseMethod, you could pass in an object that implements IPerformMethod (in this case it's either an instance of Checker or Store). public void TraverseMethod(IPerformMethod item) { Console.WriteLine("Traverse function"); item.SpecialFunction(); } //To call the method TraverseMethod(new Checker()); TraverseMethod(new Store()); (Obviously you can rename the IPerformMethod interface to something more descriptive but if I understand the question correctly, this seems to be what you want). when i try to implement the above code I am unable to define the parameter within the TraverseMethod as IPerfromMethod type. is there anything that I could have possibly done wrong. It's hard to tell without code. I'm not sure if your comment is a typo, but it should be IPerformMethod not IPerfromMethod. If that's not it then make sure your interface is accessible to the class. Sounds like a perfect place to use a lambda: public delegate void TraverseDelegate(); public void traversemethod(TraverseDelegate dlg){ Console.WriteLine("Traverse function"); dlg(); } and in the Main method use: Traverse v = new Traverse(); v.traversemethod(() => { Checker r = new Checker(); r.checkermethod(); Store s = new Store(); s.storemethod(); }); EDIT/UPDATE(=UPDIT :-) ) You can also make the delegate a member field of Traverse, and then pass it as a constructor argument and call traversemethod without any arguments: public class Traverse{ public delegate void TraverseDelegate(); private TraverseDelegate dlg; public Traverse(TraverseDelegate dlg){ this.dlg=dlg; } public void traversemethod(){ Console.WriteLine("Traverse function"); dlg(); } } and in the Main method use: Traverse v=new Traverse(()=>{ Checker r = new Checker(); r.checkermethod(); Store s = new Store(); s.storemethod(); }); v.traversemethod(); Does the traversemethod() take any argument?? As I keep getting an error which says that the method has no overload and takes 1 argument. Notice that in my first code-snippet I declared traversemethod to take a delegate argument. If you don't want traversemethod to take any arguments, you could also pass the delegate in Traverse's constructor(I'll update the answer with that approach). I am totally new to lambda, now it flags an expected "class, enum, struct" error at new traverse, new checker & new store in main Can you update the question with your code that tries to use lambdas? Or make a gist or something. Here is the link to the code that I am trying to run https://gist.github.com/ajitpeter/6547444 The problem is that you moved the Main method out of the Compute class and into the global scope - which is illegal in C#, where methods must be declared inside classes. I was still in the C++ mindset :-) both of the answers work as my requirement.
common-pile/stackexchange_filtered
java compiling with jars I'm trying to figure out how an existing Java program (I did not make myself ofcourse) was compiled with existing jars I have Test.java (original source file): package Demo; //import classes from jars here etc... public class Test { public static void main(String args[]) { etc... } } Now I have two other jars: file1.jar file2.jar Demo.jar There is a batch script to run it: @echo off set CLASSPATH="file1.jar";"file2.jar";"Demo.jar" java -cp %CLASSPATH% Demo.Test This WORKS, but now I need to change the source file Test.java, recompile and run with the jars class dependencies. (sorry if I'm not making sense) Now, I have tried to recompile this to reproduce same results with no luck: javac -cp file1.jar;file2.jar;Demo.jar Test.java defined manifest: manifest.mf Main-class: Demo.Test Created directory "store" for class files and moved class files there Ran: jar -cmf manifest.mf Demo.jar store Which created the "Demo.jar" Then I ran the run the batch script above but not the same results (doesn't work at all) Any help would be appreciated. Thank you! Did the batch script not work? yes, the batch script works initially. this is an existing program I'm trying to figure out how it works so I can recompile it when I make changes to the "Test.java" and run it the same way Can you show the error that occurs? Might point us in the right direction Your batch script is for running the code. It sets CLASSPATH so JVM knows where to look for the required classes. It has nothing to do with compiling the code. when running batch script again: cannot find or load Demo.Test class java - runs the byte-code javac - complies (translates Java statements to byte-code) jar - builds JAR files (packs compiled classes together) hi PM 77-1, I know what its referring too. All I'm asking is general help/pointers on how to recreate the results in this case with jars provided and the source file. What exactly do you want to recreate and from what point? Just like how I explained I have a folder with the jar files, a source file that I want to change and recompile and run with the jar files class dependencies, that is all. It is difficult to create true executable jars as soon as you rely on external jars. The only solution here is to : put all jars in the same folder : yours and its dependencies add a classpath entry inside your manifest launch the jar using java -jar Demo.jar The manifest will have to look like : manifest.mf Main-class: Demo.Test Class-Path: file1.jar file2.jar what I'm just trying to do is because the Test.java file is dependent on the jars classes, I want to make some changes to the Test.java file and make it work. I don't know how to get it to compile and link appropriately. I was hoping for some steps to take to get this done in the original working way that I described. Try better and read the docs I mentioned, it's the official java way.
common-pile/stackexchange_filtered
How to catch the error output in shell when error code is not enough? I came across the script with if-else branch with a particular command succeed or not like this: pg_ctl -D /var/lib/pgsql/data -w promote if [ $? -ne 0 ]; then echo: failure exit 1 else echo: succeed exit 0 fi It looks straight forward. But if the postgresql server it wanted to promote is already running as primary, it will also throw out an error code=1 and error message containing 'is not in standby mode'. So it is okay if this error occurs, but error code=1 or $? -ne 0 produces a false positive. I want to just take this particular error out as another successful outcome, and how can I achieve it? There is no straight forward bash variable like $? to catch the exact error message, however, it is possible to store the outcome in a text file for analysis. In this case, the script is like this: pg_ctl -D /var/lib/pgsql/data -w promote &> promote_return if [ $? -ne 0 ]; then if [ `grep -c 'is not in standby mode' promote_return` -ne 0 ]; then echo okay: no need to promote twice. exit 0 else echo failure: please check the file promote_return for error message. exit 1 fi else echo succeed exit 0 fi
common-pile/stackexchange_filtered
How to chain requests using Insomnia (get token from login api to use as header for another api) I'm trying to update the header for my apis with a sif token that is retrieved from another login call. I know how to do this in Postman. There I go to the Tests tab and add something like this for the login api, which would set my global variable. var data = JSON.parse(responseBody); postman.setGlobalVariable("SIF_TEACHER", data.sifToken); I've read this tutorial from the Insomnia official support page but can't really understand it and couldn't find any other doc on chaining requests there. Thank you. In your workspace press CTRL+E to open "Manage Environments" window Add a variable like "token" to the environment Put a response function (teal f) as value of this variable by pressing CTRL+SPACE. Select one to your liking from the dropdown, in your case "Response => Body Attribute" should work well. This will open a "Tag" form, like this one: Select your login request and filter the response json or xml for the value containing your token value, f.e. $.access_token. Probably set trigger behaviour to "When Expired" too. You can now access this variable anywhere in your workspace for other requests by pressing CTRL+SPACE in any form field and selecting the variable (purple x). If you only need this for one request, you can skip setting up the environment variable for this and directly put the function where you need it, same way as described before. Is it possible to extract using regex from raw-response ? This is so hidden that I have to access here back and forth.... tysm! Better explanation than offical docs. thank you Anyone knows how this works when exporting the collection+environment? I managed to configure the tags and get them working but they are recorded in this way : req_daac1bc86d1b4cf3b0ed4c84c8a6fa75. By their id hash. So when I import it anywhere else, even though the request exists because it is imported at the same time, this reference does not exist because the same request has a different hash. Anyone knows a workaround for this? If, like me, you can't find a key combination that works, define a blank variable like "myvar": "" and then right-click inside the empty quotation marks. You can check the link, in the comments there is a mini clip with the indications https://github.com/Kong/insomnia/issues/2744 Please read https://meta.stackoverflow.com/tags/link-only-answers/info "Link rot" "Your answer is in another castle: when is an answer not an answer?" There is a plugin that allows you to have variables which you can set its value from different request an use them in others. This is great for when you want to chain requests but you have multiple possible parents and don't want to duplicate the child request, for example you could have "Login with A" and "Login with B" and both save to id, then you can have a "Get info" with the id. Setting a variable is done using an special tag in the header of the request ("Save variable") and then use its value wherever you want with the "Variable" tag. You can see more about the plugin in https://insomnia.rest/plugins/insomnia-plugin-save-variables . I got the solution by adding an pre-request script like this: const tokenUrl = ''; const requestBody = { "login": "", "password": "teste" }; const response = await fetch(tokenUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(requestBody) }); if (response.ok) { const data = await response.json(); const token = data.token; insomnia.environment.set('authToken', token); } else { throw new Error('Erro to generate token: ' + response.status); } and then on Auth tab put the variable authToken.
common-pile/stackexchange_filtered
How do I run a subsequent script if the text entry field is not focused? I am currently using the first script which is valid if I have my cursor selected in the text field. tell application "System Events" tell application process "Capture One 20" set frontmost to true tell (first window whose subrole is "AXStandardWindow") set subjElem to (first text field of scroll area 1 of group 2) set subjProp to properties of subjElem set subjFocused to focused of subjElem end tell end tell end tell return subjFocused If I don't have my cursor in the text field than I get this error. How do I run a subsequent script based off this error? tell application "Capture One 20" begin live view end tell Why not use try-catch so that when the UI element is not detected, you fall into the on error block and process your subsequent script? @user3579815 Eventually I landed there, but I went with "if not exists" first, but then I realized the location would change between group 1 and group 2. Now I need to expand the scroll areas and groups. I will try using a wild card.
common-pile/stackexchange_filtered
Removing and adding actors to a group - libgdx I have a group that has a Map that associates every entity with an actor; it has the method addEntity and removeEntity for adding and deleting entities to/from the Map and their respective actors to/from the group. public final void addEntity(final Entity entity) { EntityActor entityActor = new EntityActor(entity, shapeRenderer); this.addActor(entityActor); //adding the actor to the group this.entitesActors.put(entity, entityActor); //adding the actor to the map } public final void addEntities(final Collection<Entity> entities) { entities.stream().forEach(this::addEntity); } public final void removeEntity(final Entity entity) { entitesActors.get(entity).addAction(Actions.removeActor()); //removes actor from group this.entitesActors.remove(entity); //removes actor from map } public final void removeEntities(final Collection<Entity> entities) { entities.forEach(this::removeEntity); } This group also has a reset method that deletes all his children and adds new ones. public final void reset(final Collection<Entity> entities) { Gdx.app.postRunnable(() -> { removeEntities(entitesActors.keySet()); this.addEntities(entities); }); } The first time reset is called (Map and group are empty) everything's fine, but the second time I call it (with Map and Group containing the entities of the first call) I got a cuncurrentModificationException from the removeEntity method. I tried to edit it like this: public final void removeEntities(final Collection<Entity> entities) { entitesActors.entrySet().stream().filter(e -> entities.contains(e.getKey())).map(e -> e.getValue()) .forEach(a -> a.addAction(Actions.removeActor())); entitesActors.keySet().removeAll(entities); } Or bypassing removeEntities method and just calling: this.clearChildren(); this.entitesActors.clear(); In both cases no exception is fired, the actors are successfully removed and added in both Map and Group but they are not drawn onto the stage. (the method draw in each actor is called but I can't see them on screen, all I got is a black screen). Somebody know the correct way to do it or maybe telling me where I make a mistake? Thanks very much for the help. EDIT: I tried @luis-fernando-frontanilla solution but it didn't worked out. Now my reset method looks like this public final void reset(final Collection<Entity> entities) { this.clearChildren(); this.entitesActors.clear(); this.addEntities(entities); } And I tried to wrap the whole reset method inside a Gdx.app.postRunnable //EntityCrew is my Group object which has the reset method Gdx.app.postRunnable(() -> this.entityCrew.reset(level.getEntities())); And I noticed that with this setup the first time too I can't see the actors of the group. They are in the group, they are drawn by the render thread but they are not displayed on screen and this thing is driving me mad. The first time reset is called (Map and group are empty) everything's fine, but the second time I call it (with Map and Group containing the entities of the first call) I got a cuncurrentModificationException from the removeEntity method. This exception happens because when you're iterating through the Collection in the render() method one element in that collection is removed confusing the iterator on what it should do. Luckily for us, LibGDX has a DelayedRemovalArray class that is made exactly for these kind of cases. It works like this: Tell the DelayedRemovalArray you want to delete one or many of its elements Put a flag on the elements you want to remove Tell the DelayedRemovalArray you finished setting the flags The DelayedRemovalArray waits for the iteration to finish and deletes the flagged elements DelayedRemovalArray<Entity> array; // Prepare to flag elements array.begin(); // Flag some elements array.removeIndex(index); // Finished flagging elements array.end(); From the LibGDX API: DelayedRemovalArray is an array that queues removal during iteration until the iteration has completed. I add group's actors to the array and I delete all of them in the way you suggested and then adding the new EntityActors but unfortunately I got the same behavior :/. I also edited my answear
common-pile/stackexchange_filtered
Partitions of integers, but ignoring commutativity and restricted to only using the first $3$ positive integers My question involves the number of ways to add up to a positive integer $n$ such that the order in which we add the terms up matter (so ignoring commutativity) and we are restricted to only using $1$'s, $2$'s and $3$'s. Hence I want to count observations such that $1+2+1$ is different from $2+1+1$ If we didn't care about order mattering or we weren't restricted to the first three numbers, this problem could have simply been solved with the partition function. Denote $\lambda(n)$ to be the function mapping a positive integer $n$ to the number of ways you can sum to $n$ using various summations of $1$s, $2$s, and $3$s. What I know so far I am only really concerned for finding it up to $n=8$, but should a generalization for $n\in \mathbb{Z}^+$ exist, I would be glad to see it. I've worked it out for $1 \le n \le 3$ using the following argument: By observation, we can pick out $\lambda (1) = 1$. Setting up however many ones we need, let's say $2$ for this case, we have $$1\_ 1$$ Where we can choose either to fill the gap with a $+$ or a $:$, where a $:$ between two numbers means combine them into one term, so $1:1$ would represent the possibility of $2$ and $1+1$ is itself the other possibility. Therefore $\lambda(2) = 2$ Similarly for $n=3$, we have $$1\_1\_1$$ Using the argument above, we have two options for each blank, so we have that $\lambda (3) = 2^2 = 4$. This strategy however falls apart for $n\ge 4$. The argument would say that $\lambda (4) = 8$, but this doesn't consider that one of those options includes filling all the gaps with a "$:$" which represents using the number $4$. We are restricted to only the first three positive integers, so after subtracting this invalid option we now have that $\lambda (4) = 7$. So now our argument no longer works, and if it wasn't for the fact that the case of $n=5$ isn't hard to quickly subtract the invalid options (which are $5, 4+1,$ and $1+4$) I wouldn't have known so fast that $\lambda (5) = 13$. I really don't want to sit and continue counting off the invalid options to find $\lambda (6)$ onwards, but I'm aware it can be done with patience. So right now the general formula I am using is $$\lambda (n) = 2^{n-1} - \text{the # of invalid options}$$ but I would like to find an improvement to this formula or maybe find a nicer formula instead. Any help is greatly appreciated. The last number is either a $1$, a $2$, or a $3$. If it's a $1$, there are $\lambda(n-1)$ ways to fill in the preceding numbers; if it's a $2$, there are $\lambda(n-2)$ ways; if it's a $3$, $\lambda(n-3)$. This gives us the recursive equation $$ \lambda(n)=\lambda(n-1)+\lambda(n-2)+\lambda(n-3) $$ which, along with the initial values $\lambda(1)=1$, $\lambda(2)=2$, $\lambda(3)=4$ you've computed, is enough to compute $\lambda(n)$ for any $n$: $$ \lambda(4)=1+2+4=7\\ \lambda(5)=2+4+7=13\\ \lambda(6)=4+7+13=24 $$ and so on. This is a homogeneous linear difference equation. You could work out an formula for $\lambda(n)$ using the method given in the link, but it would involve the roots of an irreducible cubic polynomial. So for most practical purposes it's probably better to just use the recursion. Recursion never fails to amaze me!! Thanks! You're welcome! It's probably also worth noting that this is a lot like the tiling approach to Fibonacci numbers, except that you're allowing 3s in your sum (equivalent to allowing for 1x3 tiles). This leads to an order-3 recurrence instead of the Fibonacci order-2 recurrence...
common-pile/stackexchange_filtered
Run command on pair of files (different file types) with matching character string I have a list of files: catfish.fa polar.fa catfish.ids.txt polar.ids.txt I want to run this command for each file with a matching character string. So for example, I'd like to run this: cat catfish.fa | seqkit grep -f catfish.ids.txt > catfish.output.fa Similarly... cat polar.fa | seqkit grep -f polar.ids.txt > polar.output.fa How can I run this command for each file pair in the directory and in parallel? Thanks for your help! This will run one job per CPU core in parallel: parallel 'cat {} | seqkit grep -f {.}.ids.txt > {.}.output.fa' ::: *fa May I suggest you run with --dry-run first, so you can see what will be run? parallel --dry-run 'cat {} | seqkit grep -f {.}.ids.txt > {.}.output.fa' ::: *fa Also consider spending 20 minutes on reading chapter 1+2 of the book GNU Parallel 2018 (print: http://www.lulu.com/shop/ole-tange/gnu-parallel-2018/paperback/product-23558902.html online: https://doi.org/10.5281/zenodo.1146014). Your command line will love you for it. Thank you for your excellent resource. When I tried this the terminal just returned a ">". I am using macOS and the parallel command is installed. End ' was missing. Fixed. Yep I kept looking at it and was like oh it was missing an '. Thank you for help and your book is excellent. I will spend time learning it. #!/bin/bash for f in *.fa do filename="${f%.*}" if [ -e ${f}.ids.txt ] then cat ${f}.fa | seqkit grep -f ${f}.ids.txt >${f}.output.fa fi done filename="${f%.*}" extracts the filename without extension, see here for an explanation. The purpose of the if is to single out only the files ending with .fa which have a corresponding .ids.txt file. If you want everything to be run in parallel on each pair, append a & at the end of the cat ${f}.fa ... file. (Beware to not generate too many parallel tasks!) With bash's Parameter Expansion: for file in *.fa; do seqkit grep -f "${file%%.*}.id.txt" >"${file%%.*}.output.fa" <"$file" & done
common-pile/stackexchange_filtered
I'm having trouble with npm install for angular 2 This is error that I'm getting in cmd prompt: npm WARN deprecated<EMAIL_ADDRESS>Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue ><EMAIL_ADDRESS>postinstall C:\Users\hp\Desktop\angular2-seed > typings install 'typings' is not recognized as an internal or external command, operable program or batch file. npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture<EMAIL_ADDRESS>npm WARN<EMAIL_ADDRESS>No description npm WARN<EMAIL_ADDRESS>No repository field. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\hp\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" npm ERR! node v4.4.7 npm ERR! npm v3.10.3 npm ERR! code ELIFECYCLE npm ERR<EMAIL_ADDRESS>postinstall: `typings install` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the<EMAIL_ADDRESS>postinstall script 'typings install'. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the angular2-quickstart package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! typings install npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs angular2-quickstart npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls angular2-quickstart npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! C:\Users\hp\Desktop\angular2-seed\npm-debug.log try to install typings first npm install typings --global @maxisam now I'm getting this: C:\Users\hp\Desktop\angular2-seed>npm install <EMAIL_ADDRESS>postinstall C:\Users\hp\Desktop\angular2-seed typings install └── (No dependencies) npm WARN optional Skipping failed optional dependency /chokidar/fsevents: npm WARN notsup Not compatible with your operating system or architecture<EMAIL_ADDRESS>npm WARN<EMAIL_ADDRESS>No description npm WARN<EMAIL_ADDRESS>No repository field. I run npm start now and it is working, thanks a lot @maxisam! When you see 'typings' is not recognized as an internal or external command, operable program > or batch file. try to install typings first npm install typings --global You need to install typings globally: - npm i typings -g
common-pile/stackexchange_filtered
How to read from an API I want to log the data that is stored in an URL as JSON with an AJAX call. $.ajax({ "url": "https://api.logair.unige.ch/v1/service/device/latest?device_id=LAEM_02&latest=1", "method": "GET", "crossDomain": true, "dataType": 'jsonp', "headers": { 'Access-Control-Allow-Origin': '*' }, success: function(response) { console.log(response) }, error: function(error) { console.log(error); } }); But I'm getting: Object { readyState: 4, getResponseHeader: getResponseHeader(e), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(e, t), overrideMimeType: overrideMimeType(e), statusCode: statusCode(e), abort: abort(e), state: state(), always: always(), catch: catch(e), … } instead of the JSON that you can find in the URL. If I change from jsonp to json I get Access to fetch at 'https://api.logair.unige.ch/v1/service/device/latest?device_id=LAEM_02&latest=1' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. seems like the api server only responds to 'jsonp' request but does not wrap response in a callback function. Ideally when a jsonp request is made, a callback is added to request and the server should wrap response in that callback. See this answer https://stackoverflow.com/questions/5359224/parsererror-after-jquery-ajax-request-with-jsonp-content-type , Currently in the network tab you can see the server responds with valid json which jquery is not expecting, thats why it calls error function insted of success Try response.data Or error.response.data for the catch I'm not familiar with JSONP, but I when I execute your API call, the response in the browser network debugger looks like usual json to me [{"transaction_id":363287,"timestamp_nix":1604087391821,"device_id":"LAEM_02","latitude":46.2111884,"longitude":6.1422013,"altitude":440,"speed":0.06644406914711,"heading":333,"temperature":22.1,"relative_humidity":39.6,"pressure":98066.1,"pm_1":null,"pm_2_5":12,"pm_4":null,"pm_10":15,"extra_data":[],"mobile_api_key_id":null}] As far as I understand JSONP it should return something like callback({...}). Also if you modify your error callback: error: function(r,e,m) { console.log("r:",r); console.log("e:",e); console.log("m:",m); } I becomes clear that the response cannot be parsed as JSONP: r: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} e: parsererror m: Error: jQuery112407275383630150669_1604133626031 was not called at Function.error (jquery.min.js:2) at b.dataTypes.<computed>.b.converters.script json (jquery.min.js:4) at Xb (jquery.min.js:4) at y (jquery.min.js:4) at HTMLScriptElement.b.onload.b.onreadystatechange (jquery.min.js:4) Because no callback function (jQuery112407275383630150669_160413362603) was called in the response. Long story short: Your backend seems to be faulty.
common-pile/stackexchange_filtered
Fluent Nhibernate Config is OK when conn. string in web.config, but not otherwise Can anyone tell me the correct syntax? I need to enter the connection string directly in my code in order to Unit test. Everything works fine when the connection string is in the web.config file as: <add name="SQLNorthwindConnectionString" connectionString="Data Source=localhost\try2;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/> Using it in the code as: _SessionFactory = Fluently.Configure(). Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("SQLNorthwindConnectionString")). ShowSql(). Cache(c => c.ProviderClass<SysCacheProvider>(). UseQueryCache())). Mappings(m => m.FluentMappings.AddFromAssemblyOf<FNHibernateHelperSQLite>().Conventions.AddFromAssemblyOf<NorthwindMVCApp.FNHibernate.CustomForeignKeyConvention>()). BuildSessionFactory(); But this doesn't work: _SessionFactory = Fluently.Configure(). Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.Is("Data Source=localhost\try2;Initial Catalog=Northwind;Integrated Security=True")). ShowSql(). Cache(c => c.ProviderClass<SysCacheProvider>().UseQueryCache())). Mappings(m => m.FluentMappings.AddFromAssemblyOf<FNHibernateHelperSQLite>().Conventions.AddFromAssemblyOf<NorthwindMVCApp.FNHibernate.CustomForeignKeyConvention>()). BuildSessionFactory(); Remove the lambda expression : MsSqlConfiguration.MsSql2008.ConnectionString(@"Data Source=localhost\try2;Initial Catalog=Northwind;Integrated Security=True")
common-pile/stackexchange_filtered
Can you take values within certain groups and put them each in a new column in R? I would like to create multiple new columns for each value of one column, grouped by another. For example, if I have this: session side_effect: 1 dizzy 1 irritable 1 anxious 3 focused 3 anxious 7 relaxed Can I get this: session side_effect1 side effect_2 side_effect_3 1 dizzy irritable anxious 3 focused anxious 7 relaxed We can use pivot_wider from tidyr to convert from 'long' to 'wide' format library(dplyr) library(tidyr) df1 %>% group_by(session) %>% mutate(rn = str_c('side_effect_', row_number())) %>% pivot_wider(names_from = rn, values_from = side_effect) # A tibble: 3 x 4 # session side_effect_1 side_effect_2 side_effect_3 # <int> <chr> <chr> <chr> #1 1 dizzy irritable anxious #2 3 focused anxious <NA> #3 7 relaxed <NA> <NA> data df1 <- structure(list(session = c(1L, 1L, 1L, 3L, 3L, 7L), side_effect = c("dizzy", "irritable", "anxious", "focused", "anxious", "relaxed")), class = "data.frame", row.names = c(NA, -6L)) worked perfectly thank you so much!!
common-pile/stackexchange_filtered
What is MediaPlayer.OnInfoListener “code 973”? I am running a stream via MediaPlayer. I use MediaPlayer.OnInfoListener to get info on the streaming process. Here is my code: mPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() { @Override public boolean onInfo(MediaPlayer mediaPlayer, int infoCode, int i2) { Log.d(TAG, "MediaPlayer.OnInfoListener: " + infoCode); return false; } }); I get infoCode = 973. I can't find it in the documentation : http://developer.android.com/reference/android/media/MediaPlayer.html What does it mean ? What exactly does the log print when you find that infoCode?
common-pile/stackexchange_filtered
How to escape single quote in EJS template my variable contains a string with an apostrophe or a single quote ' i'd like to display it with EJS. I use <img class="card-img-top" src='<%= data[i][0].omdb.Poster %>' alt='<%= data[i][0].omdb.Title; %>'> When data[i][0].omdb.Title; contains an apostrophe, HTML is broken. <%= is known to escape html. But not single quote! How to do it? Any idea please? I can't find anything on ejs doc. <%= is known to escape html. But not single quote! How to do it? Use double quotes around your attributes. Then single quotes won't matter. (If you really want to use ' then you can do ...Poster.replace(/'/g, "&apos;")).
common-pile/stackexchange_filtered
Japanese keyboard layout in Windows 7 doesn't correspond to what's written on the physical keyboard I have an English version of Windows 7, but my keyboard is Japanese. However, even though I choose a Japanese keyboard (Microsoft IME) under Keyboard and Languages, the layout isn't right. I think it's English layout, but I can't be sure. Anyway, I want the layout and usage to be exactly like it is on a Japanese Windows 7, as there are some nice (mouse free) shortcuts to change between input modes. Any suggestions? You can edit the registry to change from a 101 key keyboard to a 106 key keyboard. Go to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters Change the value of LayerDriver JPN from "kbd101.dll" to "kdb106.dll", and three other settings. I also had to change the KeyboardSubType to 2. I followed the official Microsoft directions found here: http://support.microsoft.com/kb/927824 OverrideKeyboardIdentifier also needs change from 101 to 106. Find the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters change these entries: LayerDriver JPN REG_SZ kbd106.dll OverrideKeyboardIdentifier REG_SZ PCAT_106KEY OverrideKeyboardSubtype DWORD 2 OverrideKeyboardType DWORD 7
common-pile/stackexchange_filtered
newman CLI '--export-collection' not outputting updated collection variables When using the newman CLI (version 5.2.2), there is a requirement to save updated collection variables after a run. To achieve this, -export-collection <path> is being used but variables in the collection at <path> do not contain updated values after a run. To set a variable value, pm.collectionVariables.set() is being used. let jsonResponse = pm.response.json(); pm.collectionVariables.set("myVariable", jsonResponse.value); When testing the request in Postman, the updated variable value persists in the collection. The same is true if the runner is used with Keep variable values checked. However, when using the newman CLI the collection variables are not updated after the run. newman run collection.json --environment environment.json --export-collection collection.json According to the documentation, --export-collection|globals|environment <path> is - The path to the file where Newman will output the final collection / global variables / environment variables file before completing a run. Testing shows that setting a global/environment variable in the request and using --export-globals|environment <path> works, with the output file containing the updated variable value. Is this a bug with the newman CLI, or is there something that can be done to fix this behaviour? its better to ask this in postman community forum or github , --export-collection The path to the file where Newman will output the final collection file before completing a run. it says final collection file , as its "final" collection file i think it should have the updated variable also . But it doesn't says anything specific about variables so not sure if that is the expectation of that flag
common-pile/stackexchange_filtered
javascript matches too many times I got problems with this regex. I want to return the first occurrence of this pattern #2344..... But somehow it is returning all occurrences. var title = '#34 #24 pofejwopwefjopewfjpfeijefow' pointsRegEx = /(#\d+){1}/; points = title.match(pointsRegEx); JSFIDDLE: http://jsfiddle.net/KbGVU/1 How about /#\d+/ ? Could you show more examples? It worked, stranged that I couldn't encapsulate it. Your regex is working fine. In your regex, you have (). This creates a group. .match returns an array. The 1st element is the result matched by the entire regex, the other elements are each group from your regex. .match is returning you ['#34','#34'] because the 1st is the entire regex, and the 2nd is the group in your regex (#\d+). Note: {1} is not needed, as it will match 1 match by default. The properties of the array returned from .match is documented here: mozilla docs. @Woho87 You should accept this as the correct answer if it helped you. Doing that will be helpful to others with the same question. Got chya... you don't need to match a match witha () grouping... http://jsfiddle.net/KbGVU/3/ /#\d*/ ought to do it I think he wants a number after the hash. So /#\d+/ would better. Those are the same thing, one is just more greedy.
common-pile/stackexchange_filtered
Person 1: I'm still confused why we subtract blue magnitude from visual to get B-V color index. Shouldn't hotter stars be brighter in blue? Person 2: They are brighter in blue, but remember magnitudes work backwards - smaller numbers mean brighter. So if a hot star has blue magnitude 1.2 and visual magnitude 1.5, its B-V is 1.2 minus 1.5, which gives -0.3. Person 1: Ah, so negative B-V means blue-hot, positive means red-cool. But why use magnitude differences instead of just measuring actual color? Person 2: Because the difference cancels out distance effects. Two
sci-datasets/scilogues
How to switch context in VS.NET 2015? I'm getting build errors because some classes I'm using are available in "DNX 4.5.1" and not "DNX Core 5.0". The error is: The type or namespace '[someclass]' could not be found. In the project column of the "Error List" window, I see DNX Core 5.0. In the context menu, DNX 4.5.1 is selected. Why does VS.NET try to keep using DNX Core 5.0 when the context is 4.5.1? 451 will be your projected .net framework. It has nothing to do with any references in the project. Check your references to make sure its only using the 451 version of your dnx. As I mentioned, that's what the context is set to. Are you referring to something else? If you're seening "DNX Core 5.0" in the project column of the Error List window it sounds like you have a project called "DNX Core 5.0" as part of your Visual Studio solution. Yes, you have a reference problem, not a context problem. Look in your references to the project. Have you listed "DNX Core 5.0"? If so, remove it and only reference the 451. In case some people are still struggling with this, you can dereference the DNX Core 5.0 by removing it from your framework references in the project.json file. The section "frameworks": { "dnx451": { }, "dnxcore50": { } }, Should become "frameworks": { "dnx451": { } }, If you're not targeting non-Windows platforms, then drop DNX Core 50 from your project.json file Rather than completely removing DNXCORE50 from your project.json. As before, you can add framework specific code if you wrap it in #if #endif as shown in the code below. The framework names DNX451 and DNXCORE50 are well known symbols actually referred to as target framework monikers (TFMs) and are the same throughout the project.json file, folder names, NuGet packages etc. Simply apply a conditional statement: public string Index(){ #if DNX451 //code logic here for DNX 4.5.1 #endif #if DNXCORE50 //code logic here for DNX Core 5.0 #endif } Found you have to use this on using statements, in my case using MySqlData.MySqlCLient - was causing me grief, thanks for this.
common-pile/stackexchange_filtered
Why symbol ω look like ╧ë, after I returned XML data from my Asp Net Core project to html via IActionResult? It's actual only for Greek symbols. Here is how I tried to solve this problem so far, I was trying to pass symbols into this functions: private string decodeSymbols(string symbols) { byte[] bytes = Encoding.Default.GetBytes(symbols); string myString = Encoding.UTF8.GetString(bytes); return myString; } private string decodeSymbols(string symbols) { return System.Net.WebUtility.HtmlDecode(symbols); } This didn't help at all. Here are examples, how it should look, and how it works. How it should look How it shouldn't look You can't encode using Default (which is ANSI for the local locale) and then decode using UTF8. You should be writing the XML file using UTF8 - are you? @MatthewWatson Thats a good question, the funny thing that i have symbols fine on my local, it looks as i expect. But when i use server, symbols are wrong. HTML has special character and you need to replace these character using System.Net.WebUtility.HtmlEncode(string) or System.Net.WebUtility.HtmlDecode(string). See Wiki : https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references @jdweng it didn't help, i tried already System.Net.WebUtility.HtmlEncode(string) and System.Net.WebUtility.HtmlDecode(string) Then the viewer that is looking at the data is using wrong Windows encoding. When you have ASCII data the codes 0 to 0x7F are always the same. The code for 0x80 to 0xFF are different depending on the windows encoding which is different depending on the country/language like Window 1251, 1252. See : https://docs.python.org/2.4/lib/standard-encodings.html Learn by example: 'ω'.encode('utf-8').decode('cp437') gives '╧ë' and unicodedata.name('╧ë'.encode('cp437').decode('utf-8')) yields 'GREEK SMALL LETTER OMEGA' in Python… [System.Text.Encoding]::GetEncoding(437).GetChars([System.Text.Encoding]::UTF8.GetBytes('ω')) is PowerShell / dotNet equivalent which could be more familiar to a C# person…
common-pile/stackexchange_filtered
What can I put on an unfinished cabinet that will not get a lot of use This cabinet will not get a lot of use. More of a storage cabinet that will have a lamp and cable box. I just need some sort of finish. Really don’t want to change the color. Hi, welcome to SE. How about nothing? There's no rule that wood must have finish on it, and in the past it was actually very common for utilitarian items to remain unfinished. Do note that wood and wood products of all kinds, including ply, MDF and chipboard/particleboard, will naturally change colour over time by themselves. Generally anything light in colour darkens, and often goes more amber-ish or tan, or a deeper beige/light brown, with exposure to light. The more light the faster and more pronounced the effect.
common-pile/stackexchange_filtered
Show that the perturbation of identity satisfies certain continuity and Lipschitz properties Let $d\in\mathbb N$, $u\in C^{0,\:1}(\mathbb R^d,\mathbb R^d)$ and $c:=|u|_{C^{0,\:1}(\mathbb R^d,\:\mathbb R^d)}$ (the semi-norm given by the Lipschitz constant). I would like to show that there is a $\tau>0$ such that $$T_t(x):=x+tu(x)\;\;\;\text{for }x\in\mathbb R^d$$ satisfies $T_t$ is a bijection for all $t\in[0,\tau]$; $T,T^{-1}\in C^{0,\:1}(\mathbb R^d,C^0([0,\tau],\mathbb R^d))$. It's easy to see that $$\left\|T(x)-T(y)\right\|_{C^0([0,\:\tau],\:\mathbb R^d)}\le(1+\tau c)\left\|x-y\right\|\;\;\;\text{for all }x,y\in\mathbb R^d.$$ Assuming $\tau\le(2c)^{-1}$ (I've read at other places that we need to assume $\tau\le\min(1,(2c)^{-1})$ but I don't understand why), we can show that $T_t$ is bijective for all $t\in[0,\tau]$: In fact, let $t\in[0,\tau]$, $y\in\mathbb R^d$ and $$f(x):=y-(T_t(x)-x)\;\;\;\text{for }x\in\mathbb R^d.$$ Then \begin{equation}\begin{split}\left\|f(x_1)-f(x_2)\right\|&=\left\|(x_1-x_2)-(T_t(x_1)-T_t(x_2))\right\|\\&\le tc\left\|x_1-x_2\right\|\end{split}\tag2\end{equation} for all $x_1,x_2\in\mathbb R^d.$ If $\tau\le(2c)^{-1}$, then $tc\le2^{-1}<1$ and hence $f$ is a strict contraction so that, by the Banach fixed-point theorem, there is a unique $x\in\mathbb R^d$ with $f(x)=x$, which is equivalent to $y=T_t(x)$. From the reverse triangle inequality and $(2)$ we see that $$\left\|x_1-x_2\right\|\le2\left\|T_t(x_1)-T_t(x_2)\right\|\tag3$$ for all $t\in[0,\tau]$ and $x_1,x_2\in\mathbb R^d$ and hence $$\left\|T_t^{-1}(x)-T_t^{-1}(y)\right\|\le2\left\|T_t(T_t^{-1}(x))-T_t(T_t^{-1}(y))\right\|=2\left\|x-y\right\|\tag4$$ for all $t\in[0,\tau]$ and $x,y\in\mathbb R^d$. How can we show the remaining claims? And, if $u\in C^1(\mathbb R^d,\mathbb R^d)$, under which condition can we show that ${\rm D}T_t=\operatorname{id}_{\mathbb R^d}+t{\rm D}u$ has a nonnegative determinant? What does $C^{0,:1}(\mathbb R^d,C^0([0,\tau],\mathbb R^d)$ mean? @zhw. Is is the space of Lipschitz continuous functions from $\mathbb R^d$ to $C^0([0,\tau],\mathbb R^d)$, where the latter is the space of continuous functions from $[0,\tau],\mathbb R^d)$. I'm slightly abusing notation when I write that $T$ belongs to this space; what's meant is that the map $x\mapsto t\mapsto T_t(x)$ is in this space. Sorry I don't understand this idea/notation at all. @zhw. I'm sure you understand it. Look, $T$ is a function depending on two arguments, $t$ and $x$. So, the natural way to think about $T$ is as a function from $[0,\tau]\times\mathbb R^d$ to $\mathbb R^d$. However, we may likewise think about $T$ as a function mapping $t\in[0,\tau]$ to a function $T_t$ from $\mathbb R^d$ to $\mathbb R^d$. In the same way, we may think about $T$ as a function mapping $x\in\mathbb R^d$ to a function $T(x)$ from $[0,\tau]$ to $\mathbb R^d$. And in this last interpretation, the claim $T\in C^{0,:1}(\mathbb R^d,C^0([0,\tau],\mathbb R^d)$ has to be understood. You were missing a parenthesis I think. The notation should be $C^{0,:1}(\mathbb R^d,C^0([0,\tau],\mathbb R^d),).$ Right? @zhw. Yes, of course. Fixed that. So it looked to me like the thing had the form $C^{0,1}(X,Y,Z),$ which made no sense to me. Assuming in addition $u\in C^1,$ it looks to me like there exists $\tau>0$ such that $DT_t$ has positive determinant everywhere. Is this of interest? @zhw. Yeah, I think I didn't noticed that when I wrote the question, but if $(T_t)_t$ is any family of $C^1$-diffeomorphisms on an open subset $U$ of $\mathbb R^d$ such that $T_0=\operatorname{id}_U$ and $[0,\tau)\times U\ni(t,x)\mapsto{\rm D}T_t(x)$ is continuous in the first argument uniformly with respect to the second, then there is a $\delta\in(0,\tau]$ such that $\det{\rm D}T_t(x)>0$ for all $(t,x)\in[0,\delta)\times U$. So, this would follow if we can show the continuity claim. That doesn't work, because you can have uniform continuity with first derivatives blowing up. For example, take $d=1$ and $$u(x)= \frac{\sin(x^4)}{1+x^2}.$$ Then $u$ is uniformly continuous on $\mathbb R.$ For $t\ge 0,$ set $T_t=I +tu.$ Then $T_t(x)$ is uniformly continuous in each variable. No matter how small $t>0$ is, $D(I+tu)(x)$ will take on negative values somewhere. However, in this problem $u$ is Lipschitz and $C^1,$ so all first derivatives are bounded. So things will work out if $t$ is small enough. @zhw. I'm not sure if I can follow. $T_0=\operatorname{id}_U$ and hence $\det{\rm D}T_0(x)=1>0$ for all $x\in U$. Now, $\det:\mathfrak L(\mathbb R^d)\to\mathbb R$ is continuous. So, if $[0,\tau)\times U\ni(t,x)\mapsto{\rm D}T_t()$ is continuous in the first argument uniformly with respect to the second, we can find $\delta>0$ with $\det{\rm D}T_t(x)>0$ for all $(t,x)\in[0,\delta)\times U$. What am I missing? Sorry, I misread what you wrote. Instead of $DT,$ I read it as $T.$ Dumb. So cancel the above two comments. I now bow out of this one.
common-pile/stackexchange_filtered
Select2 with checkbox not getting checked I have the following select2 html markup: <select id="industry_list" class="js-select2 form-control select2-hidden-accessible" style="width: 100%" multiple="" data-placeholder="Select industry..." name="industry_list[]" tabindex="-1" aria-hidden="true"> <option value="1">Accounting</option> <option value="37">Administration</option> <option value="41">Agriculture</option> <option value="2">Banking and Finance</option> </select> And the following javascript to prepend a checkbox to the options: window.prependCheckbox = function(data) { if (!data.id) { return data.text; } return $('<div class="checkbox no-margin">').append( $('<label>').append( $('<input type="checkbox" />').prop('checked', data.element.selected) ).append(data.text) ); }; $(function () { if ($(".js-select2").length === 0) { return; } $(".js-select2").select2({ templateResult: prependCheckbox, closeOnSelect: false }); }); If i select the checkbox or the label everything works fine i.e. checkbox get checked. But if I click the option label slightly to the right, the option still gets selected but the checkbox doesn't get checked - see image where i clicked the agriculture option where the cursor is it got selected but the checkbox did not get checked where as the other I click the checkbox or the label and checkbox get checked how do i get checkbox to get checked/unchecked regardless where i click on the option? label is an inline element by default, so yours will only extend as far as the width of the text demands it. Apply display: block to them. if I click the option label slightly to the right - sounds like you're clicking outside the <label> but still inside the <li> (as generated by [tag:select2]). Use the browser element inspector to view how much margin your <label> has.
common-pile/stackexchange_filtered
Get HTMLPurifier 4.5 to allow only one tag HTMLPurifier by default allows a lot of tags that I don't want to allow. According to the documentation you have to add definitions like this: $config = HTMLPurifier_Config::createDefault(); if ($def = $config->maybeGetRawHTMLDefinition()) { $def->addAttribute('a', 'target', new HTMLPurifier_AttrDef_Enum(array('_blank','_self','_target','_top'))); } $purifier = new HTMLPurifier($config); The problem is that I can't find a way to remove all tags that comes from HTMLPurifier_Config::createDefault();. For example the HTML <div>Sometext</div> will keep the DIV tag using the above initialization code. How can I set HTMLPurifier to only allow <strong>, <a href="*"> and <p>? I feel that HTMLPurifier may have become slightly over architected. You say: "According to the documentation you have to add definitions like this". Unless something fundamental has changed since the last time I checked the library (a year ago, about), that's not quite true - that part exists for if you want to teach HTML Purifier new attributes that it isn't natively aware of. For example, if you wanted to teach your HTML Purifier to accept non-standard <font> attributes, like align="", you'd need to alter the raw HTML definition. However, if your whitelist consists purely of regular HTML elements (and yours does!), you just need to use the $config object: $config = HTMLPurifier_Config::createDefault(); $config->set('HTML.AllowedElements', array( 'strong','a','p' )); $config->set('HTML.AllowedAttributes', array( 'a.href' )); $purifier = new HTMLPurifier($config); That should work. Are you running into problems with that constellation? (Check out this document, too: http://htmlpurifier.org/live/INSTALL ) Thank you. I've done it similarly to that before, but I thought the most recent version had changed their API a lot. The solution I found was to use the old way of configuring HTMLPurifier; if($def = $config->maybeGetRawHTMLDefinition()) { $config->set('HTML.AllowedElements', array( 'strong','a','p' )); $config->set('HTML.AllowedAttributes', array( 'a.href' )); } How this works in relation with the HTMLDefinition I don't know. Maybe they have a compatability layer. The biggest concern I have is that this is not using the $def variable returned - and that the changes I do to the config is not cached. I'm confused why you have that if in there at all; check out the end of http://htmlpurifier.org/live/INSTALL - you should be able to set those configuration values without a raw HTML definition get.
common-pile/stackexchange_filtered
access previous page viewstate in current page using response redirct? Is it possible to access the viewstate define in page1 from page2. Page1 is having response.rediect to page2. I don't want server.Transfer solution. No, that is not possible. The ViewState saves (serialize) the "changed" properties of ASP.NET controls and page during page processing. You should try the Session state.
common-pile/stackexchange_filtered
Why are not Laravel instances shared by default? I have been surprised to discover that Laravel instances are not shared by default. The "simplest" way I have found to declare a provider is the following: <?php namespace App\Providers; use App\SomeService; use Illuminate\Support\ServiceProvider; class SomeServiceServiceProvider extends ServiceProvider { protected $defer = true; public function register() { $this->app->singleton(SomeService::class); } public function provides() { $provides = parent::provides(); $provides[] = SomeService::class; return $provides; } } TMHO the "standard" service in a dependency injection container is a shared instance. I am curious about why they choose this approach ? And as a bonus, if you know a simpler way to declare a shared instance. Are you asking why they don't use singletons more often? I'm a little confused what you're asking. Yes, in my opinion it should be a logical default (to avoid resource consumption) Only if the class was designed to be shared. There are lots of cases where you wouldn't want stale instance data. Yes, it depends a lot on how you manage state.
common-pile/stackexchange_filtered
How to trim an SSN that generates from a model I have an SSN thats being sent in via a model that needs to be trimmed to only show the last four. I have it written as so string primarySsn = primaryApplicant.Ssn; Console.WriteLine(primarySsn.Remove(0, 5)); This isn't trimming and is still leaving the XXX-XX- that I don't want on the string. Your code works almost fine. Try this https://dotnetfiddle.net/BM1mWt Keep in mind that the Remove method does not alter the original string. So in your example, primarySsn will remain unchanged after the call to Remove. The code you provided should display only the last 4 characters of the string. You could try this one: var lastFour = primarySsn.Substring(primarySsn.Length-4,4);
common-pile/stackexchange_filtered
Debug error Flutter with third party SDK - Execution failed for task ':app:checkDebugAarMetadata'. > Could not resolve all files for configuration I am trying to integrate a third party android SDK in my Flutter project. After many trouble shooting, code probably is going to look like a Frankestein, I do not understand what I am missing or doing wrong. I keep getting the following error: - https://repo.maven.apache.org/maven2/io/flutter/x86_64_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_64_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom - https://jitpack.io/io/flutter/x86_64_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_64_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom - https://plugins.gradle.org/m2/io/flutter/x86_64_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_64_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom Required by: project :app > Could not find io.flutter:x86_debug:1.0.0-c4cd48e186460b32d44585ce3c103271ab676355. Searched in the following locations: - https://jcenter.bintray.com/io/flutter/x86_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom - https://dl.google.com/dl/android/maven2/io/flutter/x86_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom - https://repo.maven.apache.org/maven2/io/flutter/x86_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom - https://jitpack.io/io/flutter/x86_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom - https://plugins.gradle.org/m2/io/flutter/x86_debug/1.0.0-c4cd48e186460b32d44585ce3c103271ab676355/x86_debug-1.0.0-c4cd48e186460b32d44585ce3c103271ab676355.pom Required by: project :app * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 11s Error: Gradle task assembleDebug failed with exit code 1 My android/build.gradle file is buildscript { ext.kotlin_version = '1.7.10' repositories { google() mavenCentral() jcenter() maven { url 'http://download.flutter.io' allowInsecureProtocol = true } } dependencies { classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath fileTree(dir: 'libs', include: '*.jar') } } plugins { id 'com.android.application' version '7.4.1' apply false id 'com.android.library' version '7.4.1' apply false id 'org.jetbrains.kotlin.android' version "1.5.31" apply false id 'dev.flutter.flutter-gradle-plugin' version '1.0.0'apply false } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } tasks.register("clean", Delete) { delete rootProject.buildDir } and my app/build.gradle file is plugins { id 'com.android.application' id "kotlin-android" id "dev.flutter.flutter-gradle-plugin" id 'org.jetbrains.kotlin.android' } def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } android { namespace "com.example.ble_prova" compileSdkVersion flutter.compileSdkVersion ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/ build/application-id.html). applicationId "com.example.ble_prova" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the- gradle-build-configuration. minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation project(path: ':mokosupport') implementation files('app\\libs\\gradle-wrapper.jar') implementation files('app\\libs\\mokoBleLib.jar') implementation files('app\\libs\\mokoSupport.jar') implementation files('gradle\\wrapper\\gradle-wrapper.jar') implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation files('/Users/username/Developer/flutter/bin/cache/artifacts/engine/ android- arm64-release/flutter.jar') } My setting.gradle file is pluginManagement { def flutterSdkPath = { def properties = new Properties() file("local.properties").withInputStream { properties.load(it) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" return flutterSdkPath } settings.ext.flutterSdkPath = flutterSdkPath() includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") repositories { gradlePluginPortal() google() mavenCentral() mavenLocal() jcenter() maven { url 'http://download.flutter.io' allowInsecureProtocol = true } } plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" apply false id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS) repositories { jcenter() google() mavenCentral() maven { url "https://jitpack.io" } gradlePluginPortal() } } rootProject.name = "ble_prova" include ':app',':mokosupport' I have removed the strings id "com.android.application" version "7.3.0" apply false id "com.android.tools" version "7.5.1" apply false because I thought it was a problem of compatibility between Android Tool and Gradle version, but the error is the same. Please help me see what I am doing wrong here. Thanks
common-pile/stackexchange_filtered
LWR Community Page Language Selector Problem I have created a LWR community page where I have my custom LWC components. I used all custom labels from the org which have their own translations in multiple languages. Now, I've hidden the standard Language Selector component, however, I'm experiencing a weird use case issue Here's the thing. I'm sending a different email template based on a record's language field. Each template has its own unique path add-on which displays the lwc component with correct label translations. For example, in serbian, there is a /sh added to the URL. First time, everything works fine. However, once you've viewed the Serbian translation LWC component page, next time, when you visit the link in English, it doesn't load (although the link is correct). So, it shows the correct link for 1 second and then changes it to an invalid value that contains /sh (in this case it should be without it as the language was English). After some digging, I've found out that there is a cookie being saved called PreferredLanguage. If I delete all cookies from my browser, it shows the page as it should. I cannot seem to access this cookie from JS in my LWC. Any ideas on how to solve this? Welcome to SFSE! Please take a moment to read How to Ask and take the tour. Including a Minimal, Complete and Reproducible Example would be helpful. Your verbal description isn't enough to address your issue. Two options: Set a new cookie and expire the default salesforce one. Simply take the exact parameters from what you see generated in your browser cookies. If you have not set or expired cookies, just Google document.cookie. Add /?redirect=false to your base URL when switching back to the default language. I have tested both methods and it's working in LWR Enhanced as of 2/3/2023. Update: Also noticed you are hiding the language picker. There is no functional need for this component. So long as you set your URL values, the page will translate. For example, you can use /?lang=zh-TW OR /zh-TW/ Yep! I've solved it a while back with the links exactly as you've mentioned in the Updates part. That works.
common-pile/stackexchange_filtered
The render result is just the transparent texture? I rendered a 1200x800 image, but it's just the transparent texture thing: I used Cycles for this image. In a test in Blender Render, it worked perfectly, although the materials were made in Cycles so you obviously couldn't see them as you were supposed to. you need to create a cycles material for visible your render because cycles engine needs nodes tree for render you can't render blender internal material into cycles render I have cycle made materials w/ nodes yes you need to change
common-pile/stackexchange_filtered
getExternalStorageDirectory() is deprecated Suppose I have a Notepad-like app, where you can create and save text documents. I want my users to be able to access those files (so that they can copy them to a computer, for example). Before API 29, getExternalStorageDirectory() was a good choice - the directory was created in the root of sdcard and easily accessible. However, since API 29 it is deprecated. So now I have to use getExternalFilesDir(null) directory. The problem is that that directory's path is something like Android/data/your_package_name/files, which is very inconvenient for the users. Many of them can't find it. So, which method should I use? Check the alternatives in the deprecated note here: https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory() https://stackoverflow.com/questions/57116335/environment-getexternalstoragedirectory-deprecated-in-api-level-29-java - these answers might be helpful. You can use a classic file-picker module which you let start in the mentioned directory. Use getExternalFilesDir(), getExternalCacheDir(), or getExternalMediaDir() (methods on Context) instead of Environment.getExternalStorageDirectory().
common-pile/stackexchange_filtered
Flutter / dart exception geolocation error i have a problem with flutter / dart using geolocation . I have followed instructions from one Udemy course but i have expirienced this error. The package is uploaded and code completly resembles to the instructors code although it wont work . I have also tried to clean build file by entering : "flutter clean" in terminal, also didnt fix the issue . If i need to post some more info let me know . Thanks for your time . Cheers [VERBOSE-2:shell.cc(181)] Dart Error: Unhandled exception: RangeError (index): Invalid value: Valid value range is empty: 0 #0 List.[] (dart:core/runtime/libgrowable_array.dart:142:60) #1 _LocationInputState._getStaticMap (file:///Users/matija/Documents/Development/artapica/lib/widgets/form_inputs/location.dart:64:37) <asynchronous suspension> #2 _LocationInputState._updateLocation (file:///Users/matija/Documents/Development/artapica/lib/widgets/form_inputs/location.dart:124:7) #3 ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:161:21) #4 FocusNode._notify (package:flutter/src/widgets/focus_manager.dart:103:5) #5 FocusManager._update (package:flutter/src/widgets/focus_manager.dart:449:20) #6 _microtaskLoop (dart:async/schedule_microtask.dart:41:21) #7 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5) Location.dart class LocationInput extends StatefulWidget { final Function setLocation; final Product product; LocationInput(this.setLocation, this.product); @override State<StatefulWidget> createState() { return _LocationInputState(); } } class _LocationInputState extends State<LocationInput> { Uri _staticMapUri; LocationData _locationData; final FocusNode _addressInputFocusNode = FocusNode(); final TextEditingController _addressInputController = TextEditingController(); @override void initState() { _addressInputFocusNode.addListener(_updateLocation); if (widget.product != null) { _getStaticMap(widget.product.location.address, geocode: false); } super.initState(); } @override void dispose() { _addressInputFocusNode.removeListener(_updateLocation); super.dispose(); } void _getStaticMap(String address, {bool geocode = true, double lat, double lng}) async { if (address.isEmpty) { setState(() { _staticMapUri = null; }); widget.setLocation(null); return; } if (geocode) { final Uri uri = Uri.https( 'maps.googleapis.com', '/maps/api/geocode/json', {'address': address, 'key': 'MYKEY'}, ); final http.Response response = await http.get(uri); final decodedResponse = json.decode(response.body); final formattedAddress = decodedResponse['results'][0]['formatted_address']; final coords = decodedResponse['results'][0]['geometry']['location']; _locationData = LocationData( address: formattedAddress, latitude: coords['lat'], longitude: coords['lng']); } else if (lat == null && lng == null) { _locationData = widget.product.location; } else { _locationData = LocationData(address: address, latitude: lat, longitude: lng); } if (mounted) { final StaticMapProvider staticMapViewProvider = StaticMapProvider('MYKEY'); final Uri staticMapUri = staticMapViewProvider.getStaticUriWithMarkers([ Marker('position', 'Position', _locationData.latitude, _locationData.longitude) ], center: Location(_locationData.latitude, _locationData.longitude), width: 500, height: 300, maptype: StaticMapViewType.roadmap); widget.setLocation(_locationData); setState(() { _addressInputController.text = _locationData.address; _staticMapUri = staticMapUri; }); } } Future<String> _getAddress(double lat, double lng) async { final uri = Uri.https( 'maps.googleapis.com', '/maps/api/geocode/json', { 'latlng': '${lat.toString()},${lng.toString()}', 'key': 'MYKEY' }, ); final http.Response response = await http.get(uri); final decodedResponse = json.decode(response.body); final formattedAddress = decodedResponse['results'][0] ['formatted_address']; return formattedAddress; } void _getUserLocation() async { final location = geoloc.Location(); final currentLocation = await location.getLocation(); final address = await _getAddress( currentLocation['latitude'], currentLocation['longitude']); _getStaticMap(address, geocode: false, lat: currentLocation['latitude'], lng: currentLocation['longitude']); } void _updateLocation() { if (!_addressInputFocusNode.hasFocus) { _getStaticMap(_addressInputController.text); } } @override Widget build(BuildContext context) { return Column( children: <Widget>[ EnsureVisibleWhenFocused( focusNode: _addressInputFocusNode, child: TextFormField( focusNode: _addressInputFocusNode, controller: _addressInputController, validator: (String value) { if (_locationData == null || value.isEmpty) { return 'No valid location found.'; } }, decoration: InputDecoration(labelText: 'Address'), ), ), SizedBox(height: 10.0), FlatButton( child: Text('Locate User'), onPressed: _getUserLocation, ), SizedBox( height: 10.0, ), _staticMapUri == null ? Container() : Image.network(_staticMapUri.toString()) ], ); } } can't provide any help to you unless you share location.dart I have added location.dart . :) Thanks. The error points to line 64 and 124, could you tell me which are those lines. PS. you seemed to have posted the code as an answer instead of editing the original post, so I've edited your post for you to include it, it is just waiting for peer review. Also please provide an example of the JSON that you receive While providing you a JSON , i inserted line : print(decoded respose); after final decodedResponse = json.decode(response.body); . I found out that i'm surrpassing daily response limit of 1 . That was setted by google recently . . .. . Thought the issue might lay there. Glad you figured it out yourself While providing you a JSON , i inserted line : print(decoded respose); after final decodedResponse = json.decode(response.body); . I found out that i'm surrpassing daily response limit of 1 . That was setted by google recently . . .. . this was error message : flutter: {error_message: You have exceeded your daily request quota for this API. If you did not set a custom daily request quota, verify your project has an active billing account: http://g.co/dev/maps-no-account, results: [], status: OVER_QUERY_LIMIT} Thank you for your time once more. Cheers
common-pile/stackexchange_filtered
Mediawiki parser and recursiveTagParse I have an issue with rendering wikitext in hook for tag processing. public static function onTagRender( $input, array $args, $parser, $frame ) { ... $text = $parser->recursiveTagParse($sometext, $frame); ... return $text; } If $sometext contains e.g. "Example from page [[XYZ]]" then I expect returned $text should contain "Example from page <a href="/wiki/XYZ" title="XYZ">XYZ</a>" But I get only "Example from page <!--LINK 0:0-->" I have tried also $parser->replaceInternalLinks(), but with same result. What have I overlooked? If some people run into the same problem, try calling replaceLinkHolders after recursiveTagParse. (I didn't have the same problem so I didn't test it.) So in OP's code snippet, that would be: public static function onTagRender( $input, array $args, $parser, $frame ) { ... $text = $parser->recursiveTagParse($sometext, $frame); $text = $parser->replaceLinkHolders($text); ... return $text; } Explanation according to my understanding: Actually, the usual parse method calls the internalParse method -- which does most of the job -- and then do some other stuff. On the other hand, recursiveTagParse is almost only calling internalParse, so it doesn't execute the other stuff from parse. Problem is, links are parsed in two steps: Links are first extracted into LinkHolderArray and they are replaced with <!--LINK $ns:$key--> in the text. (This is done by replaceInternalLinks, called by internalParse, so that's fine.) Then <!--LINK $ns:$key--> markers are parsed into HTML links. (This is done by replaceLinkHolders which is called by parse, not by internalParse, and thus not by recursiveTagParse.) Parser::recursiveTagParse only do partial rendering, afaik. That may or may not be the problem. To fully render any user input, you will have to create a parser function (http://www.mediawiki.org/wiki/Manual:Parser_functions) instead of a tag function. See http://www.mediawiki.org/wiki/Manual:Tag_extensions#How_do_I_render_wikitext_in_my_extension.3F
common-pile/stackexchange_filtered
Compare Datetime I have some exception files which I want to be deleted after 14 days or so. But how can I compare the date times? It actually looks like this, but it does not work. DateTime date = DateTime.Now; DateTime newDate = date.Subtract(TimeSpan.FromDays(date.Day + 14)); DirectoryInfo exceptionsDirectory = new DirectoryInfo(pathToSave); foreach (FileInfo actualFile in exceptionsDirectory.GetFiles()) { if (actualFile.LastWriteTime.Subtract(TimeSpan.FromDays(date.Day + 14)) == newDay) { try { File.Delete(actualFile.FullName); } catch (Exception ex) { // do .. } } } Use something like this: DateTime expirydate = DateTime.Now.Subtract(TimeSpan.FromDays(14)); DirectoryInfo exceptionsDirectory = new DirectoryInfo(pathToSave); foreach (FileInfo actualFile in exceptionsDirectory.GetFiles()) { if (actualFile.LastWriteTime < expirydate) { try { File.Delete(actualFile.FullName); } catch (Exception ex) { // do .. } } } As with most DateTime related answers this would be better if it used DateTime.UtcNow and actualFile.LastWriteTimeUtc. It doesn't matter in this case since the question said "14 days or so" but in case anyone takes this code and tries to apply it to, say, one hour old files, they ought to use Utc. @IanMercer, it's not always good idea. In many situations you MUST rely on local and not on UTC time. I didn't say "always", I said "most". For instance: nearly every multi-user application running on a server (WWW, WCF, WebApi, ...) has no use for DateTime.Now. Whenever you need to calculate the difference between two times you need to use Utc. etc. etc. And even when you do need to work with local time you are better off using DateTimeOffset rather than DateTime because it captures both Utc and the current offset.
common-pile/stackexchange_filtered
Hand detection and tracking methods So, guys, please help me with detecting/tracking hand for user who are sitting at the computer in front of computer(laptop) frontal camera. I've tried these methods: Colour based detection(I've detected the human face by opencv haar cascade face detection and extracted the skin HSV ranges. In the next I've found the objects with the skin colour. For example, the face I can remove by knowing face detection by haar cascade, but what about other human body parts and background objects with skin colour if I need only hand? How to make this algorithm be more stable for illumination?) Train own haar cascade classifier(I've trained my own cascade to detect hand using 3.5k positive and 4k negative photos. It took 3 days to train. The dataset is pretty rich(various hand configurations and orientations, light conditions, different backgrounds). It works not so bad but it's very slow because of I set scaleFactor=1.3 and minNeighbors=70. If I decrease minNeighbors false alarms will grow tremendously and small reactangles will cover the whole video frame. Training params: opencv_traincascade -data data -vec samples.vec -bg neg.txt -numStages 16 -minhitrate 0.999 -maxFalseAlarmRate 0.5 -numPos 3200 -numNeg 3900 -w 24 -h 24 -mode ALL -precalcValBufSize 1024`` -precalcIdxBufSize 1024 Train LBP cascade classifier (The training was faster than haar cascade and detection works closer to real time but this detection method has a lot mishits) Training params: opencv_traincascade -data lbp -vec samples.vec -bg neg.txt -numStages 25 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 3200 -numNeg 3900 -w 24 -h 24 -mode ALL -precalcValBufSize 4096 -precalcIdxBufSize 4096 -featureType LBP I tried the different values of numStages from 16 to 25. Camshift algorithm to track hand The source code is here http://pastebin.com/q5zK8cZt. How it works? Just need to mark 4 poins around detected object and this algorithm must track it and draw rectangle around. The problem is if I started to move my hand this rectangle starts to grow and cover the whole video frame. It looks like this algorithm works only for small objects (or the objects are locating long distance from camera) Maybe I need to mix these methods or you will suggest another? Maybe I need to train neural network for example YOLO? I don't have wish to do it cause of it takes too long time and have to rent GPU-based servers. Did you have a look at random forests already ? Here are a few interesting links : https://github.com/kjw0612/awesome-random-forest#human--hand-pose-estimation GPU servers? No, you don't: there is a web based backend for object recognition. If you want to use Yolo you will need to mark a huge image train set (Around 2000 per class). I can advise fetch images from here using script like that (function(global) { const next = () => Array.from(document.querySelectorAll('.search-pagination__button-text'))[1].click(); const uuid = () => Math.random().toString(36).substring(7); const sleep = (timeout = 5000) => new Promise((res) => setTimeout(() => res(), timeout)); global.urls = []; global.next = () => next(); global.start = async () => { for (let i = 0; i !== 81; i++) { window.scrollTo(0,document.body.scrollHeight); await sleep(5000); document.querySelectorAll('.search-content__gallery-results figure > img[src]').forEach(({src}) => global.urls.push(src)); next(); await sleep(5000); } }; })(window); After that, you need to mark bounded boxes of objects in images. There is a online tool, which work right in your web browser For training neural network follow this instruction, binaries also can be taken from here.
common-pile/stackexchange_filtered
Explain the difference between the result got from Spark approxQuantile function and percentile_approx When I run the code below, I got the result: Quantiles segments =WrappedArray(-27.0, 2.0, 4443.0), which shows the median is 2.0 val quantiles = dfQuestions .stat .approxQuantile("score",Array(0,0.5,1.0),0.25) println(s"Quantiles segments =${quantiles.toSeq}") Quantiles segments =WrappedArray(-27.0, 2.0, 4443.0) When I used the percentile_approx(score, 0.25), I got the same result. Can anyone tell me why is 0.25 used in here, not 0.5 dfQuestions.createOrReplaceTempView("so_questions") sparkSession.sql("select min(score), percentile_approx(score, 0.25), max(score) from so_questions").show() So first, I am getting an error when I try code resembling yours: NameError: name 'Array' is not defined Replacing your Array() with brackets [] works although I removed your first argument of 0 because that yielded: Py4JJavaError: An error occurred while calling o257.approxQuantile. : java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double This is odd because the Apache Spark webpage for pyspark.sql.DataFrame.approxQuantile() indicates 0 for the probabilities argument captures the minimum. Perhaps this is a versioning issue. Anyhow, this worked: dfQuestions.stat.approxQuantile("score", [0.5,1.0], 0.25) Nevertheless, assuming both approxQuantile() and percentile_approx() are operating as expected then it is possible that the 0.25 percentile and 0.5 percentile (median) are the same. For example, they are equivalent in this list of 12 values: 0, 0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4 The 0.25 percentile is the fourth value = 2 (1/3 of values below 2) and the 0.5 percentile is between the sixth (2) and seventh (2) values, which is 2 because they are equivalent. Lastly, I allow that the approximations may not be working as expected. I have experienced more accurate results with percentile_approx(), even with a relativeError argument of 0 (exact calculation) instead of your 0.25 for approxQuantile(). The inaccuracy of an "exact calculation" does not make sense. I may be making an unknown mistake somewhere. I use percentile_approx() in a SQL line a la: score_quantile = sqlContext.sql("select percentile_approx(score, 0.25) as \ approx25Quantile from dfQuestions") score_quantile.show()
common-pile/stackexchange_filtered
Error connecting to localhost on port 4445. with Nightwatch and Selenium I'm trying to run my script using Nightwatch(Javascript), but I'm getting this error : \ Connecting to localhost on port 4445... ‼ Error connecting to localhost on port 4445. × failed Error: An error occurred while retrieving a new session: "session not created: This version of ChromeDriver only supports Chrome version 90" × failed Error: Nightwatch client is not ready. Looks like function "createSession" did not succeed or was not called yet. at Object.globals [as get] (C:\automation-Nightwatcg-12-27\QA Automation \node_modules\nightwatch-api\lib\proxy.js:21:17) at World.<anonymous> (C:\automation-Nightwatcg-12-27\QA Automation\/cucumber.conf.js:72:17) From nightwatch.js.conf webdriver: { start_process: !Boolean(process.env.NIGHTWATCH_SELENIUM_GRID), port: process.env.NIGHTWATCH_SELENIUM_PORT || 4445, }, I tried to run ChromeDriver Starting ChromeDriver 96.0.4664.45 (76e4c1bb2ab4671b8beba3444e61c0f17584b2fc-refs/branch- heads/4664@{#947}) on port 9515 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. So when running ChromeDriver, I can see it is running on port 9515 . I tried to edit the file nightwatch.js.conf with the port 9515 , but it didn't work. I also did those steps, but they didn't help Delete your package-lock.json file and node_modules folder. Then do npm cache clean 1-npm cache clean --force 2-npm install It seems I have a port conflict Does anyone has an idea to to proceed with this issue ? thank you in advance This version of ChromeDriver only supports Chrome version 90 This straight away looks to me like a compatibility issue between the chrome version you have on your machine and the chrome driver version you are using. maybe you need to update both of them to be compatible. Thank you Raju , you are right , I was inserting the updated vision of chrome.exe under the wrong file under Lib instead of bin .
common-pile/stackexchange_filtered
Space with diagonal matrices? Good evening everyone, I am trying to calculate the following quotient vector space $\mathbb{M_3(R)}/D$ Where $D$ is the space of diagonal matrices of order 3. My work: Let $A$ and $B$ be two matrices such that $A,B∈M_3(R)$, We say that $A∼B$ iff $A−B∈D$. But I do not know how to continue, that is, I do not know how to make this happen. I need to find the equivalence class of a matrix $A∈M_3(R)$. Can someone please help me? We know that $M_3(\mathbb{R}) \cong \mathbb{R}^9$ and $D \cong \mathbb{R}^3$, so we will have $M_3(\mathbb{R})/D \cong \mathbb{R}^6$. In fact, we can see $$ M_3(\mathbb{R})/D \cong \{A\in M_3(\mathbb{R}) \; | \; A_{ii} = 0\}$$ The equivalence class of $A$ is $\{A+\lambda I$ | $\lambda\in \mathbb{R}\}$, leaving us six entries to vary. How can I see $M_3(\mathbb{R})/D \cong {A\in M_3(\mathbb{R}) ; | ; A_{ii} = 0}$? Sorry! Construct a map $M_3(\mathbb{R}) \rightarrow {A\in M_3(\mathbb{R}) ; | ; A_{ii} = 0}$ sending $A \mapsto B$ where $B_{ij} = A_{ij}$ if $i \neq j$ and $B_{ij} = 0$ if $i = j$. This has kernel $D$ and is surjective, giving the required isomorphism by the first isomorphism theorem. Be this other exercise very similar, what if I want to see this vector space quotient $\mathbb{M_3(R)}/S$?, where $S$ represents the set of scalar matrices of order 3. What would be the equivalence class of any matrix $A$ and what isomorphism would define? Two matrices are equivalent if their difference is diagoanl; in other words, if the off diagonal entries of two matrices are the same then they are equivalent. In particular, all diagonal matrices are equivalent. The dimension of $M_3$ is $9$ and the dimension of the quotient space is $9-3$ since it is the off diagonal entries that define this quotient space. Is this object clear now? EDIT: Suppose $A$ is a matrix with entries $A_{ij}$ then $B\in [A]$ ( the equivalence class containing $A$) if $B_{ij}=A_{ij}$ for all $i,j$ whenever $i\neq j$. Thanks for your answer, but it's still not quite clear to me, how can I find the equivalent class of any $A$ Matrix 3x3 in this quotient? What do you mean whith "all diagonal matrices are equivalent"? Wellcthe difference of two diagonal matrcies is diagonal so by this definition they must be equivalent.
common-pile/stackexchange_filtered
XML parser returns NoneType I am trying to parse below XML format using the ElementTree XML in Python, but I get "member" as None, when I use .text it gives attribute error <address-group> <entry name="TBR"> <static> <member>TBR1-<IP_ADDRESS>_21</member> <member>TBR2-<IP_ADDRESS>_24</member> <member>TBR3-<IP_ADDRESS>_21</member> <member>TBR4-<IP_ADDRESS>_24</member> </static> </entry> <address-group> Here is my code: import xml.etree.ElementTree as ET tree = ET.parse("addrgrp.xml") root = tree.getroot() tag = root.tag print (tag) attr = root.attrib for entries in root.findall("entry"): name = entries.get('name') print (name) ip = entries.find('static') print (ip) for mem in ip.findall('member'): member = mem.find('member') print (member) What do you want to do? I mean - what is the information you want to collect from the XML doc? The code below aggregate the members of each entry by entry name import xml.etree.ElementTree as ET import pprint XML = ''' <address-group> <entry name="TBR1"> <static> <member>TBR1-<IP_ADDRESS>_21</member> <member>TBR2-<IP_ADDRESS>_24</member> <member>TBR3-<IP_ADDRESS>_21</member> <member>TBR4-<IP_ADDRESS>_24</member> </static> </entry> <entry name="TBR2"> <static> <member>TBR1-<IP_ADDRESS>_21</member> <member>TBR2-<IP_ADDRESS>_24</member> <member>TBR3-<IP_ADDRESS>_21</member> <member>TBR4-<IP_ADDRESS>_24</member> </static> </entry> </address-group>''' root = ET.fromstring(XML) data_by_entry = {} entries = root.findall('.//entry') for entry in entries: data_by_entry[entry.attrib['name']] = [m.text for m in entry.findall('./static/member')] pprint.pprint(data_by_entry) output {'TBR1': ['TBR1-<IP_ADDRESS>_21', 'TBR2-<IP_ADDRESS>_24', 'TBR3-<IP_ADDRESS>_21', 'TBR4-<IP_ADDRESS>_24'], 'TBR2': ['TBR1-<IP_ADDRESS>_21', 'TBR2-<IP_ADDRESS>_24', 'TBR3-<IP_ADDRESS>_21', 'TBR4-<IP_ADDRESS>_24']} The source of your problem is that: within for mem in ip.findall('member'): loop mem is the current member element, but the first instruction in this loop is member = mem.find('member'), so you attempt to find another (nested) member within the current member, which doesn't exist. Another flaw in your code is that there is no point in printing a node which does not have any text. Change your loop to the code below: for entries in root.findall('entry'): name = entries.get('name') print(name) ip = entries.find('static') print('Members:') for mem in ip.findall('member'): print(mem.text) and you will get meaningful result.
common-pile/stackexchange_filtered
How to solve Typescript import module problem I have split my code into several projects. And now trying to import the modules, located in node_modules. import Ticker from "ticker" // Typescript not complaining But the transpiled JS "import Ticker from "ticker;" does, module spec missing ‘./’, ‘../’ of ‘/’. But adding "./" leads to: "Cannot find module '.ticker' or its corresponding type declarations." import {Ticker} from "./node_modules/ticker/dist/ticker.js", results in a working application. But Typescript complains "Could not find a declaration file for module './node_modules/ticker/dist/ticker.js'. " Even if I use ///< reference path='node_modules/ticker/typings/ticker.d.ts' / > The ticker project package contains "main": "dist/ticker.js", "module": "dist/ticker.js", "typings": "typings/ticker.d.ts", ticker.d.ts declare module 'ticker' { class Ticker { constructor (container:HTMLElement); add (htmlElem:HTMLElement):number; } export default Ticker; } The main project tsconfig.json contains: "moduleResolution": "node", "baseUrl": "./", "paths": { "Ticker":["/node_modules/ticker/dist/ticker.js"] }, I'm using only tsc and getting confused by all provided options and possibilities. Why does VCode recognize the path "import {Ticker} from "./node_modules/ticker/ticker", pointing to the location of ticker.ts. But not "./node_modules/ticker/dist/", pointing to the ticker.js? "I have split my code into several projects. And now trying to import the modules, located in node_modules" Why is your code in node_modules? That's unusual. Third-party modules go there, but the modules for your own app (the one you're writing the code for) usually don't. Have you looked at another node module how they are set up? I would emulate their structure and configs. Is "ticker" a real node module? If yes you can set up post-install scripts to write configs, build to dist/ etc. The base project consists of a NodeJS data web crawler/scraper, a NodeJS data server (API's), and front-end dashboard applications. Multiple uses, project and thus code re-usage. Different sub-projects and maintainers. " Is "ticker" a real node module?", no! A web component (HTML dashboard). Other sub-projects are Node applications.
common-pile/stackexchange_filtered
How to solve boolean[]/Boolean[] method function mismatch? I am trying to send public static boolean key[] = new boolean[68836]; to the method in another class. But keep getting the following error: error: method tick in class Game cannot be applied to given types; game.tick(key); required: Boolean[] found: boolean[] reason: actual argument boolean[] cannot be converted to Boolean[] by method invocation conversion Ah, I saw what I did wrong! But now I also learned something that I did not know before. All thanks to Eran. Make an array of Boolean instead? Consider improving your title. It isn't very helpful as it doesn't refer to the problem in any way. If you're not sure of the difference between Boolean and boolean, do some research on wrapper classes for primitives. A boolean array cannot be converted to a Boolean array. boolean is primitive, Boolean is a sub-class of Object. You should pass a Boolean[] to your method, since that's what it expects. The funny thing is that it works in Eclipse but not in Netbeans. @MegaMeanboy - Not the same code. Likely either the parm value or the method definition is different in one vs the other. Ah, I saw what I did wrong! But now I also learned something that I did not know before. All thanks to Eran.
common-pile/stackexchange_filtered
Recovering accidentally deleted partition on a solid-state drive using "fdisk" As far as I know, a solid-state drive (SSD) stores data in different locations that the operating system cannot control. If I accidentally delete a partition, and then enter the exact start and end blocks of the previous partition when creating a new partition with fdisk, can I recover the files as I would on a regular hard drive (HDD)? CAUTION: Before making any changes to the drive at all, image every single byte of the drive in raw form. That way, you can always restore the drive to where it is now and, if necessary, you can experiment with data recovery attempts on copies of that image. Yes. SSDs move blocks around internally, but the block numbers they present as the interface to whatever is talking to them remain consistent and point to the same stored data, wherever it happens to be; so restoring a partition with the same start and end sectors as it had previously will restore the partition as it was. The only risk is if you trim the drive and the tool you use to trim discards the blocks which used to be in the deleted partition; if that happens you won’t be able to restore anything. (This isn’t specific to SSDs; some hard drives support block discard, and thin-provisioned storage supports block discard too.) Just make sure when you re-establish the partition boundaries that your tool does not make a new filesystem automatically for you @Stephen Kitt: When writing data, SSD is willing to use the blocks which has fewer writes or just the one is zero or any rules? @auzyveyauzyvey that depends on the drive’s firmware. In any case it’s transparent to the operating system. @roaima: I did it myself...As that if I didn't, I thought I couldn't see whether the data is there. When I rebuilt the partition with the right number, fdisk didn't tell me the NTFS signature, it means my data has gone? @auzyveyauzyvey fdisk doesn’t know about file systems, just partition types, and it‘s up to you to set those. To check whether your data is still there, you need to try mounting the file system. If you care about your data but don’t have recent enough backups, make a copy of the drive first. The NTFS signature is from the PBR - partition boot sector. With NTFS, the PBR must match the partition, it has some info on start & size of partition as well as other Windows info. I would have tried testdisk first. http://www.cgsecurity.org/wiki/TestDisk_Step_By_Step Sometimes deeper search may show files & best to immediately back them up, as some never see them again. Can the OS tell the SSD to store or modify a data in a specific block? I really don't think fdisk is the right tool for this, if you want to get data back from the SSD you need to avoid writing ANYTHING to the drive. I don't know this for sure but I would expect fdisk to create a new blank partition boot record when it creates the new partition. A deleted partition requires a proper partition recovery tool. I don't have a recomendation but if it is a NTFS partition you might need a Windows based recovery tool? If you have a big enough hard drive lying around then it might be worth cloning the SSD sector-for-sector? fdisk does not do "partition boot records" (and I don't think I've seen any partitioning tool that would), as those are dependent on what will be put in that partition later – there is no generic PBR that it could use anyway. You got me there, the PBR is only set during formatting, right? Well if fdisk strictly only sets the partition table entry and doesn't touch the partition contents at all then OP's plan could work.
common-pile/stackexchange_filtered
Round off error in C (Forward and Backward sum) #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ float sum=0.0; for(int i=1;i<=1000000;i++) sum+=(1.0)/i; printf("Forward sum is %f ",sum); sum=0.0; for(int i=1000000;i>=1;i--) sum+=(1.0)/i; printf("Backward sum is %f ",sum); return 0; } Output:- Forward sum is :- 14.357358 Backward sum is :- 14.392652. Why is there a difference in both sums ? I think that there is some precision error which is causing the difference in both the sums but I am not able to get a clear picture of why is this happening. OT: regarding: float sum=0.0; and sum=0.0; The variable 'sum' is declared as float, but the literals are doubles!. Suggest using: float sum=0.0f; and sum=0.0f; Note the trailing f that makes the literals float Possible duplicate of Is floating point math broken? use search to find duplicatres https://stackoverflow.com/questions/588004/is-floating-point-math-broken OT: regarding the statements: sum+=(1.0)/i; the literal 1.0 is a double, which the compiler should have told you about converting that double to float OT: it is poor programming practice to include header files those contents are not used. Suggest removing: #include <string.h> #include <math.h> #include <stdlib.h> @P__J__: That is not a duplicate. It covers general information about floating-point, not specific issues that arise, and not this particular issue. We do not mark various C questions as duplicates of one “Is C broken?” question. We answer the individual issues. The same should be done with floating-point. This is one of the surprising aspects of floating-point arithmetic: it actually matters what order you do things like addition in. (Formally, we say that floating-point addition is not commutative.) It's pretty easy to see why this is the case, with a simpler, slightly artificial example. Let's say you have this addition problem: 1000000. + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 But let's say that you're using a single-precision floating-point format that has only 7 digits of precision. So even though you might think that 1000000.0 + 0.1 would be 1000000.1, actually it would be rounded off to 1000000.. So 1000000.0 + 0.1 + 0.1 would also be 1000000., and adding in all 10 copies of 0.1 would still result in just 1000000., also. But if instead you tried this: 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 1000000. Now, when you add 0.1 + 0.1, there's no problem with precision, so you get 0.2. So it you add 0.1 ten times, you get 1.0. So if you do the whole problem in that order, you'll get 1000001.. You can see this yourself. Try this program: #include <stdio.h> int main() { float f1 = 100000.0, f2 = 0.0; int i; for(i = 0; i < 10; i++) { f1 += 0.1; f2 += 0.1; } f2 += 100000.0; printf("%.1f %.1f\n", f1, f2); } On my computer, this prints 100001.0 100001.0, as expected. But if I change the two big numbers to 10000000.0, then it prints 10000000.0 10000001.0. The two numbers are clearly unequal. The first loop starts with adding relatively large parts to the sum, and decreasingly smaller parts when the sum gets larger. So while more bits are needed to represent the sum, less bits are available for the small parts. In the second loop, small parts are added to the sum, and increasingly larger parts are added when the sum gets larger. So less bits are required to store the the newly added part relative to the current value of sum. (Not a very scientific explanation, but i hope this verbal attempt makes the principle clear) N.b.: it also means the second result is more accurate. In an attempt to be more precise: in order to add two floating point numbers they need to be scaled to have the same number of bits for mantissa and exponent. When the sum gets larger, the item added to will be scaled so as not to loose significance of this sum. As a result, the least significant bits of the part to be added will be scaled out of the register before the addition. For example (hypothetical) adding 0.00000001 to 1,000,000,000 will result in adding zero to this large number. @rici, important semantics: updated. However, I added some precision to my answer :-)
common-pile/stackexchange_filtered
Right-click on a table to to add to new Design Query in Access 2003 to 2007, 2010, 2013? In Access 2003, I used to be able to right-click on a table and create a new query in Design View with that table already added. It always saved me some clicking. In the newer versions of Access I have to use the Create tab on the ribbon and click the Query Design icon. Are there any other shortcuts to quickly creating a query that I am missing? Maybe a keyboard shortcut? The Quick-access toolbar is handy but I have hundreds of databases, and setting that up for each one is mind-numbing. Thx There is no known keyboard shortcut in newer versions of Access, nor is there a right-click shortcut. For inexplicable reasons, Microsoft seems to have removed them. You will have to use the ribbon, or you can add the Query Design function to the Quick Access Toolbar (the bar at the very top of Access which, by default, has the Save, Undo and Redo icons). I did, however, discover that CTRL + G brings up the VBA screen, which I wasn't previously aware of. :o)
common-pile/stackexchange_filtered
MongoDB PHP library - code works in terminal but not on browser I have installed the MongoDB PHP library using pecl by following the official documentation given on http://php.net/manual/en/mongodb.installation.pecl.php I have created a collection named 'ma' containing two documents 'd1' and 'd2', through the mongo shell. I am trying to connect to d1 through this file: connect.php <?php require_once __DIR__ . "/vendor/autoload.php"; $client = new MongoDB\Client("mongodb://localhost:27017"); $collection = $client->ma->d1; echo "Done\n"; echo $collection; ?> connect.php runs on my terminal and gives this output: $ php connect.php Done ma.d1 But on the browser it gives this error: This page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500 My machine is 64-bit Ubuntu 14.04 LTS. PHP version: 5.5.9. MongoDB shell and server version: 3.6.2. Apache server version: 2.4.7. I am sure the driver was installed correctly because I get this: $ php --ri mongodb | grep version MongoDB extension version => 1.4.0 libbson bundled version => 1.9.2 libmongoc bundled version => 1.9.2 I'm new to this driver. Any help would be greatly appreciated. Get rid of the use of PEAR/PECL. For all major PHP extensions, you will find pre-packaged and tested binaries right where you also found those for PHP itself. This will rule out that anything was wrong with the installation itself. Then, you can enable/disable extensions depending on whether the code is served by Apache or run on the commandline, check if both are enabled. BTW: You need to check the error logs. Doing so, you could have solved the problem yourself. Thanks for the suggestion, but since the official PHP site gave me the option to use PECL, I followed it. And I got it to work, so it's all good. Did you add the mongodb.so extension directive in the php.ini that is used by apache? See here: http://php.net/manual/en/mongodb.installation.manual.php Yes, I added that line during the installation but turns out I was supposed to restart Apache after that. I've answered my own question but thank you anyway. After adding extension = mongodb.so to the php configuration file (/etc/php5/cli/php.ini in my case), you have to restart the Apache server. sudo killall apache2 sudo service apache2 restart Also, not sure if this was related to MongoDB or just to Apache, but I got this error on restart: "apache2: Could not reliably determine the server's fully qualified domain name, using <IP_ADDRESS>. Set the 'ServerName' directive globally to suppress this message." So I followed this answer: https://askubuntu.com/a/256018 Finally, use this code to ensure the extension is being loaded: <?php echo extension_loaded("mongodb") ? "loaded\n" : "not loaded\n"; ?>
common-pile/stackexchange_filtered
How to arrange list using lambda or linq How to arrange list using lambda or linq. Following is the list (Tickets), The list having a field called MessageId", each MessageId may or may not contains sub messages and so on (ie, ReplyMessageId). I have the following list MessageId ReplyMessageId Message PostedDate 66 65 "Hello" 6/25/2013 10:00:01 AM 68 66 "[Reply to Hello]-1" 6/25/2013 10:12:23 AM 72 66 "[Reply to Hello]-2" 6/25/2013 11:12:23 AM 73 66 "[Reply to Hello]-3" 6/26/2013 9:12:23 AM 74 66 "[Reply to Hello]-4" 6/25/2013 11:12:12 PM 75 68 "[Reply to Hello-1] -1" 6/25/2013 11:05:12 AM 76 73 "[Reply to Hello-3] -1" 6/26/2013 10:10:23 AM 80 75 "[Reply to Hello-1-1] -1" 6/25/2013 11:45:22 AM 81 68 "[Reply to Hello-1]-1" 6/25/2013 11:45:22 AM For example, MessageId 68 is the reply of MessageId 66 and MessageId 68 having sub messages 75,81. The output list should be in the following format. MessageId ReplyMessageId Message PostedDate 66 65 "Hello" 6/25/2013 10:00:01 AM 74 66 "[Reply to Hello]-4" 6/25/2013 11:12:12 PM 73 66 "[Reply to Hello]-3" 6/26/2013 9:12:23 AM 76 73 "[Reply to Hello-3]-1" 6/26/2013 10:10:23 AM 72 66 "[Reply to Hello]-2" 6/25/2013 11:12:23 AM 68 66 "[Reply to Hello]-1" 6/25/2013 10:12:23 AM 81 68 "[Reply to Hello-1]-1" 6/25/2013 11:45:22 AM 75 68 "[Reply to Hello-1]-1" 6/25/2013 11:05:12 AM 80 75 "[Reply to Hello-1-1]-1" 6/25/2013 11:45:22 AM Try something like this var test = msgs.OrderByDescending(x => x.MessageId).ThenByDescending(x => x.PostedDate); Your second table doesn't match the definition; it is not "ordered by MessageId,Posted date in descending order" - since your first column MessageId is neither strictly ascending nor descending (...72,68,81,75,80,...). Presumably, then, this relates somehow to ReplyMessageId - but: can you define your intent more clearly, please? Frankly, personally I'd just construct this as a hierarchical (rather than flat) object model; much easier to work with As I understand your message is represented by MessageId, so what is sub-message represented by? I'd just build the tree; much simpler than trying to handle it while flat: class MessageItem { private readonly List<MessageItem> children = new List<MessageItem>(); public List<MessageItem> Children { get { return children; } } public int MessageId { get; set; } public int ReplyMessageId { get; set; } public DateTime PostedDate { get; set; } public string Message { get; set; } public override string ToString() { return string.Format("{0} ({1}): {2}", MessageId, ReplyMessageId, Message); } } static void Main() { // input data var cu = CultureInfo.InvariantCulture; var data = new[] { new MessageItem{ MessageId = 66, ReplyMessageId = 65, Message = "Hello", PostedDate = DateTime.Parse("6/25/2013 10:00:01 AM", cu)}, new MessageItem{ MessageId = 68, ReplyMessageId = 66, Message = "[Reply to Hello]-1", PostedDate = DateTime.Parse("6/25/2013 10:12:23 AM",cu)}, new MessageItem{ MessageId = 72, ReplyMessageId = 66, Message = "[Reply to Hello]-2", PostedDate = DateTime.Parse("6/25/2013 11:12:23 AM",cu)}, new MessageItem{ MessageId = 73, ReplyMessageId = 66, Message = "[Reply to Hello]-3", PostedDate = DateTime.Parse("6/26/2013 9:12:23 AM",cu)}, new MessageItem{ MessageId = 74, ReplyMessageId = 66, Message = "[Reply to Hello]-4", PostedDate = DateTime.Parse("6/25/2013 11:12:12 PM",cu)}, new MessageItem{ MessageId = 75, ReplyMessageId = 68, Message = "[Reply to Hello-1] -1", PostedDate = DateTime.Parse("6/25/2013 11:05:12 AM",cu)}, new MessageItem{ MessageId = 76, ReplyMessageId = 73, Message = "[Reply to Hello-3] -1", PostedDate = DateTime.Parse("6/26/2013 10:10:23 AM",cu)}, new MessageItem{ MessageId = 80, ReplyMessageId = 75, Message = "[Reply to Hello-1-1] -1", PostedDate = DateTime.Parse("6/25/2013 11:45:22 AM",cu)}, new MessageItem{ MessageId = 81, ReplyMessageId = 68, Message = "[Reply to Hello-1]-1", PostedDate = DateTime.Parse("6/25/2013 11:45:22 AM",cu)}, }; // build the hierarchy, using a parent lookup var ids = data.ToDictionary(x => x.MessageId); List<MessageItem> orphans = new List<MessageItem>(); foreach (var item in data) { MessageItem parent; (ids.TryGetValue(item.ReplyMessageId, out parent) ? parent.Children : orphans).Add(item); } // write the hierarchy using a stack (to avoid recursion) Stack<MessageItem> pending = new Stack<MessageItem>(); // the following looks backwards, but isn't (the stack reverses the order) // personally, I would use => x.PostedDate, but that gives a different order // (the *correct* order, IMO); this gives the *requested* order; no point // ordering *after* MessageId, as presumably that is unique foreach (var msg in orphans.OrderBy(x => x.MessageId)) pending.Push(msg); while (pending.Count > 0) { var next = pending.Pop(); Console.WriteLine(next); foreach (var msg in next.Children.OrderBy(x => x.MessageId)) pending.Push(msg); } } Great work... Thanks a lot. @Sanooj saying thanks with a +1 up-vote would be better. @Marc Gravell, I want to show the list in hierarchical way, So can you add a property(say "MarginLeft") in the resulting list with some values.
common-pile/stackexchange_filtered
How to ignore files or directories within bind-mount volume in docker-compose file? Is there any way to ignore some files or directories within volume of type bind-mount? I would like to ignore for example all bin and obj directories within my solution. The issue is that I have dozens of bin and obj folders in my project. I have tried with glob pattern but is seems not working with yaml files. version: '3.8' services: service-1: image: some-img:latest container_name: some-name build: context: ../ dockerfile: ./docker/Dockerfile volumes: - ../src/:/app/src/ # bind-mount - /app/src/project1/bin # AS-IS - /app/src/project1/obj # AS-IS - /app/src/project2/bin # AS-IS - /app/src/project2/obj # AS-IS - /app/src/*/bin # TO-BE (not working) - /app/src/*/obj # TO-BE (not working) - '/app/src/*/obj' # TO-BE (not working) Does this answer your question? Add a volume to Docker, but exclude a sub-folder Unfortunately no. I know how to ignore single file/directory by typing their path explicitly, but I would like to know how to ignore all specific files/directories without typing them explicitly. For exmaple ignore all bin folders from entire project
common-pile/stackexchange_filtered
Upload photo to facebook group Graph API I'm trying to make a post with photos as attachments to my facebook group where I'm admin using user access token. Permissions: user_birthday, user_hometown, user_location, user_likes, user_events, user_photos, user_videos, user_friends, user_status, user_tagged_places, user_posts, user_gender, user_link, user_age_range, email, read_insights, read_audience_network_insights, publish_video, manage_pages, pages_manage_cta, pages_manage_instant_articles, pages_show_list, publish_pages, read_page_mailboxes, ads_management, ads_read, business_management, pages_messaging, pages_messaging_phone_number, pages_messaging_subscriptions, instagram_basic, instagram_manage_comments, instagram_manage_insights, publish_to_groups, groups_access_member_info, leads_retrieval, public_profile, basic_info I tried multi-photo story solution: https://developers.facebook.com/docs/graph-api/photo-uploads#publishing-a-multi-photo-story For each photo in the story, upload it as published=false using the /user-id/photos endpoint. but with published=false I'm getting error: "message": "(#200) Requires extended permission: publish_actions" With published=true it works as expected (publishing new single photo to group), but I don't need that functionality. I can't even upload to my photos (me/photos endpoint) with published=False, same error. That solution only works for Pages (and appearently user profiles, according to the docs), because on Pages you can also schedule posts with that parameter. In groups, you can only publish immediately. Btw, publish_actions is deprecated, you should read this: https://developers.facebook.com/docs/graph-api/changelog/breaking-changes#login-4-24 Thanks, so there is no way to make a post to groups with photos using graph API? I just checked, there are scheduled posts in groups: http://prntscr.com/kc284g the bigger question is: why even try, when it stops working in a few days because of the breaking changes? btw, my bad, it seems to work for user profiles too, but there is no mention about groups: "You can upload an unpublished photo without publishing a story to the /user-id/photos or /page-id/photos edge"
common-pile/stackexchange_filtered
jQuery does not find IMG component by its ID I have a webpage which contains such code: <img class="img-qrcode" id="img_<IP_ADDRESS>" src="http://localhost:7777/data/code_img\<IP_ADDRESS>.png" alt="./data/code_img\<IP_ADDRESS>.png" style="display:none"> I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code: $("#img_<IP_ADDRESS>") The added screenshot shows that it returns an empty array. Why does it not find the element with ID ? Because it's not valid , Is img-qrcode an unique class? You should escape the dots. https://api.jquery.com/category/selectors/ I get values of IDs from database, the HTML page is formed by PHP script. These IDs mean the codes of parts. Using an attribute selector for id, you don't have to worry about escaping the class selector (.) let img = $("img[id='img_<IP_ADDRESS>']"); console.log(img.attr('src')) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img class="img-qrcode" id="img_<IP_ADDRESS>" src="http://localhost:7777/data/code_img\<IP_ADDRESS>.png" alt="./data/code_img\<IP_ADDRESS>.png" style="display:none"> The a . character has special meaning in a selector (it starts a class selector) so you need to escape it. (Remember to escape the slash character in a string literal). Generally it is easier to just avoid using . chapters in an id. I cannot avoid '.' symbols, because they are unique identifiers entered by users... They are IDs of parts. @IvanP. — Then either (1) When prompting users to enter a unique ID, ban . or (2) Do what I said in the first paragraph. Find with ^ let img = $("img[id^='img_123']"); console.log(img.attr('src')) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img class="img-qrcode" id="img_123" src="http://localhost:7777/data/code_img\<IP_ADDRESS>.png" alt="./data/code_img\<IP_ADDRESS>.png" style="display:none"> Does not fit my specifics. I may have ID which looks like '7<IP_ADDRESS>' @IvanP. It's totally wrong and invalid! can not start an id with number! Since #id.className is a valid selector jQuery assumes it so and tries to find such element. In your case you will have to escape the dot. Change $("#img_<IP_ADDRESS>") to $("#img_123\\.000\\.00\\.01") and it will work. Official jQuery documentation(https://api.jquery.com/category/selectors/) states it clearly. To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^{|}~` ) as a literal part of a name, it must be escaped with with two backslashes This return undefined, try to test it before post it I have tested it and it does not return undefined. You can check it here: https://codepen.io/v08i/pen/mdJPjWx Console output here: https://i.imgur.com/cKXJJ1M.png When some special symbols are in the jquery selector, you need to add 『\\』 console.log($("#img_123\\.000\\.00\\.01")); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title of the document</title> </head> <body> <img class="img-qrcode" id="img_<IP_ADDRESS>" src="http://localhost:7777/data/code_img\<IP_ADDRESS>.png" alt="./data/code_img\<IP_ADDRESS>.png" style="display:none"> </body> </html>
common-pile/stackexchange_filtered
formatting dynamic json array I have an json array as follows: Maindata=[ {"name":"string1"}, {"name":"string2"}, {"name":"string3"} ]; what I need is an array of following type: data=[ { "name":"string1", "name":"string2", "name":"string3" } ]; can anybody help me with some methods to obtain required json from original array. (note: maindata is json array formed dynamically thats why its structure is like that) Thanks in advance I don't think what you want as output is a valid object why is data not an object? why is there an array? Your second JSON is not valid JSON since object cannot have duplicated name. as I said Maindata is obtained dynamically creating html elemnts. like clicking a button so to add textboxes. So key of each element remains same. value String differs for each of them please look for my updated question and json Why do you need an array of one element, which contains a malformed "object"? With reduce, you can do like following var Maindata = [{ "name1": "string" }, { "name2": "string" }, { "name3": "string" }]; var finalObj = Maindata.reduce((acc, cur) => { Object.assign(acc, cur); return acc; }, {}) console.log(finalObj); its working if name and string are unique every time as your answer says. but in my case "name" stays same at each element so its returning only last element. can you update your answer. thank you You cannot have two properties of a single object with the same name. You could use Object.assign and spread the array elements. var array = [{ name1: "string1" }, { name2: "string2" }, { name3: "string3" }], object = Object.assign({}, ...array); console.log(object); You can use Array.forEach or Array.reduce to iterate though the items of the Maindata object and for each item you can iterate through its keys(using Object.keys) and group the data into a new structure.(See the below snippet) Solution using Array.forEach var Maindata=[ {"name1":"string1"}, {"name2":"string2"}, {"name3":"string3"} ]; var result = {}; var newMaindata=[]; Maindata.forEach(function(el){ Object.keys(el).forEach(function(key){ result[key]=el[key]; }); }); newMaindata.push(result); console.log(newMaindata); Solution using Array.reduce var Maindata = [{ "name1": "string1" }, { "name2": "string2" }, { "name3": "string3" }]; var result ; var newMaindata = []; result = Maindata.reduce(function(acc,el) { Object.keys(el).forEach(function(key) { acc[key] = el[key]; }); return acc; },{}); newMaindata.push(result); console.log(newMaindata);
common-pile/stackexchange_filtered
Should I throw std::bad_alloc? I am allocating memory on the stack, and distributing it manually to shared pointers. I end up doing something like this at startup (I've simplified it by ignoring alignment issues): char pool[100]; std::shared_ptr<Obj> p = new(reinterpret_cast<void*>(pool)) Obj; pool += sizeof(pool); Of course, it is possible that the 100 is not enough, so in that case I'd like to throw an exception: char pool[100]; char* poolLimit = pool + 100; if (pool + sizeof(Obj) >= poolLimit) throw std::bad_alloc(); // is this a good idea? std::shared_ptr<Obj> p = new(reinterpret_cast<void*>(pool)) Obj; pool += sizeof(pool); Is it correct to throw a std::bad_alloc here? Or should I just throw std::runtime_error? Why are you doing this? Looks like an x/y problem. @Ben it's part of an implementation of a heterogenous memory pool. The actual implementation uses std::align but for the purpose of this question that kind of detail wasn't necessary. The fact that it allocates on the stack is a minor detail, it could be on the heap as well. (I'm assuming you are writing an user-mode application here, not a kernel module, device driver or network stack). Throw std::bad_alloc. Only an idiot would try to catch that. But it doesn't really matter what you throw because the application is dead at that point anyway. What you want is for the application to quit at that point in a clear and unambiguous way. Calling abort would be even better. If you are operating out of a fixed buffer you really need to make sure it is big enough for all needs.
common-pile/stackexchange_filtered
How to use MockFor to mock client on HttpBuilder? I have some Grails production code I'd like to test and I've seen some examples of that here, see below. Problem is that I run into MissimgMethodExceptions on the client part of the HttpBuilder. This is the production code I'd like to test: class RunkeeperActivitiesRetrieverService { def http = new RESTClient("http://api.runkeeper.com/") def getActivities() { http.client.clearRequestInterceptors(); http.client.addRequestInterceptor(new HttpRequestInterceptor() { void process(HttpRequest httpRequest, HttpContext httpContext) { httpRequest.addHeader('Authorization', 'Bearer xxxxxxxxxx') } }) //Do more with the httpBuilder } } I found some help on the topic of mocking the HTTPBuilder here: Groovy HTTPBuilder Mocking the Response and some on mocking interfaces in the groovy docs here: http://groovy.codehaus.org/Groovy+way+to+implement+interfaces Using that code I came to this test code: def mock = new MockFor(HTTPBuilder) def impl = [ addRequestInterceptor : {HttpRequestInterceptor interceptor -> println "hi 4"+interceptor}, clearRequestInterceptors : {println "hi 88"} ] def client = impl as HttpClient mock.demand.getClient {return client} mock.use{ service.http = new HTTPBuilder() println service.getActivities() } Unfortunately my knowledge of Groovy is too limited to solve the exception that is thrown: groovy.lang.MissingMethodException: No signature of method: $Proxy15.clearRequestInterceptors() is applicable for argument types: () values: [] What am I missing here? You're casting impl to HttpClient - it doesn't appear the method in question is defined on that interface. Perhaps you mean to use some subclass of AbstractHttpClient.
common-pile/stackexchange_filtered
Visual Studio 2017 opening edmx file cause HRESULT: 0x80029C4A error I am trying to open edmx file with ADO.NET Entity Data Model Designer but I am getting the below error: Cannot load 'C:\MyUserName\source\repos\MyProject\MyModel.edmx': Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)) I have tried answers to similar questions: Repairing Visual Studio from Visual Studio Installer Re-installing Visual Studio Removing and re-installing Entity Framework 6 tools Running visual studio as admin and clean-rebuild project But none of them worked. Also, I can not re-install EntityFramework from the NuGet Package Manager or Console, the same error pops up. Adding a new ADO.NET Model is not possible either due to this error. This problem is not only occurring in this project but all of them so I guess it is directly related to Visual Studio. How can I fix this issue? Thanks! I am using .NET 4.8, EntityFramework 6.4.4 Hi @wenbingeng-MSFT, Thanks for your answer! I have switched to Visual Studio 2022 and everything works, Actually, I don't want to mess things up again by modifying the registry. Hi, you can share your solution and mark it to help more people Please follow these steps: Delete the registry (1) Win+r opens the run window and enters regedit to run the registry editor. (2) Find the registry of version 1.xxx Uninstall Visual Studio Reinstall Visual Studio
common-pile/stackexchange_filtered
UPS UK terms of service gives them a blank check - legal? UPS has terms and conditions (PDF) that include the following: 4. Customs Clearance When a shipment requires customs clearance, it is the shipper’s obligation to provide, or to ensure that the receiver will provide, UPS with complete and accurate documentation for the purpose but UPS will, unless instructed otherwise, act on behalf, at the expense and at the risk of the shipper or receiver in obtaining customs clearance. Provided that, in the case of shipments whose points of dispatch and destination are both within the same customs area, UPS only performs customs clearance if instructed to do so. The shipper also agrees that UPS may be considered as being the receiver of the package or the shipment for the sole purpose of appointing a customs broker to carry out any customs clearance insofar as is allowed by law They've used these terms to charge me an additional "brokerage fee" for a package I sent. The charge is 113.29 euros and the package won't be released unless I pay them. But at no point is the amount stated to the user - they could well have charged a 1000 euros and I'd still be on the hook for that. In my case, the contents of my package were worth less than the broker fee. Is it even legal to have T&C that just let them charge anything they want? Is there an ombudsman or some other government body to whose attention I can bring this to? It's in a different document - and probably a regular fee. UPS Service Guide [Singapore] explains for example what brokerage fees are. In general, they are to cover UPS' expenses that they incurred paying your import taxes when the package came into the country. A price listing for UPS services for Germany, also lists various customs and brokerage items. Among the brokerage fees, there's a single line item that has a percentage price: Disbursement Fee. The pricing there is listed as: UPS customs brokers are experienced with complex commercial shipments. Electronic transmissions of shipment data helps speed customs clearance. UPS may prepay duties, taxes and other government charges on behalf of the payer. Disbursement charges are noted in the Additional Charges Table. €6 per shipment having an intrinsic value lower or equal to €22, €12,50 minimum or 2,50% of the advanced amount when the intrinsic value of the goods exceed €22. Deducting the Bonded Transfer Handling Fee, the price tag for the item would need to be in the ballpark of 3547,60 € to incur a disbursement fee of 88,69 €, which is their fee for lending you the taxes and duties for the item. Thanks, my package was worth 115 euros (100 GBP) per the commercial invoice. It consisted of personal effects and a couple of weeks ago, the UPS customer service confirmed that I didn't need to pay any customs duty on it since I declared that it was entirely composed of personal effects. Even if I paid duty, it would be not that much. So I'm not sure why the broker fee was so high @user1936752 I suspect that Customs disagreed with your personal effects label and that was the cause of the issue. @user1936752 you might want to inquire about the exact splitdown of all charges - and as you say 100 GBP I assume the german table does not apply but the british one - you might need to look that up Taking a broader view … It is perfectly legal for a contract clause to be in effect a “blank cheque”; or more accurately a right to levy charges that cannot be determined in advance and may be substantial. Some examples: A liquidated damages clause imposing a per diem amount for each data project is delivered late. An indemnity against suits bought by third parties. A cost plus contract where the buyer agrees to pay the vendor’s costs plus a percentage margin. There is nothing inherently unlawful about such clauses although, in practice, they do tend to lead to higher levels of dissatisfaction and dispute than clauses where the costs are known up front.
common-pile/stackexchange_filtered
How to call a non static method from static method I need to call a non static method from a static[webmethod]. It is not getting call, I tested it using breakpoints.i tried to call it by making a instance to the class. This is what i am trying . [WebMethod] public static string get_runtime_values(string get_ajax_answer_title,string get_ajax_answer_des) { if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals(""))) { return "null"; } else { int got_question_id = getting_question_id; DataHandler.breg obj = new DataHandler.breg(); obj.add_anwers(got_question_id, get_ajax_answer_title, get_ajax_answer_des); return "inserted"; } querystring object_new = new querystring(); object_new.show(); } querystring is name of the class here.The control is going into if and else statements depending upon input,but after that it directly get jump out.Moreover when i hover the mouse over querystring ,it says Unreachable code detected. What should I do to make it working? You have a return in both the if and else sections... you'll never reach the next line also: replace if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals(""))) with if (get_ajax_answer_title.Equals("") && (get_ajax_answer_des.Equals(""))) You could have googled this before posting such question it will save every ones time at SO.this should help http://stackoverflow.com/questions/1360183/call-non-static-method-from-static-method-c-sharp. @ankur That won't help, the cause is completely different. @hvd oops i didn't check the complete stuff yup freefaller has pointed out the thing which needs to be changed . [WebMethod] public static string get_runtime_values(string get_ajax_answer_title,string get_ajax_answer_des) { string result; if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals(""))) { result="null"; } else { int got_question_id = getting_question_id; DataHandler.breg obj = new DataHandler.breg(); obj.add_anwers(got_question_id, get_ajax_answer_title, get_ajax_answer_des); result="inserted"; } querystring object_new = new querystring(); object_new.show(); return result; } It's not a good idea to just put code... for one thing, it's not always obvious what your change is, and it's always better to give a reason for the change That's because you return from both halves if the preceding if statement. There is no way for it to get up to that line. It's because you have a return statement in both the IF and ELSE section. So regardless of the result of the conditional; you never get below that. Your method ends after the if statement, wether it is true (return "null") or not (return "inserted"). So your code that is after the if statement (where you create the query string) can never be executed. querystring object_new = new querystring(); object_new.show(); part will never be reached because in both of your block statement in your condition you wrote a return. Yes, that is because you have return statements at the end of both your if and else blocks. Change it to [WebMethod] public static string get_runtime_values(string get_ajax_answer_title,string get_ajax_answer_des) { string ret = "null"; if (!get_ajax_answer_title.Equals("") || (!get_ajax_answer_title.Equals(""))) { int got_question_id = getting_question_id; DataHandler.breg obj = new DataHandler.breg(); obj.add_anwers(got_question_id, get_ajax_answer_title, get_ajax_answer_des); ret = "inserted"; } querystring object_new = new querystring(); object_new.show(); return ret; } Your problem is that you are exiting your method in both your if and else clauses. Your code is essentially: MyMethod() { if (someCondition) return else return // Any code at this point cannot be executed, because // you have definitely returned from your method. } Unreachable code detected. is because both paths of your if statement return early. if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals(""))) { return "null" } else { return "inserted"; } // Can't get here. You have answered your original question correctly, i.e. Instantiate an instance of a non-static method to be able to call a method on it. querystring object_new = new querystring(); object_new.show();
common-pile/stackexchange_filtered
What's the most straightforward way to clone an empty, *bare* git repository? I've just finished cruising the Google search results that contain all the email rants about how stupid it is that git can't clone an empty repository. Some kind soul even submitted a patch. Until git is upgraded, what is the simplest, most straightforward method to clone an empty, bare git repository? The ideal solution will support the -o option to give the remote repo a name other than origin, and it will be implementable as a simple shell script, e.g., git-clone-empty-repo. (Why I want to do this: I've set up a bare, empty git repo on our NetApp filer where it will be backed up, but I want to work with a clone on my local hard drive and push and pull back and forth. Other people I work with will be doing the same. I create new git repos a lot and my inability to clone an empty repo makes me crazy.) EDIT: VonC's thread suggests that $ git-init $ git-remote add origin server:/pub/git/test.git is equivalent to cloning the remote repo when the repo is empty. This is not quite what I want because I always use the -o option with git clone; I name the remote repo according to what machine it is on or some other memorable criterion. (I have too many repos to keep them straight if they're all called origin.) EDIT: The following answer will be marked accepted :-) To clone an empty, bare repo at path, Keep at ~/git/onefile a non-bare git repo containing one innocuous file such as .gitignore. (Alternatively, create such a repo dynamically.) (cd ~/git/onefile; git push path master) git clone -o name path In other words, don't attempt to clone the empty repo, but rather after creating it, push to it a simple repo containing one innocuous file. Then it is no longer empty and can be cloned. If someone does not beat me to it, I will post a shell script. Added a way to transform an "almost empty" repository into an "almost empty" bare repository, as requested I think that modern supports cloning empty repository, or future git would support cloning empty repository Version <IP_ADDRESS>, current on Debian, does not clone an emty, bare repo. May be just have a git repo with the minimum number of file in it: one: .gitignore with obvious ignore patterns in it. And then clone that "almost empty" repository. Note that such an "almost empty" repository ("almost" because it still has a minimal working directory alongside the .git directory) can then by 'git clone --bare' (as illustrated here), making it a true bare repo (but not an "empty" one). This is that bare repo you can then: clone everywhere you want. or (more importantly) push to (since it is a bare repo) You have in this thread a good summary of the "other way around" (which I keep here for reference). $ git-init $ git-remote add origin server:/pub/git/test.git For a new project (no code yet) I wanted to make an empty, bare repository (no working copy) on a remote public server as a starting point, clone it locally, and gradually create content locally and push it out to the remote, public server. To which Junio C Hamano responded: You prepared an empty bare repository for publishing, and that is very good. The next step is that you prepare your contents elsewhere. That would be your private working place, i.e. the place you would normally work in). You push from your private working place into that publishing repository. Your working place is where the very initial commit should come from, since you are the one who is starting the project. Note that the private working place does not have to be a clone of the empty one. That actually is backwards. Your work started from your private working place to the publishing one. You could even clone your private repository to publishing one to make it clear who is the master and who is the copy if you wanted to, but because you already have the bare repository for publishing, just pushing into it is all that is needed. I'm creating a bare git repo so there is no working directory. Perhaps I need a standard 'almost empty' repo in a standard place which I can then push to an empty repo? But once you create an "almost empty" repos, you can 'git clone --bare' it and make it a true bare repo ( http://stackoverflow.com/questions/738154/what-does-git-updating-currently-checked-out-branch-warning-mean ) If create an almost empty repo, I may as well just push from it to a newly initialized bare repo. If you don't mind scraping the extra cruft off your answer, I could upvote it :-) Note to self: See http://stackoverflow.com/questions/1298190/gitosis-and-git-clone-problem/1298224#1298224 about cloning empty repo
common-pile/stackexchange_filtered
Possibility of working on KDDCup data in local system I'm trying to apply classification algorithms to KDD Cup 2012 track2 data using R http://www.kddcup2012.org/c/kddcup2012-track2 It seems not possible to work with this 10GB training data on my local system with 4GB RAM. Can anyone work on this data using this kind of a local system ? Or is using a cluster the norm ? It would be great if anyone could provide me with any guidance on how to get started with working on a cluster and the normally used type of cluster for such tasks I think that you have, at least, the following major options for your data analysis scenario: Use big data-enabling R packages on your local system. You can find most of them via the corresponding CRAN Task View that I reference in this answer (see point #3). Use the same packages on a public cloud infrastructure, such as Amazon Web Services (AWS) EC2. If your analysis is non-critical and tolerant to potential restarts, consider using AWS Spot Instances, as their pricing allows for significant financial savings. Use the above mention public cloud option with R standard platform, but on more powerful instances (for example, on AWS you can opt for memory-optimized EC2 instances or general purpose on-demand instances with more memory). In some cases, it is possible to tune a local system (or a cloud on-demand instance) to enable R to work with big(ger) data sets. For some help in this regard, see my relevant answer. For both above-mentioned cloud (AWS) options, you can find more convenient to use R-focused pre-built VM images. See my relevant answer for details. You may also find useful this excellent comprehensive list of big data frameworks. Thanks for the answer. I have access to some local systems, can you give me a start on how to set up a cluster using these systems without any cloud services ? Looks like everywhere AWS is being used. @abhivij: You're welcome. Setting up a cluster is not a rocket science, but might be not trivial, depending on the requirements and your current skills. You can read this blog post and this blog post as a starting point. (to be continued) @abhivij: (cont'd) Also, you'd have to refer to documentation on multiprocessing R packages that you will decide to use, for example this tutorial. A more high-level overview and example of an R-based cluster can be found in this working paper. Hope this helps.
common-pile/stackexchange_filtered
Kotlin Goal Oriented Action Planning I've implemented Goal Oriented Action Planning (GOAP) in Kotlin. Goal Oriented Action Planning is an algorithm originally devised by J Orkin for the game F.E.A.R. and performs a state space search using A* in order to formulate a plan of actions to get from an initial state to a goal state. I've commented the code comprehensively and written some tests. I'm looking for a code review to make sure my naming is good, my comments are good and that overall it makes sense. import org.junit.Test import java.lang.Math.* import java.util.* import kotlin.collections.HashSet import kotlin.test.assertFalse import kotlin.test.assertTrue /** * This set of algorithms is an example of a Goal Oriented Action Planner (aka GOAP) * * Goal Oriented Action Planning (GOAP) is a method of planning developed by J Orkin for the game F.E.A.R. * It can be conceptualized in a few ways - I like to think of it as dynamically calculated FSM * as you do not need to explicitly write the state transition table and it is instead calculated at run time * by searching through states given a set of actions. In other words GOAP is a state space search algorithm that outputs plans. * You can read more about GOAP here: http://alumni.media.mit.edu/~jorkin/goap.html * * First there is an implementation of A* which is the basis for the state space search * I have also implemented simple Cartesian graph search to show the extensibility of the A* implementation * * The idea with GOAP is that you would have many agents in an environment, and each agent has sensors that update a state that the agent maintains * The agents will then be able to formulate a plan of actions, given a goal state and their current state by using the GOAP algorith * This plan would then be actuated by actuators which in turn would then affect the environment, causing the sensors to update the agents state * This process continues in a feedback loop so the agents should be able to act autonomously within any given environment. * * In other words, this solution can be used for games, robotics or even abstract problem domains such as shipping systems * Where plans must be formulated based on dynamically changing conditions * * The plans generated by this particular implementation of GOAP are totally ordered * In future, work will be undertaken to modify this solution so that it can generate partially ordered plans * But that is a much more challenging problem to solve as partially ordered plans would require a completely different approach than A* */ /** * Searches for the shortest path [from] -> [to] and returns a [Stack] of [AStarNode] representing the path (i.e. this is A*) * By applying [heuristic] and [cost] for each evaluated open node to calculate the f cost to the goal * This is non greedy BFS so long as [heuristic] is admissible (i.e. never overestimates) * For example, in the case of 2D geometric search, the [heuristic] can be considered admissible if it measures euclidean distance * In addition [from] and [to] should be part of either an oriented or bi directional graph which can be navigated via calling [neighbours] on a given [AStarNode] */ fun<T> path(from: AStarNode<T>, to: AStarNode<T>, heuristic: ((AStarNode<T>, AStarNode<T>) -> Int), cost: ((AStarNode<T>, AStarNode<T>) -> Int)) : Stack<AStarNode<T>> { /** * Reconstructs a path, represented as a [Stack] of [AStarNode] * By updating a pointer to a node until the pointer points at null */ fun reconstructPath(from: AStarNode<T>) : Stack<AStarNode<T>> { val path = mutableListOf<AStarNode<T>>() var current: AStarNode<T>? = from path.add(current!!) while (current?.from !== null) { path.add(current.from!!) current = current.from } path.reverse() return Stack<AStarNode<T>>().apply { path.forEach { this.push(it) } } } // Use a priority queue for maintaining the open boundary of the search // This means the search will always expand the optimal edge of the border val openQueue = PriorityQueue<AStarNode<T>>() // Use a hash set for the closed nodes to increase performance on big graphs val closedSet = HashSet<AStarNode<T>>() // The g cost of the initial node is by definition 0 from.g = 0 // The heuristic cost of the initial node is the heuristic function applied to it and the goal from.f = heuristic(from, to) // Of course, the initial node is the only node on the open border of the search before searching openQueue.offer(from) // Begin the search // While there are still nodes to explore on the open border while (!openQueue.isEmpty()) { // Get the highest priority node val current = openQueue.poll() // Check if we've reached the goal node if (current == to) return reconstructPath(current) // Ok, we still need to search // Add the node to the closed set so we don't evaluate it again closedSet.add(current) // For each neighbour of the node calculate it's g cost and update it's from pointer current.neighbours().forEach { neighbour -> // If the neighbour is in the closed set ignore it if (closedSet.contains(neighbour)) return@forEach // Calc a new g score val tentativeG = current.g + cost(current, neighbour) // Push the neighbour into the open border if it's not already there // If it is already there and has a lower g cost then ignore it if (!openQueue.contains(neighbour)) { openQueue.offer(neighbour) } else if (tentativeG >= neighbour.g) { return@forEach } // We've found a shorter path // Update the neighbours from pointer and costs neighbour.from = current neighbour.g = tentativeG neighbour.f = neighbour.g + heuristic(neighbour, to) } } // The open border was exhaustively checked, no path exists! throw IllegalArgumentException("No path can be found from $from to $to") } /** * Parameterized type which wraps some [data] along with a pointer to the [from] node and [g] and [f] costs used in A* search * The type argument [T] means that A* can be performed for any type as long as there is an admissable heuristic calculable for the type [T] */ abstract class AStarNode<T>(val data: T?, var from: AStarNode<T>? = null, var g: Int = Int.MAX_VALUE, var f: Int = Int.MAX_VALUE) : Comparable<AStarNode<T>> { /** * Returns a [Collection] of neighbour nodes * In the case of euclidean nodes this is simply the connected nodes on the graph * In the case of non euclidean nodes this could be a function of any number of things * For instance, in a state space search, this could return any states which were transition to from valid actions */ abstract fun neighbours() : Collection<AStarNode<T>> /** * Implemented so these can be used in a priority queue */ override fun compareTo(other: AStarNode<T>): Int { return when { this.f < other.f -> -1 this.f > other.f -> 1 else -> 0 } } } /** * An implementation of [AStarNode] for cartesian space search * A cartesian space search takes place on a 2D plane through a oriented or bi-direction graph of points in space * A point in cartesian space is defined by an [x] and a [y] value and, in this case, also has an associated [label] */ class CartesianNode(val x: Int, val y: Int, label: String, private val neighbours: MutableCollection<CartesianNode> = mutableListOf()) : AStarNode<String>(label) { /** * Distance to another node is euclidean and worked out using pythagorean theorem */ fun distanceTo(other: CartesianNode) : Int { val dx = abs(this.x - other.x).toDouble() val dy = abs(this.y - other.y).toDouble() return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt() } /** * Used to add an [other] neighbour */ fun addNeighbour(other: CartesianNode) { this.neighbours.add(other) } /** * Implement the neighbours functionality by simply returning an immutable copy of the neighbours list */ override fun neighbours(): Collection<AStarNode<String>> { return this.neighbours.toList() } /** * A cartesian node is equal to another one if the coordinates are the same */ override fun equals(other: Any?): Boolean { return if (other !is CartesianNode) { false } else { this.x == other.x && this.y == other.y } } /** * Implement hash code so this can be used in a hash set */ override fun hashCode(): Int { var hash = 7 hash = 31 * hash + g hash = 31 * hash + f hash = 31 * hash + data.hashCode() return hash } } /** * Wraps [findPath] providing functions for the heuristic and cost in cartesian space */ class CartesianPathfinder { fun findPath(from: CartesianNode, to: CartesianNode) = path(from, to, { x, y -> (x as CartesianNode).distanceTo(y as CartesianNode) }, { x, y -> (x as CartesianNode).distanceTo(y as CartesianNode) }) } /** * An implementation of [AStarNode] for state space search * A state space search occurs in an abstract space where points within that space represent states * and edges between the point represent actions taken to reach a state from a state * A point in state space search is defined by a [worldState] and keep a reference to an [actionPool] of possible [GoapAction] * These also keep a reference to the [actionTaken] to reach the state */ class GoapNode(val worldState: WorldState, private val actionPool: Collection<GoapAction>, actionTaken: GoapAction? = null) : AStarNode<GoapAction>(actionTaken) { /** * Implementation of neighbours for state space search * Neighbours in this case are other states which can be reached by applying all possible valid actions to this state */ override fun neighbours(): Collection<AStarNode<GoapAction>> { // For all actions in the action pool // If they are valid, apply the action to this state, otherwise ignore it return actionPool.mapNotNull { action -> if (action.isValid(worldState)) { GoapNode(worldState.applyAction(action), actionPool, action) } else { null } } } /** * Goap nodes are equal if the amount of differences between the states is 0 */ override fun equals(other: Any?): Boolean { return if (other !is GoapNode) { false } else { this.worldState.countDifferences(other.worldState) == 0 } } /** * Implement hash code so that these can be used in a hash set */ override fun hashCode(): Int { var hash = 7 hash = 31 * hash + g hash = 31 * hash + f hash = 31 * hash + data.hashCode() return hash } } /** * An action is defined primarily by [preconditions], [postConditions] and a name * An action can be applied to a [WorldState] if the given [WorldState] satisifes the actions [preconditions] * The result of applying an action to a [WorldState] is the state of the world will be modified by applying the [postConditions] of the action * When performing state space search, the action also has procedural checks performed to validate if it is not only statically valid but also dynamically valid * This is achieved by running the [isProcedurallyValid] function at plan time (when working out the neighbours of world states) * Actions can be also be determined to be dynamically complete via the [isComplete] function and can be executed in an environment using the [execute] function */ data class GoapAction(val name: String, val preconditions: Map<String, Boolean>, val postConditions: Map<String, Boolean>, val cost: Int, val isProcedurallyValid: ((GoapAgent) -> Boolean), val isComplete: ((GoapAgent) -> Boolean), val execute: ((GoapAgent) -> Unit)) /** * Returns true if an action is valid [forWorldState] */ fun GoapAction.isValid(forWorldState: WorldState) : Boolean { return forWorldState.isActionValid(this) } /** * Define the contract for a planning agent * This can be implemented for any number of environments * Be it games, robotics or any other abstract domain */ interface GoapAgent { val blackboard: Blackboard fun hasPlan(): Boolean fun plan() fun onActionCompleted(fromAction: GoapAction) } /** * A world state is simply a [Map] of facts about the world * Facts are binary and have an associated name * for instance: * HasMoney = false * HasReachedTarget = true */ data class WorldState(val state: Map<String, Boolean>) /** * Returns a [WorldState] by applying [action] to source [WorldState] */ fun WorldState.applyAction(action: GoapAction) : WorldState { return WorldState(this.state.toMutableMap().apply { this.putAll(action.postConditions) }) } /** * Returns the number of differences between the source [WorldState] and the [against] state */ fun WorldState.countDifferences(against: WorldState) : Int { // Fold the against state into an integer representing the differences return against.state.keys.fold(0) { acc, key -> acc + when (val prop = this.state[key]) { null -> 1 else -> when (prop == against.state[key]) { true -> 0 else -> 1 } } } } /** * Creates a copy of the source [WorldState] with the updated [value] for the given [variable] */ fun WorldState.setStateVariable(variable: String, value: Boolean) : WorldState { return WorldState(this.state.toMutableMap().apply { this[variable] = value }) } /** * Returns true if the [action] is valid for the source [WorldState] */ fun WorldState.isActionValid(action: GoapAction) : Boolean { // Fold the actions preconditions into an integer representing the unsatisfied variables // And return true if the unsatisfied variables are 0 else false return action.preconditions.keys.fold(0) { acc, key -> acc + when (val prop = this.state[key]) { null -> 1 else -> { when (prop == action.preconditions[key]) { true -> 0 else -> 1 } } } } == 0 } /** * A blackboard maintains a state of the world and has references to sensors and actuators * An agent has a reference to a blackboard, which can be though of as the agents central system for sensing, remember and actuating in an environment */ class Blackboard(private val world: WorldState) { fun updateState(variable: String, value: Boolean) { this.world.setStateVariable(variable, value) } } /** * Wraps [path] providing state search specific heuristic and cost functions */ class GoapPlanner { fun plan(actionPool: Collection<GoapAction>, fromState: WorldState, toState: WorldState) = Stack<GoapAction>().apply { this.addAll( path( GoapNode(fromState, actionPool, null), GoapNode(toState, actionPool, null), { a, b -> (a as GoapNode).worldState.countDifferences((b as GoapNode).worldState) }, { _, b -> (b as GoapNode).data?.cost ?: 0 } ).mapNotNull { goapNode -> goapNode.data } ) } } /** * Provides a clean API to execute plans that an [agent] has formulated */ class PlanExecutor(private val agent: GoapAgent, private val plan: Stack<GoapAction>) { /** * Returns true if the plan is not empty */ fun hasPlan() = plan.isNotEmpty() /** * Checks if the action on top of the stack is complete * If it is, it pops the stack * It then performs [execute] on the action on top of the stack */ fun execute() { if (this.plan.isNotEmpty()) { if (this.plan.peek().isComplete(this.agent)) { agent.onActionCompleted(this.plan.pop() as GoapAction) } else { this.plan.peek().execute(this.agent) } } } } /** * Set of tests for validating the correctness of the GOAP algorithm */ class GoapTests { @Test fun testSimplePath() { // Make a 2 node bi-directional graph val a = CartesianNode(0, 0, "a") val b = CartesianNode(10, 10, "b") a.addNeighbour(b) b.addNeighbour(a) // Create a cartesian pathfinder val pathfinder = CartesianPathfinder() // Find a path from a -> b val path = pathfinder.findPath(a, b) // Assert that the path is of length 2 // And that it goes a -> b assertTrue { path.size == 2 } assertTrue { path[0] == a } assertTrue { path[1] == b } } @Test fun testComplexPath() { // Make a more complicated bi-directional graph val a = CartesianNode(0, 0, "a") val b = CartesianNode(10, 10, "b") val c = CartesianNode(20, 10, "c") val d = CartesianNode(20, 20, "d") val e = CartesianNode(30, 10, "e") // Doubly link all the nodes a.addNeighbour(b) b.addNeighbour(a) b.addNeighbour(c) b.addNeighbour(d) c.addNeighbour(b) c.addNeighbour(e) d.addNeighbour(b) d.addNeighbour(e) e.addNeighbour(c) e.addNeighbour(d) // Create a cartesian pathfindr val pathfinder = CartesianPathfinder() // Find a path from a -> e val path = pathfinder.findPath(a, e) // Assert that the path is of length 4 // And that the path is a -> b -> c -> e assertTrue { path.size == 4 } assertTrue { path[0] == a } assertTrue { path[1] == b } assertTrue { path[2] == c } assertTrue { path[3] == e } } @Test fun testSimplePlan() { // Create an initial state where HasBread is false val initialState = WorldState(mutableMapOf( Pair("HasBread", false) )) // Create a desired state where HasBread is true val goalState = WorldState(mutableMapOf( Pair("HasBread", true) )) // Create a pool of actions // In this case, there is 1 action "GetBread" // That has no preconditions and a single postcondition where HasBread becomes true val getBreadAction = GoapAction( name = "GetBread", preconditions = emptyMap(), postConditions = mapOf(Pair("HasBread", true)), cost = 5, isProcedurallyValid = { true }, isComplete = { true }, execute = { }) val actionPool = listOf(getBreadAction) // Create a GOAP planner val planner = GoapPlanner() // Find a plan of actions that take us from the initial state to the desired state val plan = planner.plan(actionPool, initialState, goalState) assertTrue { plan.size == 1 } assertTrue { plan.peek() == getBreadAction } } @Test fun testComplexPlan() { // Create an initial state where all variables are false val initialState = WorldState(mutableMapOf()) // Create a desired state where HasToast is true val goalState = WorldState(mutableMapOf( Pair("HasToast", true) )) // Define some more complex actions // With preconditions and postconditions val workForMoneyAction = GoapAction( name = "WorkForMoney", preconditions = emptyMap(), postConditions = mapOf(Pair("HasMoney", true)), cost = 5, isProcedurallyValid = { true }, isComplete = { true }, execute = { }) val getBreadAction = GoapAction( name = "GetBread", preconditions = mapOf(Pair("HasMoney", true)), postConditions = mapOf(Pair("HasBread", true), Pair("HasMoney", false)), cost = 5, isProcedurallyValid = { true }, isComplete = { true }, execute = { }) val makeToastAction = GoapAction( name = "MakeToast", preconditions = mapOf(Pair("HasBread", true)), postConditions = mapOf(Pair("HasToast", true), Pair("HasBread", false)), cost = 5, isProcedurallyValid = { true }, isComplete = { true }, execute = { }) // Create the action pool val actionPool = listOf( workForMoneyAction, getBreadAction, makeToastAction ) // Create the planner val planner = GoapPlanner() // Find a plan to take us from the initial state to the desired state of having toast val plan = planner.plan(actionPool, initialState, goalState) // Assert that the plan is of length 3 and has the correct actions in the correct order assertTrue { plan.size == 3 } assertTrue { plan.pop() == makeToastAction } assertTrue { plan.pop() == getBreadAction } assertTrue { plan.pop() == workForMoneyAction } } @Test fun testWorldStateDiffWhenStatesAreSame() { val a = WorldState(mutableMapOf( Pair("HasBread", true) )) val b = WorldState(mutableMapOf( Pair("HasBread", true) )) assertTrue { a.countDifferences(b) == 0 } } @Test fun testWorldStateDiffWhenStatesAreDifferent() { val a = WorldState(mutableMapOf( Pair("HasBread", true) )) val b = WorldState(mutableMapOf( Pair("HasBread", false) )) assertTrue { a.countDifferences(b) == 1 } } @Test fun testWorldStateDiffForDifferingLengthStateMaps() { val a = WorldState(mutableMapOf( Pair("HasBread", false), Pair("HasMoney", true) )) val b = WorldState(mutableMapOf( Pair("HasBread", true) )) assertTrue { a.countDifferences(b) == 1 } } @Test fun testActionIsNotValidForWorldState() { val forState = WorldState(mutableMapOf( Pair("HasMoney", false) )) val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { }) assertFalse { action.isValid(forState) } } @Test fun testActionIsValidForWorldState() { val forState = WorldState(mutableMapOf( Pair("HasMoney", true) )) val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { }) assertTrue { action.isValid(forState) } } @Test fun testMakeToastIsInvalidForHasBreadFalseWorldState() { val makeToast = GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { }) val forState = WorldState(mutableMapOf( Pair("HasToast", false), Pair("HasBread", false), Pair("HasMoney", true) )) val isValid = makeToast.isValid(forState) assertTrue { !isValid } } @Test fun testApplyAction() { val initialState = WorldState(mutableMapOf( Pair("HasMoney", true) )) val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { }) val expectedWorldState = WorldState(mutableMapOf( Pair("HasMoney", true), Pair("HasBread", true) )) val resultingWorldState = initialState.applyAction(action) assertTrue { resultingWorldState == expectedWorldState } } @Test fun testGoapNodeNeighboursSimple() { val actionPool = listOf( GoapAction("WorkForMoney", emptyMap(), mapOf(Pair("HasMoney", true)), 5, { true }, { true }, { }), GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true), Pair("HasMoney", false)), 5, { true }, { true }, { }), GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { }) ) val forState = WorldState(mutableMapOf( Pair("HasToast", false), Pair("HasBread", false), Pair("HasMoney", false) )) val node = GoapNode(forState, actionPool) val neighbours = node.neighbours() assertTrue { neighbours.size == 1 } } @Test fun testGoapNodeNeighboursComplex() { val actionPool = listOf( GoapAction("WorkForMoney", emptyMap(), mapOf(Pair("HasMoney", true)), 5, { true }, { true }, { }), GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true), Pair("HasMoney", false)), 5, { true }, { true }, { }), GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { }) ) val forState = WorldState(mutableMapOf( Pair("HasToast", false), Pair("HasBread", false), Pair("HasMoney", true) )) val node = GoapNode(forState, actionPool) val neighbours = node.neighbours() assertTrue { neighbours.size == 2 } } } This is quite a lot to analyze, so I will focus only few examples on semantics, best practices and language features. Naming Good: Have a structure well understandable not too long Arguable: Some of your parameter and field names are way too short. abstract class AStarNode<T>(val data: T?, var from: AStarNode<T>? = null, var g: Int = Int.MAX_VALUE, var f: Int = Int.MAX_VALUE) : Comparable<AStarNode<T>> { g, f fun distanceTo(other: CartesianNode) : Int { val dx = abs(this.x - other.x).toDouble() val dy = abs(this.y - other.y).toDouble() return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt() } dx, dy are arguable, because I can understand them through method name. Comments Very many of them - although they are well understandable, I'm a fan when the number of code lines is much bigger than the comment lines. A best practice is to use comments to describe the reason for something not obvious or complex - not the implementation. Good: Very good example of yours, where a comment says WHY and not WHAT: /** * Implemented so these can be used in a priority queue */ override fun compareTo(other: AStarNode<T>): Int Arguable: Many comments could be left out, because ... they are obvious // Begin the search /** * Implement hash code so that these can be used in a hash set */ override fun hashCode(): Int { var hash = 7 hash = 31 * hash + g hash = 31 * hash + f hash = 31 * hash + data.hashCode() return hash } commenting a setter - I don't see any need here for a comment // The g cost of the initial node is by definition 0 from.g = 0 tell me something I could have figured out in 2 seconds looking into the code /** * A cartesian node is equal to another one if the coordinates are the same */ override fun equals(other: Any?): Boolean { return if (other !is CartesianNode) { false } else { this.x == other.x && this.y == other.y } } /** * Returns true if the plan is not empty */ fun hasPlan() = plan.isNotEmpty() If you have to explain in the code how your method works (not necessarily classes), its neither well written, nor has it an understandable name. // For each neighbour of the node calculate it's g cost and update it's from pointer I strongly believe that comments can, and often do, pollute source code. The goal should be to write the code so well, that it explains itself. Language features Good: Almost nothing to complain about. You seem to get along with kotlin. Arguable: Some things are a bit more complex than they could be, or miss some existing helping functionalities: override fun compareTo(other: AStarNode<T>): Int { return when { this.f < other.f -> -1 this.f > other.f -> 1 else -> 0 } } can be override fun compareTo(other: AStarNode<T>): Int = this.f.compareTo(other.f) override fun hashCode(): Int { var hash = 7 hash = 31 * hash + g hash = 31 * hash + f hash = 31 * hash + data.hashCode() return hash } can be override fun hashCode(): Int = HashCodeBuilder(13,17) .append(g) .append(f) .append(data) .toHashCode() Code readability Good: Very small classes Well written to the ability of being testable Good and rare usage of interfaces and inheritance You wrote tests - this is already a big win Arguble: While your classes remain small and beautiful, some of your methods don't follow the same example. Method inside a method: extract it. A Method usually has to do one thing and not create another one - quite unusual implementation I haven't seen so far: fun<T> path(from: AStarNode<T>, to: AStarNode<T>, heuristic: ((AStarNode<T>, AStarNode<T>) -> Int), cost: ((AStarNode<T>, AStarNode<T>) -> Int)) : Stack<AStarNode<T>> { /** * Reconstructs a path, represented as a [Stack] of [AStarNode] * By updating a pointer to a node until the pointer points at null */ fun reconstructPath(from: AStarNode<T>) : Stack<AStarNode<T>> { Very long method: extract the functionality into other functions / classes. The first method in the example has ~100 lines! fun<T> path(...) When the called instance / method has many parameters, it is always better to use named params - like here: class GoapPlanner { fun plan(actionPool: Collection<GoapAction>, fromState: WorldState, toState: WorldState) = Stack<GoapAction>().apply { this.addAll( path( GoapNode(fromState, actionPool, null), GoapNode(toState, actionPool, null), { a, b -> (a as GoapNode).worldState.countDifferences((b as GoapNode).worldState) }, { _, b -> (b as GoapNode).data?.cost ?: 0 } ).mapNotNull { goapNode -> goapNode.data } ) } Tests Good: Short Have comments Initialisation uses with named params Arguable: Much duplication for objects and parameters. Its better to define some fields to be used by other tests, which are not that important, but are needed e.g. for initialisation. Pair("HasBread", true) Pair("HasMoney", true) Weird assertions assertTrue { !isValid } Assertions which will tell nothing valuable when they fail assertTrue { resultingWorldState == expectedWorldState } The error message would be something like "Expected to be true, but was false". This is worthless! You need to debug to find out WHY they are not equal. There are plenty of methods and other libraries which offer so much better solutions, like AssertJ. There you could write assertThat(resultingWorldState).isEqualTo(expectedWorldState) and when it fails, it would tell you what was expected, what is the result and what is the difference - much more information. Or here: // Assert that the plan is of length 3 and has the correct actions in the correct order assertTrue { plan.size == 3 } assertTrue { plan.pop() == makeToastAction } assertTrue { plan.pop() == getBreadAction } assertTrue { plan.pop() == workForMoneyAction } When any of this fails, you don't know which one (besides the exception on line xy), what was the real value, what is the difference? Naming Yes, here we are again. The names of a test are allowed to be longer than usual and should be very explainable. Names like testSimplePath,testComplexPath, testComplexPath, .. tell me nothing! Companies have often their own patterns and standards on test names, but my advice would be to start every test with the word 'should'. Like: should return true, when property xy is bigger than zero. A test should be as simple as it can be and as explainable as it is possible. This includes the name where you can define your case in prose. BTW: You can use backticks to have a function name with spaces in between. Thanks for reading and I hope I could give you some advice which is actually valuable. The END Great feedback, appreciate the time you must have put in to write this up. Whilst I agree with most of your comments, one in particular I am not so sure I agree with: "Method inside a method: extract it" I hear a lot of people saying this, and I honestly do not see the benefit of extracting a method that will have a single call site into a private function. My argument for this is; A) it is not re-used B) by moving it you have just made the method with the single call site more complex to understand (you haven't made it any less complex, you've just moved the logic) Thanks. To your reply: "B) by moving it you have just made the method with the single call site more complex to understand" I don't get it, how an extracted method - which reduces the outside functions size - makes it more complex. It sounds contradicting. If something is so long I need to encapsulate it in multiple functions which only are interesting in this (method) context - It would even make sence to create an own class for it. Small methods - even iff its just for the lines of code - are always easier to read I took a single method as example how to make the code simpler: fun WorldState.isActionValid(action: GoapAction): Boolean { // Fold the actions preconditions into an integer representing the unsatisfied variables // And return true if the unsatisfied variables are 0 else false return action.preconditions.keys.fold(0) { acc, key -> acc + when (val prop = this.state[key]) { null -> 1 else -> { when (prop == action.preconditions[key]) { true -> 0 else -> 1 } } } } == 0 } One thing I noticed is that the comment describes the implementation. I don't like these comments since they are better expressed in code. First step: replace fold with all. fun WorldState.isActionValid(action: GoapAction): Boolean { return action.preconditions.keys.all { key -> when (val prop = this.state[key]) { null -> false else -> { when (prop == action.preconditions[key]) { true -> true else -> false } } } } } I replaced fold with all, since you were effectively using integers to represent a simple boolean decision. By the way, your code had the potential to break unexpectedly when the code would add \$2^{32}\$ times a 1. Curiously, IntelliJ doesn't notice that the innermost when can be made much simpler, so I have to do it manually. fun WorldState.isActionValid(action: GoapAction): Boolean { return action.preconditions.keys.all { key -> when (val prop = this.state[key]) { null -> false else -> prop == action.preconditions[key] } } } Next, I extracted the prop variable and converted the when to an if, since I though that IntelliJ might be able to simplify this condition. But it wasn't helpful at all. fun WorldState.isActionValid(action: GoapAction): Boolean { return action.preconditions.keys.all { key -> val prop = this.state[key] if (prop == null) false else prop == action.preconditions[key] } } Next, I replaced the if-then-else with a simple and. fun WorldState.isActionValid(action: GoapAction): Boolean { return action.preconditions.keys.all { key -> val prop = this.state[key] prop != null && prop == action.preconditions[key] } } One thing that I don't like is the action.preconditions[key], since the lookup is unnecessary: fun WorldState.isActionValid(action: GoapAction): Boolean { return action.preconditions.all { entry -> val prop = this.state[entry.key] prop != null && prop == entry.value } } Now that's much more readable. I ran the unit tests you provided after each step, to ensure that I didn't make any mistakes. I trusted you to have written good tests, I didn't look at them. In the first try of this refactoring, I had inverted one of the conditions and your tests failed. That was good and encouraging. One last minification: fun WorldState.isActionValid(action: GoapAction): Boolean { return action.preconditions.all { state[it.key] ?: false == it.value } } And another: fun WorldState.isActionValid(action: GoapAction): Boolean { return action.preconditions.all { state[it.key] == it.value } } Same for countDifferences: fun WorldState.countDifferences(against: WorldState): Int { return against.state.count { state[it.key] != it.value } } Oh, I cannot resist. If the code is down to a three-liner, a one-liner is possible as well: fun WorldState.countDifferences(against: WorldState) = against.state.count { state[it.key] != it.value } fun WorldState.isActionValid(action: GoapAction) = action.preconditions.all { state[it.key] == it.value } I normally prefer code that is less than 100 columns wide on the screen, but you seem to like longer lines, so it's ok that there are horizontal scrollbars in this particular code example. Great answer, really good points in here There's a bug in distanceTo: /** * Distance to another node is euclidean and worked out using pythagorean theorem */ fun distanceTo(other: CartesianNode): Int { val dx = abs(this.x - other.x).toDouble() val dy = abs(this.y - other.y).toDouble() return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt() } What you compute here is the Manhattan distance, not the Euclidean distance. Calculating sqrt(a * a) doesn't make sense since it is the same as a. Did you mean sqrt(dx * dx + dy * dy)? Kotlin has roundToInt, which lets you combine the round and toInt calls. Here's a unit test for it: @Test fun cartesianDistance() { val node1 = CartesianNode(0, 0, "") val node2 = CartesianNode(3000, 4000, "") assertEquals(5000, node1.distanceTo(node2)) } In general, sqrt(a²) is the same as abs(a). It's only the same as a here because we already did abs() when creating a. Of course, the corrected code for Euclidean distance need not (and should not) call abs() there, because negatives always square to a positive value. It's not a language I know, but is there really no provided hypot() function such as exists in C? Parp! goot spot God how did I do that?
common-pile/stackexchange_filtered
Video Capture Not working With UIImagePickerController I call a function when a button is pressed to present the imagePickerController but it seems that when a video must be taken the app crashes, even when I am running on a device (iPad 2). @IBAction func beginTest() { imagePicker = UIImagePickerController() imagePicker.allowsEditing = false imagePicker.delegate = self imagePicker.sourceType = .Camera imagePicker.mediaTypes = [kUTTypeVideo as String, kUTTypeImage as String] if photoTests.contains(currentTestNum) { imagePicker.cameraCaptureMode = .Photo } else { imagePicker.cameraCaptureMode = .Video //exception thrown here. } presentViewController(imagePicker, animated: true, completion: nil) } You should use UIImagePickerController.availableMediaTypesForSourceType(.Camera) https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerController_Class/#//apple_ref/occ/clm/UIImagePickerController/availableMediaTypesForSourceType: You should use kUTTypeMovie, not video. Some iOS devices support video recording. Use this method, along with the isSourceTypeAvailable: method, to determine if video recording is available on a device. The availability of video recording is indicated by the presence of the kUTTypeMovie media type for the UIImagePickerControllerSourceTypeCamera source type.
common-pile/stackexchange_filtered
Graph isomorphism between two functional graph. From this, I could understand what a functional graph is. But how can we find a function $f$ such that f is an isomorphism between two fuctional graph, $H$ and $G$ given by fuctions $h(x)$ and $g(x)$ respectively. To avoid deciding upon whether those graphs are isomorphic or not let us assume that both graphs are cycles of length $n$. And as far as I can think about is that two cycles of same length must be isomorphic. I don't even know that it makes sense to talk about an isomorphism between functional graphs, or about a functional graph being a cycle of length $n$. What exactly are you trying to ask here?
common-pile/stackexchange_filtered
だろう in question context? This is sentence: 「“見る”か。お前はいったい、どのような世界を“見て”いるのだろうな」 I'm not sure if this is really a question, but words like いったい and どのよう suggest that it probably is. So if this is really a question, then how should I inerpret だろう at the end, because usually as far as I know it represents information about which speaker thinks its almost certainly is true. But here, it looks like question is in form of something like "In which way did you see world?", and I don't understand how だろう fits here. だろう after an interrogative (いつ, 何, なぜ, ...) is something that may be called a "I-wonder marker". While ~ですか forms a question addressed to someone else, ~だろう forms a question addressed to yourself. お前はいったい、どのような世界を“見て”いるのだろうな。 I wonder what kind of world you are "seeing". I wonder what the world you are "seeing" is like. どのように is "in what way" or "how", but どのような is "what kind of" or "like what". More simpler examples: ここはどこだろう? (I wonder,) Where am I? ここはどこですか? (Please tell me,) Where am I? 誰だろう? (I wonder,) Who is it?
common-pile/stackexchange_filtered
Is a specific product function orthogonal to all harmonic functions Suppose $\Omega=[-1,1]^3$. Let $f:[-1,1]\to \mathbb R$ and $g:[-1,1]^2\to \mathbb R$ be smooth functions and suppose that given any harmonic function on $\Omega$ (i.e. $\Delta u =0$ on $\Omega$), with $u \in L^2(\Omega)$, there holds: $$ \int_{\Omega} u(x^1,x^2,x^2) f(x^1)g(x^2,x^3)\,dx=0.$$ Does it follow that $f$ and $g$ are identically zero? If $h=\Delta w$ with $w$ smooth and compactly supported, then $\int uh=\int u\Delta w=\int (\Delta u) w=0$ for every harmonic function $u$. Its true that $\Delta w$ is orthogonal to harmonic functions for all $w \in H^2_0(\Omega)$ but I don’t see how that is relevant at all. The function at hand, may not be writable as $\Delta w$ with $w \in H^2_0(\Omega)$. Yes, true. This gives only a counteraxample with a function which is the sum of 2 in the above form. What happens in 2 variables? Looks like it is so (though the conclusion is rather that either $f$, or $g$ is identically $0$ (one of the two is enough). Let $v$ be the solution of the problem $\Delta v=fg$ in $\Omega$, $v|_{\partial\Omega}=0$. Then, by Green's formula, the integral in question is (up to minus) $\int_{\partial\Omega}u\frac{\partial v}{\partial n}$. However, the boundary values of $u$ can be anything sufficiently nice we want, so this may hold only if $\frac{\partial v}{\partial n}$ is identically zero on the boundary, in which case $v$ can be extended by $0$ outside $\Omega$ and its Laplacian (in the sense of generalized functions, at least) is still $fg\chi_\Omega$. Now it suffices to show that the Laplacian of a compactly supported function cannot be a product like above unless it is zero. Indeed, its Fourier transform would then be the product $F(z_1)G(z_2,z_3)$ of two entire functions and it should vanish whenever $z_1^2+z_2^2+z_3^2=0$. If there exist $a,b\in\mathbb C$ with $a^2+b^2=-c^2\ne 0$ such that $G(a,b)\ne 0$, then the function $F(cz)G(az,bz)$ of one complex variable vanishes identically and, since the second factor is not zero for $z=1$, we must have $F\equiv 0$, i.e., $f\equiv 0$. Otherwise $G(z_2,z_3)$ is zero on a dense set in $\mathbb C^2$, so it is identically $0$ and so is $g$.
common-pile/stackexchange_filtered
Is there a garbage collection in Kotlin? Java has a Garbage Collection. But you should take precautions to avoid the memory leak. Does that apply to kotlin? Is there a memory leak in Kotlin? Is there a Garbage Collection at Kotlin? Short Answer: Yes (Not so) Long explanation: kotlin actually runs on JVM as well as Java. So java does not have any garbage collection. Java is just a programming language. The garbage collection part comes from Java Virtual Machine. Kotlin being an revolutionary language still depends on JVM. Actually any language depending on the JVM automatically have Garbage Collection. Are the things that we avoid from memory leak in java valid for kotlin? or does kotlin automatically regulate them? Most of the Kotlin calls translate to traditional, valid Java calls. I say "most" because Kotlin compiler can take some shortcuts that are valid for the JVM, but not for the Java language as it is. That way, it is safe to assume that you need to be as careful with Kotlin as you should be when using plain-old Java. @HasanKucuk There are instances where Kotlin will avoid holding references to the outer class, see https://proandroiddev.com/how-kotlin-helps-you-avoid-memory-leaks-e2680cf6e71e
common-pile/stackexchange_filtered
Puppet module not run on agents while this has been defined in Hiera on the Puppetmaster Once I've installed Puppet, Foreman, Hiera and Facter, how do I get them all to work with one another? The Foreman GUI is operating properly and can be viewed using a browser. Hiera is installed, and by guides I read on the internet it seems like it's configured correctly and Facter also works properly, but agents are not getting modules from the Puppet server. I've added a very simple MOTD module and configured it to run in common.yaml. But the module is not installed on agent machines and no error is displayed. Running puppet agent -t on the server and on clients works: [root@puppet production]# puppet agent -t Info: Retrieving pluginfacts Info: Retrieving plugin Info: Loading facts Info: Caching catalog for puppet.nj.peer39.com Info: Applying configuration version '1425802774' Notice: Finished catalog run in 0.05 seconds [root@puppet production]# hiera.yaml looks like that: [root@puppet production]# cat /etc/puppet/hiera.yaml :backends: - yaml :yaml: :datadir: '/etc/puppet/hieradata/%{::environment}' :hierarchy: - fqdns/%{::fqdn} - roles/%{::role} - domains/%{::domain} - common environment.conf looks like that: [root@puppet production]# pwd /etc/puppet/environments/production [root@puppet production]# cat environment.conf modulepath = modules manifest = /etc/puppet/environments/production/manifests/ [root@puppet production]# I also tried loading the module through a fqdn.yaml file but to no avail and no error is displayed. /etc/puppet/puppet.conf looks like that: [master] autosign = $confdir/autosign.conf { mode = 664 } reports = foreman external_nodes = /etc/puppet/node.rb node_terminus = exec ca = true ssldir = /var/lib/puppet/ssl certname = puppet.company.com strict_variables = false environmentpath = $confdir/environments Edit #1: My common.yaml looks like that: classes: - motd When I said fqdn.yaml I meant: [root@puppet fqdns]# pwd /etc/puppet/hieradata/production/fqdns [root@puppet fqdns]# ll total 8 -rw-r--r-- 1 root root 23 Mar 11 09:26 pnd01.company.yaml -rw-r--r-- 1 root root 17 Mar 12 08:24 puppet.company.com.yaml [root@puppet fqdns]# That's my site.pp, which is located at /etc/puppet/environments/production/manifests: [root@puppet manifests]# cat site.pp hiera_include("classes", []) Package { allow_virtual => false, } node default { } On the puppetmaster, how does the log look for when it compiles the catalog? Also, how does common.yaml look? What do you mean by "loading the module through a [yaml]"? Please note that literal fqdn.yaml is not in your hierarchy - fqdns/<agent-fqdn>.yaml is. Is there a site.pp or any .pp in your manifests directory? Is Puppet configured to use the foreman as an ENC? If not, what is foreman doing in your setup anyway? Thanks for your replies, I've edited my question, please check Edit #1. @FelixFrank, what do you mean as an ENC please? More info on ENCs. This looks all right. Try some Hiera debugging first. Also use notify resources to debug the manifest. The Puppetmaster needs to be restarted if the hiera.yaml has been changed The format of the hiera files is important, i.e. two spaces instead of null and --- common.yaml --- classes: - motd instead of classes: - motd If Puppet Environments are enabled the datadir should be configured as follows: /etc/puppet/hiera.yaml :yaml: :datadir: "/etc/puppet/environments/%{::environment}/hieradata" Every environment should contain a hieradata directory and it should include the common.yaml. If no environments are used the hiera.yaml looks as follows: :yaml: :datadir: "/etc/puppet/hieradata" move the common.yaml to this directory and restart the puppetmaster Defining hiera_include('classes') in the site.pp instead of hiera_include("classes", []) is sufficient That's the way it is written, SF's [ ] code block removed the spaces but the file looks just like you showed.
common-pile/stackexchange_filtered
Toolbar problems when scroll disabled I have a situation where disabling scroll on mobile when my cart is turned on causes really weird graphical issue with android firefox toolbar. Cart is a fixed container taking an entire screen. When toolbar is shown it just stays there and freezes (probably because i just turned off scrolling) but when its hidden and I'll turn on my cart white bar shows up in place of the toolbar picture related, as you can see it's obscuring my buttons as well. I found workaround for that where I make custom --vh unit based on actual screen height. let vh = window.innerHeight * 0.01; document.documentElement.style.setProperty('--vh', `${vh}px`); I disable scroll by ading this on body overflow-y:hidden; I was also trying to disable it with different tricks like setting position to fixed or relative but it causes the same bug. This only happens on firefox android. Is there a way I can turn off scrolling without causing this, or maybe someone knows how to fix displaying 100vh height on mobile with pure css? try min-height: -webkit-fill-available; instead height: 100vh I'm sorry, I should have mention that I already tried -webkit-fill-available before and dosn't help, actually quite the opposite, turns off my overflow in cart completely. I think it's supposed to help with safari not firefox.
common-pile/stackexchange_filtered
Proving a subspace under a linear transformation by the closure of standard addition and scalar multiplication $T(x,y,z)= (3x-2y, -2x+3y, 5z)$ be a linear transformation from $\mathbb{R}^3$ to $\mathbb{R}^3$ Show that $A= \{(u,v,z) \in \mathbb{R}^3~|~(u,v,w)=T(x,y,z)\}$ for some $(x,y,z)$ in $\mathbb{R}^3$ is a subspace of $\mathbb{R}^3$ by proving that it is closed under standard addition and scalar multiplication. I think you also need to observe that the subspace contains the zero vector. But all this is a bit excessive: the image $R(T)$ of ANY linear operator is a subspace. Remarks The whole exercise is equivalent to prove that the image $A:=\operatorname{im}(T)$ of a linear operator $T:V\rightarrow W$ is a linear subspace of $W$. Following the remark by @LinearAlgebra, I will use $$A=\{(u,v,w)\in\mathbb R^3~|~(u,v,w)=T(x,y,z)\} $$ for some $(x,y,z)\in\mathbb R^3$. On addition Let $(u_1,v_1,w_1), (u_2,v_2,w_2)\in A$, with $(u_1,v_1,w_1)=T(x_1,y_1,z_1)$ and $(u_2,v_2,w_2)=T(x_2,y_2,z_2)$. Then $$(u,v,w):=(u_1,v_1,w_1)+(u_2,v_2,w_2)=T(x_1,y_1,z_1)+T(x_2,y_2,z_2)=\text{linearity of }T= T(x_1+x_2,y_1+y_2,z_1+z_2)\in A. $$ On scalar multiplication Let $(u_1,v_1,w_1)\in A$, with with $(u_1,v_1,w_1)=T(x_1,y_1,z_1)$ and $\lambda\in\mathbb R$. Then $$\lambda(u_1,v_1,w_1)=\lambda T(x_1,y_1,z_1)=\text{linearity of }T=T(\lambda x_1,\lambda y_1,\lambda z_1)\in A.$$ You are welcome. The above is a general property, independent of the linear map. Feel free to flag it if it is useful. how would be find the basis of A? check if $T$ is injective and/or surjective etc...before searching for a basis of $A$
common-pile/stackexchange_filtered
Sorting Ms Access tables records and VB.net i've implemented a system on vb.net 2010 having its database on Ms Access 2010 (.accdb). i have to read records from the tables to a combo box by binding its datasource to the tables directly. the problem is that the data in the combo box is not sorted since in the database itself the records are not sorted. how can i achieve the sorting? Thanks Use the ORDER BY clause of the SELECT statement: ORDER BY Clause where can i access this? given that i did not use SQL to read data from the MS Access tables. i used data binding source :S Relational database tables are inherently unsorted. If you are binding to the tables directly you should not expect the data to be sorted. This applies not only to Access, but also Oracle, Postgres, MySQL, SQLite, etc. If you want the data sorted, a SQL query will be the most efficient way to do it by far. yeah, i know but i thought that there was a solution apart from using SQL query. my bad :( anyways, thnx ;)
common-pile/stackexchange_filtered
Positive interaction term with one negative component? Say I have an augmented growth regression, where my Y is GDP growth, and my Xs are the classical MRW variables, + international aid + corruption + the interaction term between the two. Basically, I'm interested in seeing if lower corruption increases the effectiveness of international aid, which means I'd like to see a positive sign on my interaction term. However, I also think I should see a negative sign on corruption, as the higher corruption, the lower should growth be. Now, my questions: Is this possible as I describe it? Can I see a negative component but a positive interaction term? In which case, how should I interpret it? Or is there a reason the coefficient on corruption should be positive, and still indicate that higher "institutional quality" has a positive impact on growth by itself and also in interaction with aid? Ignore the other variables. Let $g$ be growth, $C$ corruption and $A$ aid. You look at $$g = \alpha C + \beta A + \gamma A\cdot C$$ You ask, "does lower corruption increases the effectiveness of foreign aid?" For this you have indeed to examine the cross-partial derivative $$\frac {\partial g}{\partial A\partial C} = \gamma$$ This is "how growth is affected at the margin by Aid, if corruption changes"... So if lower corruption increases the effectiveness of Aid, $\gamma$ should be negative, not positive... ...if your corruption index is mapped as "the higher the value of $C$ the higher the corruption". If your "corruption index" is mapped in reverse (and so in reality it measures "non-corruption"), the anticipated sign reverses also.
common-pile/stackexchange_filtered
c++:Hackerank:Error in taking input This is a part of my question.I tried many times but couldn't get the answer Problem Statement You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics. Note Suppose a, b, and c are three different people, then (a,b) and (b,c) are counted as two different teams. Input Format The first line contains two integers, N and M, separated by a single space, where N represents the number of people, and M represents the number of topics. N lines follow. Each line contains a binary string of length M. If the ith line's jth character is 1, then the ith person knows the jth topic; otherwise, he doesn't know the topic. Constraints 2≤N≤500 1≤M≤500 Output Format On the first line, print the maximum number of topics a 2-person team can know. On the second line, print the number of 2-person teams that can know the maximum number of topics. Sample Input 4 5 10101 11100 11010 00101 Sample Output 5 2 Explanation (1, 3) and (3, 4) know all the 5 topics. So the maximal topics a 2-person team knows is 5, and only 2 teams can achieve this. this is a a part of my work.Any clue how can i get this to work #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, m, max = 0, max1 = 0, count = 0; cin >> n >> m; //for input of N and M int a[n][m]; for (int i = 0; i<n; i++) //for input of N integers of digit size M for (int j = 0; j<m; j + >> cin >> a[i][j]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { max = 0; for (int k = 0; k<m; k++) { if (a[i][k] == 1 || a[j][k] == 1) max++; cout << k; if (k = m - 1 && max>max1) max1 = max; if (k == m - 1 && max == max1) count++;; } } } cout << max1 << endl << count; return 0; } I think the way of taking my input logic is wrong.could you please help me out.I am stuck in this question from 5 days. PLease only help me on how should i take input and how to read the digit of integer. https://stackoverflow.com/questions/737240/c-c-array-size-at-run-time-w-o-dynamic-allocation-is-allowed You cannot do this cin>>n>>m;, then int a[n][m];, the array size must be know at compile time, not run time. then how should i take input in this question? You can make a std::vector<std::vector<int>>. but sir how will i read digit of integer specifically and the array size issue of decalaring its size at compile time is valid in c99 C99 is not C++. More fun, I believe that trick is only optional in more recent C standards. if (k = m - 1 && max>max1) max1 = max; you sure you don't want k == m - 1? Your method of input is wrong. According to your method, the input will have to be given like this (with spaces between individual numbers): 1 0 1 0 1 1 1 1 0 0 1 1 0 1 0 0 0 1 0 1 Only then it makes sense to create a matrix. But since the format in the question does not contain any space between a number in the same row, thus this method will fail. Taking into consideration the test case, you might be tempted to store the 'N' numbers in a single dimensional integer array, but keep in mind the constraints ('M' can be as big as 500 and int or even unsigned long long int data type cannot store such a big number). Don't think of 10101 as the first input. It is a stream. cin >>char will read exactly one character from that stream, skipping and discarding all of the usual whitespace characters. Repeated cin >> char will continue to extract characters one at a time. Wrap while (std::cin >> temp) cout <<temp; in a little quickie program and watch what happens as you type. @user4581301 yes, you were right. I did not know this. But, the way Hammad has taken input, it's wrong, isn't it? Oh yeah, it's wrong. The whole line, or as much as the int can eat without causing the conversion to fail, will be read in as one integer. Don't have a compiler with me so there's probably a syntax boner or two in there, but the logic walks through on paper. Builds the storage: std::cin >> n >> m; //for input of N and M std::vector<std::vector<bool>>list(n,std::vector<bool>(m, false)); Loads the storage: char temp; for (int i = 0; i < n; i++) //for input of N integers of digit size M { for (int j = 0; j < m; j++) { std::cin >> temp; if (temp == 1) { list[i][j] = true; } } } Runs the algorithm for (int a = 0; a < n; a++) { for (int b = a+1; b < n; b++) { int knowcount = 0; for (int j = 0; j < m; j++) { if (list[a][j] | list[b][j]) { knowcount ++; } } if (knowcount > max) { groupcount = 1; max = know; } else if(knowcount == max) { groupcount ++; } } }
common-pile/stackexchange_filtered
Do I have to report empty bank accounts on form 8938 "Statement of Specified Foreign Financial Assets" I have empty bank accounts that I no longer use. It's unclear to me if I should report those accounts on form 8938. I don't think an empty bank account is an asset, provided it is literally empty. According to IRS.gov, you have to report empty foreign bank accounts on Form 8938 (mirror) “Statement of Specified Foreign Financial Assets". From https://www.irs.gov/businesses/corporations/basic-questions-and-answers-on-form-8938#ReportQ2 (mirror): Q2. If I have to file Form 8938, am I required to report all of my specified foreign financial assets regardless of whether the assets have a de miminis maximum value during the tax year? If you meet the applicable reporting threshold, you must report all of your specified foreign financial assets, including the specified foreign financial assets that have a de minimis maximum value during the tax year. For exceptions to reporting, see Exceptions to Reporting on page 6 of the instructions for Form 8938 (mirror). For tax purposes, since pretty much all forms require reporting in rounded whole dollars, I think "de minimis value" may refer to $0.00 < X < $0.50 (exclusive). Or do you have a definition? (your link discusses treatment of de minimis, but does not define it except in the context of bond discount) I'll first note that I'm not a US citizen or resident, so others may be better qualified to answer. However, having found a copy of the form, part VI, question 4 asks for the "Maximum value of asset during tax year (check box that applies)" and the first box is labelled "$0–$50,000", suggesting to me that empty accounts should be included.
common-pile/stackexchange_filtered
How do I return a filename as an ANT property? I have a property file that is name app_id-*.app (where * = any application name that can be created) that I need to pass as an arg to an ANT exec call. I was wondering if there is a way to return the full filename of the filename based on the wildcard as a property that I can then pass to another target. Could you clarify the question some more? Do you need to read a directory, and then input the file name, or is it a build dependent file name that you can enter in a properties file or on the command line, etc? Each application is created in a directory and consists of 4 files, each named differently. I need to return one of the filenames to pass to the exec call, which is one of the four files, and always starts with app_id_*. I ended up creating a fileset and passing that to a property which worked great: <path id="app-id-file"> <fileset dir="@{path}"> <include name="app_id_*.app"/> </fileset> </path> <property name="application.id.file" refid="app-id-file"/> <echo message="Application ID filename is ${application.id.file}" />
common-pile/stackexchange_filtered
Which finger on right hand to use to play G note on piano in Twinkle Twinkle Little Star? When my daughter learned piano the first time one year ago, the teacher let us use this fingering: CC GG AA G FF EE DD C 11 55 55 5 44 33 22 1 We stop learning for a while and we start again. However, this new teacher let us use this fingering: CC GG AA G FF EE DD C 11 44 55 4 44 33 22 1 We are quite confused. Fingering is rarely an absolute question of right or wrong. How old is your daughter? Both are acceptable, so in this case, I suggest using the fingering recommended by the current teacher. However, if making the change is proving difficult, then have a parent-teacher conversation to acknowledge the difficulty and ask to use the old fingering for this song. A good teacher will be flexible. (And the best teachers would already have recognized the confusion and allowed the student to play in the familiar way or gauged how to surmount any difficulty in switching.) The differences between the two fingerings amount to the following: The 55 55 5 fingering ("repeated 5s") requires two shifts of the hand (from G to A, then back to G); whereas, the 11 44 55 4 44 fingering ("repeated 4s") requires "opening" the hand (from C [11] to G [44] and only one shift (from G [4] to F [44]). Also, the two hand-shifts in the "repeated 5s" fingering happen close together in the music, while the adjustments in the "repeated 4s" fingering are more separated from each other. In the "repeated 4s" fingering, the hand movements better match the phrasing of the music, the hand-shift coming at a break between phrases. Twink - le, twink - le, lit - tle star. 1 1 4 4 5 5 4 (hand "opens") (hand shift) 1 1 5 5 5 5 5 (hand shift)(hand shift) How I won - der what you are. 4 4 3 3 2 2 1 4 4 3 3 2 2 1 An advantage to the "repeated 5s" fingering is that the hand never has to leave "five-finger position", a common starting point for learning in which each finger is on consecutive notes — C D E F G. I would prefer the new fingering because it introduces the idea of changing hand position to prepare for what is coming. @Peter I'm with you, for the same reason. And it's better fingering practice anyway, so good to instill proper fingering early. How about 5 4 for G G, then 3 4 for F F ? This way the hand moves along the keys' changing direction? @GrandAdagio I like it. Very clever. The hand movement matching the direction of the music is a great benefit. The only reason I can think of not to use it with a beginner is that it can be confusing to play the same note with different fingers, but that would depend on the particular learner. Thank you Aaron. I'm flattered :) Happy New Year! In the early stages of learning piano, the hand(s) will be anchored over just 5 notes - and tunes will accommodate this. That makes it easy to play tunes - no need to look at the keys. But when the tune strays beyond the 5 notes, something has to change. One option is to stretch and allow the pinky to play ^5 and ^6. The whole hand could actually slide a little to the right for ^6, then back to the 'safe' position for the rest. Another option is to stretch the whole hand, as new teacher advocates, so ^5 is played by finger 4, putting pinky over ^6. Another good reason this works now is probably tat your daughter has grown somewhat in the intervening year, and that stretch isn't really a stretch. It also prepares her for moving out of that 'safe' 5 fingers for 5 notes syndrome. With fingering of anything, at any level,I advocate the student trying out all available options, not just blindly following teacher's choice, as there may be an even better one that hasn't been used so far. It will depend on the piece, and the student's physical hand structure, as we all differ . A really good teacher will be able to justify and explain why s/he recommends certain things - ask the question. The primary source of confusion is that you think there's a "correct" way. There's none. It's like picking a color for an apple in a picture: should it be green? Red? Yellow? Sticking to one version when learning might be a good idea because reasonable fingering helps muscle memory. Learning to switch fingerings might also be a good idea because that helps improvise and read a vista (citation required). At the level of playing "Twinkle Twinkle Little Star" - none of the above really matters. It’s perhaps more like “What kind of shoes should my daughter wear — pull-on, velcro, buckle, lace-up?” There’s no single absolute right answer, but it’s not just an arbitrary choice like the apple colour either — depending on the child’s age, competence, and other so on, some answers may well be better than others for this specific stage. @PLL I can imagine some really bad fingerings, certainly. But, like in case of the shoes, it's not something to overthink. There's a lot of variables, there will be much more tunes than just "Twinkle, twinkle...". I think this is something that is hard to get wrong :) @PLL: To put it another way: you will not get a better fingering, specific to your child, by asking for it on the Internet. Same with shoes: we don't know the context, we don't know the shoes, we don't know the child's manual skills, we don't know her motivation. If your kindergarten teacher says that lace-up is fine, then it's probably fine, and certainly not something to be confused about.
common-pile/stackexchange_filtered
How to convert Map<int, Map<int, Map<int, Map<int, int>>>> to json So I have this data : { 2021: { 01: { 4: {2: 3}, 5: {2: 3}, 6: {2: 3}, ... }, }, 2022: { 01: { 4: {2: 3}, 5: {2: 3}, 6: {2: 3}, ... }, }, } which is a Map<int, Map<int, Map<int, Map<int, int>>>> The purpose of this structure is to hold information abount every day of a years calendar week like this: { year: { calendarweek: { day: {2 out of 3}, day: {2 out of 3}, ... }, }, year: { calendarweek: { day: {2 out of 3}, day: {2 out of 3}, ... }, }, } Now I want to store this information as Json but the conversion is giving me a REALLY hard time. So how would I de- and encode this data from/to json? this is not a valid JSON - what do you want to do with such poor json? I know that this is not a JSON, its a Map<int, Map<int, Map<int, Map<int, int>>>>. My question was how I would convert this structure to JSON. so what is the second snippet you posted? the one with day: {2 out of 3}? is it a final string you want to get? the second snippet was just for expanation what the numbers stand for. the day: {2 out of 3} just meant that the key in this case is a 2 and the value a 3. Sorry thats a bit misleading. Actually, I am just thinking maybe I should create an entire new Class for this information. Indeed to encode your data to Json format, the keys should be String objects otherwise you get error messages, my example: import 'dart:convert'; const data = { '2021': { '01': { '4': {'2': 3}, '5': {'2': 3}, '6': {'2': 3}, }, }, '2022': { '01': { '4': {'2': 3}, '5': {'2': 3}, '6': {'2': 3}, }, }, }; void main(List<String> args) { var myData = jsonEncode(data); // var myData = jsonEncode({'2':3}); print(myData.runtimeType); print(myData); } Result: String {"2021":{"01":{"4":{"2":3},"5":{"2":3},"6":{"2":3}}},"2022":{"01":{"4":{"2":3},"5":{"2":3},"6":{"2":3}}}}
common-pile/stackexchange_filtered
Text collage (word cloud) in LaTeX? There are some automatic method (package, class, macro) in LaTeX to do a text collage similar to that showed in the image? If not, is would be possible without too much manual work?. The background, the font and the shape of the collage does not matter (is enough a rentangular shape). I don't think someone has implemented a word cloud engine in TeX, yet. Maybe you have more luck searching for Lua libraries which could be leveraged. Here's a blog post which uses a Java word cloud engine which can be hooked into TeX: Word clouds in ConTeXt For anyone trying to implement this, here's the algorithm wordle uses: Here's how Wordle actually works sort of related (possible starting point): Placing text at random positions on the screen in beamer. I also added word clouds to the title- hope that's ok :) Possible duplicates: Wordle-like word clouds, Word clouds in LaTeX The right words were finally "word clouds", so the question is really a duplicate. But I asked specifically for a LaTeX solution, that is not still answered in Marco's links. Although only related, for me only the cmhughes's link is in the right direction.
common-pile/stackexchange_filtered
Modify menus shown to Portal users Odoo/Openerp What I want to do is this: When a new user is given access to the Portal, I want her only to be able to see a single Sales menu with a submenu Sales/Customers and nothing else. I was able to do that by adding the menu to the Portal group, but I need to hide the other menus (Website,Mail,Projects). I removed all the other views from Portal group and made sure that my customer does not belong to any other group than Portal but the menus are still there. From what I can understand the menus are shown only to certain groups of users. My user only belongs to the Portal group these menus are not referenced there. I only have my Sales/Customer there How can I remove them? Please edit your question and add: 1. Your code/your attempts 2. Your input, current output and expected output @Odedra this security problem, not sure for why you asking for code. Out-of-box odoo is designed to show all those menu as portal menu, so what you want todo here is create new group with portal check-box true and assigned all menu you wnat him to see and assign needed security. Designing this group be bit lazy as you will have todo lot of trails. Bests
common-pile/stackexchange_filtered
I Can't call methods in kotlin I am new to kotlin and just starting to learn about classes and methods but in the code below I can't call the makeReddit() method: class Site( address: String, foundationYear: Int) { var address: String = address var foundationYear: Int = foundationYear fun makeReddit(address: String , foundationYear: Int) { this.address = "reddit.com" this.foundationYear = 2005 } } fun main() { val site : Site = makeReddit() } And I get this error : Kotlin: Unresolved reference: makeReddit You have to initialize the Site first and call the method like site.makeReddit("reddit.com", 2005), but it looks like that method only sets the variables and doesn't do anything else, so you could just use a data class Site(address: String, foundationYear: Int) and initialize is via constructor: val site = Site("reddit.com", 2005). Depends on what you are trying to do with that site and year. I strongly suggest you go through some Kotlin tutorials (and maybe even java/oop tutorials). You can start with these tutorials First you need to grasp the concept on how kotlin/oop works. Otherwise you'll be asking so many questions on StackOverflow on why your code doesn't compile. This was a Task on JetBrains Academy Kotlin Course and the task was just saying There is this class: class Site(val address: String, val foundationYear: Int) Implement the makeReddit() function that returns a Site with the reddit.com address and the foundation year of 2005. Your makeReddit() method doesn't return anything at the moment... You would have to declare it fun makeReddit(address: String , foundationYear: Int) : Site { ... } and in the body really return a Site... That "JetBrains Academy Kotlin Course" might be too advanced for your right now. First you need to understand what is a class, what is a function and what it can do. For instance in your case the task is to add a function which should returns something, but you are not returning anything, which might indicate that you are not familiar with return concept. JetBrains Academy course is just for beginners it takes you from the early start as it teaches you about the Units of information and all of these fundamentals ..... what's above is what happens after 24 hours non-sleeping day :D But If you really recommend a certain course what would you recommend? In Kotlin, functions do not necessary need to be declared in some class. A function declared outside of a class is called a top-level function. In this task, you can declare makeReddit as a top-level function beside the Site class: class Site(val address: String, val foundationYear: Int) { // ... } fun makeReddit(): Site { // create and return "reddit" site } Then you'll be able to call it just as makeReddit() from other places, for example from main function: fun main() { val reddit: Site = makeReddit() println(reddit.address) } This was a Task on JetBrains Academy Kotlin Course and the task was just saying There is this class: class Site(val address: String, val foundationYear: Int). Implement the makeReddit() function that returns a Site with the reddit.com address and the foundation year of 2005. (your comment) This looks like a task targeting the use of a companion object, because you need a method makeReddit() that you can use without an instance of a Site, like Site.makeReddit(). Here's how you could do it: class Site(val address: String, val foundationYear: Int) { var url: String = address var founded: Int = foundationYear // provide a singleton that creates an instance companion object SiteFactory { // the fun to be used without an instance of Site fun makeReddit() : Site { // return the (fix) values of reddit.com return Site("reddit.com", 2005) } } // provide a String representation override fun toString(): String { return "$url founded in $founded" } } Then you can create instances of a Site in (at least) two different ways: fun main() { // create the reddit site instance directly from Site val reddit = Site.makeReddit() // create an instance with different values via constructor val random = Site("ran.dom", 2008) // and print both of them println("reddit: $reddit") println("random: $random") } That fun main() will output reddit: reddit.com founded in 2005 random: ran.dom founded in 2008
common-pile/stackexchange_filtered
Unable to get whole http message I am using curl for sending a POST HTTP message to my server. At Server side I am opening a socket and reading the data by using following code recv(socket_Fd, (void *)ucBuffer, (size_t)((sizeof(ucBuffer) - 1)), NULL); I am able to get the header of the POST message but in message body I am getting only one line , rest are missing. Data I am receiving at server end. POST /info HTTP/1.1 User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/<IP_ADDRESS> libidn/1.23 librtmp/2.3 Host: <IP_ADDRESS>:10000 Accept: */* Content-Length: 356 Content-Type: application/x-www-form-urlencoded Bhupesh Bhargava In message header it's showing right content length but message body is missing. Any idea where I am doing wrong. curl command I am using curl --data-binary @/home/bhupesh/data_save2 http://<IP_ADDRESS>:10000/info The only working solution till now I got is curl --data-binary "$(cat /home/bhupesh/data_save2)" http://<IP_ADDRESS>:10000/info but still I am not clear about it The curl command seems to be OK and if we go by the documentation here, the following should be true. Data is posted in a similar manner as --data-ascii does, except that newlines are preserved and conversions are never done. So, this leaves us with the fact that there should be a problem in your Server implementation. It is not quite sure how you are getting the received stuff at the server, but you should be careful about sequencing what you receive by yourself. Here is an example how you could do that.
common-pile/stackexchange_filtered
Why do I need secret on delegated az ad app? what can go wrong if we don’t have secrets/cert on Azure Ad app registration with only delegated permissions? Depends on what you want to do. authorized access between resources Do use service principal with certificate if you want to access one cloud resource from another: https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal Access to resources is restricted by the roles assigned to the service principal, giving you control over which resources can be accessed and at which level. For security reasons, it's always recommended to use service principals with automated tools rather than allowing them to log in with a user identity. Most notably, the service principal, can't be used with credential theft using social engineering and much more. delegated permissions That's the way to go if we're talking about user interaction with services that call one another. You only need a secret/certificate if you need to prove your app's identity when acquiring tokens. If you have a desktop app, mobile app, or other kind of "public client" that runs on a user's device, these cannot prove their identity as they cannot keep a secret. So for these you would never register a secret/certificate. If you have e.g. a Web API that is a "confidential client", you only need a secret/certificate if that API needs to call other APIs. Otherwise those don't need it. A "traditional" back-end Web app would usually need a secret/certificate to do authorization code flow to authenticate the user. So it really depends on the type of your app.
common-pile/stackexchange_filtered
Circular redirect issue with Google OAuth2 and PassportJS in a NodeJS project In my NodeJS project, I'm trying to protect access to certain controllers (since all the routes under the controller would also be protected). When using my front-end, I want to ensure users are from MYDOMAIN.com by having them authenticate using their Google Workspace account. However, I also want to support stateless API calls using access tokens (e.g. using Postman). I've managed to get my BearerStrategy working with PassportJS. But, when a user attempts to access my protected URL through the web, I end up in a circular loop where the user keeps getting redirected back to "/" after completing the authentication. I THINK (though this is my first real NodeJS project - the one I'm learning all these new building blocks with) it's because my express-session handling isn't being done right and it's deleting my sessions which I was trying to use to keep my redirectTo URL. I tried come ChatGPT help - that got my BearerStrategy working. But since I also want to controller to support the GoogleStrategy with Session support, it seems to delete the session when it goes there. My app.js (simplified to just a non-protected, protected, and my auth routes): //app.js const express = require("express"); const app = express(); const passport = require("passport"); const expressUtils = require("./expressUtils"); // Used to parse JSON bodies expressUtils.setMiddlewares(app); // Add View Template Engine - EJS expressUtils.setViewEngine(app); // Set the public_static folder for CSS, Images, etc. expressUtils.setPublicStaticFolder(app); expressUtils.setPassportStrategy(); // Set up the Passport Strategy expressUtils.setPassportMiddlewares(app); // Add Passport middlewares //I have more controllers const checkinController = require("./controllers/checkin"); const locationController = require("./controllers/location"); const authController = require("./controllers/auth"); // app.use(controllers); app.use("/auth", authController); app.use("/", checkinController); // Add middleware for protected controllers/routes app.use( "/locations", function (req, res, next) { // Save the URL of the resource the user is trying to access req.session.redirectTo = req.originalUrl; console.log(req.session); next(); }, function (req, res, next) { if ( req.headers.authorization && req.headers.authorization.startsWith("Bearer ") ) { // If the request has an Authorization header that starts with 'Bearer ', // use the Bearer strategy with session: false console.log("app.js Locations: bearer"); console.log(req.headers); passport.authenticate("bearer", { session: false })(req, res, next); } else { //next(); console.log("app.js Locations: google"); // Otherwise, use the Google strategy with session: true passport.authenticate("google", { session: true })(req, res, next); } }, expressUtils.ensureAuthenticated, expressUtils.refreshTokenIfNeeded, locationController ); // Sync the session store expressUtils.sessionStore.sync(); const port = process.env.PORT || 3000; app.listen(port, function () { console.log("Server is running on port " + port); }); I keep my middleware in a separate module (expressUtils.js): const express = require("express"); // Use flash messages const flash = require("connect-flash"); const session = require("express-session"); const methodOverride = require("method-override"); const axios = require("axios"); const passport = require("passport"); const GoogleStrategy = require("passport-google-oauth20").Strategy; const BearerStrategy = require("passport-http-bearer").Strategy; const { OAuth2Client } = require("google-auth-library"); // for refresh token const config = require("./config"); // Make sure your config file includes Google clientID and clientSecret const client = new OAuth2Client(config.secret_clientid); const util = require("util"); // The util.inspect function is used to print out the entire object, even if it has nested properties. // For Sessions - Sequelize connection to db and session store const db = require("./models/index.js"); const sequelize = db.sequelize; const SequelizeStore = require("connect-session-sequelize")(session.Store); // Initialize session store const sessionStore = new SequelizeStore({ db: sequelize, }); console.log("ClientID:", config.secret_clientid); console.log("ClientSecret:", config.secret_oauth); function setViewEngine(app) { app.set("view engine", "ejs"); } function setPublicStaticFolder(app) { app.use(express.static("public")); } function setPassportStrategy() { console.log ("Setting up passport strategy..."); passport.use( new GoogleStrategy( { clientID: config.secret_clientid, clientSecret: config.secret_oauth, callbackURL: "/auth/google/callback", accessType: "offline", // Request offline access to obtain refresh token scope: [ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", ], // Add the scope parameter here }, function (accessToken, refreshToken, profile, cb) { console.log("GoogleStrategy callback invoked..."); console.log("Access Token: ", accessToken); console.log("Refresh Token: ", refreshToken); console.log("Profile: ", util.inspect(profile, { depth: null })); if (profile._json.hd === "MYDOMAIN.com") { // Store the access token and refresh token in the user object profile.accessToken = accessToken; profile.refreshToken = refreshToken; return cb(null, profile); } else { return cb(null, false, { message: "Invalid domain" }); } } ) ); passport.use( new BearerStrategy(async function (token, done) { console.log("BearerStrategy callback invoked..."); console.log("Token: ", token); try { // Try to verify the token as an ID token const ticket = await client.verifyIdToken({ idToken: token, audience: config.secret_clientid, }); const payload = ticket.getPayload(); console.log("Payload: ", util.inspect(payload, { depth: null })); // Check the 'hd' field in the payload to make sure it's your domain if (payload.hd !== "MYDOMAIN.com") { throw new Error("Invalid domain"); } // If everything checks out, the token is valid done(null, payload, { scope: "read" }); } catch (error) { console.log("Error verifying ID token: ", error.message); // If the token couldn't be verified as an ID token, try to verify it as an access token try { const payload = await verifyAccessToken(token); done(null, payload, { scope: "read" }); } catch (error) { console.log("Error verifying access token: ", error.message); done(null, false, { message: error.message }); } } }) ); passport.serializeUser(function (user, cb) { console.log("Serializing user..."); console.log("User: ", util.inspect(user, { depth: null })); cb(null, user); }); passport.deserializeUser(function (obj, cb) { console.log("Deserializing user..."); console.log("Object: ", util.inspect(obj, { depth: null })); cb(null, obj); }); } function setPassportMiddlewares(app) { app.use(passport.initialize()); app.use(passport.session()); } function setMiddlewares(app) { app.use(express.urlencoded({ extended: true })); app.use(express.json()); //Allow the app to override form methods since HTML forms don't support DELETE natively app.use(methodOverride("_method")); app.use( session({ secret: config.secret_session, // TO DO: Change this resave: false, saveUninitialized: true, store: sessionStore, // Use the new session store }) ); app.use(flash()); // this ensures flash messages are available to all routes and views app.use((req, res, next) => { res.locals.messages = req.flash(); next(); }); app.use((req, res, next) => { console.log("------------------------"); console.log("Request Details:"); console.log("Method:", req.method); console.log("URL:", req.originalUrl); console.log("Body:", req.body); console.log("Session:", req.session); next(); }); } async function verifyAccessToken(token) { const response = await axios.get( `https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=${token}` ); const payload = response.data; // Check the 'aud' field in the payload to make sure it's your app's client ID if (payload.aud !== config.secret_clientid) { throw new Error("Invalid client ID"); } // Check the 'hd' field in the payload to make sure it's your domain const emailDomain = payload.email.split("@")[1]; if (emailDomain !== "MYDOMAIN.com") { throw new Error("Invalid domain"); } // If everything checks out, the token is valid return payload; } // Support both access tokens (BearerStrategy) and Google function ensureAuthenticated(req, res, next) { console.log("ensureAuthenticated: headers..."); console.log(req.headers); console.log("ensureAuthenticated: user..."); console.log(req.user); if (req.user) { return next(); } // Store original URL before redirecting to login req.session.redirectTo = req.originalUrl; console.log("ensureAuthenticated: redirectTo..."); console.log(req.session.redirectTo); req.session.save((err) => { if (err) { return next(err); } res.redirect("/auth/google"); }); } // Custom middleware to check if access token is expired and refresh it if necessary function refreshTokenIfNeeded(req, res, next) { const user = req.user; console.log("refreshTokenIfNeeded: req.user"); console.log(req.user); if (!user || !user.accessToken || !user.refreshToken) { console.log("refreshTokenIfNeeded: user, accessToken or refreshToken missing"); // If user or tokens are missing, proceed without refreshing return next(); } const accessTokenExpiration = user.accessTokenExpiration; // Check if access token is expired or about to expire in a certain threshold if ( accessTokenExpiration && Date.now() >= accessTokenExpiration - 60000 // Refresh token if access token is about to expire in 1 minute ) { const refreshToken = user.refreshToken; // Use the refresh token to get a new access token oauth2Client .refreshToken(refreshToken) .then((refreshResponse) => { const newAccessToken = refreshResponse.credentials.access_token; // Update the user object with the new access token and its expiration user.accessToken = newAccessToken; user.accessTokenExpiration = Date.now() + refreshResponse.credentials.expires_in * 1000; console.log("refreshTokenIfNeeded: access token refreshed"); // Proceed to the next middleware or route handler next(); }) .catch((error) => { // Handle the error, e.g., log or respond with an error message console.error("Error refreshing access token:", error); next(); // Proceed to the next middleware or route handler even if the refresh fails }); } else { // Access token is still valid, proceed to the next middleware or route handler console.log("refreshTokenIfNeeded: access token still valid"); next(); } } module.exports = { setViewEngine, setPublicStaticFolder, setMiddlewares, setPassportStrategy, setPassportMiddlewares, ensureAuthenticated, addAuthorizationHeader, refreshTokenIfNeeded, sessionStore, }; And I maintain my Google Callback URL etc. in my auth.js controller: // In app.js, I use this as "/auth" const express = require("express"); const passport = require("passport"); const router = express.Router(); router.get("/google", function (req, res, next) { console.log("/auth/google"); // Save the redirectTo value in the session req.session.redirectTo = req.query.redirectTo; passport.authenticate("google", { scope: ["profile", "email"], hd: "MYDOMAIN.com", // Specify the hosted domain (your Google Workspace domain) })(req, res, next); }); router.get( "/google/callback", passport.authenticate("google", { failureRedirect: "/login" }), (req, res) => { // Redirect to original URL or homepage if no URL is stored var redirectTo = req.session.redirectTo || "/"; delete req.session.redirectTo; // I've tried with this commented out too res.redirect(redirectTo); } ); module.exports = router; In case it's helpful, here's a snippet from the logs when I run with DEBUG=express-session: Request Details: Method: GET URL: /auth/google/callback?code=CODE&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=0&hd=MYDOMAIN.com&prompt=consent Body: {} Session: Session { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, flash: {}, redirectTo: '/locations' } GoogleStrategy callback invoked... Access Token: ACCESS_TOKEN Refresh Token: undefined Profile: { id: 'USER_ID', displayName: 'USER_NAME', name: { familyName: 'FAMILY_NAME', givenName: 'GIVEN_NAME' }, emails: [ { value: 'USER_EMAIL', verified: true } ], photos: [ { value: 'USER_PHOTO_URL' } ], provider: 'google', _json: { sub: 'USER_ID', name: 'USER_NAME', given_name: 'GIVEN_NAME', family_name: 'FAMILY_NAME', picture: 'USER_PHOTO_URL', email: 'USER_EMAIL', email_verified: true, locale: 'en', hd: 'MYDOMAIN.com' } } Executing (default): SELECT "sid", "expires", "data", "createdAt", "updatedAt" FROM "Sessions" AS "Session" WHERE "Session"."sid" = 'SESSION_ID'; Executing (default): DELETE FROM "Sessions" WHERE "sid" = 'SESSION_ID' Serializing user... User: { id: 'USER_ID', displayName: 'USER_NAME', name: { familyName: 'FAMILY_NAME', givenName: 'GIVEN_NAME' }, emails: [ { value: 'USER_EMAIL', verified: true } ], photos: [ { value: 'USER_PHOTO_URL' } ], provider: 'google', accessToken: 'ACCESS_TOKEN', refreshToken: undefined } Executing (default): SELECT "sid", "expires", "data", "createdAt", "updatedAt" FROM "Sessions" AS "Session" WHERE "Session"."sid" = 'NEW_SESSION_ID'; Executing (default): INSERT INTO "Sessions" ("sid","expires","data","createdAt","updatedAt") VALUES ($1,$2,$3,$4,$5) I learned that the PassportJS passport-google-oauth20 strategy will delete the session on authentication. So, in order to retain the redirect URL, you can't place it on the session. As an alternative, I used cookie-parser to set a secure cookie with the redirect URL and the deleted the cookie after redirect. After making that change, I was also able to remove these 2 middlewares: expressUtils.ensureAuthenticated, expressUtils.refreshTokenIfNeeded,
common-pile/stackexchange_filtered