Get custom grails plugin version from within the plugin

Question: I have a Grails plugin that I've written that has its version set using set-version within our continuous integration environment.  While building, I'd like to programmatically output the version from within "eventCompileEnd" event hook.  So, for my Grails app I can just get the "app.version" metadata but plugin versions are set in the GrailsPlugin.groovy file in the root of the plugin.  Is there any way to access that value? Here's the version info I'm referring to:
class MyUtilityGrailsPlugin {
   // the plugin version
   def version = "4.6.8"

   // the version or versions of Grails the plugin is designed for
   def grailsVersion = "2.1 > *"

   ...etc.

Answer: You can use below eventCompileEnd event in _Events.groovy of the app to get the name and version of all the plugins used in the app from GantBinding which is by default available to the post compile event. You can filter your plugin info based on the name:
//scripts/_Events.groovy
eventCompileEnd = {msg->
    msg.supportedPluginInfos.each{println "${it.name} - ${it.version}"}
}

If you want to access the plugin info  from any where else (for example: BootStrap) using applicationContext would be the simplest approach. Something like below would be useful:
//Bootstrap.groovy
def grailsApplication

def init = { servletContext ->
    grailsApplication.mainContext.getBean('pluginManager')
                                 .allPlugins.each{plugin->
        println "Plugin Info ${plugin.name} - ${plugin.version}"
    }
}

In your case, appCtx will not be available in post compile event, so you have to depend on GantBinding.
Answer: I found that version information can be retrieved from within an event hook for that plugin by doing this:
pluginSettings.getPluginInfo(isPluginProject.getParent()).version;

pluginSettings is a bound variable in the current scope and isPluginProject actually returns a File object that represents the GrailsPlugin.groovy file.


Why don't I see more progress when sanding my stair treads?

Question: Doing some DIY around the house, any suggestions would greatly help.
I want to refinish my indoor steps and railing(sand and repaint)
When i am trying to sand the steps its very hard to sand it, although i am applying pressure i dont see it sanding (no dust/powder).Basically nothing is happening. Sanding paper i am using is Grit 80.
Any ideas what i am doing wrong or what is missing?
Thanks in advance.
Comment: Grit 80? Bud, you need 24 or 36 for the first pass. Then 60, then 80, then 120, and finish with 160 for an excellent finish.
Comment: Floors and stairs receive finishes which are meant to take abuse for decades so that's why 80 grit is doing practically nothing. I'm not sure what your expectations are but I see those stairs are quite damaged so the end result could be disheartening. You could save yourself a lot of disgruntlement if you decide to simply paint the stairs with a high quality paint designed for foot traffic. An oil-based or shellac-based primer would do well for adhesion to the existing polyurethane.
Comment: You picked a tough job for a newbie... :-)
Comment: Don't worry, we're **all** still learning. The only ones that are not learning are the ones which gave up :-)
Comment: Thanks man, newbie here, still learning :)
Comment: @MonkeyZeus, those grits are appropriate for an entire floor with a drum or plate sander. You wouldn't use them with a hand sander. 60 is as coarse as I've ever wanted to use.
Comment: The "easy" way to clean up the damage would be remove the treads and use a planer/thicknesser machine or a jack plane to take off the varnish.
Answer: A vibrating or oscillating sander isn't going to be aggressive enough for that job. It's really only suitable for light finish sanding. You need something that spins, or at least something with a random orbit (more movement).
80 grit is probably a good choice for working through the varnish on your steps but you need the moves only a different type of sander provides or you'll grow old waiting. Part of the problem is that varnish clogs paper grit quickly--it doesn't let go like clean sawdust does.
You might also consider chemically stripping the varnish to hurry the restoration process. Sanding through it can be a real chore.
All that said, if you have the option of temporarily removing your treads, that's what I'd be doing. You'll have a difficult time getting satisfactory results around the edges with them installed. You'll have visible lines from the existing varnish and stain, and you may have visible surface level variation as well. If you can gently pop them out, pull the nails out the back side, and sand or strip fully in a workshop area, that's the ticket.
Comment: While I agree 100% with removing the treads and refinishing on the bench, those look like they're cased in, so removal isn't quite as easy as "pop the nails & pull". _If_ there's adequate access to the underside of the staircase, the OP may be able to figure out exactly how the treads were installed and be able to pull them out from there. May not be a 1st DIY level project, though.
Comment: Yeah, the skirt may need to be removed as well. It's not clear whether they could be lifted out from the left. .
Comment: @jayroy Stripping the varnish is no cake-walk either. Some of the products recommend letting it sit for 8 hours or more so those stairs will be completely inaccessible in the meantime. I tried letting one sit for 48 hours when I was refinishing my floors and the results were disappointing. Big box stores generally won't sell the good stuff that professionals use as it can be quite noxious. Even if you succeed you will likely have to do some sanding to remove all of the old color.
Comment: I've had success with *heat* stripping varnish, on smaller surfaces like door trims.
Comment: @GlenYates a belt sander could work on removed treads, but a) they cut material _really_ fast, which takes lots of practice to keep even across an entire piece, and b) anything in-place like this would be really hard to get right as a belt sander can't reach 3 of the edges. You'd have almost as much trouble matching the edges with another technique as using that alternative for the entire piece.


How to resize one of the plugins of the Flot library?

Question: I'm displaying charts using the Flot library and almost all of them are working fine with the resize plugin.
Nevertheless, I need to start using one of the  extra-plugins that allows to display bars side by side. Since this is just a non-official plugin chart, I'm having a issue to use Flot's Resize Plugin and Benjamin's Bar-side-by-side Plugin. It's not working and I keep getting this error:
Uncaught TypeError: Cannot call method 'push' of undefined (jquery.flot.resize.js:51)

I need to make this resizing for this specific chart. Some help would be really appreciated. Somebody could tell me what could be done to fix this problem?
Edit: I'm adding two JsFiddle examples:
First, the bar chart example working correctly (but without the resize plugin). Clcik Here
Second, the same bar chart example using the resize plugin. Click Here
Comment: Could you put a jsfiddle.net together demoing the problem?
Comment: Hi Mark, I've just put two jsfiddle's.. The first one works perfectly without the resize plugin, and the second one doesn't work because of the resize plugin.
Answer: The version of Flot (v. 0.6) referenced in both of your Fiddles is really old. The resize plugin ties into the shutdown hook in Flot:
plot.hooks.shutdown.push(shutdown);

Version 0.6 of Flot doesn't have the shutdown hook defined. The shutdown hook was added with version 0.7.
I updated the flot files referenced in your JSFiddle to the latest versions. Both the orderbars and resize plugin work as expected.
JSFiddle


who creates the passkey (and how many will be created?)

Question: Passkey is nice. The math is nice. The tech is nice. [web standard is a Zumutung <- ask chatgpt]
https://security.googleblog.com/2023/05/so-long-passwords-thanks-for-all-phish.html
What I still dont see:

What software CREATES the passkey.
User autonomy is important and it is a key question (pun intended). I do not really see this answered anywhere.

Is it the pass manager or the operating system?
It should be the pass manager, since we store our secrets in a pass manager that we trust. I am not hostile to Apple, Google, Microsoft (or Linux), I use the Google Pass Manager btw. But it should be a choice and if you choose an open source pass manager (which I might in the future), it should create the key pair (and with it, the secret private key). However, it seems to me that pass managers may only get API from the os and the os creates the keys as of now. Practically as of now, 3 US companies would create all the secrets of the world in the future?
https://developer.apple.com/documentation/authenticationservices/public-private_key_authentication/supporting_passkeys
Another thing I cant get my head around:

HOW MANY passkeys are INTENDED to be created. A passkey requires a pass manager. Should domain service providers (relying party) let users that do not use cross platform pass managers create passkeys on Apple, Google, Microsoft (later on Linux) and so having secrets in 4 pass managers eventually (hopefully those who do not use pass managers, now step up the game and install brutal security for all of these accounts of theirs, because it is enoguh to breach one of them).

Or the design intention is to just let them create the one and only passkey (until deletion or change) and it is the responsibility of the user (and actually AGML) that they can sync THE passkey cross platform? And how will this happen? Export, encrypted export, magic?
[Warm welcome for the question to get voted down to -4 within a minute by operators or such... I actually have researched a LOT. And asking a simple but key question may show a lot of research effort. Nobody seems to ask who CREATES the passkey (but it may be important for security and not every user is sheep material: they do understand that some secret is created for them and plenty of them want to know who creates it and who manages it. With passwords you or your pass manager creates the secret and that is really understandable. I think I managed to dig to 2 simple core questions: who should create the passkey and how the hell will it be synced for people who do not want to make the effort to invest (time,effort,money) in a truly cross platform pass manager. If and only if these 2 questions are answered and communicated(!) to users is it possible for passkeys to become a success, which would be great. And nobody talks about them anywhere!]
Comment: I wondered about this quite a bit too. Great question. At first the webauthn protocol was "sold" as private keys bound to devices. But this evolved in keys being synced, and from the answers it appears browsers now also enable third-party software to produce and manage these keys... what comes next? ;) ...it's also difficult to untangle the "spec" from the "browser reality" since they are "not in sync"
Comment: Good comment, good to know I am not the only one feeling this way. Great wording: untangle the "spec" from the "browser reality". I must add browser and os reality or rather Apple-Google-Microsoft reality since both os and browser is practically A-G-M (some linux, some firefox or brave and other chromiums). I mean the whole thingy is random ECDSA private key created and managed instead of passwords. Better against fishing but why not random 25-49 char human readable and backupable pass, where deterministically calculated ECDSA pub key is anonym user id and priv key signs a random challenge?
Answer: On the subject of who holds the passkey, it's important to understand that the relying party -- the site running the JavaScript navigator.credentials.create() function, has the ability to steer things in some ways.
There are 2 possibilities:

Relying party specifies publicKeyCredentialCreationOptions .authenticatorSelection.authenticatorAttachment = cross-platform: The browser will require the user to plug in a "roaming authenticator", which is typically a USB key.

Relying party specifies publicKeyCredentialCreationOptions .authenticatorSelection.authenticatorAttachment = platform: This is the type of attachment you're likely referring to, which is when OS (or a 3rd party app, coming soon) holds the key.

To find out more, check out the Webauthn spec. The latest editor's draft here: https://w3c.github.io/webauthn/#dictionary-authenticatorSelection contains all the documentation on the parameters above.
Edit: Removed incorrect information about the requireResidentKey param. See @agl's comment below.
Comment: "That parameter requireResidentKey is a boolean, and if set to true, indicates to the browser that the key should not be synced."

requireResidentKey does not control syncing. (In fact, setting it makes it more likely that you'll get a synced credential.) It specifies that the credential is "discoverable", i.e. that it can be found without specifying its credential ID. That means that it can work without entering a username first, can appear in autocomplete, etc.
Comment: thanks! as far as I understand, requireResidentKey = true will not enforce sync stop (apple and google sync always, NOW) it rather something like client side discoverable credentials without credential id vs. server side :https://w3c.github.io/webauthn/#client-side-discoverable-credential actually pass manager holds the passkey, my questions was who creates them :) pass managers or Apple,Google,Microsoft OS? so if you use open source pass manager, is it any protection against NSA :)
Comment: if you liked the question, can you please upvote, some trolls voted it -4 just because it is not apparent that I worked a lot to come up with this question :) I am really interested in answers! as of now, I am pretty sure Apple, Google,Microsoft just gives API to pass managers where they can GET the passkey generated by THEM! I would use passkeys anyways but I want to understan WHY, has it some security rationale or just power play and NSA stuff?
Comment: I find the comment nice but my 2 questions remain totally unanswered. I edited my question so that it is easier to read and discover my true questions (I tend to write verbose, I know it and I work on it every day) Thanks!
Answer:
What software CREATES the passkey. User autonomy is important and it is a key question (pun intended). I do not really see this answered anywhere.

