Using JWT authorization in combination with X-Auth-Tokens in Spring Boot

Question: I'm trying to setup Spring Boot 3 to use both authentication using JWT and HTTP sessions with X-Auth tokens. The goal is to use X-Auth tokens as primary authentication method, but users might authenticate using an external provider which grants a JWT access token.
I've successfully managed to create two different authorization endpoints, one at /auth using form based login and returns an X-Auth token, and one at /authJwt. JWT authorization is only enabled at /authJwt and all other endpoints are protected using X-Auth tokens.
Is it possible to enable generation of X-Auth tokens by authentication using a JWT? I've configured HTTP sessions to always be created, and a call to /authJwt returns an X-Auth token in the HTTP header. But the X-Auth token is not valid when trying to authenticate.
This is the security configuration which I'm using (I've removed some irrelevant parts):
@Configuration
@EnableWebSecurity()
public class WebSecurityConfiguration {

    // Endpoints which will be public and not require authentication
    private static final String[] AUTH_WHITELIST = {
        "/auth"
    };

    /**
     * Filter chain for authenticating using JWT tokens
     */
    @Bean
    @Order(1)
    public SecurityFilterChain oAuth2ResourceFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .securityMatcher("/authJwt")
                .cors().and().csrf().disable()
                .requestCache().disable().exceptionHandling().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .and()
                .authorizeHttpRequests().anyRequest().authenticated()
                .and()
                .oauth2ResourceServer()
                .jwt();
        return httpSecurity.build();
    }

    /**
     * Filter chain for enabling authentication.
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors().and().csrf().disable()
                .requestCache().disable().exceptionHandling().and()
                .formLogin().loginPage("/auth").usernameParameter("loginName").passwordParameter("loginPassword")
                .successHandler((request, response, authentication) -> response.setStatus(HttpServletResponse.SC_OK))
                .and()
                .authorizeHttpRequests(requests -> requests
                    .requestMatchers(AUTH_WHITELIST).permitAll()
                    .anyRequest().authenticated()
                )
                // Return 401 on no session
                .exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                .and()
                .logout();
        return httpSecurity.build();
    }
}

This is the configuration for the sessions:
@Configuration()
@EnableSpringHttpSession
public class SpringHttpSessionConfig {

    @Bean
    public MapSessionRepository sessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }
}

Can anyone point in the correct direction of exchanging JWT tokens for X-Auth tokens?
Answer: You could set up a custom authentication filter for the JWT token which would authenticate the user using the JWT token and then create an X-Auth token for the authenticated user.

Custom JWT auth filter:

import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import java.io.IOException;

public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JwtAuthenticationFilter() {
        super("/authJwt");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        String token = request.getHeader("Authorization");

        // JWT authentication logic

        return null; // return the authenticated user
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        // Generate X-Auth token for the authenticated user
        String xAuthToken = "GENERATED_X_AUTH_TOKEN";
        response.setHeader("X-Auth-Token", xAuthToken);

        // Continue processing the request
        chain.doFilter(request, response);
    }
}

Register the custom filter in your WebSecurityConfiguration class:

@Configuration
@EnableWebSecurity()
public class WebSecurityConfiguration {

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter();
    }

    @Bean
    public SecurityFilterChain oAuth2ResourceFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .securityMatcher("/authJwt")
                .cors().and().csrf().disable()
                .requestCache().disable().exceptionHandling().and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .and()
                .authorizeHttpRequests().anyRequest().authenticated()
                .and()
                .oauth2ResourceServer()
                .jwt()
                .and()
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }
}

Now, when a user sends a request with a valid JWT token to the /authJwt endpoint, the filter authenticates the user using the JWT token, generates an X-Auth token and returns it in the X-Auth-Token header.
Comment: Thanks! We will try your solution and report if it works for us.
Comment: Your solution looks like it should work but we haven't had time to try it yet. I'll give you the bounty, and we'll accept when we have verified. Thanks for the suggestion, anyway!
Comment: Thank you for the reply! I managed to figure it out without using sessions and posted my solution here as well. This solution seems to also be working, but would probably require some more configuration to make the tokens valid when using Spring Sessions.
Answer: I realized I had assumed I needed to use Spring Session, but it was easier to solve it without sessions. Instead I added a custom token store and token filters which manages authorization. The token store:
@Component
public class TokenStore {

    private final ConcurrentHashMap<String, Authentication> authenticationCache
       = new ConcurrentHashMap<>();

    /**
     * Generates and registers authentication token.
     *
     * @param authentication The authentication used.
     * @return Generated authentication token.
     */
    public String generateToken(Authentication authentication) {
        String token = UUID.randomUUID().toString();
        authenticationCache.put(token, authentication);
        return token;
    }

    /**
     * Returns authentication from authentication token.
     *
     * @param token The authentication token to check.
     * @return Authentication if token exists, otherwise null.
     */
    public Authentication getAuth(String token) {
        return authenticationCache.getOrDefault(token, null);
    }

    /**
     * Removes authentication token.
     *
     * @param token Authentication token.
     */
    public void removeAuth(String token) {
        authenticationCache.remove(token);
    }
}

Token filter which is added to the SecurityFilterChain to validate access tokens:
@Component
public class TokenFilter extends OncePerRequestFilter {

    private final TokenStore tokenStore;

