Code Bug Fix: Reinstantiate an @EnvironmentObject in a view

Original Source Link

In my application, I have the need to reinstantiate an @EnvironmentObject at the tap of a button. Where is the right spot to do that?

Here’s a screenshot of my view – in the Archived Objects list, I want to have immutable objects. So, when I tap Archive Object, I want to add the current object to the array and create a new current object.

enter image description here

A simplified version of the app looks as follows.

I instantiate the object in the SceneDelegate:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    var myObject = MyObject()
    let myObjects = MyObjects()

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        let contentView = ContentView()
            .environmentObject(myObject)
            .environmentObject(myObjects)

        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

    //.....
}

Here’s my models:

class MyObject: ObservableObject, Identifiable {
    @Published var id = UUID()
}

class MyObjects: ObservableObject {
    @Published var values: [MyObject] = [
        MyObject(),
        MyObject()
    ]
}

In my view, I have the need to put my current object to an (archive) array and then create a new current object to work with. Here’s what I’m trying:

struct ContentView: View {

    @EnvironmentObject var currentObject: MyObject
    @EnvironmentObject var objects: MyObjects

    var sceneDelegate: UISceneDelegate {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
            let sd = windowScene.delegate as? SceneDelegate else { fatalError() }
        return sd
    }

    var body: some View {
        VStack {
            Form {
                Section(header: Text("Current Object")) {
                    Text(currentObject.id.uuidString)
                }
                Section(header: Text("Archived Objects")) {
                    List(objects.values, id: .id) { object in
                        Text(object.id.uuidString)

                    }
                    Button(action: {
                        self.objects.values.append(self.currentObject)

// as the environment object is get only, I cannot reinstantiate it here...
//                        self.currentObject = MyObject()
                    }) {
                        Text("Archive Object")
                    }
                }
            }

            Spacer()
        }
    }
}

Here is a solution. See comments inline.

Tested with Xcode 11.4 / iOS 13.4

demo

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {

        // Usage
        ContentView(current: MyObject())
            .environmentObject(MyObjects())
    }
}


struct ContentView: View {
    @EnvironmentObject var objects: MyObjects
    @State private var current: MyObject        // tracks current

    init(current: MyObject) {
        _current = State(initialValue: current)
    }

    var body: some View {
        // rebuilt on *current* changed
        ContentInnerView(current: $current)
            .environmentObject(current)
    }

    struct ContentInnerView: View {
        @Binding var current: MyObject   // change current

        @EnvironmentObject var objects: MyObjects
        @EnvironmentObject var currentObject: MyObject

        init(current: Binding<MyObject>) {
            _current = current
        }

        var sceneDelegate: UISceneDelegate {
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                let sd = windowScene.delegate as? SceneDelegate else { fatalError() }
            return sd
        }

        var body: some View {
            VStack {
                Form {
                    Section(header: Text("Current Object")) {
                        Text(currentObject.id.uuidString)
                    }
                    Section(header: Text("Archived Objects")) {
                        List(objects.values, id: .id) { object in
                            Text(object.id.uuidString)

                        }
                        Button(action: {
                            self.objects.values.append(self.currentObject)
                            self.current = MyObject() // << works !!
                        }) {
                            Text("Archive Object")
                        }
                    }
                }

                Spacer()
            }
        }
    }
}

Tagged : / /

Math Genius: Fibonacci Numbers with Hot Potato Game

Original Source Link

Five people, $A, B, C, D, E$ are playing a game of Hot Potato. The potato starts with Person $A.$ Every person must pass the ball to someone else. The potato returns to person $A$ after the eighth pass. How many possible sequences of passes are there?

I think we draw a circle of the people $A,B,C,D,$ and $E.$ There are eight passes that were completed and each person has $4$ choices. Then we find the total, I’m not sure if this is the right approach, though.

It’s not quite right to say that everyone has $4$ choices. Since the $8$th pass goes to $A$, the $7$th pass can’t go to $A$, or $A$ would make the last pass to himself. If we write down the players who touch the ball, in order, we’ll have a $9$-letter string formed from the letters $A,B,C,D,E$ that starts and ends in $A$, such that no letter appears twice in succession, and the problem is to count these.

