Iterating over pandas series in reversed order

Question: How to iterate over pandas series in reversed order?
The regular iteration is:
for index, value in series.items():

How to do it in reverse, something like:
for index, value in reversed(series.items()):

Answer: You can reverse a Series like below:
In [251]: s = pd.Series([0,1,2])

To reverse it:
In [252]: s.iloc[::-1]
Out[252]:
2    2
1    1
0    0

To iterate it, you can do this:
In [254]: for ix, val in s.iloc[::-1].items():
     ...:     print(val)
     ...:
2
1
0


what is Spring boot Admin

Question: I am exploring about jmx. I read about jmx I got JMX is using for monitoring application or device. For monitoring spring boot Application I got two option one is Spring Boot Actuator and Spring Boot Admin. I refer following link for Spring Boot Admin.
http://codecentric.github.io/spring-boot-admin/1.5.7/#spring-cloud-discovery-static-config
I have lot of confusion about Spring boot Admin.

what is it exactly?
why we are  using?
monitoring end point means  what exactly doing?
Is it really need in production environment?

I am new in spring environment. Can anyone help me to clarify my confusions please?
Answer: A short summary:
JMX is a technology that is suitable for monitoring and managing applications. However, it still requires you to write managed beans to set up the monitoring or the managing of your applications.
Spring boot actuator is a library that can be used with Spring boot applications and which will provide:

A framework for creating your own metrics using CounterService, GaugeService, ... (Spring boot 1.x) or Micrometer (Spring boot 2.x)
Automatic generation of certain endpoints (health of the application, metrics, ...) over certain protocols (HTTP/REST or JMX)

Spring boot admin on the other hand is a web application/graphical user interface that works on top of Spring boot actuator to manage Spring boot applications. It also integrates with Spring cloud to automatically discover Spring boot applications.
So, all three mentioned technologies do a different thing, but are often
 used together to monitor Spring boot applications.
Is it really necessary in a production environment? That's up to you to decide, and that's purely opinion-based and not suitable to answer on Stack Overflow.
Answer: I just summarize my google search about your question:
1. what is it exactly?

Spring Boot Admin is a application to manage and monitor your Spring
  Boot Applications. The applications register with our Spring Boot
  Admin Client (via HTTP) or are discovered using Spring Cloud (e.g.
  Eureka). The UI is just an AngularJs application on top of the Spring
  Boot Actuator endpoints.

2. why we are using? 3.monitoring end point means what exactly doing? 4.Is it really need in production environment?

In essence, Actuator brings production-ready features to our
  application.
Monitoring our app, gathering metrics, understanding traffic or the
  state of our database becomes trivial with this dependency.
The main benefit of this library is that we can get production grade
  tools without having to actually implement these features ourselves.
Actuator is mainly used to expose operational information about the
  running application – health, metrics, info, dump, env, etc. It uses
  HTTP endpoints or JMX beans to enable us to interact with it.
Once this dependency is on the classpath several endpoints are
  available for us out of the box. As with most Spring modules, we can
  easily configure or extend it in many ways.
Answer: Basically, Spring boot admin is used for health checks of our microservices.Lets assume you have more number of microservices, and deployed in a server...if any of the service wents down..how the developer get intimated with that?..thats where spring boot admin plays a role to initimate the developer about the service downtime and alert whenever any of the microservices went down..it can be done by spring boot admin and remaind notifier

what is Spring boot Admin


Marble flooring at my house oscillates when we walk over it.How to rectify or resolve this issue?

Question: The marble flooring at my house is popping i.e  when people walk over it, the marble flooring oscillates up & down..and it might come out in the next few days if left unattended..kindly provide me a solution as to how to resolve it?.since only 3-4 tiles are having the trouble.
Comment: Not nearly enough detail to give accurate suggestions. Given the information provided I'd say call a flooring guy in to re-set the tiles.
Answer: There may be several causes for tiles becoming loose. The most popular are:  1). sub-floor not level. An un-even floor won't fully support the tiles. The unsupported area of the tile will slightly flex and overtime will magnify its' motion until it loosens completely.  2). Thin-set not mixed or not properly applied. The cement adhesive needs to be mixed according to the instructions. If there is too much or not enough water the tile will not bond properly. If the thin-set is troweled onto the floor with the wrong sized notched trowel or too thin a layer the tile may not adhere fully.  And 3). the sub-floor must be rigid and secure with no bounce or movement. If it is not prepared correctly by nailing or screwing loose boards down it will flex and transfer that movement through the tile resulting in a failed or loose tile.
Answer: You need to pull the tiles up.  You then need to remove the thinset under them and thinset and install the tile.  If you don't have thinset and a good subfloor under you might as well redo the whole room.  If 3-4 tiles are doing this, then it was a very very poor install.  There are a lot of ugly things that can happen with a tile install but this just reeks of the whole job done half-assed.
My personal guess is this job was done with mastic and the mastic has dried and the walking is causing the bond to disengage.


How to make apscheduler not double execute?

Question: I have the apscheduler working but for some reason when it writes to my file it makes a double-entry every time the BackgroundScheduler is called.
I'm not understanding why it writes 2 lines and the timestamp will be varied by a few milliseconds in the .txt file
I only want the 1 entry, so I can eventually have it written to a database but I need to understand what is making it double executes
I don't see where in my code that it would make it double write.
Please help thank you in advanced
main.py
from flask import Flask, render_template
from flask_caching import Cache
from flask_bootstrap import Bootstrap
from flask_ckeditor import CKEditor
from datetime import date
from apscheduler.schedulers.background import BackgroundScheduler
from market_data import MarketData
import os

sched = BackgroundScheduler()
sched.start()
current_year = date.today().year
data = MarketData()

def grab_every_five():
    p_data = get_c_data()
    with open(file='data.txt', mode='a', encoding='utf-8') as f:
        f.write(f'{p_data}\n')

sched.add_job(grab_every_five, 'interval', minutes=1)
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})
app = Flask(__name__)
cache.init_app(app)

app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
ckeditor = CKEditor(app)
Bootstrap(app)

@app.route('/', methods=['GET', 'POST'])
def home_page():
    c_data = get_c_data()
    return render_template("index.html",
                           year=current_year,
                           asset_count="{:,.0f}".format(c_data['active']),
                           fiat_total="{:,.2f}".format(c_data['total_market_cap']),
                           per_asset="{:,.2f}".format(c_data['value_per_active']),
                           per_all_asset="{:,.2f}".format(c_data['value_per_all']),
                           new_asset="{:,}".format(c_data['total_asset']),
                           country="{:,.2f}".format(c_data['asset_per_country']),
                           all_asset="{:,}".format(c_data['total_asset']),
                           time_stamp = c_data['time_stamp']
                           )

@cache.cached(timeout=60, key_prefix='c_data_cache')
def get_c_data():
    temp_data = data.get_data()
    return temp_data

if __name__ == "__main__":
    app.run(debug=True)

Answer: Ok i found the answer in this post apscheduler in Flask executes twice
It turns out with debug mode on it has the reloader also load an instance of the apscheduler
The easiest and fastest fix was to turn off the reloader as mentioned in the article I've linked to
I just had to add this line of code:
app.run(use_reloader=False)


after execute makemigrations some items are missing in the result

Question: The model name is Question, here is the code.
from django.db import models

class Question(models.Model):
    id = models.AutoField(primary_key=True),
    title = models.CharField(max_length=255),
    subtitle = models.CharField(max_length=255),
    publishedAt = models.DateTimeField(auto_now_add=True)

After execute the command
python manage.py makemigrations questions
I've gotten The result
class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Deal',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('publishedAt', models.DateTimeField(auto_now_add=True)),
            ],
        ),
    ]

I am wondering where is title and subtitle.
Comment: Have you notice a comma after your model fields? Remove it and run the command again
Comment: oh my mistake ... Thank you very much!!!
Answer: I've removed commas after model fields, and gotten correct result.


Angular: unable to bind select option

Question: I want to bind option values of select box.
<select class="form-control" required name="status" id="status" [ngModel]="status" #status="ngModel">
    <option value="ONE"  [ngValue]="status">Active</option>
    <option value="ZERO"  [ngValue]="status">Deactive</option>
</select>

The values what I received from the API is below:
{id: 1, genreName: "Action", genreDescription: "", status: "ZERO"}

Also, when I submitted the form, I see the console log:

{genre_name: "Action", status: NgModel}
Comment: Try with `Active`
Comment: @Emilien Nothing happen. It selects no value.
Answer: Hi you can check the below link:
https://stackblitz.com/edit/angular-select-dropdown-ufit9g?file=src%2Fapp%2Fapp.component.ts
It has a working solution for it.
Answer: Try this:
<select class="form-control" required name="status" id="status"
    [ngModel]="data.status" (ngModelChange)="onChange($event)" >
    <option [value]="'ONE'"  >Active</option>
    <option [value]="'ZERO'"  >Deactive</option>
</select>

TS:
 data = {id: 1, genreName: "Action", genreDescription: "", status: "ZERO"}
 onChange(e){
   console.log(e)

 }

https://stackblitz.com/edit/angular-wgdhjv?file=src/app/app.component.ts

Angular: unable to bind select option


What is the term for a list of points that contains distinct informations kept apart with a pattern?

Question: I have a sorted list of points coming from a program calculating the intersections of bodies with a regular pattern of lines. After discarding the tangents, it results in a well structured list of Points P1 to Pn with $n\in2N ; N\in\mathbb{N}^{>0}$.
Now, each odd point Po with $o\in2N-1 ; N\in\mathbb{N}^{>0}$ does represent a "start" and each even point Pe with $e\in2N+; N\in\mathbb{N}^{>0}$ represents the "end" that belongs to this and only this Po. My trouble now lies in the nomenclature:
What is the correct term for a list that contains patterned sublists of a specific length (here 2)?
Answer: Specifically, if the sublists are of length $2$, I would say that the list "interleaves start points and end points" or resulted from "interleaving start points and end points"; it is an "interleaved list of start and end points".
More generally, and especially for length $\gt2$, I would say that you have "concatenated" lists to form a single list, or "flattened" a list of lists into a single list.