    public TokenFilter(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    /**
     * Checks if an authentication token is valid and sets authentication.
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authToken = request.getHeader(AuthConstants.AUTH_TOKEN_NAME);
        if (authToken != null) {
            Authentication authentication = tokenStore.getAuth(authToken);
            if (authentication != null) {
                SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
                securityContext.setAuthentication(authentication);
                SecurityContextHolder.setContext(securityContext);
            }
        }
        filterChain.doFilter(request, response);
    }
}

The tokens are genereated either on the success handler of the form login:
private void successHandler(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
   String token = tokenStore.generateToken(authentication);
   response.addHeader(AuthConstants.AUTH_TOKEN_NAME, token);
}

Or in the endpoint for the /authJwt endpoint:
/**
 * Exchanges a valid JWT to an access token.
 *
 * This endpoint is protected using the OAuth2 filter chain.
 */
@PostMapping(value = "/authJwt")
public void verifyClient(HttpServletResponse response, Authentication authentication) {
   String token = tokenStore.generateToken(authentication);
   response.addHeader(AuthConstants.AUTH_TOKEN_NAME, token);
}


What causes this odd pattern in the paint on a block foundation wall?

Question: My basement is having some water issues. I am working to resolve that, but in the meanwhile: can you guess what is causing this pattern in the painted cinder blocks near the bottom right corner (some at bottom left as well)?
What I am getting at: are the edges of the blocks a darker color because they were wet when they were painted, or because water came along after they were painted and did something?
Answer: Cinderblocks/concrete blocks normally have a hollow section:

If they were mounted sideways, so that the core was in the middle, then they would need to be filled in with concrete and they would end up being different, even when finished & painted, in the middle than on the sides.
This does seem a little odd, because normally they will be stacked so that the hollow core is vertical - i.e., so the wall sides are solid. But it could explain the problem.
Comment: It's a reasonable explanation _except_ that the phenomenon is _not_ consistent and that block, as you mention, is not installed flat like that. I'd be interested to know if there is _ever_ a reason (beyond wonky DIY job) to install them on the flat.
Answer: The darker color indicates the infiltration of water. It usually occurs after the block was painted rather than prior because, as usually the case, the paint wouldn't adhere to a moist/wet surface.
However, it can occur in a basement if the wall-floor edges were not cleaned properly (the surface was dry but dirty).
Comment: I had a basement drainage person out yesterday, so I grilled him about these patterns as well. He suggested that the blocks were dry locked in the past, and then some water forced itself through the grout causing discoloration. Then the former owner ground out the discolored areas (e.g. mainly the grout and nearby) and then painted everything. So the edges that were cleaned out are a bit darker because more of the paint was absorbed by the cinder block.
Answer: My guess was going to be that the mortar is more porous than the cinder blocks so there was more water infiltration coming in those areas and affecting the color regardless of whether the discoloration was done during or after painting.
However, upon closer inspection I can see that certain blocks are fully affected by the discoloration so that leads me to believe some sort of sealant was used prior to painting.
Most discoloration seems confined to the mortar and surrounding areas which is akin to the application results of grout sealant.
In particular, the left block seems fully affected but the right block was only half affected so the previous person just applied it more liberally than other spots for whatever reason.

p.s.
It's relieving to see that my basement walls aren't the only ones that look less-than-appealing =)
https://diy.stackexchange.com/a/181876/42053
Comment: Hah thanks for the link, that was very informative. I am also cursing the former owner for making this mess, rather than dealing with the problem properly. Once I am satisfied with the exterior drainage and sealing, I think I'm going to get all this paint and crap off. Have you ended up trying anything with your basement?
Comment: @negacao I have not tried anything with my basement. Having a good dehumidifier with an automatic pump (~$300) prevents mustiness and has prevented new black spots from forming so I make sure to keep it operational. I have a 2 and 3 year old so clearing out the basement to try and scrape the Drylok is wayyyyyy down low on my priority list. Realistically, I'll just clean it up and Drylok it again when we're ready to sell the house ¯\\_(ツ)_/¯


memory and time efficient way to sort random incoming data

Question: I need to sort data coming from different lists of random values (values can be repeated) into a list of unique values in a memory and time efficient way (there are hundreds of lists that can have up to thousands of records each). Right now I have 2 methods
Method 1- Sort as data comes in:
public List<ClassB> ListSorter1(List<ClassA> listA){
    List<ClassB> data = new ArrayList<>();
    for (ClassA a : listA) {
        int idx = Collections.binarySearch(data, a.getValue());
        if (idx < 0) {
            int ip = -(idx + 1);
            data.add(ip, a.getValue());
        }
    }
}

Method 2 - get all the unique data and then sort:
public List<ClassB> ListSorter2 (List<ClassA> listA){
    List<ClassB> data = new ArrayList<>();
    for (ClassA a : listA) {
        if (!data.contains(a.getValue())) {
            data.add(a.getValue());
        }
    }
    Collections.sort(data);
}

The problem I'm having is that method 2 performs better (about 20% faster than method 1 and roughly the same memory usage) when <ClassB> is simple data (Integer), but as soon as I change to a more complex class, the time required to sort the list skyrockets, taking up to 10 times more than method 1 (and still about the same memory usage), both using the same comparator function.
Why this difference in performance?
Is there a more efficient way to do this?
Comment: Looks like you could just maintain a java.util.TreeSet
Comment: It's not at all clear what you mean by "a more complex class" here... but you might want to log how many comparator calls are made in each case.
Comment: Add the values to a SortedSet, this will be more efficient and simpler.
Answer: First of all it is strange that Method 1 is 20% slower than Method 2, but I assume that it is tested on a very small collection.
Cause for a big slowdown in Method 2 is for two reasons:

When you iterating data is not sorted, so
contains method has to go through whole list in order to find element - which is O(n). contains has O(n) complexity no meter if  data is sorted, since it iterates over the whole collection.
So, for Method 2 it is O(n^2) complexity

For method 1, you are managing ordered list, and you are using binarySearch which is O(ln(n)).
So, method 1 has a complexity of O(n*ln(n))
Comment: Thanks, I will continue investigating on possible improvements to the code
Comment: will do as soon as i get enough rep to do that


Why do I need to remove the positive charactaristic function for the pdf of the outgoing direction to integrate to 1 with GGX?

Question: Context: I am attempting to implement Trowbridge–Reitz (GGX) based on Microfacet Models for Refraction through Rough Surfaces in a pathtracer. I use numerical integration to check if the pdfs integrate to 1 (I convert solid angle to spherical coordinates using the jacobian and integrate that):
It is stated that the probability of generating a given microfacet normal for GGX is
Where m is the microfacet normal and n is the macrofacet normal (which I set to (0, 0, 1) for the sake of testing). Note that || on the dot product isn't needed since D(m) < 0 if the dot product is below zero due to the positive characteristic function (X+) on all the given microfacet distributions including GGX (see below).

As expected when I integrate p_m(m) it indeed does integrate to 1 as you would expect.

The problems arise when I try to integrate the pdf of the sampled direction (o). Which I should be able to do by using the jacobian.

The paper states that for ideal reflection the jacobian is 1/(4|o dot h|)

So I reasoned that this would be true:

The reason why I'm assuming the first equality is true is due to:
"Let us assume that for any given incident
and outgoing directions, there is at most one microsurface
normal that scatters energy from i to o, and that we can compute that normal as h(i, o), which we call the half-direction". As well as the equation above (38).
I would like to point out that I am only doing ideal reflection, so no refraction.
The problem is when I attempt to integrate the expression in the image above. It does not integrate to 1 or a consistent value.
To make the distribution integrate to 1 I have to get rid of the positive characteristic function in D(m). Which results in p_m(m) integrating to 0 but p_o(o) integrating to 1.
Why does removing the positive characteristic function have this result and why doesn't p_o(o) integrate to 1 when it remains?
Also as a side note, I find that using

to calculate o given h and i leads to sampled distribution not matching up with the pdf (I use a chi-squared test of the binned values to verify this) compared to not using the absolute value (which matches up to most formulas online). Note that for my testing  I generate i in the top hemisphere and pointing away from the surface.
Answer: Looks like the boundary of the integration changes to positive m.n and so you drop the Heaviside fnc to reflect that. (Actually a sample for m.n<0 is not a valid sample, you ain't taking its value at all but just discard it.. meaning in code it's an if() before the actual sampling routine).
Ie. something like this :

The 2|i.m|m-i is actually 2(i.m)m-i (Walter is writing it like that in ie. Notes on the Ward BRDF).
Comment: I understand you can drop the Heaviside function to integrate into 1. As for why it doesn't integrate to 1 with the Heaviside function: It turns out the mapping from m to o is not one-to-one since both 2(i . m) m - i and 2(i . -m) -m are valid and for the jacobian to work you need to take into consideration both. So in practice, this looks like if  (m . n < 0) { m = -m }. After this change, the function integrates into one (with the Heaviside function) as you would expect.
Comment: Hello, I'm not quite sure what you mean by "boundary of the integration change[s] to positive m.n and so you drop the Heaviside f[u]nc[tion] to reflect that". I thought the boundary of integration with the microfacet normal is positive m.n due to the Heaviside function and presumably when we drop the Heaviside function when integrating the output (rather than the microfacet normal) direction m.n can be < 0 which works for some reason. Also rather than having an if statement I just set the pdf to 0 (with the microfacet normal which has the Heaviside function) which should function the same.
Comment: I have added a simple example to the answer. The Heaviside fnc is a constant after all and can be put outside the integral while changing the boundaries.


Use regex to match 5 num, dot, 1 num, dot, 5 num

Question: I'm trying to create regex to match the following pattern:
00000.1.17372

i.e: 5 Numbers DOT 1 Number DOT 5 Numbers
I have tried the following re.match:
find = re.match('d{5}.d{1}.d{5}', string)

In context:
import re

string = "{u'blabla': u'asdf', u'dd': u'a', u'cotry': u'jjK', u'l': u'/q/iii:00000.1.17372', u'stfe': u'', u'fdfhdiufhi': u'GB', u'y_name': u'Unitm', u'mw': u'00000.1.17372'}"

find = re.match('d{5}.d{1}.d{5}', string)

print find

However, this doesn't seem to work, as the output is:
None

Comment: `re.match(r'^\d{5}\.\d\.\d{5}$', string)`
Comment: Use `search` instead. `match` only works at the beginning of a string.
Comment: This matches 'ddddd#d#ddddd'
Answer: Use the following with re.findall:
r'\b\d{5}\.\d\.\d{5}\b'

See the regex demo
The point is:

to match a digit, you need to use \d
a dot must be escaped to match a literal dot
to match whole words, you need to use \b word boundary or you will find matches of 5-digit chunks in 2234567654 like strings
re.findall will return a list of all non-overlapping matches (since there are no capturing groups in this pattern)

Sample Python code:
import re
regex = r"\b\d{5}\.\d\.\d{5}\b"
test_str = "{u'blabla': u'asdf', u'dd': u'a', u'cotry': u'jjK', u'l': u'/q/iii:00000.1.17372', u'stfe': u'', u'fdfhdiufhi': u'GB', u'y_name': u'Unitm', u'mw': u'00000.1.17372'}"
matches = re.findall(regex, test_str)
print(matches)

Comment: What do you mean by 'To match whole words', when there are no words included? :) Sorry for misunderstanding.
Comment: Whole word matching means there are no "word" chars before or after the value. "Word" chars include letters, digits and underscore (~`[a-zA-Z0-9_]` - depending on the `re.UNICODE` flag).
Answer: The pattern you want is:
\d{5}\.\d\.\d{5}

You need to escape the dots and use the proper token for a number, which is \d.


User needs admin approval after registration for login and redirect to login page right after registration

Question: In my Laravel 5.5 application with default auth system,I am trying to implement a login procedure like this,
1.I have a is_approved field in users table which is default 0;
2.If admin approved a user, it will be 1 and user can log in.
3.User will be redirected to login page after the registration with a message "You
  have been successfully registered.Please wait for the admin approval".
So when a user registered he should be redirected to login page instead of home and if he tries to login in the login page with email and password it should say "You are not approved yet ! ".
What i need to modify for this in Laravel authentication system ?
Comment: There are many ways to achieve this. You can add a `protected function attemptLogin(Request $request)` in your login controller to override the equivalent [trait one](https://github.com/laravel/framework/blob/5.5/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php#L74) or you can add a middleware to check whether a user has logged in and log them out if they are not approved and many many other ways. First you should make an attempt and then ask a question when you have a concrete programming issue.
Comment: I register the user and it takes him to home.I am not quite sure  which trait or controller i need to modify for this issue.
Answer: I override and modify the   register method in my RegisterController  ,
public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        return redirect()->back()->with('success', 'You have been successfully registered!. Please wait for the admin approval');
    }

and in my LoginController I override and modify the  credentials method,
public function credentials(Request $request)
    {
        return [
            'email' => $request->email,
            'password' => $request->password,
            'is_approved' => 1,
        ];
    }

Its working perfectly !


Counting number of points on plane in special procedure

Question: Lets define following function $f : \mathbb{N} \rightarrow \mathbb{N}$
First consider arbitraty four points on plane $\mathbb{R}^{2}$, that are corner of some square. We write then $f(1)=4$
Later we mark each middle point between any pair of previous set of points. Now we count number of new points, and forget about the past ones this will be our number $f(2)$ (i claim that $f(2)=5$)
We continue that procedure.

Find formula for $f(k)$

If it is impossible find lower bound of that function.
I tried to apply some theory about acting groups on set, because in general for $f(k)$ we have at most ${f(k)\choose 2}$ points, but we must be aware of repetition. The repetition comes from symmetries and that is why i seriously thinking about usege of group theory.
Comment: Your sequence appears to be the successive differences of this sequence: http://oeis.org/search?q=9%2C25%2C81%2C289%2C1089%2C4225&sort=&language=english&go=Search
Comment: https://www.wolframalpha.com/input/?i=%282%5E%28n%2B1%29+%2B+1%29%5E2+-+%282%5E%28n%29%2B1%29%5E2
Comment: Oh...if you're totally forgetting the previous points (i.e. you can't take the midpoint between points from two different iterations) it's different. Sorry I think I misread
Comment: In that case, doesn't look like anything relevant shows up in OEIS
Answer: Generation 3 forms a square with the centre removed, that can go at integer coordinates from $-1$ to $1$.
Double coordinates at every stage, I think you get an integer square, with point of even coordinates removed.
If generation $2n-1$ runs from $-m$ to $m$, then generation $2n$ runs from $-2m$ to $2m$.
If generation $2n$ runs from $-m$ to $m$ then generation $2n+1$ runs from $1-2m$ to $2m-1$ because the outer layer is wiped out, the midpoints are all from previous generations.
I think the square sides are either $(2^{gen}+10)/6$ or $(2^{gen}+14)/6$, and the removed square of previous points  respectively $(2^{gen}+4)/12$ and $(2^{gen}+20)/12$.
That gives the following sequence.  The first two are different, but from the third generation on they are the difference of two squares mentioned above.
$$4,5,8,16,40,120,408,...$$