Suppose $A$ doesn’t appear in the intermediate string (the $7$=letter string between the ends.) Then there are $4$ choices for the first letter (anything but $A$) and $3$ choices for each succeeding letter (anything but $A$ or the preceding letter.) That makes $4cdot3^6$ strings with exactly $2$ $A$‘s.

Now suppose there is exactly $1$ $A$ in the intermediate string. There are $5$ places the $A$ can appear, since it can’t be first or last. We can break the $9$-letter string into two that start and end with $A$, one with $k$ letters, and one with $10-k$ letters. (The middle $A$ is counted twice.) By the same reasoning as above there are $cdot3^{k-3}$ possibilities for the first string and $4cdot3^{10-k-3}$ for the second, which gives $4^2cdot3^4$ combinations, regardless of the value of $k$. So, we have $5cdot4^2cdot3^4$ strings with exactly $3$ $A$‘s.

Can you carry on?

Tagged : /

Code Bug Fix: How to search through data using Laravel and Vue js?

Original Source Link

I’d like to create a Search bar where Users can search and find matching results by 3 columns, job_title, company_name and country.

I was able to create a Search Filter through one of the columns using a computed property.

The problem is its returning matching records from the job_title column only, instead of all 3 columns. Is there a way to add multiple columns to this?
I tried return jobPost.match(this.search); instead of return jobPost.job_title.match(this.search); to maybe get the whole table but that just returned an error.

data() {
            return {
                jobPosts: [],
                search: ''

            };
        },
computed: {
            filteredJobs: function() {
                return this.jobPosts.filter((jobPost) => {
                    return jobPost.job_title.match(this.search);
                })
            }
        }

CandidateSearchController.php file:

public function search(Request $request)
    {
        $search = $request->get('q');
        $jobPosts = JobPost::with('employerprofile')
            ->where('job_title', 'like', '%'.$search.'%')
            ->get();

        return Response::json(array(
            'jobPosts' => $jobPosts,
        ), 200);
    }

Search input and Button:

<input type="text" v-model="search" placeholder="Search job titles.."/>
<button class="btn btn-primary" style="padding: 7px 10px; margin-top: -1px;">
   <i class="fas fa-search"></i>
</button>

Since you have a single input you can use OR in sql query itself to match a given string to job title, company and country

public function search(Request $request)
{
    $search = $request->get('q');
    $jobPosts = JobPost::with('employerprofile')
    ->where('job_title', 'like', '%'.$search.'%')
    ->where(function($q) {
        $q->where('job_title', 'like', '%'.$search.'%')
           ->orWhere('company_name', 'like', '%'.$search.'%');
           ->orWhere('country', 'like', '%'.$search.'%');
    })
    ->get();

    return Response::json(array(
        'jobPosts' => $jobPosts,
    ), 200);
}

Tagged : /

Ubuntu HowTo: sudoers can not edit network settings

Original Source Link

I have two users which I have defined as sudoers in /etc/sudoers which looks like this:

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL
bob      ALL=(ALL:ALL) ALL
mary      ALL=(ALL:ALL) ALL
# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

However after entering their password, none of them can change Network Settings to add manual DNS IP addresses. Instead I get this annoying message:

System policy pervents modification of network settings for all users.

enter image description here

I have no difficulty switching to root using sudo su in the terminal.

So how can I fix this?

Tagged : / / /

Making Game: powercfg won’t produce battery report or sleep study

Original Source Link

I’m trying to diagnose a potential issue with my (fully up to date) Surface Pro 6. When I put it to sleep overnight it drops about 15-25% battery.

In my investigation, I wanted to look at both

powercfg /batteryreport
powercfg /sleepstudy

however, when I run these commands from an elevated cmd prompt I get the response

Unable to perform operation.  An unexpected error (0xb7) has occurred:  Cannot create a file when that file already exists. 

while true, battery-report.html, does exist… this doesn’t matter on any other machine – it just overwrites it.

my powercfg works fine, if I run

powercfg /energy

it outputs the expected

Enabling tracing for 60 seconds...
Observing system behavior...
Analyzing trace data...
Analysis complete.

Energy efficiency problems were found.

8 Errors
8 Warnings
42 Informational

See C:WINDOWSsystem32energy-report.html for more details.

This contains a bunch of USB Suspend:USB Device not Entering Selective Suspend reports that I think, are from my Surface Dock. Run it unplugged and they aren’t present.

Regardless, this isn’t the problem I’m trying to solve here.