Wait how long after applying wood stain before urethane pass?

Question: I am wondering how long after applying the stain do I need to wait before applying urethane. The weather in my parts is a bit capricious, so I am keen to keep wood outside as little as possible.
Comment: You want the wood and stain to be dry, with dry wood some stains can be coated in 24 hours. On my personal projects I try and give a week but if the wood is well dried I have put poly over stain that was applied 12 hours prior. Just make sure to allow the time the MFG suggests or longer, a fan moving air can speed the process.
Comment: There is a _ton_ of finishing information at [woodworking.se]. Check out the `finishing` tag
Answer: The stain needs to be dry but also make sure the wood does not absorb moisture.
Normally wood for interior use needs to be kept indoors / under cover within temperature and humidity limits otherwise it can start to bend.
Answer: Wood is sensitive to humidity.  Taking indoor furniture and leaving it outside for extended periods (especially in the humidity and rain!!!) is inviting warpage later.
You are better off giving stain all the time you possibly can give it, regardless of your olfactory sensibilities.  Most of the off-gassing will occur in the hours after staining, so when it's dry to the touch, consider bringing it indoors.
When you "rush it", you wind up with defects, and stain/sealer defects are not feasible to "fix".  With the inexpensive pine furniture I use, I just consider it a $70 lesson, Freecycle the faulty furniture, and buy another piece and go again.


Grub not showing up at boot

Question: I have installed the linux-lowlatency kernel recently.
Setup of a DAW (MIDI support) was the reason to change from Fedora to Ubuntu.

After reboot uname shows that I am running the generic kernel.
There are 2 entries (normal and revovery) for the lowlatency kernel in
/boot/grub/grub.cfg
but the grub menu does not show up at boot time at all.

... and no - I do not want to buy Windows software like an answer else where to this question suggests
Comment: have you tried reconfiguring/re-installing grub?
Comment: Sometimes GRUB can be configure to not show at boot at automatically boot to first entry. Try holding the left shift button at start-up to make it show.
Answer: To enable the grub menu to select the kernel, you have to comment the line in /etc/default/grub

#GRUB_HIDDEN_TIMEOUT=0

Then you have to run update-grub and reboot and the grub menu should appear.

Grub not showing up at boot


Using pandas with json normalize

Question: I am trying to normalize a very simple JSON structure.
data = [{"pedido": {"situacao": "OK", ....}}, {"pedido": {"situacao": "NOK", ...}}]
rs = json_normalize(data, 'pedido', [['pedido', 'situacao']])

I would like to get just the index and another column called pedido.situacao. There is a bunch of other field on json but I want to get only situacao:
0 pedido.situacao
0  situacao              OK
1  situacao             NOK

It seens there is a extra column with "0"as label.
Answer: We can do
df=pd.concat(pd.DataFrame(x) for x in data)
         pedido
situacao     OK
situacao    NOK

Update
df=pd.concat([pd.DataFrame(x) for x in data],keys=range(len(data))).unstack(level=1)
df.columns=df.columns.map('.'.join)
df
  pedido.situacao
0              OK
1             NOK

Comment: I want only a single column called pedido.situacao
Answer: You can just do this:
rs = pd.json_normalize(data)
print(rs[['pedido.situacao']])

  pedido.situacao
0              OK
1             NOK

Using pandas with json normalize


How do I fish in Torchlight 2?

Question: I am wondering how you're supposed to catch fish in Torchlight 2. I am in the Estherian Enclave literally right at the start of the game on my first character, and have found a Fishing Hole:

Upon clicking on the label for the Fishing Hole, I cast a line into the water and get a button on screen:

I have tried waiting for audible indicators that I have caught a fish (similar to WoW) and there are a couple of different sounds that play but regardless of when I click the button I catch nothing.
I have also tried waiting for the blue circle that pulses around the button to reach certain points (like fully under the button, or as far out as it extends away from the button) before clicking but this doesn't appear to have an effect either.
Regardless of what I've tried so far, I always end up at this screen;

How do I catch fish in Torchlight II?
Answer: You simply must wait for the circle to turn purple. You'll hear a sound too.
Often, the circle will go very close to becoming the right size, only to enlarge later, so don't be fooled by that. The circle will normally remain purple for a second or two, so you have plenty of time to react to the color and the sound without resorting to guesswork. So don't resort to guesswork.
If you do miss the window of opportunity - just wait until the circle turns purple again. You can do so with no penalty and this won't use up the fish hole more than once.
This is especially important on wilderness fish holes — they have better drops, but you only get 3 to 9 tries per hole: you do not want to catch nothing on these.
Comment: That is a *very* subtle colour change!
Comment: I never noticed the color change! I always just waited until the ring shrunk to the button size and hit the button. Sometimes there is the "Caught something" sound, sometimes there isn't. I found if I wait on the sound, I'd normally miss the fish, which sucks in dungeon/adventure area fishing holes.
Answer: When the white ring around the fishing button (which pulses when you try to fish) gets very close to the button and it turns into red, then press it. Then you catch something.
On holes outside of the town, you can also use dynamite which can be purchased to use up all tries and get the fish without having to do the minigame. Caution: this method yields lower returns! e.g. if you throw dynamite into a fishing hole that has 9 tries you won't get all 9 items.
Answer: You can use dynamite to mine for fish. It's an old dwarven tradition.

How do I fish in Torchlight 2?


What would the box sizing calculation be for 6ga NM and 6ga THHN into a box?