The passkey is created by the "authenticator". WebAuthn, the standard, doesn't care what the authenticator is. Practically it could be a security key(*) or a password manager.
The reason that it seems like the answer might be "operating system" is that, on iOS 16 and Android 13 (the current versions at the time of writing) only iCloud Keychain or Google Password Manager (respectively) can be used to create passkeys. But this isn't fundamental and in iOS 17 and Android 14, there are APIs for other password managers to plug into passkey flows.

HOW MANY passkeys are INTENDED to be created.

An account typically only has one password, but it can have many passkeys. Today that's a practical necessity unless users want to pull out their phone every time they sign in because syncing doesn't work everywhere yet. But even in a world where syncing is working great, the intention is very much that users be able to register multiple passkeys if they wish and the API is designed around this: it hints when the user signed in with a phone so that the site can prompt the user to register the local device.
(*) A passkey is supposed to sync and, if you create one on a security key, it won't sync so technically isn't a passkey. But we assume that people using security keys are expert enough to understand that and don't clutter the UI with the distinction.
Comment: As of Aug 2023 I think it is a perfect answer. Webauthn spec says authenticator, which should be the pass manager. The browser is asked to perform passkey creation, which is bound to user verification that is performed by the OS. Would pass managers (like open source bitwarden or proton) be allowed only to store and manage, or also to create passkeys? Who controls the A-G-M OS APIs, since the spec says nothing about it. Will these APIs make third party pass managers THE authenticators, so we only have to trust our chosen pass manager? Or will they be only some receivers in this passkey flow?
Comment: So pass managers should create passkeys but how many? The end product seems to be having plenty of passkeys to the same account, instead of syncing one passkey. Not that I feel it is the right way since site owners and users have to manage them too... I think it will be a mess. There could be only one passkey but there seem to be plenty of created on different platforms... well, it should be explicit that passkeys need pass managers and pass managers should be synced everywhere and just create and manage and use one passkey. Let us see what happens in the future...
Answer: According to Google, it's based on the Fido2 standard, so any software compliant with that should be able to generate the keypair. The private key will typically never leave your device, unless you use some synchronization mechanism to reuse the key on other devices or otherwise take action to move it from the device.
The default mechanism for Google on Android is to use the builtin support, so while you do not have full control on the software, it all happens locally on your device.
The number of passkeys should be one for every device and account. So with 3 accounts and 4 devices you'd typically need 12 passkeys (i.e. keypairs).
Comment: not true, apple syncs private key within a second (without asking) to keychain and google syncs with google pass manager, it is totally synced within ecosystems (apple, google, microsoft) or will be synced and I guess they will be exportable too... of course pass manager will sync them too and keep in cloud... it happens on the device answers nothing, where else? the question is it happens within the pass manager or os (or browser but it is rather one of the former 2) both pass manager and os are on the device of course
Comment: I am not sure whether webauthn standard has something to do with it... it is rather implementation, do pass managers get the info from os that local biometrics/passcode authentication was ok and they generate the key pair and store it or just get an API from apple/google/microsoft where they can get the key... seems to be a big difference to me... do 3 US companies are supposed to create the secrets of everybody in the future?
Comment: @rj Concerning "not true..."- that's why I wrote "unless you use some synchronization mechanism".
Comment: not true that the key will typically(!) not leave your device, it may be true on microsoft because normally you have one windows pc but it typically leaves the device, in future practically 100%... I think you remember the old fido ways, but apple/google/microsoft created passkeys with explicitly sync in mind for usability... I might not have been clear but I am interested in the typical thing when people start to create passkeys with os and sync with pass manager... sorry if I was harsh, thats my style. my actual question was: who creates the passkey, sync and storage is via pass manager


how get php total time?

Question: i have created work total time program in PHP - give input time - 1.30, 2.10, 1.40 and get output time - 4.80(8 hrs). but i need output time - 5.20(8.40 hrs).
Notes: 1.30+2.10+1.40=4.80(8 hrs), but i need 5.20(8.40 hrs). please help me...
Comment: 4.80 = 8hrs and 5.20 = 8.40 hrs? what kind of time measurement is that? einstein relativity or something?
Comment: Just add the extra 40 minutes. Or is there something you're not telling us?
Comment: How is exactly 4.80 the same as 8 hours, am I missing something?
Comment: I think Murugesh writes 4.80 to mean 480mins (8hrs) and 5.20 to mean 520mins (8hrs 40mins).
Answer: 1.30 + 2.10 + 1.40 is wrong. Should be:
((1 * 60) + 30) + ((2 * 60) + 10) + ((1 * 60) + 40) = 320 (minutes)
320 minutes = 5 hours and 20 minutes.
Answer: You need to keep track of minutes and seconds separately:
$minutes = array();
$seconds = array();
foreach ($times as $time) {
    $parts = explode('.', $time);
    $minutes[] = $time[0];
    $seconds[] = $time[1];
}
$total_minutes = array_sum($minutes);
$total_seconds = array_sum($seconds);
while ($total_seconds > 60) {
    $total_minutes++;
    $total_seconds -= 60;
}
echo $total_minutes . ' minutes and ' . $total_seconds . ' seconds';

Answer: Excerpt from PHP site for your pleasure:
function AddTime ($oldTime, $TimeToAdd) {
  $pieces = split(':', $oldTime);
  $hours=$pieces[0];
  $hours=str_replace("00","12",$hours);
  $minutes=$pieces[1];
  $seconds=$pieces[2];
  $oldTime=$hours.":".$minutes.":".$seconds;

  $pieces = split(':', $TimeToAdd);
  $hours=$pieces[0];
  $hours=str_replace("00","12",$hours);
  $minutes=$pieces[1];
  $seconds=$pieces[2];

  $str = $minutes." minute ".$seconds." second" ;
  $str = "01/01/2000 ".$oldTime." am + ".$hours." hour ".$minutes." minute ".$seconds." second" ;

  if (($timestamp = strtotime($str)) === false) {
    return false;
  } else {
    $sum = date('h:i:s', $timestamp);
    $pieces = split(':', $sum);
    $hours = $pieces[0];
    $hours = str_replace("12", "00", $hours);
    $minutes = $pieces[1];
    $seconds = $pieces[2];
    $sum = $hours.":".$minutes.":".$seconds;
    return $sum;
  }
}

$firstTime  = "00:03:12";
$secondTime = "02:04:34";

$sum=AddTime($firstTime, $secondTime);

if($sum != false) {
  echo $firstTime." + ".$secondTime." = ".$sum;
} else {
  echo "failed";
}

Output:
00:03:12 + 02:04:34 = 02:07:46

Comment: This code is with a good overhead IMO, but will work for you.
Answer: For each number (represented as $t below) you can do this:
// start with $total=0
$hours = floor($t); // 1.10 -> 1 hr
$minutes = ($t - $hours) * 100; // 1.10 -> 10 mins
$total += ($hours * 60) + $minutes;

That gives you the total number of minutes. To get hours/mins separately, do this:
$total_mins = $total % 60; // 130 -> 10 mins
$total_hours = ($total - $total_mins) / 60; // 130 -> 2 hrs

how get php total time?


How to find the complement of the following graphs?

Question:
So G is a simple graph, the complement of G, denoted G' is obtained as follows:
The vertex set of G' is identical to the vertex set of G. However 2 distinct vetices v and w of G' are connected by an edge if and only if, v and w are not connected by an edge in G. How can we find the compliment of the above graphs?
for a) am I suppose to draw a graph with 4 edges that doesn't overlap with that original graph?
Same goes for b), so v1 - v4 and v2- v3 ?
Answer: This is just a direct application of the definition of compliment.
For the first graph, G' has edges v1-v3 and v4-v3
and the second graph, G' has edges v1-v4, v1-v3, v2-v4, and v2-v3


Where can I find jsdom documentation?

Question: I'm looking for documentation on jsdom that is more descriptive than just the readme at https://github.com/tmpvar/jsdom.
Specifically, I'm looking for instructions on how to interpret the nodeType property of a DOM node created by jsdom. The property stores an integer which has no inherent meaning as far as I can see. In the immediate example I'm sure there's some testing I can do to discover what integer maps to what DOM node type, but it's taking a long time to write custom tests and introspection code just to work my way around these objects. Other questions that I'd use the doc for are about how to access a node's parent directly, traverse children, access text data, etc. (all by accessing object properties directly outside of any jquery specific functions).
Where can I find jsdom documentation on the properties of a DOM node?
Comment: @casperOne, can you elaborate on why this was closed? AFAIK none of my other documentation-request style questions I've asked were closed like this. They haven't caused debate/arguments/polling etc. Should I have included the full list google searches / unhelpful resources I had already tried to show all the research that had gone into the quesiton before posting?
Answer: While not specific to jsdom, the NodeTypes - Named Constants table at http://www.w3schools.com/dom/dom_nodetype.asp seems to relate to the values I'm seeing for nodeType values.
Comment: And regarding the other questions I mentioned, http://www.w3schools.com/dom/default.asp seems to answer them all. No detailed doc = jsdom just uses common conventions I just wanted aware of

Where can I find jsdom documentation?


Implementing division using only adds and multiplies