Update

powercfg /systemsleepdiagnostics = works…

powercfg /systempowerreport = fails (file exists error again)

powercfg /srumutil = fails with…

Error: SruUpdateStats failed
Completed with status 183 (0x000000b7)
Unable to perform operation.  An unexpected error (0x1f) has occurred:  A device attached to the system is not functioning.

Summary

These are broken…

powercfg /batteryreport
powercfg /sleepstudy
powercfg /systempowerreport
powercfg /srumutil

while these are not…

powercfg /energy
powercfg /systemsleepdiagnostics

Tagged : / /

Math Genius: Math Induction proof union and intersections

Original Source Link

I’m totally new to Math Induction. I have a question on using Math Induction proof with union and intersections.

Here’s the initial problem:
Prove that, for if C, D1, D2, …, Dn are n + 1 sets, that

$$Cbigcap(bigcup_{i=1}^nD_i)=bigcup_{i=1}^n(C bigcap D_i)$$

Basis step.

Prove P(1).

$$P(1):C bigcap D_i = C bigcap D_i$$

Induction step

Write out P(k) by replacing “n” with “k” in the original equation.

$$P(k): Cbigcap(bigcup_{i=1}^kD_i)=bigcup_{i=1}^k(C bigcap D_i)$$

Proof

Using the assumption that P(k) is true, add k+1 on the left-hand side and replace “k” with “k+1” to the right-hand side.

$$P(k+1): Cbigcap(bigcup_{i=1}^{k+1}D_i)=C bigcap((bigcup_{i=1}^kD_i)bigcup D_{k+1})$$

RHS (associative properties – change the grouping )

$$=C bigcap(bigcup_{i=1}^kD_i)bigcup D_{k+1})$$

Question: are we just replacing the k with k+1? if so why? or am I totally off?

RHS of P(k+1)

$$=C bigcap(bigcup_{i=1}^{k+1}D_i)$$

We want to prove that:
$$ C cap left( bigcup_{i=1}^{n} D_i right) = bigcup_{i=1}^{n} (C cap D_i) $$

The first step is to prove that it holds for some value of $n$. It is obvious that the equality is verified for $n=1$, so we can proceed. We assume that the equality holds for some $n$, and we prove that this implies that the equation holds for $n+1$. Pay attention to this step: we are proving that, if the equality holds for $n$, then it also holds for $n+1$. Since we know that $n=1$ is true, this will lead us to conclude that $n=2$ holds. But then, $n=3$ holds, and so on. This is how proof by induction works. So we suppose that the equality is verified for some $n$, and we want to prove that this implies:
$$ C cap left( bigcup_{i=1}^{n+1} D_i right) = bigcup_{i=1}^{n+1} (C cap D_i) $$
Note that the LHS can be rewritten as:
$$ C cap left(left( bigcup_{i=1}^{n} D_i right)cup D_{n+1}right) $$
By the distributive law, $A cap (B cup C) = (A cap B) cup (A cap C)$. Thus, we obtain:
$$ C cap left(left( bigcup_{i=1}^{n} D_i right) cup D_{n+1}right) = left(C cap left( bigcup_{i=1}^{n} D_i right)right) cup (C cap D_{n+1}) $$
But, using the inductive assumption, this is the same as:
$$ left( bigcup_{i=1}^{n} (C cap D_i) right) , cup , (C cap D_{n+1}) $$
which is equal to
$$ bigcup_{i=1}^{n+1} (C cap D_i) $$
as we wanted to prove. Thus, the proof by induction is complete.

Tagged :

Code Bug Fix: Logic: Prevent infinite loop when using portals

Original Source Link

In a game that I am currently working on, there are portals, which are linked in pairs of two. Whenever the player enters a portal, it should be teleported to the other portal that is linked to the portal that they just entered. The problem is, that once it is teleported over, the other portal see’s that the player is collding with it, and will teleport it back to the first, which will send it back and so on. The code for this porject is large and over many files, but here is the most important:

(Javascript, ignore the frame and pause vaibles, those are for animation)