Question: My situation is essentially the same as this question, for reference.  I am trying to accomplish the same goal:  feeding a sub-panel in an outbuilding from my home's main service panel.
I have a 6ga NM wire (3 conductors #8 bare ground) and a set of 4 THHN 6ga (3 conductors w/insulated #8 ground) coming into a space where I need a junction box.  What size box would that require, given that this is only for the purpose of splicing the two sets together, there are no devices present, and no other wires in or passing through?
To extend the question a bit, this is happening in the interior space, so a surface mounted box would be ideal.  Is there such a thing as a box that fits the bill and doesn't look like it belongs in a factory?
Comment: You can install the box in an accessible attic. In basements many times I will make a picture frame and use Velcro to mount it to the wall. I recently had a new inspector require the UFER ground to have a sign on the frame so I used a ground symbol on the wood she was fine with that, I have had to put signage on service panels that I had cabinets so there are code compliant ways to hide the boxes. As long as the finish is not damaged and the panel is designed to be removable the box is accessible. See the answers for the size.
Comment: Can you mount this where it wouldn't be as visible? Say, inside the attic?
Comment: @Machavity At this point, no.  The NM wire was run to an accessible point during a basement remodel.  The THHN will run through a brick wall to this box.
Comment: @Machavity In fact, going up was never possible.  It was always going to have to punch out the basement wall somewhere.
Comment: Psst... to splice #6 or smaller, "MAC Block Connector".  Mini Polaris connectors at a fraction of the price.
Comment: @Harper-ReinstateMonica I have polaris connectors for the splices. But I'm not sure what else you might be implying.
Comment: @Harper-ReinstateMonica Never mind...I see it now.  Took me a bit to actually find MAC.  Wish I'd have seen those sooner.
Comment: Oh I know, they're hard to search for, I know.  The very opposite of prescription drugs which are named based on the Internet .com domain being available lol.
Answer: 5 cubic inches per 6 Ga conductor terminating in the box (30)
plus
3 cubic inches for up to 4 8 ga grounds. (3)
33 cubic inches.
If the NM clamp is external, no additional allowance. If the NM clamp is interior, add another 5 cubic inches (38).
A 4-11/16 x 2-1/8 steel box will have room to spare. You can dress it up however you like, paint it, etc. Or you might find a 6x6x4 PVC box more to your taste? That part really becomes a decorating question, and a cabinet with a door that opens without tools is an option to hide any box you don't like the look of.
Comment: NEC 314.16 14Ga 2, 12Ga 2.25, 10Ga 2.5, 8Ga 3, 6Ga 5 - look up box fill calculator for an easy way on a computer. Grounding conductor rules changed with 2020 code (after 4, must add 1/4 per )
Comment: Is there a particular NEC section (or other source) that spells out how to derive these numbers?  Perhaps a chart for quick reference?
Answer: There's a couple of ways to play this. Neither is terribly aesthetic.

Deep metal junction box. You'll need clamps, but these are cheap and easy to find. Add a lid
A large PVC box. You can buy these in varying sizes (4x4, 6x6) and they come with no holes (you'll need to drill some). Make a hole and add a clamp to fit it


Manage/Restrict access of users, contacts and leads in AppExchange product DocuSign

Question: I am using AppExchange product DocuSign for sending documents to end-user for digital signature in one of the objects in SFDC.
I am doing it using 'Send with DocuSign' button in the detail page. My questions are:

Can we manage/restrict the addition of recipients based on relationship? for example:  I have contacts available to opportunity. In the opportunity detail page i want that sender can only select contacts from the list of contacts associated with the opportunity.  Or add as recipients only users of particular profiles/roles etc.
Can we also control the visibility of buttons highlighted in the below screen shot?
Answer: Currently, the answer to both is no, as long as you are using the managed package.  There are lots of ways (using custom buttons, for example) to skip the screen you see above, and "program" button to send just the people you want to send, however.


Is the unbreaking enchantment beyond III effective?

Question: In my singleplayer world, I was testing the difference between an Unbreaking III and an Unbreaking IV enchanted armour (using TooManyItems), but I didn't see much of a difference.  I would like some help from the mathematicians of this website to tell me what at what level of unbreaking the enchantment stops being more effective.  Also, does this calculation apply to all versions past 1.5.2?
Answer: ###Yes, but with rapidly diminishing returns
According to the wiki page on Enchanting1, the effect of Unbreaking is:

Increases durability
[...]
For armor, (60 + (40/(Level+1)))% chance a use reduces durability. (In
other words, each durability hit against "unbreaking" armor has a
20%/27%/30% chance of being ignored.) Thus, on average, armor lasts
25%/36%/43% longer.

You can see that the formula is different for armor, and even with the regular three levels, the chance to not lose durability when hit increases slower with higher levels. Extrapolating the "20%/27%/30%" using the formula given yields:
Unbreaking |  1 |  2 |  3 |  4 |  5 |  6 |  7 | ... | 10 | ... | 20
Chance     | 20 | 27 | 30 | 32 | 33 | 34 | 35 | ... | 36 | ... | 38
Increase   | 20 |  7 |  3 |  2 |  1 |  1 |  1 | ...

(Values are rounded in the table, but not in game). The chance converges to 40% for high values of Unbreaking, with diminishing returns the higher the enchantment level gets, to the point where is negligible.
If you directly compare an Unbreaking III Diamond Chestplate to an Unbreaking IV one, on average, the former breaks after 529100/(60+40/4)=756 hits, the latter after 529100/(60+40/5)=778. That is only a relative increase of 3% more hits.
1 While the page has changed, the game mechanics have been the the same since at least March 2013.
Answer: According to the wiki, Unbreaking IV cannot be acquired in Survival Mode.

Armor enchanted with Unbreaking has a 40 * (1 - 1/(Level+1))% chance to ignore durability damage.
    Level   | Chance to ignore (%) | Durability increase (%)
 ===========================================================
      I     |          20          |           25
     II     |         26.7         |           36
     III    |          30          |          42.9
     IV     |          32          |          47.1
      V     |         33.3         |           50
     VI     |         34.3         |          52.2
     VII    |          35          |          53.8
     ...    |         ...          |          ...
  infinite  |          40          |          66.7

You can see that Unbreaking IV only gives a 3.6 % relative improvement over Unbreaking III, so of course you wouldn't notice the difference with quick tests.
Comment: Why the downvote ?


If an unhandled exception occurs, is App.OnSuspending still called?

Question: Title says it all. Basically, in a Windows 8 Store App, if an unhandled exception occurs then will the OnSuspending event be called? I've found this is practically impossible to debug with any amount of certainty
Comment: This ought to be done the Socratic way.  An app stores its state in the suspend event handler so it can cleanly restart when it happens to get terminated.  Would you like WinRT to call your suspend event handler when your program state is completely corrupted?   Perhaps that's obvious.  Have you considered what happens when the exception occurs on a worker thread, just as your suspend handler is running?
Comment: @HansPassant I meant it was impossible to debug because the only way you can even get a breakpoint on the Suspend event is to explicitly suspend the program from Visual Studio. I wasn't sure if unhandled skips straight to terminated or what.. but apparently it does go straight to terminated
Answer: No it is not called. :(
I found out this when developing with the new MediaCapture APIs.  If you don't clean up resources (e.g. stop recording/preview) the phone becomes unstable and freezes the OS when trying to use the camera the next time.  The recommendation is to use the suspending event to clean up the resources, therefore thats what I did.  But my phone (device not emulator) would become unstable if I encountered an unhandled exception, therefore the cleanup method was not called.  This leads me to believe that on unhandled exception, suspending is not called.
http://msdn.microsoft.com/en-US/library/windows/apps/xaml/Dn642092(v=win.10)#cleaning_up_mediacapture_resources_properly
I'd recommend doing what berXpert suggested.  Setting handled to be true doing your action then exiting out.
Answer: If you need to call something after unhandled happens, you could attach to the unhandledexception event at the App object:
<code>public App()
{
    ...
    this.UnhandledException += (s,e) => {
            e.Handled = true;
            this.DoSomethingWithTheError;
            this.Exit();
    };
}
</code>
It will exit the app any way.
Comment: sorry I downvoted before realizing you had something unique here.  At first I didn't see DoSomethingWithTheError / Exit.  My bad.  But a way to improve your answer would be to write out what is unique and explain that instead of say 'handle the unhandled event'


JavaScript filter out elements of array that are dividers of one element of an array

Question: I have an array.
let x = [ 2, 3, 4, 6, 5 ];

I want to filter it out to be:
let x = [ 2, 3, 5 ];

The logic behind it is that 6 is able to divide with 2 and 3. So if any element of an array that is greater and able to divide with any other element of an array (except it self) should be removed.
Comment: Does this answer your question? [How to filter array values greater than x](https://stackoverflow.com/questions/33772718/how-to-filter-array-values-greater-than-x) and then change the if statement to match the logic you want
Answer: You could check with the predecessors and filter the array.

const
    values = [2, 3, 4, 6, 5],
    result = values.filter((v, i, a) => !a.slice(0, i).some(w => v % w === 0));

console.log(result);
Answer: This will loop through every element, and check for multiples greater than elements in the array. If those are found, they are removed.
for (let num of x) {
    for (let i in x) {
        if (x[i] > num && x[i] % num == 0) {
            x.splice(i,1);
        }
    }
}

Answer: another approach:
let arr = [2, 3, 4, 6, 5]
arr = arr.reduce((acc, current) => acc.some((previous) => current % previous == 0) ? acc : [...acc, current], []);
console.log(arr) // [2, 3, 5]

edit: It seems below approach is better, because it does not use spread operator to append element:
let array = [2, 3, 4, 6, 5];
array = array.filter((current, i, arr) => !arr.slice(0, i).some(previous => current % previous == 0))
console.log(array); // [2, 3, 5]


Reading command line parameters

Question: I have made little program for computing pi (π) as an integral. Now I am facing a question how to extend it to compute an integral, which will be given as an extra parameter when starting an application. How do I deal with such a parameter in a program?
Comment: http://pubs.opengroup.org/onlinepubs/009695399/functions/getopt.html
Comment: (Title edited to make more appropriate)
Comment: So is your question really just about command line arguments?
Comment: yea, and then I don't know how to deal it with in actual program, if I read as a char than transfer it to int for computing? Just this is the part a dont understand
Answer: When you write your main function, you typically see one of two definitions:

int main(void)
int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main are:

int argc - the number of arguments passed into your program when it was run. It is at least 1.
char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example
For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.
[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...
[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral

A Simple Case for You
And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.
So in your code...
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.
Answer: #include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  int i, parameter = 0;
  if (argc >= 2) {
    /* there is 1 parameter (or more) in the command line used */
    /* argv[0] may point to the program name */
    /* argv[1] points to the 1st parameter */
    /* argv[argc] is NULL */
    parameter = atoi(argv[1]); /* better to use strtol */
    if (parameter > 0) {
      for (i = 0; i < parameter; i++) printf("%d ", i);
    } else {
      fprintf(stderr, "Please use a positive integer.\n");
    }
  }
  return 0;
}

Answer: Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project.
http://tclap.sourceforge.net/
A similar library is available for C as well.
http://argtable.sourceforge.net/
Answer: There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

Reading command line parameters


What is the intuition behind Slater's condition in optimization? (And other constraint qualifications.)

Question: I would like to "grok" Slater's condition and other constraint qualification conditions in optimization.
Slater's condition is only one of many different constraint qualifications in the optimization literature.  Which one is the most fundamental?  Which one tells me "what's really going on"?  What is the basic idea at the heart of this?
Also, constraint qualifications appear in both convex and non-convex optimization.  Is there a unifying viewpoint that shows it is the same simple, basic idea in all cases?
I'd be interested in any insights or viewpoints that lead to a deeper understanding of constraint qualifications in optimization.

Edit: Here is one possible viewpoint.  Buried on p. 223 (chapter 23) of Rockafellar's Convex Analysis, we find the following fundamental and vital fact.

Let $f_1,\ldots,f_m$ be proper convex functions on $\mathbb R^n$, and let $f = f_1 + \cdots + f_m$. If the convex sets $\text{ri}(\text{dom }
f_i), i = 1,\ldots m$, have a point in common, then $$ \partial f(x) = \partial f_1(x) + \cdots + \partial f_m(x). $$ This condition for equality can be weakened slightly if certain of the functions, say $f_1,\ldots, f_k$, are polyhedral: then it is enough if the sets $\text{dom } f_i, i = 1,\ldots,k$ and $\text{ri}(\text{dom } f_i), i = k+1,\ldots,m$ have a point in common.

This subdifferential sum rule can be used to derive optimality conditions for various convex optimization problems, including the KKT conditions for convex problems.  For example, the optimization problem
\begin{align}
\text{minimize} & \quad f(x) \\
\text{subject to } & \quad x \in C
\end{align}
where $f$ is a closed convex functin and $C$ is a closed convex set, is equivalent to the problem
$$
\text{minimize} \quad f(x) + I_C(x)
$$
where $I_C$ is the indicator function for $C$.
The optimality condition for this problem is
$$
0 \in \partial (f + I_C)(x) = \partial f(x) + \partial I_C(x),
$$
but for the equality to be valid the "overlapping relative interior" condition must be satisfied.  So, we need the relative interior of $C$ to have a point in common with the relative interior of $\text{dom } f$. This is a "constraint qualification" for the problem of minimizing $f$ subject to the constraint that $x \in C$.
So is this "overlapping relative interiors" condition appearing in the subdifferential sum rule the ultimate, most fundamental constraint qualification?
Can Slater's condition be viewed as a special case of this "overlapping relative interior" condition?
The "overlapping relative interior" condition apparently has nothing to do with non-convex optimization problems.  Is there a unifying viewpoint that applies to both convex and non-convex problems?
Comment: You can basically reduce them to "make Lagrangian multiplier rule work (be necessary)". Or more technical, to make the tangential cone equal the linearized tangential cone (or other kind of approximation). Notice that the tangential cone is purely geometric, but most approximations are analytic an depends on the set description.
Comment: @user251257 Does the "make the tangent cone equal the linearized tangent cone" interpretation still work for convex optimization problems with nondifferentiable objective and constraint functions?
Comment: @user251257 Your comment was helpful, by the way, thank you.
Comment: On your edit: You state a subgradient-sum theorem which allows functions to take infinite values, but requires existence of points where the functions are all finite.  This makes sense as a requirement since we cannot evaluate subgradients at points where the function value is $\infty$. This seems to be a minor detail that does not (directly) relate to Slater's condition, since Slater's condition applies to problems with functional inequality constraints (and does not necessarily involve a sum of functions).
Comment: @Michael I think the subdifferential sum rule might be at the heart of one way of understanding the KKT conditions, though.  The most fundamental optimality condition, for minimizing a function $f$, is $0 \in \partial f(x)$.  The problem of minimizing $f(x)$ subject to $x \in C$ can be expressed as minimizing $f(x) + I_C(x)$, and the optimality condition is $0 \in \partial f(x) + \partial I_C(x)$.  Now the next step is that if $C$ is determined by a bunch of inequality constraints, we can describe $\partial I_C(x)$ much more explicitly, and as a result obtain (hopefully) the KKT conditions.
Comment: @Michael In that approach, if it works out, the key step is when we invoke the subdifferential sum rule, which requires the overlapping relative interior condition to be satisfied.  And in the case where $C$ is determined by a bunch of inequality constraints, perhaps the overlapping relative interior condition turns out to be identical to Slater's condition.
Answer: Slater's condition relates to existence of Lagrange multipliers in a convex program.  Lagrange multipliers exist when there is a nonvertical supporting hyperplane that passes through a point on the boundary of a related convex set. Intuitively, nonvertical hyperplanes can only fail to exist when constraints of the convex program can only be achieved at "edge" type points of the set...Slater ensures constraints can be achieved at "non-edge" type points.
Discussions with pictures can be found in various places, such as Convex Analysis and Optimization by Bertsekas, Nedic, and Ozdaglar. The Slater result is very simple to derive and below I summarize a math derivation that may also give intuition.

The convex program
Mathematically we have a general convex program:
\begin{align}
\mbox{Minimize:} \quad & f(x) \\
\mbox{Subject to:} \quad & g_i(x) \leq 0 \quad , \forall i \in \{1, \ldots, k\} \\
& x \in \mathcal{X}
\end{align}
where $\mathcal{X} \subseteq \mathbb{R}^n$ is a convex set and $f, g_1, ..., g_k$ are convex functions defined over $\mathcal{X}$. Let us suppose there is (at least one) $x^* \in \mathcal{X}$ that is an optimal solution to the above convex program.
Lagrange multipliers
Define the set $\mathcal{A}$:
$$ \mathcal{A} = \{(y_0, y_1, ..., y_k) : y_0 \geq f(x), y_1 \geq g_1(x), ..., y_k \geq g_k(x) \mbox{ for some $x \in \mathcal{X}$} \}$$
It can be shown that $\mathcal{A}$ is a convex set and the point $(f(x^*), 0, 0, ..., 0)$ is a boundary point of the set.  By the hyperplane separation theorem it follows there are real numbers $\theta_0, \theta_1, ..., \theta_k$, not all zero, such that
$$ \theta_0y_0 + \sum_{i=1}^k \theta_i y_i \geq \theta_0f(x^*) \quad \forall (y_0, ..., y_k) \in \mathcal{A} $$
By nature of the set $\mathcal{A}$ (namely, any point that dominates a point in $\mathcal{A}$ is also in $\mathcal{A}$), it is easy to show the above can only hold if $\theta_i \geq 0$ for all $i \in \{0, 1, ..., k\}$.  Since for any $x \in \mathcal{X}$ we have  $(f(x), g_1(x), ..., g_k(x)) \in \mathcal{A}$, a special case of the above inequality is:
$$ \theta_0f(x) + \sum_{i=1}^k \theta_i g_i(x) \geq \theta_0f(x^*) \quad \forall x \in \mathcal{X} \quad (Eq. 1)$$
We say the hyperplane is nonvertical if $\theta_0 \neq 0$, in which case we can define $\mu_i = \theta_i/\theta_0 \geq 0$ for all $i \in \{1, ..., k\}$ and we call these Lagrange multipliers because they are nonnegative and:
$$ \theta_0 \neq 0 \implies f(x) + \sum_{i=1}^k \mu_i g_i(x) \geq f(x^*) \quad, \forall x \in \mathcal{X}$$
Assuming $\theta_0 \neq 0$, the above inequality implies that $x^*$ is a minimizer of $f(x) + \sum_{i=1}^k \mu_ig_i(x)$ over all $x \in \mathcal{X}$, the minimum value is $f(x^*)$, and  $\mu_i g_i(x^*)=0$ for all $i \in \{1, ..., k\}$.
Slater's condition
Slater's condition:  Suppose there is an $s \in \mathcal{X}$ such that $g_i(s) < 0$ for all $i \in \{1, ..., k\}$.  (So all constraints can be achieved with positive slackness.)
Claim:  If Slater's condition holds, then $\theta_0 \neq 0$ and hence Lagrange multipliers exist.
Proof: Assume $\theta_0=0$ and plug $s \in \mathcal{X}$ into Eq. 1 to get a contradiction (recalling that not all $\theta_i$ are zero).  $\Box$
I do not fill in the details here since I sometimes give these details as a homework exercise (Exercise VIII-B.8 on page 40 here):
http://ee.usc.edu/stochastic-nets/docs/network-optimization-notes.pdf
Fig. 19 on page 55 of those notes gives a simple counter-example where a nonvertical hyperplane does not exist, and this is also useful to get intuition on Slater's condition. These examples are standard and similar ones can be found in the Bertsekas book.
Further intuition
Going back to the set $\mathcal{A}$ and the boundary point $(f(x^*), 0, 0, ..., 0)$, intuitively we see that if Slater's condition holds then any vertical hyperplane that passes through this boundary point would chop $\mathcal{A}$ into two pieces (with points of $\mathcal{A}$ lying strictly on one side of the vertical hyperplane, and other points lying strictly on the other side). Hence, if Slater's condition is true, then a vertical hyperplane  would fail to be a supporting hyperplane. [Again refer to Fig. 19 in the above notes to visualize.]


Can I use the addAll Collection method to add all elements (type:byte) from arrays(byte[]) to a List of type Byte?

Question: I have to append (variable number of) byte arrays.
Collections seem to only work with the wrapper classes, ie Byte.
After about 20 hours I've came up with this, and it works, but I wondered if it could be improved (ADD TO LIST, but any other improvement suggestions welcome:), ie

Collections.addAll method all the array elements to the specified
  collection. This is how Collections.addAll method is being called. It
  does the same as Arrays.asList method however it is much faster than
  it so performance wise this is a best way to get the array converted
  to ArrayList.

Here it is in it's current beta version
public static byte[] joinArrays(byte[]... args) {

    List<Byte> arrayList = new ArrayList();

    for (byte[] arg : args) { // For all array arguments...
        for (int i = 0; i < arg.length; i++) { // For all elements in array
            arrayList.add(Byte.valueOf(arg[i])); // ADD TO LIST
        }
    }
    byte[] returnArray = new byte[arrayList.size()];

    for (int i = 0; i < arrayList.size(); i++) {
        returnArray[i] = arrayList.get(i).byteValue(); //Get byte from Byte List
    }
    return returnArray;
}

Comment: Should be moved to Code Review?
Answer: You could stick to your arrays and avoid the boxing/unboxing into Byte with something like this:
public static byte[] joinArrays(byte[]... args) {
    int byteCount = 0;
    for (byte[] arg : args) { // For all array arguments...
        byteCount += arg.length;
    }
    byte[] returnArray = new byte[byteCount];
    int offset = 0;
    for (byte[] arg : args) { // For all array arguments...
        System.arraycopy(arg, 0, returnArray, offset, arg.length);
        offset += arg.length;
    }
    return returnArray;
}

Comment: Right! Much faster and optimal in memory usage than using collections.
Answer: Here is one variation
public static byte[] joinArrays(byte[]... args) {
    byte[] result = null;
    if(args.length > 0) {
        result = args[0];
        for(int index = 1; index < args.length; index++){
            result = concat(result, args[index]);
        }
    }
    return result;
}

public static byte[] concat(byte[] a, byte[] b) {
    int aLen = a.length;
    int bLen = b.length;
    byte[] c= new byte[aLen+bLen];
    System.arraycopy(a, 0, c, 0, aLen);
    System.arraycopy(b, 0, c, aLen, bLen);
    return c;
}


Undefined reference to symbol acos@@GLIBC_2.2.5 while compiling xpdf

Question: I get the following error while compiling xpdf using make. I've tried using the command: LIBS=-l make but it doesn't work. I know the problem is that the c compiler cannot recognise the math code in the source code because the math library is not available to it, but I don't know how to fix it.
[ 71%] Linking CXX executable pdftohtml
    /usr/bin/ld: CMakeFiles/xpdf_objs.dir/Gfx.cc.o: undefined reference to symbol 'acos@@GLIBC_2.2.5'
    //usr/lib64/libm.so.6: error adding symbols: DSO missing from command line
    collect2: error: ld returned 1 exit status
    make[2]: *** [xpdf/CMakeFiles/pdftohtml.dir/build.make:219: xpdf/pdftohtml] Error 1
    make[1]: *** [CMakeFiles/Makefile2:428: xpdf/CMakeFiles/pdftohtml.dir/all] Error 2
    make: *** [Makefile:130: all] Error 2

I have put my Makefile and CmakeLists.txt on pastebin for more information.
Comment: Well, the issue seems to be that your link command is missing `-lm` ("DSO missing from command line") but I don't know enough about cmake to suggest a fix - and it's probably more a question for stackoverflow than for askubuntu
Comment: @steeldriver I was thinking thesame. I don't quite know how to add it to the command line.
Comment: Something like this perhaps? [Math functions not working with "make" in C](https://stackoverflow.com/questions/36365070/math-functions-not-working-with-make-in-c/36365412#36365412)
Comment: @steeldriver  thanks for the link. I read it but I couldn't find the code `add_executable` in the CmakeList.txt file.
Comment: So whose code is it? where did you get it? did you write the CMakeList.txt file yourself?
Comment: Its not my code. Its from this  [program](https://www.xpdfreader.com/). This is probably caused by how the code was written
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/78810/discussion-between-steeldriver-and-mywrathacademia).
Answer: After debugging the code, the solution I used was to add -lpaper to the DCMAKE_CXX_FLAGS or the DCMAKE_EXE_LINKER_FLAGS during the cmake command, either works. Thanks @steeldriver for very good insights.


Change borders' color, length and distance from label in a shiny widget using css

Question: I have the shiny app below in which I use css to change the borders' color of the shiny widget to red and also change the length of the input and its distance from its label "Name". But despite some of the parameters I have given in css part work, those mentioned above do not. Here is what needs to be done.

library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyjs)

css <-
  "
.container {
margin: 20px;
padding: 15px;
}
#expr-container .selectize-input {
  font-size: 44px;
line-height: 44px;
color: blue;
border-color: red;
width: 300px;
}
#expr-container .selectize-dropdown {
font-size: 16px;
line-height: 22px;
}
#expr-container .selectize-dropdown-content {
max-height: 5px;
padding: 0;
}
#expr-container .selectize-dropdown-content .option {
border-bottom: 1px dotted #ccc;
}
#expr-container label{
display: table-cell;
text-align: center;
vertical-align: middle;
}
#expr-container .form-group {
display: table-row;
}
"
mytitle <- paste0("Life, Death & Statins")
dbHeader <- dashboardHeaderPlus(
  titleWidth = "0px",
  tags$li(a(
    div(style="display: inline;padding: 0px 0px 0px 0px;vertical-align:top; width: 150px;", actionButton("conse", "Consent",style=" background-color: #faf0e6; border-color: #faf0e6"))
  ),
  class = "dropdown")

)