MAUI XAML - Can't reference property value of custom control nested inside another custom control from outside

Question: I would like to set the Text property from MyCustomContentPage in XAML:
File 1:
<Grid x:Name="MyCustomControl" x:Class="MyCustomControl">

</Grid>

public class MyCustomControl : Grid
{
    public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(MyCustomControl), String.Empty);
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    public MyCustomControl()
    {
        Binding = this;
        InitializeComponent();
    }
}

File 2:
<Grid x:Name="MyCustomGrid" x:Class="MyCustomGrid">
    <Border Content="{Binding MyCustomControl}">
</Grid>

public class MyCustomGrid : Grid
{
    public static readonly BindableProperty MyCustomControlProperty = BindableProperty.Create(nameof(MyCustomControl), typeof(MyCustomControl), typeof(MyCustomGrid), null);
    public MyCustomControl MyCustomControl
    {
        get { return (MyCustomControl)GetValue(MyCustomControlProperty); }
        set { SetValue(MyCustomControlProperty, value); }
    }
    public MyCustomGrid()
    {
        Binding = this;
        InitializeComponent();
        MyCustomControl = new MyCustomControl();
    }
}

File 3:
<ContentPage x:Name="MyCustomContentPage" x:Class="MyCustomContentPage">
    <MyCustomGrid MyCustomControl.Text="GOODBYE" />
</ContentPage>

public class MyCustomContentPage : ContentPage
{
   //...
}

but I can't do this: MyCustomControl.Text="GOODBYE", it says that:

Bindable Text property not found on type MyCustomControl.

Thank you in advance
Comment: To improve `Binding` behavior, be sure to set `x:DataType` and make use of compiled bindings for optimizations and correctness. https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/compiled-bindings?view=net-maui-8.0
Answer: Let me see if I follow.

MyCustomControl
The intent of your xaml seems to have a Label nested in the Grid that "is" the custom control, which would reduce to this:
<?xml version="1.0" encoding="utf-8" ?>

<Grid
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:controls="clr-namespace:nested_custom_control.Controls"
    x:Class="nested_custom_control.Controls.MyCustomControl">

</Grid>

The label binds its own Text property to its parent control (as shown above) and the control exposes a bindable property named Text (as shown below).
namespace nested_custom_control.Controls;

public partial class MyCustomControl : Grid
{
    public MyCustomControl() => InitializeComponent();

    public static readonly BindableProperty TextProperty = BindableProperty.Create(
        propertyName: "Text",
        returnType: typeof(string),
        declaringType: typeof(MyCustomControl),
        defaultValue: string.Empty,
        defaultBindingMode: BindingMode.TwoWay);

    public string Text
    {
        get => (string)GetValue(TextProperty);
        set => SetValue(TextProperty, value);
    }
}

Next, you explain in your comment:

MyCustomGrid Is a form that contain múltiples nested CustomControls.

I understand that to mean that there will be a deterministic number of MyCustomControl in a layout determined by MyCustomGrid as in this minimal example.

<?xml version="1.0" encoding="utf-8" ?>

<Grid
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:controls="clr-namespace:nested_custom_control.Controls"
    x:Class="nested_custom_control.Controls.MyCustomGrid"
    RowDefinitions="*,60,60,60,*"
    BackgroundColor="Azure">
    <Border
        Grid.Row="1">

        <controls:MyCustomControl
            x:Name="myCustomControl1"
            Text="{Binding Path=UserName, Source={RelativeSource AncestorType={x:Type controls:MyCustomGrid}}}"/>
    </Border>
    <Border
        Grid.Row="2">
        <controls:MyCustomControl
            x:Name="myCustomControl2"
            Text="{Binding Path=Phone, Source={RelativeSource AncestorType={x:Type controls:MyCustomGrid}}}"/>
    </Border>
    <Border
        Grid.Row="3">
        <controls:MyCustomControl
            x:Name="myCustomControl3"
            Text="{Binding Path=Email, Source={RelativeSource AncestorType={x:Type controls:MyCustomGrid}}}"/>
    </Border>
</Grid>

To specify "what text goes where" MyCustomGrid is exposing bindable properties UserName, Phone, and Email to "direct traffic" to the intended target custom control. Again, the MyUserControl objects are binding their own Text property to different properties in the parent grid.
public partial class MyCustomGrid : Grid
{
    public MyCustomGrid() => InitializeComponent();
    public static readonly BindableProperty UserNameProperty = BindableProperty.Create(
    propertyName: "UserName",
    returnType: typeof(string),
    declaringType: typeof(MyCustomGrid),
    defaultValue: string.Empty,
    defaultBindingMode: BindingMode.TwoWay);
    public string UserName
    {
        get => (string)GetValue(UserNameProperty);
        set => SetValue(UserNameProperty, value);
    }

    public static readonly BindableProperty PhoneProperty = BindableProperty.Create(
    propertyName: "Phone",
    returnType: typeof(string),
    declaringType: typeof(MyCustomGrid),
    defaultValue: string.Empty,
    defaultBindingMode: BindingMode.TwoWay);

    public string Phone
    {
        get => (string)GetValue(PhoneProperty);
        set => SetValue(PhoneProperty, value);
    }

    public static readonly BindableProperty EmailProperty = BindableProperty.Create(
    propertyName: "Email",
    returnType: typeof(string),
    declaringType: typeof(MyCustomGrid),
    defaultValue: string.Empty,
    defaultBindingMode: BindingMode.TwoWay);

    public string Email
    {
        get => (string)GetValue(EmailProperty);
        set => SetValue(EmailProperty, value);
    }
}

Usage
Although I realize that MainPage is probably going to bind this and consume it in a much more sophisticated manner, to demonstrate that values are going where they're supposed to we can put a single instance of MyGridControl on the main page.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:controls="clr-namespace:nested_custom_control.Controls"
    x:Class="nested_custom_control.MainPage">

    <controls:MyCustomGrid x:Name="myCustomGrid1"/>
</ContentPage>

Then exercise it like this.
namespace nested_custom_control
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            myCustomGrid1.UserName = "Tommy IV";
            myCustomGrid1.Phone = "(000)000-0000";
            myCustomGrid1.Email = "firstname.lastname@example.com";
        }
    }
}

Answer: You are almost there. May I suggest to use a ContentView as control. In that case it would look like this. Note the Reference to ThisView
<ContentView
    x:Class="MauiTest.Controls.MessageView"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Name="ThisView">

</ContentView>

To note in the code behind for the control is that you don't have a BindingContext. That is rarly the case when dealing with controls.
public partial class MessageView : ContentView
{
    public static readonly BindableProperty MessageTextProperty =
            BindableProperty.Create(nameof(MessageText), typeof(string), typeof(MessageView), defaultValue: default(string));

    public string MessageText
    {
        get => (string)GetValue(MessageTextProperty);
        set => SetValue(MessageTextProperty, value);
    }

    public MessageView()
    {
        InitializeComponent();
    }
}

In your View you have a reference to the contols
<ContentPage
    x:Class="MauiTest.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:controls="clr-namespace:MauiTest.Controls"
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">

    <VerticalStackLayout
        HorizontalOptions="Center"
        VerticalOptions="Center">

       <controls:MessageView MessageText="GOODBYE" />

    </VerticalStackLayout>
</ContentPage>

Comment: Hi Peter, thank you for response, and excuse me whether i dont explain it with my code. MyCustomGrid Is a form that contain múltiples nested CustomControls, so i want to do in XAML:  where Client, Agent, and Sale are SubControls, and i want to set their properties that way. but i dont know whether is it posible.
Comment: You can still have nested controls with this. The contentView is a container and in there you set the . Don't use Binding or BindingContext. Rember that when you assign a Text property it is just for that property and you still need to assign that propert to the Label in your control. You can use `propertyChanged` for that. You set that in the `BindableProperty`


Multi-column join + aggregate subquery resulting in infinite run time

Question: I thought I knew what I was doing with queries, but this has more-or-less ruined my 4th of July holiday so I think it's high time to ask for help.  I imagine it's something trivial and obvious but it's escaping me for now.
I've got 3 tables in question here:
prod_account_details => 538k records
line_number PK,
acct_id integer, -- nearly unique, but not quite; acct_id PLUS address is unique
address varchar(100),
entity_name varchar(100),
(... a few other fields ...)

Indexes: btree on acct_id, hash on address, also btree on (acct_id, address).
prod_customer_profiles => 532k records, nearly 1:1 with account details
acct_id integer, -- corresponds to account_details.acct_id
match_input_address varchar(100), -- corresponds to account_details.address
(... lots of other fields ...)

Indexes: btree on acct_id, hash on match_input_address, also btree on (acct_id, match_input_address).
prod_billing_letters => 518k records, 1:M with account_details (covering ~181k acct_ids)
line_number PK,
acct_id integer, -- FK to account_details, not formally via constraint but semantically
(... a few other fields ...)

Indexes: btree on acct_id.
--- Queries ---
So firstly, what works:
(1)

SELECT ad.acct_id, ad.entity_name, ad.address, acx.flag_infobase_match
FROM prod_account_details ad
INNER JOIN prod_customer_profiles acx ON ad.acct_id = acx.acct_id
    AND ad.address = acx.match_input_address;

That returns the 532k matched records in 3.0 seconds.
Now if we INNER join to the billing_letters table via a grouped subquery:
(2)