export class Portal extends gameObject{
    constructor(x, y, size, id){
        super(x, y, size);
        this.currentFrame = 0;//updated when (below) > (2 below)
        this.countingFrame =0;//update every time;
        this.pause = 3;//frames between frames
        this.id = id;
        this.justVisited = false;
    }
    update(player, portals){
        if(this.countingFrame >= this.pause){
            this.currentFrame = (this.currentFrame + 1) % 4;
            this.countingFrame = 0;
        }else{
            this.countingFrame ++;
        }
        if(super.checkPlayerCollision(player)){
            this.justVisited = true;
            for(let i in portals){
                if(this.id === portals[i].id && portals[i] !== this && !portals[i].justVisited){
                    player.x = portals[i].x;
                    player.y = portals[i].y;
                }
            }
        }else{
            for(let i in portals){
                if(this.id === portals[i].id && portals[i] !== this && portals[i].justVisited){
                    this.justVisited = false;
                }
            }
        }
    }
    render(canvas, spritesheet){
        super.render(canvas, spritesheet, this.currentFrame , 26);
    }
}

This is one attempt at patching it up, but it still failed. How can I make it so that the player goes throught the first one as soon as it collides, comes out the second, and won’t retrun to the first untill the player moves off and then back on?

EDIT:After a little bit of seaching, the answer that was most often given to this question was “Move the player outside the reach of the second portal when it teleports over there“. This will not work in my case, because when the player updates, his position changes with respect to the amount of time seince the last frame. In a perfet world, that would be ok, but because it is not perfect, the player cannot reliably be on a single point. Also, it would look weird if I moved it out of the hitbox entirely, so that doesn’t work either.

This keeps the portal from fireing untill the player has stepped off both of the linked portals

class Portal extends gameObject{
    constructor(x, y, size, id){
        super(x, y, size);
        this.currentFrame = 0;//updated when (below) > (2 below)
        this.countingFrame =0;//update every time;
        this.pause = 6;//frames between frames
        this.id = id;
        this.playerMoveOff = true;
        this.other = null;   
    }
    findOther(portals){
        for(let portal of portals){
            if(portal.id === this.id && portal !== this){
                this.other = portal;
            }
        }
    }
    update(player){
        if(this.countingFrame >= this.pause){
            this.currentFrame = (this.currentFrame + 1) % 4;
            this.countingFrame = 0;
        }else{
            this.countingFrame ++;
        }
        if(super.checkPlayerCollision(player)){
            if(this.other.playerMoveOff && this.playerMoveOff){
                player.x = this.other.x;
                player.y = this.other.y;
            }
            this.playerMoveOff = false;
        }else{
            this.playerMoveOff = true;
        }
    }
    render(canvas, spritesheet){
        super.render(canvas, spritesheet, this.currentFrame , 26);
    }
}

class Portal extends gameObject{
    constructor(x, y, size, id){
        super(x, y, size);
        this.currentFrame = 0;//updated when (below) > (2 below)
        this.countingFrame =0;//update every time;
        this.pause = 6;//frames between frames
        this.id = id;
        this.playerMoveOff = true;
        this.other = null;   
    }
    findOther(portals){
        for(let portal of portals){
            if(portal.id === this.id && portal !== this){
                this.other = portal;
            }
        }
    }
    update(player){
        if(this.countingFrame >= this.pause){
            this.currentFrame = (this.currentFrame + 1) % 4;
            this.countingFrame = 0;
        }else{
            this.countingFrame ++;
        }
        if(super.checkPlayerCollision(player)){
            if(this.other.playerMoveOff && this.playerMoveOff){
                player.x = this.other.x;
                player.y = this.other.y;
            }
            this.playerMoveOff = false;
        }else{
            this.playerMoveOff = true;
        }
    }
    render(canvas, spritesheet){
        super.render(canvas, spritesheet, this.currentFrame , 26);
    }
}

Tagged : /

Ubuntu HowTo: display not working after Ubuntu splash screen

Original Source Link

18.04 on an Asus Z97.

On boot, the monitor works fine and gets as far as displaying the Ubuntu splash screen (Ubuntu plus the dots). After that the display loses the signal. I have vino running and remote desktop works fine.

I’ve tried both HDMI and DVI, and both an Elecrow 1080p and an old Viewsonic monitor. Every time, the signal is lost at the same point. I’ve tried various screen resolutions but no difference.

From the remote desktop, display settings shows ‘unknown monitor’.

I’m running gdm3 as I was never able to get lightdm running on this system. I just tried it again and it fails to create a display so I can’t even get a remote desktop. I can still log in with putty though.