shinyApp(
  ui = dashboardPagePlus(
    header = dbHeader,
    sidebar = dashboardSidebar(width = "0px",
                               sidebarMenu(id = "sidebar", # id important for updateTabItems
                                           menuItem("Consent", tabName = "conse", icon = icon("line-chart"))
                               )           ),
    body = dashboardBody(
      useShinyjs(),
      tags$script(HTML("$('body').addClass('fixed');")),

      tags$head(tags$style(".skin-blue .main-header .logo { padding: 0px;}")),

      tabItems(
        tabItem("conse",

                  fluidRow(column(1,),column(3,

                                             tags$style(css),
                                             tags$div(id = "expr-container",textInput("name", label = ("Name"), value = ""))))

                )

      )

    )

  ),
  server<-shinyServer(function(input, output,session) {
    hide(selector = "body > div > header > nav > a")

  }
  )
)

Answer: Perhaps you are looking for this:
css <-
"
#expr-container .form-control {
  background-color: transparent;
  border: 3px solid black;
  color: blue;
}
"

mytitle <- paste0("Life, Death & Statins")
dbHeader <- dashboardHeaderPlus(
  titleWidth = "0px",
  tags$li(a(
    div(style="display: inline;padding: 0px 0px 0px 0px;vertical-align:top; width: 150px;", actionButton("conse", "Consent",style=" background-color: #faf0e6; border-color: #faf0e6"))
  ),
  class = "dropdown")
)

