dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test case verifies Docker-based setup and configuration of an OpenSUSE 42.2 environment. It checks Docker availability, creates a repository container, configures host resolution, deploys a test container with network linkage, installs Python-docker-py, and ensures proper cleanup. The test validates container netw... | def test_1142_opensuse(self):
prefix = PREFIX
docker = DOCKER
repo_image = "opensuse-repo:42.2"
box1_image = "opensuse:42.2"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_im... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test case verifies the setup and functionality of an OpenSUSE 42.3 Docker environment by pulling a repository image, configuring a container with host overrides, installing required packages, and cleaning up resources. It checks Docker availability, image existence, container lifecycle management, repository confi... | def test_1143_opensuse(self):
prefix = PREFIX
docker = DOCKER
repo_image = "opensuse-repo:42.3"
box1_image = "opensuse:42.3"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_im... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test verifies OpenSUSE Leap 15.0 Docker image functionality by: 1) Checking Docker availability and required images 2) Creating a repo container and obtaining its IP 3) Configuring host aliases 4) Testing package installation in a container 5) Ensuring proper cleanup. It validates container operations, network con... | def test_1150_opensuse(self):
prefix = PREFIX
docker = DOCKER
repo_image = "opensuse-repo:15.0"
box1_image = "opensuse/leap:15.0"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + re... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test case verifies Docker-based OpenSUSE environment setup by launching a repository container, configuring a client container with host overrides, modifying repository configurations, installing packages, and cleaning up resources. It ensures proper network connectivity, repository operations, and package managem... | def test_1151_opensuse(self):
prefix = PREFIX
docker = DOCKER
repo_image = "opensuse-repo:15.1"
box1_image = "opensuse/leap:15.1"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + re... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test case sets up Docker containers to verify OpenSUSE Leap 15.2 repository functionality. It creates a repository container, configures a test container with the repo's IP, installs python-docker-py, and cleans up resources. The test ensures proper package installation and network configuration in a Dockerized Op... | def test_1152_opensuse(self):
prefix = PREFIX
docker = DOCKER
repo_image = "opensuse-repo:15.2"
box1_image = "opensuse/leap:15.2"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + re... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test case verifies the setup and functionality of OpenSUSE-based Docker containers. It creates a repository container, configures a client container with mirrored repository access, tests zypper repository refresh, and installs python-docker-py without GPG checks, ensuring proper container orchestration and packag... | def test_1252_opensuse(self):
prefix = PREFIX
docker = DOCKER
repo_image = "opensuse-repo:15.2"
box1_image = "opensuse/leap:15.2"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + re... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test creates and configures Docker containers to verify Ubuntu 14.04 image functionality with a custom mirror. It sets up a repository container, configures a client container with host overrides, installs Apache, and validates operations while ensuring cleanup. The main task is testing Ubuntu 14.04 Docker image b... | def test_1404_ubuntu(self):
prefix = PREFIX
docker = DOCKER
repo_image = "ubuntu-repo:14.04"
box1_image = "ubuntu:14.04"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_image)... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test case verifies that an Ubuntu 16.04 Docker container can successfully install packages using a locally hosted repository mirror. It creates a repository container, configures a test container to use this mirror, installs Apache2, and ensures the environment is cleaned up afterward. The test confirms proper Doc... | def test_1604_ubuntu(self):
prefix = PREFIX
docker = DOCKER
repo_image = "ubuntu-repo:16.04"
box1_image = "ubuntu:16.04"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_image)... |
def image_exists(prefix, name):
docker = DOCKER
name = name.strip()
if prefix:
proc = runs("{docker} inspect {prefix}/{name}".format(**locals()))
else:
proc = runs("{docker} inspect {name}".format(**locals()))
if proc.rc:
logg.debug("%s not found: rc=%i\n\t%s", name, proc.rc,... | This test case verifies Ubuntu 18.04 Docker image functionality by creating a local repository container, configuring a test container with host overrides for Ubuntu mirrors, updating packages, installing apache2, and cleaning up. It ensures proper Docker setup, repository access, and package installation in isolated c... | def test_1804_ubuntu(self):
prefix = PREFIX
docker = DOCKER
repo_image = "ubuntu-repo:18.04"
box1_image = "ubuntu:18.04"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
if not image_exists(prefix, repo_image): self.skipTest("have no " + repo_image)... |
def centos_sync() -> None:
centos = CENTOS
centos_dir()
subdirs: Dict[str, List[str]] = OrderedDict()
if centos.startswith("6"):
subdirs = SUBDIRS6
if centos.startswith("7"):
subdirs = SUBDIRS7
if centos.startswith("8"):
subdirs = SUBDIRS8
for base in subdirs:
... | The function `centos_make()` executes a sequence of CentOS-related operations, including synchronizing repositories, pulling packages, configuring the repository, running tests, performing checks, and managing tags to streamline CentOS system maintenance or deployment tasks. | def centos_make() -> None:
centos_sync()
centos_pull()
centos_repo()
centos_test()
centos_check()
centos_tags() |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies Docker operations on a CentOS 7.3.1611 image by checking container lifecycle management, package installation (python-docker-py), and network configuration (add-hosts). It ensures the Docker environment is functional, skips if prerequisites fail, and executes cleanup steps after testing. | def test_2073_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:7.3.1611"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies Docker mirror functionality with CentOS 7.4.1708 by: 1) Checking Docker socket availability 2) Validating repository image existence 3) Creating/test-running a container with --add-hosts 4) Installing python-docker-py package 5) Cleaning up containers. It ensures proper mirroring operations and ... | def test_2074_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:7.4.1708"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test function verifies Docker operations on CentOS 7.5.1804 by checking Docker availability, pulling the image, starting a container with host additions, installing python-docker-py, and cleaning up resources. It ensures proper Docker functionality, image existence, and package installation within the containerize... | def test_2075_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:7.5.1804"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test function verifies Docker operations on a CentOS 7.6.1810 image by checking repository existence, creating/destroying containers, adding host configurations, installing packages, and ensuring proper cleanup. It skips tests if prerequisites fail, uses a custom mirror, and validates container lifecycle managemen... | def test_2076_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:7.6.1810"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies Docker operations on a CentOS 7.7.1908 image, including container creation, package installation (python-docker-py), and cleanup. It checks for Docker availability, image existence, and executes commands to start/stop containers while testing network configuration with --add-hosts parameters. | def test_2077_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:7.7.1908"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies Docker operations on a CentOS 8.0.1905 image using a custom mirror. It checks Docker availability, ensures the image exists, creates and configures a container with host additions, installs python2-numpy, and validates container lifecycle management (start/stop). The test confirms proper executi... | def test_2080_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:8.0.1905"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies Docker image operations on CentOS 8.1.1911 by checking image existence, launching containers with host additions, installing packages (python2-numpy), and cleaning up resources. It ensures proper Docker functionality, repository access, and package management in a CentOS environment. | def test_2081_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:8.1.1911"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies the functionality of a CentOS Docker image (8.3.2011) by checking image existence, launching a container with host additions, installing python2-numpy, and ensuring proper cleanup. It skips tests if Docker is unavailable or the image is missing, confirming container lifecycle management and pack... | def test_2083_centos(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:8.3.2011"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | The code tests Docker operations with OpenSUSE 42.2 by checking Docker availability, verifying image existence, creating/removing containers, adding host configurations, installing Python-docker-py, and stopping containers. It validates Docker image management, container execution, and package installation workflows in... | def test_2142_opensuse(self):
docker = DOCKER
mirror = _docker_mirror
image = "opensuse:42.2"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies the functionality of using a custom Docker mirror with an OpenSUSE 42.3 image. It checks Docker availability, ensures the image exists, sets up a container with host additions, installs Python-docker-py via zypper, and cleans up resources. The test specifically validates mirror configuration, co... | def test_2143_opensuse(self):
docker = DOCKER
mirror = _docker_mirror
image = "opensuse:42.3"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipT... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies the functionality of an OpenSUSE Leap 15.0 Docker image by pulling it via a mirror, launching a container with host additions, installing python-docker-py, and ensuring proper execution and cleanup. It checks Docker socket availability, image existence, container lifecycle management, and packag... | def test_2150_opensuse(self):
docker = DOCKER
mirror = _docker_mirror
image = "opensuse/leap:15.0"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test function verifies the setup and configuration of an OpenSUSE Leap 15.1 Docker image using a mirror tool. It checks Docker environment readiness, initializes a container with specific host additions, installs required packages (python, python-xml), updates repositories, and ensures proper cleanup by stopping t... | def test_2151_opensuse(self):
docker = DOCKER
mirror = _docker_mirror
image = "opensuse/leap:15.1"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | The code tests Docker operations on OpenSUSE by starting a container, installing Python packages, and verifying setup with mirror commands. It checks Docker availability, image existence, runs container commands, installs dependencies, and cleans up resources. | def test_2152_opensuse(self):
docker = DOCKER
mirror = _docker_mirror
image = "opensuse/leap:15.2"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test script verifies Docker operations with a custom mirror by launching an Ubuntu 14.04 container, installing Apache2, and validating execution. It checks Docker availability, ensures the image exists, creates and configures a container, executes package updates/installation, then cleans up resources. The test fo... | def test_2404_ubuntu(self):
docker = DOCKER
mirror = _docker_mirror
image = "ubuntu:14.04"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipTest... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies the installation and execution of Apache2 in a Docker container using a custom mirror. It checks Docker availability, ensures the Ubuntu 16.04 image exists, creates and configures a container with host additions, installs Apache2, and cleans up resources. The test confirms proper setup and funct... | def test_2604_ubuntu(self):
docker = DOCKER
mirror = _docker_mirror
image = "ubuntu:16.04"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipTest... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test verifies Docker setup with Ubuntu 18.04 by pulling the image, creating a container with host additions, installing Apache2, and cleaning up. It checks Docker availability, image existence, and executes container operations to ensure proper functionality and cleanup. | def test_2804_ubuntu(self):
docker = DOCKER
mirror = _docker_mirror
image = "ubuntu:18.04"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.skipTest... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test case verifies the functionality of adding EPEL repositories and host configurations to a CentOS 7.7 Docker image using a mirror tool. It creates a container, installs epel-release, disables SSL verification in yum, installs Python Flask, and ensures the setup works correctly before cleaning up resources. | def test_3077_centos_epel(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:7.7.1908"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test verifies the functionality of adding and using the EPEL repository on a CentOS 7.9 Docker image. It checks if the mirror tool correctly configures repos, starts containers with EPEL support, installs epel-release, disables SSL verification, and installs Python 3.6 Flask. The test ensures proper Docker contain... | def test_3079_centos_epel(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:7.9.2009"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test function verifies the setup and functionality of a CentOS 8.1.1911 Docker image with EPEL repository integration. It checks Docker availability, initializes a test container with EPEL, installs epel-release, disables YUM SSL verification, and installs python3-flask-sqlalchemy. Cleanup is performed if KEEP is ... | def test_3081_centos_epel(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:8.1.1911"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.... |
def output(cmd, shell=True):
if isinstance(cmd, string_types):
logg.debug(": %s", cmd)
else:
logg.debug(": %s", " ".join(["'%s'" % item for item in cmd]))
run = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE)
out, err = run.communicate()
return decodes(out)
def image_e... | This test function verifies the installation and configuration of the EPEL repository in a CentOS 8.3.2011 Docker container. It starts a container, adds hosts, installs EPEL-release, disables SSL verification, and installs python3-flask-sqlalchemy to validate package availability. Cleanup is performed if KEEP is false. | def test_3083_centos_epel(self):
docker = DOCKER
mirror = _docker_mirror
image = "centos:8.3.2011"
if not os.path.exists(DOCKER_SOCKET): self.skipTest("docker-base test")
repo_image = output("{mirror} repo {image}".format(**locals()))
if not image_exist(repo_image): self.... |
def centos_epeldir() -> None:
centos = CENTOS
epel = major(centos)
dirname = "epel.{epel}".format(**locals())
if path.isdir(dirname):
if path.islink(dirname):
os.unlink(dirname)
else:
shutil.rmtree(dirname) # local dir
# we want to put the mirror data on an e... | The main task of the code is to configure and manage the EPEL (Extra Packages for Enterprise Linux) repository on a CentOS system by creating necessary directories, synchronizing package data, and setting up repository configurations. | def centos_epel() -> None:
centos_epeldir()
centos_epelsync()
centos_epelrepo() |
def shuffle(self, x, y):
n = x.shape[0]
order = np.arange(n)
np.random.shuffle(order)
x[:] = x[order]
y[:] = y[order]
def nextEpoch(self, x, y):
self.loss, self.acc = 0, 0
self.shuffle(x, y)
n = x.shape[0]
for i in range(n//self.batchSize):
... | The code trains a neural network model by splitting input data into training and validation sets, iterating over specified epochs, and optimizing model parameters using batches. It configures hyperparameters (learning rate, weight decay), shuffles data, trains on the training set, evaluates loss/accuracy during trainin... | def train(self, x, y, numberOfEpochs=100, batchSize=16, learning_rate=1e-3, weight_decay=1e-4):
self.batchSize = batchSize
self.learning_rate = learning_rate
self.weight_decay = weight_decay
self.shuffle(x, y)
n = x.shape[0]
m = 4*n//5
self.x_train = x[:m]
... |
def calculateTime(data, query_loc, query_param):
#calculates the total time spent at a specified location (query_loc)
#returns the total time in hours spent in query_loc,
#a list of the time spent at the specified location in each visit,
#and a dictionary of the total time spent at each location
'''this func... | The code analyzes location and activity data from JSON files for a specified year and location. It calculates total hours spent in a given location (or custom coordinates) and a specific activity across each month, aggregates results into a dataframe, generates visualizations, and outputs monthly and yearly totals. It ... | def runAnalysis(DIR, YEAR, location, LATITUDE, LONGITUDE, RADIUS, ACTIVITY):
#function that runs the analysis for a given location
months = ['JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER']
total_hours_location = 0
total_hours_activity = 0
calend... |
def get_soup(val):
#Sleep is required so our robot doesnt rush ahead too fast and get shot down by wikipedia
time.sleep(0.0055)
#Get the value and send user-agent header, pretending like we are making a relevant request from a machine
html = requests.get(val, headers={'User-Agent': 'Mozilla/5.0 (Windows... | The code extracts name data from a list of URLs, processes each page to identify names and their origins, handles pagination by recursively fetching subsequent pages, and organizes the collected names into a dictionary grouped by gender. It ensures no duplicate entries for origins and updates the provided return dictio... | def get_name_values(gender_arg, list_arg, return_dict):
name_data = {"name_values": {}}
for val in list_arg:
soup = get_soup(val)
# print(f.split(":", 1)[-1])
#TODO: Refactor me to look nicer
origin = re.findall(r"^(.*?)_", val.lower().replace("old_", "").replace("h... |
def exit_sbs(message=constants.MENU_EXIT_MSG):
"""Exit with message and close database connection.
Keyword arguments:
message -- string to exit with as message (default MENU_EXIT_MSG)
"""
db.disconnect()
sys.exit(message)
def add_income(card):
"""Add income to own card.
Arg... | The function processes a selected menu option for a logged-in user, executing actions like retrieving balance, adding income, transferring funds, closing the card, or logging out. It updates the card ID to -1 upon logout or card closure and returns the updated card ID or -1 if the user is a guest. | def logged_in_menu(selected, card_id):
"""Try and access selected option in the logged in menu (see logged_in_options list).
Arguments:
selected -- valid integer matching an option from logged_in_options list
card_id -- card id or -1 if guest
Returns:
The card id or -1 if guest
... |
def set_ain(self):
"""Set account identifier number (7th to 15th card number digit)."""
ain_len = self.card_number_len - len(self.mii) - len(self.iin) - 1 # len(self.checksum)
self.ain = (str(random.randint(0, pow(10, ain_len) - 1))).zfill(ain_len)
def set_checksum(self):
"""Set card che... | This code initializes a card-related object, generating or setting attributes like MII, IIN, checksum, AIN, PIN, and balance. If no data is provided, it creates these components using set methods; if data is given, it populates attributes directly from the input tuple. The main task is to either generate a synthetic ca... | def __init__(self, mii=4, iin="00000", card_number_len=16, checksum_type="any", data=()):
if not data:
self.mii = str(mii)
self.iin = str(iin)
self.checksum = ""
self.checksum_type = checksum_type
self.card_number_len = card_number_len
self... |
def set_ain(self):
"""Set account identifier number (7th to 15th card number digit)."""
ain_len = self.card_number_len - len(self.mii) - len(self.iin) - 1 # len(self.checksum)
self.ain = (str(random.randint(0, pow(10, ain_len) - 1))).zfill(ain_len)
def luhn_algo(self):
# multiply even-in... | This code initializes a credit card object by setting parameters like MII, IIN, checksum type, and card length. It generates a valid card number using the Luhn algorithm, assigns a PIN, and initializes a balance. The main task is creating a structured credit card data model with standardized formatting and validation r... | def __init__(self, mii=4, iin="00000", card_number_len=16, checksum_type="any"):
self.mii = str(mii)
self.iin = str(iin)
self.checksum_type = checksum_type
self.card_number_len = card_number_len
self.set_ain()
self.luhn_algo()
self.set_number()
self.set_pi... |
def _create_dir(directory):
"""Create directory."""
if not os.path.exists(directory):
os.makedirs(directory)
def _setup():
"""Setup parser if executed script directly."""
parser = argparse.ArgumentParser(description='Quack builder')
parser.add_argument(
'-y', '--yaml', help='Provide ... | The main task of the code is to initialize and execute a task workflow by setting up configuration directories, loading or prompting for configuration data, selecting a profile, and running tasks while reporting completion statistics. It handles default profile setup, config validation, and dependency tracking, ultimat... | def main():
"""Entry point."""
global _ARGS
_create_dir('.quack')
if _ARGS is None:
_ARGS = _setup()
config = _get_config()
if not config:
config = _prompt_to_create()
if not config:
return
if not _ARGS.profile:
_ARGS.profile = 'init'
profile =... |
def get_t(self, steps=None):
if steps is None:
steps = self.out_steps
return torch.linspace(0., 4 * np.pi * steps / self.approx_steps, self.out_steps, requires_grad=False)
def get_initial_params(self, max_amp=5):
return np.concatenate((np.zeros(2), np.ones(2 * self.size), max_amp * n... | The code trains a neural network by first using the COBYLA optimization method to minimize a loss function iteratively until a threshold is met, then switches to Adam optimizer for further training over multiple epochs. It processes batches from a generator, computes loss between model predictions and labels, and updat... | def compile_and_train(self, gen):
train_gen = batch_generator(gen.train, self.batch_size, use_torch=True)
current_loss = None
itr = 0
while current_loss is None or current_loss > self.coef_loss_threshold:
itr += 1
train_batch = next(train_gen)
input_pa... |
def get_content(self, is_labelled: bool) -> str:
inserted_str_pairs = [
(span, self.get_cmd_str_pair(
attr_dict,
label_hex=self.int_to_hex(label + 1) if is_labelled else None
))
for label, (span, attr_dict) in enumerate(self.split_items)
... | The code assigns labels to subobjects based on color-coded labels from a labelled SVG. It aligns original SVG subobjects with labelled SVG elements, maps colors to label indices, and sets labels to -1 if alignment fails or colors are invalid. Unrecognized colors trigger warnings, ensuring only valid labels are applied ... | def generate_mobject(self) -> None:
super().generate_mobject()
labels_count = len(self.labelled_spans)
if not labels_count:
for submob in self.submobjects:
submob.label = -1
return
labelled_content = self.get_content(is_labelled=True)
fil... |
def build_user_projections(self):
for i in self.users.keys():
self.users[i].projections = self.get_user_projections(self.users[i])
def build_similarities(self):
for i in self.users:
self.users[i].similarities = self.get_user_similarities(self.users[i])
def build_recommendations(s... | The code's main task is to calculate user projections, compute similarities between users, and generate personalized recommendations using collaborative filtering techniques. | def calculate(self):
self.build_user_projections()
self.build_similarities()
self.build_recommendations() |
def GetEnd(dict):
nodelist = NodeList(dict)
indegree = InDegreeCount(dict)
outdegree = OutDegreeCount(dict)
for node in nodelist:
if node not in outdegree.keys() or indegree[node] > outdegree[node]:
return node
def GetStart(dict):
nodelist = NodeList(dict)
indegree = InDegree... | The function `EulerianPath` constructs an Eulerian path in a directed graph. It first identifies the start and end nodes, adds a dummy edge from end to start, then finds an Eulerian cycle using `EulerianCycle`. It locates the split point where the dummy edge appears in the cycle and rearranges the cycle to form the pat... | def EulerianPath(edge_dict):
# get starting, ending node
end_node = GetEnd(edge_dict)
start_node = GetStart(edge_dict)
if end_node in edge_dict:
edge_dict[end_node].append(start_node)
else:
edge_dict[end_node] = [start_node]
cycle = EulerianCycle(edge_dict)
n = len(cycle)
... |
def GetEnd(dict):
nodelist = NodeList(dict)
indegree = InDegreeCount(dict)
outdegree = OutDegreeCount(dict)
for node in nodelist:
if node not in outdegree.keys() or indegree[node] > outdegree[node]:
return node
def GetStart(dict):
nodelist = NodeList(dict)
indegree = InDegree... | The function finds an Eulerian path in a directed graph by modifying the graph to create a cycle, then reassembling the path by splitting the cycle at the connection between the original end and start nodes. | def EulerianPath(edge_dict):
# get starting, ending node
end_node = GetEnd(edge_dict)
start_node = GetStart(edge_dict)
if end_node in edge_dict:
edge_dict[end_node].append(start_node)
else:
edge_dict[end_node] = [start_node]
cycle = EulerianCycle(edge_dict)
n = len(cycle)
... |
def GetEnd(dict):
nodelist = NodeList(dict)
indegree = InDegreeCount(dict)
outdegree = OutDegreeCount(dict)
for node in nodelist:
if node not in outdegree.keys() or indegree[node] > outdegree[node]:
return node
def GetStart(dict):
nodelist = NodeList(dict)
indegree = InDegree... | The function finds an Eulerian path in a directed graph by first augmenting the graph with an edge from the end node to the start node, then computing an Eulerian cycle. It identifies the split point in the cycle where the added edge appears and reorders the cycle to form a path from the original start node to the orig... | def EulerianPath(edge_dict):
# get starting, ending node
end_node = GetEnd(edge_dict)
start_node = GetStart(edge_dict)
if end_node in edge_dict:
edge_dict[end_node].append(start_node)
else:
edge_dict[end_node] = [start_node]
cycle = EulerianCycle(edge_dict)
n = len(cycle)
... |
def DeBrujin(Patterns):
nodes = []
for Kmer in Patterns:
nodes.append(Prefix(Kmer))
nodes.sort()
adjDic = {}
for node in nodes:
dummylist = []
for Kmer in Patterns:
prefix = Prefix(Kmer)
if node == prefix:
dummylist.append(Suffix(Kmer))... | The main task of the code is to reconstruct a string from a set of overlapping substrings (Patterns) by constructing a De Bruijn graph, finding an Eulerian path in the graph, and converting the path into a genome sequence. This process assembles the original string by aligning the substrings in the correct order. | def StringReconstruction(Patterns):
dB = DeBrujin(Patterns)
path = EulerianPath(dB)
text = PathToGenome(path)
return text |
def _get_zones_for(self, today):
return [zone for zone in Zone.select() if zone.is_enabled and zone.should_run_on(today)]
def _get_spray_zones(self, zones):
return [zone for zone in zones if zone.is_spray()]
def _get_drip_zones(self, zones):
return [zone for zone in zones if zone.is_drip()]
def _get_multi_z... | This code schedules irrigation for different zones (spray, drip, multi) based on predefined start times and calculated durations, adjusting for smart scheduling (e.g., sunrise). It logs details, schedules watering intervals, and sends a Slack message listing pending tasks with zone-specific info like names, valves, tim... | def schedule(self, now=None, smartSchedule=True):
if not now:
now = self.utility.now()
today = now
logger.info(f'Scheduling for {today.date()}')
first_start_time = today.replace(hour=1,minute=0,second=0,microsecond=0)
multi_start_times = [
today.replace(hour=10,minute=0,second... |
def print_hashes_if_archived(args):
archived = get_archived_version(args.ipath)
if archived:
if args.verbose:
print(f'"{green(args.ipath)}" is already archived as "{green(archived.path)}".\n')
print_hashes(args.ipath, archived.path)
def make_current_archive_item(args):
# return ArchiveItem.current(args.ipath ... | This function archives a file by copying its contents to a specified path. If the target file exists, it either overwrites it (with --force) or displays a diff between the files. If the target doesn't exist, it creates a new archive. The operation checks for existing archives and handles conflicts via force flag or dif... | def archive_current(args):
if print_hashes_if_archived(args):
return
cur = make_current_archive_item(args)
if cur.exists:
if args.force:
print(f'Overwriting "{cur.path}" with contents of "{args.ipath}"')
shutil.copy(args.ipath, cur.path)
else:
print(f'Target at "{cur.path}" exists. Use --force to ove... |
def make_current_archive_item(args):
# return ArchiveItem.current(args.ipath if args.mtime else None)
if args.mtime:
# Return last-modified-time-based target path.
return ArchiveItem.current(args.ipath)
else:
# Return now-time-based target path.
return ArchiveItem.current(None)
def get_quickdiff(apath, bpat... | This function checks if the target archive path is occupied. If so, it warns that archiving would fail without --force, displays a diff between existing content and the new archive, and suggests reviewing the diff. If the path is free, it confirms successful archiving. Verbose mode adds hash details. | def print_dry_run_info(args):
cur = make_current_archive_item(args)
qdiff = get_quickdiff(args.ipath, cur.path, colorize = not args.plain)
if cur.exists:
print(f'''Attempting to archive without the --force flag would fail because the
default target path "{cur.path}" for the current blog page
is occupied already.
... |
def parse_args(args = sys.argv[1:]):
notes = '''QUERY is either of the form [[Y-]M-]D or D[.M[.Y]] or M/D[/Y],
or it is a negative integer, -1 being the most recently archived page, etc.
The special value -0 (or just 0) will print the oldest archived page.
The special value # will print the number of archived pa... | The main task of the code is to parse command-line arguments and execute corresponding functions based on flags like `colors`, `backref`, `diff`, `archive`, `new`, `explain`, `extant`, or `list`. If no valid flag is provided, it defaults to displaying dry-run information. The code acts as a dispatcher for a CLI tool, h... | def main(args = sys.argv[1:]):
parser, args = parse_args(args)
if args.colors: print_colors()
elif args.backref: print_backref(args)
elif args.diff: print_diff_last_archived(args)
elif args.archive: archive_current(args)
elif args.new: make_brand_new(args)
elif args.explain or args.extant: explain(args)
... |
def get_w_to_mw():
res = {}
with open('mw-w-ig-vn.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
res[row[1]] = row[0]
return res
def get_mw_infos(data):
# todo: handle cases like "8189165275, 9788189165277" which are isbn10, isbn13 of same isbn
... | The main task of the code is to process a database of identifiers (e.g., ISBNs, ISSNs) from YAML and CSV files, categorize them into monovolumes and multivolumes based on compatibility checks, and generate structured CSV outputs for analysis. It loads configuration data, reviews existing ISBNs, analyzes identifier mapp... | def main():
db = None
with open("db.yml", 'r') as stream:
db = yaml.load(stream, Loader=yaml_loader)
w_to_mw = get_w_to_mw()
existing_isbns = {}
get_mw_infos(existing_isbns)
reviewed_db = {}
add_csv(reviewed_db, "reviewed_files/ISBN review step 1 - Karma-malformed (to review).csv", [... |
def well_formed(isbn):
# assumes isbn is normalized
match = re.search(r'^(\d{9}[0-9X]|\d{13})$', isbn)
return True if match else False
def addqm(isbn):
if looksgood(isbn):
return isbn
else:
return isbn+"?"
def equivalent(isbn1, isbn2):
if isbn1 is None and isbn2 is None:
... | The function compares ISBNs from a database and scans for each "mw" entry, tracking discrepancies. It updates statistics on mismatches and categorizes differences into lists (e.g., malformed ISBNs, equivalent ISBNs) for further processing. It checks if single entries are malformed or equivalent, appending them to speci... | def handle_differences(data, stats):
for mw, mw_data in data["mw_info"].items():
from_db_not_in_scans = set(mw_data["from_db"]) - set(mw_data["from_scans"])
stats["in_db_not_in_scans"] += len(from_db_not_in_scans)
from_scans_not_in_db = set(mw_data["from_scans"]) - set(mw_data["from_db"])
... |
def equivalent(isbn1, isbn2):
if isbn1 is None and isbn2 is None:
return True
if isbn1 is None or isbn2 is None:
return False
if len(isbn1) == len(isbn2):
return isbn1 == isbn2
if len(isbn1) not in [10, 13] or len(isbn2) not in [10, 13]:
return isbn1 == isbn2
if len(i... | The code processes multivolume works by comparing ISBNs from database records and scanned data. It categorizes entries into 'new_isbns', 'proposed_substitutions', or review lists based on volume completeness and ISBN consistency, updating statistics for tracking found/missing volumes and discrepancies. | def handle_multivolumes(data, stats):
for mw, mwinfo in data["mw_info"].items():
if len(mwinfo["ig_to_vnum"]) < 2 or len(mwinfo["per_ig"]) == 0:
continue
ordered_igs = sorted(mwinfo["ig_to_vnum"].keys(), key=lambda x: mwinfo["ig_to_vnum"][x])
all_isbns = []
for ig, isbn_l... |
def get_w_to_mw():
res = {}
with open('mw-w-ig-vn.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
res[row[1]] = row[0]
return res
def get_mw_infos(data):
# todo: handle cases like "8189165275, 9788189165277" which are isbn10, isbn13 of same isbn
... | The main task of the code is to analyze discrepancies between a database (`db.yml`) and a mapping (`w_to_mw`), tracking statistics like matches, mismatches, and missing entries. It categorizes data into structured formats (e.g., substitutions, malformed entries) and exports results to CSV files for review. The process ... | def main():
db = None
with open("db.yml", 'r') as stream:
db = yaml.load(stream, Loader=yaml_loader)
w_to_mw = get_w_to_mw()
stats = {
"total": 0,
"same_as_db": 0,
"different_from_db": 0,
"not_in_db": 0,
"db_not_found": 0,
"isbn_used_multiple_times... |
def calculation_spring_axis(self, spring1_len, spring2_len, spring3_len, spring1_pos, spring2_pos, spring3_pos, Num_layer):
max_len = max(spring1_len, spring2_len, spring3_len)
min_len = min(spring1_len, spring2_len, spring3_len)
dif_len = max(spring1_len - min_len, spring2_len - min_len, sprin... | The function adjusts the lengths of three springs in a specified layer of a structural model by recalculating their axes using given new lengths. It validates the layer index, computes geometric relationships, updates spring axes in the walls list if feasible, and propagates changes to the layer and upper layers. If th... | def change_inner_layer_len(self, LayerNum, spr1_len, spr2_len, spr3_len):
# layerNum from 0 to Num_layer = int(self.walls.__len__()/6) -1
ToNum_layer = int(self.walls.__len__() / 6)
if LayerNum < 0:
return 0
Num_layer = LayerNum
spring1_pos = self.walls[(Num_layer) *... |
def repete_three(phrase,lang,keyWord,fName=None):
output_1 = False
output_2 = False
keyWord_1 = translate(keyWord[0],lang)
keyWord_2 = translate(keyWord[1],lang)
Connection = CheckingConnectionToGoogle()
if isinstance(Connection,tuple):
Connection = Connection[0]
translator = T... | The code assesses a victim's responsiveness post-accident by checking hearing, understanding, and eye-opening ability. It calculates verbal, eye, and motor response scores, generates a report, and returns scores, report, and conversation logs for medical evaluation. | def eye_opening(lang, name, day, accident, place ):
total = 0
Connection = CheckingConnectionToGoogle()
conversation = ['']
if isinstance(Connection,tuple):
Connection = Connection[0]
e_score = 0
v_score = 0
m_score = 0
report = ''
recieve = repete_three('Hello, I am here... |
def __BuildGraph(self):
GraphCanvas = self.master.nametowidget("graph_canvas")
# Chose Between left and right frame
LeftGraphFrame = GraphCanvas.nametowidget("left_graph_frame")
RightGraphFrame = GraphCanvas.nametowidget("right_graph_frame")
SizeL = len(LeftGraphFrame.winfo_chil... | The main task of the code is to construct the left-side GUI panel, including a "Build Graph!" button to generate visualizations, a "Clear Frame" button to reset graph areas, radio buttons for selecting dice calculation methods (Max/Sum/Min), and labels/instructions for inputting regular and custom dice formats. It orga... | def __BuildLeftSide(self):
# Add Left Frame
LeftFrame = Frame(self.master, height=800, name="left_side_frame")
LeftFrame.grid(row=0, column=0, rowspan=5, sticky="nsew")
# Add Build Graph Button
BuildGraphButton = Button(LeftFrame, text="Build Graph!", command=lambda:self.__Build... |
def Open_Snippet(self):
fileName = self.OpenFile()
# make sure it is valid file
if not fileName:
return
data = self.Bring_Data_From_File(fileName)
self.Snippet_TextBox.setPlainText(data)
def Scan_Snippet(self):
# TODO apply Scanning Algorithm
self.sn... | This code sets up a graphical user interface (GUI) for an application, configuring a main window with text editors for code snippets and tokens, buttons to load/process data, a title label, and menu options for file operations and theme switching. It initializes UI components, connects actions to functions, and applies... | def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 620)
MainWindow.setMinimumSize(QtCore.QSize(800, 620))
MainWindow.setMaximumSize(QtCore.QSize(800, 620))
font = QtGui.QFont()
font.setBold(False)
font.setUnderline(False)
... |
def getSignal(self,ampl, shift, alpha, ph, noiseLevel,mm_cond):
"""
The function takes in a set of parameters and returns a signal with noise
:param ampl: Amplitude of the signal
:param shift: the frequency shift of the signal
:param alpha: the decay rate of the signal
:... | This code tests a signal processing model by generating synthetic signals, applying FFT transformations, and comparing predicted outputs with actual signals. It visualizes results, calculates SNR, and saves plots for analysis, evaluating model performance on signal reconstruction and parameter estimation tasks. | def test_asig(self,shift_t, alpha_t, ph_t, nl):
sns.set_style('white')
id = "test_" + str(shift_t) + "_" + str(alpha_t) + "_" + str(nl)
ampl_t = self.min_c + (self.max_c - self.min_c)/2 + np.multiply(np.random.random(size=(1, 1+self.numOfSig)), (self.max_c - self.max_c))
y_n, y_wn = self... |
def predict_ensembles(self,y_test, mean_= True):
decs = []
encs = []
frl = []
dampl = []
phl = []
sp = torch.nn.Softplus()
for autoencoder in self.autoencoders:
# expect dect, enct, enc, fr, damp, ph,mm_rec,dec
dect, enct, _, fr, damp, ph, ... | The code processes test signals by loading data, predicting outputs using a model, performing FFT analysis, and saving quantified results including amplitude, shift, damping, and phase parameters along with SNR data into a CSV file for further analysis. | def quantify(self):
sns.set_style('white')
path = "quantify/"
Path(self.saving_dir+path).mkdir(exist_ok=True)
data= np.load(self.saving_dir + "test_" + str(self.test_nos)+ ".npz")
y_n, snr, idx = [data[x] for x in data]
y_test_np = y_n.astype('complex64')
y_test =... |
def ppm2f(self, r):
return r * self.trnfreq
def plotppm(self, sig, ppm1, ppm2, rev, linewidth=0.3, linestyle='-'):
p1 = int(self.ppm2p(ppm1, len(sig)))
p2 = int(self.ppm2p(ppm2, len(sig)))
n = p2 - p1
x = np.linspace(int(ppm1), int(ppm2), abs(n))
sig = np.squeeze(sig)
... | The function trains an autoencoder model by processing and plotting magnetic resonance data (if enabled), preparing training data, and iteratively training multiple encoder models using PyTorch Lightning with GPU acceleration. It includes data preprocessing, model training with early stopping and logging, saving traine... | def dotrain(self):
"""
The function trains the autoencoder model.
"""
if self.MM_plot == True:
if 'param' in self.MM_type:
mm = 0
for idx in range(0, self.numOfMM):
if self.MM_conj == True:
x = np.con... |
def ppm2f(self, r):
return r * self.trnfreq
def plotppm(self, sig, ppm1, ppm2, rev, linewidth=0.3, linestyle='-'):
p1 = int(self.ppm2p(ppm1, len(sig)))
p2 = int(self.ppm2p(ppm2, len(sig)))
n = p2 - p1
x = np.linspace(int(ppm1), int(ppm2), abs(n))
sig = np.squeeze(sig)
... | The code performs hyperparameter tuning using Ray Tune's BOHB algorithm to optimize a model's configuration. It defines search spaces for learning rate, batch size, regularization weight, and other parameters, then runs the tuning process with specified schedulers and reporters. The best hyperparameters are identified ... | def tuner(self):
"""
The function takes in the parameters of the model and the data, and then uses the Ray Tune library to find the best
hyperparameters for the model.
The function is called in the main function, and the best hyperparameters are then used to train the model.
T... |
def field_names_class_param(node: NodeType):
return Assign(
targets=[Name(id="field_names", ctx=Store())],
value=ast.List(
elts=[Constant(value=name) for name in (node.fields or dict()).keys()],
ctx=Load(),
),
)
def from_field(name: str, field: FieldSpecification)... | This function generates a Python class definition for a TreeSitter node type. It constructs a `ClassDef` with a dynamically determined name (adding "Bool" for boolean types), inherits from `TreeSitterNode`, and includes field annotations and parameters based on the node's fields and children. The body combines field-sp... | def build_class_for_type(node: NodeType) -> ClassDef:
name = node.type
if camelize(name) in ["True", "False"]:
name += "Bool"
fields = node.fields or dict()
children = node.children
return ClassDef(
name=camelize(name) if node.named else "Token",
bases=[Name(id="TreeSitterNod... |
def is_template(path: Path) -> bool:
return "_template_" in path.name
def compile_all(path: Annotated[Path, typer.Argument(help="Path to directory")]):
for mjml_file in path.rglob("*.mjml"):
if not is_template(mjml_file):
compile_mjml_file(mjml_file)
def compile_mjml_file(path: Path):
te... | The function compiles MJML files. If the input path points to a template, it compiles all templates in the directory; otherwise, it compiles the specific MJML file at the given path. | def compile_mjml(path: Annotated[Path, typer.Argument(help="Path to mjml file", file_okay=True, dir_okay=False)]):
if is_template(path):
print("Template detected, compiling all templates")
compile_all(path.parent)
else:
compile_mjml_file(path) |
def gev_fit_ERA5data(ERA5_filename='ERA5_land_hourly_total_precipitation.csv'):
df = pd.read_csv(ERA5_filename)
# Convert the 'date' column to datetime and set it as the index
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
###compare with Courty's POR:
#comment out t... | The code generates synthetic precipitation data using statistical fitting of historical ERA5 data. It calculates intensity-duration relationships, constructs a hyetograph with alternating blocks, computes cumulative rainfall, and exports the results to a DSS file for hydrological analysis. Key steps include fitting GEV... | def main():
installation = 'Freefall'
data_dir = r'C:\Users\RDCRLCSE\Documents\Python Scripts\PET Expansion'
ERA_data_file = f'ERA5_land_hourly_total_precipitation_{installation}.csv'
duration = 24 #storm duration, hours for selecting overall average storm intensity
T = 100 #return period, yea... |
def exec(cmd, exit_on_err=False):
print("[run_exp.py] executing: " + cmd)
try:
subprocess.run(cmd, shell=True, check=True)
except Exception as e:
print("[run_exp.py] error executing: {}".format(cmd))
print(e)
if exit_on_err:
exit(0)
return 1
return 0
d... | The function compiles and launches compute/storage nodes for a distributed system. It compiles storage nodes (if specified), sets configurations, copies config files via SCP, runs `make clean`, compiles using `compile.sh`, and starts processes on remote nodes via multiprocessing. It also handles local compilation, remo... | def start_nodes(env, job, nodes, storage_nodes, compile_only=True,
is_debug=True):
# compile storage node
if int(job.get("NUM_STORAGE_NODES", 0)) > 0:
exec("cd {}; python3 install.py sync {} {} {}".format(
env["repo"],
env["curr_node"], "100-0", "0-{}".format(int(... |
def generate_args(job):
# generate a list of string format job through a job containing lists
# by iterating all the combinations
args = [""]
for key in job:
new_args = []
if key == "CONFIG":
continue
if isinstance(job[key], list):
for i, x in enumerate(jo... | This code runs multiple experiments by generating configurations, synchronizing code across nodes, executing them in debug/compile/release modes, and collecting results. It iterates through all setup combinations, manages distributed node execution, and processes outputs into CSV/JSON files for analysis. | def test_exp(env, nodes, storage_nodes, job):
# parse commands
exp_name = job["CONFIG"].split('/')[-1].split('.')[0]
# generate config by iterating all the combinations of setups
args = generate_args(job)
# sync codebase
print("[run_exp.py] syncing codebase with all nodes")
if env["num_nod... |
def get_nodes(section_name):
judge_result = is_local_or_get_nodes(section_name)
if judge_result is True:
import socket
# just local (one node)
return [socket.gethostname()]
else:
return judge_result
def _run_for_ping(self, node):
return s(f"ssh -o ConnectTimeout=10 {n... | The code asynchronously pings multiple nodes using a thread pool. If only one node exists, it directly runs the ping operation and sends a message. For multiple nodes, it designates the first as the master, distributes ping tasks to worker nodes via a thread pool, and attaches callbacks to handle results, passing maste... | def ping_async(self):
section = "ping"
nodes = get_nodes(section)
if len(nodes) == 1:
sp_obj = self._run_for_ping(nodes[0])
self._ping_msg(sp_obj, master_=nodes[0])
return
master = nodes[0]
workers = nodes[1:]
len_workers = len(work... |
def extend(self, x_new, x_nearest):
"""
Expands the tree out into the frontier.
"""
X_near = self.near(x_new, self.delta)
self.graph.add_node(x_new, dist(x_nearest, x_new))
self.find_parent(x_new, x_nearest, X_near)
return X_near
def rewire_neighbors(self, x_new, ... | The code implements a path planning algorithm by iteratively sampling points, finding nearest nodes, generating new nodes via steering, rewiring neighbors, and connecting to the goal. It builds a graph up to 300 nodes, optimizing paths through shrinking radius exploration, and returns the computed trajectory from start... | def search(self):
"""
Function to search through the graph.
"""
self.graph.add_node(self.x_init, 0)
while self.graph.num_nodes() <= 300:
r = self.shrinking_ball_radius()
print(r)
x_rand = self.sample_free()
print(x_rand)
... |
def extend(self, x_new, x_nearest):
"""
Expands the tree out into the frontier.
"""
X_near = self.near(x_new, self.delta)
self.graph.add_node(x_new)
self.find_parent(x_new, x_nearest, X_near)
return X_near
def rewire_neighbors(self, x_new, X_near):
"""
... | The code implements a search algorithm to build a path toward a goal within a graph. It iteratively samples random points, finds the nearest node, and creates new nodes by steering toward the sample. If collision-free, it extends the graph, rewires neighbors for optimization, and connects to the goal. The process repea... | def search(self):
"""
Function to search through the graph.
"""
self.graph.add_node(self.x_init)
while self.graph.num_nodes() <= 300:
r = self.shrinking_ball_radius()
x_rand = self.sample_free()
x_nearest = self.nearest(x_rand, r)
x... |
def create_bounding_box(hsv_image, width, height):
'''This function determines the minimum and maximum values in the x-direction from the tool'''
# Setting the minimum value of x to the max possible value, which is the width of the image
x_min = width
# Setting the maximum value of x to the min possibl... | The code automates green pixel masking in images by creating bounding boxes, determining HSV thresholds, and converting green regions within these boxes to black. It processes multiple images from a folder, resizes, saves masks, and displays results live for real-time validation. | def automated_masking(pixel_value):
# Creating list of image names in folder 'images'
image_names = os.listdir('images')
# Looping through tha image_names list
for image_name in image_names:
# Path to the image
image_path = 'images/' + image_name
# Opening the image and getting... |
def _verify_args(self):
if not self._check_makim_file():
self._print_error(
'[EE] CONFIG: Config file .makim.yaml not found.'
)
os._exit(1)
def _change_target(self, target_name: str):
group_name = 'default'
if '.' in target_name:
gr... | This code executes a target command based on provided arguments, performing setup tasks like argument verification and target configuration, checking conditional execution criteria, running dependencies, and finally executing the command if conditions are met. | def run(self, args: dict):
self.args = args
# setup
self._verify_args()
self._change_target(args['target'])
self._load_shell_args()
self._load_target_args()
# commands
if self.target_data.get('if') and not self._verify_target_conditional(
sel... |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def DELTA0(term1,term2):
def neq0(t):
return NOT(EQZ(t,Token("0")))
return AND(DELTA(term1,term2),AND(neq0(ADDRESS(term1)),neq0(ADDRESS(term2))))
def IFF(term1, term2):
return AND(IMPL(term1,term2),IMPL(term2,term1))
def LEQP(term1,term2):
r... | The function Aleq checks if the implication holds: if DELTA0(p,q) is true, then LEQP(p,q) is equivalent to LEQ(OFFSET(p), OFFSET(q)), by returning the logical implication of these conditions. | def Aleq(term):
p = term.slps[1]
q = term.slps[2]
return IMPL(DELTA0(p,q),IFF(LEQP(p,q),LEQ(OFFSET(p),OFFSET(q)))) |
def AND(term1,term2):
return a2("and",term1,term2)
def LT(term1,term2):
return AND(NOT(EQZ(term1,term2)), LEQ(term1,term2))
def ADD(term1,term2):
return a2("+",term1,term2)
def PROD(term1,term2):
return a2("*",term1,term2)
def LEQ(term1,term2):
return a2("<=",term1,term2) | The main task of the code is to check if the sum of term1's slps[2] and the product of a token 's' with term2 lies within the range (0, A], returning true if both conditions (greater than 0 and less than or equal to A) are satisfied. | def RANGEPLUS(term1,term2):
return AND(LT(Token("0"), ADD(term1.slps[2],PROD(Token(s),term2))),LEQ(ADD(term1.slps[2],PROD(Token(s),term2)),Token(A))) |
def AND(term1,term2):
return a2("and",term1,term2)
def LT(term1,term2):
return AND(NOT(EQZ(term1,term2)), LEQ(term1,term2))
def ADD(term1,term2):
return a2("+",term1,term2)
def ADDRESS(term1):
return ADD(BASE(BLOCK(term1)),OFFSET(term1))
def PROD(term1,term2):
return a2("*",term1,term2)
def LEQ(term... | The main task of the code is to generate a logical expression checking if the sum of `term1`'s address and `term2` multiplied by a token `s` lies within a range defined by 0 and token `A`, using `AND` to combine lower and upper bounds. | def RANGE(term1,term2):
return AND(LT(Token("0"), ADD(ADDRESS(term1),PROD(Token(s),term2))),LEQ(ADD(ADDRESS(term1),PROD(Token(s),term2)),Token(A))) |
def EQP(term1,term2):
return a2("=p",term1,term2)
def CREATE(term1,term2):
return a2("Create",term1,term2)
def BLOCK(term1):
return a1("Block",term1)
def ADDRESS(term1):
return ADD(BASE(BLOCK(term1)),OFFSET(term1)) | The code defines a function `Ap` that takes a `term` as input and returns the result of applying the `EQP` function to two arguments: the result of `CREATE(BLOCK(term), ADDRESS(term))` and the original `term`. The main task is to generate a processed output using the `EQP` function by first creating a block and address... | def Ap(term):
return EQP(CREATE(BLOCK(term),ADDRESS(term)),term) |
def AND(term1,term2):
return a2("and",term1,term2)
def LEQ(term1,term2):
return a2("<=",term1,term2)
def ADDRESS(term1):
return ADD(BASE(BLOCK(term1)),OFFSET(term1)) | The function `Ain` checks if the memory address of the input `term` lies within the range [0, A] by combining two conditions using logical AND: the address is greater than or equal to 0 and less than or equal to A. It returns `True` if both conditions are satisfied, indicating the address is valid within the specified ... | def Ain(term):
p = term
return AND(LEQ(Token("0"),ADDRESS(p)),LEQ(ADDRESS(p),Token(A))) |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def AND(term1,term2):
return a2("and",term1,term2)
def LEQ(term1,term2):
return a2("<=",term1,term2)
def EQP(term1,term2):
return a2("=p",term1,term2)
def ADDRESS(term1):
return ADD(BASE(BLOCK(term1)),OFFSET(term1))
def CREATE(term1,term2):
retu... | The code defines a function `Aa` that checks if a value `a` is within the range [0, A] and verifies if the address generated by `CREATE(l, a)` equals `a`, returning the logical implication of these two conditions. | def Aa(term):
l = term.slps[1]
a = term.slps[2]
return IMPL(AND(LEQ(Token("0"),a),LEQ(a,Token(A))),EQP(ADDRESS(CREATE(l,a)),a)) |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def AND(term1,term2):
return a2("and",term1,term2)
def DELTA0(term1,term2):
def neq0(t):
return NOT(EQZ(t,Token("0")))
return AND(DELTA(term1,term2),AND(neq0(ADDRESS(term1)),neq0(ADDRESS(term2))))
def DB(term1,term2):
return EQZ(ALIGN(term1)... | This function computes a logical implication involving operations on terms p and q. It evaluates whether the conjunction of DELTA0 and DB operations on p/q implies an equality between the product of Token(s) and MINP(p,q) and the minimum of OFFSET(p) and OFFSET(q). The core task is to verify a logical relationship usin... | def Amin(term):
p = term.slps[1]
q = term.slps[2]
return IMPL(AND(DELTA0(p,q),DB(p,q)),EQZ(PROD(Token(s),MINP(p,q)),MIN(OFFSET(p),OFFSET(q)))) |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def AND(term1,term2):
return a2("and",term1,term2)
def NOT(term1):
return a1("not",term1)
def EQZ(term1,term2):
return a2("=",term1,term2)
def ADDRESS(term1):
return ADD(BASE(BLOCK(term1)),OFFSET(term1))
def RANGE(term1,term2):
return AND(LT(Tok... | The code defines a function `Aplus` that checks a logical condition involving memory addresses and offsets. It verifies whether, if a pointer `p` is non-zero and within a valid range, the offset at `p + i` equals the sum of `p`'s offset and the product of a token `s` and `i`. This likely relates to memory safety or typ... | def Aplus(term):
p = term.slps[1]
i = term.slps[2]
return IMPL(AND(NOT(EQZ(ADDRESS(p),Token("0"))),RANGE(p,i)),EQZ(OFFSET(ADDP(p,i)),ADD(OFFSET(p),PROD(Token(s),i)))) |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def AND(term1,term2):
return a2("and",term1,term2)
def NOT(term1):
return a1("not",term1)
def EQZ(term1,term2):
return a2("=",term1,term2)
def ADDRESS(term1):
return ADD(BASE(BLOCK(term1)),OFFSET(term1))
def RANGE(term1,term2):
return AND(LT(Tok... | The main task of the code is to construct a logical implication statement. It combines conditions checking if the address of `p` is non-zero and valid (`RANGE(p,i)`) with a `DELTA` operation involving `ADDP(p,i)` and `p`, returning an implication structured as `IMPL(AND(...), DELTA(...))` to represent a formal logical ... | def Adelt(term):
p = term.slps[1]
i = term.slps[2]
return IMPL(AND(NOT(EQZ(ADDRESS(p),Token("0"))),RANGE(p,i)),DELTA(ADDP(p,i),p)) |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def AND(term1,term2):
return a2("and",term1,term2)
def DELTA0PLUS(term1,term2):
return DELTAPLUS(term1,term2)
def DB(term1,term2):
return EQZ(ALIGN(term1),ALIGN(term2))
def EQZ(term1,term2):
return a2("=",term1,term2)
def PROD(term1,term2):
retu... | The function Aminplus processes a term by checking if its first two components are LevelPart instances starting with "Create+". If true, it constructs a logical implication involving DELTA0PLUS, DB, and EQZ operations; otherwise, it delegates to Amin(term). | def Aminplus(term):
p = term.slps[1]
q = term.slps[2]
if (isinstance(p,LevelPart)and(len(p.slps)>0)and(p.slps[0].s=="Create+")) and (isinstance(q,LevelPart)and(len(q.slps)>0)and(q.slps[0].s=="Create+")):
return IMPL(AND(DELTA0PLUS(p,q),DB(p,q)),EQZ(PROD(Token(s),MINP(p,q)),MIN(OFFSET(p),OFFSET(q))))... |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def RANGEPLUS(term1,term2):
return AND(LT(Token("0"), ADD(term1.slps[2],PROD(Token(s),term2))),LEQ(ADD(term1.slps[2],PROD(Token(s),term2)),Token(A)))
def EQZ(term1,term2):
return a2("=",term1,term2)
def OFFSET(term1):
return a1("Offset",term1)
def ADDP(... | The main task of the code is to process a symbolic term by checking if its structure meets specific conditions (e.g., a "Create+" operation within nested components). If so, it generates a logical implication involving range operations, offsets, and algebraic expressions. Otherwise, it delegates to a simpler function `... | def Aplusplus(term):
p = term.slps[1]
i = term.slps[2]
if (isinstance(p,LevelPart)and(len(p.slps)>0)and(p.slps[0].s=="Create+")):
return IMPL(RANGEPLUS(p,i),EQZ(OFFSET(ADDP(p,i)),ADD(OFFSET(p),PROD(Token(s),i))))
return Aplus(term) |
def IMPL(term1,term2):
return a2("=>",term1,term2)
def RANGEPLUS(term1,term2):
return AND(LT(Token("0"), ADD(term1.slps[2],PROD(Token(s),term2))),LEQ(ADD(term1.slps[2],PROD(Token(s),term2)),Token(A)))
def DELTA(term1,term2):
return EQZ(BLOCK(term1),BLOCK(term2))
def ADDP(term1,term2):
return a2("+p",ter... | The function Adeltplus processes a term by checking if its second slp component (p) is a LevelPart with a "Create+" prefix. If true, it constructs a new term using IMPL, RANGEPLUS, DELTA, and ADDP operations. Otherwise, it delegates to Adelt. The core task involves conditional term transformation based on structural ru... | def Adeltplus(term):
p = term.slps[1]
i = term.slps[2]
if (isinstance(p,LevelPart)and(len(p.slps)>0)and(p.slps[0].s=="Create+")):
return IMPL(RANGEPLUS(p,i),DELTA(ADDP(p,i),p))
return Adelt(term) |
def get_line(dr):
"""Returns the (start_theta,end_theta) values of a line 'dr' where
which give the starting position and ending position of the line
on the boundary of the hyperbolic plane."""
# Do the following line twice, because otherwise it somehow fails to
# normalise it some of the time
d... | The code generates a list of images for an animation by drawing geometric shapes and lines on each frame. It uses specified methods ('klein' or 'poincare') to render lines, with 'poincare' involving complex transformations using trigonometric and matrix operations to create curved paths. The function processes each fra... | def draw_frames(frames, imgx=600, imgy=600, width=1, method='poincare', nsamples=50):
"""Returns a list of images which together make up an animation."""
nframes = len(frames)
images = [Image.new("RGB", (imgx, imgy)) for i in range(nframes)]
for i in range(len(frames)):
draw = ImageDraw.Draw(ima... |
def interpolate(transformation, nframes=50):
"""Returns a list of transformations that interpolates between the
identity transformation and the specified transformation. If 'nframes'
equals 1, then simply return the input transformation in a singleton
list."""
if nframes == 1:
return [transf... | The function generates a sequence of images animating a linear transformation applied to given lines, interpolating between the original and transformed states over `nframes` steps. It handles negative determinants by warning the user and exiting early. The output is a list of rendered frames showing the transformation... | def animate_transformation_without_display(transformation,
lines,
nframes=100,
width=1,
title=None):
try:
intermediate_transformations =... |
def interpolate(transformation, nframes=50):
"""Returns a list of transformations that interpolates between the
identity transformation and the specified transformation. If 'nframes'
equals 1, then simply return the input transformation in a singleton
list."""
if nframes == 1:
return [transf... | The function `animate_transformation` animates the application of a given transformation to a list of lines by interpolating between the identity transformation and the input transformation over `nframes`. It handles negative determinant errors, applies interpolated transformations to lines, generates frames, and displ... | def animate_transformation(transformation,
lines,
nframes=100,
width=1,
title=None,
via='tk_multiprocess'):
"""Takes as input a transformation and a list of lines.
It interpolat... |
def average(dataset):
Y = dataset.iloc[:, -1].values.reshape(-1,1)
return np.mean(Y)
def find_MSE(self, dataset):
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1].values.reshape(-1,1)
y_pred = self.predict(X)
MSE = (np.sum(((Y-y_pred)**2))/len(Y))
return MS... | This function prunes a decision tree by evaluating if replacing a subtree with a leaf node (holding the dataset's average value) reduces the mean squared error (MSE) on the test data. If the pruned node achieves equal or better performance, it replaces the original subtree; otherwise, it recursively prunes left and rig... | def prune_tree(self, root, dataset, test_dataset):
if(root.leaf_value):
return root
prune_root = Node(leaf_value=average(dataset))
actual_acc = self.find_MSE(test_dataset)
prune_acc = self.find_MSE_prune(prune_root, test_dataset)
print(f"{prune_root.node_id}, {root.n... |
def compare(A, B):
for i in range(board_size):
for j in range(board_size):
if A[i][j] == B[i][j]:
continue
else:
return False
return True
def merge_board_left(board):
for row in board:
row = merge_one_row_left(row)
return board
de... | The function `possible_merges` checks if any of the four possible board merges (left, right, up, down) would result in a different board. If any merge changes the board, it returns `False` (indicating possible merges exist), otherwise returns `True` (no possible merges). | def possible_merges(board):
temp = board.copy()
if compare(board, merge_board_left(temp)) or compare(board, merge_board_right(temp)) or \
compare(board, merge_board_up(temp)) or compare(board, merge_board_down(temp)):
return False
return True |
def compare(self, A, B):
for i in range(self.board_size):
for j in range(self.board_size):
if A[i][j] == B[i][j]:
continue
else:
return False
return True
def merge_board_left(self, board):
for row in board:
... | The function checks if any of the four possible merges (left, right, up, down) would alter the board. If any merge changes the board, it returns False (indicating merges are possible); otherwise, it returns True (no merges possible). This determines if further moves are available in a game like 2048. | def possible_merges(self, board):
temp = board.copy()
if self.compare(board, self.merge_board_left(temp)) or self.compare(board, self.merge_board_right(temp)) or \
self.compare(board, self.merge_board_up(temp)) or self.compare(board, self.merge_board_down(temp)):
return False... |
def getTweets(self, account='BBCNews', count=200, no_fetches=1):
old_id = 0
tweets = []
for i in range(no_fetches):
t = self.api.GetUserTimeline(screen_name=account, max_id=old_id, count=count, include_rts=1)
new_tweets = [i.AsDict() for i in t]
old_id = new_t... | The main task of the code is to fetch tweets, save them, generate a sorted dataframe of top tweets, display the top entries, create an HTML email body from the data, and send the email using an EmailSender instance. The process includes retrieving tweets, organizing them into a structured format, and automating email n... | def main(self, no_tweets=10):
# Get tweets
print("Fetching tweets...")
tweets = self.getTweets(no_fetches=6)
self.saveTweets(tweets)
#tweets = loadTweets()
# Make sorted dataframe of top tweets
df = self.createDataFrame(tweets)
print(df.head(no_tw... |
def _pos_quat_from_model(
elem: MjcfElement, model: mujoco.MjModel
) -> Tuple[np.ndarray, np.ndarray]:
if elem.name is not None:
geom_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_GEOM, elem.name)
geom_pos = model.geom_pos[geom_id]
geom_quat = model.geom_quat[geom_id]
return ... | This function parses an MJCF capsule element into a Collider configuration, determining its radius, length (from 'fromto' points or size), position, rotation, and material. It adjusts length by adding twice the radius if specified, converts the capsule's orientation to Euler angles, and returns a populated Collider obj... | def _parse_capsule(
capsule: MjcfElement, model: mujoco.MjModel, add_radius: bool = True
) -> config_pb2.Collider:
if capsule.size is None:
commit_defaults(capsule)
size = capsule.size
if size is None:
raise ValueError(f"capsule elem {capsule.name} is missing a size attribute")
radiu... |
def _pos_quat_from_model(
elem: MjcfElement, model: mujoco.MjModel
) -> Tuple[np.ndarray, np.ndarray]:
if elem.name is not None:
geom_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_GEOM, elem.name)
geom_pos = model.geom_pos[geom_id]
geom_quat = model.geom_quat[geom_id]
return ... | This function parses a Mujoco box element into a Collider configuration, extracting size, position, rotation, and material. It ensures the box has a defined size, converts the orientation from quaternion to Euler angles, and returns a structured Collider object with halfsize, rotation, position, and material properties... | def _parse_box(box: MjcfElement, model: mujoco.MjModel) -> config_pb2.Collider:
if box.size is None:
commit_defaults(box)
size = box.size
if size is None:
raise ValueError(f"box elem {box.name} is missing a size attribute")
position, quat = _pos_quat_from_model(box, model)
rot_euler ... |
def _pos_quat_from_model(
elem: MjcfElement, model: mujoco.MjModel
) -> Tuple[np.ndarray, np.ndarray]:
if elem.name is not None:
geom_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_GEOM, elem.name)
geom_pos = model.geom_pos[geom_id]
geom_quat = model.geom_quat[geom_id]
return ... | This function parses an ellipsoid element from a MuJoCo model into a Collider configuration. It handles default size values, extracts position and orientation, converts quaternion to Euler angles, and constructs a Collider with radius, rotation, position, and material attributes. | def _parse_ellipsoid(
ellipsoid: MjcfElement, model: mujoco.MjModel
) -> config_pb2.Collider:
if ellipsoid.size is None:
commit_defaults(ellipsoid)
size = ellipsoid.size
if size is None:
raise ValueError(f"ellipsoid elem {ellipsoid.name} is missing a size attribute")
position, quat =... |
def _pos_quat_from_model(
elem: MjcfElement, model: mujoco.MjModel
) -> Tuple[np.ndarray, np.ndarray]:
if elem.name is not None:
geom_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_GEOM, elem.name)
geom_pos = model.geom_pos[geom_id]
geom_quat = model.geom_quat[geom_id]
return ... | The function parses a cylinder element from an MJCF model into a Collider configuration. It sets default size if missing, extracts position and orientation, converts quaternion to Euler angles, and constructs a Collider with radius, length, rotation, position, and material. | def _parse_cylinder(
cylinder: MjcfElement, model: mujoco.MjModel
) -> config_pb2.Collider:
if cylinder.size is None:
commit_defaults(cylinder)
size = cylinder.size
if size is None:
raise ValueError(f"cylinder elem {cylinder.name} is missing a size attribute")
position, quat = _pos_q... |
def _parse_box(box: MjcfElement, model: mujoco.MjModel) -> config_pb2.Collider:
if box.size is None:
commit_defaults(box)
size = box.size
if size is None:
raise ValueError(f"box elem {box.name} is missing a size attribute")
position, quat = _pos_quat_from_model(box, model)
rot_euler ... | The function `parse_geom` converts a MuJoCo geometry element (`MjcfElement`) into a `Collider` configuration based on its type. It uses conditional checks to dispatch to specialized parsing functions for each geometry type (e.g., box, sphere, mesh). The output is a `config_pb2.Collider` object, raising an error for uns... | def parse_geom(geom: MjcfElement, model: mujoco.MjModel) -> config_pb2.Collider:
if geom.type == "box":
return _parse_box(geom, model)
elif geom.type == "sphere":
return _parse_sphere(geom, model)
elif geom.type == "cylinder":
return _parse_cylinder(geom, model)
elif geom.type ==... |
def _read_hostname(self):
fname = os.path.join(self.sosdir, 'hostname')
self.hostname = self._read(fname)
print("Hostname: %s" % self.hostname)
def _is_dpdk_enabled(self):
other_config_str = self._get_ovsdb_other_config()
if 'dpdk-init' not in other_config_str:
LOG.er... | The code analyzes OpenvSwitch (OVS) by checking if DPDK is enabled. If enabled, it validates the configuration; if not, it logs an error indicating DPDK is disabled in OVS. | def analyze(self):
self._read_hostname()
self.dpdk_enabled = self._is_dpdk_enabled()
if self.dpdk_enabled:
LOG.info("DPDK is enabled in OVS")
self._validate_config()
else:
LOG.error("DPDK is not enabled in OpenvSwitch (dpdk-init)") |
def detectARMarkers() :
global currentSegment, timer, colorImage, WALL_FOLLOWED_BEFORE
colorImage = rc.camera.get_color_image()
depthImage = rc.camera.get_depth_image()
colorImage = rc_utils.crop(colorImage, (0, 130), (480, 500))
depthImage = rc_utils.crop(depthImage, (0, 130), (480, 500))
# rc... | The code updates the robot's behavior by detecting AR markers or line-following segments, updating the current segment's logic, and adjusting speed/angle via controller inputs in debug mode. It checks the current segment, triggers specific detection if not in line-following modes, updates segment mappings, and applies ... | def update():
detectARMarkers()
if currentSegment not in [Segment.LineFollow, Segment.ConeSlalom, Segment.SlabSlalom] : detectLineFollow()
# Update selected segment
SegmentMappings[currentSegment].update()
if DEBUG : rc.drive.set_speed_angle(
rc.controller.get_trigger(rc.controller.Trigger.RIG... |
def encode_text(self, text: List[str]) -> ClipEncodeTextOutput:
text_tokens = clip.tokenize(text).to(self.device)
text_embeds = self.clip_model.encode_text(text_tokens)
return ClipEncodeTextOutput(text_embeds=text_embeds)
def encode_rois(self, image: torch.Tensor, rois: torch.Tensor, pad_square:... | This function predicts by preprocessing an image, encoding text (if not provided), encoding image regions of interest (ROIs), and decoding combined image-text encodings to generate output. It handles multimodal input processing for tasks like image-text alignment or retrieval, using optional padding and threshold param... | def predict(self,
image: PIL.Image,
text: List[str],
text_encodings: Optional[ClipEncodeTextOutput],
pad_square: bool = True,
threshold: float = 0.1
) -> ClipDecodeOutput:
image_tensor = self.image_preprocessor.preprocess_pil_image(image)
... |
def extract_rois(self, image: torch.Tensor, rois: torch.Tensor, pad_square: bool = True, padding_scale: float = 1.0):
if len(rois) == 0:
return torch.empty(
(0, image.shape[1], self.image_size, self.image_size),
dtype=image.dtype,
device=image.device
... | The function processes regions of interest (ROIs) by extracting cropped ROI images from the input image tensor, encoding them using an image encoder, and converting predicted bounding boxes from ROI-local coordinates to global image coordinates. It returns the encoded features with adjusted box predictions. | def encode_rois(self, image: torch.Tensor, rois: torch.Tensor, pad_square: bool = True, padding_scale: float=1.0):
# with torch_timeit_sync("extract rois"):
roi_images, rois = self.extract_rois(image, rois, pad_square, padding_scale)
# with torch_timeit_sync("encode images"):
output = se... |
def _text_normalize(self, text: str) -> list:
"""This module generate a word-coocurrence graph from raw text
:param str text: texto to normalize
"""
prep_text = self.prep.prepocessing_pipeline(text)
return prep_text
def __get_entities(self, doc_words_list: list) -> list: ... | The main task of the code is to transform a list of documents into a graph structure by preprocessing text, extracting entities (nodes) and relations (edges), building a graph, and applying a graph transformation. It returns a dictionary containing the graph, node/edge counts, and status, handling errors gracefully. | def __transform_pipeline(self, corpus_docs: list) -> list:
output_dict = {
'doc_id': 1,
'graph': None,
'number_of_edges': 0,
'number_of_nodes': 0,
'status': 'success'
}
try:
#1. text preprocessing
logger.deb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.