I tried some of the solutions here: External monitor not detected on Ubuntu 18.04 but no luck.

With gdm3:

xrandr: Failed to get size of gamma for output default
Screen 0: minimum 320 x 240, current 1600 x 1200, maximum 1920 x 1200
default connected primary 1600×1200+0+0 0mm x 0mm
1600×1200 60.00* 70.00 65.00
1920×1200 60.00
1920×1080 60.00
1680×1050 70.00 60.00
1400×1050 70.00 60.00
1600×900 60.00
1280×1024 60.00
1440×900 60.00
1400×900 60.00
1280×960 60.00
1440×810 60.00
1368×768 60.00
1360×768 60.00
1280×800 60.00
1152×864 70.00 60.00
1280×720 60.00
1024×768 70.00 60.00
960×720 60.00
928×696 60.00
896×672 60.00
1024×576 60.00
960×600 60.00
960×540 60.00
800×600 70.00 65.00 60.00 56.00
840×525 70.00 60.00
700×525 70.00 60.00
800×450 60.00
640×512 60.00
720×450 60.00
700×450 60.00
640×480 60.00
684×384 60.00
680×384 60.00
640×400 60.00
576×432 70.00 60.00
640×360 60.00
512×384 70.00 60.00
512×288 60.00
480×270 60.00
400×300 60.00 56.00
320×240 60.00

I have a couple of other linux systems where everything just works so I’m thinking this is a driver issue but I have no idea what to do about it.

Any ideas?

Rob.

In the recovery terminal, or if you can connect remotely, try adding nomodeset to your grub configuration:

sudo sed -i "s|quiet splash|quiet nomodeset splash|g" /usr/share/grub/default/grub
sudo update-grub

This will change the line in /usr/share/grub/default/grub

From…

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

To…

GRUB_CMDLINE_LINUX_DEFAULT="quiet nomodeset splash"

This instructs the kernel to not load video drivers and use BIOS modes instead until X is loaded.

Tagged : /

Math Genius: Area between two curves with respect to y

Original Source Link

enter image description here

Let $x_1$ be the red curve and $x_2$ be the blue curve. I’ve tried integrating $x_1-x_2$ as well as $x_2-x_1$ from $y=0$ to $y=9/2$ and both answers were marked wrong.

What do I do here? I’m thinking it might be better to integrate with respect to $x$ and break it down into intervals, but I’m not sure how to go about doing this.

In that region, the smallest $y$-coordinate of a point is $0$ (occuring at the point $(0,0)$) and the greatest $x$-coordinate is $frac92$ (occuring at the point $left(-frac{27}4,frac92right)$).

So, you should consider the integral$$int_0^{9/2}(3y-y^2)-(y^2-6y),mathrm dy=int_0^{9/2}9y-2y^2,mathrm dy=frac{243}8.$$

Tagged : /

Code Bug Fix: Trigger different events in JQuery based on if condition in html in Flask

Original Source Link

I have developed a Flask website, which I need to trigger different alert messages depending on customers’ salary after clicking on a button. I am doing the if statement inside the HTML using the Jinja2 template and according to condition triggers the id and then use this id to trigger an event using JQuery. I believe I am doing something wrong since nothing is happening after I click on the button.

Following is part of my code:

    <div>   
        {% if ((current_user.salary)>=2000 and (current_user.salary) <=5000)  %}
            <div id="msg0"></div>
        {% endif %}

        {% if ((current_user.salary)>=1000 and (current_user.GPA) <2000)  %}
            <div id="msg1"></div>
        {% endif %}
    </div>

JQuery Code:

  $( document ).ready(function(){
      $("#second").unbind('click').bind( 'click', function() {
    $('#msg0').alert("Your salary is above 2000");
    $('#msg1').alert("You salary is less than 2000");
        });
});

I did not include the code for designing the button since it is irrelevant I can click on the button. However, I do not think what I am doing with ` is correct. Maybe my JQuery code is not correct.

I would appreciate it if anyone can help me.`

Consider the following code.

$(function(){
  $("#second").off('click').click(function() {
    if($("#msg0").length){
      alert("Your salary is above 2000");
    }
    if($("#msg1").length){
      alert("You salary is less than 2000");
    }
  }
});

You need to check which of these elements exist in the DOM. To do this, we can check if the jQuery Object has length of 1 or higher.

Tagged : / /