shinyApp(
  ui = dashboardPagePlus(
    header = dbHeader,
    sidebar = dashboardSidebar(width = "0px",
                               sidebarMenu(id = "sidebar", # id important for updateTabItems
                                           menuItem("Consent", tabName = "conse", icon = icon("line-chart"))
                               )           ),
    body = dashboardBody(
      useShinyjs(),
      tags$script(HTML("$('body').addClass('fixed');")),

      tags$head(tags$style(".skin-blue .main-header .logo { padding: 0px;}")),

      tabItems(
        tabItem("conse",

                fluidRow(column(2,paste("Name: ")),
                         #column(1,),
                         column(5, #textInput("name", label = NULL, value = "", width="100%")
                                tags$style(css),
                                tags$div(id = "expr-container", textInput("name", label = NULL, value = "", width="100%") )
                                ))

        )

      )

    )

  ),
  server<-shinyServer(function(input, output,session) {
    hide(selector = "body > div > header > nav > a")

  }
  )
)

Comment: In that case, you can include the previous CSS code and it should work.  Please play with it by modifying or adding one item at a time.
Comment: If you don't want to mess with shinys default CSS you can just leave the label empty and create a label next to it instead of forcing the existing label to the side and adjusting the space.
Comment: Thanks but how can I make the borders color black and change the length of input as well?
Comment: Also the more I increase the 150px to the right the smaller the input length is getting.
Comment: ok you used the label-out solution. the only issue here is that the text seems a little bit higher that the center of the input


Dice sum probability

Question: Simulate two separate dice (use random numbers with the appropriate range) being rolled 10 times. What are the percentage of rolls that resulted in a sum of 7, a sum of 2 and a sum of 11.
I came across this problem and have spent ages trying to figure out the algorithm for this...any help would be appreciated. I would show you what I came up with but i have nothing...
Answer: You need a random number generator that gives a uniform distribution on $[1,6]$ to be a die. Then loop from $1$ to $10$, rolling two dice each time. Total the dice and count the times you get $2, 7, 11$. Report the results
Comment: so what you are saying is: I give two random numbers to two dice and loop between 1 to 10 and see how many times i get 2, 7 and 11?
Answer: This looks like a programming exercise rather than a math exercise. Specifics will depend on your programming language, but it is going to be something like

n2 = n7 = n11 = 0;
for i = 1 to 10 do
  d1 = random(1,6) // get a random integer between 1 and 6
  d2 = random(1,6) // and another one
  s = d1 + d2
  if s == 2 then n2 = n2 + 1; fi
  if s == 7 then n7 = n7 + 1; fi
  if s == 11 then n11 = n11 + 1; fi
od
print "2's:  ", 10 * n2, "%"
print "7's:  ", 10 * n7, "%"
print "11's: ", 10 * n11, "%"

It's much more fun to try to figure out the expected number of 2's, 7's and 11's, but I'll leave that as (another) exercise.

Dice sum probability


puppet applly and deferred functions: Error: Unknown function 'mymodule::myupcase'

Question: I'm following this puppet doc to test Deferred functions, below I replicate the steps.

start creating the required directory strucutre and running some Puppet Develpment Kit (pdk) commands:

cd ~/dev/src/local/puppet_tests
pdk new module mymodule
cd mymodule
pdk new class mymodule
mkdir -p lib/puppet/functions/mymodule

Next, you should paste the code below in your manifest/init.pp file:

class mymodule {
  $d = Deferred("mymodule::myupcase", ["mysecret"])

  notify { example :
    message => $d
  }
}

class { 'mymodule': }

Next, create a file name myupcase.rb under the directory lib/puppet/functions/mymodule and paste the code below:

Puppet::Functions.create_function(:'mymodule::myupcase') do
  dispatch :up do
    param 'String', :some_string
  end

  def up(some_string)
    Puppet::Pops::Types::PSensitiveType::Sensitive.new(some_string.upcase)
  end
end

Now, you should run the puppet apply manifest/init.pp

~/dev/src/local/puppet_tests/mymodule main*
❯ puppet apply manifests/init.pp
Notice: Compiled catalog for localhost.localdomain in environment production in 0.04 seconds
Error: Unknown function 'mymodule::myupcase'

Removing the following part of the code in the init.pp file, it works, but just because you remove the reference to the $d variable:
  notify { example :
    message => $d,
  }

What am I missing here ?
My S.O. is MacOX 13.4.1, puppet 8.1.0.
Installed both puppet-agent and pdk using brew:
brew install --cask puppetlabs/puppet/puppet-agent
brew install --cask puppetlabs/puppet/pdk

EDITED:
I have made an additional test, now using the pdk new function to create the function, but the error persists:
cd ~/dev/src/local/puppet_tests
pdk new module mymodule
cd mymodule
pdk new class mymodule
pdk new function myupcase --type=v4

It have created some additional directory named spec/ with some additional files. The final myupcase.rb is:
# frozen_string_literal: true

# https://github.com/puppetlabs/puppet-specifications/blob/master/language/func-api.md#the-4x-api
Puppet::Functions.create_function(:"mymodule::myupcase") do
  dispatch :myupcase do
    param 'String', :a
    return_type 'String'
  end
  # the function below is called by puppet and and must match
  # the name of the puppet function above. You can set your
  # required parameters below and puppet will enforce these
  # so change x to suit your needs although only one parameter is required
  # as defined in the dispatch method.
  def myupcase(x)
    x.upcase
  end

  # you can define other helper methods in this code block as well
end

The init.pp file remains the same.
Comment: `pdk test unit`?
Comment: You appear to have followed the documentation faithfully, but the `puppet apply` step there looks suspect to me.  Aside from `puppet apply` being disfavored for some time, I would expect that in order for it to locate your function, the directory `~/dev/src/local/puppet_tests` would need to be in its modulepath.
Comment: The question is missing the function definition and invocation. We cannot assist without either.
Comment: I hope to have added all the required information now :)
Comment: If you are using `pdk` then why not use the `new function` subcommand? Since this appears to be an autoloading issue, then that may fix this issue for you.
Comment: I have recreated everything, now using pdk. For the function i used the command `pdk new function myupcase --type=v4`. The only thing I have changed manually is the `init.pp` file to use the same code sample from the docs. Still, getting a `Error: Unknown function 'mymodule::myupcase'`. I will update the question with this additional test.
Comment: @JohnBollinger, you nailed it. Thank you very much. You can post your comment as an answer and i will accept it.
Answer: The function itself looks fine, and you appear to have placed it properly in your module.  That puppet apply does not find it likely arises from your module not being in its module path (and you have already confirmed this). Similar errors would arise if the main class tried to use any other contents of the module: other classes, defined types, module data, etc.
Overall, the last step of the documentation, wherein you test the function by applying manifests/init.pp seems very ill advised, and when it does work to test the function, that's only because the module's init.pp contains class { 'mymodule': } at top scope, which is a whole other level of bad.
This is what you should do instead:

remove the class declaration class { 'mymodule': } from your module's init.pp.  It simply should not be there.

ensure that the parent directory (~/dev/src/local/puppet_tests) of your module directory is in Puppet's modulepath.

if you want to test with puppet apply then create a separate manifest for that, anywhere:
test.pp
include mymodule

Note: as a general rule, prefer include-like class declarations such as that over resource-like ones such as we removed from init.pp.
Use the the command /path/to/puppet apply path/to/test.pp to run the test.


Why is a device needed between JTAG and the TRACE32 software from Lauterbach?