SELECT ad.acct_id, ad.entity_name, ad.address, acx.flag_infobase_match, dl.num_records AS dl_count
FROM prod_account_details ad
    INNER JOIN prod_customer_profiles acx ON ad.acct_id = acx.acct_id
        AND ad.address = acx.match_input_address
    INNER JOIN (SELECT count(*) AS num_records, acct_id FROM prod_billing_letters GROUP BY acct_id ) dl ON ad.acct_id = dl.acct_id;

That it returns fine too, 161k records in 1.3 seconds.
But now if I do something as simple as changing that second join (to the subquery) to a LEFT JOIN, it blows up. i.e. I want all valid accounts, appended with the count of records in the billing_letters table if any exist:
(3)

SELECT ad.acct_id, ad.entity_name, ad.address, acx.flag_infobase_match, dl.num_records AS dl_count
FROM prod_account_details ad
    INNER JOIN prod_customer_profiles acx ON ad.acct_id = acx.acct_id
        AND ad.address = acx.match_input_address
    LEFT JOIN (SELECT count(*) AS num_records, acct_id FROM prod_billing_letters GROUP BY acct_id ) dl ON ad.acct_id = dl.acct_id;

What happens is, this runs for 20+ seconds, and then starts returning ~100 records every 10 seconds, which at the volume I'm talking about (>500k) would take forever to return.  And next up I need to bolt on the counts for some other, bigger tables too, so we're quickly approaching heat-death-of-the-universe amounts of runtime here.
Now what's interesting is, if I relax the join on the first two tables, i.e. drop the address part of the join and only do the acct_id one,
(4)

SELECT ad.acct_id, ad.entity_name, ad.address, acx.flag_infobase_match, dl.num_records AS dl_count
FROM prod_account_details ad
    INNER JOIN prod_customer_profiles acx ON ad.acct_id = acx.acct_id
    LEFT JOIN (SELECT count(*) AS num_records, acct_id FROM prod_billing_letters GROUP BY acct_id ) dl ON ad.acct_id = dl.acct_id;

That it starts returning immediately, and spools 695k records in 4.7 seconds.  The problem is that we need the address part of the join in there, because there are some duplicate acct_ids on both sides so we get a bunch of cartesian-join junk.
--- EXPLAIN query plans ---
So here's the Explain for query (1), with just the two tables:
Gather  (cost=102995.20..123944.32 rows=1 width=41)
  Workers Planned: 2
  ->  Parallel Hash Join  (cost=101995.20..122944.22 rows=1 width=41)
        Hash Cond: ((ad.acct_id = acx.acct_id) AND (ad.address = (acx.match_input_address)::text))
        ->  Parallel Seq Scan on prod_account_details ad  (cost=0.00..14226.43 rows=224343 width=39)
        ->  Parallel Hash  (cost=97096.88..97096.88 rows=224288 width=26)
              ->  Parallel Seq Scan on prod_customer_profiles acx  (cost=0.00..97096.88 rows=224288 width=26)

Now, when we add on the third table, its strategy for that join changes.  Here's the Explain for (2), with the inner join that works:
Gather  (cost=22500.40..83636.43 rows=1 width=49)
  Workers Planned: 2
  ->  Nested Loop  (cost=21500.40..82636.33 rows=1 width=49)
        ->  Hash Join  (cost=21500.40..40427.74 rows=56285 width=54)
              Hash Cond: (ad.acct_id = prod_billing_letters.acct_id)
              ->  Parallel Seq Scan on prod_account_details ad  (cost=0.00..14226.43 rows=224343 width=39)
              ->  Hash  (cost=19345.40..19345.40 rows=123920 width=15)
                    ->  GroupAggregate  (cost=0.42..18106.20 rows=123920 width=15)
                          Group Key: prod_billing_letters.acct_id
                          ->  Index Only Scan using prod_billing_letters_acct_id_idx on prod_billing_letters  (cost=0.42..14269.36 rows=519529 width=7)
        ->  Index Scan using prod_customer_profiles_match_input_address_idx on prod_customer_profiles acx  (cost=0.00..0.74 rows=1 width=26)
              Index Cond: ((match_input_address)::text = ad.address)
              Filter: (ad.acct_id = acct_id)

But then change it to a LEFT JOIN from query (3), the problem child, and it changes to:
Nested Loop Left Join  (cost=102995.63..144838.72 rows=1 width=49)
  Join Filter: (ad.acct_id = prod_billing_letters.acct_id)
  ->  Gather  (cost=102995.20..123944.32 rows=1 width=41)
        Workers Planned: 2
        ->  Parallel Hash Join  (cost=101995.20..122944.22 rows=1 width=41)
              Hash Cond: ((ad.acct_id = acx.acct_id) AND (ad.address = (acx.match_input_address)::text))
              ->  Parallel Seq Scan on prod_account_details ad  (cost=0.00..14226.43 rows=224343 width=39)
              ->  Parallel Hash  (cost=97096.88..97096.88 rows=224288 width=26)
                    ->  Parallel Seq Scan on prod_customer_profiles acx  (cost=0.00..97096.88 rows=224288 width=26)
  ->  GroupAggregate  (cost=0.42..18106.20 rows=123920 width=15)
        Group Key: prod_billing_letters.acct_id
        ->  Index Only Scan using prod_billing_letters_acct_id_idx on prod_billing_letters  (cost=0.42..14269.36 rows=519529 width=7)

Just reading that, I can't readily tell why #2 finishes fast, whereas #3 runs without end.  If the difference was JUST the use of a left join to the third table, then why does #4 finish easily too, just with a single-column join between the first two tables?
This has befuddled the rest of my experimentation with it, so I'd really appreciate some insight.
Answer: I can't see anything obviously wrong, but I can suggest an alternative approach to trial...
SELECT
  ad.acct_id,
  ad.entity_name,
  ad.address,
  acx.flag_infobase_match,
  (
    SELECT COUNT(*) AS num_records
      FROM prod_billing_letters
     WHERE acct_id = ad.acct_id
  )
    AS dl_count
FROM
  prod_account_details     ad
INNER JOIN
  prod_customer_profiles   acx
    ON  ad.acct_id = acx.acct_id
    AND ad.address = acx.match_input_address

