.NET 6 not showing up in Visual Studio 2022

Question: I have .NET 6 installed.

But it doesn't show up.

I even have the "Use previews of the .NET SDK" on.
I don't understand what I'm missing.
Comment: And is this an existing project? The project file for .NET 6.0 projects works differently. You may need to use the upgrade assistant: https://learn.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-winforms-framework
Comment: Try to download and install the [SDK](https://dotnet.microsoft.com/en-us/download/dotnet/6.0)
Comment: SDK in "Install other frameworks"? Already did it.
Comment: What exactly are you trying to do? What type of project are you setting up?
Comment: Forms App @ewerspej
Comment: You mean Windows Forms?
Comment: Yes.. @ewerspej
Answer: First of all .NET Framework 6.0 does not exist, the latest release is actually .NET Framework 4.8.1. What you mean is .NET 6 or if you prefer using the old naming then .NET core 6.
For you to use .NET 6 be sure to create a project using a template without the (.NET Framework) at the end (if coming from an existing .NET Framework project you need to migrate it to .NET 6)
.NET Framework and .NET (.NET Core) are completely different enviroments, .NET Framework being the oldest which is replaced by the newer .NET (.NET Core).
You can check this for more information about .NET Framework vs .NET Core vs .NET vs .NET Standard vs C#.
Comment: Yes, exactly. To upgrade a Windows Forms project to .NET 6.0, it's usually necessary to use the upgrade assistant or manually change the project file: https://learn.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-winforms-framework
Answer: Exactly right like Mike said.
You should try cmd to check if dotnet is installed or not.
Try dotnet list-sdks to show all versions installed for dotnet core.
Or you can see the selected version by dotnet --version


Skipp the error while scraping a list of urls form a csv

Question: I managed to scrape a list of urls from a CSV file, but I got a problem, the scraping stops when it hits a broken link. Also it prints a lot of None lines, is it possible to get rid of them ?
Would appreciate some help here. Thank you in advance !
Here is the code :
#!/usr/bin/python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup #required to parse html
import requests #required to make request

#read file
with open('urls.csv','r') as f:
    csv_raw_cont=f.read()

#split by line
split_csv=csv_raw_cont.split('\n')

#specify separator
separator=";"

#iterate over each line
for each in split_csv:

    #specify the row index
    url_row_index=0 #in our csv example file the url is the first row so we set 0

    #get the url
    url = each.split(separator)[url_row_index]

    #fetch content from server
    html = requests.get(url).content

    #soup fetched content
    soup = BeautifulSoup(html,'lxml')

    tags = soup.find("div", {"class": "productsPicture"}).findAll("a")

    for tag in tags:
       print(tag.get('href'))

And the result with the error looks like this :
https://www.tennis-point.com/asics-gel-resolution-7-all-court-shoe-men-white-silver-02013802720000.html
None
https://www.tennis-point.com/cep-ultralight-run-sports-socks-men-black-light-green-12143000063000.html
None
https://www.tennis-point.com/asics-gel-solution-speed-3-clay-court-shoe-men-white-grey-02013802634000.html
None
https://www.tennis-point.com/asics-gel-solution-speed-3-all-court-shoe-men-white-silver-02013802723000.html
None
https://www.tennis-point.com/asics-gel-challenger-9-indoor-carpet-shoe-men-white-grey-02012401735000.html
None
https://www.tennis-point.com/asics-gel-court-speed-clay-court-shoe-men-dark-blue-yellow-02014202833000.html
None
https://www.tennis-point.com/asics-gel-court-speed-all-court-shoe-men-white-silver-02014202832000.html
None
Traceback (most recent call last):
File "/Users/imaging-adrian/Desktop/Python Scripts/close_to_work.py", line 33, in <module>
tags = soup.find("div", {"class": "productsPicture"}).findAll("a")
AttributeError: 'NoneType' object has no attribute 'findAll'
[Finished in 3.7s with exit code 1]
[shell_cmd: python -u "/Users/imaging-adrian/Desktop/Python
Scripts/close_to_work.py"]
[dir: /Users/imaging-adrian/Desktop/Python Scripts]
[path: /Users/imaging-adrian/anaconda3/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/munki]

The links inside my CSV files look like this :
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E701Y-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E601N-4907;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E601N-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E600N-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E326Y-0174;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E801N-4589;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E800N-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E800N-9093;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E800N-4589;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E804N-9095;

Comment: Can you fix your indentation please. Also, always try to use csv module to parse a csv file. Don't parse it with `split`.
Comment: :( sorry, I'm very new to Python.
Comment: @AnotherUser31 even if you're new to Python, you certainly know that Python uses indentation to delimit code blocks, so your code snippet is not only invalid, it's also impossible for another developer to understand the control flow.
Comment: @brunodesthuilliers  I got ya ! I'll try to fix it ! gimme a minute
Answer: Here is working version,
from bs4 import BeautifulSoup
import requests
import csv

with open('urls.csv', 'r') as csvFile, open('results.csv', 'w', newline='') as results:
    reader = csv.reader(csvFile, delimiter=';')
    writer = csv.writer(results)

    for row in reader:
        # get the url
        url = row[0]

        # fetch content from server
        html = requests.get(url).content

        # soup fetched content
        soup = BeautifulSoup(html, 'html.parser')

        divTag = soup.find("div", {"class": "productsPicture"})

        if divTag:
            tags = divTag.findAll("a")
        else:
            continue

        for tag in tags:
            res = tag.get('href')
            if res != None:
                writer.writerow([res])

Comment: I think you are close, I just got an error saying : SyntaxError: 'continue' not properly in loop
Comment: The first part is right (except possibly for the `continue` statement), the second is a WTF - `tags` will either be an empty list or a list of `tag.a` objects - it will never contain both tags and `None` values.
Comment: Alright managed to fix the continue. it should be "continue" inside semicolons. But than I got another error, NameError: name 'findAll' is not defined :(
Comment: @AnotherUser31 it should be `divTag.findAll("a")` (I fixed it in the answer).
Comment: @brunodesthuilliers no errors but no links either :(   it should print some urls :((
Comment: @AnotherUser31 this is another problem. Using an intermediate variable to store and test the result of `soup.find()` solves your initial problem (the AttributeError) so you should consider accepting BcK's answer and start debugging your new problem instead (and post a new question with your updated code if you cannot solve the problem by yourself).
Comment: @brunodesthuilliers thank you very much for your time ! but what I am looking for now ? how to print the links ? kinda confused how should I call my new question ?
Comment: @AnotherUser31 Sorry I was busy, couldn't answer, but apparently you still haven't corrected your indentation. If you want proper help, please ask properly. Your code is really confusing, no one will want to help if you ask like this.
Comment: @BcK I did updated the code, can u have a look please ? Thank you so much !
Comment: @AnotherUser31 Added solution.
Comment: @BcK you are the man !!!!! it works so smooth !!!!  I know I ask too much, but how is it possible to save the results into a csv file?
Comment: @AnotherUser31 updated and cleared the code to include writing to a file.
Comment: @BcK you are amazing ! teşekkür ederim ! there's a way to contact you ? wanna ask more questions !
Comment: @AnotherUser31 Yeah, you can always email me at **firstname.lastname@example.com**. You are welcome.


Get names from foreign keys

Question: For my internship I am making a assignment for tournaments in the break (pool billiard, FIFA, darts etc)
I made a database with all the players and a list with games and the winners.
Players (p_id PK, name)

Games (g_id PK, player_one FK, player_two FK)

Winners (g_id FK, winner FK)

So in games you can pick the players and by winners, you can pick the winner from the players.
How can I show the names of the players in a table instead of the ID of the player?
Comment: what did you try so far?
Comment: `SELECT w.*, p.name FROM Winners w JOIN Players p ON w.winner = p.p_id`
Comment: I tried doing some stuff with join and inner joins that I looked up. I am not the best joiner, but I am not getting the right results.
Comment: **some stuff** is very informative, thank you for your explanation
Answer: Something like
SELECT
    g.g_id,
    p1.name as `player_one`,
    p2.name as `player_two`
FROM Games g
INNER JOIN Players p1
ON p1.p_id = g.player_one
INNER JOIN Players p2
ON p2.p_id = g.player_two

For your games table and
SELECT
    w.g_id,
    p.name as `winner`
FROM Winners w
INNER JOIN Players p
ON p.p_id = w.winner

For your winners table
And to join all three together
SELECT
    g.g_id
    ,p1.name AS `player_one`
    ,p2.name AS `player_two`
    ,pw.name AS `winner`
FROM Games g
INNER JOIN Players p1
ON p1.p_id = g.player_one
INNER JOIN Players p2
ON p2.p_id = g.player_two
LEFT JOIN Winners w
ON w.g_id = g.g_id
LEFT JOIN Players pw
ON pw.p_id = w.winner

Get names from foreign keys


Is it a bug of grails?

Question: When I typed these code, it works perfectly.
def users = User.getAll(params.userChecked)*.id
println 'user : ' + users

But when I did like this, it shows error
def users = User.getAll(params.userChecked)*.id
println 'user : ' + users

def x = [1, 2]
x.each(){
  def roles = Role.withCriteria{
      users {
             eq 'id', new Long(80)
            }
  }
  println roles
}

But when I removed above code, the below was normally worked.
def x = [1, 2]
x.each(){
  def roles = Role.withCriteria{
      users {
             eq 'id', new Long(80)
            }
  }
  println roles
}

I didn't understand what's wrong ? Here's the error
No signature of method: java.util.ArrayList.call()...

Answer: You just replace
def users = User.getAll(params.userChecked)*.id

with
 def usersList = User.getAll(params.userChecked)*.id

You have two different list one in hasMany, that name users and another defining in controller that creating confusion just change name . All code will work fine.
 def users = User.getAll(params.userChecked)*.id
    println 'user : ' + users

    def x = [1, 2]
    x.each(){
      def roles = Role.withCriteria{
          users {
                 eq 'id', new Long(80)
                }
      }
      println roles
    }

Comment: The root of the problem is that when there is a variable named `users` in scope at the point when you call `withCriteria`, the `users { ... }` block inside the criteria closure is treated by Groovy as an invocation of the `call` method of the in-scope `users` object, rather than as an invocation of the `users` method on the criteria builder (the closure delegate).
Answer: As explained in the other answer, the problem is the name clash between the users variable in the outer scope and the users {...} call inside the criteria closure.  The simplest way to fix this is to rename the variable, but if that is not an option then an alternative fix is to use delegate. inside the closure:
def roles = Role.withCriteria{
  delegate.users {
    eq 'id', new Long(80)
  }
}

This removes the ambiguity and forces Groovy to send the call to the closure delegate (the criteria builder) instead of the variable in the containing scope.  You can use the same trick anywhere else where you have a name clash with a builder, I've had to use it in the past when creating XML with a MarkupBuilder.

Is it a bug of grails?


Delphi - deferring assignment to an out parameter

Question: In Delphi, suppose I have a method with a (much simplified) signature like this:
procedure abc( const prop1:string; const arg1:TValue; const prop2:string;
  out arg2:TValue );

I'm building a TList<PPropValPair> of records like this using the parameters provided:
type
  TPVPType = (ptIn, ptOut);
  PPropValPair = ^TPropValPair;
  TPropValPair = record
    io   : TPVPType;
    prop : string;     // property name
    iVal : TValue;     // input value
    oVar : Variant;    // <-- how to save for later use???  Variant? TValue?
  end;

(On the face of it, this example looks silly. Again, it's quite simplified just to communicate the problem.)
At run-time, I want to stuff all of the input values ival (where io=ptIn) into each public property 'prop' in a class, call a class method, then extract the values of all public properites 'prop' (where io=ptOut) into oVar.
The input side is working fine using RTTI.
However, I need to somehow save a REFERENCE to the output vars in oVar so I can save the value of the associated properties after the class method has been called.
I'm not assigning anything to arg2 directly. Rather, I'm saving a reference to arg2 and assigning the value indirectly later on.
The trick is ... I don't want to have to do any additional annotations of the output parameters in abc(...).
In C++, you can declare a parameter as a 'reference' by prepending it with '&'.  So in C++ terms this might be defined roughly as:
procedure abc( arg1 : TValue; &arg2 : TValue );

Later, you can refer to &arg2 and it's using a POINTER to the object.  But in calling the function, you just say:
abc( somevar1, somevar2 );

somevar1 is passed by value, and somevar2 is passed by reference. Inside the function, I can save somevar2 in a reference var, then later on assign a value to it via the pointer (if it's a string) by saying &arg2ref = 'abc'.
I'm guessing there's a way to do this in Delphi, either with a Variant as the oVar type, or using RTTI, or something else.  I just haven't figured out the magic combination of pieces yet.  (I just don't use pointers very often in Delphi.)
Maybe I need to save a raw pointer in oVar along with the type (say, oType), and cast a value through the pointer to save the property's value?
I'm hoping someone here might have some clear ideas.
BTW, I'm using Delphi XE3.
Answer: Use a pointer. It doesn't have to (and indeed shouldn't) be a "raw" pointer. Use a typed pointer, PValue. Pass in a PValue to your function, and then store that in oVal, which you should also declare a a PValue. Use @ to create a pointer, and ^ to dereference.
I would not recommend passing arg2 by reference. Although you can still use @ on it to get a pointer to the original variable passed to abc, the reference parameter disguises the fact that the variable needs to remain available indefinitely. Instead, declare arg2 as PValue so it's more obvious to the caller that indirection is involved.
// declaration
procedure abc(...; arg2: PValue);

// call
abc(..., @somevar2);

Comment: So what would the signature and call look like with PValue?

The scope of all these variables is relatively limited - sometimes just a few lines in a procedure, sometimes a dozen or two. I'm not concerned about lifetime of the references, although it's good to know.
Comment: The ultimate target assignment looks generally like this:

   arg^.oVar := aProp.GetValue(thisForm);

aProp is a TValue. How do I get that into oVar if it's a PValue?
Comment: Consider reading the [documentation about pointers and pointer types](http://docwiki.embarcadero.com/RADStudio/XE3/en/Pointers_and_Pointer_Types).
Comment: I'd prefer to avoid using the @ on the out vars in the function call. I've found that the documentation on pointers isn't very helpful when interacting with RTTI stuff.
Comment: Suit yourself. The documentation applies equally well to `TValue` as it does to a `PValue` with the `^` operator applied to it, so the specific place you use `@` will have no effect on where and how you use RTTI.
Comment: The problem is I either get a compiler error or a run-time error trying to assign the TValue to a PValue. The PValue seems to be untyped. I haven't been able to come up with a combination that works.
Comment: The purpose of using the TValue is it's like a variant in that it figures out the type itself. But saving through an untyped pointer means you have to cast it to something, and we don't know at run-time what that is. A TValue assignment (on the left) would figure it out, but the PValue cannot -- it wants a hard cast, which negates the purpose of having the TValue.  Maybe there's a way for the TValue to force a write through the pointer? (eg, the Make method? Or something similar in TValue? I'm not that familiar with TValues to be sure.)
Comment: Further research suggests I need to use TValue.ExtractRawData(thePValue); -- I'll try this and report back.
Comment: I never said to use an untyped pointer. Use a typed pointer; namely, `PValue`. The thing a `PValue` variable points at will behave identically in every way to a variable of type `TValue`. To get a `TValue` from a `PValue`, simply apply the `^` operator to it, just like you would apply the `*` operator in C. You've already demonstrated knowledge of that operator in a previous comment. You only have to make one change to apply the `^` operator to `oVar`: `arg^.oVar^ := aProp.GetValue(thisForm)`.


Autoscroll when UINavigationbar Prompt text is too long?

Question: If I have a very long text as the prompt text, ex:
[[self navigationItem] setPrompt:[NSString stringWithFormat:@"This is a very long message which I want it to be scrolled. So that the user can read all the text."]];

How can I make it scroll automatically?
My solution is:

Set the promptText to nil.
Create a UILabel with the long text.
Animate the uilabel.position.x and use a loop.
Answer: Mostly Torn answers this question in his blog
http://blog.stormyprods.com/2009/10/simple-scrolling-uilabel-for-iphone.html


Hang Bathroom Light Fixture

Question: I've hung multiple lighting options before, but they have always been when there is a electrical box in the wall behind the drywall.  In this case, I removed the old light fixture in my bathroom, and there was a circular hole in the wall with wires hanging out of the wall.
Since there is no electrical box for me to screw the mounting bracket into, what is the proper way for me to hang the light fixture?
Comment: Many bathroom fixtures have integral junction boxes, negating the need for an in-wall box. Does yours?
Comment: Or this? [Bathroom vanity light with no junction box](https://diy.stackexchange.com/questions/119964/bathroom-vanity-light-with-no-junction-box)
Comment: Or this? [Old Work Box for Vanity Light?](https://diy.stackexchange.com/questions/154803/old-work-box-for-vanity-light)
Answer: To do it right, you will need to install a round junction box and mount it securely and route the wires through it. Then attach your fixture to the box.
You can use one like this if there's a stud by the hole.

or this if there's no stud where the hole is.
Answer: You need an "old work light box" (example pictured).

In case you're not familiar with "old work" vs "new work" - old work is for retrofits where the walls are already finished. New work is used for new construction where they can install before the drywall & paint is applied.
Light boxes are what should have been installed here. If your round hole is very small you might need to embiggen it to the size that will fit a light box, and if it's very much larger than the box you might need to cut the drywall and replace a section of it - if you do that, you might as well install a New Work light box since you'll have the drywall off anyway.

Hang Bathroom Light Fixture


How does the game know when to increase the one handed weapon skill?

Question: I play a stealth character that does 30x backstabbing damage, so I basically one shot most enemies with my dagger if I can get close enough. But my one handed weapons skill rarely increases. I can't recall ever getting a skill increase from a backstab kill.
How does the game know when to increase the one handed weapon skill?
Answer: According to wiki information (from UESP and Wikia), you get experience in skill based on base damage and not the number of hits or the damage done. As such, damage multipliers do not provide any extra experience to skill.
You can try finding a trainer or use following books to get some skill points:
The following books also increase the player's skill, with some easier ways to get them:

2920, Morning Star, v1 (In Northwatch Keep - On a shelf behind the counter in the dining area.)
Fire and Darkness (No real easy way to get it)
Mace Etiquette (In Fort Greenwell's Captain's Quarters, on the floor.)
Night Falls on Sentinel (Can show up as random loot in chests.)
The Importance of Where (In Jorgen and Lami's House in Morthal - inside the bucket on the barrel to the left of the bed.)
Oghma Infinium (Gained through a quest "Discerning the Transmundane" and disappears after reading.)

The following miscellaneous quests increase the One-Handed Skill:

Retrieve Amren's family sword for Amren in Whiterun. This also
increases Block.
Retrieve Hjalti's sword for The Ghost of Old Hroldan at Old Hroldan
Inn. This also increases Block.
Find Rjorn's Drum for Giraud Gemane in The Bard College in Solitude.
This also increases all other combat-oriented skills such as Heavy
Armor and Smithing.
Help Wulf Wild-Blood in Skaal Village find out what became of his
brother. This also increases Block, Archery and Heavy Armor. (Dragonborn DLC only)

Following people can help you train your skills for money:

Amren of Whiterun (Common)
Athis of the Companions in Whiterun (Expert)
Chief Burguk in Dushnikh Yal (Master)

If you want to use less legitimate ways, certain targets can serve as an exploit for training combat skills, because they are essential, and therefore cannot normally die, because they may be expendable, or because they have high health or can regenerate health. They are not normally "enemies".
They include: Shadowmere, Hadvar or Ralof during Unbound, creatures you have conjured, Paarthurnax (before starting his quest), and M'aiq the Liar.
Another, more "easy" way is to use trainers then pickpocket the money back. Becoming Harbinger of The Companions will also allow training to expert level with Athis and you can have him as a follower which allows all the gold spent training to be returned (take it from his inventory).
Source(s):

http://www.uesp.net/wiki/Skyrim:One-handed
http://elderscrolls.wikia.com/wiki/Skill_(Skyrim)
http://elderscrolls.wikia.com/wiki/One-Handed_Weapons
Comment: also, trolls, if you have no problem surviving in a fight with one, just find a troll, attack it a couple times, let it regenerate and continue.


Showing $\int_0^{\infty}(1-F_X(x))dx=E(X)$ in both discrete and continuous cases

Question: Ok, according to some notes I have, the following is true for a random variable $X$ that can only take on positive values, i.e $P(X<0=0)$
$\int_0^{\infty}(1-F_X(x))dx=\int_0^{\infty}P(X>x)dx$
$=\int_0^{\infty}\int_x^{\infty}f_X(y)dydx$
$=\int_0^{\infty}\int_0^{y}dxf_X(y)dy$
$=\int_0^{\infty}yf_X(y)dy=E(X)$
I'm not seeing the steps here clearly. The first line is obvious and the second makes sense to me, as we are using the fact that the probability of a random variable being greater than a given value is just the density evaluated from that value to infinity.
Where I'm lost is why:
$=\int_x^{\infty}f_X(y)dy=\int_0^{y}f_X(y)dy$
Also, doesn't the last line equal E(Y) and not E(X)?
How would we extend this to the discrete case, where the pmf is defined only for values of X in the non-negative integers?
Thank you
Comment: You are integrating a function of two variables over the region $\{(x,y) \colon x \leq y < \infty, 0 \leq x < \leq \infty\}$ by letting $y$ vary from a fixed $x$ all the way to $\infty$ (inner integral) and then letting $x$ vary from $0$ to $\infty$ (outer integral). An alternative way is to fix $y$ and so $x$ varies from $0$ to $y$ (inner integral) and then let $y$ vary from $0$ to $\infty$ (outer integral).  Since the _integrand_ is not a function of $x$ at all, the inner integral just gives $y$.
Comment: See the answers to [this question](http://math.stackexchange.com/q/64186/15941).  The proof for the discrete case is, in my opinion, easier for beginners to understand.
Comment: It's not

$$ \int_x^\infty f_X(y)\,dy = \int_0^y f_X(y)\,dy.$$

The order of integration is changed (allowed per Fubini's theorem), you have

$$\int_0^\infty \left(\int_x^\infty f_X(y)\,dy \right)\, dx = \int_0^\infty \left(\int_0^ydx \right)\,f_X(y) dy.$$
Comment: @DilipSarwate, thank you for the explanation. It does make sense now.
Comment: Even though there's already a [good link](https://math.stackexchange.com/questions/64186) provided by Dilip Sarwate, I'd still like to make the links to the current choice of target posts for [continuous](https://math.stackexchange.com/questions/172841) and [discrete](https://math.stackexchange.com/questions/843845). Please see the meta post for [(abstract) duplicates](https://math.meta.stackexchange.com/a/29382/356647).
Answer: The region of integration for the double integral is $x,y \geq 0$ and $y \geq x$. If you express this integral by first integrating with respect to $y$, then the region of integration for $y$ is $[x, \infty)$. However if you exchange the order of integration and first integrate with respect to $x$, then the region of integration for $x$ is $[0,y]$. The reason why you get $E(X)$ and not something like $E(Y)$ is that $y$ is just a dummy variable of integration, whereas $X$ is the actual random variable that defines $f_X$.


Spring Boot Project cannot run by IntelliJ IDE

Question: Edit:
Here's the WebApplication file:
@SpringBootApplication
@EnableAsync
@EnableAutoConfiguration
public class WebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WebApplication.class);
    }
}

I am using IntelliJ(15.0.2) to run a spring boot project,
It is working properly when I execute java -jar spring-boot-sample.war
Unfortunately it failed to run by IDE and complained Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
The error details are as follows:
[2016-07-25 12:32:46.979] boot - 5719 ERROR [restartedMain] --- SpringApplication: Application startup failed
org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766)
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180)
    at com.rentacoder.WebApplication.main(WebApplication.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:185)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 13 more
[2016-07-25 12:32:47.014] boot - 5719  INFO [restartedMain] --- ClasspathLoggingApplicationListener: Application failed to start with classpath: [file:/Users/hzhang/work/workplace/IdeaProjects/RHS/target/classes/]

Below is the dependencies settings in the POM file:
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
        <relativePath/>
    </parent>

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

Did I miss something in POM settings?
Comment: It looks like you're trying to run it using a _spring boot application class_. Can you share that as well? Also can you try uncommenting the `provided from the `spring-boot-starter-tomcat` so when you launch the application it will use the embedded tomcat and retry?
Comment: @Morfic  Please check my edit, I post the application file; I commented out provided from the spring-boot-starter-tomcat, unfortunately, it is still not working
Comment: USe  @SpringBootApplication annotation before class defination
Comment: Is that all of it? Like @PankajKumar suggested, how are you configuring your spring context, java-annotation or XML?
Comment: Everything seems fine ....just try adding that annotation..as your spring is not starting...this annotation helps to boot
Comment: @PankajKumar please see my edit. I have annotations. I suspect my configuration is wrong. I only configured `Main class` and `Use classpath of module`
Answer: As a quick workaround, you can add a jar configuration that uses the resulting jar from target folder.
In this way you can start the application normally or in debug mode.
As a drawback for this approach: you won't have the hotswap available and you will see the changes only after a maven build. But in this case I usually add in the add jar run configuration window in before section a maven goal with "clean package -DskipTests" so each time I press run I will have the latest changes available.
This is a quickfix; the problem can be solved in other ways - I done it some times ago but I can't remember exactly what was the problematic dependency - you need to dig a little in Spring source code with some debugging around the methods from which the exception jumps.
Answer: How did you set the Configuration on IntelliJ? Since it's a WAR file, you'd need to have a web server container. Your pom has spring-boot-starter-tomcat, so you'll need to create a Tomcat Server configuration. This is a paid feature in IntelliJ, so you probably can't do it with the community edition.
A work-around is to create a Remote Debugging on your war file:
http://blog.trifork.com/2014/07/14/how-to-remotely-debug-application-running-on-tomcat-from-within-intellij-idea/
Comment: @RickChen  Can you please provide some valid link? The one you posted is empty.  BTW, I am using Intellij Ultimate
Comment: Not trying to be patronising, but do you have any official docs to support your statement that `you'll need a tomcat server configuration in IJ after adding spring-boot-starter-tomcat`? As far as I know it's the exact opposite, it will provide you with an [embedded tomcat preconfigured to make it _work out of the box_](http://projects.spring.io/spring-boot/), so you can run your app from the _main class_. After all, I believe this is the reasoning behind boot being opinionated, am I wrong?
Comment: @HaifengZhang the link works if you remove the `]` at the end, it's most likely an unfortunate formatting error
Comment: @Morfic Thanks for correcting the link. I've updated the answer. As for the question of embedded vs running in a container, you were right that boot can do both. Since the OP didn't specify the entire pom file for me to see the packaging tag, I made an assumption based on the fact that it had produced a war instead of a jar, which would create the Embed error that he experienced.


My backend is not working , Can someone help figure out the issue with my code?

Question: [This is the output of Results.html and the second image is the debug(console output) I am building an web app in python3 , I am using flask and html , the app is suppose to receive any Mathematical problem from the user input, try to solve it and return the results in results.html, but the issue now is that every time  I enter a problem it keeps on returning "no solution found"
app.py

from flask import Flask, render_template, request

app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        problem = request.form['problem']
        # code to solve problem goes here
        return render_template('results.html')
    else:
        return render_template('index.html')

# Define function for solving problems
def solve_problem(problem_str):
    problem_str = problem_str.replace(" ", "")
    # Check if the problem has been solved before
    if problem_str in prev_problems:
        return prev_problems[problem_str]

    # Check if the problem is an equation
    if "=" in problem_str:
        # Parse the equation
        left, right = problem_str.split("=")
        expr = sympy.parsing.sympy_parser.parse_expr(left) - sympy.parsing.sympy_parser.parse_expr(right)

        # Solve the equation
        solutions = sympy.solve(expr, sympy.symbols('x'))

        # If the left-hand side was not zero, add the right-hand side to the solutions
        if left != str(solutions[0]):
            solutions = [sol + sympy.parsing.sympy_parser.parse_expr(right) for sol in solutions]

    # Check if the problem is a system of equations
    elif 'system' in problem_str:
        eqns = problem_str.split(',')
        eqns = [sympy.parsing.sympy_parser.parse_expr(eqn) for eqn in eqns]
        vars = []
        for eqn in eqns:
            vars += list(eqn.free_symbols)
        vars = sorted(set(vars), key=lambda var: str(var))
        solutions = sympy.solve(eqns, vars)

    # Check if the problem is a polynomial equation
    elif 'polynomial' in problem_str:
        expr = sympy.parsing.sympy_parser.parse_expr(problem_str.replace('polynomial', ''))
        solutions = sympy.roots(expr, multiple=True)

    # Check if the problem is a derivative
    elif 'derivative' in problem_str:
        expr, x, a = problem_str.split(',')
        expr = sympy.parsing.sympy_parser.parse_expr(expr)
        a = float(a)
        solutions = sympy.diff(expr, sympy.symbols(x)).subs(sympy.symbols(x), a)

    # Check if the problem is an integral
    elif 'integral' in problem_str:
        expr, x, a, b = problem_str.split(',')
        expr = sympy.parsing.sympy_parser.parse_expr(expr)
        a = float(a)
        b = float(b)
        solutions = sympy.integrate(expr, (sympy.symbols(x), a, b))

    # Check if the problem is a Fourier series
    elif 'fourier series' in problem_str:
        expr, x, a, b = problem_str.split(',')
        expr = sympy.parsing.sympy_parser.parse_expr(expr)
        a = float(a)
        b = float(b)
        period = b - a
        fs = sympy.fourier_series(expr, (symbols(x), a, b))
        solutions = fs.truncate(n=5)

    # Check if the problem is a partial differential equation
    elif 'heat equation' in problem_str:
        x, y, t = symbols('x y t')
        u = sympy.Function('u')(x, y, t)
        k = symbols('k')
        eq = Eq(sympy.diff(u, t) - k*(sympy.diff(u, x, x) + sympy.diff(u, y, y)), 0)
        solutions = sympy.pde.pdsolve(eq)

    else:
        # Parse the problem into a SymPy expression
        expr = sympy.parsing.sympy_parser.parse_expr(problem_str)

        # Solve the problem by simplifying the expression
        solutions = sympy.simplify(expr)

    # Check for additional functionality
    if 'sin' in problem_str or 'cos' in problem_str:
        solutions = sympy.solveset(expr, symbols('x'))
    elif 'tan' in problem_str:
        expr = sympy.parsing.sympy_parser.parse_expr(problem_str)
        solutions = sympy.simplify(expr)

    elif 'limit' in problem_str:
        expr, x, a = problem_str.split(',')
        expr = sympy.parsing.sympy_parser.parse_expr(expr)
        a = float(a)
        solutions = sympy.limit(expr, symbols(x), a)

    elif 'second derivative' in problem_str:
        expr = problem_str.replace('second derivative of ', '')
        expr = sympy.parsing.sympy_parser.parse_expr(expr)
        solutions = sympy.diff(expr, symbols('x'), 2)

    elif 'heat equation' in problem_str:
        u = sympy.Function('u')(symbols('x'), symbols('y'))
        eq = sympy.Eq(sympy.diff(u, symbols('x'), symbols('x')) + sympy.diff(u, symbols('y'), symbols('y')), 0)
        solutions = sympy.pde.pdsolve(eq)

    # Check if the problem is a second-order differential equation
    elif 'second order differential equation' in problem_str:
        # Parse the equation
        expr, x = symbols('y'), symbols('x')
        y = sympy.Function('y')(x)
        eq = sympy.Eq(sympy.diff(y, x, x) + 2*sympy.diff(y, x) + 5*y, 0)
        solutions = sympy.dsolve(eq)

    # Check if the problem is a partial differential equation with more than two variables
    elif 'wave equation' in problem_str:
        x, y, z, t = symbols('x y z t')
        u = sympy.Function('u')(x, y, z, t)
        eq = Eq(sympy.diff(u, t, t) - sympy.diff(u, x, x) - sympy.diff(u, y, y) - sympy.diff(u, z, z), 0)
        solutions = sympy.pde.pdsolve(eq)

    elif 'plot' in problem_str:
        # Parse the function and plot
        expr = sympy.parsing.sympy_parser.parse_expr(problem_str.replace('plot ', ''))
        p = plot(expr, show=False)
        p.show()
        return "Graph displayed."

    elif 'numeric' in problem_str:
        # Parse the function, convert to a lambda function, and evaluate numerically
        expr = sympy.parsing.sympy_parser.parse_expr(problem_str.replace('numeric ', ''))
        f = lambdify(x, expr)
        a, b = [float(x) for x in input("Enter the start and end points: ").split()]
        n = int(input("Enter the number of steps: "))
        x_vals = [a + i*(b-a)/n for i in range(n+1)]
        y_vals = [f(x) for x in x_vals]
        p = plot(expr, (x, a, b), show=False)
        p.scatter(x_vals, y_vals)
        p.show()
        return "Graph displayed."
    else:
        pass

    # Store the solution in the previous problems dictionary
    prev_problems[problem_str] = solutions

    # Return the solution(s) to the user
    return solutions

@app.route('/result')
def result():
    problem = request.args.get('problem')
    explanation = solve_problem(problem)
    return render_template('results.html', problem=problem, explanation=explanation)

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

results.html

Math Problem Solver

        {% if explanation %}

{{ explanation }}

        {% else %}

No solution found.

        {% endif

index.html

    <form action="/" method="POST">
        Enter a math problem:

        <input type="text" id="problem" name="problem">

        <button type="submit">Solve</button>
    </form>

I have already tried testing the solve_problem function without the gui implementation , it is working fine providing the write answers, but I just can't get it to work on gui version.
I am sorry if this sounds like an easy issue but I would appreciate any input as someone who is still learning.
Thank you in advance.
Comment: Can you update your question with the error you see in the console?
Comment: I just added two images , one is the output of results.html and the other is the debug(console) output. The console doesn't show any error, I think the issue might be with my syntax or indentation but I have been going through the code over and over again, still no luck.
Answer: Does your code ever call solve_problem()? It looks like your index.html form posts pack to your index function, which then simply calls return render_template('results.html') without including the explanation. You also have a /result route, but I don't think that is called either.
Perhaps you want to change your /index route similar to:
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        problem = request.form['problem']
        explanation = solve_problem(problem)
        return render_template('results.html', explanation=explanation, problem=problem)
    else:
        return render_template('index.html')


Junction box partially behind drywall and partially exposed

Question: Let's say I have a 200 amp breaker panel that is flush mount.  I want to wire in an EVSE across the garage using conduit.  Somehow I need to make that transition for the conduit from behind the drywall to conduit on the surface of the drywall.  I believe a junction box is the right way to do this.  The obvious solution is a surface mount junction box and have conduit enter it from the back, turn in the box, and come out the side to continue on the rest of the way.
I'm wondering, can I get a deep (> 6") junction box and have it partially in the wall and partially exposed so that the conduit from the panel could come in through the top of the box on the back half and exit out the side on the front half?  I would probably mount the box to the wall stud on the side of the box.
<code>   ----
   |  |
   |  | breaker panel
   |  |
   ----
    |
    |  conduit behind drywall
    |
    ---
    | |  junction box
    | |-------------------  <- conduit on surface of drywall to EVSE
    ---
</code>
Can a conduit body be used in this way instead of a junction box (assuming a sweep elbow fits in the stud space to change from down to out)?
It's a 2"x6" exterior wall.  Will be using PVC schedule 80 conduit on the exposed run.
Answer: You can certainly do it with a junction box (in the wall) an an extension ring (out of the wall.) I don't know if there's anything against using a deep box halfway out of the wall as you suggest or not.
If a sweep fits, an LB will do - or if you don't actually need a pull point there, an offset through the surface of the wall will also do. Just make sure it adds up to less than 360° in bends between pull points. i.e. you are in conduit on both side of the drywall surface, there's no transition. You need a box if it's cable on one part and conduit on the other - if it's all conduit, bring it through the wall, mud and paint the wall around the conduit penetration (or use fireblock foam/caulk if the wall requires, or a fancy fire collar if the LAHJ insists) and keep going.
Answer: Yes you can have a box in the wall and exposed.
Also schedule 80 for the exposed run will be fine.
The only issue I see in your drawing is the face of the junction box is where you have the conduit coming out. The face of the box must be accessible (have to be able to open it) but coming out the side will be fine.
Answer: You might be making it harder than it is.
Come down out of the service panel to a flush mount junction box.  I might use a 4-11/16" because it will be more versatile and it's easier to find with knockouts for 1" conduit.
That's a perfectly ordinary installation that can be adapted to many uses.
Then, slap an extension box on top of it.   The extension box will have appropriate knockouts on the side, come out of that with surface conduit or regular conduit.
Comment: A Raco 187 works good for this, mount horizontal and mount to two device box or mud ring using 4 small screw holes. You are limited to 3/4" conduit, but 40% fill is not a problem, 3@#8 and 1@10 is only 26% sch40 pvc fill.
Comment: 32% sch80 pvc fill, but question why sch80?
Comment: Schedule 80 because it will all be exposed to potential damage.
Comment: EMT may be a better choice if you're not married to plastic. EMT handles the ground path for you, so one less wire.  It's also much better at the jobs we use conduit and junction boxes for, e.g. damage resistance and ability to contain arcing (it just arcs to box and that trips the breaker).
Answer: Junction boxes can be fittied with only the face showing (as is common in finished rooms) or on the surface of the wall (more common in industrial settings). there are different boxes for the two applications.
fitting one half-exposed seems perverse: getting a good transision to drywall could be tricky.
It seems to me that you could mount a junction box on the surface of the wall and have the conduit enter through the drywall from the back and exit from the side.
You could do the same thing use an ell back conduit body. (LB body)
Answer: Just a note, if you're not close to your bend limit, you may not need a JB.  If you have a conduit bender it is not particularly hard to offset a pipe to the surface of a wall.  Just bend your offset to the correct depth, install it, install drywall around it with a 1/4" gap for caulk, caulk the hole for a nice look, and continue the pipe once the surface is finished. If the wall is a fire wall you need fire caulk.  This can be made to look very clean and professional.
If you do want a box and the depth your pipe runs behind the wall is compliant, you can also add a 90 and put a connector on it so when the boarding is on you can just attach the connector to a knockout on the back of a surface mount box or screw on an LB.
Answer: I think you shall install a junction box just as usually done, then with the cover shown below, you can connect the exposed conduit through the hole (with applicable fittings/connectors).

Comment: This has merit, but it would need to be flexible conduit I think.  Otherwise the conduit would render the j-box inaccessible.
Comment: You have to be able to remove the cover. Which won't be happening with a chunk of schedule 80 PVC attached to the cover and the wall. These covers have a very limited scope of use, and this ain't it.


Same Bosch batteries, but one battery only works in one tool, what can I do?

Question: So, I have some BAT612 18V batteries from Bosch.
I should be able to use both batteries with either of my tools (Angle Grinder - GWS18V-45PC, Drill - DDS181A), but one battery works in both tools and the other only works in the drill.
Does anyone know why this is the case?
Or maybe how to fix it?
Comment: Maybe one is tired and the circuitry in the grinder doesn't consider it adequate. The tools are designed to not over-drain LI batteries because that can destroy them.
Comment: @isherwood OCP/UVP is handled by the battery's charge controller (built into each battery pack), not the tool.
Comment: You're probably right, but I wonder if it isn't a little of both. My only other idea is a quirky contact issue.
Comment: Yeah, I could see that the contact issue, but they both are fairly straight and new, but I did notice when I clicked the battery in that doesn't work in the Angle Grinder. I can push the battery check button and everything is OK until i press the tools trigger. Then it cuts off.
Answer: Contact issue, I think. Please see if one tool has a deeper contact than the other. Or rough up the tool contact with some sand paper.


How can I find the root of $f(x)=x^2-\cos(x) \qquad [0,2\pi]$ using Newton method?

Question: Considering to apply the Newton method to find $f$ root, which is the initial value of $x_0$:
\begin{cases} x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)} \\ x_0=?
\end{cases}

Study of the function $f$ on the interval $[0,2\pi]$:

$$f(0) \ f(2\pi)<0$$
$$f'(x)=2x+\sin(x)>0 \qquad \forall x \in [0,2\pi]$$

So: $$\exists! \qquad x^*\in [0,2\pi]: f(x^*)=0$$

Theorem of Newton method convergence:
$$sign (x_0-x^*)=sign(f' f'')$$

$$f''(x)=2+\cos(x)$$
$$sign(f' f'')=1$$

$$x_0=2\pi$$
Is it correct?
Thanks!
Comment: Since $f$ is convex, Newton's method will eventually work as long as $x_0$ is not exactly at the minimum, which in this case is $0$. (However, if you choose $x_0<0$ you will find the negative root.)
Answer: You can try just about anything as $x_0$, and see where it leads you.  $x_0 = 0$ would get you in trouble right away, as $f'(0) = 0$; $x_0$ too close to $0$ would also be bad because $f'(0)$ will be nearly $0$, leading to a very large $x_1$.  $x_0 = \pi/4$ might be a good choice, because $f(\pi/4)$ is rather close to $0$.
Answer: $x^2-\cos(x)$ is increasing and convex on $[0,2\pi]$, hence if you start Newton's iteration at the right of the only root you get a decreasing sequence converging to your root (with the chance to employ some steps of the secant method in-between to improve the convergence speed). Since $1^2-\cos(1)$ is positive but not that large, it is not a bad idea to start iterating at $x_0=1$.
With few iterations we get that the root is at $\approx 0.8241323123$.


os.environ not setting environment variables

Question: I'm trying to set a Windows environment variable using Python.
It seems that, contrary to the docs, os.environ can get environment variables but cannot set them. Try running these in a Windows Command Prompt:
This works:
python -c "import os; print(os.environ['PATH'])"

This does not:
python -c "import os; os.environ['FOO'] = 'BAR'"

Try typing set in the Command Prompt. The environment variable FOO does not exist.
How can I set a permanent Windows environment variable from Python?
Comment: See http://stackoverflow.com/questions/235435/environment-variables-in-python-on-linux or http://stackoverflow.com/questions/488366/how-do-i-make-environment-variable-changes-stick-in-python
Comment: Think of this as a feature for your protection: nothing that a subshell does can mess with the program that calls it.  This allows you to call./create subshells with confidence that it won't interfere with any of your environment variables.
Comment: @CharlesDuffy, what's specific to Python is that the `os.environ` dict can get out of sync with the actual process environment, e.g. a DLL function could call `_putenv`.
Comment: @CharlesDuffy, this sync quirk is noteworthy; it's something every Python programmer should know, and so bears repeating even as a tangential comment. Also, technically the environment variables set in the current process can outlive it by spawning child processes. ;-)
Comment: If you want to check whether `os.environ` is creating environment variables, checking from your shell is the wrong tool. Use Process Explorer to inspect the state of your Python process, and you'll see that these truly are created, even though they don't outlive the process that creates them.
Comment: By the way, this is how environment variables work everywhere -- in every language and every operating system I'm aware of. Nothing specific to Python.
Comment: @eryksun: True, but hardly pertinent to the question immediately at hand.
Comment: For windows I can recommend a module to set variables through registry. Also has CLI app: https://github.com/beliaev-maksim/py_setenv this has good control on user/system level and does not have limit in length as setx
Answer: os.environ[...] = ... sets the environment variable only for the duration of the python process (or its child processes).
It is not easily (i.e. without employing OS-specific tools) possible and surely not advisable to set the variable for the shell from which you run Python. See aumo's comment for alternative and somewhat obscure approaches to the problem.


Using Eloquent relationship to retrieve data for child relationship

Question: I'm using Laravel 5.6 and MySQL. I have categories, sub_categories, category_info, and services.
A category can have 1 or more sub_categories. A category belongs to one menu category
A sub_category has only one category.
A category has 1 category info record. It doesn't matter if its a category or sub_category it will have one record in the category_info table.
My table structure is as follows
Menu_Categories
id
1,
2

Categories
id, parent_category_id, menu_category_id
1, null, 1
2, null, 1
3, 1, null
4, 1, null

Category_Info
category_id, name
1, Legal Services
2, Misc
3, US Legal Services
4, Europe Legal Services

Controller
$cats = MenuCategories
        ::with(['categories', 'categories.info', 'categories.sub_categories'])
        ->get();

Menu Categories Model
public function categories() {
    return $this->hasMany(Categories::class, 'menu_category_id', 'id');
}

Categories Model
public function menu_categories() {
    return $this->belongsTo(MenuCategories::class, 'menu_category_id');
}

   public function sub_categories() {
    return $this->hasOne(Categories::class, 'parent_category_id');
}

public function info() {
    return $this->hasOne(CategoryInfo::class, 'category_id');
}

SubCategory Info Model
    public function category() {
    return $this->belongsTo(CategoryInfo::class);
}

I need to return the categories and the category info as follows
{
    Categories: {
        {
            id: 1,
            parent_category_id, null,
            Sub_Categories: {
                {
                    id: 3
                    parent_category_id: 1
                    Category_Info: {
                        {
                            category_id: 3,
                            name: US Legal Services
                        }
                    }
                },
                {
                    id: 4
                    parent_category_id: 1,
                    Category_Info: {
                        {
                            category_id: 4,
                            name: Europe Legal Services
                        }
                    }
                },
            },
            Category_Info: {
                {
                    category_id: 3,
                    name: Legal Services
                }
            }
        },
        {
            id: 2,
            parent_category_id, null,
            Category_Info: {
                {
                    category_id: 3,
                    name: Misc
                }
            }
        },
    }
}

With the way I have relationships set up it is returning data incorrectly. It is not returning Category_Info for sub_categories.
{
    Categories: {
        {
            id: 1,
            parent_category_id, null,
            Sub_Categories: {
                {
                    id: 3
                    parent_category_id: 1
                },
                {
                    id: 4
                    parent_category_id: 1,
                },
            },
            Category_Info: {
                {
                    category_id: 3,
                    name: Legal Services
                }
            }
        },
        {
            id: 2,
            parent_category_id, null,
            Category_Info: {
                {
                    category_id: 3,
                    name: Misc
                }
            }
        },
    }
}

Is it possible to return Category_Info for the sub_categories as well? Thanks in advance.
Comment: `'categories.sub_categories.info'`?
Comment: it worked, thank you!
Answer: Thank you to Jonas Staudenmeir for helping me out

$cats = MenuCategories
        ::with(['categories', 'categories.info', 'categories.sub_categories', 'categories.sub_categories.info'])
        ->get();


How can I cast an ASP.NET Label?

Question: I have an ASP.NET page. I have labels like:

Çalıştığı Kurumun Unvanı

There are 10 of them in each 15 pages. In a condition, I want to change the innerTexts of these labels. Therefore in Page Load or Init, I want to write something like this:
foreach (Control ctrl in mainDiv.Controls)
{
    if (ctrl.GetType().BaseType.Equals(CalistigiFirmaUnvanLabel.GetType())
    {
        //if this labels innerText is in my Dictionary, then change it like (Label).InnerText = sth;
    }
}

However, the "Label" cast doesn't work. When I look at the type of calistigifirmaVergiNoLabel, it says it is System.Web.UI.HtmlControls.HtmlGenericControl. When I cast Label for the ctrl inside the inner if, it doesn't have a property "InnerText". How can I cast it? Also, this code takes the div's too. I only want the labels. I deleted the BaseType but then it didn't enter the if statement.
Comment: That's because a `` is a `HtmlGenericControl`. If you want to use the ASP Label then declare it as ``
Comment: can't I do it with an html label?
Comment: Yeh, use `if (ctrl is HtmlGenericControl)` then cast it to that type and then check its `InnerText`.
Comment: Thank you. I'll change the Control to HTMLGenericControl
Answer: You can access html labels from C# or divs for that matter too (HtmlGenericControl, or (HtmlGenericControl("label")) and type cast it to their respective types after calling findControl().  If you want to access it without the findcontrol and type cast, you need to have the 'asp' tag prefix  like:
<asp:Label

and you need to include runat="server" in the control attributes so that the code behind can access it directly. (and so it shows for you in intellisense)
Comment: I couldn't find the HTMLLabel. Right now, I am trying the HtmlGenericControl. It doesn't matter it takes the divs but I just don't want the dictionary to make a useless lookup
Comment: I'm sorry man, I forgot the label was weird, what you're looking for is: HtmlGenericControl myLabel = new HtmlGenericControl("label");
Comment: Sorry I put the wrong label here. The actual ones have the runat="server".
Answer: You can use the runat="server" property with the HtmlGenericlControl like this:
Çalıştığı Kurumun Unvanı

When the runat="server" property is applied, you can then access your label in code like this:
string labelText = CalistigiFirmaUnvanLabel.InnerText;

However, this answer assumes that each of the 10 labels on the page have different IDs.
Answer: Label = <asp:Label id="x" runat="server" />
 gets translated as an HtmlGenericControl; however, you should be able to use this to figure out what the underlying tag is, check for the label tag, and process acccordingly.  Or use the server-side equivalent, so the server-side code works as you expect.
Also, them you can do:
if (ctrl is Label)
{
   string text = ((Label)ctrl).Text;
}

How can I cast an ASP.NET Label?


Update util-linux on Ubuntu 12.04 LTS to 2.23

Question: Does anyone know how to update util-linux on Ubuntu 12.04 LTS to util-linux 2.23 version? I really need the nsenter command feature which is not present in util-linux 2.20 I currently have.
Answer: You currently can't do that using the standard apt-get approach, because the package is not available in the official repo.
You have a few options:

install from 3rd party ppa or site that offers binary packages for your distro
download and compile from source - https://www.kernel.org/pub/linux/utils/util-linux/v2.23/
Comment: I have tried to install it from an `.rpm` package by converting it do `.deb` with `alien` and an error is raised, couldn't get to install it.
Comment: what's the error? you can always try on a test environment to build the package from source, but that can easily get out of hand, depending on the links with other libraries...
Comment: `dpkg -i util-linux_2.23.2-7.1_amd64.deb
(Reading database ... 65363 files and directories currently installed.)
Preparing to replace util-linux 2.20.1-1ubuntu3 (using util-linux_2.23.2-7.1_amd64.deb) ...
Unpacking replacement util-linux ...
dpkg: error processing util-linux_2.23.2-7.1_amd64.deb (--install):
 trying to overwrite '/bin/login', which is also in package login 1:18.104.22.168+svn3283-3ubuntu5.1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
 util-linux_2.23.2-7.1_amd64.deb`


What is ${\rm Aut}(G^n)$?

Question: Suppose $G$ a finite indecomposable group such that $Z(G)=\{e\}$.
Now consider $G^n$. What is ${\rm Aut}(G^n)$?
My claim is ${\rm Aut}(G^n)={\rm Aut}(G)^n \rtimes S_n$.
Comment: You need to assume in addition that $G$ is indecomposable. Then it is true. It can be proved using the Krull-Schmidt Theorem.
Comment: This is false. Take, for example, $G=S_3\times S_3$.
Comment: With $G = S_3 \times S_3$, ${\rm Aut}(G^2) = S_3^4 \rtimes S_4$.
Answer: The Krull-Schmidt Theorem (see Wikipedia article - it was apparently first proved by Wedderburn, and also by Remak) says that for a group $G$ satisfying ACC and DCC on normal subgroups (which holds in particular for finite groups), if $G \cong G_1 \times \cdots \times G_k \cong H_1 \times \cdots \times H_l$, with each $G_i,H_i$ indecomposable, then $k=l$, the $H_i$ can be reordered such that $G_i \cong H_i$ for all $i$, and also $G \cong G_1 \times \cdots \times G_{k-1} \times H_k$. In other words, $G_k$ can be replaced by $H_k$ in the decomposition.
Now assume that $Z(G)=1$. Since $G_k$ can be replaced by $H_k$, $H_k$ must project onto the quotient group $G/(G_1 \times \cdots \times G_{k-1})$. Let $g =(g_1,\ldots,g_{k-1},g_k) \in H_k$ with $g_i \in G_i$. If some $1 \ne g_i$ with $i \le k-1$ then, since $g_i \not\in Z(G_i)$, taking the commutator of $g$ with an element of $G_i$ that does not centralize $g_i$ gives an element in $G_i \cap H_k$, contradiction. So $G_k=H_k$. Similarly we can show that $G_i=H_i$ for all $i$, so the direct decomposition of $G$ into indecomposable groups is unique, and not just unique up to isomorphism.
So, if $Z(G) = 1$ and $G \cong G_1 \times \cdots \times G_k$ with $G_i$ indecomposable, then ${\rm Aut(G)}$ is isomorphic to the semidirect product of ${\rm Aut}(G_1) \times \cdots \times {\rm Aut}(G_k)$ with the subgroup of $S_k$ that permutes the isomorphic $G_i$.

What is ${\rm Aut}(G^n)$?


Cast error when drawing Subgraphs in MSAGL

Question: I have a root Subgraph object with four child Subgraphs each containing a few Nodes. I have added all the Subgraphs and Nodes to the Graph and set the RootSubgraph on the Graph. However, when trying to draw the Graph I get a cast error from within the library (Microsoft.Msagl.GraphViewerGdi.Draw.cs, line 1044) where the GeometryNode of a Subgraph is cast to a Cluster. The GeometryNode is set to a Cluster in GeometryGraphCreator.ProcessSubgraphs and the error message gives me no information about why the cast fails. How can I fix this?
For now I've simply set the Label to null to avoid the drawing code but I would like to use a label eventually.
Answer: The problem was in my initialisation of the Subgraph:
var subgraph = new Subgraph(id)
{
    Attr =
    {
        Id = id,
        FillColor = fillColor,
    },
    Label =
    {
       FontSize = 10,
       Text = id
    }
};

Assigning the Label property this way skipped some extra set up code needed to correctly link the Label with the Subgraph. Leaving it out altogether lets the constructor handle the Label itself.


In mean value theorem over $[x_0,x]$, will $x^* \to+\infty$ always as $x \to +\infty$?

Question: The mean value theorem states that if $f:\Bbb R \to \Bbb R$ is continuous over $[x_0,x]$, and differentiable over $(x_0,x)$, then there exists $x^*\in(x_0,x)$ s.t. $f'({x^*}) = \frac{{f(x) - f({x_0})}}{{x - {x_0}}}$.
Now suppose $f$ is differentiable over $[x_0,+\infty)$, do we always have (or we can let, in cases like $f(x)$ is constant) $x^* \to+\infty$ as $x \to +\infty$? If not, on what condition this can happen?
Comment: You probably meant $f'(x^*) = \cdots$.
Comment: Consider $f(x) = \sin(x)$...
Answer: This is false. Consider $f\left( x \right) = \left\{ {\begin{array}{*{20}{c}}
  0&{x \geqslant 0} \\
  {{e^{\frac{1}{x}}}}&{x < 0}
\end{array}} \right.$
It is easy to verify $f(x)$ is differentiable over $\Bbb R$ and ${f'}\left( x \right) = \left\{ {\begin{array}{*{20}{c}}
0&{x \ge 0}\\
{ - {x^{ - 2}}{e^{{x^{ - 1}}}}}&{x < 0}
\end{array}} \right.$
We can choose any $x_0<0$, and notice $\frac{{f\left( x \right) - f({x_0})}}{{x - {x_0}}} < 0$ for any $x>x_0$, implying $x^*<0$ for any $x_0<x<+∞$, and we actually have $x^*→0$ as $x→+∞$.
Answer: The counter example by Tony is nice, but I wanted to find a counter example which would not be piecewise, unfortunately I had not much success.
My idea was that since $x^*$ depends of $x$
Then it is equivalent to have a function $\phi$ such that $\displaystyle{\frac{f(x)}{x}=f'(\phi(x))}$
The request that $x^*$ does not go to infinity is that $\phi$ is bounded on some interval $[x_0,+\infty[$.
Also in order to pull out an ODE verified by $f$, having $\phi$ a square root of identity $\phi(\phi(x))=x$ would help a lot, because that makes it easy to get rid of $f''(\phi(x))$ since $\phi$ is its own inverse.
$f(x)=xf'(\phi(x))$
$f'(x)=f'(\phi(x))+x\phi'(x)f''(\phi(x))$
$\displaystyle{\frac{f(x)}{x}=f'(\phi(x))=f'(x)+\phi(x)\phi'(\phi(x))f''(x)}$
So $f$ verifies the ODE : $\bigg(x\;\phi(x)\;\phi'(\phi(x))\bigg) y''+x\;y'-y=0$

first try $\phi(x)=\frac 1x$

This gives $-x^2y''+xy'-y=0\quad$ solutions $y=ax+bx\ln(x)$
Unfortunately, reporting in the initial equation for $\frac{f(x)}{x}$ gives $b=0$ and $f(x)=ax$ is not a counter-example, we can take any $x^*$ since $f'$ is constant.

second try $\phi(x)=\frac{1-x}{1+x}$

This gives $x(\frac{x^2-1}{2})y''+xy'-y=0\quad$ solutions $y=ax+b\big(1+(2x\ln(x-1)-2x\ln(x)\big)$
And again, this leads to $b=0$.
Thus, I feel like I'm being cursed, it is like the term before $y''$ never existed... So much for trying to find a neat counter-example.


How to install matplotlib 2.0 beta on Windows?

Question: I follow the standard installation procedure for matplotlib on Windows. I type the following commands in my terminal:
    > python -m pip install -U pip setuptools
    > python -m pip install matplotlib

Then I check my matplotlib version:
    > python
    >>> import matplotlib
    >>> matplotlib.__version__
    '1.5.1'

Apparently this installation procedure doesn't give me the latest matplotlib version. The latest stable release is '1.5.3'. I would expect to get at least that version.
Even better, I would like to test out the latest beta release: '2.0.0 b4'. What instructions should I type in my terminal to get that version?
Note:
I'm using the following python version:
>>> import sys
>>> sys.version
'3.5.2 |Anaconda 2.5.0 (64-bit)| (default, Jul  5 2016, 11:41:13)
[MSC v.1900 64 bit (AMD64)]'

Comment: Added an edit to get is as a .whl file to save you the trouble of compiling from source.
Answer: for matplotlib 1.5.3
conda update matplotlib

for matplotlib-2.0.0b4 use wheels provided here :
use the .whl as follows :
pip install some-package.whl


Install Ubuntu to external HDD from a current Ubuntu installation?

Question: I'd like to install Ubuntu 18.04 on a USB HDD.  I'm currently running Ubuntu 16.04 on my internal HDD - can I just plug the external drive in and run the installer from my current OS?  I haven't found any info on how to do that, but it seems like I shouldn't need to reboot just to install an OS on an unused HDD.
Comment: Nope. Any method you use that is done with the current system active is likely to corrupt your destination.
Comment: Why is that?  If I tell the installer to use /dev/sdb I don't see why it would care what's going on with /dev/sda.
Answer:
but it seems like I shouldn't need to reboot just to install an OS on an unused HDD

Have you ever seen a method from any OS creators on how to do that?  I have not. Well not yet.
You can create an exact copy from 1 partition to another partition with ...
dd if=/dev/sdX of=/dev/sdY bs=64K conv=noerror,sync

where if is the partition to copy and of the destination that is to be created. The sdX and the sdY need to be changed to the proper device (check with fdisk -l). Typing the wrong device will erase that device without any warnings.
Using the normal reboot with live session install is by far the more adviced method.
Warnings

do this with an active system and your destination can become corrupt: the active system will write to your partition during the copy and if that happens while content is being copied ... you get a destination that is not an exact copy where the damage can be be fatal for the new setup
sdY is going to be overwritten and there is not a way back from it.

Besides the manual method: Clonezilla is made for this

What is Clonezilla?
Clonezilla is a partition and disk imaging/cloning program similar to True Image® or Norton Ghost®. It helps you to do system deployment, bare metal backup and recovery. Three types of Clonezilla are available, Clonezilla live, Clonezilla lite server, and Clonezilla SE (server edition). Clonezilla live is suitable for single machine backup and restore. While Clonezilla lite server or SE is for massive deployment, it can clone many (40 plus!) computers simultaneously. Clonezilla saves and restores only used blocks in the hard disk. This increases the clone efficiency. With some high-end hardware in a 42-node cluster, a multicast restoring at rate 8 GB/min was reported.

But ... even they use a live session method.
Comment: Thanks, but the goal is to do a fresh install of a new OS so cloning isn't an option.
Answer: I ended up using VirtualBox, based on https://superuser.com/questions/495025/use-physical-harddisk-in-virtual-box.
Basically, I did
sudo chown me:me /dev/sdb
VBoxManage internalcommands createrawvmdk -filename /path/to/file.vmdk -rawdisk /dev/sdb

Then I created a VM, attached the install DVD and added a HDD from an existing file (file.vmdk).  I set the "mode" for the HDD to "writethrough" (File->Virtual Media Manager->file.vmdk->modify).  Also if you intend to boot from the disk on an EFI system be sure to enable EFI in VirtualBox (check the "use EFI" box in the VM's settings) so the installer creates the appropriate partitions.
This approach is nice because it lets me install and setup the OS from my current OS - no need for another computer to look things up in case something goes wrong, I can do other work while I wait for things to install, etc.
Answer: Another VirtualBox method to install to USB drive
You Can do a Full install to USB drive from Ubuntu using Virtual Box.

From Ubuntu install VirtualBox if you do not already have it.
Start VBox and make a new Ubuntu machine.
Start the Ubuntu machine and point it at the Ubuntu iso file.
When the process gets to the Try/Install window select "Try".
Plug in your USB and confirm it is visible to VBox.
Select the Install Ubuntu icon on the desktop.
When you get to partitioning select "Something else"
Select the USB as target for the install.
Continue the installation as normal until complete.

I have tried this with the latest versions of Ubuntu and VirtualBox. (and with previous versions of each.


Embeddable Workflow/BPM Library For Python?

Question: Let's say you are building a Python-based web app that requires some workflow management such as that in jBPM or Windows Workflow Foundation. Is there a library that offers this in the Python world?
Comment: The workflow system should clearly be in the middle layer, not the clients. The clients then need to ask the middle layer about what workflow transactions is available based on the item and security. If you want to store things in postgres I'd recommend you use sqlalchemy, and then SpiffWorkflow may work, but I haven't used it and don't know if it's any good. Search for workflow on PyPI, but be aware most products there are for Plone. :)
Comment: Here is the very similar question, but django specific - http://stackoverflow.com/questions/6795328/workflow-frameworks-for-django/25717038#25717038
Comment: Per Lennart's suggestion below I will expand the above. The system will consist of multiple clients interacting with a middle layer, that, in part, must have a workflow subsystem of some sort. The workflow subsystem exists to create an "embedded BPM" that can flexibly manage the changing processing requirements. The first upper layer "client" will likely be a web client that involves CherryPy and AJAX on the browser. The backend will likely be PostGRES. This is somewhat mutable.

What other info can I add?
Comment: To add, I say "first client" because there will eventually be more, and they won't necessarily be web-based, so something too tied into Zope or some other framework won't work. It has to be able to stand alone.
Comment: Agreed. Maybe I wasn't clear, but the workflow engine would be in the middle layer. Thanks for your help.
Answer: Oh yes, tons. But most of them depend on a specific framework. DCWorkflow is integrated with Zopes CMF, for example. hurry.workflow is for Zope 3, etc. SpiffWorkflow presumes sql-alchemy, etc. This is because you need to have something to apply the workflow to, and that means you need to make some basic assumptions on the objects you use.
Hurry.workflow is probably one of the more independent ones, but it still assumes both that you use the Persistence library (and therefore in practice ZODB), and zope3's security model.
So you probably need to expand a bit on your requirements here...
Comment: SpiffWorkflow seem **not** to presume sql-alchemy, or at least, I'm not finding any reference pointing in that direction. It might be something that has changed since this post... A quick search in the mailing list seems to indicate the [current persistency mechamism uses pickle](http://groups.google.com/group/spiff-devel/browse_frm/thread/448348770062f96).
Comment: It used to require SQLAlchemy, yes. Pickling only is just as limiting.
Answer: Have you looked at this? http://code.djangoproject.com/wiki/GoFlow


Mongoose Find and Update by _id

Question: I was trying to insert a name to my schema's "data_stream_map" array by finding using two parameters,
As follows,
var query = {
        '_id': new ObjectId("594261a0ea2d89001c851424"),
        'inputs.name':  "name1"
    };

    return WFWorkflowModel.findOneAndUpdate(query, {$addToSet: {'inputs.$.data_stream_map': "121_name1"}}).then(function (result) {
        return true;
    }, function (error) {
        console.error("WFEditor micro service - update dataStream.");
        return error;
    });

Nothing in the internet worked with me yet. But when it comes to Robomongo 0.9.0 this works,
db.getCollection('wfcomponents').findOneAndUpdate({
        _id:  ObjectId("594261a0ea2d89001c851424"),
        'inputs.name':  "name1"
    }, {$addToSet: {'inputs.$.data_stream_map': "120_name1"}})

The mongoose document as follows,
{
    "_id" : ObjectId("594261a0ea2d89001c851424"),
    "key" : "task",
    "description" : "",
    "__v" : 0,
    "updated" : ISODate("2017-06-12T07:08:58.462Z"),
    "created" : ISODate("2017-06-12T07:08:44.079Z"),
    "gridLocation" : {
        "y" : 1,
        "x" : 7
    },
    "inputs" : [
        {
            "name" : "name1",
            "data_stream_map" : [

            ]
        }
    ]
}

The used mongoose version is "mongoose": "^4.6.5", I'm out of clues, is there anyone can help me to overcome this issue? I refereed lots of stack overflow questions but its still unresolved.
Comment: What is the issue? This looks fine. You are using `.findOneAndUpdate()` without returning the document so you could just use `.update()` . Is that the problem, that the document does not return?
Comment: Well as you can see you are using the exact same arguments, so something else is different. Check you are connecting to the same database namespace and collection. Mongoose models "pluralize" collection names. I would suggest you are pointing to a different collection and should specify explicitly as in `mongoose.model('WFWorkflowModel',  WFWorkflowModelSchema, 'wfcomponents')` or whatever you actually called it,  where the "third" argument there overrides the default choice of collection name. So explicitly name it.
Comment: no the problem is it doesnt insert the name to the data_stream_map.
Comment: tried update() as well but no help.
Comment: okay sure ill try
Answer: 1.) update Robomongo to 1.0, its has updates in the system that are necessary. 2.) check out this link i provided, Not sure if your question is a duplicate but this has good answers and i think pertains to your problem, and quick tip you cant update ids in mongodb, you need to delete and create again(explained in the link provided). Hope i read the question right, best of luck.
P.S. If your just trying to query input, make sure that your files are properly linked i.e. you are requiring all of your modules properly. If you have that set mongoose uses find, findOne, findById, where. Links are provided. Again hope im answering the question properly, not sure what your trying to achieve.
How update the _id of one MongoDB Document?
http://mongoosejs.com/docs/models.html
http://mongoosejs.com/docs/queries.html
Comment: yeah sure will try these.
Answer: Model.findOneAndUpdate(query,update,{new:true}).exec(function(err,docs){
        console.log(docs)
})
//your code is correct , just lost the options{new:true},which will return the updated doc but not the found doc

Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.

Mongoose Find and Update by _id


What happens to Fiora's ultimate versus invisible champion

Question: Say, Fiora uses her ultimate on Twitch and the person on their team with oracle get's out of Twitch's range, making Twitch invisible again, will Fiora's ultimate keep hitting him?
Comment: I smell... SCIENCE!?! :D
Answer: If Fiora targets a champion with her ultimate and that target becomes invisible/out of sight then the ultimate ends. You can see an example of this with Akali's shroud below:


Slingshot is not launching (Font-Error)

Question: After having installed slingshot (Version 0.9-1 from the universe repository) on 16.04 i tried to start it by executing slingshot in the terminal.
The output is
Traceback (most recent call last):
  File "/usr/games/slingshot", line 61, in <module>
    class Game:
  File "/usr/games/slingshot", line 67, in Game
    Settings.font = pygame.font.Font(get_data_path("FreeSansBold.ttf"), 14)
IOError: unable to read font filename

The font itself is installed on my system, according to the output of locate FreeSansBold.ttf
/usr/share/fonts/truetype/freefont/FreeSansBold.ttf

Reference Links regarding slingshot:

Project GitHub
Listing at PyGame
Answer: There is a Launchpad-Bug regarding this issue - see here for more details.
A comment there is mentioning that this issue should be fixed in 0.9-1 which is not true at least for me.
I was able to troubleshoot the broken symlink problem by running:
cd /usr/share/games/slingshot/data
sudo ln -sf ../../../../lib/python2.7/dist-packages/pygame/freesansbold.ttf FreeSansBold.ttf

Comment: Good catch. But It should work with any other FreeSansBold file I guess? Though I don't know what this game is about

Slingshot is not launching (Font-Error)


Xcode 6.3 - You already have a current iOS Development certificate or a pending certificate request

Question: Xcode as of 6.3 is no longer allowing me to automatically perform device provisioning for a client.  Has anyone else experienced this issue?  I found no results when searching for this on Google...
This client has their own bundle ID and it's possible they also have their own provisioning profile for this device.  So maybe Apple is matching up the bundle ID irrespective of the developer account being used for provisioning.
I was able to address the issue by modifying the app's bundle ID and manually going through the provisioning process, but I'm guessing this issue is extremely rare, so I'm not sure if this post will be of use to anyone.
Comment: I just received this as well, I'm definitely in the same boat. I'm loathed to start down a path of just deleting access and keys hoping it will reset given I'm fairly new to Xcode.
Answer: When I am create new certificate from my Xcode 9.2 the error was appear
<code>"You already have a current iOS Distribution certificate or a pending certificate request"</code>.
Just 2 step for fix this error.

Remove old certificate from developer.apple.com
Create new certificate from Xcode or developer.apple.com

My problem has been solved (I am using Xcode 9.2).
Comment: How do I remove the certificate from the site?
Comment: You can hire me for this task :), Joke a part, just search on google.
Comment: I am using free provisioning, I don't have a certificate.
Comment: Try to change bund id and run project again.
Comment: https://developer.apple.com/forums/thread/712697
Answer: I just found that if I remove my account from Xcode, and then sign in again, it solved the issue. I did revoke my existing certificates and request new ones though as part of that process. I didn't import an existing profile.
Comment: I try with your steps but my problem was not fix, Please check how can I resolved this issue https://stackoverflow.com/questions/29701062/xcode-6-3-you-already-have-a-current-ios-development-certificate-or-a-pending/49979593#49979593.
Answer: My team has maxed out on release certificates, because apparently there is a quota.
We had to delete one of the existing release certificates.
Answer: This issue is actually more common than you think.
Some Solutions:
I usually find that opening Xcode's settings and signing out of my account and the signing in again resolves most of those issues.
You may have an older mac that already used up that one allotted development certificate. In that case you'll want to export the developer profile from that machine. If you no longer have access to that machine, it may be time to invalidate that certificate and simply request a new one.
Another option may be to double check your build settings in your project and ensure that it's looking for the right certificate. It's fairly common in my experience for these settings to make decisions on their own, and confirming that they're what you expect may help.
Background:
When dealing with provisioning, it's really easy to get caught up with the frustration of all of the steps you need to go through. The first thing to note is if the error you see is talking about a "Certificate" or a "Profile." In your case, it's a certificate. Good.
Certificates differ from provisioning profiles in a few ways. Certificates are usually only generated twice: once for development, and once for distribution. (Exceptions to this rule are if you decide to add support for some of the special features like push notification or for generating passbook passes on a server.)
The process for generating certificates is also a little more bureaucratic than profiles. You request a certificate from Apple's Member Center. You generate a provisioning profile.
The reason for the word request vs generate is because both Apple and your iOS team's admin need to approve certificate requests. This is because certificates identify you as part of your iOS developer team, and offer all the powers associated with that.
For the sake of completeness, I'll add that provisioning profiles are generated based on that certificate, and really only tell iOS what environment your app is meant to run in. (On any device via the store, specific devices, etc.)
Now, the important part for you is the request business. Most people don't pay much attention to this terminology, since indie developers and small teams (where the developers are admins) don't require developers to ask for permission.
Your error is talking about a previously generated certificate or request. You can only have one development certificate per developer. You either have one, or you've requested one and someone has to approve.
That's what's happening here.
Answer: This process is made simple with Xcode 8.3 and 9. Just delete one of your old certifcates in the "validate" interface and click the plus button to request new one, Xcode will request for you and add it in keychain. in my case, maximum number was reached, so I deleted one which was lost in a old Mac  and created new one.
Comment: ty for this hint! where is the 'validate interface'? I do not see it.
Comment: XCode does not prompt with any "validate interface" and typing that in help does not lead to anything...
Comment: Xcode should prompt you with the validate interface when there is a certificate issue.
Comment: we had 3 distribution profiles. for me it work to delete on and create a new distribution file
Answer: This error may also be occur if you reach your distribution certificate limit. After creating 3 iOS Distribution Certificates in an account, the following error message will be displayed when you try to create 4th one: "You already have a current Distribution certificate or a pending certificate request."
Open this link
https://developer.apple.com/account/resources/certificates/add
Press + icon in front of Certificate

Check Apple Distribution section if its show the red text as shown in image then you should revoke you existing certificates to generate new one because you have reached you limit.

Just 2 step for fix this error.

Remove old certificate from developer.apple.com
Create new certificate from Xcode or developer.apple.com
Answer: Delete old developer certificate from https://developer.apple.com/account/ios/certificate/ and try to create developer certificate from xcode
Answer: 1) Remove old certificate from apple developer account.
2) Go to the 'Xcode' 3) Select 'Preferences' option and then Select the 'Account' Tab
3) Select apple id from left side and click on 'Manage Certificate'.
4) Click on '+' (add certificate) button.
5) Add 'Apple Distribution' Certificate.
Answer: Unfortunately, only a macbook restart resolved this for me.
Creating another Distribution certificate was not an option, because it had already reached the max. number of certificates.
I manually added an existing one (incl. its private key) to the Keychain …and still Xcode said "Not in Keychain". I then tried to trigger a refresh of the Xcode listing by removing & adding my developer account to Xcode, but that didn't work — neither did restarting Xcode.
So, when all else fails, you try to reboot your system.
Answer: When you have three active distribution certificates that were created on distinct machines, you'll see this issue. You can either ask for the private key of a previously made one or simply revoke any of them and make your own.
Comment: How?  How do you do that?


How to implement group-membership JavaScript policy in Keycloak

Question: A 2-year old keycloak-user list question w/o an answer:

there's a protected resource called Project
and an owner - a Project Manager
Each project manager has access to only their own projects (owner-only policy).
Project Managers in turn report to one or more Portfolio Managers. A Portfolio Manager should be able to access all his/her project managers' projects (portfolio-manager policy).

Let's assume the system design if flexible and this fact who are the Portfolio Managers for a particular Project Manager
can be either kept inside Keycloak (but not as keycloak groups) or in the client app itself. How can this be implemented as a JavaScrtipt-based
authorization policy in Keycloak? I guess the request can be injected with this info somehow but can't figure it out from the docs.
Answer: It turned out to be rather easy. I've decided to keep the info about managers in another database, and then the app (service-nodejs) needs to pass this info as a claim to keycloak. I've tested this on the service-nodejs keycloak quickstart. Here are the relevant pieces:
// app.js route:

app.get('/service/project/:id',
  keycloak.enforcer(['Project'], {
      response_mode: 'permissions',
      claims: (request) => {
          return { "portfolio.managers": ['alice', 'bob'] } //hard-coded
      }
  }), function(req, res) {
      res.json({ message: `got project "operation "` });
  });

The policy protecting the Project resource is an aggregated of OwnerOnly and PortfolioManagers:
// portfolio-managers-policy:

var context = $evaluation.getContext();
var identity = context.getIdentity();
var userid = identity.getAttributes().getValue('preferred_username').asString(0);
var managers =  context.getAttributes().getValue('portfolio.managers')

if (!managers) {
    print('managers not provided, cannot decide!');
    $evaluation.deny();
} else {
    // check if the user is one of the portfolio managers of this project:
    for (var i = 0; i < managers.size(); i++) {
        if (managers.asString(i) == userid) {
            $evaluation.grant();
            break;
        }
    }
}

Note that the service-nodejs keycloak client must be confidential in order to call the token endpoint.


PowerShell string replacement

Question: I am trying to build a PowerShell script such that I give it an input file and regex, it replaces the matching content with the environment variable.
For example, if the input file contains the following:
<?xml version="1.0" encoding="utf-8"?>
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="fabric:/Services" xmlns="http://schemas.microsoft.com/2011/01/fabric">
   <Parameters>
      <Parameter Name="IntegrationManager_PartitionCount" Value="1" />
      <Parameter Name="IntegrationManager_MinReplicaSetSize" Value="2" />
      <Parameter Name="IntegrationManager_TargetReplicaSetSize" Value="#{INT_MGR_IC}" />
      <Parameter Name="EventManager_InstanceCount" Value="#{EVT_MGR_IC}" />
      <Parameter Name="Entities_InstanceCount" Value="#{ENT_IC}" />
      <Parameter Name="Profile_InstanceCount" Value="#{PRF_IC}" />
      <Parameter Name="Identity_InstanceCount" Value="#{IDNT_IC}" />
   </Parameters>
</Application>

I would like to build a script that replaces #{INT_MGR_IC} with the value of the INT_MGR_IC environment variable and so on.
Specifically, I am interested to know how to:

Extract and loop over keys from the file such as: #{INT_MGR_IC}, #{EVT_MGR_IC}, etc.
Once I have the key, how do I replace it with an associated environment variable. For example, #{INT_MGR_IC} with INT_MGR_IC env. variable.

Update
This is the RegEx I am planning to use: /#{(.+)}/g
Comment: What you mean loop over keys? loop over each parameter?
Comment: @jisaak: Correct, 1. Extract all the strings that are enclosed within `#{` and `}` ... and then replace them with associated ENV variable.
Comment: OK guys, before you start voting to close the question, please ask me if you are having difficulties understanding the question! I think this is a valid question. At least, this is the valid problem I am trying to solve at work. I am sure someone, somewhere will also benefit -- especially when it comes to config file transformations in the automated build/deploy process.
Comment: Okay, I will try to provide you are script. But not using regex, read why: http://stackoverflow.com/a/1732454/1163423
Comment: @jisaak: Thanks a lot for the quick response and link. I am going through it. Appreciate it :)
Answer: Just load the file using the Get-Content cmdlet, iterate over each Parmeter, filter all parameter that Value starts with an #using Where-Object and change the value. Finally, use the Set-Content cmdlet to write it back:
$contentPath = 'Your_Path_Here'
$content = [xml] (Get-Content $contentPath)
$content.DocumentElement.Parameters.Parameter | Where Value -Match '^#' | ForEach-Object {
    $_.Value = "REPLACE HERE"
}
$content | Set-Content $contentPath

In case you need to determine an environment variable, you could use [Environment]::GetEnvironmentVariable($_.Value).
Comment: I guess instead of a `^#` regex you could use `.StartsWith('#')`
Comment: Yeah, but it would require to use curly brackets and `$_.Value` notation. But would still be more readable - I agree. Another one:  `Where { $_.Value[0] -eq '#' }`.  ;-)
Comment: Thank you. I am giving it a try.
Answer: Thanks a lot for everyone who helped. Especially, @jisaak :)

Here is the final script I built that solved the problem in the question. Hopefully its useful to someone!
$configPath = 'Cloud.xml'
$config = [xml] (Get-Content $configPath)
$config.DocumentElement.Parameters.Parameter |  Where {$_.Value.StartsWith("#{")} | ForEach-Object {
    $var = $_.Value.replace("#{","").replace("}","")
    $val = (get-item env:$var).Value
    Write-Host "Replacing $var with $val"
    $_.Value = $val
}

$config.Save($configPath)

PowerShell string replacement


Regex for keyboard keys in string

Question: I'm making a tiny autohotkey for OSX in Python, I've managed to send keyboard input and obtain keyboard input, but I'm stuck with one bit. I'm trying to make combinations for example:
1: {CTRL}1
2: {CTRL}{SHIFT}12{CTRL}
3: {CTRL}{SHIFT}b{CTRL}

These ones should be the ones detectable, but I'm trying to set up a regex capture group for each item in the string (Everything between curly braces and everything out of the curly braces), those thee lines should pretty much capture the following:
1: '{CTRL}', '1'
2: '{CTRL}', '{SHIFT}', '12', '{CTRL}'
3: '{CTRL}', '{SHIFT}', 'b'

I've been trying so hard on Pythex and I can't seem to make any of my regexes work properly.
Here's my Pythex attempt which didn't work out quite so well
Answer: Find everything not a brace, optionally surrounded by braces:
set(re.findall(r'(\{?[^}{]+\}?)', your_string))

Wrapped in set so multiple command keys appear only once, but you can remove that if you want.
Comment: Is there a way I can use set() only on the items that have braces?
Comment: Not in one swoop that I can think of, but you could `set(s for s in matches if s.startswith('{'))` and `[s for s in matches if not s.startswith('{')]`

Regex for keyboard keys in string


how to import module

Question:
Possible Duplicate:
How to import the src from the tests module in python

I want to call another module which is located in another dir. My code structor is
flask_beginner/
  app.py
  models/
      __init__.py
      user.py
  tests/
      __init__.py
      user_test.py

I want to call user module from user_test.py. My user_test.py is  like this..
import models.user
....

But it raise error that no module named models.user
Do you have any idea?
My Python Version is 2.7.2.(with virtualenv)
Thanks in advance.
Answer: import sys
sys.path.append('PathToModule')
import models.user

Answer: If you are running user_test.py from the tests directory it will not be able to find the models package. However if you run it from flask_beginner directory it will be able to find the module. The reason being the directory from which you are executing the scripts is appended to the python path and hence it can find all the modules in your project.
Comment: Thanks I understand it . I run module from my root dir, it success!Thanks.
Answer: When you run import <module_name>, Python searches in all the directories in the PythonPath variable for a module with that name and, if it finds it, imports it. The current directory (i.e. the directory in which your script is running) is usually in PythonPath, so most scripts will be able to find a module which is in the same directory.
If you need to import a module that's in a different directory, you'll need to add that directory to the PythonPath. You can do this as follows:
import sys
sys.path.append(<the_path_to_the_module>)

(Where, of course, you should replace <the_path_to_the_module> with the right path, which, in this case, would be '../models/user.py')

how to import module