Question: What is the point of having this rectangular thingy like https://www.microsemi.com/images/soc/partners/solution/ip/Trace_small.jpg? How comes that gdbserver is able to debug over the Ethernet without any additional H/W and this TRACE32 behemoth S/W itself cannot decode/encode signals coming out of and to JTAG port? Isn't JTAG a port itself? Doesn't it send signals? Why cannot this piece of S/W interpret them? Why is this thingy needed (which BTW once works, once doesn't and in general is black magic). Is there a reason for existing of a specific device between JTAG and USB port (having in mind that TRACE32 installations has 800 MB...)
Answer: There are probably certain aspects to consider:

Run mode debugging vs. Stop mode debugging
Simple signal converter vs. Smart debug probe
Pure JTAG debugger vs. Debug & Trace tool

Run mode debugging vs. Stop mode debugging
"Run mode debugging" means "Debug an application on a system running an operating system". That is what is also happening when you debug an application on your Windows/Linux/Mac machine. When you hit a breakpoint in your application the CPU is still running. It is only the debugged application which is stopped.
So if your embedded system is running an operating system your GDB might be able to connect via Ethernet to a gdbserver running on your target OS, which allows your to debug an application on your device.
"Stop mode debugging" means "Debugging all software on a CPU by controlling the run-state of the CPU". So if you hit a breakpoint on a CPU with stop mode debugging, your entire CPU will stop. This allows you to debug bare metal applications or an operation system itself or an application in the context of the operation system or even a hypervisor.
For stop mode debugging you usually need a chip with a JTAG interface (or SWD or similar) and an in-circuit debugger. Basically something which allows you to control the CPU on a very low level. In former times this was done by using an in-circuit emulator (instead of JTAG) which replaced the CPU with a special bond-out chip, which allowed also to control the chip on a very low level. To make thinks more confusing some vendors call their JTAG probes also "in-circuit emulator".
Simple signal converter vs. Smart debug probe
For stop mode debugging you need a probe which converts the interfaces of your PC to the low level debug interface of your chip. So basically some USB to JTAG converter. Or and Ethernet to JTAG converter.
The simplest probe I can think of is simply some device which allows you to control some GPIOs (General Purpose Input Output) pins via USB. Then all the JTAG communication protocol and higher debug protocol is totally done in software. Advantage: Very flexible. Disadvantage: Very slow.
More advanced probes know how to do JTAG and thus, only the high level debug protocol has to be handled via USB, while the low level JTAG communication is done by the probe itself. These probes are often still quite slow, since USB is not so efficient when you need short latencies.
High end probes usually handle the debug protocol itself, which is individual for each CPU architecture or sometimes even for a single chip. So the host PC running the debug software sends only a high level command like "do a single step", while all the rest is handled by the probe itself. This boosts performance especially with complex multicore chips which required often a lot of JTAG communication until even a simple task completes.
Simple USB to JTAG converters are often already on the PCB of cheap evaluation boards. In theory you could also integrate such a converter directly in the chip itself, but this is usually not done by the chip manufacturers, since it would increase the costs of every single chip. In the professional sector high end debuggers are pretty common, because companies don't want to have their developers sitting in front of their PC just waiting for a slow debugger to finish an application download.
In general I assume that the faster, more flexible and more feature-rich a debugger is, the bigger and more expensive it gets. So it depends a lot on your needs.
Pure JTAG debugger vs. Debug & Trace tool
All JTAG debuggers allow you to stop and restart your CPU, set breakpoints and read and write memory and CPU registers. That is the stop more debugging I've mentioned above.
Some debug probes allow you also to record the code execution and data accesses by the CPU while the CPU is running and without stopping it. This is called a Real Time Trace. For such a trace recording you need both a debug probe and a chip which supports this.
E.g. on ARM Cortex chips this feature is called the ETM, which is not available with Cortex-M0/M0+ chips but usually available with Cortex-A/R chips and Cortex-M3 (and bigger) chips when the chip has 100 pins and more.
Tools which support trace are usually bigger and more expensive than debug probes without trace support.
Things which have an influence on the price of a debugger with trace recorder:

Size of internal memory to save the trace data
Supported maximum speed on one target trace pin (for parallel trace).
Number of supported trace pins (for parallel trace) (e.g. single pin SWO trace is usually much cheaper than ETM trace).
Support of high speed serial trace ports/maximum speed per lane/number of supported lanes.
Upload speed to the host PC (Does the probe have a USB 3 and/or Gigabit Ehternet inteface or just USB 2?)

The device from Lauterbach, which you are referring to, supports the tracing of Cortex-M chips with a total of 1600 MBit/s on the trace port. The official product page is here https://www.lauterbach.com/microtrace_cortexm.html

You wrote

which BTW once works, once doesn't and in general is black magic

If your tool is not working, I suggest to request support from your tool vendor. For Lauterbach visit https://www.lauterbach.com/tsupport.html
JTAG debugging itself is really not black magic: The JTAG protocol itself is an IEEE standard and the debug protocol (on the next level) is often described in the chip manufacturers manuals accessible to the public. However it is of course a lot of engineering.


Both sinks in guest bath spontaneously filled to the top