Question: I'm writing a BigDecimal class in C#. I've successfully implemented +, - and * operators. But I can't figure out a way to calculate division of 2 BigDecimals. What's the quickest way to implement division using those 3 operators? Or is there a better way to do that? (Considering both development time and algorithm speed)
Goal 1: I want the result to be another BigDecimal with a fixed precision (that should be changeable)
Goal 2: As you mentioned, the purpose of BigDecimal is not a fixed precision. So how can I achieve infinite precision?
Another Question: Is it better (regarding speed and flexibility) to use Microsoft BCL's BigRational class for Arbitrary-precision arithmetic and then use Christopher Currens's extension method in this thread: Is there a BigFloat class in C#? to get decimal representation instead of writing a new class?
Comment: What would you like the output of 1/3 to be? Infinite number of threes?
Comment: @SepehrM You don't actually resolve the result to a single numeric value.  The internal state of the `BigDecimal` would simply be a numerator an a denominator (possibly simplified).  This would let you represent any rational number without limiting yourself to a fixed precision.  It wouldn't let you represent an irrational number though.
Comment: Your "another question" is not answerable. "Better" implies that there is a metric you are using to evaluate the costs of two possibilities against the value they produce in achieving a goal. Without knowing what either your cost metric is or what your goals are, how can we possibly know which is going to be better for you?
Comment: Are you trying to implement "long division" explicitly? Did you learn to do division by hand in school (sorry for asking but the math curriculum isn't what it used to be...). http://www.doubledivision.org/
Comment: @EricLippert I want the result of 1/3 to be 0.33333333333333333333 with my desired precision ...
Comment: So your big decimal is arbitrary precision?
Comment: @EricLippert That's right! My bad ...
Comment: @EricLippert How is it possible to have "infinite" precision?
Comment: @Floris I'm a first year student in computer science and I do know long division. However my English is not perfect. So don't mistake my bad English for lack of knowledge.
Comment: @SepehrM - no problem; I was asking what you knew - because it changes what kind of answer would make sense _for you_. Not intended as a "hah you know nothing" comment - I hope you didn't take it that way.
Comment: @Servy Thanks I see. But then what would be the difference between BigDecimal and BigRational (already implemented in Microsoft's BCL)?
Answer: First off, I presume that by "big decimal" you mean that you are representing a rational where the denominator is restricted to be any power of ten.
You'll want to think hard about what you want the output of the division of two decimals to be. Decimals are closed over addition, subtraction and multiplication but not closed over division. That is, any two decimals multiplied together produces a third: (7 / 10) * (9 / 100) gives you 63 / 1000, which is another decimal. But divide those two decimals and you get a rational that does not have a power of ten in the denominator.
To answer the question you actually asked: just as multiplication can be built out of addition in a loop, division can be built out of subtraction in a loop. To divide 23 by 7, say:

Is 7 < 23? Yes.
Subtract 7 from 23 to get 16.
Is 7 < 16? Yes.
Subtract 7 from 16 to get 9
Is 7 < 9? Yes.
Subtract 7 from 9 to get 2.
Is 7 < 2? No. We have our first digit. We did three subtractions, so the first digit is 3.
Multiply 2 by 10 to get 20
Is 7 < 20? Yes.
Subtract 7 from 20 to get 13.
Is 7 < 13? Yes.
Subtract 7 from 15 to get 6.
Is 7 < 6? No. We did two subtractions and a multiplication by 10, so the next digit is 2.
Multiply 6 by 10 to get 60
Is 7 < 60? Yes...
...
We did eight subtractions, so the next digit is 8...
... and so on

Do you know of a faster algorithm for this purpose?

Sure, there are lots of faster algorithms for division. Here's one: Goldschmidt's Algorithm.
First off, I hope that it is clear that if you are trying to compute X / D then you can first compute 1 / D and then multiply that by X. Moreover, let us assume WOLOG that D is strictly between 0 and 1.
What if it isn't? If D is negative, invert both it and X; if D is zero, give an error; if D is 1 then the answer is X; if D is greater than 1 then divide it and X both by 10, which should be easy for you since your system is decimal.  Keep applying those rules until you have a D between zero and one.  (As an additional optimization: The algorithm is slowest when D is very small, so if D is less than, say, 0.1, multiply X and D by ten until D is greater than or equal to 0.1.)
OK, so our problem is that we have a number D between zero and one and we wish to compute 1 / D.  Probably the easiest thing to do is to work an example. Suppose we are trying to compute 1 / 0.7. The correct answer is 1.42857142857...
Start by subtracting 0.7 from 2 to get 1.3.  Now multiply both parts of the fraction by 1.3:
(1 / 0.7) * (1.3 / 1.3) = 1.3 / 0.91

Great. We have now computed 1 / 0.7 to one digit of accuracy.
Now do it again. Subtract 0.91 from 2 to get 1.09.  Multiply both parts of the fraction by 1.09:
(1.3 / 0.91) * (1.09 / 1.09) = 1.417 / 0.9919

Great, now we have two correct digits. Now do it again. Subtract 0.9919 from 2 to get 1.0081.  Multiply top and bottom by 1.0081:
(1.417 / 0.9919) * (1.0081 / 1.0081) = 1.4284777 / 0.99993439

Hey, now we have four correct digits. See how that goes? Every step of the way the denominator gets much closer to 1, and therefore the numerator gets closer to 1 / 0.7.
This converges much more quickly than the subtraction method.
Do you see why it works?
Since D is between 0 and 1, there is a number E such that D = 1 - E, and E is also between 0 and 1.
When we multiply D by (2 - D), we are multiplying (1 - E) by (1 + E), which gives 1 - E2.
Since 0 < E < 1, clearly E2 is smaller than E and also between 0 and 1, which means that 1 - E2 is closer to 1. In fact it is a lot closer to 1.  By repeating this process multiple times we get close to 1 very quickly. Effectively what we're doing here is roughly doubling the number of correct digits on each step. Obviously that is a lot better than the subtraction method, which gives one additional digit on each step.
Keep on doing that until you have the accuracy you desire. Since you're roughly doubling the number of accurate digits on each step, you should be able to get to an acceptable degree of accuracy pretty quickly.  Since we already arranged that D is greater than or equal to 0.1 to start with, E is never larger than 0.9; repeatedly squaring 0.9 gets you down to a very small number pretty quickly.
Comment: @SepehrM: You can answer this question by **setting a performance goal**, implementing the code and then **testing to see if you met your goal**.
Comment: +1 That looks so easy to implement, but is it wise to do so? Isn't it too slow?
Comment: I did that and I just tried DreamWalker's code snippet and It was far away from my desired goal. So do you know of a faster algorithm for this purpose?
Comment: @SepehrM: I've posted a much faster algorithm.
Answer:
You can look to Java BigDecimal implementation for some ideas
For calculate a/b you can use Binary search algorithm for find such c that b * c = a (you should run algorithm until the desired precision is reached).
Also you can look to this BigFloat class, it has interesting implementation with exponential form
For infinite precision you can store you BigDecimal as rational fraction of two BigInteger.

Algebra for rational fraction represention:
(x1/x2) + (y1/y2) = (x1*y2+x2*y1)/(x2*y2)
(x1/x2) - (y1/y2) = (x1*y2-x2*y1)/(x2*y2)
(x1/x2) * (y1/y2) = (x1*y1)/(x2*y2)
(x1/x2) / (y1/y2) = (x1*y2)/(x2*y1)

Example of implementation for double (fixed precision):
public double Divide(double a, double b, double eps)
{
    double l = 0, r = a;
    while (r - l > eps)
    {
        double m = (l + r) / 2;
        if (m * b < a)
            l = m;
        else
            r = m;
    }
    return (l + r) / 2;
}

Comment: Your second choice only works for integer division (which, if that's what he wants, may be fine).  If he needs non-integer division then it won't really help.
Comment: Fot non-integer division we can use algorithm until the required accuracy is reached
Comment: But the idea of a BigDecimal is that it doesn't have a fixed precision, it has "infinite" precision.
Comment: Look to the comment 3 to question by author: it is about the desired accuracy, not about infinite precision
Comment: He posted that after my comment, and that's not the standard implementation of a BigDecimal, but sure, if that's what he wants, then it's possible to do that.
Comment: @Servy and DreamWalker: Thanks. I edited my post with my 2nd goal. How is that achievable?
Comment: @DreamWalker I tested your code snippet but It's too slow! Isn't there a faster algorithm?
Comment: You asked about quickest way to implement — it's solution with small amount of code. Solution with good performance takes many lines of code. Try google some articles about long arithmetic — there are a lot of theory about this topic.
Answer: Eric Lippert's answer looks a lot like "long division in the slowest possible way". It is accurate, budt it's not fast. Assuming that you have a way of approximating your BigDecimal with a double, and since you already have +, - and * implemented in your BD class, you could do (approximately) the following:
BD operator/(BD a, BD b) {
  BD r, result=0, residual;
  double aa, bb, rr;
  residual = a;
  bb = b;
  while (residual > desired) {
    rr = (double)residual / bb;
    r = rr; // assuming you have a conversion from double to bigdecimal with loss of precision
    result += r;
    residual = a - (result * b);
  }
  return result;
}

This will do a successive approximation, but many digits at once (basically you find the error using BD arithmethic, then divide that out using double arithmetic).  I think that should be a relatively straightforward and efficient approach.
I have implemented a version of the above using float and double - just to prove to myself that the principle can work. Using a straightforward C framework, it takes just two iterations to get the precision down to the level of the double division. I hope you get the idea.
#include <stdio.h>

double divide(double a, double b);
int main(void) {
  double a, b, result;
  float fa, fb, fr;
  a = 123.5;
  b = 234.6;
  fa = a;
  fb = b;
  fr = fa / fb;
  printf("using float: %f\n", fr);
  result = divide(a, b);
  printf("using double: %lf\n", result);
  printf("difference: %le\n", result - fr);
}

double divide(double a, double b) {
      double r, result=0, residual;
      float aa, bb, rr;
      residual = a;
      bb = b;
      while (residual > 1e-8) {
        rr = (float)residual / bb;
        r = rr; // assuming you have a conversion from double to bigdecimal with loss of precision
        result += r;
        residual = a - (result * b);
        printf("residual is now %le\n", residual);
      }
      return result;
    }

Output:
using float: 0.526428
residual is now 8.881092e-06
residual is now 5.684342e-14
using double: 0.526428
difference: 3.785632e-08

Comment: This answer was "sitting on a page" for several days before I submitted it - I see that since I wrote it Eric produced a much more detailed and faster solution already. I still think my implementation may shed some further light on this, so I'll leave it here.


Waiting for elevated vbscript to finish before execution of java code

Question: I am looking for a way to wait for a vbscript to finish execution before continuing to execute java code. I have a process call the script, which works fine, and a waitFor() to stop execution until it completes. The problem is that the script restarts itself with admin privileges upon start up. Since the process finishes when it restarts itself, the script doesn't have time to execute before my program continues.
Is there any way to have the program wait for this elevated script to run, or to start the script in such a way that it doesn't need to be restarted with elevated rights?
This is how I elevate the script
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, """" & WScript.ScriptFullName & """ /elevate //nologo" , "", "runas", 1
WScript.Quit
End If

This is how I call and wait for the process.
Process child = Runtime.getRuntime().exec("cscript
C:\\some\\path\\name\\scriptName.vbs");
child.waitFor();

Thanks in advance
Answer: Simple: use two different scripts!
The first one is started by the Java code. That script starts the second script with elevated permissions. And waits for the second script to finish.
Then Java will continue when effectively both scripts are done!
Otherwise you would need to implement some other (complicated!) way for the single script to send  "signals" to another JVM thread. Complicated and easy to get wrong.
Regarding your question how to do that: see here for example.
Comment: Thanks, I am exploring this option right now. Do you know of any resources where I might find out how to run one script from another, and how to wait for it to finish and return a string with its status? I am new to vbscripts and have been piecing them together slowly.
Comment: See my updated answer (and hint: google has such answers for you, too)
Comment: I cant find a way to run it elevated and wait for it to complete from the first script.
Answer: I had the same problem, execute a VBA script from Java and wait until it's finished:
  Runtime.getRuntime().exec(new String[]{"C:\\Windows\\System32\\wscript.exe", "C:/macro.vbs"});

The Macro contains a VBS code that is running a Macro (generateOutputFiles) inside an excel file:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\excel\test.xls")
objExcel.Application.EnableEvents = False
objExcel.Application.DisplayAlerts = False
objExcel.Application.Run "test.xls!generateOutputFiles"
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

After a long and painful research, I have decided to create a flag on the VB script itself after the end of its main program and wait for it in Java code as follows:
In VBA:
Set objExcel = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Delete the exesting end execution flag
endLoadingFlagPath = "C:\excel\LOADING_END_FLAG"
If (objFSO.FileExists(endLoadingFlagPath)) Then
   objFSO.DeleteFile endLoadingFlagPath
End If

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\excel\test.xls")
objExcel.Application.EnableEvents = False
objExcel.Application.DisplayAlerts = False
objExcel.Application.Run "test.xls!generateOutputFiles"
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close
' Create the end execution flag right after the main VB program
Set objFile = objFSO.CreateTextFile(endLoadingFlagPath)

In Java:
import java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

public class Test {

private static final Logger logger = Logger.getLogger("SCRIPT_RUNNER");

    public void executeVBScript() throws Exception {
        Runtime.getRuntime().exec(new String[]{"C:\\Windows\\System32\\wscript.exe", "C:/macro.vbs"});
        waitLoadingFinished();
    }

    private void waitLoadingFinished() throws Exception {
        File endLoadingFlagFile = new File("C:\\excel\\LOADING_END_FLAG");
        for(int attempt = 0; attempt < 10; attempt++) {
            utilSetDelay(5);
            if(endLoadingFlagFile.exists()) {
                return;
            }
        }
        throw new Exception("Timeout waiting for task");
    }

    private void utilSetDelay(long seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch(Exception ex) {
            logger.warn("Cannot sleep:" + ex.getMessage());
        }
    }
}

The attempt count and sleep delay can be set as parameters.


Which version of Ubuntu to install?

Question: I have an old Toshiba f10-100
Specs are:
<code>processor: 1.70 GHz Intel® Pentium® M processor 735
hard disk: 60 GB
system memory: 512 MB (although I am in the process of buying an extra 1G ram for it)
graphics: nvidia GeForce Go 6600, 128MB
</code>
My laptop still runs on XP 32bit and is used mostly for working on my PhD - lots of typing, bit of browsing, lots of article reading (PDFs) and listening to music. I have a netbook for more everyday tasks. The laptop still works very well, if slowly, but needs a new operating system, I suspect I should install Ubuntu 12.04 LTS but would appreciate any advice on the matter.
Answer: For your current setup i would recommend you install Xubuntu after you upgrade the RAM to 1GiB you can go for Ubuntu 13.10 with gnome 3 gnome-session-fallback (no effects), it should run ok.
I hope this is helpful, good luck and welcome to the community.

Which version of Ubuntu to install?


pylab bargraph query

Question: i am relatively new to plotting in pylab and here is a question. I have a text file containing words that have lengths ranging from 2 to 10 and now my task is to plot the frequencies of each of the word categories using bargraph. I was able to write the script and plot it but the xtick labels are screwed up and i am wondering what is the reason for this. Thanks in advance for your help.
two_letter=[]
three_letter=[]
four_letter=[]
five_letter=[]
six_letter=[]
seven_letter=[]
eight_letter=[]
nine_letter=[]
ten_letter=[]

inFile = open('words.txt')
for line in inFile.readlines():
    fields = line.split(' ')
    for word in fields:
        if len(word) == 2:
            two_letter.append(word)
        elif len(word) == 3:
            three_letter.append(word)
        elif len(word) == 4:
            four_letter.append(word)
        elif len(word) == 5:
            five_letter.append(word)
        elif len(word) == 6:
            six_letter.append(word)
        elif len(word) == 7:
            seven_letter.append(word)
        elif len(word) == 8:
            eight_letter.append(word)
        elif len(word) == 9:
            nine_letter.append(word)
        else:
            len(word) == 10
            ten_letter.append(word)
two_l = len(two_letter)
three_l = len(three_letter)
four_l = len(four_letter)
five_l = len(five_letter)
six_l = len(six_letter)
seven_l = len(seven_letter)
eight_l = len(eight_letter)
nine_l = len(nine_letter)
ten_l = len(ten_letter)

all = [two_l,three_l,four_l,five_l,six_l,seven_l,eight_l,nine_l,ten_l]
cord = range(1,10)
labels = ["two_let", "three_let", "four_let", "five_let", "six_let", "seven_let", "eight_let", "nine_let", "ten_let"]

import pylab
pylab.bar(cord,all, color='#88aa33')
xticks(cord, labels, rotation='vertical')
pylab.show()

Answer: You can use the keyword argument align in the bar command to have the labels in the center of the bars:
pylab.bar(cord,all, color='#88aa33', align='center')

To make more space for the labels, you can adjust the size and position of the plot with the subplots_adjust function:
subplots_adjust(bottom=0.25)

Making enough space for the labels can also been done automatically with:
from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable
make_axes_area_auto_adjustable(gca())

pylab bargraph query


Evaluation of expressions like if( argv[1][0] != ~'t')

Question: I have to input a string to make the second if condition false and print "Correct!". Can it be done?
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {

 if(argc != 2) { // argc is how long argv is, including that path-to-self
     puts("You need to give me exactly one argument!");
     return -1;

   }
// argv[1] represents the command line input you have given to the program. Which is a string or a char array.

 if(argv[1][0] != ~'t' || argv[1][1] != ~'h' || argv[1][2] != ~'e') {
      puts("noooo!");
      return 0;
    }
 else printf("Correct!\n");

 return 0;
}

Comment: "the" is not the answer right? And ~'t' doesn't evaluate to a character.
Answer: If an argument is passed to the program (i.e. the first argc != 2 check doesn't fail) then the expression argv[1][0] != ~'t' will always be true (as well as the other checks but those won't be made because of short-circuit evaluation).
The expression ~'t' will first be converted to an int (see this reference for why, the same thing will happen to argv[1][0]). That means you will have ~0x00000074 (if using the ASCII alphabet and 32-bit int). That will evaluate as 0xffffff8b.
It doesn't matter what argument you give your program, argv[1][0] will never be equal to 0xffffff8b and so the condition is true.
Comment: `char` is normally 8 bits, so use a character from outside ASCII. It should certainly be possible on all common platforms.
Comment: They can compare as equal if `char` is signed.
Comment: `'t'` is actually already of type `int`. The C language is irrational in many ways.
Comment: @interjay Only if the character is `0x8b`, and in normal standard ASCII that's not possible (it's a 7-bit encoding).


how to remove sql developer - 220.127.116.11.1703 on ubuntu 20.04

Question: i installed sqldeveloper-184.108.40.206.1703-no-jre.zip
and now i cant remove it
i tried using sudo apt remove sqldeveloper
this error come up :E: Unable to locate package sqldeveloper
Comment: Why do you expect apt remove to work when you did not install it using apt? Please find the readme.txt or install.txt or the uninstall.txt or uninstall.sh in the directory you unzipped this. There will be one of those. I would expect you need to "rm" the direcotory since you unpacked a zip, you did not install that zip.  Maybe the contents of it and if so: find the file inside the zip.
Answer: Following @Rinzwind 's comment on your question, this did the job for me:
sudo find / -name "*sqldeveloper*" -type d -exec rm -vR {} \;

You can even do it in two steps if you wanna make sure you're not deleting folders you might need (e.g university folders, ...) :

step 1: sudo find / -name "*sqldeveloper*" -type d

This allows you to see all of the folders with the name "sqldeveloper" in it, you can even precise how deep should the find command search using -maxdepth N where N is the maximum level of depth it will go to (exp: 3).

step 2: Remove them one by one manually using :

rm -vR /the_path_of_the_folder_to_remove

apt remove sqldeveloper

does not work because sqldeveloper is installed by being unzipped, and not using apt-get install .

how to remove sql developer - 21.2.1.204.1703 on ubuntu 20.04


Why can't I take screenshots of Persona 5?

Question: While playing Persona 5 (finally) last night, I came across a funny scene that I wanted to show a friend. However, when I hit the Share button, the "Save Screenshot" and "Save Video Clip" options were disabled. I am completely sure that I have enough space on my system to save screenshots or video clips, so what's going on?
Answer: In order to prevent spoilers, ATLUS blocked the PS4's native share functionality for the entirety of the game. This includes saving screenshots and videos. Thus, this isn't an issue with your PS4, it's a restriction placed on the game itself.
For reference, see this article:

Atlus confirmed to Polygon that because Persona 5 is such a story-based game, the company made the decision to prohibit players from sharing content.
"This being a Japanese title with solely a single-playthrough story means Japan is very wary about it," an Atlus representative said. "Sharing is currently blocked through the native PS4 UI."

Note: as mentioned by @MadMAxJr in the comments, this includes screenshots typically taken when earning trophies. Thus, there will not be any screenshots taken when earning trophies in this game.
Comment: It even blocks the screenshots that are usually taken when you earn a trophy.  So mementos of your progress are not allowed either.
Comment: @MadMAxJr I just confirmed this. I'll add it to the answer!
Comment: *"there will not be any screenshots taken when earning trophies in this game"* not like those screenshots were worth anything anyway. most of the ones i have are black screens, badly frames or menus


Not getting company info

Question: I am new to this linkedin api. I have made a small example which is working when I am using the keyword search by using the following url:
https://api.linkedin.com/v1/company-search:(companies:(id,name,universal-name,website-url,industries,status,logo-url,blog-rss-url,twitter-id,employee-count-range,specialties,locations,description,stock-exchange,founded-year,end-year,num-followers))?keywords={IBM}&oauth2_access_token=<access Token>

But when I am searching any company info by using the email-domain search then it is giving me 403 error:
<error>
  <status>403</status>
  <timestamp>1432820120642</timestamp>
  <request-id>XLWN5Y7T7R</request-id>
  <error-code>0</error-code>
  <message>Member 385883298 does not have permission to get company 66028</message>
</error>

I am using the following url for this:
https://api.linkedin.com/v1/company-search:(companies:(id,name,universal-name,website-url,industries,status,logo-url,blog-rss-url,twitter-id,employee-count-range,specialties,locations,description,stock-exchange,founded-year,end-year,num-followers))?email-domain=ibm.com&oauth2_access_token=<acess Token>

So as you have posted your answer which is related to this problem I guess you are saying that I have to be the administrator for the company page for which I am searching. As like in my above url i.e. email-domain=ibm.com. If I am wrong or not getting the things, please guide me.
Thanks
Comment: I am not sure what is the purpose of the last paragraph of the questions statement. It is making things confusing as I don't see anyone who posted an answer yet.
Comment: Sorry actually some related answers I fond while googling for this issue so by mistake I written this.
Answer: As part of the recent changes to the LinkedIn API - you are required to be the administrator of the company you are making API calls on behalf of.  As a result, the company search calls are no longer openly available.
You can make a call to check whether the authenticated user is an Administrator of a given company like this:
https://api.linkedin.com/v1/companies/{Insert CompanyID here}/relation-to-viewer/is-company-share-enabled?format=json

This will return a boolean value.  If true, you're good to go.  If false, you'll need to get an existing company admin to grant the user company administrator status using the tools available on www.linkedin.com
Comment: Is there any other alternative to use company API ?
Comment: @Justin, can you elaborate on what you mean by using the administrators account to make API calls? I'm trying to figure out why the LinkedIn feeds have disappeared all of a sudden. The url being used is `https://api.linkedin.com/v1/companies/{0}/updates?oauth2_access_token={1}` but I get the same error on the OP is seeing. Where does the admin come into it?
Comment: LinkedIn must recognize you as an administrator for the company that you are making the API call on behalf of.  Prior to May 12th, this was not a requirement, but it is now.

I've updated the original answer with details on how to determine if the user is an admin that can make the call or not.

Not getting company info


Create a Webhook when installing an app in Shopify

Question: I'm developing an app to sync Shopify product list with my own DB.
When a product is deleted from Shopify admin, I need to delete it in my MySQL DB.
I think I have to create a Webhook for product deletion.
I know the way to create Webhooks in Shopify admin page, but I'd like to create it when my app is installed.
Please give me your answer if you have any idea.
I've tried to find answers for this problem, but couldn't find any solution.
Comment: I just typed "shopify api create webhook" into Google, and found [How to Create Shopify Webhooks With the Shopify API Tutorial](https://hookdeck.com/webhooks/platforms/how-create-shopify-webhooks-with-shopify-api-tutorial) in no time.
Comment: It depends, if Shopify when Webhooks is configure uses a DB to store the code, then the question is whether you can get access to the table where the Wbhook is stored? On the other if the Webhoos are store in folder/directory where Shopify reads/includes/requires the Webhook from then you need to know the location and drop you Webhook there. Does Shopify document it's internal configuration, internal working of how Webhooks are loaded in the Shopify platform?
Comment: Please follow [ask] when asking questions
Answer: I suppose you are looking for automated Webhook Subscription via API. Yes, Shopify does allows that.
You need to Subscribe to the hooks via API call when you app is being installed or autorized by the Shopify store. Please check the Documentations below.
For understanding the webhooks and behaviours: https://shopify.dev/apps/webhooks
Apis for Webhook Subscription: https://shopify.dev/api/admin-rest/2022-10/resources/webhook


Scrapy: ROBOTSTXT_OBEY=True gives an error

Question: When setting ROBOTSTXT_OBEY=True in scrapy settings I get the following error:
    TypeError: to_bytes must receive a unicode, str or bytes object, got list.
I've tried multiple websites to see if it was an issue with the robots.txt file, but i get the same error for all websites.  Even for google
    scrapy shell https://www.google.com/ --set="ROBOTSTXT_OBEY=True"
TypeError: to_bytes must receive a unicode, str or bytes object, got list

How can I respect robots.txt and crawl using scrapy?
Answer: Found out the issue.  When USER_AGENT is set I get the error.  If no USER_AGENT is set then ROBOTSTXT_OBEY=True works without error.
Comment: Consider opening a feature request in https://github.com/scrapy/scrapy/issues/ to ask for a better error message in this scenario.


What's this material of my deck?

Question: I always thought my deck is wood, but my neighbor came and said it's not. Now I'm in doubt. Anyone can identify the material and how to maintain it? Do I need to use sealer on it? Thanks!
Comment: Do not know the material, but think it is some kind of moulded plastic/composite material.  It should be maintenance free.
Answer: The material looks to be TREX. It is widely available from a number of sources.
Here is the Care and Cleaning Guide
In the event the product is not Trex, the care and cleaning for most all composite decking is the same.

What's this material of my deck?


Does my Remote Light bulb use power when not turned on?

Question: I just recently bought an RGB light bulb which comes with a remote and I was wondering if you turn it off with the remote but you leave the switch on does it still consume power?
Answer: Yes, but we're talking minimal usage. The bulb has to listen for your remote so it's using something.
Comment: Worth measuring how much, though: depending on the quality of the design, it could be anywhere from microwatts to a watt or more.
Comment: @Mark [This thread](http://cocoontech.com/forums/topic/10326-power-consumption-of-automated-light-switches-when-off/) from years ago (about automated switches) showed X10 lamp remote switches (similar technology) at 0.1A and 0.02W. I would expect about the same from a modern bulb


Please verify my proof of the ratio test and my reasoning about it. (I want to post it as an answer to another question).

Question: I recently asked the question What is the reasoning behind why the ratio test works? Although the answer of a user has been up-voted, as a college student who is just learning the concept, I did not initially find it illuminating at all. In the interest of posting an answer that is understandable to people such as myself, I sought to formulate a more detailed answer. I would appreciate it if you, the good people of MSE, could review my elaborated reasoning about the proof, to verify that it is correct to post as an answer.
I would also like to thank the user dxiv for their help in the question Help with reasoning about a component of the wikipedia proof for the ratio test.
The proof is as follows.
The hypothesis is that if $L = \lim_{n \to \infty}\begin{vmatrix}{ \dfrac{a_{n+1}}{a_n} }\end{vmatrix} < 1$, then the series $\sum_{n=1}^{\infty}a_n$ converges absolutely.
One way to prove that a series converges is by bounding its value.  The series is already bounded from below, since $L \ge 0$. This is because we are taking the absolute value of $\dfrac{a_{n+1}}{a_n}$. Therefore, we can show that the series converges absolutely by showing that its terms will eventually become less than those of some (any) convergent geometric series.
Let $r$ be the common ratio of some convergent geometric series.
As a random example, let $r = \dfrac{L + 1}{2}$, where $0 \le L \lt 1$. Here, $\dfrac{L + 1}{2}$ is defined as being the mid-point between $L$ and $1$.
$r$ is claimed to be strictly between $L$ and $1$.
We can verify this:
$r = \dfrac{L + 1}{2}$
$\Rightarrow 2r - 1 = L$
$\therefore 1 > 2r - 1 = L \ge 0$
$ \Rightarrow 2 > 2r = L + 1 \ge 1$
$\Rightarrow 1 > r = \dfrac{L + 1}{2} \ge \dfrac{1}{2}$
$\therefore 1 > r = \dfrac{L + 1}{2} \ge L \ge 0$, since $0 \le L \lt 1$.
As stated in the hypothesis, we know that $|a_{n+1}|$ is defined to be the next term in the series. $|a_n|$ is defined to be the current term of the series.
As previously stated, we have already bounded the series $\sum_{n=1}^{\infty}a_n$ from below. We must now bound it from above.
What does it mean for the series to be bounded from above? It means that $|a_{n+1}|$ (the next term in the series) cannot exceed $|a_n|$ (the current term in the series).
We also defined $r$, where $1 > r \ge L \ge 0$, to be the common ratio of a convergent geometric series. This makes sense, since we know that if $|r| < 1$, the geometric series is convergent.
Therefore, we are saying:
$|a_{n+1}| < r^n|a_n|$
$\Rightarrow \sum_{n=1}^{\infty}|a_{n+1}| < \sum_{n=1}^{\infty}r^n|a_n|$
$|r| < 1$
$\therefore \sum_{n=1}^{\infty}|a_{n+1}| < \sum_{n=1}^{\infty}r^n|a_n|$, where $\sum_{n=1}^{\infty}r^n|a_n|$ is convergent.
As have proven, $\sum_{n=1}^{\infty}|a_{n+1}|$ is bounded from above and must therefore also be convergent.
Thank you.
Answer: Use
$$
2=1+1>1+L>L+L=2L
$$
to find $1>r=\frac{1+L}2>L$.
You get $\left|\dfrac{a_{n+1}}{a_n}\right|<r$ not for all $L$, but only for almost all, i.e., excluding finitely many, i.e., for all $n>N$ for some $N$.
Then the recursion only tells you $|a_{N+k}|<r^k·|a_N|$.
Now your upper bound for the series of absolutes is a sum of a finite sum and a geometric series,
$$
\sum_n|a_n|\le\sum_{n<N}|a_n|+\sum_{k=0}^\infty |a_N|·r^k=\sum_{n<N}|a_n|+|a_N|·\frac1{1-r}
$$
Comment: As it is, your proof is wrong. The first point is to shorten the first half of your contemplations. The second says that limits are something that happens at (index) infinity, for finite values the sequence might be badly behaved. Then your solution of the recursion $|a_{n+1}|<r·|a_n|$ for $n\ge N$ is completely wrong, as is your use of it in the construction of the majorant.
Comment: $\sum_{k=0}^∞ |a_{N+k}|<\sum_{k=0}^∞ r^k⋅|a_N|$ from $|a_{N+2}|<r·|a_{N+1}|<r·r·|a_N|$, $|a_{N+3}|<r·|a_{N+2}|<r·r^2·|a_N|$ etc.
Comment: @ThePointer: But yesterday in the comments to the previous posts, you already reproduced all this correctly. Why the step-back in this question? Sloppy typing?
Comment: I don't understand what you're saying. Please clarify.
Comment: I think I see what you're saying. But I am still unsure where the finite value series come from?
Comment: My latest comment to yesterday's post was exactly what I posted in the original post. Note that the comment didn't use finite series or $N$. The latest comment reasoned about $\sum_{n=1}^{\infty}|a_{n+i}| < \sum_{n=1}^{\infty}r^i|a_n|$, which is what I've done/posted above. I assumed that this was correct, since it was left with an up-vote (in yesterday's post). Unfortunately, it must have been incorrect. I'm now working to reason about your comments so that I can post improvements. :)
Comment: Your post says $L < r < 1$ but shouldn't it be $ L /le r < 1 $? Also, you said $L < r$ not for all $ L$. However, you also claimed $L < r < 1$. Therefore, we must have $L < r$ for all $L$?
Comment: There is only one $L$, if at all, for each series under consideration. -- Please read again carefully the formulas in your question with emphasis on the indices used and compare them to your previous efforts.


How to merge the values of list1 with list 2?

Question: I have two lists:
list1 = ["red", "green", "blue", "yellow"]
list2 = ["car", "tree", "house", "guitar"]

My desired output is a new list:
list3 = ["red house", "red guitar", "red tree", "red car", "green house", "green guitar" etc]

I guess I need a for loop that iterates through list 1 and combines the i with the value/index in list 2 (and adding a string " "). But I can't figure out how to do that without getting errors.
Thank you for your help.
Comment: Please update your question with your code that gives you errors. Please also include the full error traceback.
Answer: Try this
list1 = ["red", "green", "blue", "yellow"]

list2 = ["car", "tree", "house", "guitar"]

list3 = []

for i in list1:
    for j in list2:
        list3.append(i+" "+j)

or in more pythonic way
list1 = ["red", "green", "blue", "yellow"]

list2 = ["car", "tree", "house", "guitar"]

list3 = [i+" "+j for i in list1 for j in list2]

Comment: For sure the second way is more pythonic, even if there are two for loops into the comprehension. +1
Comment: I always refer to this [answer](https://stackoverflow.com/a/45079294) for a visual way of converting between nested for loops and a list comprehension.  (+1 btw)
Answer: As an alternative solution you can use itertools.product like below:
>>> import itertools

>>> list1 = ["red", "green", "blue", "yellow"]
>>> list2 = ["car", "tree", "house", "guitar"]

>>> list(itertools.product(*[list1 , list2]))
[('red', 'car'),
 ('red', 'tree'),
 ('red', 'house'),
 ('red', 'guitar'),
 ('green', 'car'),
 ('green', 'tree'),
 ('green', 'house'),
 ('green', 'guitar'),
 ('blue', 'car'),
 ('blue', 'tree'),
 ('blue', 'house'),
 ('blue', 'guitar'),
 ('yellow', 'car'),
 ('yellow', 'tree'),
 ('yellow', 'house'),
 ('yellow', 'guitar')]

>>> list(map(' '.join , (itertools.product(*[list1 , list2]))))
['red car',
 'red tree',
 'red house',
 'red guitar',
 'green car',
 'green tree',
 'green house',
 'green guitar',
 'blue car',
 'blue tree',
 'blue house',
 'blue guitar',
 'yellow car',
 'yellow tree',
 'yellow house',
 'yellow guitar']

You can use this solution for more than two lists:
>>> list1 = ["red", "green"]
>>> list2 = ["car", "tree"]
>>> list3 = ["here", "there"]
>>> list(map(' '.join , (itertools.product(*[list1 , list2, list3]))))
['red car here',
 'red car there',
 'red tree here',
 'red tree there',
 'green car here',
 'green car there',
 'green tree here',
 'green tree there']


Are the answers solved to these questions correct or wrong?

Question: Functions f and g are given as f(x) = x^2 - x and g(x) = 2x - 3,
(a) Find f(0), f(-1), g(0) and g(-1).
(b) If f(x) + g(x) = 3, find x.
(c) If f(p) + g(-p) = 1 , find p.
(d) If f(z) = g(z) + 1, Find z
I found my answers as follows:-
(a) f(0) = 0, f(-1) = 0, g(0) = -3, g(-1) = -5
(b) x = 2 or x = -3
(c) p = -1 or p = 4
(d) z = 1 or z = 2
Correct me if am wrong!
Thank you.
Comment: Perhaps you could show your work for each part.
Answer: i have got $$f(0)=0,f(-1)=2,g(0)=-3,g(-1)=-5$$
$$x=-3,x=2$$
$$p=-1,p=4$$
$$z=2$$
$$z=1$$
we have to solve $$z^2-z=2z-3+1$$ and this is $$z^2-3z+2=0$$
$$z_{1,2}=\frac{3}{2}\pm\sqrt{\frac{9}{4}-\frac{8}{4}}$$
Comment: Can you show me how you solved for z.
Answer: So far, I managed to find a mistake at point (a):
$$ f(-1) = (-1)^2 - (-1)$$
$$f(-1) = 1 + 1\implies f(-1) = 2$$
Comment: Oh right, how could i have missed that. Thanks.


How to verify if a span of vectors is a subset of another span of vectors

Question:
$\displaystyle b_1=\left\lbrace\frac{12}{9},\frac{12}{9},2\right\rbrace^T,b_2=\{-18,-18,21\}^T$ and $\displaystyle v_1=\{-1,-1,2\}^T,v_2=\{3,3,-3\}^T$. $b_1 \in \operatorname{Span}\{v_1,v_2\} \text{ and } b_2 \in \operatorname{Span}\{v_1,v_2\}$. Can we conclude that (Without performing further verification) $\operatorname{Span}\{b_1,b_2\} \subseteq \operatorname{Span}\{v_1,v_2\}$? What about $ \operatorname{Span}\{v_1,v_2\} \subseteq  \operatorname{Span}\{b_1,b_2\}$?

As the question has provided, both $b_1,b_2$ belongs to the span of $v_1,v_2$. However, the answer key only pointed out that we can only conclude $\operatorname{Span}\{b_1,b_2\} \subset \operatorname{Span}\{v_1,v_2\}$ but not $ \operatorname{Span}\{v_1,v_2\} \subset  \operatorname{Span}\{b_1,b_2\}$ without any further explanation.
Is the fact that both $b_1 \in \operatorname{Span}\{v_1,v_2\} \text{ and } b_2 \in \operatorname{Span}\{v_1,v_2\}$ implies that $\operatorname{Span}\{b_1,b_2\} \subseteq \operatorname{Span}\{v_1,v_2\}$ ?
More generally, as my question's title suggests, how do I verify if a Span of vectors is a subset of another span of vectors? (I am capable of verifying if a single vector belongs to a span of vectors) but I can't make any connections between the two
Comment: You should write $span \{b_1,b_2\} \subseteq span \{b_1,b_2\} $ and not $span \{b_1,b_2\} \in span \{b_1,b_2\} $
Comment: Oh I didn't notice that. Thanks for pointing that out
Answer: If $b_1 \in \text{Span}(v_1, v_2) $ and $b_2 \in \text{Span}(v_1, v_2)$, then $\text{Span}(b_1, b_2) \subset \text{Span}(v_1, v_2)$.
Proof:
$b_1 \in \text{Span}(v_1, v_2) $ $\implies $ $b_1 = k_1 v_1 + k_2 v_2$. Similarly, $b_2 \in \text{Span}(v_1, v_2)$ $\implies $ $b_2 = c_1 v_1 + c_2 v_2$.
Hence, an arbitrary vector $w \in \text{Span}(b_1, b_2)$ satisfies
\begin{align}
  w &= m_1 b_1 + m_2 b_2\\
    &= (m_1 k_1 + m_2 c_1) v_1 + (m_1 k_2 + m_2 c_2 ) v_2
\end{align}
This implies $w \in \text{Span}(v_1, v_2)$. Hence, $\text{Span}(b_1, b_2) \subset \text{Span}(v_1, v_2)$.
End Proof
If $b_1 \in \text{Span}(v_1, v_2) $ and $b_2 \in \text{Span}(v_1, v_2)$, then $\text{Span}(v_1, v_2) \subset \text{Span}(b_1, b_2)$ is in general False.
Counterexample
Take $b_1 = b_2 = v_1$. Then, Span$(b_1, b_2)$ = Span$(v_1)$. Hence,  $\text{Span}(v_1, v_2) \nsubseteq \text{Span}(b_1, b_2)$
Response to comments:
If $b_1 \in \text{Span}(v_1, v_2) $ and $b_2 \in \text{Span}(v_1, v_2)$, then $\text{Span}(b_1, b_2) \subset \text{Span}(v_1, v_2)$.
Now if $\text{Span}(b_1, b_2) \subset \text{Span}(v_1, v_2)$  and dim(Span($b_1, b_2$)) $=$ dim(Span($v_1, v_2$)), then indeed Span($b_1, b_2$) $=$ Span($v_1, v_2$). This follows from a general rule that any subspace $A$ of a vector space $V$ satisfying dim$(A) = $ dim($V$) implies that $A = V$.
Comment: So if I have another vector, $v_3$ that is in the span, can I say then: Span($v_1,v_2,v_3$) $\subset$ Span($b_1,b_2$)? (Just this seems bit weird as we are having a 3-vector set span as a subset of a 2-vector set span)
Comment: yes that is true. I edited my answer to insert a short proof.
Comment: Yes that is true. Another way to see this is that the subspace Span$(v_1, v_2)$ has the same dimension as the parent vector space Span$(b_1, b_2)$ so they must be equal.
Comment: Thanks a lot! I have done some further "investigation" I found that in this particular questions, $b_1,b_2$ also are in Span($v_1,v_2$). So I think we can conclude that, along with Span($v_1,v_2$) $\subseteq$ Span($b_1,b_2$), Span($v_1,v_2$) $=$ Span($b_1,b_2$) (Since they are both subset of each other, so they must equal). Is my reasoning correct?
Comment: Thanks a lot! It is much clear now
Answer: As @ironX & @pietro said, and also by definition of vector spaces, they contain the $Span$ of any subset of themselves. But for inverse, also as they said truly, you can't conclude it. Of course, if you are curious to find such condition:
If you have $\dim(Span\{ v_1, v_2 \}) \leqslant \dim(Span\{ b_1, b_2 \})$, beside $Span\{ b_1, b_2 \} \subseteq Span\{ v_1, v_2 \}$, then you can conclude the inverse: $Span\{ v_1, v_2 \} \subseteq Span\{ b_1, b_2 \}$ and so they become equal with equal dimension.
In some cases investigating the independency of vectors can help much.
Answer: Indeed you cannot say that $Span\{v_1,v_2\} \subseteq Span\{b_1,b_2\}$ in general. To see that consider the trivial case where:
$v_1=\begin{pmatrix} 1 \\ 0 \end{pmatrix}$, $v_2=\begin{pmatrix} 0 \\ 1 \end{pmatrix}$
and $b_1=b_2=\begin{pmatrix} 1 \\ 0 \end{pmatrix}$.
It is clear that $Span\{b_1,b_2\}=Span\{b_1\} \subseteq Span\{v_1,v_2\}$ but not the contrary (you cannot generate $v_2$ using $b_1$).
Now, about your question "Is the fact that both $b_1 \in Span\{v_1,v_2\} \text{ and } b_2 \in Span\{v_1,v_2\}$ implies that $Span\{b_1,b_2\} \subseteq Span\{v_1,v_2\}$ ?" The answer is yes.
To see that, go back to the definition of $Span\{v_1,...,v_n\}$ : it is the set of vectors that can be genereated by a linear combination of $(v_1,...,v_n)$.
In your case, as $b_1$ and $b_2$ can be computed as linear combinations of $v_1$ and $v_2$, thus any linear combination of $b_1$ and $b_2$ can be computed as linear combinations of $v_1$ and $v_2$. Hence the result.
Now a general method to see if a Span of vectors $b_1,...,b_k$ is a subset of another span of vectors $v_1,...,v_k$ is to check if for all i in 1,...,k $b_i$ is a linear combination of $v_1,...,v_k$.
Hope it helps you!


How can I tell if my vinyl floor is inlaid or contains asbestos?

Question: I'm removing the flooring sheets from an apartment, and I'd like to figure out whether it's linoleum (as we've been calling it this whole time) or vinyl sheets or what else.
Here a picture (more can be found here):

I'm wondering:

Would you know whether it's Linoleum or Vinyl or what else? According to what I read on the internet I believe it's most likely Vinyl flooring (no uniform color, the sheet itself is just a couple of millimeters thin, it was installed around the '70s etc).
How do I get rid of it? They say Vinyl flooring is made of PVC and is quite toxic. A dumpster is the way, isn't it?
Most likely there's no asbestos, right? I'm just being paranoid here, since on the internet they seem to link vinyl flooring to asbestos a lot.

The apartment is located in a 14 store mid-to-low-end apartment building built in 1969 in West Berlin (West Germany), if this can help.
Thanks!
Answer: In the US at least, asbestos was used during and after the 70's. I can't speak for Germany.
To really know if it contains asbestos or not you'll need to test it. In the US at least you can get a kit for about $10 to collect a sample. Then it's another $40 or $50 for a lab to test your sample.
I'd say it's linoleum based on the fiber backing. See if you can melt it with a burning match - vinyl will melt easily but linoleum won't. Do this with a small sample (don't try to light your floor on fire...) and have a way to put it out.
To find out what to do with it, call whoever takes your trash away. The law regarding trash disposal will vary a huge amount by jurisdiction so it's tough to answer exactly.
Answer: Linoleum™ is a brand name as well as a material, which makes it somewhat ambiguous here. You're referring to "inlaid" vinyl, where the color is all the way through, as opposed to modern vinyl with a transparent wear layer. Incidentally, Linoleum™ is still in production by Armostrong, and not all of it is inlaid.
It's more accurate to say that PVC is made from vinyl, or is a type of vinyl, than the other way around. It stands for polyvinyl chloride, and it isn't usually recyclable.
I'm not able to tell you where there's asbestos in your building from a photo. Get help from a local inspector if needed.
Comment: You can certainly make a pretty good guess by looking at tile and its attributes on whether it has asbestos or not.  Not sure you have an answer here.
Comment: *I* can't. *You* may be able to. And I'm not sure guesses are appropriate with regard to asbestos. Feel free to vote accordingly.
Comment: Just to clarify, "PVC" stands for Poly VINYL Chloride. the chemical composition of what we generically call "vinyl", whether it be flooring, pipes, toys, cooking utensils etc. It's all the same basic material and if it were considered a hazardous material, we are all in trouble!
Answer: Buy an asbestos testing kit, follow the directions to take a sample, and mail it to the testing company.
If it has asbestos you will have to follow local codes to dispose of it - in many districts it may not actually be regulated for homeowners and you can dispose of it in regular garbage/dumpster.  I would wear gloves, mask, etc and dispose of them when done, but supposedly it is stable in tile form and shouldn't be a problem unless you grind or powder it.  Do not take my advice as 100%, please check with a professional.


Unable to read memory for HWND in Win32 API

Question: I'm trying to figure out how to close an application (i.e. Mozilla Firefox) sing its HWND. But when I do something like this:
HWND hwnd = FindWindow("MozillaWindowClass", 0);
DestroyWindow(hwnd);

Visual Studio's debugger tells me that hwnd is unused - unable to read memory and nothing happens to Firefox. I was wondering what I'm doing wrong
Thanks
Comment: `HWND` is an opaque type. The value is merely a handle; there is no memory to see.
Comment: Are you sure you can safely close an application by simply annihilating one of its windows? Why do you want to do this? What is your goal? Kinda looks suspicious, to me.
Comment: After you actually get a handle to the window, Send WM_CLOSE message.
Comment: Don't discard the only option that actually does have a chance of working reliably: [UI Automation](https://msdn.microsoft.com/en-us/library/windows/desktop/ee684009.aspx).
Answer: If you check the documentation for DestroyWindow it says:

A thread cannot use DestroyWindow to destroy a window created by a
  different thread.

You could try using SendMessage to send a WM_CLOSE message to the application.
Comment: Thanks for your help. I have no idea why SendMessage wasn't working earlier.


Multiple commands in a Trigger (Update multiple columns with different conditions)

Question: I have an issue which i'm hoping someone out there will be able to assist.
I'm trying to write a trigger which takes the datetime stamp and puts just the date into a new column. But likewise, also if a value in a different column is equal to x, then replace it with y.
I can get individual statements to work (i.e if I have just the date code or the replacement code individually it works fine), but I can't get them to both work in the same trigger.
SET NEW.date = LEFT(NEW.entrydate, 10);
IF
    (NEW.connect_ip = "184.108.40.206")
    THEN SET
    NEW.connect_ip = "0.0.0.0";
    END IF

Answer: Multi-statement triggers need BEGIN and END around their "body", and usually DELIMITER overridden around their declaration.
Example/Template:
DELIMITER $$

CREATE TRIGGER [blah blah]
BEGIN
   [do stuff]
END$$

DELIMITER ;

Alternatively, for your specific case, I noticed an answer the other day with a possiblity I had overlooked; you can set multiple things in a SET statement:
SET NEW.date = LEFT(NEW.entrydate, 10)
    , NEW.connect_ip = IF(NEW.connect_ip = "220.127.116.11", "0.0.0.0", "184.108.40.206")
    ;


First Proth number with a million digits

Question: I am examining the Proth numbers $n = h\cdot 2^k+1$, where $k$ is an integer and $h<2^k$ an odd integer.
Now I want to find the first Proth number with a million digits.
But I hve no idea how I could solve this.
So I know that we get the number of digits of $n$ by $\lfloor \log_{10}(n)\rfloor + 1$.
So I write
$$
\log_{10}(n)
= \log_{10}(h\cdot 2^k+1)\approx \log_{10}(h) + k\cdot\log_{10}(2).
$$
But how would I go on from here?
Answer: The binary expansion of $n=h\cdot 2^k+1$ looks like this:
$$\underbrace{1\ldots 1}_{\le k \text{ digits}}\;\;\;\;\underbrace{0\ldots0}_{k-1\;0's}1$$
So you take the binary expansion of $10^{999,999}$, and look for the least significant zero digit that is no more than half-way from the start; then replace this digit by $1$, replace all less-significant digits with $0$, and add $1$.
Comment: @Lereu: $h$ is the number defined by those initial $\le k$ digits.
Comment: To make it a bit clearer, let's try $3$ digits instead of a million.  $10^2 =1100100$ in binary.  This is $7$ bits: the third one  happens to be $0$, so we replace that by $1$, replace the less-significant digits by $0$, and then add $1$, obtaining $1110001$ in binary or $113$ in decimal, i.e. $113 =  7 \cdot 2^4 + 1$ is the first Proth number with $3$ decimal digits.
Comment: @Lereu: A good question! In this special case, you have to add a leading $0$, and that becomes the least significant zero digit. So you get $1111101000_2\to 01111101000_2\to 10000000001_2=1025$, with $h=1$ and $k=10$.
Comment: No, the _least_ significant zero digit that is no more than half-way from the start is in the sixth place:
$$11000\color{red}{0}11010100000_2\to 11000\color{red}{1}00000000001_2=100353$$

Which looks like a Proth number to me!
Comment: shouldn't there be an $h$ in the binary expansion, too?
Comment: Oh I see, thank you for clarification. Yet i have problems to get to the solution. I don't really understand what to do now.
Comment: @RobertIsrael Thank you, I understand that. But if I try it with 4 digits, I have $10^3 = 1111101000_2$, so there is no 0 half-way from the start. What do i do?
Comment: @TonyK Thank you, but I guess the formula is wrong, e.g. $10^5 = 11000011010100000_2$. So this becomes to $11100000000000001_2 = 114689$. But the first Proth number with 6 digits is $100865$.


How to queryset all user that are in a foreign table?

Question: I have a model called book and in that model there is a foreignkey field (called author) to the user model.
I need in one of my views to returm a list of all the authors(not all users, just users that appear in the book model(just the authors).
I don't know why, but i'm having a hard time getting that.
Can any one please help me with this?
10x,
Erez
Comment: It's easier to answer questions like this when you show your models, or a simplified version of them.
Comment: I'm sorry, usualy i put some code, but I thought that in this case it is not relevant....If needed i will do that :-)
Answer: Try this:
User.objects.filter(book__isnull=False).distinct()

I'm assuming there is only one foreign key from the Book model to the User model.

isnull filters for all users which are in the which are linked to the Book model.
distinct ensures that each author only appears once in the results.
Comment: First, 10x, i'm trying what you wrote but i am having a new problem... Can i use a related_name instead of the the User model? I have a related name in the Book model for the author field that is called book_author, beacouse the reverse loop for User take to another model..... so, Can i user the selated_name instead?
Comment: If the foreign key to User has a related name, replace book__isnull with related name__isnull.
Comment: I can't reply again until next week, so if my comment above doesn't help, hopefully somebody else can.
Comment: 10x, working great, no i know how to do outer join in (kind of...) in django :-) This is soooooo cool :-)


Go: cannot package in symlink

Question: I have one go project. In this project, for example I have a lib_project that is a symlink to another directory, for example: github_project
After I pull source code to local, I update another git submodules (github_project is one submodule). And then I go here and compile project.
After that, I go to my main project and try to run command go. I meet exception:
package github.com/main_project/test.go: cannot find package "github.com/main_project/lib_project/some_random_file.go" in any of:

        /usr/local/Cellar/go/1.7.1/libexec/src/github.com/main_project/lib_project/some_random_file.go (from $GOROOT)

        /Users/my_user/Documents/go/src/github.com/main_project/lib_project/some_random_file.go (from $GOPATH)

I have tested and see that the directory github.com/main_project/lib_project/some_random_file.go is exsit. I can cd to this and open file. That looks like Go doesn't recognize symlink folder (in this case is lib_project)
Answer: The Go tools purposely don't follow symlinks. Make sure there aren't any in your GOPATH, and always use the full import path relative to $GOPATH/src/ for installed packages, and relative to the vendor/ directory for vendored packages.
Comment: FWIW you *can* symlink local packages from within vendor sub-directories. I use this extensively to [in-git-repo development](https://git.kernel.org/pub/scm/libs/libcap/libcap.git/tree/go/Makefile) build-tree test the [libcap/cap](https://pkg.go.dev/kernel.org/pub/linux/libs/security/libcap/cap) and [libcap/psx](https://pkg.go.dev/kernel.org/pub/linux/libs/security/libcap/psx) packages.

Go: cannot package in symlink


The shape change when the window decrease with svg

Question: I'm currently working on a website and I need help on a svg trapezoid shape.
I decided to use SVG because, before that, my trapezoid was realized with css and the main problem with that is that is wasn't responsive as I expected.
This is the shape I would like : Trapezoid.
I've already realized this shape but the problem is when the window size decrease the shape look like that.
So my question is, does there any ways to "lock" the points to keep the shape of the 1st image ?
HTML :
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="84%" height="200" preserveAspectRatio="none">
                    <polygon fill="blue" points="1.5 0, 100 0, 85 100, 1.5 100"/>
                        ...
        </svg>
Edit:
Thanks to Paulie_D, i've patched my problem with :
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100%" height="200" preserveAspectRatio="xMaxYMin slice" class="spaceBetweenButton" >
    <polygon fill="#00a8f3" points="1.5 0, 100 0, 0 100, 1.5 100"/>
        ...
</svg>
But now I would like to add another trapezoid at the right of the 1st like that but as before, my problem isn't on how to realize the shape but on how it render with this code :

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100%" height="200" preserveAspectRatio="xMaxYMin slice" transform="rotate(180)" class="spaceBetweenButton">
        <polygon fill="#00a8f3" points="0 0, 130 0, 0 130, 0 130" />
    </svg>

And how it appear. At first sight I thought that the problem was in the preserveAspectRatio so I've tried to replace it by xMaxYMin slice off but I didn't found a way to have a decent result with it.
So I have 2 problem, how to extend the right trapezoid (I think it's with the width of the svg) and how to move it on the left. I've tried to add margin but the space between the 2 trapezoid changes when we resize the window.
Thanks for your help.
Valentin.
Comment: "`preserveAspectRatio="none"`" is probably a clue.
Comment: You fixed the height and width is dynamic, so the shape will change to maintain the dimensions. Either make the height dynamic or fix the width. From the image it looks like you shouldn't have any problem if the image moves out of view towards left, so I propose `{ width: /* Some fixed value */, position: absolute; right: 0; }` and on parent `{ position: relative; overflow: hidden; }`
Answer: Just add another polygon to your SVG.

Move the right hand end of the first polygon left a bit
Add a second polygon of the right shape, to the right of that, leaving an appropriate gap.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100%" height="200" preserveAspectRatio="xMaxYMin slice" class="spaceBetweenButton" >
    <polygon fill="#00a8f3" points="0 0, 83 0, 0 83"/>
    <polygon fill="#00a8f3" points="85 0, 100 0, 100 100, 0 100, 0 85"/>
</svg>


What does the symbol with a shield and two swords next to clan members' names mean?

Question: When I open my clan roster, I now notice there is a symbol that has a shield + two swords next to most clan member's name.  What does this signify?  Are they ready for clan battles?
Answer: This symbol means that those player can participate in clan's war, The other players who don't have it are spectators and they can't participate in war.
The logic behind that is like this :

If a player join your clan after you started the war they will become a spectator and will not be able to actively participate in the clan war.
If your clan members are more than enemy's clan, The players who have lowest trophies    will become spectator so both clans have the same number of members ( e.g 30 vs 30 or 45 vs 45)
Comment: This has now changed.. You can opt in and out any members of your clan.
Answer: Also there's another icon you can have besides the bronze shield with crossed swords. You can have a dull silver or grey shield with crossed swords and a red line or bar underneath it. This mean you are ineligible to participate in a clan war for a period of time. I was in a clan and I started a war then left my clan for another clan. I have to wait until my old clan finishes the war that I abandoned before I can participate in another war. If you click on the "i" icon next to your blue level in the top left hand corner it will show your player profile. On the top left it will show the bronze shield with two crossed swords symbol for coc clan wars and say how many days or hours left until uou are eligible to participate in a clan war again.


In Java, how do I see if an object is of the right type to be passed as a method parameter? Especially if the type is a primitive?

Question: I'm using reflection to call a method in Java. I'd like to see if the value that potentially is to be passed into the method is of the right type before I invoke the method.
My initial idea was to get the class of the parameter via method.getParameterTypes() and then compare that type to the type of the object that I'd like to pass in. If it's a subclass, then proceed.
However, this fails on a method that takes a primitive. If I have a method:
private void doThing(boolean parp) {}

The return value of getParameterTypes for this indicates that the type of the parameter is a class  called boolean in the java.base module. However, I might be wanting to pass in a value which is of type java.lang.Boolean, which although is perfectly legal to pass in, doesn't sit in the type hierarchy. java.lang.Boolean isn't a subclass of, or apparently in any way related to boolean.
What test can I use against a method's given parameter type and the type of a given object to determine whether its legal to pass that object into the method?
Comment: `MethodType type = MethodType.methodType(method.getReturnType(), method.getParameterTypes()).wrap();`. You still have to create for `null` validity or primitive value widening conversions yourself if you want to support it.
Comment: You need use pure java, or can use library for resolve that
Comment: The Boolean object can be null, boolean cannot. This applies for int, double and float as well. You can try and do something along this concept.
Comment: @Holger nice. Unfortunately my context is Android API21, and this needs 26 :( Good solution though.
Answer: Like this, perhaps:
private static final Map<Class<?>, Class<?>> primitiveToBoxed = new HashMap<>();
static {
  primitiveToBoxed.put(Boolean.TYPE, Boolean.class);
  primitiveToBoxed.put(Character.TYPE, Character.class);
  primitiveToBoxed.put(Byte.TYPE, Byte.class);
  primitiveToBoxed.put(Short.TYPE, Short.class);
  primitiveToBoxed.put(Integer.TYPE, Integer.class);
  primitiveToBoxed.put(Long.TYPE, Long.class);
  primitiveToBoxed.put(Float.TYPE, Float.class);
  primitiveToBoxed.put(Double.TYPE, Double.class);
  primitiveToBoxed.put(Void.TYPE, Void.class);
}

private static final Map<Class<?>, Set<Class<?>>> allowedConversions = new HashMap<>();
static {
  allowedConversions.put(Short.class, setOf(Byte.class));
  allowedConversions.put(Integer.class, setOf(Byte.class, Character.class, Short.class));
  allowedConversions.put(Long.class, setOf(Byte.class, Character.class, Short.class, Integer.class));
  allowedConversions.put(Float.class, setOf(Byte.class, Character.class, Short.class, Integer.class, Long.class));
  allowedConversions.put(Double.class, setOf(Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class));
}

static <T> Set<T> setOf(T... elements) {
  return new HashSet<>(Arrays.asList(elements));
}

static boolean isCompatible(Class<?> type, Object value) {
  if (type.isPrimitive()) {
    if (value == null) {
      return false;
    }
    type = primitiveToBoxed.get(type);
  }
  return value == null || type.isAssignableFrom(value.getClass())
      || allowedConversions.getOrDefault(type, emptySet()).contains(value.getClass());
}

Comment: Hmmm... this isn't 100% correct; it gives false negatives for widening conversions allowed by reflection. For example, it's legal to pass an `int` to a method that takes a `long` using reflection, but `isCompatible(Long.TYPE, 1)` erroneously returns `false`.
Comment: Okay, updated to support widening conversions. Whew. IMO you might as well just try to invoke the method and catch the IllegalArgumentException ;-)
Comment: @growse Indeed. I wonder if there is a more elegant way to solve the problem. If you find one, please post a self-answer so we can all benefit.


Nesting multiple levels of Jackson WRAPPER_OBJECTs

Question: By no means am I a Jackon/JSON wizard, which is probably evident from the following issue I'm running into:
I have 2 possible data structures I'm receiving.
The first one is called amountTransaction:
{
  "amountTransaction": {
    "clientCorrelator":"54321",
    "endUserId":"tel:+16309700001"
  }
}

Which is represented by the following Java object:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonTypeName(value = "amountTransaction")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AmountTransaction {
  private String clientCorrelator;
  private String endUserId;
  ...
}

However the amountTransaction object also appears as child element of the paymentTransactionNotification object:
{
  "paymentTransactionNotification": {
    "amountTransaction": {
      "clientCorrelator": "54321",
      "endUserId": "tel:+16309700001"
    }
  }
}

..which I thought would be represented by:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonTypeName(value = "paymentTransactionNotification")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentTransactionNotification {
  private AmountTransaction amountTransaction;
  ...
}

Parsing the JSON with the amountTransaction object alone works fine. It's a pretty straightforward example of a WRAPPER_OBJECT.
However when trying to parse the JSON for the paymentTransactionNotification, I'm getting an exception indicating that it can't properly deal with the amountTransaction as element of the paymentTransactionNotification:
com.fasterxml.jackson.databind.JsonMappingException: Could not resolve type id 'clientCorrelator' into a subtype of [simple type, class com.sf.oneapi.pojos.AmountTransaction]

Any thoughts on how I can properly annotate this so my code can properly deal with both stand alone, as well as encapsulated amountTransaction objects?
Comment: I think you should show how you think this should map to a POJO -- I am not quite clear on how it would work, because properties of a POJO have names, and your JSON seems to be missing that part of information.
Answer: By default wrapping root node in Jackson is disabled. You can wrap inner objects but if you want to wrap root node you need to enable jackson feature for it (https://jira.codehaus.org/browse/JACKSON-747):
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE);
objectMapper.enable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE);

When you enabled these features you already said Jackson to wrap the root element and you don't need @JsonTypeInfo and @JsonTypeName anymore. You can simple delete them. But now you need to customize the root node name and you can use @JsonRootName for it. Your classes should look like this:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("amountTransaction")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AmountTransaction {
    private String clientCorrelator;
    private String endUserId;
...............
}

And
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("paymentTransactionNotification")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentTransactionNotification {
  private AmountTransaction amountTransaction;
.............
}

I've tried and Jackson converted both JSON requests as expected.
Comment: I was going to speak to soon and say it wasn't working yet but then I realized I forgot to set the Features on my Unit test objectMapper.

So yeah, this works perfect.

Only note is that in Jackson 2.4.0 the Feature constants have changed a bit:

`objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);`
Comment: I also have similar [question](https://stackoverflow.com/questions/48433294/design-pojo-for-nested-levels-of-a-field-and-extract-id-from-the-last-level) related to nested fields and I am confuse on how can I make nested level POJO and extract id from the last level of `parentCategory`? Wanted to see if you can help me out.


What do different pin colors mean?

Question: The pins dropped by enemy noise come in a few different colors. I've seen yellow, purple, green, and pink. What do the different pin colors mean?
Answer: If you check the Noisepedia, you will see that enemies drop different Pins at different difficulties (and the percentage chance of each).  These Pins are colour-coded when they drop.
"Easy" pins are Green, "Normal" pins are Purple, "Hard" pins are Yellow, and "Ultimate" pins are Red.  These match the colours of each Difficulty on the Difficulty/Level menu.  (The first game also had small Black Pins for Dark Matter, but Neo treats Dark Matter as a normal Pin)
At higher difficulties, "failing" to drop a pin means that it will roll for the next difficulty down, to give you a chance at dropping that instead.  For example, here are example drop rates shown in the Noisepedia, and from battling at each difficulty level (assuming single battle, with no Chain nor Final Remix attack):

Difficulty
Easy
Normal
Hard
Ultimate
No Reward
Notes

Noisepedia
60%
30%
50%
100%
N/A
Base Rates

Easy
60%
0%
0%
0%
40%
Easy Pin or Nothing

Normal
42%
30%
0%
0%
28%
Easy Drop is 60% (Base Drop Rate) of 70% (chance to not get Normal Pin)

Hard
21%
15%
50%
0%
12%
Easy Drop is 60% (Base Drop Rate) of 35% (chance of getting neither Normal nor Hard Pin)

Ultimate
0%
0%
0%
100%
0%
There is a 0% chance to not get an Ultimate pin

There is one significant exception:  Pig Noise do not show a Drop Table in the Noisepedia.  Instead, they have a 100% chance for the battle to drop a single pin (no matter how many Noise are in the battle), the Pin varies based on the specific battle (i.e. the same type of Pig can drop different Pins on Different days), it is the same Pin at every difficulty (no reason not to fight them on Easy — the battles are often closer to Puzzles), and the Pin they drop shows in-battle as a pink Pig's Head, rather than the normal circle.  Also, each Pig can only be fought once per Save-File; even if you replay the day, it will not reappear.
Comment: I believe pink pins drop when fighting pig noise, regardless of difficulty.
Comment: @Stevoisiak Good point, added

What do different pin colors mean?


How can I get my old villager back (I want them to remember me)? - Animal Crossing New Leaf

Question: I want to get Camofrog back and I've heard about the 16 villager cycle. However I don't know where he moved to... so my initial question is... can I get him back if he randomly appears in my campsite? After cycling out 16 villagers, is there a chance he could appear in my campsite again, and if so, will he remember me?
Answer: He/she could reappear in your campsite but will NOT remember you at all. This happened to me and the resident did not remember me


Why isn't my city growing?

Question: It is my first game of Civilization 5, but I have played Civilization 3 and 4 many times. Twice I have seen my capital having a stagnation for no apparent reason. From what I read food is the only reason a city would stagnate. I have even seen a city with more feed than required being in stagnation.
At this moment I have a source of 15 food and 12 are consumed by civilians, so this makes 3 extra food. As I understand it, there is no reason there should be a stagnation, but there is.
I guess there is also a happiness factor, but my happiness is well above unhappiness.
What could cause that? Could it be a bug?
Answer: Whenever you build a Settler, all your extra food goes towards  increasing the production of that unit. Due to this your city will always be stagnant when you're building  a settler, and I'm willing to bet this is what is happening to you.
Comment: @Wipq In Civ 5 this only applies to Settlers.  In Civ 4 it applied to both Settlers and Workers.
Comment: Note that the city AI takes no notice of the fact that you are building a settler, and carries on trying to churn out food. So it's usually worthwhile to change the city focus to Prodution while the settler is being built - it may speed up the settler, and will make no difference to city growth.
Comment: That must be it. Is it new to civ 5? I don't recall that issue in civ 4. And it would explain why a worker takes so long to build, even longer than a library which I recall was the opposite in civ4.
Comment: I can not recall whether it was in Civ 4 or not
Answer: There is an "Avoid growth" option, which prevents city from jumping to the next growth level. Maybe you selected it without knowing
The option is on your right panel, right at bottom of Citizen Management options.

See full detail here: https://i.stack.imgur.com/pQ85c.jpg
Even though the city has enough food to grow it won't grow.
Comment: I am testing this after work. Since I remember it working the other way.
Comment: I just tested it during my break, and you are right.
Comment: It actually does prevent growth
Comment: When I posted this, it worked this way, my city wasn't growing and it drove me nuts until I found that check. Could be it changed since then...

Why isn't my city growing?