Comment: It returns the right data in a reasonable amount of time, so thank you for the workaround.  That said, you can't filter on those fields in the outer-query WHERE clause or bring other aggregations in without a separate sub-SELECT each time.  So I'm still on the lookout for a way to fix the join-based approach.
Comment: @SteveEstes - Use a Lateral Join?  *(The PostGreSQL equivalent to the OUTER APPLY in the answer's edit history.)*


linking methods from an enum to member variables of client class

Question: The following enum structure performs certain operations while remaining agnostic to the client class (for encapsulation reasons)
    public enum MyEnum implements Commands{
    A{
        public int method1(int varY) {
            return varY+2;
        }

        public MyEnum method2(){
                       return MyEnum.B;
              }

             //...other methods implementing Commands interface
    },
    B{

        public int method1(int varX) {
            return varX-2;
        }

               public MyEnum method2(){
                       return MyEnum.C;
              }

        //...other methods implementing Commands interface
    },
    C{

        public int method1(int varY) {
            return varY-2;
        }

        public MyEnum method2(){
                        return MyEnum.D;
               }

              //...other methods implementing Commands interface
    },
    D{

        public int method1(int varX) {
            return varX+2;
        }

        public MyEnum method2(){
                      return MyEnum.A;
                 }

             //...other methods implementing Commands interface
    }

The client class
    public class Client {
    private int varX;
    private int varY;
    private MyEnum enum;

    MyEnum getEnum(){
        return enum;
    }

    int varX(){
        return varX;
    }

    int getVarY(){
        return varY;
    }

    public Client(int varX, int varY, MyEnum enum){
        this.varX = varX;
        this.varY = varY;
        this.enum = enum;
    }

    public void performMethod1(MyEnum enum){
        varX = getEnum().method1(getVarX()); //???
        varY = getEnum().method1(getVarY()); //???
    }

     public void performMethod2(...){
                enum = getEnum().method2();
      }
}

My question is how to link the specific implementations of method1() belonging to MyEnum.A and MyEnum.C so that they operate on Client class member varY, and the method1() implementations of MyEnum.B and MyEnum.D to operate only on Client class member variable varX.
For example within a main() method:
Client aClient = new Client(aVarX, aVarY, anEnum);
aClient.performMethod1(aClient.getEnum());

So, depending in the current enum state, the above statement should operate only on varX or varY and change the state on aClient.
Let's say for:
aClient.performMethod1(MyEnum.A);

The state of aClient represented by varY should be changed to varY+2. varX should remain unchanged.
As you can see by the simple naming convention, at this time varX in MyEnum is not linked to varX in Client class in any way. My thoughts lean toward the type of the variables. Since I am working with primitives (int) there is no way to distinguish..
Would you recommend I create different custom types for each of the varX and varY (wrap them somehow?) in Client class?
I hope I am not too verbose with the question. Please let me know in case I am not being clear with it. Many thanks.
Comment: In "performMethod1(...)", you use "getEnum().method1(...)" so its the enum of the Client that do method1 NOT the "enum" parameter.

I am not sure if you want to use the parameter "enum" to do method1 or what? Please clearify more.
Comment: Yes, the Client simply delegates to the different enumerations in the MyEnum class to perform the method logic.

But since MyEnum is a member variable of the Client as well, to chage state of the Client I would need to pass MyEnum to the other methods.. like method2(). Is that any clearer? Thanks for your comment
Comment: I updated both the MyEnum and Client code, to show that Client delegates to MyEnum which keeps a reference of, and changes the state of that enum which is an attribute of Client's. -- The aim is to do the same with the varX, varY Client members
Comment: >> The aim is to do the same with the varX, varY Client members

How can you do that without naming Client? As I said earlier either the enum has to know about the Client or the Client has to switch on the enum. Since enums are used for switching, that seems the better way to do it :-)
Comment: I am not sure I understand what you mean by "naming the Client"? As for the Client switching on the enum, that is certainly a way to go, but the objective is to avoid switch or if statements
Answer: You want different things to happen to the Client depending on different values of the MyEnum. If the MyEnum has to be client agnostic then either the Client will have to recognize different states of the MyEnum (a switch in Client.performMethod1) or a separate processor class will have implement that logic.
Comment: I see the point, but the objective is to avoid switch/if statements in the Client. The enum has all the alternatives already built-in

For example in another method not shown in the MyEnum, let's say method2, I could operate on the MyEnum cases itself. And then, in Client I could wrap this in performMethod2(MyEnum enum) and change the enum state of Client
Comment: I edited my original post to include method2() in MyEnum. It is better shown now that, Client has the ability to simply delegate to MyEnum by performMethod2(), keep its state and behavior encapsulated, while MyEnum is basically Client agnostic - no references to any objects that use its enumerations. -- So since this is possible with a MyEnum variable, it should be possible with the varX and varY primitives, right?


Cannot use emoji in terminal and on kate kubuntu 22.04

Question: I have Kubuntu 22.04 installed and I cannot use emoji in terminal and Kate application.
I found some articles online:

Use emoji inside terminal
Cannot Use Emoji within Browsers

Neither does not work for me. I need some help, please.
Comment: @Nmath Before I have upgraded to Kubuntu 22.04.even on 21.10 version i had this issue.
Comment: maybe i am missing package or something?
Comment: @Nmath i dont believe so. How can i find out?
Answer: NVM it works.
I used this command
sudo apt install kubuntu-Desktop
There were several packages that need to be installed. Once installed, I reboot my PC. Now, it works!


How to manage different screen resolution in wp7?

Question: I want to know what is the best way to handle the different screen resolutin while developing apps in windows phone 7.
Because i develope all application in 480 x 800 pixels and as i know not all mobile support  480 x 800 pixel  resolution .
If I hardcode the width, height, margin, etc. in the xaml, than it will be create problem  when the phone does not support 480x800 resolution.
So what is the best way to manage all resolutin in single application? like in android have differnt folder for diffrent resolution(Hdpi,Ldpi).
Help me
Comment: possible duplicate of [WP8 Emulator screen size](http://stackoverflow.com/questions/13470605/wp8-emulator-screen-size)
Comment: yes,wp7 does not support different solution but wp8 support this one and as per i know wp8 have very complex method for resolution.Suppose i have 100 image in diffrent page so  i have to use 300 "if" condition.this is much complex.Any other best solution for that?
Answer: Please read my previous answers on the topic: Zen of WP8 Multi-resolution support, APIs for WP8 mutli-resolution, DevCenter multiple XAP support, and WP7 & WP8 co-development guide.
Specifically have a look at the WP7 & WP8 co-development guide under Runtime adaption. That has this code snippet:
public Uri GetScaledImageUri(String imageName)
{
    int scaleFactor = (int)Application.Current.Host.Content.ScaleFactor;
    switch (scaleFactor)
    {
        case 100: return new Uri(imageName + "_wvga.png", UriKind.RelativeOrAbsolute);
        case 150: return new Uri(imageName + "_720p.png", UriKind.RelativeOrAbsolute);
        case 160: return new Uri(imageName + "_wxga.png", UriKind.RelativeOrAbsolute);
        default:  throw new InvalidOperationException("Unknown resolution type");
    }
}

// Next line will load a correct image depending on the resolution of the device
MyImage.Source = new BitmapImage(GetScaledImageUri("myImage"));

Also have a look at APIs for WP8 mutli-resolution that has these three mutually exclusive code snippets:
Image myImage = new Image();
if (MultiRes.Is720p)
    myImage.Source = new BitmapImage(new Uri("puppies.720p.jpg"));
else if (MultiRes.IsWvga)
    myImage.Source = new BitmapImage(new Uri("puppies.wvga.jpg"));
else if (MultiRes.IsWxga)
    myImage.Source = new BitmapImage(new Uri("puppies.wxga.jpg"));

if (MultiRes.Is720p)
    myImage.Source = new BitmapImage(new Uri(@"assets\16by9AspectRatio\puppies.jpg"));
else
    myImage.Source = new BitmapImage(new Uri(@"assets\15by9AspectRatio\puppies.jpg"));

if (MultiRes.IsHighResolution)
    myImage.Source = new BitmapImage(new Uri(@"assets\HD\puppies.jpg"));
else
    myImage.Source = new BitmapImage(new Uri(@"assets\SD\puppies.jpg"));

Comment: JustinAngel:thanks and you mean wp7 support only 480x800 pixel resolution?
Comment: yes that is fine but i want to diffrent resolution in same project so what about images folder and how to apply diffrent images and grid or stack panel size according diffrent resolution
Comment: You'll have to write code yourself to change images based on resolutions. You can make up your own file & folder name conventions. Again, See the code example for that under "Runtime adaption" in the linked article and specifically the method "GetScaledImageUri".
Comment: Yes, WP7 the platform only supports WVGA (480x800) so WP7 apps will only run in 480x800 logical pixels with 15:9 aspect ratio even on WP8. Once the app is recompiled to WP8 apps can support 16:9 aspect ratio. Please read the attached articles. However, WP7 apps running on WP8 WXGA/720P will have their images and videos bitmap scaled which might not look good.
Comment: :thanks but i think its very complecated when i have more than 10 image control than i have to apply 30 condition? and all images are apply on coding part? what is the work of xaml side?
Comment: :thanks sir you give right solution but its much complex.Resolution is not possible like iphone? for example in iphone contain only one image folder with diffrent name of image and system take image autometicaly as per phone resolution.
Comment: @JustinAnjel:Hello sir this is mansinh dodiya(.net and windows phone developer).may i take your facebook or twiter id?
Answer: I got solution for handling  diffrent screen resolution while developing application in wp8.
JustinAngel anser is also right but its some complecated because it contains a lot of code that needs to be maintained and its some what difficult.
So use Telerik RedControls.No code-behind is necessary to maintain and a simple straightforward way of loading different images depending on the resolution.
Please Reffer this link
Multi-Resolution support in Windows Phone 8 Made Easy
Hope this is help for all wp8 developer.


Moving button above tab bar (overlap) iOS

Question: I have a Tab Bar Controller, with 3 View Controllers, and one of the VC's contain's a button that animates, but slightly overlaps the tab bar.
I have it animating nicely, but obviously the buttons sits below the tab bar in the stacking order.
What's the best way to get it to sit above the tab bar? I have tried adding it as a subview of the Tab Bar Controller, like so:
initialRecordButtonX = recordButton.frame.origin.x
self.tabBarController?.view.addSubview(recordButton)
recordButton.frame.origin.x = initialRecordButtonX

But this seems to give me an issues with alignment, the button isn't in the original buttons position, but to the top left of the screen.
UPDATE:
var tabView : (UIView) = self.tabBarController!.view
var btnPoint : CGPoint = recordButton.center;
var btnRect : CGPoint = recordButton.convertPoint(btnPoint, toView: tabView)
self.tabBarController?.view.addSubview(recordButton)
recordButton.frame.origin = btnRect

Comment: You're grabbing the button's center, converting it to a point in another rect, and then setting the button's frame's origin to its original center point.  Read that in plain-English and see if you can spot your bug.
Comment: I can't spot it at the moment. The original centre point would be set by Storyboard right? Might be missing the obvious though!
Comment: Don't use ```recordButton.center``` use ```recordButton.frame.origin```
Comment: btnRect value is now (280.0,300.0), which matches the storyboard, yet it's still top left. Could it be down to constraints? Just doing some debug, viewDidLayoutSubviews - printing btnRect, I get (280.0,300.0) and (0.0,0.0) outputted.
Comment: If you are using ```autolayout```, yes. You might need to give the recordButton layoutContraints with code.
Answer: You probably have to convert the recordButton.frame to the coordinate system of tabBarController.view.
You can use:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/convertPoint:toView:
Answer: I ended up using a container, with the button being in a parent view controller, which fixed my issue.
Answer: Did you try to use .zPosition for the zAxis?
Therefore you can use any numbers. You can use .zPosition = 1 or with .zPosition = 9876.26. The only important thing is to make the numbers different. If the number is smaller, the element is lower / behind the other ones. If the number is larger, it is on top.
Hope that helps :)
Answer: You can try this: self.tabBar.viewWithTag(0)?.addSubview(recordButton)


virtual environment and/or acl?

Question: I was wondering if there is another method from access control on a folder to execute a file. I thought of something like a password protected virtual environment and only when accessing the virtual environment can one execute the files inside the folder(s). Or is there a simple acl method?
Comment: and also something like the folders/files are only visible after activating the virtual environment? so if the environment is not activated the files/folders just don't appear to be there (hidden)
Answer: Assuming you are referring to a Python virtual environment: this has nothing to do with access control. A Python venv just tweaks a bunch of settings in the current shell so the Python environment and interpreter is independent of the system-wide settings and modules. All files / directories in a Python venv can be access based on the set permissions (and ACL if used / set).
So you could use ACL or, as an alternative, assign the folder and everything included to a new group and then make the files accessible / executable only for the group.
What is the better way depends on what you want to achieve in the end. Probably you could go more in details of the final goal?
Comment: thanks, the goal is to keep a folder hidden with all its content, and after a certain command the directory 'appears' with all its files, without having to gpg encrypt-decrypt the direcorty, yet still using some sort of authentication to make the directory visible and accesible
Comment: Well, neither Linux permissions nor ACL are designed for that. Even when protecting a directory (and its subdirectories) this way, the top directory will be visible. Although unprivileged users will not be able to access it.
I'm not sure there any tool which is capable of doing what you intend to do. A possible way which may work is to put the files on a different drive and only mount it on-demand. However, I'm not sure how detailed you can assign mount privileges so only an assigned group of users can perform a mount.

virtual environment and/or acl?


Can I sample a Vulkan SRGB image with UNORM image view?

Question: This is my first try for a Vulkan rendering engine and I would like insights. My image loading code currently put images in SRGB VkImage, this is of course not suitable for normal maps and other data-textures that requires a UNORM format, I would like to avoid making a separate pool for "visual" and "data" textures or in-shader color-space remapping.
So is it safe to make a "savage C casting" by using a UNORM format in my VkImageView on a sRGB VkImage? Does this cost performance ?
I target consumer desktop iGPU/dGPU as first-class plus mobile devices and I might add supports for 16bits color formats.
Comment: "*I would like to avoid making a separate pool for "visual" and "data" textures or in-shader color-space remapping*" Why would they be different "pools"? Just use appropriate image formats. What formats you use don't (usually) change what "pool" your data comes from.
Comment: I forgot to mention that I accept user-generated glTF, my images pool use file hashes as key and one might in theory reuse the same texture for sRGB and linear spaces so guessing on first use the right format is fragile.
Answer: So I dug into Vulkan spec today and based on my interpretation the answer is: YES, you can do savage casting between UNORM and SRGB.

To cite Vulkan specification (same in 1.0.270 and 1.3.270) about Image Views:

... if image was created without the VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT flag and they are not equal they must be compatible. Image format compatibility is defined in the Format Compatibility Classes section. Views of compatible formats will have the same mapping between texel coordinates and memory locations irrespective of the format, with only the interpretation of the bit pattern changing.

And the Format Compatibility Classes section state that:

Uncompressed color formats are compatible with each other if they occupy the same number of bits per texel block as long as neither or both are alpha formats (e.g., VK_FORMAT_A8_UNORM_KHR). Compressed color formats are compatible with each other if the only difference between them is the numeric format of the uncompressed pixels. Each depth/stencil format is only compatible with itself.

Hence any UNORM format is compatible with equivalent SRGB and vice-versa. This is also true for compressed texture and for every GPUs with SRGB support it's a mandatory "feature".
Fun-fact, according to https://vulkan.gpuinfo.org/ stats as of 2023-11-14, B8G8R8A8_SRGB (99.87%) is technically "better supported" than B8G8R8A8_UNORM (99.38%) for optimally tiled sampled textures and color attachments (realistically it's safe to assume that all GPUs supports both).
Finally I fell that UNORM/SRGB performance difference is insignificant.


What does upgrading an expression do?

Question: When praying to a spirit in Sky: Children of the Light, there is an option to spend candles to upgrade expressions. I upgraded my "wave hello" expression to level 2 as a test, but I can't figure out how it changed.
What does upgrading an expression do?
Answer: Generally the 2nd level of an expression adds in some sort of lighting effect.  This doesn't effect how the game works, but rather adds another level to how you can communicate with other players.
The game still allows you access to the 1st level of the expression (1st level is used when you tap the expression.)  For this reason you'll have to hold the expression button slightly longer to activate the 2nd or higher level of an expression.  You'll be able to tell what level you're using based on which dot above the expression is lit up when you release the expression button.  These dots are not present until after that expression has more than 1 level.

What does upgrading an expression do?


Why did I get an empty list using Scrapy shell?

Question: The website is "https://www.jbhifi.com.au/collections/laptops". I'm trying to crawl the href for the "next page".

But why scrapy shell returns an empty list? I'm using the statement:
response.css("li.ais-pagination--item ais-pagination--item__next a").xpath("@href")

Please show me how to scrape this using Scrapy. I suspect this is because the class starts with "ais" (but don't know why it causes the problem). This happened to me in the past. Any solutions? Cheers!
Comment: If you have problem with categories, you can automate that part and find out which category you are in by `response.xpath('//meta[@property="og:url"]/@content').get()
` and just modify the pagination related part of URL
Comment: ```
In [8]: response.xpath('//*[@id="collection-search-pager"]').get()
Out[8]: ''```
next page href does not exists in page source
Comment: Why don't you modify URL to get to next page ?
Comment: I'm trying to use scrapy to scrape the entire jb hi-fi. Modifying URL would not work for a different category (I'm in the computer category). I'm trying to automate everything.
Comment: It would work... by considering all the categories (but painful). And if Jbhifi changes the category name in the future (it will be more pain debugging). Retail shops like Jb hi-fi do change their category a lot.
Comment: next page href does not exists in page source
Comment: In my image (the right blue circle) have the required href. I just want the XPath, CSS or in conjunction with XPath and CSS to retrieve it.
Answer: There is a need to understand that if you are extracting selectors merely on basis of inspect element it does not work that way. You need to check page source that what actually comes at time when page was loaded. While inspecting we are able to see all that content which all request against a page update. In your case there is no such class in page source ais-pagination--item__next. You have to track network, check which call is being hit on click of next page button and crack the logic which is being implemented.


How can I prevent mold on the wall/particle board behind the kitchen sink?

Question: Behind the kitchen sink I noticed this deteriorating situation happening so I took it apart until I found no more mold and then washed with bleach (1 tbsp to 1 gallon) and let it dry good.  It's all the way down to the dry wall.  There does not appear to be a leak or any sort, but the splashing from washing dishes seems to have caused.  Any recommendations on how to go about fixing and avoiding in the future?
Answer: It's hard to tell from the picture but it looks like it was tile mounted to a wood board.  Wood is one of the worst materials for behind the sink.  If going to replace with tile, use a concrete backer board instead and consider using tile trim caps to cover the top.  Otherwise use a solid stone or stone like material.
And make sure the caulking is in good shape.  Every couple of years it needs to be stripped out and replace.  If it is starting to look old and cracked, it's been there too long.  No mater what the material, water under or behind the splash with always cause problem.s
Comment: A silicone caulk will last longer than a paintable latex caulk, too.


Why won't my Nether Portal light?

Question: When I buld a nether portal and light it it wont light. The obsidian lights on fire but no portal please help me fix this.
Comment: How did you build your portal? Try to provide some more information so it's easier for us to help you.
Comment: Are you on single player?
Comment: @kutschkem Single play and multiplayer doesn't affect nether portal lighting, unless he's in a server.
Comment: @Jim I don't quite remember why I asked that, I think lighting the portal only works inside your claim on some servers with grief prevention
Answer: Make sure your portal has a complete connection around an area that your charactor can pass through, like the picture below, before lighting it, or else the portal will not open. (Example is for a 4x5 portal frame)

Source of Photo
Comment: Portals are no longer constrained to be only 2x3
Comment: ahh @SaintWacko thank you, did not know that!  Updated
Comment: I edited it slightly to clarify it. Feel free to revert if you feel it changes too much.

Why won't my Nether Portal light?


AWS ALB URL-Routing: Redirecting '/#/signin' Path

Question: I want to redirect all paths matching /#/signin to a different URL using AWS Application Load Balancer's listener rules for path based routing. However, AWS declares this path as invalid as it contains the character #. Is there a way to acheive routing for such paths using AWS ALB?
Note - modifying the path is not an option.
Answer: You won't be able to redirect that path with any AWS technology, or any sever-side technology at all, because anything after a # in a URL is a "fragment" which is never sent to the server.
When you load the URL https://example.com/#/signin in a browser, the browser splits it into several parts:

The scheme "https", which tells it the protocol to use, and the format of the rest of the URL
The hostname "example.com", which is used to look up an IP address to connect to, and then sent in the TLS handshake (SNI) and in the HTTP "Host:" header
The path "/" which is requested once the connection is established
The fragment "#/signin" which is used once the response is received to scroll to a matching anchor on the page, if one is found; and is then made available to JavaScript
Answer: For the correct solution, check @IMSoP's answer.
I'm leaving mine to provide additional information:

I believe you cannot do redirects like that purely with ALB.
You can, however, target a Lambda and that lambda could do any custom routing logic you want. True, this approach is not the best.
It feels better to catch this issue before the ALB, like using CloudFront functions:
https://aws.amazon.com/blogs/aws/introducing-cloudfront-functions-run-your-code-at-the-edge-with-low-latency-at-any-scale/
It would be pretty typical usage for this feature.
You could also look at API gateways, but I'm not entirely sure it would be easier to use.

If we are moving away from AWS space, these redirections could be made with DNS as well. If you are using i.e.: Cloudflare before your AWS resources, it could be done with that as well:
https://developers.cloudflare.com/support/page-rules/configuring-url-forwarding-or-redirects-with-page-rules/
Comment: You will find that all of these technologies reject, or ignore, URLs with `#` in them, because it's actually impossible to process them on the server side, as I explain in my answer.


Binomial Formula evaluation for the problem $9 \mid 10^k - 1$ for $k \in \mathbb{N}$

Question:
Prove using binomial formula $9 \mid 10^k - 1$ for $k \in \mathbb{N}$

I am aware of similar answer to this question here and here however my query is about the manipulation on the binomial formula in my proof.
My attempt at the proof :
We notice that $$10^k - 1 = (9 + 1)^k - 1$$ $$=\left(\sum_{i = 0}^{k} {k \choose i} 9^{k-i} \right) - 1$$
How do I further remove the -1 to show that this indeed is divisible by 9 ?
Comment: Every term in the summation but the last is a multiple of $9$ and the last term in the summation is equal to $1$ itself and cancels with the $-1$ outside of the summation.
Comment: @JMoravitz pls write this comment as answer so that OP can accept your answer.
Comment: Oh I see, Thanks!
Answer: Hint
$$\left(\sum_{i = 0}^{k} {k \choose i} 9^{k-i} \right) - 1=$$
$$=\sum_{i = 0}^{k-1} {k \choose i} 9^{k-i}+ {k \choose k} 9^{k-k} - 1$$
How much is ${k \choose k} 9^{k-k}$?
Comment: Please strive not to add more dupe answers to dupes of FAQs, cf. site policy [here](https://math.meta.stackexchange.com/q/33508/242).
Answer: You can't really remove the $-1$, but don't need to:   one of the terms in the sum is $1$, cancelling with the  $-1$.  The rest are divisible by  $9$.


Parsing string values from a special response pattern in java

Question: In my application , i am getting a response string from a device that has a pattern like that;
+CUSD: <m>[,<str>,<dcs>]

Here <m> is number, <str> is string, <dcs> is number and the values in brackets may exist or may not exist.
For example i may get this response;
+CUSD: 4

or this response;
+CUSD: 2, "The string value which can have also comma",15

So, i want to parse <m>,<str> and <dcs> values from response. How can i do that ?
Comment: String.split (",", -1);
Comment: Could you have commas in your string? Could you have quotes in your string?
Comment: Yes i can have commas in my string and but not have quotes
Answer: You may start with a pattern like
\+CUSD\: ([0-9]+)(,\"([a-zA-Z, ]+)\",([0-9]+))?

where \+CUSD\: is the static part, ([0-9]+) describes <m>, ,\"([a-zA-Z, ]+)\", describes <str> with the commas and ([0-9]+) describes <dcs>.
Corrected (now ignoring whitespaces)
\+CUSD\: ([0-9]+)(,\s*\"([a-zA-Z, ]+)\",\s*([0-9]+))?

Comment: thanks, but when i try your pattern, the results are like that ;
group 1: [+CUSD: 2," The string,value which can have also comma",15]
group 2: [2]
group 3: [," The string,value which can have also comma",15]
Comment: Yes, because whitespaces do not get captured. Corrected the original answer.
Answer: You mean this regex,
\+CUSD:\s*(\d+)(?:,\s*\"([^\"]*)\"(?:,(\d+))?)?

In java it would be,
"\\+CUSD:\\s*(\\d+)(?:,\\s*\\\"([^\\\"]*)\\\"(?:,(\\d+))?)?"

DEMO
First capturing group(\d+) captures the <m> part and the second one([^,]*) captures the <str> part and the third one (\d+) captures the <dcs> part.
Comment: thanks but in demo, a comma in the string value breaks down the regex
Comment: you mean the comma before number 15
Comment: in java your pattern gives error here "([^,]*)\\" cause of quotes
Comment: your java string would be `"\\+CUSD:\\s*(\\d+)(?:,\\s*\\\"([^,]*)\\\"(?:,(\\d+))?)?"`
Comment: i cant get three groups from second scenario which has string value. it takes all input as a one group
Comment: now see the demo you should. It captures the string if it contains `,`
Comment: yes it works correct in demo :) so can you correct pattern for java because it gave error, i corrected but then not worked properly
Comment: use a verbatim symbol before the regex. In that way, you don't need to escape backslash. `@"\+CUSD:\s*(\d+)(?:,\s*\"([^"]*)\"(?:,(\d+))?)?"`
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/56694/discussion-between-jman-and-avinash-raj).
Answer: import java.text.ParseException;

public class Main
{

    public static void main(String args[])
        throws ParseException
    {
        parse("2, \"The string, value which can have also comma\",15");
        parse("4");
    }

    private static void parse(String str)
    {
        String[] part = new String[] {"m", "str", "dcs"};
        System.out.println("Input: "+str);
        String[] pieces = str.split("\"");
        for (int i = 0; i < pieces.length; i++)
        {
            System.out.println(part[i]+":"+pieces[i].replace(",",""));
        }
        System.out.println("--------------------------------------------");
    }

}

Result:
Input: 2, "The string, value which can have also comma",15
m:2
str:The string value which can have also comma
dcs:15
--------------------------------------------
Input: 4
m:4
--------------------------------------------

Comment: thanks but I am reading string value from socket so "\" character does not exist.
Answer: you could do something like this.
String response = "+CUSD: <m>,<str>,<dcs>";
String[] array = response.substring(response.indexOf(':')).split(",");
for (String s : array)
{
    System.out.println("extracted string = " + s);
}

Comment: my string value can has comma so split method will fail.


How to perform backward fill in SQL in snowflake

Question: I am trying to derive a column in snowflake SQL query that is equivalent to fill function in tidyr package of R. I have added the Expected output column which basically has the TIMESTAMP2 value when accompanied with a future non-null value. I am able to get this done using LAST_VALUE as mentioned below but it is filling the last row of TIMESTAMP2 as well with 6/7/23 3:21 AM while I am expecting a NULL value over there as it is not accompanied by a future non-null value. Could someone please share their thoughts on this of what I am missing?
LAST_VALUE(TIMESTAMP2 IGNORE NULLS) OVER (PARTITION BY A  ORDER BY TIMESTAMP1 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

Group TIMESTAMP1        TIMESTAMP2       Expected Output
A     11/22/21 7:24 AM  6/16/22 7:26 AM  6/16/22 7:26 AM
A     10/11/22 6:46 AM  NULL             5/11/23 3:17 AM
A     10/11/22 6:47 AM  NULL             5/11/23 3:17 AM
A     10/11/22 6:47 AM  NULL             5/11/23 3:17 AM
A     10/11/22 6:50 AM  NULL             5/11/23 3:17 AM
A     10/11/22 6:51 AM  5/11/23 3:17 AM  5/11/23 3:17 AM
A     5/30/23 5:22 AM   6/7/23 3:21 AM   6/7/23 3:21 AM
A     10/24/23 7:19 AM  NULL             NULL```

Comment: Could you please provide data as text not image ?
Comment: Added the data as text..
Answer: The ORDER BY should be in descending order :
SELECT *, LAST_VALUE(TIMESTAMP2 IGNORE NULLS)
               OVER (PARTITION BY Grp  ORDER BY TIMESTAMP1 DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS EXPECTED
FROM mytable
ORDER BY TIMESTAMP1;

Results :
GRP TIMESTAMP1      TIMESTAMP2      EXPECTED
A   2021-11-22 7:24 2022-06-16 7:26 2022-06-16 7:26
A   2022-10-11 6:46 null            23-05-11 3:17
A   2022-10-11 6:47 null            23-05-11 3:17
A   2022-10-11 6:47 null            23-05-11 3:17
A   2022-10-11 6:50 null            23-05-11 3:17
A   2022-10-11 6:51 23-05-11 3:17   23-05-11 3:17
A   2023-05-30 5:22 23-06-07 3:21   23-06-07 3:21
A   2023-10-24 7:19 null            null

Demo on oracle 23


"-f" in apt-get -f install command?

Question: Let me know word "-f" mentioned in apt-get -f install, what it actually denotes?

apt-get -f install
Comment: perfect example for rtfm ...
Answer: -f tells apt-get to fix broken packages by trying to locate and install missing dependencies.
Comment: `Errors were encountered while processing:
 postfix
 mailutils
E: Sub-process /usr/bin/dpkg returned an error code (1)`
Comment: Please help me on the above error. If possible, in the question also. https://askubuntu.com/questions/985925/sub-process-usr-bin-dpkg-returned-an-error-code-1-mailutils-installation

"-f" in apt-get -f install command?


Brightness flickering on Lenovo Yoga 720 | Ubuntu 18.04

Question: I have a Lenovo Yoga 720 and am running Ubuntu 18.04. The screen changes brightness automatically every 5-10 sec. This does not happen with Ubuntu 17 or Windows 10 (dual boot). Please assist.
<code>description: Convertible
product: 81C3 (LENOVO_MT_81C3_BU_idea_FM_YOGA 720-13IKB)
vendor: LENOVO
version: Lenovo YOGA 720-13IKB
serial: MP1CHKDC
width: 64 bits
capabilities: smbios-3.0 dmi-3.0 smp vsyscall32
</code>
Answer: This may be caused by the adaptive brightness setting. I had the same issue. It's way too aggressive for my preferences.
Go to Settings > Power then turn automatic brightness off
Comment: Wow, what a poorly executed feature. I thought this was a graphics driver bug, changed my drivers, switched to wayland then believed it must have been a hardware failure. Thanks for the tip, this saved me hours more debugging and perhaps buying a new computer!
Comment: I spent one hour debugging kernel options for i915 (yoga 910) only to find this is the issue, because I didn't imagine they would implement an auto brightness that changes all the time in such a distracting manner. People generally don't expect your brightness to keep changing randomly dozens of times a minute (really) with constant ambient light.
Comment: This solved the same problem on a Lenovo Yoga 730-15IKB
Comment: Thanks, this was driving me bonkers on my Yoga.
Comment: Bingo. Thanks for the help.
Answer: I have the same issue after upgrading Ubuntu to 18.04 from 16.04 on my XMG C404 laptop.
Changing the Refresh Rate of my screen helped yesterday, today I'm back to flickering, although less often/disturbing than before. Any news what could be the cause?
Settings > Displays > Refresh Rate
I reduced it from initially 60Hz to 59.96Hz. And then also tried increasing to 120Hz.


DDD/MVC: how to avoid hitting the Repository from the View?

Question: After reading several other questions, it looks like it's not advisable to have an entity class use a Repository. So given these repositories:
class RestaurantRepository {
    public function findAll() { ... }
}

class ReviewRepository {
    public function findByRestaurant(Restaurant $restaurant) { ... }
}

I should not do this in my class:
class Restaurant {
    public function getReviews() {
        // ...
        return $restaurantRepository->findByRestaurant($this);
    }
}

Buts let's say I have this controller, which gives a list of Restaurants to the view:
class IndexController {
    public function indexAction() {
        $restaurants = $restaurantRepository->findAll();
        $this->view->restaurants = $restaurants;
    }
}

What is the "good practice" to get each restaurant's reviews in the view script? I can therefore not do this:
foreach ($this->restaurants as $restaurant) {
    $reviews = $restaurant->getReviews();
}

And I guess that injecting the ReviewRepository in the view is not what we can call a "best practice" as well...
Any comment welcome!
Answer: If you need to have the reviews with the restaurant, your restaurant repository should (perhaps, optionally) retrieve these with the restaurant.  These would be stored in the class instance as a collection of Reviews along with each Restaurants other data.  This will allow you to construct a more efficient query that will get all the data in one go and populate the required objects.  The design pattern is called aggregate root.
class RestaurantRepository {
    public function findAll($withReviews = 0) { ... }
}

class IndexController {
    public function indexAction() {
        $restaurants = $restaurantRepository->findAll(1);
        $this->view->restaurants = $restaurants;
    }
}

<?php
foreach ($this->restaurants as $restaurant) {
    foreach ($restaurant->reviews as $review) {
       ...
    }
}
?>

Comment: Thanks for your answer. Actually, both Restaurant and Review are aggregate roots (a Review has a Restaurant and a User, and has its own Repository). A Review can be created outside a Restaurant, so in my understanding it's not part of the Restaurant aggregate. Therefore should a Restaurant's *Review collection* still be populated by the Restaurant repository?
Comment: I finally realized that I didn't need all the reviews for each restaurant, but just a summary of them. I've therefore put review statistics (number of reviews, average rating) in the Restaurant entity, and don't need to access the ReviewRepository anymore. And if I needed to do this, I would just introduce a value object that would contain the restaurant along with its reviews, and pass this to the view.


"Some Controls Could Not Be Added to This Location" When Adding More Than One Dropdown to a Cell in a Table

Question: I am making a function in my access database that creates a calendar using a template with a pre-made table in it. It'll have a "status" dropdown for each shipment taking place on a given day. I was able to create a dropdown for each cell in the table, but as soon as I move the set statement inside of this do-while loop, I get the following message in word:

Some controls could not be added to this location

followed by:

Run-time error '4198': Command Failed

In access
I found this question mentioning problems with content controls:
Adding content control throws an exception dynamically
But it's not in VBA. Is it possible that there is some kind of equivalent issue here or is this a dead end?

For i = 1 + 1 To NUMBER_OF_WEEKS + 1 '16 + 1

        For j = 1 To NUMBER_OF_DAYS_IN_THE_WEEK ' 7

             Do While Not rst.EOF ' rst is a DAO.Recordset of shipping dates ordered chronologicly. multiple items can ship the same day
                If rst![Ship] <> currDay Then ' if nothing left to ship this day, move to next cell/row
                    Exit Do
                End If

                doc.Tables(1).Cell(i, j).Range.InsertAfter vbCrLf 'supposed to add a new line between dropdown lists

                Set DDown = doc.Tables(1).Cell(i, j).Range.ContentControls.Add(wdContentControlDropdownList) 'This line fails upon adding a second dropdown to a cell

                'Add items to dropdown
                DDown.DropdownListEntries.Add "Shipping within 7 days"
                DDown.DropdownListEntries.Add "On schedule"
                DDown.DropdownListEntries.Add "On Hold"

            Loop

        'move to the next day
        currDay = currDay + 1
    Next j
Next i

I was expecting to result in multiple dropdown lists for each day, but it results in a single dropdown in the 2nd cell of the first row (can't ship on sundays so it skips the first cell of each row) before saying that the Content control cannot be added
Answer: The tricky part about putting things in a table is making sure the target position is in the cell and not in the table structures or, in the case of content controls, within the content control. Working with Range objects makes this easier to control.
Note that it's not clear from the code in the question when i and j are being incremented, so the approach may need to be adjusted for the actual loops being performed. Since I don't have your database, my testing was done out-of-context, but something like this, building it into the code in the question.
First, declare objects for working with the target table, cell and range. The key is to collapse the target Range before inserting new content.
There's also an "oddity" when inserting numerous content controls in a loop that Word will suddenly mix up the actual target Range with that of the last content control inserted. For this reason, the code selects the target Range in each loop, which seems to help Word keep things straight...
Dim tbl As Word.Table, cel As Word.Cell
Dim celRange As Word.Range
Dim DDown As Word.ContentControl

Set tbl = doc.Tables(1) 'one table, so do it before the loop

Do While Not rst.EOF ' rst is a DAO.Recordset of shipping dates ordered chronologicly. multiple items can ship the same day
    If rst![Ship] <> currDay Then ' if nothing left to ship this day, move to next cell/row
        Exit Do
    End If

    Set cel =  tbl.Cell(i, j)
    Set celRange = cel.Range
    'Move the target focus to the end of the cell
    celRange.Collapse wdCollapseEnd
    celRange.MoveEnd wdCharacter, -1

    Set DDown = celRange.ContentControls.Add(wdContentControlDropdownList)

    'Add items to dropdown
    DDown.DropdownListEntries.Add "Shipping within 7 days"
    DDown.DropdownListEntries.Add "On schedule"
    DDown.DropdownListEntries.Add "On Hold"

    'The target range will still be ahead of the content control, so
    'Prepare for the next content control by adding a new paragraph
    ' and putting the target area at the end of the cell
    Set celRange = cel.Range
    celRange.Collapse wdCollapseEnd
    celRange.MoveEnd wdCharacter, -1
    celRange.Text = vbCrLf  'add a new line between dropdown lists
    celRange.Collapse wdCollapseEnd

    'After some iterations, celRange remains attached to the inserted content control
    'causing an error about the target overlapping a plain text content control.
    'Selecting the range puts the focus for insertion in the right place
    celRange.Select
    Set DDown = Nothing

Loop

Answer: You need to move the current selection cursor position to a spot after the end of the control you just added. This is the solution offered in the SO question you reference in your question Adding content control throws an exception dynamically
The code in that question isn't VBA, but the underlying libraries are the same, hence the similarities.
Change your loop as follows:
    Do While Not rst.EOF ' rst is a DAO.Recordset of shipping dates ordered chronologicly. multiple items can ship the same day
        If rst![Ship] <> currDay Then ' if nothing left to ship this day, move to next cell/row
            Exit Do
        End If

        Set DDown = doc.Tables(1).Cell(i, j).Range.ContentControls.Add(wdContentControlDropdownList) 'This line fails upon adding a second dropdown to a cell

        ' move current selection to after the end of the newly added control
        doc.Application.Selection.Start = DDown.Range.End+1

        'Add items to dropdown
        DDown.DropdownListEntries.Add "Shipping within 7 days"
        DDown.DropdownListEntries.Add "On schedule"
        DDown.DropdownListEntries.Add "On Hold"

    Loop

Comment: It's still giving me the same errors. When I roll over the line of code you recommended, it said: `DDown.Range.End  = `. is that a problem?


Ubuntu 12.04 LTS fails to boot after Linux kernel update and restart on Intel® Core™ i7-3720QM CPU @ 2.60GHz × 8 laptop

Question: I did the most recent updates as I regularly do but this time I got the black screen of death after restarting. No way I can get the system to boot even though the boot options and BIOS settings look right to me.
I ran Ubuntu 12.04 from a cd and I can see the HD partitions but can't access the files because I am not the owner(owner: 1000 - user #1000).
What is the best way to recover my data?
What boot recovery tools are safer/easier to use?
I wonder if this happens to other distros that have a reputation for more testing like Fedora or OpenSuse. Any comments would be welcome on this subject.
Thanks,
Pablo
Answer: One thing you can try right off the bat is to boot up your computer while holding the left SHIFT key until you get to the GRUB prompt. Then select an older Kernel version to boot using the arrow keys and enter key. You may have to choose "Advanced Options" to get to the kernel versions.
Failing that, you can try booting with Recovery Mode, also from that same Grub menu. For backing up, this answer should help you access the files on your hard drive while booted with the Live CD. How do I get root access to hard drive from livecd?
If you still cannot access your hard-drive files, they may be encrypted. Try this answer to access encrypted drives & files: How to recover encrypted home data with Live CD?
Comment: Thanks Michael. I did not know about the shift key while rebooting to access the grub menu. Instead I went for the live CD and looked up the internet for a remedy and used the advice in [Boot-Repair](https://help.ubuntu.com/community/Boot-Repair). I remembered I had used the GUI version of this program when I started with Ubuntu last year and it had fixed the failed boots after installations. Now my question is how can I get rid of the GRUB screen every time a start the computer? I want to run the latest Linux kernel version as deployed by Ubuntu through the updates. Thanks
Comment: I thought the Grub screen would go back to normal by itself... but if not, you can edit Grub configuration by following information in this answer http://askubuntu.com/questions/100232/how-do-i-change-the-grub-boot-order
Comment: Michael. Thanks again. **Grub Customizer** worked very well. There is an option under _General Settings/ Visibility_ called "Look for other operating systems". Since I only run Ubuntu I disabled it and its companion option "Show menu" and there you have it, the grub menu does not show when I boot my machine. I also found options for hiding previous OS versions or prioritizing which one appears first on the list and an option for how many seconds you want the Grub screen to show before selecting the default OS if more than one is installed. I could use this customization for other boxes.
Comment: Glad to hear that Pablo. If you think this provided good information, you may click the green "Checkmark" icon in the top left corner of the answer on this page.


How can I fill the empty space behind a bug screen installed on these stone arches?

Question: I want to install bug screens in the open stone arches of my sunroom. I have flexible screen retainers ready to replace the wood that the previous owner roughly installed for the same purpose.

The problem I'm trying to solve is with the deep spaces between the stones that I'd be screwing into. I'd at best have 3 inches of open air behind the screen retainers (in the mortar joints) if I just screwed them into the stone face and left it alone. You can see a similar problem here with the wood currently installed. Hello bugs.

What is the best way to build up a backing or otherwise bug seal up those gaps? Is it just to use type N mortar and create a smooth surface?
Answer: You have the right idea - you're either looking at a VERY tedious scribing job for a filler board, or a relatively very simple "pack it with masonry" approach, unless there's some suitable surface outside where you could just run the screen to cover both the opening and the stonework, but you might not like that look.
Might use less-robust mortar (type O) to simplify removal if ever desired. This is a very non-structural application where its low strength won't have a downside.
Comment: Or, of course, the messy and highly regrettable "modern" approach of spray-foaming it...which I do not recommend, in spades.
Comment: There's a lot of polymer foams which would conform to the masonry shape, or be easily cuttable to size, but I don't know what is suitably weather, UV and pest resistant for this purpose. You'd certainly want a closed cell one...