Question: I went into my extra bathroom today and noticed both sinks were filled to the brim with water, no overflow. Both of these sinks share a drain in the middle and I've had a clog before but couldn't snake it because it just went from one sink to the other and wouldn't go through the middle pipe that drains out.
I did just have a new HVAC system put in this and it is in the attic above this bathroom. Not sure if that has anything to do with it. Also, flushed the toilet the other day and heard a glug type noise but it seemed to go back to normal.
Any ideas what could cause this? Could it be the HVAC or is that just coincidence? I assume there's a clog somewhere down the line but I can say for almost complete certainty that nothing has been put down those sink drains.
Comment: Nothing in the overflow pan because the clog isn't right at the HVAC (sometimes it is, or more often it has to drain **up** using a pump, and the pump fails - but you're in the attic so it drains down), it is farther down so it gets down *past* the sinks and then hits the clog and comes out at the lowest point above the clog - which is your sinks. (Sometimes it is toilet or tub/shower, depends on how your pipes are set up.) This is going to be a plumber job *unless* you can take apart the drain pipes below the sinks and snake from there.
Comment: The HVAC system should have a condensate drain. See where that goes...
Comment: @manassehkatz-Moving2Codidact not going to lie, I went up there but it's really tight in my attic and I couldn't really tell what I was looking at. The only drain on that side of the house is this bathroom though (unless it has its own drain, which I wouldn't imagine is usual), it's almost above the bathroom.
Comment: So it sounds like (but really just guessing here) you (a) either have a clog or a serious venting problem and (b) condensate drains into the same pipe so it backed up into the sinks. On a hot humid day you can get a **LOT** of condensate - basically squeezing the water out of the air.
Comment: @manassehkatz-Moving2Codidact went back up and it's definitely draining to that drain. Nothing in the overflow pan though. The pipe is definitely clogged, if it was the AC or not I'm not sure anyone can say. I'll call the AC company in the morning and if they punt I'll call a plumber. You have to snake it from the roof anyway so I can't do it.
Answer: Just wanted to update this with an answer. Needed a plumber to come out and clear the pipe. Where the T is where the two sinks meet was clogged, since it is an old style you go from one sink to the other when trying to snake it so you have to go in from the roof.
The reason it became an issue after the new AC unit is because the new unit was pulling a lot more condensation and so it backed up faster. The clog wasn't 100% so some water could slowly drain out. Given those sinks don't see a ton of use, any time it was used there was enough time between the next use so it just never built up until the new AC unit was installed.
Plumber suggested a cup of drain-o type clog remover every three months as a preventative. Need to change out that T to a newer style that you can snake easier and save me the plumber bill but with the pipes behind the walls you can't tell where they meet and it's no guarantee that it is in the middle. He has a camera he can use that would tell so I wouldn't have to go tearing up my walls hoping for the best, might do that and put in an access door so I can clean it out easily.
Answer: It looks like the AC condensate drain is sharing a section of plumbing, and that there is an issue.
Usually, it's easy to disassemble the drain under a sink (with a bucket underneath!), remove the p-trap, and then snake through the common drain pipe. Also check the roof stack vent, which can cause backup, as well as odors.
[BTW, I recently had an acquaintance tell me of ceiling and wall damage due to condensate overflow from a newly-installed split AC.]
Comment: You need to fix your sink drain problem, it was improperly constructed. You need a cleanout that can actually access the sink drains, all the way into the wall and down.
Comment: @user1723699 As the answer states, you take off the trap and snake directly into the drain pipe, not through a sink, in the situation you have described. Put some pictures in by editing your question and we can give more detailed advice.
Comment: The problem is I have two sinks and if you try to snake it, it just goes into the other sink. Last time I had a clog the plumber got it from the roof so I guess I'll have to do that again
Comment: @kreemoweet I agree but it is not accessible without ripping apart a wall. I am heavily considering it now as it's the second time I've had this issue.
Comment: @Ecnerwal if it didn't mean ripping out drywall to (hopefully) be able to access that I would. There is no current access to the middle drain pipe.
Comment: Since the plumber cleaned *through the roof*, it's very likely he also cleared an issue was with the vent stack, as well as the drain. Are animals nesting in, or or falling into the vent?


Php code seems to run twice

Question: Can any any one help with the following code it runs and works fine but seems to always log a double entry each time for a single hint.
Not sure if its the host or my code
Time: 23rd February 2012 5:45:36 am
IP Address: xxx.xxx.141.162
Browser: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1Time: 23rd February 2012 5:45:36 am
IP Address: xxx.xxx.141.162
Browser: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1

.
<?php

    // Create a new image instance
    $im = imagecreatetruecolor(60, 20);

    // Make the background red
    imagefilledrectangle($im, 0, 0, 60, 20, 0xFF0000);

    // Draw a text string on the image
    imagestring($im, 3, 1, 1, 'Tracking', 0xCCFFFF);

    // Output the image to browser
    header('Content-Type: image/gif');

    imagegif($im);
    imagedestroy($im);

    // Get server variables
$address = $_SERVER['REMOTE_ADDR'];
$referer = isset($_SERVER['HTTP_REFERER']) ?
            $_SERVER['HTTP_REFERER'] : '';
$browser = $_SERVER['HTTP_USER_AGENT'];

    //Open log file
$file = fopen("log.html",'a');

//Set time zone and date format
date_default_timezone_set('Australia/Sydney');
$accessTime = date("jS F Y g:i:s a");

    //write collected data to file
fwrite($file, "Time: $accessTime
");

if( $address != null)
    fwrite($file,"IP Address: $address
");

if($referer != null)
    fwrite($file,"Referer: $referer
");

fwrite($file,"Browser: $browser
");

    // save file and close
fclose($file);

?>

Comment: It isn't this code causing it. Check any rewrite rules you may have on your hosting account.
Comment: a db is a much better way to do the logging. if your running Apache this is logged by the server by default.
Comment: Is that sample of the log correct? Every `Time` line has *two* following `IP`/`Browser` lines? Is that your actual code, or has it been modified?
Comment: Added a favicon so it is not that
Answer: I think this may be because of request to favicon.ico. Browser does request to http://your-site.com/favicon.ico and webserver rewrite this request to your script that log it to file. So you get two lines in log file.
Comment: Great idea, might be his issue.
Comment: @ceejayoz Try log $_SERVER['REQUEST_URI']
Comment: Hi Guys to try and answer your questions

I do not have any rewrite rules for this folder.

This is just a proof of concept where I needed to just log the date,time,ip and browser info to a text file so no need to do DB logging.

To see and test it

http://finch.herobo.com/stats/stats.php

This is the file I open in my browser window

This is the log file

http://finch.herobo.com/stats/log.html
Comment: The problem appears to be with firefox

I traced the http call and firefox makes 2 calls to the url when i tested with another browser it does not could some one else please test with firefox

here is the http llog

http://oi43.tinypic.com/34rvedh.jpg
Comment: @John may be used some plugin in Firefox that do additional request?
Comment: @Ramil Amr i have tried it with multiple machine and still the same issue. Please if you do have a copy of firefox please try it.
Comment: @all I have added the following to the script in an hope that more people will try it now that it does not hold the full ip address of the vising user.

$address = preg_replace('/\.\d+\.\d+$/', '.xxx.xxx', $address);

Php code seems to run twice


How to insert data into GCP Datastore which is in different project in VM instance?

Question: Hi I am new to GCP and python, I have one requirement:
I have 2 projects project_1 and project_2, I am running python code in project_1's VM instance and want to insert data into project_2's Datastore. I dont know how to set project_2 in the python code.
If there is any code which sends data to different project's datastore that would be helpful.
I am using this code and it is inserting data into project_1's datastore.
Please help me out.
Thanks in advance
from google.cloud import datastore
# Create, populate and persist an entity with keyID=1234
client = datastore.Client()
key = client.key('EntityKind', 1234)
entity = datastore.Entity(key=key)
entity.update({
    'foo': u'bar',
    'baz': 1337,
    'qux': False,
})
client.put(entity)
# Then get by key for this entity
result = client.get(key)
print(result)

Answer: Your question would benefit from showing some in finding the solution.
A Google search for "datastore.Client", returns the API documentation for the wrapper describing the parameters:
project (str) – (Optional) The project to pass to proxied API methods.
credentials (Credentials) – (Optional) The OAuth2 Credentials to use for this client.

You will want to specify the other project using the project argument.
You will need to ensure that the Service Account that you're using (probably the Compute Engine default Service Account but you should consider creating a specific Service Account for your code), includes appropriate IAM roles|permissions to read|write to Datastore, perhaps roles/datastore.user.
See this tutorial for getting started with the Cloud Client Libraries for Datastore using Python.
Comment: Thanks you so much for your inputs, datastore.Client(project=my-project) helped me..!!!!


WPF minimized owned windows should stay minimized, if Parent is minimized and then restored

Question: I have a Main window and a child window. The owner of the child window is main window. The child window is not a dialog. I have used the following code in the constructor of the child window:
this.Owner = Application.Current.MainWindow;
this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
this.ShowInTaskbar = false;

I have set this.ShowInTaskbar = false because I want the child window to be displayed in the bottom of the screen when minimized(and not in the taskbar). When I minimize the Main window, child window should also minimize(this is working). But when the child window is already minimized and then if I minimize and restore the main window the child window is also restoring. I want the child window to stay minimized if it was already minimized.
Comment: This is probably by design. Think Notepad Find window...
Comment: How you make "the child window to be displayed in the bottom of the screen when minimized(and not in the taskbar)"?  How you manage such state?
Comment: emoacht, That is default WPF behaviour. All you have to do is set ShowInTaskbar = false.
Comment: I understand you mean the title bar only window at the bottom edge of primary screen.
Answer: This behavior is by design but you can override it by checking for the child's WindowState property in the parent's StateChanged event. Set a flag if it was minimized, and manually minimize the child window when it's going to switch to normal while the flag is set.
In this sample I put a button for creating and opening a new child Window, and set the child's properties and event listeners in the parent class. So there are no XAML and code-behind files for the child window. The code looks like this:
XAML:
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="407,157,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
</Window>

Code-Behind:
public partial class MainWindow : Window
{
    private Window childWindow;
    private bool ignoreStateChange = false;

    public MainWindow()
    {
        InitializeComponent();
        this.StateChanged += MainWindow_StateChanged;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        childWindow = new Window() { Owner = this, WindowStartupLocation = WindowStartupLocation.CenterOwner, ShowInTaskbar = false };
        childWindow.StateChanged += ChildWindow_StateChanged;
        childWindow.Show();
    }

    private void MainWindow_StateChanged(object sender, EventArgs e)
    {
        if (WindowState == WindowState.Normal && childWindow?.WindowState == WindowState.Minimized)
            ignoreStateChange = true;
    }

    private void ChildWindow_StateChanged(object sender, EventArgs e)
    {
        if (ignoreStateChange)
        {
            ignoreStateChange = false;
            childWindow.WindowState = WindowState.Minimized;
            return;
        }
    }
}


jquery Isotope Custom Layout: masonry bottom

Question: Has anyone seen a custom layout for isotope which is masonry from bottom up? It is not that complicated in the original Masonry plugin, as demonstrated here.
jQuery Masonry from bottom up
However, I am having difficulty translating this method to masonry layout in the unminified Isotope. Any suggestions would be much appreciated.
Answer: I have not seen any custom layout. But, recently I changed the Isotope's js to reflect the bottom up masonary.
On line 590, Change the following code
<code>_positionAbs : function( x, y ) {
  return { left: x, top: y };
},
</code>
to
<code>_positionAbs : function( x, y ) {
  return (this.options.fromBottom) ? { left: x, bottom: y } : { left: x, top: y };
},
</code>
and then set the fromBottom options to true while calling. Optionally, you can add the same property in $.Isotope.settings on line 330.
P.S. I know its been two months but it may help someone.
Answer: You'll need to make the following changes:
Modify Isotope's _positionAbs method
Set transformsEnabled: false in the Isotope options
Add CSS transition property styles for right/top.
<code>$.Isotope.prototype._positionAbs = function( x, y ) {
   return { right: x, top: y };
};

// initialize Isotope
$('#container').isotope({
    transformsEnabled: false
    // other options...
});
</code>
and
<code>.isotope .isotope-item {
-webkit-transition-property: right, top, -webkit-transform, opacity;
 -moz-transition-property: right, top, -moz-transform, opacity;
  -ms-transition-property: right, top, -ms-transform, opacity;
   -o-transition-property: right, top, -o-transform, opacity;
      transition-property: right, top, transform, opacity;
}
</code>


Can a derived class define a member with the same name as a member from its base class? How to differentiate their usage?

Question: In C++ you can put a member in a base class and a member with the same name in the inherited class.
How can I access a specific one in the inherited class?
Comment: The question you should be asking is why do you have classes in the same inheritance hierarchy that have duplicately named members that are distinct?  See Effective C++ Item 33.
Comment: If your question is how to access the derived method from a base reference or pointer, add a comment. As it is written the question can be interpreted in two ways (and all answers deal with just one of them)
Comment: @TheJuice, I am not sure if this isn't a bad practice, but I've seen this in the code which uses the `PIMPL` idiom: base class has its own `m_pImpl` different from the child's one.
Answer: In that case you should fully qualify a member name.
class A
{
public:
  int x;
};

class B : public A
{
public:
  int x;
  B()
  {
    x = 0;
    A::x = 1;
  }
};

Comment: I thought it always worked like this. But with GCC 13, the compiler generates an error for this: `invalid use of non-static data member`.
Answer: If you specify the name you'll access the one in the inherited class automatically. If you mean how do you access the one in the base class, use Base::member
Answer: One approach (already mentioned in all other answers) is to use the qualified member name, like Base::member. It can be used in conjunction with explicit access through this pointer, if that's your style: this->Base::member.
Another approach is to perform access through this pointer explicitly converted to the base class type: ((Base *) this)->member.
Of course, the above  references to this pointer are made under assumption that you are trying to access the member from within some non-static member function of the class. To access if from "outside", the same tricks can be applied to any other pointer (or reference): some_pointer->Base::member or ((Base *) some_pointer)->member.
For data members these two approaches are equivalent. For member functions they can lead to different results with virtual functions. For this reason, in general, the first approach should be preferred.
Answer: To access the hidden member in the base class you have to prefix the member name with the base class name.  See below:
class A
{
protected:
   int i;
};

class B : public A
{
public:
   void foo( void )
   {
      int a_i = A::i;
      int b_i = i;
      int b_i_as_well = B::i;
   }
private:
   int i;
};

Answer: Yes.
Qualify your call, f(), with a class name: SpecificClass::f().
Answer: By prefixing it with classname::.
Answer: #include <iostream>
using namespace std;

struct Base {
    int memfcn();
};

struct Derived : Base {
    int memfcn(int);
};

int main() {
    Derived d;
    Base b;
    d.Base::memfcn();  //you can even use :: in conjunction with dot(.). This is new to me.
}


How do I check values in a list of class in python?

Question: Hello I define a class person as following:
class Person(object):
    def __init__(self, X, Y):
        self.name = X
        self.city = Y
names = ['Bob', 'Alex', 'John']
cities = ['New York', 'London', 'Rome']
N = list()
for i in range(0,3):
    x = names[i]
    y = cities[i]
    N.append(Person(x,y))

I want to to check the corresponding cities of a name automatically, something like this
N.name['Bob'].city =
'New York'

Comment: Not possible with classes (in current form). If there's a one-one relation (or one-many), then consider using dictionaries.
Answer: Use python dictionaries
people = {}
names = ['Bob', 'Alex', 'John']
cities = ['New York', 'London', 'Rome']
if len(names) != len(cities):
  # You might want to do something other than a base exception call here
  raise Exception('names and cities must be of equal size')
for i in range(len(names)):
  people[names[i]] = cities[i]
print(people['Bob'])

>>>'New York'

Answer: Create a dictionary with name as key:
class Person(object):
    def __init__(self, name, city):
        self.name = name
        self.city = city
names = ['Bob', 'Alex', 'John']
cities = ['New York', 'London', 'Rome']

persons = {n: Person(n,c) for n,c in zip(names, cities)}

print(persons['Bob'].city)


Why can't I dominate certain law enforcement?

Question: I'm trying to understand how you can effectively dominate a SWAT/FBI/whatever law enforcement in payday 2, because only certain ones are "able" to be dominated. which confuses me, how is this determined?
Also, I already know that tasers and higher can't be dominated, but the question is for the weaker forces, regular SWAT/FBI and guards.
Anyone on this list of law enforcement: http://payday.wikia.com/wiki/Enemies_%28Payday_2%29
The further down the list you go, obviously the harder it is to dominate them, but what determines this? Is there any clue to try to dominate a specific one instead getting myself killed trying to do so.
Comment: The skill is chance based... Does that help?
Comment: @Ramhound which means it's random xd
Comment: Guards are all created equally.  You are allowed one dominated guard per played after 4 are dominated it won't work.  Also you can't dominate after a shot is fired at them.
Comment: I'm really just trying to get an answer that doesn't say its random, because i don't think anything in games is ever random, they just might seem random, but they normally work under some kind of formula/algorithm.
Comment: @Sickest Ever heard of an RNG? There is a massive number of things in games that are random... Really not sure where you got otherwise.
Answer: Domination has a complex set of conditions and multipliers that affect your chances, and there is a state and duration combination that is very similar to shouting down civilians.  The Long Guide has a section, "Domination," just after the ones on stealth.  It's a long section, but well worth reading.
During stealth, if you shout at them (and have Domination skill) within 1.5 seconds of alerting, you will succeed.
Out of stealth, an enemy will never surrender if he is at full health and not reloading.
Answer: It's random. If you have the skill dominator from the mastermind tree, you can dominate in stealth like 99% of the time. While you're already seen and the alarm has been set off, it's alot harder.

The further down the list you go, obviously the harder it is to
dominate them, but what determines this? Is there any clue to try to
dominate a specific one instead getting myself killed trying to do
so.

the tactic everyone uses is just shoot him with a bullet till he really stops shooting and then try it again. Do this over and over again. There isn't a clue to try to dominate a specific one.
Comment: @Ramhound Can you please use @ username so people know you are talking to them. Now he wont be notified
Comment: thats not true, i have those perks and its not 99% of the time whats so ever. It's not even close to 99%, more like 10% with FBI / Swat.
Comment: Depends if they have been shot at.  Your current question only says guards not FBI/SWAT...
Comment: @Ramhound Yeah which counts as most stealth missions. Thats why I say 99%. Guards are like very easy. There isn't a real specific chance.
Comment: @Sickest FBI? FBI isn't hard to dominate... You mean the ones from firestarter day 2? Swat isn't even there when in stealth.
Comment: Well... the question has changed from guards to "Certain law enforcement"
Comment: The original question mentions "Tasers and higher", which gives away that he meant all law enforcement by "guards", you just need to make a slight adjustment to the answer.
Comment: @3ventic His question stated: `Also, i already know that Tasers and higher can't be dominated, but the question is for the weaker forces` So it's not about the tasers and highers.
Comment: An FBI and guard and special "Taser" are all different.  Only the actual guards are guards...only Non-specials can be dominated
Comment: @ramhound FBI(IF he means the one from firestarter day 2) and guards(From banks and juwelry's) are easily the same to dominate. Also police officers really feel the same to me.
Comment: http://payday.wikia.com/wiki/Enemies_%28Payday_2%29
Comment: @Sickest Aha well sorry I went for the thing I remembered the best... Thanks anyway.
Comment: That page is wrong you can only dominate and cuff 1 guard per player
Comment: No; his user name is to much of a pain to type on a phone; also my last comment applies to all
Comment: @ramhound You can actually dominate a guard, joker him, and dominate another, that would be 2 dominated guards, i didn't read the page just merely pointed it out to show the FBI agents in the game for Loko.
Comment: @Sickest I editted the answer to answer your main question.
Comment: Try aiming while you dominate.


SES not allow to authenticate

Question: SES not allow me to authenticate.
I can able to telnet on port 25 but whenever I am giving "AUTH LOGIN" below commands the connection was lost.

$ telnet.exe email-smtp.us-west-2.amazonaws.com 25
Trying 188.8.131.52...
Connected to email-smtp.us-west-2.amazonaws.com.
Escape character is '^]'.
220 email-smtp.amazonaws.com ESMTP SimpleEmailService-1207632523 AyQgU69E2tr9zUK96DuI
ehlo example.com
250-email-smtp.amazonaws.com
250-8BITMIME
250-SIZE 10485760
250-STARTTLS
250-AUTH PLAIN LOGIN
250 Ok
STARTTLS
220 Ready to start TLS
AUTH LOGIN

Connection closed by foreign host.

I am following below link:
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-smtp-client-command-line.html
Any help much appreciated.
Answer: 220 Ready to start TLS has to be followed by TLS negotiation from your side.  You can't send cleartext after that, as you are doing.
To test interactively from the command line, follow the examples using openssl s_client, which you can think of as "ssl telnet," if that helps. That isn't precisely accurate, but in this case, it's close enough.

SES not allow to authenticate


Creating a List in python for Google App Engine

Question: Before i go on, let me say that i have searched the Internet for clarification before i am asking it here.I have a class
class Course(ndb.model):
  tutor = ndb.StringProperty(required=True)
  ...

and a Student class.
I want to include in the Course class a list of Students (represented by their id)registered on the course.From my search, i came across options like StringListProperty() from this website and class ListProperty(item_type, verbose_name=None, default=None, ...) from the Google tutorial on Types and Property Classes.I am still confused as to which is the right way to do this.I need a layman's explanation and possibly a guide to where i can find a tutorial with example.Thanks
Answer: You've got a bunch of options, but probably the most straight forward is to use a ndb.KeyProperty with repeated=True.  The values will be the key of your particular student.  e.g.:
class Student(ndb.Model):
    name = ndb.StringProperty()

class Course(ndb.Model):
    students = ndb.KeyProperty(repeated=True)

def create_course(students):
    """Create a new course object and return it.

    Args:
        students: iterable of `Student` model instances.
    """
    c = Course()
    c.students = [s.key for s in students]
    return c

Comment: It would be a classmethod of the Course class.  This approach has some potential down sides.  If you have large numbers of students it may not scale.  You may find that you have an enrolment for each year in the course.  Also you would probably want to manage adding students to the course after the fact. Do you need to record date of enrollment, can students join during a course duration - ie semester etc.....
Comment: Can students be enrolled in more than one course? Do you need to keep historical details about past enrollments ?
Comment: No,students cannot be enrolled in more than one course.And a course can have a maximum of 10 students.I haven't thought about keeping such details but might be added,


PostgreSQL, Hibernate : Default increase sequence length by 1

Question: I am working on a Spring-MVC project in which we are using Hibernate as our ORM and PostgreSQL as the database. We have a Students class, whose ID we are using in one of the PDF form generated, and for business reasons we require that the number be incremented by 1 always. I checked that the allocation-size parameter can be changed for Hibernate, but does it also effect the underlying sequence in PostgreSQL or do I have to create a new one?
If the underlying sequence is not altered by Hibernate, how can I change the sequence so that it's auto-incremented by 1 in PostgreSQL. Thank you.
Code :
  @Id
    @Column(name="studentid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "student_gen")
    @SequenceGenerator(name = "student_gen",sequenceName = "student_seq",allocationSize = 1)
    private int studentid;

Answer: No, the sequence in Postgres won't be changed just by modifying the Hibernate annotation.
You can use ALTER SEQUENCE student_seq INCREMENT BY 1 to modify the sequence.
Comment: Thank you. If I don't change the allocation size on Model and just give the above command, is that okay? As it will take us a new deployment. Thank you.
Comment: No, it won't be okay actually. See http://stackoverflow.com/questions/2595124/java-jpa-generators-sequencegenerator and http://stackoverflow.com/questions/5346147/hibernate-oracle-sequence-produces-large-gap for more info. Basically the generator works **with** the database sequence, and unless the `allocationSize` is the same as `INCREMENT BY`, the values generated can become really odd.


Can the CPU scout players for me?

Question: In previous Madden games with in-season scouting, there's been an option to allow the CPU to do it for you.
In Madden 17, I can't find one. If I sim a week, I lose half the unused scouting points from the previous week. I assumed that simming multiple weeks would result in the CPU scouting for me, since it would be impossible for me to spend the points myself, but alas that is not the case. I tried simming about 4 weeks, and lost hundreds of scouting points without getting any additional information. Not sure if they really thought that through.
This is a problem, as I'm trying to set up a franchise where I just sim each regular season. That franchise isn't going to do too well if they never scout any college players.
Is there a way to get the computer to scout players for you? How?
Answer: There does not seem to be, no.
My eventual solution to this was to just let the computer draft as well. If it's drafting, then I don't need to see the scouting reports.
Of course, the computer is terrible at drafting, but it would probably be terrible at scouting as well.
If nothing else, this should help prevent the power creep from my great drafting that eventually leads to me winning 8 out of 10 super bowls and starting a new franchise for some competition.

Can the CPU scout players for me?