query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Generates key pair that can be used for Solo signed firmware updates. \b Generates NIST P256 keypair. Public key must be copied into correct source location in solo bootloader The private key can be used for signing updates. You may optionally supply a file to seed the RNG for key generating.
def genkey(input_seed_file: Optional[str], output_pem_file: str) -> None: vk = pynitrokey.fido2.operations.genkey( output_pem_file, input_seed_file=input_seed_file ) local_print( "Public key in various formats:", None, [c for c in vk.to_string()], None, "".join(["%02x" % c for c in vk.to_string()]), None, '"\\x' + "\\x".join(["%02x" % c for c in vk.to_string()]) + '"', None, )
[ "def genkey(input_seed_file, output_pem_file):\n\n vk = solo.operations.genkey(output_pem_file, input_seed_file=input_seed_file)\n\n print(\"Public key in various formats:\")\n print()\n print([c for c in vk.to_string()])\n print()\n print(\"\".join([\"%02x\" % c for c in vk.to_string()]))\n print()\n print('\"\\\\x' + \"\\\\x\".join([\"%02x\" % c for c in vk.to_string()]) + '\"')\n print()", "def generate_private_key():\n return os.urandom(32)", "def _gen_key(version):\n priv = keys.generate_sign_key()\n pub = keys.public_sign_key(priv)\n return trcs.Key(version=version, priv_key=priv, pub_key=pub)", "def generate_private_key():\n return secretkey.generate_key(32)", "def generate_keys():\n aeskey = get_random_bytes(16)\n rsakey = RSA.generate(2048)\n\n \"\"\" Old, bad(?) implementation. We're not using this anymore. To be fair, we never really got an explanation of why it was bad to directly write into bootloader.c, then make, then remove the key, but it was phased out to promote using the proper way instead nonetheless. \n # Change into directory containing bootloader source.\n bldir = FILE_DIR / '..' / 'bootloader' / 'src'\n os.chdir(bldir)\n with open('bootloader.c', 'r') as file:\n bootloader = file.read()\n if bootloader[0:12] == 'char AES_KEY': # Check if a key is already present from a previous build\n bootloader = bootloader[bootloader.index('\\n')+1:] # Remove old key\n byteout = ''\n for i in range(16): \n byteout += ', 0x' + aeskey[i:i+1].hex() # Write the bytes in hex form for C implementation (0xXX, etc.)\n byteout = byteout[2:]\n file.close()\n with open('bootloader.c', 'w') as file:\n file.write('char AES_KEY[16] = {'+byteout+'};\\n') # Write key into bootloader\n file.close()\n with open('bootloader.c', 'a') as file:\n file.write(bootloader) # Append rest of the bootloader code back on\n file.close()\n \"\"\"\n \n # Change into directory containing tools\n os.chdir(FILE_DIR)\n with open('secret_build_output.txt', 'wb') as file: \n file.write(aeskey) # Write AES key into secret file as binary bytes (to be used by fw_protect)\n file.write(rsakey.export_key(format='DER')) # Write RSA key \n print(len(rsakey.export_key(format='DER')))\n# file.write(rsakey.publickey().export_key())\n \n st = make_bootloader(aeskey, rsakey.n.to_bytes(256, 'big'), rsakey.e.to_bytes(3, 'big'))\n# st = make_bootloader(aeskey, struct.pack(\">I\", rsakey.n), struct.pack(\">I\", rsakey.e))\n if st != 0: # Throw error if build failed\n raise SystemExit(f'Build Failed - Make returned code {st}')", "def generate_vapid_keypair():\n pk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)\n vk = pk.get_verifying_key()\n return {\n 'private_key': base64.urlsafe_b64encode(pk.to_string()).decode('utf-8').strip(\"=\"),\n 'public_key': base64.urlsafe_b64encode(b\"\\x04\" + vk.to_string()).decode('utf-8').strip(\"=\")\n }", "def generate_key_pair(self):\n assert self.public_key is None, 'This user already has a public key'\n assert self.private_key is None, 'This user already has a private key'\n key_pair = RSA.generate(NUM_KEY_BITS)\n self.private_key = key_pair.export_key().decode()\n self.public_key = key_pair.publickey().export_key().decode()", "def generate_keys():\n\n from remofile.keys import generate_keys\n public_key, private_key = generate_keys()\n\n print(\"public key: {0}\".format(str(public_key, 'utf-8')))\n print(\"private key: {0}\".format(str(private_key, 'utf-8')))", "def keygen(filepath):\n private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())\n\n with open(filepath, 'wb') as private_key_file:\n private_key_file.write(private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()))\n\n write_public_keyfile(filepath, filepath + '.pub')", "def make_key(self):\n\t\tif self.key:\n\t\t\tif not os.path.isfile(os.path.join(self.root, self.key + \".biprivatekey\")):\n\t\t\t\tprint_green(\"\\nRequested key does not exist.\")\n\t\t\t\tret = subprocess.call([self.dscreatekey, self.key], stdout = subprocess.DEVNULL if self.quiet else None, stderr = subprocess.DEVNULL if self.quiet else None) # Created in root\n\t\t\t\tif ret == 0:\n\t\t\t\t\tprint_blue(\"Created: \" + os.path.join(self.root, self.key + \".biprivatekey\"))\n\t\t\t\telse:\n\t\t\t\t\tprint_error(\"Failed to create key!\")\n\n\t\t\t\ttry:\n\t\t\t\t\tprint_blue(\"Copying public key to release directory.\\n\")\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\tos.makedirs(os.path.join(self.release_dir, \"Keys\"))\n\t\t\t\t\texcept IOError:\n\t\t\t\t\t\tpass\n\n\t\t\t\t\tshutil.copyfile(os.path.join(self.root, self.key + \".bikey\"), os.path.join(self.release_dir, \"Keys\", self.key + \".bikey\"))\n\n\t\t\t\texcept:\n\t\t\t\t\tprint_error(\"Could not copy key to release directory.\\n\")\n\t\t\t\t\traise\n\n\t\t\telse:\n\t\t\t\tprint_green(\"\\nNOTE: Using key \" + os.path.join(self.root, self.key + \".biprivatekey\\n\"))\n\n\t\t\tself.key = os.path.join(self.root, self.key + \".biprivatekey\")", "def ssh_keygen():\n dsa_filename = os.path.join(remote_home(), '.ssh', 'id_dsa')\n run(\"ssh-keygen -t dsa -P '' -f %s\" % dsa_filename)\n remote_pubkey()", "def keygen(self):\n self._generate_sk()\n self._generate_pk()\n return [self._secret_key, self._public_key]", "def generate_nodekey(nodekey_file):\n\n cmd = sh.Command('bootnode').bake('-genkey', nodekey_file, '-writeaddress')\n run_cmd(cmd)\n\n nodekey = fs_utils.read_file(nodekey_file)\n\n return nodekey", "def _make_private_key(self):\n\t\treturn int(binascii.hexlify(os.urandom(16)), 16)", "def generate_key(force=False):\n if generate_key.secret_key is not None and not force:\n return generate_key.secret_key\n\n choices = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'\n key = ''.join([random.SystemRandom().choice(choices) for i in range(50)])\n generate_key.secret_key = key\n return generate_key.secret_key", "def generate_keypair(self) -> str:\n # create an NaClDSEncoder object\n nacl_enc = NaClDSEncoder()\n # generate new keys\n nacl_enc.generate()\n\n self.keypair = nacl_enc.keypair\n self.public_key = nacl_enc.public_key\n self.private_key = nacl_enc.private_key\n return self.keypair", "def generate_keys(self):\n private_key = RSA.generate(1024, Crypto.Random.new().read)\n public_key = private_key.publickey()\n return binascii.hexlify(private_key.exportKey(format='DER')).decode('ascii'), binascii.hexlify(public_key.exportKey(format='DER')).decode('ascii')", "def generateKeyPair(cls):", "def generate_key(ctx, name):\n click.echo(f\"Generating key file {name}.key...\")\n\n # key generation\n key = Fernet.generate_key()\n\n # string the key in a file\n with open(f'{name}.key', 'wb') as file_key:\n file_key.write(key)\n\n click.echo(f\"Key file {name}.key successfully generated!\")\n click.echo(\"Save {name}.key somewhere secure, you will not be able to recover files encrypted using this key \"\n \"without it.\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Signs a fwhex file, outputs a .json file that can be used for signed update.
def sign( verifying_key: str, app_hex: str, output_json: str, end_page: int, pages: int ) -> None: msg = pynitrokey.fido2.operations.sign_firmware( verifying_key, app_hex, APPLICATION_END_PAGE=end_page, PAGES=pages ) local_print(f"Saving signed firmware to: {output_json}") with open(output_json, "wb+") as fh: fh.write(json.dumps(msg).encode())
[ "def sign(verifying_key, app_hex, output_json):\n\n msg = solo.operations.sign_firmware(verifying_key, app_hex)\n print(\"Saving signed firmware to\", output_json)\n with open(output_json, \"wb+\") as fh:\n fh.write(json.dumps(msg).encode())", "def sign_file(self, file_path):\n\t\twith open(file_path, 'rb') as f:\n\t\t\tdata = f.read()\n\t\t\treturn self.sign_content(data)", "def sign_log(log_path, private_key_path, out_path=None):\n with open(log_path, \"rb\") as log_obj, open(private_key_path) as key_ob:\n jd = json.loads(log_obj.read(), parse_float=decimal.Decimal)\n rsa_key = RSA.import_key(key_ob.read())\n # print(\"__signdata to sha256 = __\" + json.dumps((jd['FlightLog'])) + \"__\")\n hashed_logdata = SHA256.new(json.dumps((jd['FlightLog']), separators=(',',':')).encode())\n log_signature = pkcs1_15.new(rsa_key).sign(hashed_logdata)\n # the signature is encoded in base64 for transport\n enc = base64.b64encode(log_signature)\n # dealing with python's byte string expression\n jd['Signature'] = enc.decode('ascii')\n if out_path:\n save_path = out_path\n else:\n save_path = log_path[:-5] + \"-signed.json\"\n with open(save_path, 'w') as outfile:\n json.dump(jd, outfile, indent=4)\n return save_path", "def save_hex_file(self, file_name):\n \n with open(file_name, 'wb') as file:\n file.write(self.hex_view_formatted())", "def sign_file(self, file, dir=None):\n _log.debug(\"sign_file: file={}\".format(file))\n try:\n certificate_hash = certificate.cert_hash(certpath=self.certificate)\n except:\n _log.exception(\"Failed to get certificate hash\")\n raise Exception(\"Failed to get certificate hash\")\n sign_file_name = file + \".sign.\" + certificate_hash\n if dir:\n sign_file = os.path.join(dir, sign_file_name)\n else:\n sign_file = sign_file_name\n print \"signed file name=\"+sign_file\n log = subprocess.Popen([\"openssl\", \"dgst\", \"-sha256\",\n \"-sign\", self.private_key,\n \"-passin\", \"file:\" + self.password_file,\n \"-out\", sign_file,\n file],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = log.communicate()\n if log.returncode != 0:\n raise IOError(stderr)\n with open(sign_file, 'rt') as f:\n signature = f.read()\n with open(file, 'rt') as f:\n content= f.read()\n with open(self.certificate, 'rt') as f:\n trusted_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, f.read())\n try:\n # Verify signature\n OpenSSL.crypto.verify(trusted_cert, signature, content, 'sha256')\n _log.debug(\"verify_signature_content: signature correct\")\n except Exception as e:\n _log.error(\"OpenSSL verification error\", exc_info=True)\n return sign_file", "def sign(apk_file_path, signed_apk_file_path, signjar, certificate, pk8):\n @requires_binary(\"java\")\n def _sign(apk_file_path, signjar, certificate, pk8):\n return _execute(\"java -jar {} {} {} {} {}\".format(signjar, certificate, pk8,\n apk_file_path, signed_apk_file_path))\n\n return _sign(apk_file_path, signjar, certificate, pk8)", "def signTransaction(tx, path, debug=False):\r\n\r\n\tdongle_path = parseBip32Path(path)\r\n\ttx[\"senderPublicKey\"] = getPublicKey(dongle_path, debug)\r\n\ttx[\"signature\"] = getSignature(dposlib.core.crypto.getBytes(tx), dongle_path, debug)", "def make_output(STIX, path = \"/STIX_data.json\"):\n try:\n with open(path, 'w') as fp:\n json.dump(Util.bundle_stix(STIX), fp)\n except:\n print \"Unable to access directory '\", path, \"'\\n\", \"Using default directory\"\n\n with open(\"STIX_data.json\", 'w') as fp:\n json.dump(Util.bundle_stix(STIX), fp)", "def sign(self, file):\r\n\r\n if not os.path.exists(file):\r\n print(colors.BOLD+\"The file \"+colors.YELLOW + file + colors.ENDC + colors.BOLD + \" doesnt exist.\" + colors.ENDC)\r\n return None\r\n \r\n f = open(file, \"rb\")\r\n content = f.read()\r\n f.close()\r\n \r\n print(\"{}\\t-> Signing file...{} OK{}\".format(colors.BOLD, colors.GREEN, colors.ENDC))\r\n key = RSA.import_key(open(self.path + '/key.bin').read()) # Import private key\r\n \r\n hash = SHA256.new(content) # Messages Hash\r\n sign = pkcs1_15.new(key).sign(hash) # Hash signed with key\r\n\r\n return sign + content", "def write():\n f = open(\"accounts.dat\", \"wb\")\n f.write((\"bank9000™ accounts data\\nwritten UTC \" + str(datetime.utcnow()) + '\\n').encode('utf-8'))\n s = base64.b64encode(json.dumps((users, accounts)).encode())\n f.write(zlib.compress(s) + b'\\n')\n f.close()", "def sign(key, file, output, clearsign=False):\n signopt = \"--clearsign\" if clearsign else \"--detach-sign\"\n GPG(signopt, \"--armor\", \"--default-key\", key, \"--output\", output, file)", "def sign(self, signer: Signer) -> str:\n\n # TODO: Consider moving the validation logic below to a low-level check_signatures() method\n\n signature_data = self.get_signature_data()\n original_config = signature_data.get(\"original_config\", None)\n if signature_data[\"signatures\"]:\n signature_data[\"signatures\"] += \"\\n\"\n\n # It is not reasonably possible to reproduce the hash of the\n # original image configuration at this point.\n if not original_config:\n raise RuntimeError(\n \"Refusing to sign; signature(s) exist without original config hash!\"\n )\n else:\n if original_config:\n LOGGER.warning(\n \"Original config hash found without signatures;overriding!\"\n )\n original_config = self.get_config_digest()\n\n digest = self.get_config_digest_canonical().encode(\"utf-8\")\n # if original_config and digest != original_config:\n # raise RuntimeError(\"Refusing to sign; embedded and calculated original config values are inconsistent!\")\n\n signature = signer.sign(digest)\n if not signature:\n raise RuntimeError(\"Failed to create signature!\")\n signature_data[\"signatures\"] += signature\n self.set_signature_data(original_config, signature_data[\"signatures\"])\n\n return signature", "def WriteShaFile(self, sha):\n file_path = os.path.join(self._framework_appsearch_root, SHA_FILE_NAME)\n old_sha = None\n if os.path.isfile(file_path):\n with open(file_path, 'r') as fh:\n old_sha = fh.read().rstrip()\n with open(file_path, 'w') as fh:\n print(sha, file=fh)\n print('Wrote \"%s\"' % file_path)\n return old_sha", "def sign_file(config, key, path, destination=None, detach=True, armor=True):\n\n key_path = \"%s/%s\" % (config.gpg_key_path, key)\n\n if not os.path.isdir(key_path):\n raise IndexError(\"Invalid GPG key name '%s'.\" % key)\n\n if not os.path.isfile(path):\n raise Exception(\"Invalid path '%s'.\" % path)\n\n if not destination:\n if armor:\n destination = \"%s.asc\" % path\n elif detach:\n destination = \"%s.sig\" % path\n else:\n destination = \"%s.gpg\" % path\n\n if os.path.exists(destination):\n raise Exception(\"Destination already exists: %s\" % destination)\n\n os.environ['GNUPGHOME'] = key_path\n\n # Create a GPG context, assuming no passphrase\n ctx = gpgme.Context()\n ctx.armor = armor\n # XXX: This is a temporary workaround until the key situation is explained\n key = [gpg_key for gpg_key in ctx.keylist()][0]\n ctx.signers = [key]\n\n logger.debug(\"Signing file: %s\" % destination)\n\n with open(path, \"rb\") as fd_in, open(destination, \"wb+\") as fd_out:\n if detach:\n retval = ctx.sign(fd_in, fd_out, gpgme.SIG_MODE_DETACH)\n else:\n retval = ctx.sign(fd_in, fd_out, gpgme.SIG_MODE_NORMAL)\n\n return retval", "def make_sigs(self, outfile, shash):\n for priv in self.privs:\n sig = bitcoin.encode_sig(*bitcoin.ecdsa_raw_sign(\n shash, priv))\n outfile.write((\"SIG \"+sig+\"\\n\").encode(\"ascii\"))", "def hex_sign(self, ignore_head=True, ignore_files=True, ignore_tracks=True):\n\n return hexlify(self.sign(ignore_head, ignore_files, ignore_tracks)).upper()", "async def jsonrpc_channel_sign(\n self, channel_name=None, channel_id=None, hexdata=None, salt=None,\n channel_account_id=None, wallet_id=None):\n wallet = self.wallet_manager.get_wallet_or_default(wallet_id)\n assert not wallet.is_locked, \"Cannot spend funds with locked wallet, unlock first.\"\n signing_channel = await self.get_channel_or_error(\n wallet, channel_account_id, channel_id, channel_name, for_signing=True\n )\n if salt is None:\n salt = str(int(time.time()))\n signature = signing_channel.sign_data(unhexlify(str(hexdata)), salt)\n return {\n 'signature': signature,\n 'signing_ts': salt, # DEPRECATED\n 'salt': salt,\n }", "def generate(self, filepath: str, data: dict): \n \n with open(filepath, 'w') as f:\n json.dump(data, f, indent=4)", "def store_signature(self):\n digest = self.get_current_signature()\n with open(self.signature_file, 'w') as f:\n f.write(digest)\n return digest" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merges hex files, and patches in the attestation key. \b If no attestation key is passed, uses default Solo Hacker one. Note that later hex files replace data of earlier ones, if they overlap.
def mergehex( attestation_key: Optional[bytes], attestation_cert: Optional[bytes], lock: bool, input_hex_files: List[str], output_hex_file: str, end_page: int, pages: int, ) -> None: pynitrokey.fido2.operations.mergehex( input_hex_files, output_hex_file, attestation_key=attestation_key, APPLICATION_END_PAGE=end_page, attestation_cert=attestation_cert, lock=lock, PAGES=pages, )
[ "def mergehex(\n attestation_key, attestation_cert, lock, input_hex_files, output_hex_file, end_page\n):\n solo.operations.mergehex(\n input_hex_files,\n output_hex_file,\n attestation_key=attestation_key,\n APPLICATION_END_PAGE=end_page,\n attestation_cert=attestation_cert,\n lock=lock,\n )", "def isect(settings, merged, extendby, temp_dir, comp, reg):\n\n # function used only here\n def extender(extendby, path, hg19, ext_path):\n cmd1 = ['slopBed', '-b', str(extendby), '-i', path, '-g', hg19]\n p1 = Popen(cmd1, stdout = open(ext_path, 'wb'))\n p1.wait()\n\n # 1) extend all files\n expanded = {}\n for pathname, path in merged.items():\n # skip those you don't want\n\n ext_name = pathname+'{0}_{1}_REextended_{2}'.format(comp, reg, extendby)\n ext_path = os.path.join(temp_dir, ext_name)\n\n extender(extendby, path, settings.hg19_path, ext_path)\n expanded[pathname] = ext_path\n\n filea, fileb = expanded.values()\n cmd2 = ['intersectBed', '-wa', '-wb', '-s', '-a', filea, '-b', fileb]\n p2 = Popen(cmd2, stdout=PIPE )\n\n isect_name = str(comp)+'_'+str(reg)+'_'+'_I_'.join(expanded.keys())\n isect_path = os.path.join(temp_dir, isect_name)\n\n out_handle = open(isect_path, 'wb')\n\n # save the intersected path\n for line in p2.stdout:\n (achrm, abeg, aend, aname, aval, astrnd,\n bchrm, bbeg, bend, bname, bval, bstrnd) = line.split('\\t')\n\n name = '#'.join(aname.split(' '))\n\n # re-center the intersection\n if int(abeg) < int(bbeg):\n center_dist = math.ceil((int(bend)-int(abeg))/2)\n center = int(int(bend) - center_dist)\n else:\n center_dist = math.ceil((int(aend)-int(bbeg))/2)\n center = int(int(aend) - center_dist)\n\n # write the center of the new mergers\n out_handle.write('\\t'.join([achrm, str(center), str(center+1), name,\n aval, astrnd]) + '\\n')\n\n out_handle.close()\n\n # save the output in an output dict\n output_dict = {'intersection': isect_path}\n # remove the intersection from + and -\n\n # 1) expand the new intersection path!\n isect_exp_name = isect_name + '_ExPanDeD{0}'.format(extendby)\n isect_exp_path = os.path.join(temp_dir, isect_exp_name)\n extender(extendby, isect_path, settings.hg19_path, isect_exp_path)\n\n # 2) subtract from the two origial files that which overlaps the extended\n # intersection\n for pathname, path in merged.items():\n cmd = ['subtractBed', '-s', '-a', path, '-b', isect_exp_path]\n outpath = path + '_Sliced'\n p3 = Popen(cmd, stdout = open(outpath, 'wb'))\n p3.wait()\n\n output_dict[pathname+'_sliced'] = outpath\n\n return output_dict", "def merge_fixes(files):\n # The fixes suggested by clang-tidy >= 4.0.0 are given under\n # the top level key 'Diagnostics' in the output yaml files\n mergefile = files[0]\n mergekey = \"Diagnostics\"\n merged = []\n seen = set() # efficiently remember fixes already inserted\n\n def have(x):\n k = key(x)\n return k in seen or seen.add(k)\n\n def unique(seq):\n return [x for x in seq if not have(x)]\n\n for file in files:\n try:\n with open(file, 'r') as inp:\n content = yaml.safe_load(inp)\n if not content:\n continue # Skip empty files.\n merged.extend(unique(content.get(mergekey, [])))\n except FileNotFoundError:\n pass\n\n with open(mergefile, 'w') as out:\n if merged:\n # Assemble output dict with MainSourceFile=''.\n output = {'MainSourceFile': '', mergekey: merged}\n yaml.safe_dump(output, out)", "def merge_files() -> None:\n with open(Path.FEATURE_FILE, 'w') as target:\n keys = None\n for csv_file in tqdm(os.listdir(Path.FEATURE_FOLDER), desc='Merging feature files'):\n if csv_file.endswith('.csv'):\n with open(os.path.join(Path.FEATURE_FOLDER, csv_file), 'r') as csv:\n\n # read keys (first line) and check consistency\n keys_new = csv.readline()\n if keys is None:\n keys = keys_new\n target.write(keys)\n empty_line = ','.join([str(0.0) for _ in range(keys.count(',') + 1)])+'\\n'\n\n if not keys == keys_new:\n warnings.warn('File format not matching: {}'.format(csv_file))\n warnings.warn('Deleting file.')\n csv.close()\n os.remove(os.path.join(Path.FEATURE_FOLDER, csv_file))\n continue\n\n # copy value lines to merged target file\n for line in csv:\n target.write(line)\n\n # add empty lines to get context clean\n for _ in range(FeatureConfig.context_length + 1):\n target.write(empty_line)\n\n csv.close()\n target.close()\n print('File merged: {}'.format(Path.FEATURE_FILE))", "def merge_master_file():\n exp_tree = load_yaml_file('experiment')\n loc_tree = load_yaml_file('location')\n add_tree = load_yaml_file('addins', required=False)\n timing_tree = load_yaml_file('timing', required=False)\n\n try:\n\n for rat in exp_tree:\n exp = exp_tree[rat]\n loc = loc_tree[rat]\n\n sys.stdout.write('Rat %d:\\n' % rat)\n sys.stdout.write(' 1) Experiment <- Location\\n')\n for day in exp['days']:\n rdstr = 'rat%03d-%02d' % (rat, day)\n exp['days'][day]['tetrodes'] = loc['days'][day]['tetrodes']\n sys.stdout.write(' - Merged tetrode locations for %s\\n' % rdstr)\n\n sys.stdout.write(' 2) Master <- Addins (First Pass)\\n')\n if add_tree and rat in add_tree:\n add = add_tree[rat]\n for day in add['days']:\n rdstr = 'rat%03d-%02d' % (rat, day)\n exp['days'][day] = add['days'][day]\n sys.stdout.write(' - Merged %s from addins\\n' % rdstr)\n\n sys.stdout.write(' 3) Master <- Timing\\n')\n if timing_tree and rat in timing_tree:\n timing = timing_tree[rat]\n for day in timing['days'].keys():\n rdstr = 'rat%03d-%02d' % (rat, day)\n sys.stdout.write(' - Updating timing for %s\\n' % rdstr)\n for maze in timing['days'][day]['sessions'].keys():\n for k in ('start', 'end'):\n master_value = exp['days'][day]['sessions'][maze][k]\n timing_value = timing['days'][day]['sessions'][maze][k]\n if master_value != timing_value:\n exp['days'][day]['sessions'][maze][k] = timing_value\n\n sys.stdout.write(' 4) Master <- Addins (Final Pass)\\n')\n if add_tree and rat in add_tree:\n add = add_tree[rat]\n for day in add['days']:\n rdstr = 'rat%03d-%02d' % (rat, day)\n exp['days'][day] = add['days'][day]\n sys.stdout.write(' - Merged %s from addins\\n' % rdstr)\n\n sys.stdout.flush()\n\n except KeyError:\n import pdb\n pdb.set_trace()\n\n write_yaml_file(exp_tree, 'master')\n return exp_tree", "def merge_callers_dicts(this_callers, other_callers):\n\n # Both data sets have this file, so merge them.\n for line_or_arc, other_test_result in iitems(other_callers):\n\n # If the other line/arc is not in this file, add it and move on.\n this_test_result = this_callers.get(line_or_arc, None)\n if this_test_result is None:\n this_callers[line_or_arc] = other_test_result\n continue\n\n # This line/arc is present in both files; merge them.\n this_test_result.merge(other_test_result)\n\n return this_callers", "def merge(branch_A_text, branch_B_text, common_ancestor_text):\n\t\t#@TODO: If these are binary files such a unified diff doesn't really make sense.\n\t\t#@TODO: Notify user somehow if there is a conflict.\n\t\t#@TODO: This rewrites the whole file even if only a single character was changed. Is there a quicker way?\n\t\t#@TODO: Moving the most likely conditionals closer to the top of the loop could speed things up by short-circuiting more. (watch out for complex logic though...)\n\t\t\n\t\t[branch_A_opcodes, branch_A_opcode_strings] = file_blob.gen_opcodes(branch_A_text, common_ancestor_text)\n\t\t[branch_B_opcodes, branch_B_opcode_strings] = file_blob.gen_opcodes(branch_B_text, common_ancestor_text)\n\t\t\n\t\tA_iter = file_blob.OpcodeIter(branch_A_opcodes, branch_A_opcode_strings, common_ancestor_text)\n\t\tB_iter = file_blob.OpcodeIter(branch_B_opcodes, branch_B_opcode_strings, common_ancestor_text)\n\t\t\n\t\tresult_text = bytearray()\n\t\tconflict_block_A = bytearray()\n\t\tconflict_block_B = bytearray()\n\t\tconflicting = False\n\t\tconflict_tag_A = '' #For use in conflicts. If a conflict is detected, assume the conflict continues until one of the opcodes change.\n\t\tconflict_tag_B = ''\n\t\t[tag_A, char_A] = A_iter.next()\n\t\t[tag_B, char_B] = B_iter.next()\n\t\t\t\n\t\twhile True:\n\t\t\t#Only conditional that checks for conflicts\n\t\t\tif (tag_A=='insert' and tag_B=='insert' and char_A!=char_B) \\\n\t\t\t\tor (tag_A=='replace' and tag_B=='replace' and char_A!=char_B) \\\n\t\t\t\tor (tag_A=='delete' and tag_B=='replace') \\\n\t\t\t\tor (tag_A=='replace' and tag_B=='delete') \\\n\t\t\t\tor (tag_A==conflict_tag_A and tag_B==conflict_tag_B): \n\t\t\t\tconflicting = True\n\t\t\t\tconflict_tag_A = tag_A\n\t\t\t\tconflict_tag_B = tag_B\n\t\t\t\tconflict_block_A.append(char_A)\n\t\t\t\tconflict_block_B.append(char_B)\n\t\t\t\t[tag_A, char_A] = A_iter.next()\n\t\t\t\t[tag_B, char_B] = B_iter.next()\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tif conflicting: #triggers at the end of a conflicting block\n\t\t\t\tfile_blob.append_conflict(conflict_block_A, conflict_block_B, result_text)\n\t\t\t\tconflict_block_A = bytearray()\n\t\t\t\tconflict_block_B = bytearray()\n\t\t\t\tconflicting = False\n\t\t\t\tconflict_tag_A = ''\n\t\t\t\tconflict_tag_B = ''\n\t\t\t\n\t\t\tif (tag_A=='equal' and tag_B=='equal') \\\n\t\t\t\tor (tag_A=='insert' and tag_B=='insert' and char_A==char_B) \\\n\t\t\t\tor (tag_A=='replace' and tag_B=='replace' and char_A==char_B):\n\t\t\t\tresult_text.append(char_A)\n\t\t\t\t[tag_A, char_A] = A_iter.next()\n\t\t\t\t[tag_B, char_B] = B_iter.next()\n\t\t\t\tcontinue;\n\t\t\tif (tag_A=='equal' and tag_B=='delete') \\\n\t\t\t\tor (tag_A=='delete' and tag_B=='equal') \\\n\t\t\t\tor (tag_A=='delete' and tag_B=='delete'):\n\t\t\t\t[tag_A, char_A] = A_iter.next()\n\t\t\t\t[tag_B, char_B] = B_iter.next()\n\t\t\t\tcontinue;\n\t\t\tif tag_A=='equal' and tag_B=='replace':\n\t\t\t\tresult_text.append(char_B)\n\t\t\t\t[tag_A, char_A] = A_iter.next()\n\t\t\t\t[tag_B, char_B] = B_iter.next()\n\t\t\t\tcontinue;\n\t\t\tif tag_A=='replace' and tag_B=='equal':\n\t\t\t\tresult_text.append(char_A)\n\t\t\t\t[tag_A, char_A] = A_iter.next()\n\t\t\t\t[tag_B, char_B] = B_iter.next()\n\t\t\t\tcontinue;\n\t\t\tif tag_A=='EOF' and tag_B=='EOF':\n\t\t\t\tbreak\n\t\t\tif (tag_A=='insert') \\\n\t\t\t\tor (tag_B=='EOF'): #insert-delete, insert-equal, insert-replace, insert-EOF, equal-EOF, delete-EOF, replace-EOF. Should some of these be conflicts?\n\t\t\t\tresult_text.append(char_A) #@TODO: bug? delete-EOF shouldn't append\n\t\t\t\t[tag_A, char_A] = A_iter.next()\n\t\t\t\tcontinue;\n\t\t\tif (tag_B=='insert') \\\n\t\t\t\tor (tag_A=='EOF'):\n\t\t\t\tresult_text.append(char_B) #@TODO: bug? delete-EOF shouldn't append\n\t\t\t\t[tag_B, char_B] = B_iter.next()\n\t\t\t\tcontinue;\n\t\t\t\n\t\treturn result_text", "def mergeme(self, srcroot, destroot, outfile, secondhand, stufftomerge, cfgfiledict, thismtime):\n\n\t\tshowMessage = self._display_merge\n\t\twritemsg = self._display_merge\n\n\t\tos = _os_merge\n\t\tsep = os.sep\n\t\tjoin = os.path.join\n\t\tsrcroot = normalize_path(srcroot).rstrip(sep) + sep\n\t\tdestroot = normalize_path(destroot).rstrip(sep) + sep\n\t\tcalc_prelink = \"prelink-checksums\" in self.settings.features\n\n\t\tprotect_if_modified = \\\n\t\t\t\"config-protect-if-modified\" in self.settings.features and \\\n\t\t\tself._installed_instance is not None\n\n\t\t# this is supposed to merge a list of files. There will be 2 forms of argument passing.\n\t\tif isinstance(stufftomerge, basestring):\n\t\t\t#A directory is specified. Figure out protection paths, listdir() it and process it.\n\t\t\tmergelist = os.listdir(join(srcroot, stufftomerge))\n\t\t\toffset = stufftomerge\n\t\telse:\n\t\t\tmergelist = stufftomerge\n\t\t\toffset = \"\"\n\n\t\tfor i, x in enumerate(mergelist):\n\n\t\t\tmysrc = join(srcroot, offset, x)\n\t\t\tmydest = join(destroot, offset, x)\n\t\t\t# myrealdest is mydest without the $ROOT prefix (makes a difference if ROOT!=\"/\")\n\t\t\tmyrealdest = join(sep, offset, x)\n\t\t\t# stat file once, test using S_* macros many times (faster that way)\n\t\t\tmystat = os.lstat(mysrc)\n\t\t\tmymode = mystat[stat.ST_MODE]\n\t\t\t# handy variables; mydest is the target object on the live filesystems;\n\t\t\t# mysrc is the source object in the temporary install dir\n\t\t\ttry:\n\t\t\t\tmydstat = os.lstat(mydest)\n\t\t\t\tmydmode = mydstat.st_mode\n\t\t\texcept OSError as e:\n\t\t\t\tif e.errno != errno.ENOENT:\n\t\t\t\t\traise\n\t\t\t\tdel e\n\t\t\t\t#dest file doesn't exist\n\t\t\t\tmydstat = None\n\t\t\t\tmydmode = None\n\n\t\t\tif stat.S_ISLNK(mymode):\n\t\t\t\t# we are merging a symbolic link\n\t\t\t\t# The file name of mysrc and the actual file that it points to\n\t\t\t\t# will have earlier been forcefully converted to the 'merge'\n\t\t\t\t# encoding if necessary, but the content of the symbolic link\n\t\t\t\t# may need to be forcefully converted here.\n\t\t\t\tmyto = _os.readlink(_unicode_encode(mysrc,\n\t\t\t\t\tencoding=_encodings['merge'], errors='strict'))\n\t\t\t\ttry:\n\t\t\t\t\tmyto = _unicode_decode(myto,\n\t\t\t\t\t\tencoding=_encodings['merge'], errors='strict')\n\t\t\t\texcept UnicodeDecodeError:\n\t\t\t\t\tmyto = _unicode_decode(myto, encoding=_encodings['merge'],\n\t\t\t\t\t\terrors='replace')\n\t\t\t\t\tmyto = _unicode_encode(myto, encoding='ascii',\n\t\t\t\t\t\terrors='backslashreplace')\n\t\t\t\t\tmyto = _unicode_decode(myto, encoding=_encodings['merge'],\n\t\t\t\t\t\terrors='replace')\n\t\t\t\t\tos.unlink(mysrc)\n\t\t\t\t\tos.symlink(myto, mysrc)\n\n\t\t\t\t# Pass in the symlink target in order to bypass the\n\t\t\t\t# os.readlink() call inside abssymlink(), since that\n\t\t\t\t# call is unsafe if the merge encoding is not ascii\n\t\t\t\t# or utf_8 (see bug #382021).\n\t\t\t\tmyabsto = abssymlink(mysrc, target=myto)\n\n\t\t\t\tif myabsto.startswith(srcroot):\n\t\t\t\t\tmyabsto = myabsto[len(srcroot):]\n\t\t\t\tmyabsto = myabsto.lstrip(sep)\n\t\t\t\tif self.settings and self.settings[\"D\"]:\n\t\t\t\t\tif myto.startswith(self.settings[\"D\"]):\n\t\t\t\t\t\tmyto = myto[len(self.settings[\"D\"])-1:]\n\t\t\t\t# myrealto contains the path of the real file to which this symlink points.\n\t\t\t\t# we can simply test for existence of this file to see if the target has been merged yet\n\t\t\t\tmyrealto = normalize_path(os.path.join(destroot, myabsto))\n\t\t\t\tif mydmode!=None:\n\t\t\t\t\t#destination exists\n\t\t\t\t\tif stat.S_ISDIR(mydmode):\n\t\t\t\t\t\t# we can't merge a symlink over a directory\n\t\t\t\t\t\tnewdest = self._new_backup_path(mydest)\n\t\t\t\t\t\tmsg = []\n\t\t\t\t\t\tmsg.append(\"\")\n\t\t\t\t\t\tmsg.append(_(\"Installation of a symlink is blocked by a directory:\"))\n\t\t\t\t\t\tmsg.append(\" '%s'\" % mydest)\n\t\t\t\t\t\tmsg.append(_(\"This symlink will be merged with a different name:\"))\n\t\t\t\t\t\tmsg.append(\" '%s'\" % newdest)\n\t\t\t\t\t\tmsg.append(\"\")\n\t\t\t\t\t\tself._eerror(\"preinst\", msg)\n\t\t\t\t\t\tmydest = newdest\n\n\t\t\t\t\telif not stat.S_ISLNK(mydmode):\n\t\t\t\t\t\tif os.path.exists(mysrc) and stat.S_ISDIR(os.stat(mysrc)[stat.ST_MODE]):\n\t\t\t\t\t\t\t# Kill file blocking installation of symlink to dir #71787\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\telif self.isprotected(mydest):\n\t\t\t\t\t\t\t# Use md5 of the target in ${D} if it exists...\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tnewmd5 = perform_md5(join(srcroot, myabsto))\n\t\t\t\t\t\t\texcept FileNotFound:\n\t\t\t\t\t\t\t\t# Maybe the target is merged already.\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tnewmd5 = perform_md5(myrealto)\n\t\t\t\t\t\t\t\texcept FileNotFound:\n\t\t\t\t\t\t\t\t\tnewmd5 = None\n\t\t\t\t\t\t\tmydest = new_protect_filename(mydest, newmd5=newmd5)\n\n\t\t\t\t# if secondhand is None it means we're operating in \"force\" mode and should not create a second hand.\n\t\t\t\tif (secondhand != None) and (not os.path.exists(myrealto)):\n\t\t\t\t\t# either the target directory doesn't exist yet or the target file doesn't exist -- or\n\t\t\t\t\t# the target is a broken symlink. We will add this file to our \"second hand\" and merge\n\t\t\t\t\t# it later.\n\t\t\t\t\tsecondhand.append(mysrc[len(srcroot):])\n\t\t\t\t\tcontinue\n\t\t\t\t# unlinking no longer necessary; \"movefile\" will overwrite symlinks atomically and correctly\n\t\t\t\tmymtime = movefile(mysrc, mydest, newmtime=thismtime,\n\t\t\t\t\tsstat=mystat, mysettings=self.settings,\n\t\t\t\t\tencoding=_encodings['merge'])\n\n\t\t\t\ttry:\n\t\t\t\t\tself._merged_path(mydest, os.lstat(mydest))\n\t\t\t\texcept OSError:\n\t\t\t\t\tpass\n\n\t\t\t\tif mymtime != None:\n\t\t\t\t\tshowMessage(\">>> %s -> %s\\n\" % (mydest, myto))\n\t\t\t\t\tif sys.hexversion >= 0x3030000:\n\t\t\t\t\t\toutfile.write(\"sym \"+myrealdest+\" -> \"+myto+\" \"+str(mymtime // 1000000000)+\"\\n\")\n\t\t\t\t\telse:\n\t\t\t\t\t\toutfile.write(\"sym \"+myrealdest+\" -> \"+myto+\" \"+str(mymtime)+\"\\n\")\n\t\t\t\telse:\n\t\t\t\t\tshowMessage(_(\"!!! Failed to move file.\\n\"),\n\t\t\t\t\t\tlevel=logging.ERROR, noiselevel=-1)\n\t\t\t\t\tshowMessage(\"!!! %s -> %s\\n\" % (mydest, myto),\n\t\t\t\t\t\tlevel=logging.ERROR, noiselevel=-1)\n\t\t\t\t\treturn 1\n\t\t\telif stat.S_ISDIR(mymode):\n\t\t\t\t# we are merging a directory\n\t\t\t\tif mydmode != None:\n\t\t\t\t\t# destination exists\n\n\t\t\t\t\tif bsd_chflags:\n\t\t\t\t\t\t# Save then clear flags on dest.\n\t\t\t\t\t\tdflags = mydstat.st_flags\n\t\t\t\t\t\tif dflags != 0:\n\t\t\t\t\t\t\tbsd_chflags.lchflags(mydest, 0)\n\n\t\t\t\t\tif not os.access(mydest, os.W_OK):\n\t\t\t\t\t\tpkgstuff = pkgsplit(self.pkg)\n\t\t\t\t\t\twritemsg(_(\"\\n!!! Cannot write to '%s'.\\n\") % mydest, noiselevel=-1)\n\t\t\t\t\t\twritemsg(_(\"!!! Please check permissions and directories for broken symlinks.\\n\"))\n\t\t\t\t\t\twritemsg(_(\"!!! You may start the merge process again by using ebuild:\\n\"))\n\t\t\t\t\t\twritemsg(\"!!! ebuild \"+self.settings[\"PORTDIR\"]+\"/\"+self.cat+\"/\"+pkgstuff[0]+\"/\"+self.pkg+\".ebuild merge\\n\")\n\t\t\t\t\t\twritemsg(_(\"!!! And finish by running this: env-update\\n\\n\"))\n\t\t\t\t\t\treturn 1\n\n\t\t\t\t\tif stat.S_ISDIR(mydmode) or \\\n\t\t\t\t\t\t(stat.S_ISLNK(mydmode) and os.path.isdir(mydest)):\n\t\t\t\t\t\t# a symlink to an existing directory will work for us; keep it:\n\t\t\t\t\t\tshowMessage(\"--- %s/\\n\" % mydest)\n\t\t\t\t\t\tif bsd_chflags:\n\t\t\t\t\t\t\tbsd_chflags.lchflags(mydest, dflags)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# a non-directory and non-symlink-to-directory. Won't work for us. Move out of the way.\n\t\t\t\t\t\tbackup_dest = self._new_backup_path(mydest)\n\t\t\t\t\t\tmsg = []\n\t\t\t\t\t\tmsg.append(\"\")\n\t\t\t\t\t\tmsg.append(_(\"Installation of a directory is blocked by a file:\"))\n\t\t\t\t\t\tmsg.append(\" '%s'\" % mydest)\n\t\t\t\t\t\tmsg.append(_(\"This file will be renamed to a different name:\"))\n\t\t\t\t\t\tmsg.append(\" '%s'\" % backup_dest)\n\t\t\t\t\t\tmsg.append(\"\")\n\t\t\t\t\t\tself._eerror(\"preinst\", msg)\n\t\t\t\t\t\tif movefile(mydest, backup_dest,\n\t\t\t\t\t\t\tmysettings=self.settings,\n\t\t\t\t\t\t\tencoding=_encodings['merge']) is None:\n\t\t\t\t\t\t\treturn 1\n\t\t\t\t\t\tshowMessage(_(\"bak %s %s.backup\\n\") % (mydest, mydest),\n\t\t\t\t\t\t\tlevel=logging.ERROR, noiselevel=-1)\n\t\t\t\t\t\t#now create our directory\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tif self.settings.selinux_enabled():\n\t\t\t\t\t\t\t\t_selinux_merge.mkdir(mydest, mysrc)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tos.mkdir(mydest)\n\t\t\t\t\t\texcept OSError as e:\n\t\t\t\t\t\t\t# Error handling should be equivalent to\n\t\t\t\t\t\t\t# portage.util.ensure_dirs() for cases\n\t\t\t\t\t\t\t# like bug #187518.\n\t\t\t\t\t\t\tif e.errno in (errno.EEXIST,):\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\telif os.path.isdir(mydest):\n\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\traise\n\t\t\t\t\t\t\tdel e\n\n\t\t\t\t\t\tif bsd_chflags:\n\t\t\t\t\t\t\tbsd_chflags.lchflags(mydest, dflags)\n\t\t\t\t\t\tos.chmod(mydest, mystat[0])\n\t\t\t\t\t\tos.chown(mydest, mystat[4], mystat[5])\n\t\t\t\t\t\tshowMessage(\">>> %s/\\n\" % mydest)\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\t#destination doesn't exist\n\t\t\t\t\t\tif self.settings.selinux_enabled():\n\t\t\t\t\t\t\t_selinux_merge.mkdir(mydest, mysrc)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tos.mkdir(mydest)\n\t\t\t\t\texcept OSError as e:\n\t\t\t\t\t\t# Error handling should be equivalent to\n\t\t\t\t\t\t# portage.util.ensure_dirs() for cases\n\t\t\t\t\t\t# like bug #187518.\n\t\t\t\t\t\tif e.errno in (errno.EEXIST,):\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\telif os.path.isdir(mydest):\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise\n\t\t\t\t\t\tdel e\n\t\t\t\t\tos.chmod(mydest, mystat[0])\n\t\t\t\t\tos.chown(mydest, mystat[4], mystat[5])\n\t\t\t\t\tshowMessage(\">>> %s/\\n\" % mydest)\n\n\t\t\t\ttry:\n\t\t\t\t\tself._merged_path(mydest, os.lstat(mydest))\n\t\t\t\texcept OSError:\n\t\t\t\t\tpass\n\n\t\t\t\toutfile.write(\"dir \"+myrealdest+\"\\n\")\n\t\t\t\t# recurse and merge this directory\n\t\t\t\tif self.mergeme(srcroot, destroot, outfile, secondhand,\n\t\t\t\t\tjoin(offset, x), cfgfiledict, thismtime):\n\t\t\t\t\treturn 1\n\t\t\telif stat.S_ISREG(mymode):\n\t\t\t\t# we are merging a regular file\n\t\t\t\tmymd5 = perform_md5(mysrc, calc_prelink=calc_prelink)\n\t\t\t\t# calculate config file protection stuff\n\t\t\t\tmydestdir = os.path.dirname(mydest)\n\t\t\t\tmoveme = 1\n\t\t\t\tzing = \"!!!\"\n\t\t\t\tmymtime = None\n\t\t\t\tprotected = self.isprotected(mydest)\n\t\t\t\tif mydmode != None:\n\t\t\t\t\t# destination file exists\n\t\t\t\t\t\n\t\t\t\t\tif stat.S_ISDIR(mydmode):\n\t\t\t\t\t\t# install of destination is blocked by an existing directory with the same name\n\t\t\t\t\t\tnewdest = self._new_backup_path(mydest)\n\t\t\t\t\t\tmsg = []\n\t\t\t\t\t\tmsg.append(\"\")\n\t\t\t\t\t\tmsg.append(_(\"Installation of a regular file is blocked by a directory:\"))\n\t\t\t\t\t\tmsg.append(\" '%s'\" % mydest)\n\t\t\t\t\t\tmsg.append(_(\"This file will be merged with a different name:\"))\n\t\t\t\t\t\tmsg.append(\" '%s'\" % newdest)\n\t\t\t\t\t\tmsg.append(\"\")\n\t\t\t\t\t\tself._eerror(\"preinst\", msg)\n\t\t\t\t\t\tmydest = newdest\n\n\t\t\t\t\telif stat.S_ISREG(mydmode) or (stat.S_ISLNK(mydmode) and os.path.exists(mydest) and stat.S_ISREG(os.stat(mydest)[stat.ST_MODE])):\n\t\t\t\t\t\t# install of destination is blocked by an existing regular file,\n\t\t\t\t\t\t# or by a symlink to an existing regular file;\n\t\t\t\t\t\t# now, config file management may come into play.\n\t\t\t\t\t\t# we only need to tweak mydest if cfg file management is in play.\n\t\t\t\t\t\tif protected:\n\t\t\t\t\t\t\tdestmd5 = perform_md5(mydest, calc_prelink=calc_prelink)\n\t\t\t\t\t\t\tif protect_if_modified:\n\t\t\t\t\t\t\t\tcontents_key = \\\n\t\t\t\t\t\t\t\t\tself._installed_instance._match_contents(myrealdest)\n\t\t\t\t\t\t\t\tif contents_key:\n\t\t\t\t\t\t\t\t\tinst_info = self._installed_instance.getcontents()[contents_key]\n\t\t\t\t\t\t\t\t\tif inst_info[0] == \"obj\" and inst_info[2] == destmd5:\n\t\t\t\t\t\t\t\t\t\tprotected = False\n\n\t\t\t\t\t\tif protected:\n\t\t\t\t\t\t\t# we have a protection path; enable config file management.\n\t\t\t\t\t\t\tcfgprot = 0\n\t\t\t\t\t\t\tif mymd5 == destmd5:\n\t\t\t\t\t\t\t\t#file already in place; simply update mtimes of destination\n\t\t\t\t\t\t\t\tmoveme = 1\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif mymd5 == cfgfiledict.get(myrealdest, [None])[0]:\n\t\t\t\t\t\t\t\t\t\"\"\" An identical update has previously been\n\t\t\t\t\t\t\t\t\tmerged. Skip it unless the user has chosen\n\t\t\t\t\t\t\t\t\t--noconfmem.\"\"\"\n\t\t\t\t\t\t\t\t\tmoveme = cfgfiledict[\"IGNORE\"]\n\t\t\t\t\t\t\t\t\tcfgprot = cfgfiledict[\"IGNORE\"]\n\t\t\t\t\t\t\t\t\tif not moveme:\n\t\t\t\t\t\t\t\t\t\tzing = \"---\"\n\t\t\t\t\t\t\t\t\t\tif sys.hexversion >= 0x3030000:\n\t\t\t\t\t\t\t\t\t\t\tmymtime = mystat.st_mtime_ns\n\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tmymtime = mystat[stat.ST_MTIME]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tmoveme = 1\n\t\t\t\t\t\t\t\t\tcfgprot = 1\n\t\t\t\t\t\t\tif moveme:\n\t\t\t\t\t\t\t\t# Merging a new file, so update confmem.\n\t\t\t\t\t\t\t\tcfgfiledict[myrealdest] = [mymd5]\n\t\t\t\t\t\t\telif destmd5 == cfgfiledict.get(myrealdest, [None])[0]:\n\t\t\t\t\t\t\t\t\"\"\"A previously remembered update has been\n\t\t\t\t\t\t\t\taccepted, so it is removed from confmem.\"\"\"\n\t\t\t\t\t\t\t\tdel cfgfiledict[myrealdest]\n\n\t\t\t\t\t\t\tif cfgprot:\n\t\t\t\t\t\t\t\tmydest = new_protect_filename(mydest, newmd5=mymd5)\n\n\t\t\t\t# whether config protection or not, we merge the new file the\n\t\t\t\t# same way. Unless moveme=0 (blocking directory)\n\t\t\t\tif moveme:\n\t\t\t\t\t# Create hardlinks only for source files that already exist\n\t\t\t\t\t# as hardlinks (having identical st_dev and st_ino).\n\t\t\t\t\thardlink_key = (mystat.st_dev, mystat.st_ino)\n\n\t\t\t\t\thardlink_candidates = self._hardlink_merge_map.get(hardlink_key)\n\t\t\t\t\tif hardlink_candidates is None:\n\t\t\t\t\t\thardlink_candidates = []\n\t\t\t\t\t\tself._hardlink_merge_map[hardlink_key] = hardlink_candidates\n\n\t\t\t\t\tmymtime = movefile(mysrc, mydest, newmtime=thismtime,\n\t\t\t\t\t\tsstat=mystat, mysettings=self.settings,\n\t\t\t\t\t\thardlink_candidates=hardlink_candidates,\n\t\t\t\t\t\tencoding=_encodings['merge'])\n\t\t\t\t\tif mymtime is None:\n\t\t\t\t\t\treturn 1\n\t\t\t\t\thardlink_candidates.append(mydest)\n\t\t\t\t\tzing = \">>>\"\n\n\t\t\t\t\ttry:\n\t\t\t\t\t\tself._merged_path(mydest, os.lstat(mydest))\n\t\t\t\t\texcept OSError:\n\t\t\t\t\t\tpass\n\n\t\t\t\tif mymtime != None:\n\t\t\t\t\tif sys.hexversion >= 0x3030000:\n\t\t\t\t\t\toutfile.write(\"obj \"+myrealdest+\" \"+mymd5+\" \"+str(mymtime // 1000000000)+\"\\n\")\n\t\t\t\t\telse:\n\t\t\t\t\t\toutfile.write(\"obj \"+myrealdest+\" \"+mymd5+\" \"+str(mymtime)+\"\\n\")\n\t\t\t\tshowMessage(\"%s %s\\n\" % (zing,mydest))\n\t\t\telse:\n\t\t\t\t# we are merging a fifo or device node\n\t\t\t\tzing = \"!!!\"\n\t\t\t\tif mydmode is None:\n\t\t\t\t\t# destination doesn't exist\n\t\t\t\t\tif movefile(mysrc, mydest, newmtime=thismtime,\n\t\t\t\t\t\tsstat=mystat, mysettings=self.settings,\n\t\t\t\t\t\tencoding=_encodings['merge']) is not None:\n\t\t\t\t\t\tzing = \">>>\"\n\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tself._merged_path(mydest, os.lstat(mydest))\n\t\t\t\t\t\texcept OSError:\n\t\t\t\t\t\t\tpass\n\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn 1\n\t\t\t\tif stat.S_ISFIFO(mymode):\n\t\t\t\t\toutfile.write(\"fif %s\\n\" % myrealdest)\n\t\t\t\telse:\n\t\t\t\t\toutfile.write(\"dev %s\\n\" % myrealdest)\n\t\t\t\tshowMessage(zing + \" \" + mydest + \"\\n\")", "def merge_upd_all(config, gsys):\n for f in [\"upd_ewl\", \"upd_wl\", \"upd_nl\"]:\n config.update_process(sys=gsys)\n f_out = config.get_filename(f)\n if not f_out:\n logging.error(\"Cannot get merged upd name\")\n f_ins = []\n for s in gsys:\n config.update_process(sys=s)\n f_in = config.get_filename(f, check=True)\n if f_in:\n f_ins.append(f_in)\n if f == \"upd_ewl\":\n merge_upd(f_ins, f_out, \"EWL\")\n logging.info(f\"merge upd_ewl complete, file is {f_out}\")\n elif f == \"upd_wl\":\n merge_upd(f_ins, f_out, \"WL\")\n logging.info(f\"merge upd_wl complete, file is {f_out}\")\n else:\n intv = config.config['process_scheme']['intv']\n merge_upd(f_ins, f_out, \"NL\", int(intv))\n logging.info(f\"merge upd_nl complete, file is {f_out}\")\n\n config.update_process(sys=gsys)", "def encode():\n updates = []\n unmerged_filenames = set({})\n unmerged_bogus_filenames = set()\n\n for line in os.popen('git ls-files --unmerged').read().splitlines():\n meta, filename = line.split('\\t')\n mode, sha1hash, stage = meta.split(' ')\n if stage != \"0\":\n unmerged_filenames.add(filename)\n bogus_filename = filename + \".%s.%s\" % (stage, SPECIAL_SUFFIX1)\n unmerged_bogus_filenames.add(bogus_filename)\n updates += [\"%s %s 0\\t%s\" % (mode, sha1hash, bogus_filename)]\n\n if not updates:\n return\n\n update_index(updates)\n add(unmerged_filenames)\n checkout(unmerged_bogus_filenames)\n\n modified_list = []\n staged_list = []\n if os.path.exists(\".git/MERGE_MODE\"):\n # For MERGE_MODE, git won't let us do partial merges, so we need\n # to save aside all modified files that were not stage. Otheriwse,\n # we get 'fatal: cannot do a partial commit during a merge.'\n\n modified_list, staged_list = save_unstaged_changes_files(unmerged_filenames)\n\n shutil.copy(\".git/MERGE_HEAD\", SPECIAL_FILENAME_MERGE_HEAD)\n shutil.copy(\".git/MERGE_MSG\", SPECIAL_FILENAME_MERGE_MSG)\n shutil.copy(\".git/MERGE_MODE\", SPECIAL_FILENAME_MERGE_MODE)\n\n add([SPECIAL_FILENAME_MERGE_HEAD,\n SPECIAL_FILENAME_MERGE_MSG,\n SPECIAL_FILENAME_MERGE_MODE])\n\n content = SPECIAL_MERGE_COMMIT_PREFIX + open(\".git/MERGE_MSG\").read()\n f = open(\".git/MERGE_MSG\", \"w\")\n f.write(content)\n f.close()\n\n params = ['git', 'commit', '-a', '--no-edit']\n else:\n params = ['git', 'commit', '-m', \"GIT_BOTTLE_STATE: unmerged-paths-normalization\",\n '--'] + (list(unmerged_bogus_filenames) +\n list(unmerged_filenames))\n\n r = os.spawnvp(os.P_WAIT, 'git', params)\n if staged_list:\n lst = []\n for filename_temp, filename in staged_list:\n os.rename(filename_temp, filename)\n lst += [filename]\n add(lst)\n\n for filename_temp, filename in modified_list:\n os.rename(filename_temp, filename)\n\n if r != 0:\n print >>sys.stderr, \"git-commit failed (%d)\" % (r, )\n sys.exit(r)", "def file_merge(infiles, outfile=None, header=1, verbose=1):\n outfile = outfile or \"_merged\".join(os.path.splitext(infiles[0]))\n out_f, outfile = safewfile(outfile)\n if verbose:\n print(\"Merging...\")\n cnt = 0\n for i, fn in enumerate(infiles):\n print(os.path.split(fn)[1], \"...\", end=\"\")\n line_no = 0\n in_f = anyfile(fn)\n if i > 0:\n for k in range(header):\n in_f.readline()\n del k\n for line in in_f:\n out_f.write(line)\n line_no += 1\n in_f.close()\n cnt += line_no\n print(line_no)\n out_f.close()\n print(\"=\" * 20)\n print(\"Done![total %d lines output]\" % cnt)", "def fix_lockfile(self):\n with open(self.outfile, 'rt') as fp:\n lines = [\n self.fix_pin(line)\n for line in self.concatenated(fp)\n ]\n with open(self.outfile, 'wt') as fp:\n fp.writelines([\n line + '\\n'\n for line in lines\n if line is not None\n ])\n self._dedup.register_packages_for_env(self.name, self.packages)", "def test_merge_from_file(self) -> None:\n import pkg_resources\n\n base_yaml = pkg_resources.resource_filename(__name__, \"configs/base.yaml\")\n config_yaml = pkg_resources.resource_filename(__name__, \"configs/config.yaml\")\n config_multi_base_yaml = pkg_resources.resource_filename(\n __name__, \"configs/config_multi_base.yaml\"\n )\n\n cfg = TestCfgNode.gen_default_cfg()\n cfg.merge_from_file(base_yaml)\n self.assertEqual(cfg.KEY1, \"base\")\n self.assertEqual(cfg.KEY2, \"base\")\n\n cfg = TestCfgNode.gen_default_cfg()\n\n with self.assertRaisesRegex(ConstructorError, \"python/object/apply:eval\"):\n # config.yaml contains unsafe yaml tags,\n # test if an exception is thrown\n cfg.merge_from_file(config_yaml)\n\n cfg.merge_from_file(config_yaml, allow_unsafe=True)\n self.assertEqual(cfg.KEY1, \"base\")\n self.assertEqual(cfg.KEY2, \"config\")\n self.assertEqual(cfg.EXPRESSION, [1, 4, 9])\n\n cfg = TestCfgNode.gen_default_cfg()\n cfg.merge_from_file(config_multi_base_yaml, allow_unsafe=True)\n self.assertEqual(cfg.KEY1, \"base2\")\n self.assertEqual(cfg.KEY2, \"config\")", "def merge_overlap_regions(\n histone_overlap_files,\n out_master_bed,\n # end here\n\n args, histone, method=\"atac_midpoint\", filter_w_overlap=True):\n # set up naive overlap based master regions\n logging.info(\"HISTONE: {}: Generating master regions...\".format(histone))\n args.chipseq[\"histones\"][histone][\"overlap_master_regions\"] = \"{0}/ggr.{1}.overlap.master.bed.gz\".format(\n args.folders[\"data_dir\"], histone)\n if not os.path.isfile(args.chipseq[\"histones\"][histone][\"overlap_master_regions\"]):\n histone_overlap_files = sorted(\n glob.glob(\"{0}/{1}\".format(\n args.chipseq[\"data_dir\"], args.chipseq[\"histones\"][histone][\"overlap_glob\"])))\n logging.info(\"Master regions using: {}\".format(\" \".join(histone_overlap_files)))\n merge_regions(histone_overlap_files, args.chipseq[\"histones\"][histone][\"overlap_master_regions\"])\n \n if method == \"atac_midpoint\":\n # If centered on ATAC region midpoint, then extract the midpoint and then extend out with bedtools slop\n args.atac[\"master_slop_bed\"] = \"{}.slop_{}bp.bed.gz\".format(\n args.atac[\"master_bed\"].split(\".bed\")[0],\n args.params[\"histones\"][histone][\"overlap_extend_len\"])\n # this bit actually belongs in ATAC? integrative?\n if not os.path.isfile(args.atac[\"master_slop_bed\"]):\n slop_bed = (\n \"zcat {0} | \"\n \"awk -F '\\t' 'BEGIN{{OFS=\\\"\\t\\\"}} \"\n \"{{ midpoint=$2+int(($3-$2)/2); \"\n \"$2=midpoint; $3=midpoint+1; print }}' | \"\n \"bedtools slop -i stdin -g {1} -b {2} | \"\n \"gzip -c > {3}\").format(\n args.atac[\"master_bed\"],\n args.annot[\"chromsizes\"],\n args.params[\"histones\"][histone][\"overlap_extend_len\"],\n args.atac[\"master_slop_bed\"])\n print slop_bed\n run_shell_cmd(slop_bed)\n\n if filter_w_overlap:\n # now intersect ATAC with the naive overlap files and only keep region if has an overlap\n args.chipseq[\"histones\"][histone][\"master_slop_marked_bed\"] = \"{}.{}-marked.bed.gz\".format(\n args.atac[\"master_slop_bed\"].split(\".bed\")[0],\n histone)\n if not os.path.isfile(args.chipseq[\"histones\"][histone][\"master_slop_marked_bed\"]):\n keep_marked = (\n \"bedtools intersect -u -a {0} -b {1} | \"\n \"gzip -c > {2}\").format(\n args.atac[\"master_slop_bed\"],\n args.chipseq[\"histones\"][histone][\"overlap_master_regions\"],\n args.chipseq[\"histones\"][histone][\"master_slop_marked_bed\"])\n print keep_marked\n run_shell_cmd(keep_marked)\n master_regions = args.chipseq[\"histones\"][histone][\"master_slop_marked_bed\"]\n \n else:\n master_regions = args.atac[\"master_slop_bed\"]\n\n elif method == \"naive_overlap\":\n # If naive overlap, don't do anything extra - already generated the master file\n master_regions = args.chipseq[\"histones\"][histone][\"overlap_master_regions\"]\n\n else:\n raise Exception(\"non existent master regions method!\")\n \n return master_regions", "def fix_up(self):\n\n # get the offset to the fix up array\n offset = unpack(\"<H\", self._entry[4:6])[0]\n print (\"Offset to fix up array: %d\" % offset)\n\n # get the number of entries in the fix up array\n num = unpack(\"<H\", self._entry[6:8])[0]\n print (\"Number of entries in the fix up array: %d\" % num)\n\n # get the fixup signature\n signature = ''.join('{:02x}'.format(b) for b in reversed(self._entry[offset:offset + 2]))\n print (\"Fixup sig: 0x\" + signature)\n\n # read in the fixup array\n fixup_array = []\n for i in range(0, num - 1):\n fixup_array.append(self._entry[offset + 2 + i * 2: offset + 4 + i * 2])\n\n # overwrite proper values\n temp_entry = [] # cannot overwrite bytes without making a new array\n current_offset = 0\n\n for i in range(0, num - 1):\n sector_offset = 510 * (i + 1) + i * 2\n\n bytes = \"0x\" + ''.join('{:02x}'.format(b) for b in\n reversed(self._entry[sector_offset:sector_offset + 2]))\n print (\"Bytes %d/%d %s;\" % (sector_offset, sector_offset + 1, bytes), end=\" \")\n\n print (\"Overwriting 0x%s into bytes %d/%d\" %\n (''.join('{:02x}'.format(b) for b in reversed(fixup_array[i])),\n sector_offset, sector_offset + 1))\n\n # add sector up until last two bytes\n temp_entry.extend(self._entry[current_offset:sector_offset])\n\n # add fixup value\n temp_entry.extend(fixup_array[i])\n\n # replace value in the fixup array with the one on disk\n fixup_array[i] = self._entry[sector_offset:sector_offset + 2]\n\n # update offset\n current_offset = sector_offset + 2\n\n # create temp_entry as bytearray\n temp_entry = bytearray(temp_entry)\n self._entry = temp_entry # overwrite the bytes in memory\n\n print (\"\")", "def intersect_wrap(paths, intersecters, outdir, extendby=20):\n #hg19 = '/home/jorgsk/work/3UTR/ext_files/hg19'\n hg19 = '/users/rg/jskancke/phdproject/3UTR/the_project/ext_files/hg19'\n\n # function used only here\n def extender(extendby, path, hg19, ext_path):\n cmd1 = ['slopBed', '-b', str(extendby), '-i', path, '-g', hg19]\n p1 = Popen(cmd1, stdout = open(ext_path, 'wb'))\n p1.wait()\n\n # 1) extend all files\n for pathname, path in paths.items():\n # skip those you don't want\n if pathname not in intersecters:\n continue\n\n ext_name = pathname+'_extended_{0}'.format(extendby)\n ext_path = os.path.join(outdir, ext_name)\n\n # if you have extended already, don't do it again\n if ext_name in paths:\n continue\n\n extender(extendby, path, hg19, ext_path)\n paths[ext_name] = ext_path\n\n # there are 4 intersections to be performed:\n # AIB, AIC, BIC, and AIBIC\n\n for r in [2, 3]:\n combinations = list(combins(intersecters, r))\n for combo in combinations:\n combo = sorted(combo)\n\n isect_name = '_I_'.join(combo) # sort to access easier\n isect_path = os.path.join(outdir, isect_name)\n\n if len(combo) == 2:\n # refer to the extended files\n (filea, fileb) = [paths[combo[0]+'_extended_{0}'.format(extendby)],\n paths[combo[1]+'_extended_{0}'.format(extendby)]]\n\n if len(combo) == 3:\n # 1) extend the intersection that exists of the first two\n orig_name = '_I_'.join(combo[:-1])\n orig_path = os.path.join(outdir, orig_name)\n ext_name = '_I_'.join(combo[:-1])+'_extended_{0}'.format(extendby)\n ext_path = os.path.join(outdir, ext_name)\n extender(extendby, orig_path, hg19, ext_path)\n # 2) Use the extended intersection as file a and the normal as b\n # Why is this one so sensitive to extendby?\n (filea, fileb) = (ext_path,\n paths[combo[2]+'_extended_{0}'.format(extendby)])\n\n cmd2 = ['intersectBed', '-wa', '-s', '-a', filea, '-b', fileb]\n p2 = Popen(cmd2, stdout=PIPE )\n\n out_handle = open(isect_path, 'wb')\n for line in p2.stdout:\n # re-center the intersection\n if len(line.split()) == 6:\n (chrm, beg, end, name, val, strnd) = line.split()\n\n if len(line.split()) == 4:\n (chrm, beg, end, strnd) = line.split()\n\n center_dist = math.ceil((int(end)-int(beg))/2)\n center = int(int(end) - center_dist)\n\n # write the center of the new mergers\n out_handle.write('\\t'.join([chrm, str(center), str(center+1), '0',\n '0', strnd]) + '\\n')\n out_handle.close()\n paths[isect_name] = isect_path\n\n return paths", "def MakeRecoveryPatch(output_zip, recovery_img, boot_img):\n\n d = common.Difference(recovery_img, boot_img)\n _, _, patch = d.ComputePatch()\n common.ZipWriteStr(output_zip, \"recovery/recovery-from-boot.p\", patch)\n Item.Get(\"system/recovery-from-boot.p\", dir=False)\n\n boot_type, boot_device = common.GetTypeAndDevice(\"/boot\", OPTIONS.info_dict)\n recovery_type, recovery_device = common.GetTypeAndDevice(\"/recovery\", OPTIONS.info_dict)\n\n # Images with different content will have a different first page, so\n # we check to see if this recovery has already been installed by\n # testing just the first 2k.\n HEADER_SIZE = 2048\n header_sha1 = sha.sha(recovery_img.data[:HEADER_SIZE]).hexdigest()\n sh = \"\"\"#!/system/bin/sh\nif ! applypatch -c %(recovery_type)s:%(recovery_device)s:%(header_size)d:%(header_sha1)s; then\n log -t recovery \"Installing new recovery image\"\n applypatch %(boot_type)s:%(boot_device)s:%(boot_size)d:%(boot_sha1)s %(recovery_type)s:%(recovery_device)s %(recovery_sha1)s %(recovery_size)d %(boot_sha1)s:/system/recovery-from-boot.p\nelse\n log -t recovery \"Recovery image already installed\"\nfi\n\"\"\" % { 'boot_size': boot_img.size,\n 'boot_sha1': boot_img.sha1,\n 'header_size': HEADER_SIZE,\n 'header_sha1': header_sha1,\n 'recovery_size': recovery_img.size,\n 'recovery_sha1': recovery_img.sha1,\n 'boot_type': boot_type,\n 'boot_device': boot_device,\n 'recovery_type': recovery_type,\n 'recovery_device': recovery_device,\n }\n common.ZipWriteStr(output_zip, \"recovery/etc/install-recovery.sh\", sh)\n return Item.Get(\"system/etc/install-recovery.sh\", dir=False)", "def merge_modified_section_data(self):\n\n for section in self.sections:\n section_data_start = self.adjust_FileAlignment( section.PointerToRawData,\n self.OPTIONAL_HEADER.FileAlignment )\n section_data_end = section_data_start+section.SizeOfRawData\n if section_data_start < len(self.__data__) and section_data_end < len(self.__data__):\n self.__data__ = self.__data__[:section_data_start] + section.get_data() + self.__data__[section_data_end:]", "def _merge_beds(in_beds, final_db):\n if len(in_beds) == 1:\n out_file = in_beds[0]\n else:\n out_file = \"%s.bed\" % os.path.splitext(final_db)[0]\n cmd = \"cat %s | sort -k1,1 -k2,2n > %s\" % (\" \".join(in_beds), out_file)\n subprocess.check_call(cmd, shell=True)\n subprocess.check_call([\"bgzip\", \"-f\", out_file])\n bgzip_out = out_file + \".gz\"\n subprocess.check_call([\"tabix\", \"-p\", \"bed\", \"-f\", bgzip_out])\n return bgzip_out" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all 'Nitrokey FIDO2' devices
def list() -> None: devs = nkfido2.find_all() local_print(":: 'Nitrokey FIDO2' keys") for c in devs: assert isinstance(c.dev, CtapHidDevice) descr = c.dev.descriptor if hasattr(descr, "product_name"): name = descr.product_name elif c.is_bootloader(): name = "FIDO2 Bootloader device" else: name = "FIDO2 device" if hasattr(descr, "serial_number"): id_ = descr.serial_number else: assert isinstance(descr.path, str) id_ = descr.path local_print(f"{id_}: {name}")
[ "def list_devices(self):\n pass", "def get_device_list():\n token = get_auth_token() # Get Token\n url = \"https://{}/api/v1/network-device/1/10\".format(DNAC_URL)\n hdr = {'x-auth-token': token, 'content-type' : 'application/json'}\n resp = requests.get(url, headers=hdr) # Make the Get Request\n device_list = resp.json()\n print_device_list(device_list)", "def show_devices():\n pushbullet = PushBullet(api_key)\n for i, device in enumerate(pushbullet.devices):\n print '[{}] --> {} ({})'.format(i, device.nickname, device.device_iden)", "async def get_device_names(self):\n msg = self.construct_message('{\"cmdId\":' + str(Command.GET_DEVICE_NAME.value) + ',\"device_ID\":0}')\n await self.send_data(msg)", "def listDevices():\n return Controller().listDevices()", "def list_devices():\n devs = find_all_vkb()\n if not devs:\n print(\"No VKB devices found\")\n return\n\n for i, dev in enumerate(devs):\n print(f\" {i:>2}: {dev.name} ({dev.guid})\")", "def MC2000BListDevices():\n str = create_string_buffer(1024, '\\0')\n result = List(str)\n devicesStr = str.raw.decode(\"utf-8\").rstrip('\\x00').split(',')\n length = len(devicesStr)\n i = 0\n devices = []\n devInfo = [\"\",\"\"]\n while(i < length):\n str = devicesStr[i]\n if (i % 2 == 0):\n if str != '':\n devInfo[0] = str\n else:\n i+=1\n else:\n if(str.find(\"MC2000B\") >= 0):\n isFind = True\n devInfo[1] = str\n devices.append(devInfo.copy())\n i+=1\n return devices", "def ios_device_list(self) -> 'outputs.IosDeviceListResponse':\n return pulumi.get(self, \"ios_device_list\")", "def get_devices():\n print(\"Scanning for available devices.\")\n nearby_devices = bluetooth.discover_devices()\n out = {}\n for bdaddr in nearby_devices:\n name = bluetooth.lookup_name(bdaddr)\n out[name] = bdaddr\n if out is not None:\n print(\"Found the following devices:\")\n print_devices(out)\n print(\"\")\n else:\n print(\"Found no devices.\")\n return(out)", "def listInputDevices():\n pass", "def EnumerateDevices(self):\n raise NotImplementedError()", "def list_devices():\n out = subprocess.check_output([\"colormgr\", \"get-devices-by-kind\", \"display\"])\n for line in out.decode(\"utf8\").split(\"\\n\"):\n if line.startswith(\"Model:\"):\n print(line.split(\":\")[1].lstrip())", "def getDevices():\n\n # Create a list\n suitable_devices = []\n\n # Iterate over each device\n for i in range(p.get_device_count()):\n # Extract device metadata (note: there is more available)\n d = {}\n d['name'] = p.get_device_info_by_index(i)['name'].split(':')[0]\n d['dev_index'] = i\n d['rate'] = int(p.get_device_info_by_index(i)['defaultSampleRate'])\n d['channels'] = p.get_device_info_by_index(i)['maxInputChannels']\n\n # Check if device has input channels and isn't the default fake device\n if (d['channels'] >= 1 and d['name'] != 'default'):\n # Save it to list\n suitable_devices.append(d)\n\n return suitable_devices", "def getIdevices(self):\n return self.extended + self.generic", "def find_devices(controller):\n pysicl.gpib_timeout(500)\n for addr in range(1,31):\n print addr\n if addr != 21:\n status = dev_status(controller+str(addr))\n print addr,status\n if status > -1:\n print addr,\":\",status\n pysicl.gpib_timeout(10000)", "def get_devices():\n url = 'https://www.chromium.org/chromium-os/developer-information-for-chrome-os-devices'\n response = requests.get(url)\n response.raise_for_status()\n html = response.text.split('<table id=\"goog-ws-list-table\"')[1].split('</table>')[0]\n html = '<table id=\"goog-ws-list-table\"' + html + '</table>'\n table = ET.XML(html.encode('utf-8'))\n keys = [k.text for k in table[0][0]]\n devices = []\n for row in table[1]:\n device = dict()\n for num, value in enumerate(row):\n device[keys[num]] = None\n if value.text:\n device[keys[num]] = value.text.strip()\n elif list(value)[0].text:\n device[keys[num]] = list(value)[0].text.strip()\n devices.append(device)\n return devices", "def usb_devices(self):\n\t\tif not self.is_connected:\n\t\t\treturn []\n\n\t\tself.__write(\"info usb\")\n\t\tdata = self.__read()\n\t\tresult = []\n\n\t\tif not data:\n\t\t\treturn result\n\n\t\tfor line in data.splitlines():\n\t\t\tif line[0] != \" \":\n\t\t\t\tcontinue\n\n\t\t\t# Split line to harvest info\n\t\t\tline = line.strip().replace(\", \", \",\").split(\",\")\n\t\t\tdevice = {}\n\n\t\t\t# Add info about device to dict\n\t\t\tfor element in line:\n\t\t\t\tkey = element.lower().split(\" \")[0]\n\n\t\t\t\t# ID: means the device has user-supplied ID on the host\n\t\t\t\tif key == \"id:\":\n\t\t\t\t\tdevice[\"userid\"] = element[4:]\n\t\t\t\telse:\n\t\t\t\t\tdevice[key] = element[len(key)+1:]\n\n\t\t\t# Add device to the result\n\t\t\tresult.append(device)\n\n\t\treturn result", "def enumerateDevices():\n names = []\n try:\n names = [name for name in runCommand([\"vdo\", \"list\"]).splitlines()\n if len(name) > 0]\n paths = [os.path.sep.join([\"\", \"dev\", \"mapper\", name]) for name in names]\n names = filter(os.path.exists, paths)\n except CommandError as e:\n print(_(\"Error enumerating VDO devices: {0}\".format(e)), file=sys.stderr)\n return names", "def _do_discover_devices(self):\n devices = pywemo.discover_devices()\n return devices" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output COUNT number of random bytes, hexencoded.
def hexbytes(count: int, serial: Optional[str]) -> None: if not 0 <= count <= 255: local_critical(f"Number of bytes must be between 0 and 255, you passed {count}") local_print(nkfido2.find(serial).get_rng(count).hex())
[ "def sample_checkCOUNT(self):\n self.open.write('SAMPLE:COUNT?')\n reply = self.open.read() \n return('Sample Count: ' + str(reply))", "def count_cmd(self):\r\n package = \"{0}:{1}\".format(self.ID, \"count\")\r\n return self.encode(package)", "def read_hex(count):\n global bytesRead\n bytesRead += count\n\n chars = f.read(count)\n c = 0\n result = ''\n for i in chars:\n result += format(i, '02x') + ' '\n c += 1\n if c % 4 == 0 and c < count - 1:\n result += ' '\n\n return result", "def output(bytes: list) -> int:\r\n\r\n byte_size = 0\r\n for byte in bytes:\r\n byte_size += byte\r\n print(\"Size nginx equals:\\t\\t\", byte_size, \"bytes!\")", "def number4(dict):\r\n keys = list(dict.keys())\r\n vals = list(dict.values())\r\n\r\n for i in range(len(keys)):\r\n print('The character \"{}\" has been generated {} times.'.format(keys[i], vals[i]))\r\n\r\n num_chars = find_num_chars(dict)\r\n print('\\nThere have been a total of {} characters generated.'.format(num_chars))", "def ue_count(self) -> str:\n return self.run_device_command(\"ue-count\")[0]", "def random_hex(cls):\n random.seed()\n return hashlib.sha224(time.asctime(time.gmtime()) + str(random.randint(1, 100000))).hexdigest()", "def set_random_hex() -> int:\n return random.randint(0, 255)", "def count() -> int:\n return _api_calls.get(Inner._VIDEO_SAMPLE_ENDPOINT + \"count\").json()", "def GenSS(COUNT, OUT):\n count = COUNT.receive_once()\n OUT.send(Packet.Type.OPEN)\n\n for i in range(count):\n s = \"%06d\" % (count - i)\n OUT.send(s)\n if i < count - 1: # prevent empty bracket pair at end\n if i % 5 == 5 - 1:\n OUT.send(Packet.Type.CLOSE)\n OUT.send(Packet.Type.OPEN)\n OUT.send(Packet.Type.CLOSE)", "def hashFunctionTest():\n m = 128\n h = HashFunction(m)\n print(h)\n\n count = [0] * m\n for i in range(m*2):\n count[h.h(random.randint(-10000,10000))] += 1\n print count", "def test_generate_random_table( self ) :\n print( \"\\ntest_generate_random_table\" )\n self.test_name = 'test_generate_random_table'\n\n self.setUp()\n\n str_random_table = generate_random_table( self.the_rnt, 4096, 64 )\n\n # that is strings, so need an integer array\n the_program = '\\nN_K_RANDOM_BYTES=[\\n' + \\\n str_random_table + ']\\n'\n\n N_K_RANDOM_BYTES = convert_string( the_program )\n \n self.assertTrue( count_duplicates( N_K_RANDOM_BYTES ) == 0 )\n self.assertTrue( count_zeros( N_K_RANDOM_BYTES ) == 0 )", "async def quote_count():\n await bot.type()\n result = varQuote.count()\n await bot.say(result)", "def trigger_checkCOUNT(self):\n self.open.write('TRIGGER:COUNT?')\n reply = self.open.read() \n return('Trigger Count: ' + str(reply))", "def _generate_nonce(n):\n\n return base64.b16encode(os.urandom(n/8))", "def get_hexadecimal_random_number():\n return \"\".join([random.choice('0123456789abcdef') for _ in range(16)])", "def test_random(self):\n random_nonce = Nonce.random()\n self.assertEqual(len(random_nonce), Nonce.LEN)", "def random_data():\n return binascii.b2a_hex(os.urandom(31)).decode('utf-8')", "def get_scancount(self):\r\n command = \":scan:count?\\n\"\r\n self._log_write(command, mode=\"write\")\r\n self.ser.write(command)\r\n answer = self.ser.read(6)\r\n self._log_write(answer, mode=\"read\")\r\n rlvalue = int(answer[:-2])\r\n self.Stat = self.Stat._replace(scancount=rlvalue)\r\n return rlvalue" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses `hmacsecret` to implement a challengeresponse mechanism. We abuse hmacsecret, which gives us `HMAC(K, hash(challenge))`, where `K` is a secret tied to the `credential_id`. We hash the challenge first, since a 32 byte value is expected (in original usage, it's a salt). This means that we first need to setup a credential_id; this depends on the specific authenticator used. To do this, use `nitropy fido2 makecredential`. If so desired, user and relying party can be changed from the defaults. The prompt can be suppressed using `prompt ""`.
def challenge_response( serial: Optional[str], host: str, user: str, prompt: str, credential_id: str, challenge: str, udp: bool, ) -> None: nkfido2.find().simple_secret( credential_id, challenge, host=host, user_id=user, serial=serial, prompt=prompt, output=True, udp=udp, )
[ "def hash_challenge(amt: str, challenge: str) -> str:\n h = hmac.new(amt.encode(), challenge.encode(), hashlib.sha256)\n return h.hexdigest()", "def generate_authenticator_response(nt_response,peer_challenge,authenticator_challenge,username,password=False,password_hash=False):\n Magic1=\"\\x4D\\x61\\x67\\x69\\x63\\x20\\x73\\x65\\x72\\x76\\x65\\x72\\x20\\x74\\x6F\\x20\\x63\\x6C\\x69\\x65\\x6E\\x74\\x20\\x73\\x69\\x67\\x6E\\x69\\x6E\\x67\\x20\\x63\\x6F\\x6E\\x73\\x74\\x61\\x6E\\x74\"\n Magic2=\"\\x50\\x61\\x64\\x20\\x74\\x6F\\x20\\x6D\\x61\\x6B\\x65\\x20\\x69\\x74\\x20\\x64\\x6F\\x20\\x6D\\x6F\\x72\\x65\\x20\\x74\\x68\\x61\\x6E\\x20\\x6F\\x6E\\x65\\x20\\x69\\x74\\x65\\x72\\x61\\x74\\x69\\x6F\\x6E\"\n\n # the2nd: modifed for OTPme to allow verification without the need to have a clear-text password\n # if we got a password we have to generate its hash and hash_hash\n if password:\n password_hash=nt_password_hash(password,False)\n password_hash_hash=hash_nt_password_hash(password_hash)\n elif password_hash:\n # if we got the password_hash we only have to generate the hash_hash\n password_hash_hash=hash_nt_password_hash(password_hash)\n\n sha_hash=sha.new()\n sha_hash.update(password_hash_hash)\n sha_hash.update(nt_response)\n sha_hash.update(Magic1)\n digest=sha_hash.digest()\n\n challenge=challenge_hash(peer_challenge,authenticator_challenge,username)\n\n sha_hash=sha.new()\n sha_hash.update(digest)\n sha_hash.update(challenge)\n sha_hash.update(Magic2)\n digest=sha_hash.digest()\n\n return \"S=\"+convert_to_hex_string(digest)", "def generate_nt_response_mschap2(authenticator_challenge,peer_challenge,username,password):\n challenge=challenge_hash(peer_challenge,authenticator_challenge,username)\n password_hash=nt_password_hash(password)\n return challenge_response(challenge,password_hash)", "def generate_nt_response_mschap(challenge,password):\n password_hash=nt_password_hash(password)\n return challenge_response(challenge,password_hash)", "def challenge_hash(peer_challenge,authenticator_challenge,username):\n sha_hash=sha.new()\n sha_hash.update(peer_challenge)\n sha_hash.update(authenticator_challenge)\n sha_hash.update(username)\n return sha_hash.digest()[:8]", "def obtain_credential(\n pk: PublicKey,\n response: BlindSignature,\n state: RequestState\n ) -> AnonymousCredential:\n\n signature1, signature2 = jsonpickle.decode(response[0][0]), jsonpickle.decode(response[0][1])\n\n t = jsonpickle.decode(state[0])\n\n #compute final siganture with the t sampled during the issue request\n final_signature = (jsonpickle.encode(signature1)\n ,jsonpickle.encode(signature2/(signature1.pow(t))))\n\n # getting the ordered list of credentials from issuer and user attributes\n issuer_attributes = response[1]\n user_attributes = state[1]\n\n credentials_dic = dict(issuer_attributes)\n credentials_dic.update(user_attributes)\n\n #putting them in the right order (order is very important, since part of the signature on the credentials is based on it)\n credentials = []\n for i in sorted (credentials_dic.keys()):\n credentials.append(credentials_dic[i])\n\n #checking if signature is valid for these credentials\n assert verify(pk, final_signature, credentials)\n\n return credentials, final_signature", "def calculate_pbkdf2_response(challenge: str, password: str) -> str:\n challenge_parts = challenge.split(\"$\")\n # Extract all necessary values encoded into the challenge\n iter1 = int(challenge_parts[1])\n salt1 = bytes.fromhex(challenge_parts[2])\n iter2 = int(challenge_parts[3])\n salt2 = bytes.fromhex(challenge_parts[4])\n # Hash twice, once with static salt...\n # Once with dynamic salt.\n hash1 = hashlib.pbkdf2_hmac(\"sha256\", password.encode(), salt1, iter1)\n hash2 = hashlib.pbkdf2_hmac(\"sha256\", hash1, salt2, iter2)\n return f\"{challenge_parts[4]}${hash2.hex()}\"", "def make_pwhash(algo, password, iterations):\n salt = binascii.hexlify(os.urandom(16))\n hsh = pbkdf2_hmac(algo, password.encode(), salt, iterations)\n hsh = binascii.hexlify(hsh)\n hsh = \"%s$%s$%s\" % (algo, salt.decode(), hsh.decode())\n return hsh", "def calculate_md5_response(challenge: str, password: str) -> str:\n response = challenge + \"-\" + password\n # the legacy response needs utf_16_le encoding\n response = response.encode(\"utf_16_le\")\n md5_sum = hashlib.md5()\n md5_sum.update(response)\n response = challenge + \"-\" + md5_sum.hexdigest()\n return response", "def getDigestResponse(self, challenge, ncount):\n nonce = challenge.get('nonce')\n algo = challenge.get('algorithm').lower()\n qop = challenge.get('qop')\n\n expected = digest.calcResponse(\n digest.calcHA1(algo,\n \"username\",\n \"test realm\",\n \"password\",\n nonce,\n cnonce),\n algo, nonce, ncount, cnonce, qop, \"GET\", \"/write/\", None\n )\n return expected", "async def secret_reveal(self, ctx: commands.Context, digest):\n pass", "def oauth():\n print _get_rand_hash()\n print _get_rand_hash()", "def HA1(realm, username, password, algorithm):\n if not realm:\n realm = u''\n return H(b\":\".join([username.encode('utf-8'),\n realm.encode('utf-8'),\n password.encode('utf-8')]), algorithm)", "def Radius_User_Password(password, secret, authenticator):\r\n password_length = struct.pack(\"!B\",len(password))\r\n padd_size = 16 - (len(password) % 16)\r\n \r\n try:\r\n p = password.encode(\"utf-8\")\r\n except AttributeError:\r\n p = password\r\n \r\n while padd_size > 0:\r\n p = p + b'\\x00'\r\n padd_size = padd_size - 1\r\n \r\n S = secret.encode(\"utf-8\")\r\n I = authenticator\r\n \r\n result = b'' \r\n c = I\r\n while p:\r\n h = hashlib.md5()\r\n h.update(S)\r\n h.update(c)\r\n b = h.digest()\r\n\r\n for i in range(16):\r\n result += bytes((b[i] ^ p[i],))\r\n\r\n c = result[-16:]\r\n p = p[16:]\r\n \r\n return result", "def derive_secret(secret, label, messages,\n hash_algorithm='sha256') -> bytearray:\n # https://tools.ietf.org/html/draft-ietf-tls-tls13-26#section-7.1\n if messages is None:\n hs_hash = secureHash(bytearray(b''), hash_algorithm)\n else:\n hs_hash = transcript_hash(messages, hash_algorithm)\n return HKDF_expand_label(secret, label, hs_hash,\n getattr(hashlib, hash_algorithm)().digest_size,\n hash_algorithm)", "def oauth():\r\n print _get_rand_hash()\r\n print _get_rand_hash()", "def generateSecretToken(page_shortname, resource_id):\n s = hashlib.sha1()\n s.update(page_shortname)\n s.update('--')\n s.update(str(resource_id))\n s.update('--')\n s.update(CONFIG['chargify_site_shared_key'])\n # chargify only keeps the first 10 chars\n return s.hexdigest()[0:10]", "def complete_hybi00(headers, challenge):\n\n key1 = headers[\"Sec-WebSocket-Key1\"]\n key2 = headers[\"Sec-WebSocket-Key2\"]\n\n first = int(\"\".join(i for i in key1 if i in digits)) / key1.count(\" \")\n second = int(\"\".join(i for i in key2 if i in digits)) / key2.count(\" \")\n\n nonce = pack(\">II8s\", first, second, challenge)\n\n return md5(nonce).digest()", "def complete_hybi00(headers, challenge):\r\n\r\n key1 = headers[\"Sec-WebSocket-Key1\"]\r\n key2 = headers[\"Sec-WebSocket-Key2\"]\r\n\r\n first = int(\"\".join(i for i in key1 if i in digits)) / key1.count(\" \")\r\n second = int(\"\".join(i for i in key2 if i in digits)) / key2.count(\" \")\r\n\r\n nonce = pack(\">II8s\", first, second, challenge)\r\n\r\n return md5(nonce).digest()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test where clause in extractor sql statement
def test_sql_statement(self) -> None: with patch.object(SQLAlchemyExtractor, '_get_connection'): extractor = SnowflakeTableLastUpdatedExtractor() extractor.init(self.conf) self.assertTrue(self.where_clause_suffix in extractor.sql_stmt)
[ "def must_return_select_with_specific_where_clause():\n\ttest = Test(1, 2, 3)\n\tquery = 'SELECT a, b, c FROM Test WHERE a = 5 AND b = 4'\n\tselect_query = entity.select(test, where_clause={'a': 5, 'b': 4})\n\tassert query == select_query", "def sqlCondition(writer):", "def _where(self):\n result = []\n result.extend(self._partition_selector())\n result.extend(self._job_and_fuzzer_selector())\n\n result = ' AND '.join(result)\n if result:\n return 'WHERE ' + result\n\n return ''", "def _make_where_clause(row_filter: str = None) -> psql.SQL:\n if row_filter:\n psql_filter = to_psql(row_filter)\n return psql.SQL(f\" WHERE {psql_filter}\")\n return psql.SQL(\"\")", "def test_build_where_statement_two_valid_attr(self):\n statement, values = self.__test_where_statement_builder(\n '/?test=foo&foo=bar')\n self.assertEqual(statement,\n 'WHERE test_column LIKE %s AND foo_column LIKE %s')\n self.assertEqual(values, ['foo', 'bar'])", "def query(self, sql):", "def sqlExpression(writer):", "def where_expr(self, truth_value_dataframe):\n return Token(\"where_expr\", truth_value_dataframe[0])", "def sqlwhere(dictionary, grouping=' AND '):\n return SQLQuery.join(\n [k + ' = ' + sqlparam(v) for k, v in dictionary.items()], grouping)", "def add_where_clause(self):\n if len(self.query_model.triples) > 0 or len(self.query_model.subqueries) > 0 or \\\n len(self.query_model.unions) >0 or len(self.query_model.optionals) > 0 or \\\n len(self.query_model.filter_clause) > 0 or len(self.query_model.optional_subqueries) > 0 or \\\n len(self.query_model.graph_triples) > 0 or len(self.query_model.graph_clause) > 0 or \\\n len(self.query_model.optional_graph_clause) > 0:\n where_string = self.__add_patterns()\n self.query_string += \"WHERE {\" + where_string + \"\\n\\t}\"\n else:\n self.query_string += \"WHERE {}\"", "def _Where(row_template=None):\n terms = []\n if row_template:\n for index in range(len(row_template)):\n term = row_template[index]\n if term is None:\n continue\n if isinstance(term, basestring):\n pattern = term.replace('*', '%').replace('.', '_').replace('\"', '\"\"')\n terms.append(u'{field} LIKE \"{pattern}\"'.format(\n field=_FieldRef(index), pattern=pattern))\n else:\n terms.append(u'{field} = {term}'.format(\n field=_FieldRef(index), term=term))\n if not terms:\n return ''\n return ' WHERE ' + ' AND '.join(terms)", "def test_tsql_select(self):\n expected_query = self.select_query\n actual_query = self.dictable.select_query_syntax()\n self.assertEqualQueries(expected_query, actual_query)", "def test_query_stmt(self):\n # The imput query is a select + 450 \"x \" long, which is long enough to get truncated.\n query = \"select \\\"{0}\\\"\".format(\"x \" * 450)\n # The expected result query should be 253 long and contains the first 250\n # chars + \"...\"\n expected_result = \"select \\\"{0}...\".format(\"x \" * 121)\n check_if_contains = False\n response_json = self.__run_query_and_get_debug_page(\n query, self.QUERIES_URL, expected_state=self.client.QUERY_STATES[\"FINISHED\"])\n # Search the json for the expected value.\n # The query can be in in_filght_queries even though it is in FINISHED state.\n for json_part in itertools.chain(\n response_json['completed_queries'], response_json['in_flight_queries']):\n if expected_result in json_part['stmt']:\n check_if_contains = True\n break\n\n assert check_if_contains, \"No matching statement found in the jsons at {}: {}\".format(\n datetime.now(), json.dumps(response_json, sort_keys=True, indent=4))", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue('table_catalog' in extractor.sql_stmt)\n self.assertFalse(self.cluster_key in extractor.sql_stmt)", "def make_where_clause(spec, **kwargs):\n where = []\n for col_to_query in spec['query_cols']:\n ids = kwargs.get(col_to_query)\n if ids:\n where.append('{} in [{}]'.format(col_to_query,\n ','.join([str(i) for i in ids])))\n\n # If boolean include_risks is false, then failing to\n # specify rei_id means you don't want attributable results.\n # Otherwise, it means you want all rei results\n if not kwargs.get('rei_id') and not kwargs.get('include_risks'):\n where.append('rei_id == 0')\n\n return \" & \".join(where)", "def select_conditional(self,query):\n query = query\n self._cursor.execute(query)\n row = self._cursor.fetchall()\n for index,record in enumerate(row):\n print(index,record,'\\n')", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertFalse(self.database_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.cluster_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.snowflake_database_key in extractor.sql_stmt)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test cluster_key in extractor sql stmt
def test_sql_statement(self) -> None: with patch.object(SQLAlchemyExtractor, '_get_connection'): extractor = SnowflakeTableLastUpdatedExtractor() extractor.init(self.conf) self.assertTrue(self.cluster_key in extractor.sql_stmt)
[ "def _statement2key(statement: sql.Selectable) -> str:\n return hashlib.sha256(str(statement.compile(compile_kwargs={'literal_binds': True})).encode()).hexdigest()", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue('table_catalog' in extractor.sql_stmt)\n self.assertFalse(self.cluster_key in extractor.sql_stmt)", "def test_describe_on_non_reserved_keywords(self):\n self.cluster.populate(1)\n self.cluster.start()\n node, = self.cluster.nodelist()\n session = self.patient_cql_connection(node)\n create_ks(session, 'ks', 1)\n session.execute(\"CREATE TABLE map (key int PRIMARY KEY, val text)\")\n describe_cmd = 'USE ks; DESCRIBE map'\n out, err = self.run_cqlsh(node, describe_cmd)\n assert \"\" == err\n assert \"CREATE TABLE ks.map (\" in out", "def cluster_identifier(self) -> str:\n ...", "def __contains__(self, key):\n query = select([exists().where(self.store.c.key == key)])\n result = self.conn.execute(query)\n return result.fetchone()[0]", "def test_data_source_postgre_sqls_id_exists_get(self):\n pass", "def _validate_primary_key(featuregroup_df, primary_key):\n cols = map(lambda x: x[0], featuregroup_df.dtypes)\n if primary_key in cols:\n return True\n else:\n raise AssertionError(\n \"Invalid primary key: {}, the specified primary key does not exists among the available columns: {}\".format(\n cols))", "def test_cd_hit():\n cluster = cd_hit.Cd_hit(\"cd-hit-est\")", "def test_data_source_postgre_sqls_id_get(self):\n pass", "def descriptions_contain(self, key, query):\n \n hit = False\n generator = DBGenerator(ModelDescriptionTable(self.dbfile)) \n for row in generator.next(): \n if query in str(row[key]):\n hit = True \n return hit", "def test_get_asset_cluster_member_by_moid(self):\n pass", "def is_relevant_sourcekey(self, sourcekey: str) -> bool:\n ...", "def get_selected_concept_query(concept_key):\n return \"\"\"\nLET concept_key = \"{concept_key}\"\nLET doc = DOCUMENT(CONCAT(\"{curation_concept_collection}/\", concept_key))\n\nRETURN doc\n \"\"\".format(\n concept_key=concept_key,\n curation_concept_collection=(\n _db_nomenclature.CURATION_CONCEPTS_COLLETION\n )\n )", "def get_specific_key(problem_id, version, key):\n return 'do some magic!'", "def test_partition_key_allow_filtering(self):\n session = self.prepare()\n\n session.execute(\"\"\"\n CREATE TABLE IF NOT EXISTS test_filter (\n k1 int,\n k2 int,\n ck1 int,\n v int,\n PRIMARY KEY ((k1, k2), ck1)\n )\n \"\"\")\n\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 0, 0, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 0, 1, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 0, 2, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 0, 3, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 1, 0, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 1, 1, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 1, 2, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (0, 1, 3, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 0, 0, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 0, 1, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 0, 2, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 0, 3, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 1, 0, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 1, 1, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 1, 2, 0)\")\n session.execute(\"INSERT INTO test_filter (k1, k2, ck1, v) VALUES (1, 1, 3, 0)\")\n\n # select test\n assert_all(session,\n \"SELECT * FROM test_filter WHERE k1 = 0 ALLOW FILTERING\",\n [[0, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 2, 0],\n [0, 0, 3, 0],\n [0, 1, 0, 0],\n [0, 1, 1, 0],\n [0, 1, 2, 0],\n [0, 1, 3, 0]],\n ignore_order=True)\n\n assert_all(session,\n \"SELECT * FROM test_filter WHERE k1 <= 1 AND k2 >= 1 ALLOW FILTERING\",\n [[0, 1, 0, 0],\n [0, 1, 1, 0],\n [0, 1, 2, 0],\n [0, 1, 3, 0],\n [1, 1, 0, 0],\n [1, 1, 1, 0],\n [1, 1, 2, 0],\n [1, 1, 3, 0]],\n ignore_order=True)\n\n assert_none(session, \"SELECT * FROM test_filter WHERE k1 = 2 ALLOW FILTERING\")\n assert_none(session, \"SELECT * FROM test_filter WHERE k1 <=0 AND k2 > 1 ALLOW FILTERING\")\n\n assert_all(session,\n \"SELECT * FROM test_filter WHERE k2 <= 0 ALLOW FILTERING\",\n [[0, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 2, 0],\n [0, 0, 3, 0],\n [1, 0, 0, 0],\n [1, 0, 1, 0],\n [1, 0, 2, 0],\n [1, 0, 3, 0]],\n ignore_order=True)\n\n assert_all(session,\n \"SELECT * FROM test_filter WHERE k1 <= 0 AND k2 = 0 ALLOW FILTERING\",\n [[0, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 2, 0],\n [0, 0, 3, 0]])\n\n assert_all(session,\n \"SELECT * FROM test_filter WHERE k2 = 1 ALLOW FILTERING\",\n [[0, 1, 0, 0],\n [0, 1, 1, 0],\n [0, 1, 2, 0],\n [0, 1, 3, 0],\n [1, 1, 0, 0],\n [1, 1, 1, 0],\n [1, 1, 2, 0],\n [1, 1, 3, 0]],\n ignore_order=True)\n\n assert_none(session, \"SELECT * FROM test_filter WHERE k2 = 2 ALLOW FILTERING\")\n\n # filtering on both Partition Key and Clustering key\n assert_all(session,\n \"SELECT * FROM test_filter WHERE k1 = 0 AND ck1=0 ALLOW FILTERING\",\n [[0, 0, 0, 0],\n [0, 1, 0, 0]],\n ignore_order=True)\n\n assert_all(session,\n \"SELECT * FROM test_filter WHERE k1 = 0 AND k2=1 AND ck1=0 ALLOW FILTERING\",\n [[0, 1, 0, 0]])\n\n # count(*) test\n assert_all(session,\n \"SELECT count(*) FROM test_filter WHERE k2 = 0 ALLOW FILTERING\",\n [[8]])\n\n assert_all(session,\n \"SELECT count(*) FROM test_filter WHERE k2 = 1 ALLOW FILTERING\",\n [[8]])\n\n assert_all(session,\n \"SELECT count(*) FROM test_filter WHERE k2 = 2 ALLOW FILTERING\",\n [[0]])\n\n # test invalid query\n with pytest.raises(InvalidRequest):\n session.execute(\"SELECT * FROM test_filter WHERE k1 = 0\")\n\n with pytest.raises(InvalidRequest):\n session.execute(\"SELECT * FROM test_filter WHERE k1 = 0 AND k2 > 0\")\n\n with pytest.raises(InvalidRequest):\n session.execute(\"SELECT * FROM test_filter WHERE k1 >= 0 AND k2 in (0,1,2)\")\n\n with pytest.raises(InvalidRequest):\n session.execute(\"SELECT * FROM test_filter WHERE k2 > 0\")", "async def test_get_node_from_key(self, r: RedisCluster) -> None:\n key = \"bar\"\n slot = r.keyslot(key)\n slot_nodes = r.nodes_manager.slots_cache.get(slot)\n primary = slot_nodes[0]\n assert r.get_node_from_key(key, replica=False) == primary\n replica = r.get_node_from_key(key, replica=True)\n if replica is not None:\n assert replica.server_type == REPLICA\n assert replica in slot_nodes", "def cddb_query(): # cd_id\n pass", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.snowflake_database_key in extractor.sql_stmt)", "def _has_clusters(self):\n return self.cluster_column in self.data.df.columns" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test SNOWFLAKE_DATABASE_KEY in extractor sql stmt
def test_sql_statement(self) -> None: with patch.object(SQLAlchemyExtractor, '_get_connection'): extractor = SnowflakeTableLastUpdatedExtractor() extractor.init(self.conf) self.assertTrue(self.snowflake_database_key in extractor.sql_stmt)
[ "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertFalse(self.database_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.cluster_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue('table_catalog' in extractor.sql_stmt)\n self.assertFalse(self.cluster_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.where_clause_suffix in extractor.sql_stmt)", "def test_data_source_postgre_sqls_get(self):\n pass", "def test_data_source_postgre_sqls_find_one_get(self):\n pass", "def test_data_source_postgre_sqls_id_get(self):\n pass", "def test_data_source_postgre_sqls_id_patch(self):\n pass", "def test_data_source_postgre_sqls_id_put(self):\n pass", "def test_data_source_postgre_sqls_id_exists_get(self):\n pass", "def test_data_source_postgre_sqls_post(self):\n pass", "def dbGenerateSaveQuery(self, env):", "def sql_query(dbname, query):\n ...", "def test_data_source_postgre_sqls_id_dynamic_datas_get(self):\n pass", "def test_data_source_postgre_sqls_id_replace_post(self):\n pass", "def test_data_source_postgre_sqls_id_dynamic_datas_post(self):\n pass", "def test_non_db_action():\n print('######### running non DB')", "def test__make_pattoo_db_record(self):\n pass", "def get_sqls(table_name):\n return {\n \"prepare_check\": \"SELECT relname FROM pg_class WHERE relkind='r' and relname='{0}';\".format(table_name),\n \"prepare_create\": \"create table {0} (kv_namespace VARCHAR(50), kv_key VARCHAR(100), kv_value VARCHAR(4000), kv_timestamp timestamp with time zone, primary key(kv_namespace, kv_key))\".format(table_name),\n \"get\": \"select kv_value from {0} where kv_namespace=%s and kv_key=%s\".format(table_name),\n \"get_all\": \"select kv_key, kv_value from {0} where kv_namespace=%s\".format(table_name),\n \"keys\": \"select kv_key from {0} where kv_namespace=%s\".format(table_name),\n \"set\": \"\"\"insert into {0} (kv_namespace, kv_key, kv_value, kv_timestamp) values (%s,%s,%s,%s) \n on conflict on constraint {0}_pkey\n do update set kv_namespace=%s, kv_key=%s, kv_value=%s, kv_timestamp=%s\"\"\".format(table_name),\n \"remove\": \"delete from {0} where kv_namespace=%s and kv_key=%s\".format(table_name),\n \"remove_all\": \"delete from {0} where kv_namespace=%s\".format(table_name),\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DATABASE_KEY in extractor sql stmt
def test_sql_statement(self) -> None: with patch.object(SQLAlchemyExtractor, '_get_connection'): extractor = SnowflakeTableLastUpdatedExtractor() extractor.init(self.conf) self.assertFalse(self.database_key in extractor.sql_stmt)
[ "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.snowflake_database_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.cluster_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue('table_catalog' in extractor.sql_stmt)\n self.assertFalse(self.cluster_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.where_clause_suffix in extractor.sql_stmt)", "def _statement2key(statement: sql.Selectable) -> str:\n return hashlib.sha256(str(statement.compile(compile_kwargs={'literal_binds': True})).encode()).hexdigest()", "def sql_query(dbname, query):\n ...", "def test_data_source_postgre_sqls_id_get(self):\n pass", "def test_data_source_postgre_sqls_id_exists_get(self):\n pass", "def test_data_source_postgre_sqls_get(self):\n pass", "def stmt():\n\n pass", "def test_data_source_postgre_sqls_id_dynamic_datas_get(self):\n pass", "def _get_db_entry(self, base, key_argument):\r\n return self.session.query(base).filter(getattr(base, key_argument[0])==key_argument[1]).first()", "def get_sqls(table_name):\n return {\n \"prepare_check\": \"SELECT relname FROM pg_class WHERE relkind='r' and relname='{0}';\".format(table_name),\n \"prepare_create\": \"create table {0} (kv_namespace VARCHAR(50), kv_key VARCHAR(100), kv_value VARCHAR(4000), kv_timestamp timestamp with time zone, primary key(kv_namespace, kv_key))\".format(table_name),\n \"get\": \"select kv_value from {0} where kv_namespace=%s and kv_key=%s\".format(table_name),\n \"get_all\": \"select kv_key, kv_value from {0} where kv_namespace=%s\".format(table_name),\n \"keys\": \"select kv_key from {0} where kv_namespace=%s\".format(table_name),\n \"set\": \"\"\"insert into {0} (kv_namespace, kv_key, kv_value, kv_timestamp) values (%s,%s,%s,%s) \n on conflict on constraint {0}_pkey\n do update set kv_namespace=%s, kv_key=%s, kv_value=%s, kv_timestamp=%s\"\"\".format(table_name),\n \"remove\": \"delete from {0} where kv_namespace=%s and kv_key=%s\".format(table_name),\n \"remove_all\": \"delete from {0} where kv_namespace=%s\".format(table_name),\n }", "def query_database(flg, word=None):\n cursor=conn.cursor()\n if flg == 1:\n query = cursor.execute(\"SELECT Definition FROM Dictionary WHERE Expression = '%s'\" % word)\n elif flg == 0:\n query = cursor.execute('SELECT DISTINCT EXPRESSION FROM Dictionary')\n return cursor.fetchall()", "def test_data_source_postgre_sqls_id_put(self):\n pass", "def test_data_source_postgre_sqls_id_patch(self):\n pass", "def __contains__(self, key):\n query = select([exists().where(self.store.c.key == key)])\n result = self.conn.execute(query)\n return result.fetchone()[0]", "def query(self, sql):", "def test_data_source_postgre_sqls_find_one_get(self):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure catalog is used as cluster in extract sql stmt
def test_sql_statement(self) -> None: with patch.object(SQLAlchemyExtractor, '_get_connection'): extractor = SnowflakeTableLastUpdatedExtractor() extractor.init(self.conf) self.assertTrue('table_catalog' in extractor.sql_stmt) self.assertFalse(self.cluster_key in extractor.sql_stmt)
[ "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.cluster_key in extractor.sql_stmt)", "def __test_catalog_object(self, db_name, tbl_name, cluster_properties):\n obj_url = self.CATALOG_OBJECT_URL + \\\n \"?object_type=TABLE&object_name={0}.{1}\".format(db_name, tbl_name)\n\n if cluster_properties.is_catalog_v2_cluster():\n impalad_expected_str = \\\n \"No URI handler for &apos;/catalog_object&apos;\"\n self.client.execute(\"invalidate metadata %s.%s\" % (db_name, tbl_name))\n self.get_and_check_status(obj_url, tbl_name, ports_to_test=self.CATALOG_TEST_PORT)\n # Catalog object endpoint is disabled in local catalog mode.\n self.check_endpoint_is_disabled(obj_url, impalad_expected_str,\n ports_to_test=self.IMPALAD_TEST_PORT)\n self.client.execute(\"select count(*) from %s.%s\" % (db_name, tbl_name))\n self.get_and_check_status(obj_url, tbl_name, ports_to_test=self.CATALOG_TEST_PORT)\n self.check_endpoint_is_disabled(obj_url, impalad_expected_str,\n ports_to_test=self.IMPALAD_TEST_PORT)\n else:\n impalad_expected_str = tbl_name\n self.client.execute(\"invalidate metadata %s.%s\" % (db_name, tbl_name))\n self.get_and_check_status(obj_url, tbl_name, ports_to_test=self.CATALOG_TEST_PORT)\n self.get_and_check_status(obj_url, impalad_expected_str,\n ports_to_test=self.IMPALAD_TEST_PORT)\n self.client.execute(\"select count(*) from %s.%s\" % (db_name, tbl_name))\n\n self.get_and_check_status(obj_url, tbl_name, ports_to_test=self.CATALOG_TEST_PORT)\n self.get_and_check_status(obj_url, impalad_expected_str,\n ports_to_test=self.IMPALAD_TEST_PORT)", "def __init__(self, keyspace = 'casi_test1', ip = '127.0.0.1'):\n ips = []\n ips.append(ip)\n self.cluster = Cluster(ips)\n self.session = self.cluster.connect(keyspace)\n self.session.row_factory = named_tuple_factory", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertFalse(self.database_key in extractor.sql_stmt)", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.snowflake_database_key in extractor.sql_stmt)", "def stmt():\n\n pass", "def _from_catalog(self):\n if self.dbconn.version < 90200:\n self.query = QUERY_PRE92\n for proc in self.fetch():\n sch, prc, arg = proc.key()\n if hasattr(proc, 'allargs') and proc.allargs == proc.arguments:\n del proc.allargs\n if hasattr(proc, 'proisagg'):\n del proc.proisagg\n del proc.source\n del proc.volatility\n del proc.returns\n del proc.cost\n if proc.finalfunc == '-':\n del proc.finalfunc\n if proc.sortop == '0':\n del proc.sortop\n self[(sch, prc, arg)] = Aggregate(**proc.__dict__)\n else:\n self[(sch, prc, arg)] = Function(**proc.__dict__)", "def _get_logical_plan(query_name: str, schema: str) -> str:\n\tquery_path = os.path.join(QUERY_ROOT, query_name)\n\twith open(query_path, \"r\") as f:\n\t\texecutable_query = _prefix_explain(query = f.read())\n\t\texecutable_query = executable_query.replace(\";\", \"\")\n\tresult = _execute(query = executable_query, schema = schema)\n\treturn result", "def test_data_source_postgre_sqls_get(self):\n pass", "def test_describe_on_non_reserved_keywords(self):\n self.cluster.populate(1)\n self.cluster.start()\n node, = self.cluster.nodelist()\n session = self.patient_cql_connection(node)\n create_ks(session, 'ks', 1)\n session.execute(\"CREATE TABLE map (key int PRIMARY KEY, val text)\")\n describe_cmd = 'USE ks; DESCRIBE map'\n out, err = self.run_cqlsh(node, describe_cmd)\n assert \"\" == err\n assert \"CREATE TABLE ks.map (\" in out", "def test_jdbc_query_executor(sdc_builder, sdc_executor, database):\n table_name = get_random_string(string.ascii_lowercase, 20)\n table = create_table_in_database(table_name, database)\n\n DATA = ['id,name'] + [','.join(str(item) for item in rec.values()) for rec in ROWS_IN_DATABASE]\n pipeline_builder = sdc_builder.get_pipeline_builder()\n dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')\n dev_raw_data_source.set_attributes(data_format='DELIMITED',\n header_line='WITH_HEADER',\n raw_data='\\n'.join(DATA))\n\n record_deduplicator = pipeline_builder.add_stage('Record Deduplicator')\n\n jdbc_query_executor = pipeline_builder.add_stage('JDBC Query', type='executor')\n query_str = f\"INSERT INTO {table_name} (name, id) VALUES ('${{record:value('/name')}}', '${{record:value('/id')}}')\"\n\n jdbc_query_executor.set_attributes(sql_query=query_str)\n\n trash = pipeline_builder.add_stage('Trash')\n dev_raw_data_source >> record_deduplicator >> jdbc_query_executor\n record_deduplicator >> trash\n pipeline = pipeline_builder.build(title='JDBC Query Executor').configure_for_environment(database)\n sdc_executor.add_pipeline(pipeline)\n\n try:\n sdc_executor.start_pipeline(pipeline).wait_for_pipeline_output_records_count(len(RAW_DATA) - 1)\n sdc_executor.stop_pipeline(pipeline)\n\n result = database.engine.execute(table.select())\n data_from_database = sorted(result.fetchall(), key=lambda row: row[1]) # order by id\n result.close()\n assert data_from_database == [(record['name'], record['id']) for record in ROWS_IN_DATABASE]\n finally:\n logger.info('Dropping table %s in %s database ...', table_name, database.type)\n table.drop(database.engine)", "def _run_and_log_sql(spark, sql_str):\n print(\"Running sql: {}\".format(sql_str))\n return spark.sql(sql_str)", "def isSQL():\n import sys\n return False if len(sys.argv) > 1 and \"nosql\" in sys.argv else True", "def main():\n\n # Load config\n config = configparser.ConfigParser()\n config.read(\"etl.cfg\")\n\n aws_key = config.get(\"aws\", \"key\")\n aws_secret = config.get(\"aws\", \"secret\")\n\n db_cluster_id = config.get(\"redshift\", \"cluster_identifier\")\n db_name = config.get(\"redshift\", \"db_name\")\n db_user = config.get(\"redshift\", \"db_user\")\n db_password = config.get(\"redshift\", \"db_password\")\n db_port = config.get(\"redshift\", \"db_port\")\n\n redshift = boto3.client(\n \"redshift\",\n region_name=\"us-west-2\",\n aws_access_key_id=aws_key,\n aws_secret_access_key=aws_secret,\n )\n\n # Make sure the Redshift cluster exists\n try:\n cluster_props = redshift.describe_clusters(ClusterIdentifier=db_cluster_id)[\"Clusters\"][0]\n except redshift.exceptions.ClusterNotFoundFault:\n print(\"Error: Cluster does not exist.\")\n return\n\n if cluster_props[\"ClusterStatus\"] != \"available\":\n print(f\"Error: Cluster is not available. Current status is: {cluster_props['ClusterStatus']}\")\n return\n\n # Dynamically retrieve the Redshift cluster host\n db_host = cluster_props[\"Endpoint\"][\"Address\"]\n\n # Connect to Redshift cluster\n conn = psycopg2.connect(\n f\"host={db_host} dbname={db_name} user={db_user} password={db_password} port={db_port}\"\n )\n\n # Data checks to run\n data_checks = [\n has_no_empty_tables,\n has_valid_temperature,\n has_valid_ratings,\n has_valid_barcode,\n has_valid_checkout_year,\n ]\n\n with conn.cursor() as cursor:\n for data_check in data_checks:\n print(f\"Running data check: {data_check.__name__}...\", end=\" \")\n data_check(cursor)\n print(\"OK\")\n\n conn.close()", "def makeCat(args):\n\n descr_text = 'Create merged catalog of sources from multiple tables'\n parser = argparse.ArgumentParser(description=descr_text)\n parser.add_argument('repoDir', help='Name of repository directory')\n parser.add_argument('visits', help='Visit selector')\n parser.add_argument('-c', '--ColFile', help='File of space-separated columns of interest')\n args = parser.parse_args()\n\n visits = args.visits\n if args.ColFile is None:\n cols = DEFAULT_COLS\n else:\n with open(args.ColFile, 'rb') as f:\n # The file of column names should contain only one row.\n for row in csv.reader(f, delimiter=' '):\n cols = row\n\n print '#' + ' '.join(cols) + ' filter'\n\n butler = dafPersist.Butler(args.repoDir)\n# vList = [dict(visit=int(v)) for v in visits.split('^')]\n vList = []\n for v in visits.split(\"^\"):\n mat = re.search(r\"^(\\d+)\\.\\.(\\d+)(?::(\\d+))?$\", v)\n if mat:\n v1 = int(mat.group(1))\n v2 = int(mat.group(2))\n v3 = mat.group(3); v3 = int(v3) if v3 else 1\n for v in range(v1, v2 + 1, v3):\n vList.append(dict(visit=v))\n else:\n vList.append(dict(visit=int(v)))\n \n for dataId in (vList):\n if not butler.datasetExists(\"src\", **dataId):\n continue\n\n srcs = butler.get(\"src\", **dataId)\n filter = butler.queryMetadata(\"calexp\", \"filter\", visit=dataId['visit'])[0]\n\n vecs = []\n for col in cols:\n if col.endswith(\".ra\") or col.endswith(\".dec\"):\n v = np.rad2deg(srcs.get(col))\n elif re.search(r\"\\.err\\.(xx|yy|xy)$\", col):\n field, which = re.search(r\"^(.*\\.err)\\.(xx|yy|xy)$\", col).groups()\n key = srcs.schema.find(field).key\n key = key[0,0] if which == \"xx\" else key[1,1] if which == \"yy\" else key[0, 1]\n\n v = srcs.get(key)\n else:\n v = srcs.get(col)\n\n vecs.append(v)\n\n for vals in zip(*vecs):\n print ' '.join([str(el) for el in vals]) + ' ' + filter", "def test_sql_statement(self) -> None:\n with patch.object(SQLAlchemyExtractor, '_get_connection'):\n extractor = SnowflakeTableLastUpdatedExtractor()\n extractor.init(self.conf)\n self.assertTrue(self.where_clause_suffix in extractor.sql_stmt)", "def query(self, sql):", "def _check_access_to_cluster(self):\n try:\n etl_dsn = self.dsn_etl\n admin_dsn = self.dsn_admin\n if etl_dsn[\"host\"] != admin_dsn[\"host\"]:\n raise InvalidEnvironmentError(\"Host is different between ETL and admin user\")\n if etl_dsn.get(\"port\") != admin_dsn.get(\"port\"):\n raise InvalidEnvironmentError(\"Port is different between ETL and admin user\")\n if etl_dsn[\"database\"] == admin_dsn[\"database\"]:\n raise InvalidEnvironmentError(\"Database is not different between ETL and admin user\")\n except (KeyError, ValueError):\n pass", "def _jude_need_cluster(self):\r\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks for updates of latest plists on Apple content server and returns the resulting files as a dict
def check(apps, latest, check_limit=11): reg = re.compile(r'\d+.plist') # Compiled regex to strip the version value and plist file extension apps = sorted([re.sub(reg, '', app) for app in apps]) # Have to convert these over to basic app names not plist values supported = [_k for _k, _ in APPLICATIONS.items()] result = latest if latest else dict() # Used if the file doesn't exist or has no updated apps found_updates = {'garageband': None, 'logicpro': None, 'mainstage': None} # Source the correct plist to read preferences if osinfo.isroot(): updater_pref = SYSTEM_UPDATER else: updater_pref = USER_UPDATER # Read the last update done to iterate over, ensuring the most recent files that were ok are sourced last_update = plist.read(f=updater_pref) if updater_pref.exists() else None # If the last update doesn't exist, fetch it if not last_update: plist.write(d=result, f=updater_pref) last_update = result.copy() # Iterate over the apps in the last update and get the version value from the plist filename # and then jump forward N number of versions to check. check_msg = ['Checking for updated sources to {apps}'.format(apps=', '.join(apps))] if last_update.get('last_checked'): date = last_update['last_checked'].strftime('%Y-%m-%d %H:%M:%S') check_msg.append(' (last checked {date})'.format(date=date)) # Print check message and last check time LOG.info(''.join(check_msg)) for app, source_plist in last_update.items(): if app in (supported and apps): ver = int(source_plist.replace(app, '')) # Create a URL to check, make sure it exists, if it does, update the result dict. # This should always return the current 'latest' version if no URL's are found for new_ver in range(ver, ver + check_limit): new_plist = '{app}{ver}'.format(app=app, ver=new_ver) url = '{feedurl}/{plist}.plist'.format(feedurl=FEED_URL, plist=new_plist) LOG.debug('Checking {url}'.format(url=url)) status = curl.status(url) if status in HTTP_OK and new_plist != result[app]: found_updates[app] = new_plist result[app] = new_plist result['last_updated'] = datetime.now() # Include a timestamp for the last with successfull update. LOG.debug('Found updated source plist at {url}'.format(url=url)) # Include a last checked timestamp result['last_checked'] = datetime.now() # Write the results if result: plist.write(d=result, f=updater_pref) # Collect the updated apps and generate a list of strings to use in update found message. updated_apps = ['{plist}.plist'.format(plist=new_plist) for app, new_plist in found_updates.items() if new_plist] # Log the updates found if updated_apps: LOG.info('Found updated sources {updates}, using updated sources'.format(updates=', '.join(updated_apps))) else: LOG.info('No updated sources found for {apps}, using last known current sources'.format(apps=', '.join(apps))) result = {_k: _v for _k, _v in result.items() if _k in apps} return result
[ "def update_package_list():\n log_helper = logging_helper.logging_helper.Logger()\n data_collector = sysinfo_ops.DataCollect()\n\n # Determine architecture and proper repository\n config = manage_config.read_config_file()\n base_url = config.get('DefaultRepo', 'base_repo')\n curated_url = base_url + '/' + 'curated.xml.gz'\n local_path = '/tmp/curated.xml.gz'\n local_file = 'curated.txt'\n\n # Download and decompress the curated list\n # todo: this needs to return 'False' on timeout and give a json status of 'fail'\n shell_ops.run_command('timeout 5 wget %s -O %s' % (curated_url, local_path))\n data_ops.uncompress(local_path, local_file)\n build_package_database()\n\n # Remove tar file after use\n try:\n os.remove(local_path)\n except: # todo: This needs to throw an error. Try 'except (OSError, IOError):'\n pass\n\n # From the UI if json == null then the response failed (timed out)\n response = ({\n 'status': 'success'\n })\n response = json.dumps(response)\n log_helper.logger.debug(\"Finished updating package list: '%s'\" % response)\n return response", "def get_lyncInstaller_info(self):\n if \"base_url\" in self.env:\n base_url = self.env[\"base_url\"]\n else:\n culture_code = self.env.get(\"culture_code\", CULTURE_CODE)\n base_url = BASE_URL % culture_code\n version_str = self.env.get(\"version\")\n if not version_str:\n version_str = \"latest\"\n # Get metadata URL\n req = urllib2.Request(base_url)\n # Add the MAU User-Agent, since MAU feed server seems to explicitly block\n # a User-Agent of 'Python-urllib/2.7' - even a blank User-Agent string\n # passes.\n req.add_header(\"User-Agent\",\n \"Microsoft%20AutoUpdate/3.0.2 CFNetwork/720.2.4 Darwin/14.1.0 (x86_64)\")\n try:\n f = urllib2.urlopen(req)\n data = f.read()\n f.close()\n except BaseException as err:\n raise ProcessorError(\"Can't download %s: %s\" % (base_url, err))\n \n metadata = plistlib.readPlistFromString(data)\n if version_str == \"latest\":\n # Lync 'update' metadata is a list of dicts.\n # we need to sort by date.\n sorted_metadata = sorted(metadata, key=itemgetter('Date'))\n # choose the last item, which should be most recent.\n item = sorted_metadata[-1]\n else:\n # we've been told to find a specific version. Unfortunately, the\n # Lync updates metadata items don't have a version attibute.\n # The version is only in text in the update's Title. So we look for \n # that...\n # Titles are in the format \"Lync x.y.z Update\"\n padded_version_str = \" \" + version_str + \" \"\n matched_items = [item for item in metadata \n if padded_version_str in item[\"Title\"]]\n if len(matched_items) != 1:\n raise ProcessorError(\n \"Could not find version %s in update metadata. \"\n \"Updates that are available: %s\" \n % (version_str, \", \".join([\"'%s'\" % item[\"Title\"] \n for item in metadata])))\n item = matched_items[0]\n \n self.env[\"url\"] = item[\"Location\"]\n self.env[\"pkg_name\"] = item[\"Payload\"]\n self.output(\"Found URL %s\" % self.env[\"url\"])\n self.output(\"Got update: '%s'\" % item[\"Title\"])\n # now extract useful info from the rest of the metadata that could\n # be used in a pkginfo\n pkginfo = {}\n pkginfo[\"description\"] = \"<html>%s</html>\" % item[\"Short Description\"]\n pkginfo[\"display_name\"] = item[\"Title\"]\n max_os = self.valueToOSVersionString(item['Max OS'])\n min_os = self.valueToOSVersionString(item['Min OS'])\n if max_os != \"0.0.0\":\n pkginfo[\"maximum_os_version\"] = max_os\n if min_os != \"0.0.0\":\n pkginfo[\"minimum_os_version\"] = min_os\n installs_items = self.getInstallsItems(item)\n if installs_items:\n pkginfo[\"installs\"] = installs_items\n requires = self.getRequiresFromUpdateItem(item)\n if requires:\n pkginfo[\"requires\"] = requires\n self.output(\n \"Update requires previous update version %s\" \n % requires[0].split(\"-\")[1])\n\n pkginfo['name'] = self.env.get(\"munki_update_name\", MUNKI_UPDATE_NAME)\n self.env[\"additional_pkginfo\"] = pkginfo\n self.env[\"display_name\"] = pkginfo[\"display_name\"]\n self.output(\"Additional pkginfo: %s\" % self.env[\"additional_pkginfo\"])", "def list(update_info):\n if not os.path.exists(update_info.installed_path):\n installed_info = \"- None!\\n\\n\"\n else:\n installed = _UpdateHandler._read_json(file_path=update_info.installed_path)\n installed_info = _UpdateHandler._get_release_message(json_data=installed)\n\n latest = _UpdateHandler._get_latest(update_info=update_info)\n latest_files = latest[\"assets\"]\n if len(latest_files) == 0:\n file_message = \"- None!\\n\\n{m}\".format(m=update_info.manual_msg)\n else:\n file_names = [\"- {n}\".format(n=x[\"name\"]) for x in latest_files]\n file_message = \"\\n\".join(file_names)\n\n template = (\n \"\\nInstalled release:\\n\\n{installed}\"\n \"Latest release:\\n\\n{latest}\"\n \"Files available:\\n\\n{file_message}\\n\"\n )\n message = template.format(\n installed=installed_info,\n latest=_UpdateHandler._get_release_message(json_data=latest),\n file_message=file_message,\n )\n log.info(message)", "def get_iOS_OS_updates(rest_factory_instance):\n logger_obj = LoggerWrapper().get_logger()\n logger_obj.debug('iOSOSUpdatesInfo:get_iOS_OS_updates++')\n os_updates = list()\n try:\n url_resource = \"https://en.wikipedia.org/wiki/IOS_version_history\"\n response, status = rest_factory_instance.make_get_request(url_resource)\n if 200 == status:\n logger_obj.info(\"successfully got OS updates data\")\n\n # collecting current OS version\n scraped_data = response.split('<td style=\"background:#d4f4b4;\">')[1].split(\"<th>Legend:\")[0]\n scraped_data = scraped_data.strip().splitlines()\n target_expression = re.compile(r'<[^>]+>')\n\n # Removing HTML Tags\n for index, line in enumerate(scraped_data):\n os_update = dict()\n found = line.find('\">')\n while -1 != found:\n space = line.find(' ')\n line = line[:space] + \">\" + line[found + 2:]\n if \"<sup\" in line:\n line = line[:line.find(\"<sup\")]\n found = line.find('\">')\n line = target_expression.sub('', line)\n scraped_data[index] = line\n if \".\" in line:\n os_update[\"Version\"] = line\n os_update[\"Build\"] = scraped_data[index + 2].split('<td>')[1]\n os_updates.append(os_update)\n\n logger_obj.debug(scraped_data)\n logger_obj.info(\"iOS OS Updates info: \" + str(os_updates))\n else:\n logger_obj.error(\"Failed to fetch iOS OS updates\")\n except:\n logger_obj.error(\"Failed to fetch iOS OS updates\")\n logger_obj.exception(traceback.format_exc())\n os_updates = {}\n logger_obj.debug('iOSOSUpdatesInfo:get_iOS_OS_updates--')\n return os_updates", "def prepare_file_list(self, format, file_lists):\n\n macapp = (format in { \"app-zip\", \"app-directory\", \"app-dmg\" })\n key = (macapp, tuple(file_lists))\n\n if key in self.file_list_cache:\n return self.file_list_cache[key].copy()\n\n fl = FileList.merge([ self.file_lists[i] for i in file_lists ])\n fl = fl.copy()\n fl.sort()\n\n if self.build.get(\"exclude_empty_directories\", True):\n fl = fl.filter_empty()\n\n fl = fl.add_missing_directories()\n\n if macapp:\n fl = fl.mac_transform(self.app, self.documentation_patterns)\n\n if not self.build[\"renpy\"]:\n\n app, rest = fl.split_by_prefix(self.app)\n\n if app:\n app = self.sign_app(app, macapp)\n\n fl = FileList.merge([ app, rest ])\n\n self.file_list_cache[key] = fl\n return fl.copy()", "def getFileListItem2(self):\n computersURL = '/file_lists/e773a9eb-296c-40df-98d8-bed46322589d/files/9e1ec8b43a88e68767fd8fed2f38e7984357b3f4186d0f907e62f8b6c9ff56ad'\n apiRequest = Wrapper_API()\n apiResponse = apiRequest.send_api_request(computersURL)\n return apiResponse", "def get_list_of_changed_files() -> None:\n start_log_group(\"Get list of specified source files\")\n files_link = f\"{GITHUB_API_URL}/repos/{GITHUB_REPOSITORY}/\"\n if GITHUB_EVENT_NAME == \"pull_request\":\n files_link += f\"pulls/{Globals.EVENT_PAYLOAD['number']}/files\"\n elif GITHUB_EVENT_NAME == \"push\":\n files_link += f\"commits/{GITHUB_SHA}\"\n else:\n logger.warning(\"triggered on unsupported event.\")\n sys.exit(set_exit_code(0))\n logger.info(\"Fetching files list from url: %s\", files_link)\n Globals.FILES = requests.get(files_link).json()", "def check_for_updates():\n local_config = models.LocalConfig.objects.first()\n client = ModoAPIClient()\n extensions = exts_pool.list_all()\n extensions = [{\n \"label\": \"Modoboa\",\n \"name\": \"modoboa\",\n \"description\": _(\"The core part of Modoboa\"),\n \"version\": client.local_core_version\n }] + extensions\n update_avail = False\n for extension in extensions:\n pkgname = extension[\"name\"].replace(\"_\", \"-\")\n for api_extension in local_config.api_versions:\n if api_extension[\"name\"] != pkgname:\n continue\n extension[\"last_version\"] = api_extension[\"version\"]\n if (\n parse_version(api_extension[\"version\"]) >\n parse_version(extension[\"version\"])\n ):\n extension[\"update\"] = True\n extension[\"changelog_url\"] = api_extension[\"url\"]\n update_avail = True\n break\n return update_avail, extensions", "def collect_list_metadata(listing, prereqs, live=False):\n pkg_dict = {}\n msgs = ''\n warnings = ''\n # a valid shell needs to exist in the filesystem for this to work\n for item in command_lib.base_keys:\n # check if the supported items exist in the given listing\n if item in listing.keys():\n if live:\n items, msg = get_live_attr_list(listing[item], prereqs)\n else:\n items, msg = get_pkg_attrs(listing[item], prereqs)\n msgs = msgs + msg\n if item == 'files':\n pkg_dict.update({item: collect_file_metadata(items)})\n else:\n pkg_dict.update({item: items})\n else:\n warnings = warnings + errors.no_listing_for_base_key.format(\n listing_key=item)\n return pkg_dict, msgs, warnings", "def recv_file_list(sock):\n header, body = recv_with_header(sock)\n metadata = json.loads(header.decode(\"utf-8\"))\n if metadata[\"type\"] != \"file_list\" or len(body) != 0:\n raise ValueError(\"Expected file_list, got {}\".format(metadata[\"type\"]))\n # return a dict with \"type\", \"files\", \"checksums\" (optionally None)\n return metadata", "def get_changed_prs(self) -> List:\n from syapse_gitdata.pull import PullRequest\n pull_requests = []\n with open('syapse_gitdata/output.json', 'r') as file_read:\n written_data = json.load(file_read)\n LOG.info('File Loaded Successfully')\n pr_dict = {}\n for pr in written_data:\n pr_dict.update({pr['url'] : pr})\n for pr in requests.get(self._pr_url, headers=self._header).json():\n if pr['url'] not in pr_dict.keys():\n req = PullRequest(pr['url'],self._header)\n req.parse_json()\n pull_requests.append(req)\n elif pr['updated_at'] != pr_dict[pr['url']]['updated']:\n req = PullRequest(pr['url'],self._header)\n req.parse_json()\n pull_requests.append(req)\n file_read.seek(0)\n return pull_requests", "def updateList(self):\r\n\r\n logging.debug(\"Checking local and remote resolver list for update\")\r\n\r\n #If the local resolver file does not exist, or it has expired\r\n if not os.path.isfile(self.listLocal) or \\\r\n os.path.getmtime(self.listLocal) < \\\r\n time.time() - self.updateListEvery:\r\n logging.info(\"Updating resolver list file\")\r\n r = requests.get(\r\n self.listLocation,\r\n headers={\r\n 'User-Agent':\"dnsyo/{0}\".format(\r\n pkg_resources.get_distribution(\"dnsyo\").version\r\n )\r\n }\r\n )\r\n\r\n if r.status_code != 200:\r\n #If status code response is not 200 and we don't\r\n #already have a resolvers file, raise an exception\r\n #Otherwise keep going with the old file\r\n if not os.path.isfile(self.listLocal):\r\n #File does not exist locally, we can't continue\r\n raise EnvironmentError(\"List location returned HTTP status {0} and we don't have a local copy of resolvers to fall back on. Can't continue\".format(\r\n r.status_code\r\n )\r\n )\r\n else:\r\n #Save the file\r\n with open(self.listLocal, 'w') as lf:\r\n lf.write(r.text)", "def softwareUpdatePrefs():\n try:\n return FoundationPlist.readPlist(\n '/Library/Preferences/com.apple.SoftwareUpdate.plist')\n except FoundationPlist.NSPropertyListSerializationException:\n return {}", "def check_for_updates():\n\n # tmp files\n uuid_file = CONFIG.MINDSDB_STORAGE_PATH + '/../uuid.mdb_base'\n mdb_file = CONFIG.MINDSDB_STORAGE_PATH + '/start.mdb_base'\n\n uuid_file_path = Path(uuid_file)\n if uuid_file_path.is_file():\n uuid_str = open(uuid_file).read()\n else:\n uuid_str = str(uuid.uuid4())\n try:\n open(uuid_file, 'w').write(uuid_str)\n except:\n log.warning('Cannot store token, Please add write permissions to file:' + uuid_file)\n uuid_str = uuid_str + '.NO_WRITE'\n\n file_path = Path(mdb_file)\n if file_path.is_file():\n token = open(mdb_file).read()\n else:\n token = '{system}|{version}|{uid}'.format(system=platform.system(), version=__version__, uid=uuid_str)\n try:\n open(mdb_file,'w').write(token)\n except:\n log.warning('Cannot store token, Please add write permissions to file:'+mdb_file)\n token = token+'.NO_WRITE'\n extra = urllib.parse.quote_plus(token)\n try:\n r = requests.get('http://mindsdb.com/updates/check/{extra}'.format(extra=extra), headers={'referer': 'http://check.mindsdb.com/?token={token}'.format(token=token)})\n except:\n log.warning('Could not check for updates')\n return\n try:\n # TODO: Extract version, compare with version in version.py\n ret = r.json()\n\n if 'version' in ret and ret['version']!= __version__:\n pass\n #log.warning(\"There is a new version of MindsDB {version}, please do:\\n pip3 uninstall mindsdb\\n pip3 install mindsdb --user\".format(version=ret['version']))\n else:\n log.debug('MindsDB is up to date!')\n\n except:\n log.warning('could not check for MindsDB updates')", "def update_download_list(args):\n with PodcastDatabase(args.database) as _database:\n podcasts = _database.get_podcast_urls()\n total_added = 0\n for _tuple in podcasts:\n name, added = pyres.rss.add_episodes_from_feed(_database,\n _tuple[0],\n args.base_dir,\n int(_tuple[1]),\n _tuple[2])\n if added:\n total_added += added\n print(\"%-50s: %3d episodes since %s\" %\n (name, added, utils.date_as_string(_tuple[2])))\n print()\n print(\"There are a total of %d episodes to be updated.\" %\n (total_added))\n\n # go ahead and get those podcasts while we're here.\n process_rss_feeds(args)", "def list_files() -> dict:\n endpoint_url = '/real-time-response/entities/put-files/v1'\n response = http_request('GET', endpoint_url)\n return response", "def http_get_patches(self):\n self._patches = []\n for patch_id in self.http_get_patch_id_list():\n obj = self.http_get_json(\n '%s%s%s' % (self._url, self.PATCHES_ID_ENDPOINT,\n str(patch_id)),\n verify=False,\n auth=(self._user, self._password),\n headers=self.HTTP_HEADER_ACCEPT_JSON)\n patch_data = obj\n self._patches.append(patch_data)\n self._cache_dump(patch_data, '%s-patches.json' % str(patch_id))\n patch_data = patch_data['software_title']\n name = patch_data['name']\n # total_computers_unpatched = patch_data['total_computers']\n # total_unpatched_versions = patch_data['total_versions']\n unpatched_versions = patch_data['versions']\n # This data structure is bizarre - it is a list of records that\n # really ought to be tuples. It goes like this:\n # [\n # \"1.2.3\",\n # {\"computers\": [\n # ... ], ... }\n # \"2.3.4\",\n # {\"computers\": [...]\n # ... }\n # ...\n # So some basic state must be kept if you use a simple for loop\n # over the list. This is done using current_version, which is set\n # to None when it expects a `version` string item and non-None when\n # it expects a `computers` string)\n current_version = None\n for row in unpatched_versions:\n if current_version is None:\n current_version = row\n continue\n for computer in row['computers']:\n # alt_mac_address = computer['alt_mac_address']\n # serial_number = computer['serial_number']\n # mac_address = computer['mac_address']\n identifier = computer['id'] # int\n # name = computer['name']\n computer_full = self._computer_data[identifier]\n computer_full = computer_full['computer']\n general = computer_full['general']\n location = computer_full['location']\n person_name = location['canonical_name']\n email = location['email_address']\n serial_number = general['serial_number']\n # ip = general['last_reported_ip']\n patch_record = {}\n patch_record['application'] = name\n patch_record['version'] = current_version\n # if self._id_to_patch_report[identifier]:\n # pass\n try:\n self._id_to_patch_report[identifier][\n 'missing_patches'].append(patch_record)\n except KeyError:\n self._id_to_patch_report[identifier] = {}\n self._id_to_patch_report[identifier][\n 'person'] = person_name\n self._id_to_patch_report[identifier]['email'] = email\n self._id_to_patch_report[identifier][\n 'missing_patches'] = []\n self._id_to_patch_report[identifier][\n 'missing_patches'].append(patch_record)\n # Some users have two computers, so distinguish between them using SN\n self._id_to_patch_report[identifier][\n 'serial_number'] = serial_number\n current_version = None\n\n # Build out a one row per missing patch list\n # This is CSV friendly since CSV can't represent lists in a row\n for identifier, patch_entry in self._id_to_patch_report.iteritems():\n missing = copy(patch_entry['missing_patches'])\n del patch_entry['missing_patches']\n for patch in missing:\n patch_entry.update(patch)\n self._user_tagged_patch_list.append(patch_entry)\n\n return self._patches", "def check_update(folder):\n \n file_names = os.listdir(folder)\n if record_file_name not in file_names:\n with open(folder + record_file_name, 'w') as record_file:\n record_file.writelines(record_file_name + '\\n')\n new_file_names = select_data_files(file_names)\n else:\n new_file_names = []\n with open(folder + record_file_name, 'r') as record_file:\n old_file_names = record_file.readlines()\n for name in file_names:\n if name not in old_file_names:\n new_file_names.append(name)\n new_file_names = select_data_files(new_file_names)\n\n return new_file_names", "def update_pull(self):\n \n file_path = os.path.join(self.script_dir,'pull list.json') \n if not os.path.isfile(file_path)or os.path.getsize(file_path) == 0 :\n with open(file_path,'w') as out:\n json.dump(self.pull_list,out)\n else:\n with open(file_path) as infile:\n data = json.load(infile)\n data.update(self.pull_list)\n\n with open(file_path,'w') as out:\n json.dump(self.pull_list,out)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a new block on the grid.
def gen_block(self): new_block = random.randrange(7) self.center_block = [4, 4] if new_block == 0: # Z Block self.falling_blocks = [[4, 4], [4, 5], [3, 4], [3, 3]] elif new_block == 1: # L Block self.falling_blocks = [[4, 4], [4, 3], [4, 5], [3, 5]] elif new_block == 2: # O Block self.falling_blocks = [[4, 4], [4, 5], [3, 4], [3, 5]] elif new_block == 3: # S Block self.falling_blocks = [[4, 4], [4, 3], [3, 4], [3, 5]] elif new_block == 4: # I Block self.falling_blocks = [[4, 4], [4, 3], [4, 5], [4, 6]] elif new_block == 5: # J Block self.falling_blocks = [[4, 4], [4, 5], [4, 3], [3, 3]] elif new_block == 6: # T Block self.falling_blocks = [[4, 4], [4, 3], [4, 5], [3, 4]] stop = False for block in self.falling_blocks: if self.grid[block[0]][block[1]][0] == 1: stop = True if stop: self.done = True else: for block in self.falling_blocks: self.grid[block[0]][block[1]] = [-1, BLOCK_SPRITES[new_block]]
[ "def create_genesis_block():\n return Block(0, date.datetime.now(), \"010101\", {\"VIN\": 123456, \"Owner\": \"Qwertz\", \"Mileage\": 0},\n hash_a_block(0, date.datetime.now(), \"010101\", {\"VIN\": 123456, \"Owner\": \"Qwertz\", \"Mileage\": 0}))", "def __create_block(self, data, genesis=0):\n previous = 0\n if not genesis:\n previous = self.__blocks[::-1][0]\n\n block = Block (\n data, \n len(self.__blocks),\n previous\n )\n\n _hash = ''\n adjust = 0\n while not self.__valid(_hash):\n core = '{}{}'.format(block, adjust)\n _hash_obj = sha256(core.encode())\n _hash = _hash_obj.hexdigest()\n adjust += 1\n\n print('Block took {} tries to be generated.'.format(adjust-1))\n self.__blocks.append(_hash)", "def makeNewBlock(self):\n\n block = textlayout.Block(\n width=self._propertyToPoints(\"width\"),\n lineHeight=self._propertyToPoints(\"line_height\"),\n marginTop=self._propertyToPoints(\"margin_top\"),\n marginBottom=self._propertyToPoints(\"margin_bottom\"),\n textAlign=self._property(\"text_align\"),\n maxLines=self._propertyToInt(\"max_lines\"),\n ellipsify=self._propertyToBool(\"ellipsify\")\n )\n\n return block", "def addBlock(self, name):\n\t\tblock = self.blocksmap[name]\n\t\tprefix = 'bl'\n\t\tif block.xref: prefix = 'xr'\n\t\tblender_group = Group.New('%s_%s' %(prefix,name)) # Blender groupObject contains definition of BLOCK\n\t\tblock_def = [blender_group, block.loc]\n\t\tself.settings.write(\"\\nDrawing block:\\'%s\\' ...\" % name)\n\n\t\tif block.xref:\n\t\t\tobname = 'xr_%s' %name # create object name from xref block name\n\t\t\t#obname = obname[:MAX_NAMELENGTH]\n\t\t\t# if material BYBLOCK def needed: use as placeholder a mesh-vertex instead of empty\n\t\t\tob = SCENE.objects.new('Empty', obname) # create a new empty_object\n\t\t\tempty_size = 1.0 * settings.var['g_scale']\n\t\t\tif empty_size < 0.01: empty_size = 0.01 #Blender limits (0.01-10.0)\n\t\t\telif empty_size > 10.0: empty_size = 10.0\n\t\t\tob.drawSize = empty_size\n\t\t\tob.loc = tuple(block.loc)\n\t\t\tob.properties['xref_path'] = block.path\n\t\t\tob.layers = [19]\n\t\t\tinsertFlag=True; blockFlag=True\n\t\t\tglobal oblist\n\t\t\toblist.append((ob, insertFlag, blockFlag))\n\t\telse:\t\t\n\t\t\tif M_OBJ:\n\t\t\t\tcar_end()\n\t\t\t\tcar_start()\n\t\t\tdrawEntities(block.entities, self.settings, block_def)\n\t\t\tif M_OBJ: car_end()\n\t\tself.settings.write(\"Drawing block:\\'%s\\' done!\" %name)\n\t\tself.blocks[name] = blender_group", "def genesis_block_generator():\n # return Block(\n # THE_GENESIS_BLOCK_DATA['timestamp'],\n # THE_GENESIS_BLOCK_DATA['last_hash'],\n # THE_GENESIS_BLOCK_DATA['hash'],\n # THE_GENESIS_BLOCK_DATA['data']\n # )\n return Block(**THE_GENESIS_BLOCK_DATA)", "def block(self):\n # First blank the previous position\n for x, y in self.game.block.last():\n y -= self.game.grid.top_buffer\n if y >= 0:\n self.pixel(x, y, 0)\n # Then draw the new position\n for x, y in self.game.block.position():\n y -= self.game.grid.top_buffer\n #self.print(\"y new: \" + str(y))\n if y >= 0:\n self.pixel(x, y, self.game.block.color)\n # Finally refresh the screen\n self.refresh()", "def make_genesis_block():\n block = Block(index=0,\n timestamp=datetime.now().isoformat(),\n data={'proof-of-work': 9, 'transactions': []},\n previous_hash=\"0\")\n return block", "def create_genesis_block(self) -> None:\n genesis_block = Block(0, [], time.time(), \"0\")\n genesis_block.hash = genesis_block.compute_hash()\n self.chain.append(genesis_block)", "def placeBlock(self):\n mousex, mousey = pygame.mouse.get_pos()\n events = pygame.event.get()\n if pygame.mouse.get_pressed()[0] and len(self.pickedUpBlocks) > 0 and self.canClick:\n placedBlock = Block(IMG_PATH_BLOCK, mousex, mousey, (100, 20))\n self.platforms.append(placedBlock)\n self.pickedUpBlocks.remove(self.pickedUpBlocks[0])\n self.changingTexts[1] = self.renderText(str(len(self.pickedUpBlocks)), COOL_FONT, (WIDTH/11*10.1, HEIGHT/10), BLACK, 25)\n placedBlock.placed = True\n self.canClick = False\n elif not pygame.mouse.get_pressed()[0]:\n self.canClick = True", "def new_tile(self):\n # replace with your code (Phase 3)\n\n # Bonus: Check if board is full and do not generate new tile\n\n # Generate a random number up to 1\n\n # Assign new tile depending on generated number\n\n # Place new tile on randomly selected empty square from board\n pass", "def generate(self):\n if len(self.network.chain) == 0:\n print(\n \"`generate` called, but chain is nonexistant;\",\n \"delegating to `genesis`...\")\n self.genesis()\n return\n\n block = Block(self.network.chain[-1].index+1,\n self.network.chain[-1].hash_val,\n random.choice(DATA_MESSAGES))\n\n # mine block\n block.hash(self.network.difficulty)\n\n # add block to this Node's chain and send it to all other Nodes in\n # network\n self.network.add_block(block)\n self.broadcast(block)", "async def mine_new_block():\n block = await self.create_block_async_func(Address.create_empty_account())\n if not block:\n self.input_q.put((None, {}))\n return\n mining_params = self.get_mining_param_func()\n mining_params[\"consensus_type\"] = self.consensus_type\n # handle mining simulation's timing\n if \"target_block_time\" in mining_params:\n target_block_time = mining_params[\"target_block_time\"]\n mining_params[\"target_time\"] = (\n block.header.create_time\n + self._get_block_time(block, target_block_time)\n )\n work = MiningWork(\n block.header.get_hash_for_mining(),\n block.header.height,\n block.header.difficulty,\n )\n self.work_map[work.hash] = block\n if self.process:\n self.input_q.put((work, mining_params))\n return\n\n self.process = AioProcess(\n target=self.mine_loop,\n args=(work, mining_params, self.input_q, self.output_q),\n )\n self.process.start()\n await handle_mined_block()", "def _initialize(self):\n y = 0 # initial y height\n for x in xrange(-BOUND, BOUND + 1, STEP):\n for z in xrange(-BOUND, BOUND + 1, STEP):\n # create a layer stone an grass everywhere.\n self.add_block((x, y - 3, z), DISPLAY2TEXTURE['stonebrick_carved'], immediate=False)\n self.add_block((x, y - 2, z), DISPLAY2TEXTURE['redstone_ore'], immediate=False)\n self.add_block((x, y - 1, z), DISPLAY2TEXTURE['gravel'], immediate=False)\n self.add_block((x, y - 0, z), DISPLAY2TEXTURE['grass_side'], immediate=False)\n if x in (-BOUND, BOUND) or z in (-BOUND, BOUND):\n # create outer walls.\n for dy in xrange(-3, 8):\n self.add_block((x, y + dy, z), ['stonebrick_carved']*6, immediate=False)\n \n \"\"\" #add random walking block\n for i in range(5):\n x, y, z = random.randint(-50, 50),1,random.randint(-50, 50)\n block = Block((x, y, z),DISPLAY2TEXTURE['brick'],speed=5)\n ex, ey, ez = random.randint(-50, 50),1,random.randint(-50, 50)\n block.add_pinpoint((ex,ey,ez))\n self.move_set.append(block)\n self.add_block((x, y, z), DISPLAY2TEXTURE['brick'], immediate=False,zoom=0.5)\"\"\"\n \n \"\"\"\n for i in range(30):\n x, y, z = random.randint(-50, 50),random.randint(0, 20),random.randint(-50, 50)\n block = Block((x, y, z),DISPLAY2TEXTURE['brick'],speed=0,acceleration_y=GRAVITY) \n end_point=self.check_below((x,y,z))\n if end_point:\n block.add_pinpoint(end_point)\n self.move_set.append(block)\n self.add_block((x, y, z), DISPLAY2TEXTURE['brick'], immediate=False,zoom=0.5)\"\"\"\n \n #self._show_block ((5, 2, 0), DISPLAY2TEXTURE['diamond'])\n #self.add_destroy_stage((5, 2, 0), 'destroy_stage_5')\n #self._show_tri((5, 3, 5),'diamond')", "def _nextblock(self):\n\n low, high = self._scanblocks()\n\n # The next block to be written to is the one with the lowest\n # sequence number. Write to the block number that contains it,\n # and assign it the sequence number after the highest one seen.\n # Blocks that don't exist are considered to have a sequence number\n # of -1, so they will always be first.\n block = {'blocknum': low['blocknum'], 'sequence': high['sequence'] + 1}\n\n # Open/create/truncate the block and write the new header.\n block['fh'] = open(self._blockpath(block['blocknum']), \"w+\")\n block['fh'].write(self._blockheader(sequence = block['sequence']))\n\n logging.debug(\"New block at %s: sequence %d\" % (self._blockpath(block['blocknum']), block['sequence']))\n\n return block", "def create_block(self, blocktype, b_obj = None):\n try:\n block = getattr(NifFormat, blocktype)()\n except AttributeError:\n raise NifExportError(\n \"'%s': Unknown block type (this is probably a bug).\"\n % blocktype)\n return self.register_block(block, b_obj)", "def form_block(self): # Ok!\r\n\r\n self.Block_list = []\r\n self.num_trials = 0\r\n for pair in self.training_order[self.step]:\r\n repeat_no = pair[2]\r\n self.num_trials += repeat_no\r\n percept = pair[0]\r\n action = pair[1]\r\n act_list = list(range(self.num_classes))\r\n act_list.remove(int(action[1])-1)\r\n for rpt in range(repeat_no):\r\n action_list = []\r\n action_list.append(str(action))\r\n comparison_list = np.random.choice(act_list,\r\n self.size_action_set-1, replace=False)\r\n for k in comparison_list:\r\n action_list.append(str(pair[1][0]+ str(k+1)))\r\n self.Block_list.append({percept: random.sample(action_list,\r\n len(action_list))})\r\n return random.shuffle(self.Block_list)", "def create_block(neo_block):\n block = models.Block()\n if neo_block.name is not None:\n block.name = neo_block.name\n if neo_block.description is not None:\n block.description = neo_block.description\n if neo_block.file_origin is not None:\n block.file_origin = neo_block.file_origin\n block.annotations = clean_annotations(neo_block.annotations)\n block.index = neo_block.index\n block.file_datetime = clean_datetime(neo_block.file_datetime)\n block.rec_datetime = clean_datetime(neo_block.rec_datetime)\n return block", "def create(self):\n\n # create a new block\n try:\n block = self.create_block()\n except self.BlockExistsException:\n logger.warning('Existing block for day - skipping it.')\n return\n\n # create the BlockGames (both included & excluded)\n included_games = self.sport_day.get_included_games()\n excluded_games = self.sport_day.get_excluded_games()\n all_games = list(included_games) + list(excluded_games)\n block_games = self.create_block_games(block, all_games) # returns the created BlockGames\n logger.info('Block Created %s' % block)\n\n # create the block prize structures\n block_prize_structure_creator = BlockPrizeStructureCreator(block)\n block_prize_structure_creator.create()\n return block", "def generate_blocks(self,\n min_block_num=8,\n max_block_num=12,\n min_input_output_number=0,\n max_input_output_number=3,\n min_key_value_number=0,\n max_key_value_number=10):\n if self.types_of_block is not None:\n raise Exception(\"Setting blocks twice.\")\n\n block_number = random.randint(min_block_num, max_block_num)\n\n a_type_number = 1\n # Mode for number of types is 20% of numbers of the nodes.\n mode_type_number = math.ceil((block_number - 1) / 5)\n b_type_number = block_number\n\n types_of_block_number = int(math.ceil(numpy.random.triangular(left=a_type_number,\n mode=mode_type_number,\n right=b_type_number)))\n\n def generate_new_string():\n return ''.join(random.choice(string.ascii_uppercase + string.digits)\n for _ in range(StandardWorkflowGenerator.LENGTH_OF_STRINGS))\n\n self.types_of_block = []\n for _ in range(0, types_of_block_number):\n operation_id = generate_new_string()\n input_number = numpy.random.randint(max_input_output_number - min_input_output_number) \\\n + min_input_output_number\n output_number = numpy.random.randint(max_input_output_number - min_input_output_number) \\\n + min_input_output_number\n inputs = sorted([generate_new_string()\n for _ in range(0, input_number)])\n outputs = sorted([generate_new_string()\n for _ in range(0, output_number)])\n\n key_value = numpy.random.randint(max_key_value_number - min_key_value_number) \\\n + min_key_value_number\n key_values = {generate_new_string(): generate_new_string()\n for _ in range(0, key_value)}\n self.types_of_block.append(Block(operation=Operation(operation_id=operation_id,\n inputs=inputs,\n outputs=outputs),\n options=key_values))\n\n self.types_of_block = tuple(self.types_of_block)\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move block left, if possible.
def move_left(self): stop = False for block in self.falling_blocks: # Check to see if block can go left if block[1] == 0 or self.grid[block[0]][block[1]-1][0] == 1: stop = True if not stop: center = self.get_center_block() block_image = center[1] for block in self.falling_blocks: # Remove blocks from grid self.grid[block[0]][block[1]] = [0, None] for block in self.falling_blocks: # Replace blocks one space to the left on the grid block[1] -= 1 self.grid[block[0]][block[1]] = [-1, block_image] self.center_block = self.falling_blocks[0]
[ "def move_left(self):\n for block in self.blocks:\n block.move_left()", "def move_left(self):\n self.set_position(self.get_position() - 1)\n return", "def move_left(self) -> None:\n empty_pos = self._get_empty_piece_position()\n # return if empty piece is on the first column\n if empty_pos.x == 0:\n return\n # swap the empty piece with the target piece\n self._swap_pieces(x1=empty_pos.x, y1=empty_pos.y, x2=empty_pos.x - 1, y2=empty_pos.y)", "def move_left(self):\n self.x -= 1", "def move_left(self):\n self.score += 0.02\n if self.map[self.hero.position[1]][self.hero.position[0] - 1] == Service.wall:\n return\n self.hero.left()\n self.interact()", "def move_left(self):\n self.tape.move_left()", "def move_left(self):\n # global continue_up, continue_down, continue_right, continue_left\n self.continue_up = 0\n self.continue_down = 0\n self.continue_right = 0\n if self.current_line.text and self.current_line.number == self.lines.total:\n self.lines.add() # create emtpy line\n\n try: # if tab, move 4 spaces\n if self.current_line.x - 6 <= self.current_line.indentation and \\\n self.current_line.text[self.current_line.x - 6 - 4:self.current_line.x - 6] == ' ' and \\\n self.current_line.y == self.current_line.end_y:\n self.current_line.x -= 4\n return\n except BareException:\n pass\n if self.config['cursor_acceleration']:\n move_rate = min(self.config['cursor_max_horizontal_speed'], int(self.continue_left / 10.0) + 1)\n else:\n move_rate = 1\n self.continue_left += 1\n self.current_line.x -= move_rate", "def move_left(self) -> None:\n if self.velocity == (VELOCITY_NORM, 0):\n return\n self.velocity = (-VELOCITY_NORM, 0)", "def move_left(self) -> None:\n # Keeps the infected characters from bunching up.\n if self.id == 'Infected':\n for char in filter(lambda x: x.id == 'Infected', characters):\n if abs(char.x - self.x) < 2 and abs(char.y - self.y) < 2:\n if abs(char.x - self.x + 1) < abs(char.x - self.x) < 2:\n if self.distance(MAIN) > 5 and self.target is None:\n return\n\n # If physically possible, moves the character left.\n if self.x - 1 > 0:\n self.x -= 1\n self.set_animate()", "def go_left(self):\n self.change_x = -4\n self.direction = \"L\"", "def move_left(self):\n self.lcd_byte(\n self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVELEFT,\n self.LCD_CMD)", "def attemptMovingCarLeft(self, leftBlock, rightBlock):\n try:\n carClosestToLight = rightBlock.carsGoingLeft[0]\n if carClosestToLight.location == rightBlock.length:\n rightBlock.moveCar(leftBlock, \"Left\")\n except:\n # no cars going left\n pass", "def move_left(robot: cozmo.robot.Robot, move):\n\tlog.info('Move left...')\n\trobot.turn_in_place(degrees(45)).wait_for_completed()\n\trobot.drive_straight(distance_mm(move), speed_mmps(speed)).wait_for_completed()\n\trobot.turn_in_place(degrees(-45)).wait_for_completed()", "def move_left(self, event):\n self.control.canvas.remove_figure(self.current_figure)\n coords = self.current_figure.move_left()\n if self.control.canvas.is_valid_coords(coords):\n self.current_figure.cells = coords\n self.control.canvas.hold_figure(self.current_figure)\n self.control.canvas.redraw()", "def sh_left(self):\n if self.pointer == 0:\n # This looks wrong at first, but remember that the pointer\n # is not absolute... ;)\n self.buf = [0] + self.buf\n else:\n self.pointer -= 1", "def move_column_left(self):\t\t\n\t\tif self.column == 0:\n\t\t\treturn self.FRAD_OUT_OF_BOUNDS\n\t\telse:\n\t\t\tself.column -= 1\n\t\t\tself.go_to_minor(self.minor)\n\t\t\treturn self.FRAD_OK", "def remove_node_and_move_left(self):\n\t\tleftNode = self.currentPosition.previousNode\n\t\trightNode = self.currentPosition.nextNode\n\n\t\tif leftNode != None:\n\t\t\tleftNode.nextNode = rightNode\n\t\tif rightNode != None:\n\t\t\trightNode.previousNode = leftNode\n\n\t\tself.currentPosition = previousNode\n\t\tself.decr_count()\n\t\treturn 1", "def robot_left(self):\r\n\t self.x = self.x - 1\r\n\t if self.x < 0:\r\n\t\t self.x = 0", "def move_right(self):\n for block in self.blocks:\n block.move_right()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the numbered line and move all blocks above it down.
def clear_line(self, line): for i in range(line, 3, -1): for j in range(0, 10): self.grid[i][j] = self.grid[i - 1][j] self.score += 100
[ "def clear_previous_line():\n print(CURSOR_PREV_LINE, end=\"\")\n print(CLEAR_UNTIL_EOL, end=\"\")", "def _set_line_to_initial_position(self, line_no: int) -> Paragraph:\n self.lines[1][line_no] = None\n self[line_no].move_to(self.get_center() + self.lines_initial_positions[line_no])\n return self", "def del_line0(self):\n self._del_line0()", "def _line_clear(self):\n self.state = list(filter(lambda row: row.count(' ') != 0, self.state))\n while len(self.state) < Field.HEIGHT:\n self.state.insert(0, [' ' for col in range(Field.WIDTH)])", "def _set_all_lines_to_initial_positions(self) -> Paragraph:\n self.lines[1] = [None] * len(self.lines[0])\n for line_no in range(len(self.lines[0])):\n self[line_no].move_to(\n self.get_center() + self.lines_initial_positions[line_no],\n )\n return self", "def _delete_till_beginning_of_line(self):\n text = self.get_edit_text()\n f_text = delete_till_beginning_of_line(text[:self.edit_pos])\n self.set_edit_text(f_text + text[self.edit_pos:])\n self.set_edit_pos(len(f_text))", "def clear(self):\n self.n = 0", "def clear_points(self):\n self._points = []\n # clear points from the number line\n return", "def UnComment(self):\n sel = self.GetSelection()\n start = self.LineFromPosition(sel[0])\n end = self.LineFromPosition(sel[1])\n if start>end: #swap around\n start,end=end,start\n #start an undo mark\n self.BeginUndoAction()\n for ln in range(start, end + 1):\n linestart = self.PositionFromLine(ln)\n if chr(self.GetCharAt(linestart)) == '#':\n #set cursor to the right of the #\n self.SetCurrentPos(linestart + 1)\n #delete to the beginning of th line\n self.DelLineLeft()\n #finish the undo mark\n self.EndUndoAction()", "def reset_points(self):\n\n self.deleted_lines = 0\n self.lines_text.set(f\"Deleted lines: {self.deleted_lines}\")\n\n self.points = 0\n self.points_text.set(f\"Points: {self.points}\")\n\n self.level = 1\n self.delay = 500", "def clear_position(self, position):\n self.set_occupation('----', position)", "def delete_to_start_of_line(code_edit):\n textCursor = code_edit.textCursor()\n pos = textCursor.position()\n textCursor.movePosition(QtGui.QTextCursor.StartOfLine)\n textCursor.setPosition(pos, QtGui.QTextCursor.KeepAnchor)\n textCursor.insertText('')", "def delete_line(self, lineno=None):\n if lineno is None:\n lineno = self.line_number()\n self._validate_lineno(lineno)\n del self._lines[self._line_index(lineno)]\n if lineno > self.number_of_lines():\n lineno -= 1\n if lineno > 0:\n self.goto_line(lineno)", "def vfd_clear_section(self, line=0, clear_start=1, length=1):\n \n \"\"\"check, if the section is valid\"\"\"\n if clear_start == None or clear_start > self._cols or length < 1: return\n \n \"\"\"calculate position and check if clearing exceeds the line length\"\"\"\n position = line*20 + clear_start\n if (position-1 + length) > (line+1)*20 : return\n \n \"\"\"position the cursor and clear Display and display tracker\"\"\"\n self.set_cursor(position)\n for i in range(length):\n self.message(\" \")\n self._DisplayTracker[line][i+clear_start-1] = 0", "def down(self, n_lines=1):\n self.goto_line(self._lineno + n_lines)", "def reset(self):\r\n self.footnotes = markdown.odict.OrderedDict()", "def clear_lines(self, index = 0):\r\n self.sub_plots(index).axes.cla()\r\n self.sub_plots(index).lines = []", "def up(self, n_lines=1):\n self.down(-n_lines)", "def clear(row):\n for i in range(self.cols):\n self.blocks.remove(Point(i,row))\n for j in range(row+1, self.rows):\n for i in range(self.cols):\n target = Point(i,j)\n destination = Point(i,j-1)\n if target in self.blocks:\n self.blocks.remove(target)\n self.blocks.add(destination)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts (x, y) grid coordinates to (x, y) pixel coordinates.
def grid2pix(self, x, y): if (x < 0 or x > 9 or y < 0 or y > 23): try: raise IndexError except IndexError as inst: print("""x index must be between 0 and 9, y index must be between 4 and 23. (%d, %d) not valid.""" % (x, y)) pix_x = self.x + MARGIN + (x * BLOCK_WIDTH) pix_y = self.y + MARGIN + ((y - 4) * BLOCK_HEIGHT) return pix_x, pix_y
[ "def grid_to_world(self, x, y):\n #XyCoordinates to be returned\n xyCoord = Point()\n\n #Assign coord values from grid values\n xyCoord.x = (x + 0.5) * self.map.info.resolution + self.map.info.origin.position.x\n xyCoord.y = (y + 0.5) * self.map.info.resolution + self.map.info.origin.position.y\n return xyCoord", "def pixel_coords_to_tile_address(x,y):\n x = int(math.floor(x / 256))\n y = int(math.floor(y / 256))\n return (x, y)", "def pixel_to_tile(self, x: int, y: int) -> tuple[int, int]:\n with ffi.new(\"int[2]\", (x, y)) as xy:\n _check(lib.TCOD_context_screen_pixel_to_tile_i(self._p, xy, xy + 1))\n return xy[0], xy[1]", "def convert_grid_coord(x,y):\n # define default row and column if black space is clicked\n row, column = 999, 999\n # start and end coords of squares\n start = list(range(4,230,25))\n end = list(range(24,255,25))\n # check to see if mouse click is in valid square\n for i in range(len(start)):\n if x > start[i] and x < end[i]:\n column = i \n if y > start[i] and y < end[i]:\n row = i \n return [row, column]", "def screen_xy_to_tile_xy(x, y):\n if x < TILE_SIZE:\n tile_x = 0\n elif x < 2 * TILE_SIZE:\n tile_x = 1\n else:\n tile_x = 2\n if y < TILE_SIZE:\n tile_y = 0\n elif y < 2 * TILE_SIZE:\n tile_y = 1\n else:\n tile_y = 2\n return tile_x, tile_y", "def pixelcoord(x, y):\n xp = a * x + b * y + minX\n yp = d * x + e * y + minY\n return xp, yp", "def getGridCoordinates(self, x, y):\n\n # add offset\n x += self.x_robot\n y += self.y_robot\n\n # limit to grid size\n if x < 0 or x > self.x_size:\n return\n if y < 0 or y > self.y_size:\n return\n\n # Coord Transformation: Place origin in middle of coord-system and reverse y-axis\n xi = int(x/self.cell_size)\n yi = int((self.height-y)/self.cell_size)\n\n\n return [xi, yi]", "def grid_to_world(self, (x,y)):\n #get importatn info out of mapdata\n resolution=self.metadata.resolution\n origin=self.metadata.origin.position\n #convert point\n return Point(x=((x+.5)*resolution+origin.x),y=((y+.5)*resolution+origin.y),z=0)", "def pixel_coordinates(nx, ny, mode=\"centers\"):\n if mode == \"centroids\":\n mode = \"centers\"\n x = np.linspace(0, nx, num=nx + 1)\n y = np.linspace(0, ny, num=ny + 1)\n if mode == \"centers\":\n x = x + 0.5\n y = y + 0.5\n x = np.delete(x, -1)\n y = np.delete(y, -1)\n X, Y = np.meshgrid(x, y)\n coordinates = np.empty(X.shape + (2,))\n coordinates[:, :, 0] = X\n coordinates[:, :, 1] = Y\n return (coordinates)", "def get_coordinates_from_square(board_dim, row, col):\n return row * WIDTH / board_dim, col * HEIGHT / board_dim", "def pixel_to_position(self, pixel):\n return int(pixel[1] // self._grid_width), int(pixel[0] // self._grid_width)", "def getpixel(x,y):\n return tuple(int.to_bytes(windll.gdi32.GetPixel(dc,x,y), 3, \"little\"))", "def grid_to_index(self, x, y):\n index = y * self.map.info.width + x\n return index", "def toNativePixelCoordinates(self, x, y, crs=None, roundResults=True):\n srcCrs = self.projection if crs is None else make_crs(crs)\n\n # convert to the native projection\n dstCrs = make_crs(self.getCrs())\n [px], [py] = warp.transform(srcCrs, dstCrs, [x], [y])\n\n # convert to native pixel coordinates\n af = self._getAffine()\n d = af[1] * af[3] - af[0] * af[4]\n x = (af[2] * af[4] - af[1] * af[5] - af[4] * px + af[1] * py) / d\n y = (af[0] * af[5] - af[2] * af[3] + af[3] * px - af[0] * py) / d\n\n # convert to integer if requested\n if roundResults:\n x, y = int(round(x)), int(round(y))\n\n return x, y", "def tiles_to_pixels(p):\n return tuple(x * TILE_SIZE for x in p)", "def pixel2pixel(x1, y1, img_wcs1, img_wcs2):\n coord1 = img_wcs1.pixel_to_world(x1, y1)\n x2, y2 = img_wcs2.world_to_pixel(coord1)\n\n return x2, y2", "def pixel_to_subtile(self, x: int, y: int) -> tuple[float, float]:\n with ffi.new(\"double[2]\", (x, y)) as xy:\n _check(lib.TCOD_context_screen_pixel_to_tile_d(self._p, xy, xy + 1))\n return xy[0], xy[1]", "def __generate_grid_coords(self, spacing: np.ndarray) -> np.ndarray:\n x, y, z = [range(0, s, spacing)\n for s in self.img.shape]\n grid = np.meshgrid(x, y, z)\n return np.vstack(map(np.ravel, grid)).T", "def xy_to_grid(self, xy_position):\n x, y = xy_position\n\n column = (x - self.BORDER // 2) // (self.CELL_LENGTH + self.CELL_SPACING)\n row = (y - self.BORDER // 2) // (self.CELL_LENGTH + self.CELL_SPACING)\n\n return row, column" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws every block currently on the screen.
def draw(self): for row in range(4, 24): for col in range(0, 10): if self.grid[row][col][0]: x, y = self.grid2pix(col, row) block_image = pygame.image.load(self.grid[row][col][1]) \ .convert() self.screen.blit(block_image, [x, y, BLOCK_WIDTH, BLOCK_HEIGHT])
[ "def block(self):\n # First blank the previous position\n for x, y in self.game.block.last():\n y -= self.game.grid.top_buffer\n if y >= 0:\n self.pixel(x, y, 0)\n # Then draw the new position\n for x, y in self.game.block.position():\n y -= self.game.grid.top_buffer\n #self.print(\"y new: \" + str(y))\n if y >= 0:\n self.pixel(x, y, self.game.block.color)\n # Finally refresh the screen\n self.refresh()", "def paint(self, screen):\n paint_block(screen, self.loc, self.color)", "def _draw_all(self) -> None:\n self._draw_player()\n self._draw_world()", "def draw(self):\n for boid in self.boids:\n boid.draw()", "def draw_all(self):\n pass", "def draw_snake(self):\n self.surface.fill(util.WHITE) # clear the last frame snake\n\n for block in self.snake_list:\n pygame.draw.rect(self.surface, (255, 0, 0), [block[0], block[1], util.SNAKE_SIZE, util.SNAKE_SIZE])", "def draw(self) -> None:\n if SHOW_OUTLINE:\n pg.draw.rect(self._screen, RED, self._rect, width=1)\n pg.draw.rect(self._screen, self._bg_color, self._rect)\n pg.draw.rect(self._screen, GRAY, self._rect, width=1)\n for _, sb in self._scoreboxes.items():\n sb.draw()\n\n pg.display.update(self._rect)", "def draw_block(self,x,y,w,h,color):\n\t\tif((x >= self.width) or (y >= self.height)):\n\t\t\treturn\n\t\tif (x + w - 1) >= self.width:\n\t\t\tw = self.width - x\n\t\tif (y + h - 1) >= self.height:\n\t\t\th = self.height - y\n\t\tself.set_window(x,y,x+w-1,y+h-1)\n\t\tb=[color>>8, color & 0xff]*w*h\n\t\tself.data(b)", "def redraw_obstacles(self):\n for i in self.blocked:\n pdraw.rect(self._display, COLOURS['black'], (i[0], i[1], 19, 19))", "def draw_grid(self):\r\n\r\n for x in range(0, FULLSIZE[0], CELLSIZE):\r\n pygame.draw.line(self.screen, GRAY, (x, 0), (x, FULLSIZE[0]))\r\n for y in range(0, FULLSIZE[1], CELLSIZE):\r\n pygame.draw.line(self.screen, GRAY, (0, y), (FULLSIZE[0], y))\r\n\r\n for x in range(0, FULLSIZE[0], CUBESIZE):\r\n pygame.draw.line(self.screen, BLACK, (x, 0), (x, FULLSIZE[0]), 2)\r\n for y in range(0, FULLSIZE[1], CUBESIZE):\r\n pygame.draw.line(self.screen, BLACK, (0, y), (FULLSIZE[0], y), 2)", "def draw():\n for item in _viewport:\n if item.enabled:\n item.draw()", "def draw_section(self): \n ## Set section postitions based on num\n if self.num <= 3:\n self.left = float(self.width * (self.num - 1))\n self.top = 0\n elif self.num > 3 and self.num <= 6:\n self.left = float(self.width * (self.num % 3))\n self.top = float(self.height) \n elif self.num > 6 and self.num <= 9:\n self.left = float(self.width * (self.num % 3))\n self.top = float(self.height * 2)\n \n ## Create rect\n # print(self.left, self.top, self.width, self.height)\n self.rect = pygame.Rect((self.left, self.top),\n (self.width, self.height))\n \n ## Create 9 blocks for each section\n self.blocks = pygame.sprite.Group()\n for num in range(1,10):\n block = Block(num, self.game)\n self.blocks.add(block)\n \n ## Draw section with blocks\n for block in self.blocks.sprites():\n pygame.draw.rect(rect=self.rect, \n color=(0,0,0), \n surface=self.screen, \n border_radius=0)\n block.draw_block(self.left, self.top)\n \n ## Draw section borders\n pygame.draw.lines(surface=self.screen,\n color=(0,255,0),\n closed=True,\n points = [(self.left, self.top), \n (self.left, self.top + self.height),\n (self.left + self.width, self.top + self.height),\n (self.left + self.width, self.top)])\n \n # Draw blocks for section\n # for num in range(1,10):\n # for block in self.blocks.sprites():\n # block.draw_block(self.num)", "def draw_board(self, canvas):\n #for column_num in range(0, WIDTH):\n # canvas.draw_line((column_num * BOX_SIZE, 0), (column_num * BOX_SIZE, HEIGHT * BOX_SIZE), 0.2, '#000000')\n #for row_num in range(0, HEIGHT):\n # canvas.draw_line((0, row_num * BOX_SIZE), (WIDTH * BOX_SIZE, row_num * BOX_SIZE), 0.2, '#000000')\n \n for row_num, row in enumerate(self._layout):\n for column_num, block_name in enumerate(row):\n if block_name != 0:\n square_colour = BLOCK_COLOURS[block_name]\n \n canvas.draw_polygon([(0 + column_num * BOX_SIZE, 0 + row_num * BOX_SIZE),\n (BOX_SIZE + column_num * BOX_SIZE, 0 + row_num * BOX_SIZE), \n (BOX_SIZE + column_num * BOX_SIZE, BOX_SIZE + row_num * BOX_SIZE), \n (0 + column_num * BOX_SIZE, BOX_SIZE + row_num * BOX_SIZE)], \n 0.0001, '#FFFFFF', square_colour)", "def draw(self, display):\r\n if not self.selected:\r\n colour = BLUE\r\n else:\r\n colour = LIGHTBLUE\r\n pg.draw.rect(display,\r\n colour,\r\n (self.x*TILE_SIZE+self.indent,\r\n self.y*TILE_SIZE+self.indent,\r\n self.size[0]*TILE_SIZE-2*self.indent,\r\n self.size[1]*TILE_SIZE-2*self.indent))", "def _draw_background(self):\r\n for i in range(self._size):\r\n for j in range(self._size):\r\n self._grid.draw_entity((i, j), BACK_GROUND)", "def drawAll(self):\r\n self.draw()\r\n if self.next: # if self.next exists\r\n self.next.drawAll()", "def on_draw(self):\n self.clear()\n self.arch.draw()\n self.bullet.draw()\n\tfps_display.draw()", "def draw(self, player, things):\n self.surface.fill(pygame.Color('white'))\n for thing in things:\n thing.update()\n seeThing = player.sees(thing)\n x = seeThing[0] + (const.TILESIZE*(const.TILESWIDE/2))\n y = seeThing[1] + (const.TILESIZE*(const.TILESWIDE/2))\n rec = (x,y,const.TILESIZE,const.TILESIZE)\n pygame.draw.rect(self.surface, pygame.Color('black'), rec, 0)\n pygame.display.flip()\n return pygame.event.get()", "def draw(self, canvas):\n for state in self.states:\n state.draw(canvas)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the embeddings (also external) for every term in a sentence Returns a vector of all embeddings concatenated
def getWordEmbeddings(self, sentence, train): for root in sentence: c = float(self.wordsCount.get(root.norm, 0)) dropFlag = not train or (random.random() < (c/(0.25+c))) sys.stdout.flush() root.wordvec = self.wlookup[int(self.vocab.get(root.norm, 0)) if dropFlag else 0] root.cposvec = self.plookup[int(self.cpos.get(root.cpos,0))] if self.pdims > 0 else None #For word embeddings if self.external_embedding is not None: if root.form in self.external_embedding: root.evec = self.elookup[self.extrnd[root.form]] elif root.norm in self.external_embedding: root.evec = self.elookup[self.extrnd[root.norm]] else: if (self.oov_external_embedding is not None and root.form.replace(" ","_") in self.oov_external_embedding): root.evec = self.oov_elookup[self.oov_extrnd[root.form.replace(" ","_")]] else: root.evec = self.elookup[0] else: root.evec = None #For cpostag embeddings if self.cpos_external_embedding is not None: if root.cpos in self.cpos_external_embedding: root.cposevec = self.cpos_elookup[self.cpos_extrnd[root.cpos]] else: root.cposevec = self.cpos_elookup[0] else: root.cposevec = None #For postag embeddings if self.pos_external_embedding is not None: if root.pos in self.pos_external_embedding: root.posevec = self.pos_elookup[self.pos_extrnd[root.pos]] else: root.posevec = self.pos_elookup[0] else: root.posevec = None # #For feats embeddings if self.feats_external_embedding is not None: if root.feats in self.feats_external_embedding: root.featsevec = self.feats_elookup[self.feats_extrnd[root.feats]] else: root.featsevec = self.feats_elookup[0] else: root.featsevec = None #For lemmas embeddings # if self.lemmas_external_embedding is not None: # if root.lemma in self.lemmas_external_embedding: # root.lemmasevec = self.lemmas_elookup[self.lemmas_extrnd[root.lemma]] # else: # root.lemmasevec = self.lemmas_elookup[0] # else: # root.lemmasevec = None # root.ivec = concatenate(filter(None, [root.wordvec, root.cposvec, root.evec, root.cposevec, root.posevec, root.featsevec, root.lemmasevec])) root.ivec = concatenate(filter(None, [root.wordvec, root.cposvec, root.evec, root.cposevec, root.posevec, root.featsevec])) if self.blstmFlag: forward = self.surfaceBuilders[0].initial_state() backward = self.surfaceBuilders[1].initial_state() for froot, rroot in zip(sentence, reversed(sentence)): forward = forward.add_input( froot.ivec ) backward = backward.add_input( rroot.ivec ) froot.fvec = forward.output() rroot.bvec = backward.output() for root in sentence: root.vec = concatenate( [root.fvec, root.bvec] ) if self.bibiFlag: bforward = self.bsurfaceBuilders[0].initial_state() bbackward = self.bsurfaceBuilders[1].initial_state() for froot, rroot in zip(sentence, reversed(sentence)): bforward = bforward.add_input( froot.vec ) bbackward = bbackward.add_input( rroot.vec ) froot.bfvec = bforward.output() rroot.bbvec = bbackward.output() for root in sentence: root.vec = concatenate( [root.bfvec, root.bbvec] ) else: for root in sentence: root.ivec = (self.word2lstm.expr() * root.ivec) + self.word2lstmbias.expr() root.vec = tanh( root.ivec )
[ "def words_embedding(words: list, glove):\n\n word_embeddings = map(partial(get_word_vec, glove=glove), words)\n concat_words_embedding = np.concatenate(list(word_embeddings))\n return concat_words_embedding", "def get_embeddings(tokenizer, model, texts):\n inputs = tokenizer(texts,\n padding=True,\n truncation=True,\n return_tensors=\"pt\",\n max_length=512)\n result = model(**inputs)\n embeddings = result.last_hidden_state[:, 0, :]\n return embeddings", "def vectorizeSentence(self, sentence):\n embeddedSentence = []\n vectorSize = self.model.vector_size\n\n for word in sentence:\n embedding = np.zeros(vectorSize)\n if(word == \"[None]\"):\n embedding = np.zeros(vectorSize)\n else:\n if(word in self.model):\n embedding = self.model[word]\n embedding=np.array(embedding)\n else:\n embedding=np.zeros(vectorSize)\n\n embeddedSentence += [embedding]\n\n return embeddedSentence", "def embed_words(self, words: List[str], verbose: bool = False) -> np.ndarray:\n embeddings = self.embedding_model.encode(words, show_progress_bar=verbose) \n return embeddings", "def embed(sentences, embedding_path):\n if embedding_path is not None:\n glove, emb_dim = load_glove(embedding_path)\n else:\n glove={}\n emb_dim=300\n embeddings = []\n\n for sentence in sentences:\n sentence_len = len(sentence)\n embedding = []\n for word in sentence:\n try:\n word_embeding = glove[word]\n except KeyError:\n word_embeding = np.random.normal(scale=0.6, size=(emb_dim,))\n glove[word] = word_embeding\n embedding.append(torch.as_tensor(word_embeding))\n torch_embedding = torch.cat(embedding, dim=0)\n # TODO Hyperparamater what to do with special tags specified in the tokenizer\n # Either a random array, array of zeros or use the word in the tag i.e. for \"#date#\" use \"date\"\n embeddings.append(torch.reshape(torch_embedding, (emb_dim, sentence_len)))\n\n return embeddings", "def extract_embeddings(self, text):\n tokens_tensor = self.tokenize_input(text)\n pooled, hidden_states = self.model(tokens_tensor)[-2:]\n last_4 = [hidden_states[i] for i in (-1, -2, -3, -4)]\n cat_hidden_states = torch.cat(tuple(last_4), dim=-1)\n return torch.mean(cat_hidden_states, dim=1).squeeze()", "def get_embeddings(self, sent):\n if sent is None:\n sent = []\n embs = [self.GO]\n for form, tag in sent:\n if len(embs) > 1:\n embs.append(self.dict[' '])\n for char in form:\n # append the token ID, or <UNK>\n embs.append(self.dict.get(char, self.UNK))\n\n embs += [self.STOP]\n if len(embs) > self.max_sent_len + 2:\n embs = embs[:self.max_sent_len + 2]\n elif len(embs) < self.max_sent_len + 2:\n embs += [self.VOID] * (self.max_sent_len + 2 - len(embs))\n\n if self.reverse:\n return list(reversed(embs))\n return embs", "def fetch_bert_embeddings(topic_docs):\n embeddings = []\n sentences = []\n for doc in topic_docs:\n doc_sents = util.split_into_sentences(nlp, doc)\n sentences.extend(doc_sents)\n doc_embs = bc.encode(doc_sents)\n # print(len(doc_embs[0]))\n embeddings.extend(doc_embs)\n embeddings = np.array(embeddings)\n return embeddings, sentences", "def apply_embeddings(sequence, embeddings_dict, tokenizer):\n\n if sequence:\n embeddings = [embeddings_dict['SOS']]\n embeddings.extend([embeddings_dict[token] if token in embeddings_dict else embeddings_dict['UNK']\n for token in tokenizer(sequence)])\n embeddings.append(embeddings_dict['EOS'])\n # if vectorizor:\n # embeddings = [vectorizor(embedding) for embedding in embeddings]\n return embeddings\n\n else: # In case input sequence is empty\n return [embeddings_dict['SOS'], embeddings_dict['EOS']]", "def sif_embeddings(sentences, model, vocab_freq, alpha=1e-3):\n\n vlookup = vocab_freq # Gives us access to word index and count\n vectors = model # Gives us access to word vectors\n size = model.vector_size # Embedding size\n\n Z = sum(vlookup.values())\n\n output = []\n\n # Iterate all sentences\n for s in sentences:\n v = np.zeros(size, dtype=REAL) # Summary vector\n # Iterate all words\n count = 0\n for w in s.split():\n # A word must be present in the vocabulary\n if w in vectors and w in vlookup:\n v += (alpha/(alpha + (vlookup[w] / Z))) * vectors[w]\n count += 1\n if count > 0:\n v = v/count\n output.append(v)\n return np.column_stack(tuple(output)).astype(REAL)", "def generate_embeddings(self):\n docs = self.DB_manger.get_all()\n if docs is None:\n return 1\n\n corpus = []\n corpus_embeddings = []\n parallel_cid_list_local = []\n for doc in docs:\n corpus.append(doc[\"content\"])\n corpus_embeddings.append(pickle.loads(doc[\"encoding\"]))\n parallel_cid_list_local.append(doc[\"cid\"])\n\n # turn list of loaded tensors to a single tensor\n corpus_embeddings = [torch.unsqueeze(t, dim=0) for t in corpus_embeddings]\n corpus_embeddings = torch.cat(corpus_embeddings, dim=0)\n\n self.bert.set_corpus(corpus)\n self.bert.set_corpus_embeddings(corpus_embeddings)\n self.parallel_cid_list = parallel_cid_list_local", "def get_word_embeddings(self):\n\n # Load vocabulary\n self._load_vocabulary()\n\n # Get save dir\n save_dir = self._get_save_dir()\n embeddings = np.load('{0}/L.npy'.format(save_dir))\n\n return embeddings, self.vocabulary_", "def glove_define_get_word_vectors(args):\n import numpy as np\n\n word_index = dict()\n vectors = []\n\n with open(args.word_embedding_path) as f:\n for i, line in enumerate(f.readlines()):\n word = line.split()[0]\n vector = np.array(line.split()[1:])\n vector = np.apply_along_axis(float, 1, vector.reshape(-1, 1))\n\n word_index[word] = i\n vectors.append(vector.reshape(1, -1))\n\n embeddings = np.concatenate(vectors, axis=0)\n\n def get_word_vectors(words):\n \"\"\"\n Returns word vectors represent words\n :param words: iterable of words\n :return: (len(words), dim) shaped numpy ndarrary which is word vectors\n \"\"\"\n word_ids = [word_index[w] for w in words if w in word_index]\n return embeddings[word_ids]\n\n return get_word_vectors", "def getTextVectors():\n raw_text_file = open(utilites.getAbsPath(setup.corpus_file_path))\n raw_text = raw_text_file.readlines()\n print(\"Corpus file \" + raw_text_file.name + \" was loaded.\")\n # use re to split the raw text string and replace the original text\n # After this all the sentence are split into such format:\n # [0]filename, [1]order of annotation, [2]annotation text\n raw_text = [re.split('\\t|#', singleLine.replace('\\n', '')) for singleLine in raw_text]\n\n # now we only need the annotations\n annotations = [line[2] for line in raw_text]\n\n # Prepare the sentences\n sentences = annotation_to_wordlists(annotations)\n\n # Set values for Word2Vec\n num_features = 300 # Use a 300-dimension vector to represent a word\n min_word_count = 5 # Word appears less than 5 times will be ignored\n num_workers = 4 # Number of threads to run in parallel\n context = 5 # Sample 5 words as input for each iteration\n\n # initialize a model using parameters above\n word_model = gensim.models.Word2Vec(workers=num_workers,\n size=num_features, min_count=min_word_count, window=context)\n\n word_model.build_vocab(sentences) # build vocabulary on split sentenced\n print(\"Language model established.\")\n print(\"Loading pre-trained language model...\")\n # initialize the network weights using pre-trained model\n word_model.intersect_word2vec_format(utilites.getAbsPath(setup.lmodel_file_path), binary=True)\n print(\"Loaded weights from pre-trained Google News language model.\")\n print(\"Training models...\")\n # train the model to get word vectors\n word_model.train(sentences)\n print(\"Training completed.\")\n\n return extractVecs(word_model)", "def _merge_sentences(text):\n\n return [word for sentence in text for word in sentence]", "def buildWordVector(text, size, model, google):\n vec = np.zeros(size).reshape((1, size))\n count = 0.\n for word in text:\n try:\n if not google:\n vec += model.wv.__getitem__(word).reshape((1, size))\n else:\n vec += model.__getitem__(word).reshape((1, size))\n count += 1.\n except KeyError:\n continue\n if count != 0:\n vec /= count\n return vec", "def add_embedding(self):\n self.embeddings = tf.Variable(tf.constant(self.wv, dtype=tf.float32))\n # The embedding lookup is currently only implemented for the CPU\n with tf.device('/cpu:0'):\n return tf.reshape(tf.nn.embedding_lookup(self.embeddings, self.input_placeholder),\n (-1, self.config.window_size * self.config.embed_size))", "def central_embedding(self, tokens):\n return np.average( [self.word2vec( i ) for i in tokens], axis=0 )", "def _generate_lemma_embs_with_special_tokens(sentences, model, tokenizer, lsc):\n inline_lemmas = _extract_lemmas_from_sentences(sentences)\n\n # clean sentences\n clean_sentences = []\n for dirty_sentence in sentences:\n clean_sentences.append(dirty_sentence.replace('_&', ' ').replace('&_', ' '))\n\n lemma_embeddings = []\n for sentence, lemma in zip(clean_sentences, inline_lemmas):\n lemma_id = tokenizer.encode(lemma)[0]\n sentence_ids = tokenizer.encode(sentence)\n shortened_sentence_ids = _shorten_ids(sentence_ids, sentence_ids.index(lemma_id),\n 1, lsc) # map sentence to list of IDs representing it\n\n # generate contextualized embeddings,\n # unsqueeze IDs to get batch size of 1 as added dimension\n with torch.no_grad():\n embeddings = model(input_ids=torch.tensor(shortened_sentence_ids).unsqueeze(0))[0]\n\n # cut the lemma embeddings out of these sentence embeddings, convert them into numpy array\n current_lemma_embeddings = embeddings[0][sentence_ids.index(lemma_id)].detach().numpy()\n\n # add current lemma embeddings to the list\n lemma_embeddings.append(current_lemma_embeddings)\n\n return lemma_embeddings" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funcion que devuelve un diccionario que contiene el valor de poblacion por cada pais y anno almacenado en el fichero, SALVO la segunda columna
def crecimiento_por_pais_anno(fichero): if not os.path.exists(fichero): raise FileNotFoundError("Error. El fichero no se encuentra en el directorio actual") elif not fichero.endswith(".csv"): raise Exception("Error. El fichero debe estar en formato csv") elif os.stat(fichero).st_size == 0: raise StopIteration("Error. El fichero esta vacio") with open(fichero) as archivo: archivo_csv = csv.reader(archivo, delimiter=",") next(archivo_csv) filas = [fila for fila in archivo_csv] if len(filas) < 3: raise IndexError("Error. El fichero debe tener como minimo tres columnas") paises = sorted(set(fila[0] for fila in filas)) [fila.pop(1) for fila in filas] return {pais: crecimiento_por_pais([fila[1:] for fila in filas if pais in fila]) for pais in paises}
[ "def carica_dati_da_regione_piemonte():\n # elenco dei file csv con i dati dei positivi\n ifiles = sorted(Path('data').glob(\"dati*_da_regione_piemonte.csv\"))\n # read all the files into a dataframe array\n dfall = pd.concat((pd.read_csv(ifile, sep=\";\",\n dtype={\"Comune\": \"string\",\n \"Codice ISTAT\": \"string\",\n \"Abitanti\": \"int64\",\n \"Positivi\": \"int64\",\n \"Rapporto\": \"float64\",\n \"Data\": \"object\"\n }) for ifile in ifiles), axis=0)\n # print(\"Numero righe comuni \", dfall.shape[0])\n\n # tipo ente è comune\n dfall['Tipo'] = 'COM'\n\n # aggiungi la provincia\n dfall['Provincia'] = dfall.apply(provincia, axis=1)\n\n # rinomina colonna Comune\n dfall.rename({'Comune': 'Ente'}, axis=1, inplace=True)\n return dfall", "def recuperar_puntajes(nombre_archivo):\n\n puntajess = [] # tanto el los archivos de texto y csv teniamos que crear una lista nueva vacia, en cambio en el archivo binario no es necesario. porque en los binarios nos va a devolver desde un principio como lo guardamos, es decir si lo guardamos como lista nos devuelve como lista y si fue como diccionaro de la misma manera.\n with open(nombre_archivo, \"r\") as f:\n for linea in f:\n print(\"estoy leyendo\", linea) # ACA VA A GUARDAR LINEA POR LINEA, CON SALTO DE LINEA, O TUPLA COMO QUIERA LLAMARSE A LA LINEA\n nombre, puntaje, tiempo = linea.rstrip(\"\\n\").split(\",\") # aca va a tomar una linea con el modulo rstrip y la \\n siginifica que va a sacar un salto de linea, es util a la hora de guardar en el archivo pero no al recuperar los datos y tambien saca la coma con split.\n puntajess.append((nombre, int(puntaje),tiempo))\n\n return puntajess", "def tabuleiro_pontuacao(tab):\n return tab[4]", "def continente_pais ( self , pais ) :\n\n for i1iIIIiI1I in self . continentes :\n if 70 - 70: Oo0Ooo % Oo0Ooo . IiII % OoO0O00 * o0oOOo0O0Ooo % oO0o\n if pais in self.continentes[i1iIIIiI1I] :\n return i1iIIIiI1I\n if 23 - 23: i11iIiiIii + I1IiiI", "def leer_datos():\n with open(\"Bogota_covid19.csv\",\"r\") as tabla:\n lineas = tabla.read().splitlines()\n for i in range(len(lineas)):\n lineas[i] = lineas[i].split(\",\")\n borrarPantalla()\n\n return lineas", "def __partePariDisp(self, car, p):\n\n cf = f\"{self.creaParteCognome()}{self.creaParteNome()+self.creaParteData()+self.creaParteLuogo()}\"\n\n parametro = 0\n\n for i in range(p, len(cf), 2):\n for d in car:\n if cf[i] + ';' in d:\n parametro += int(d.split(';')[1])\n return parametro # Restitusce la somma dei codici dei caratteri in posizione Pari (p=1) e Dispari (p=0)", "def extractColumns(self, dxlFileContent):\n extractedCols = []\n position = 1\n \n columns = dxlFileContent.getElementsByTagName('column')\n \n for column in columns:\n dico = {}\n dico['type'] = 'PlominoColumn'\n dico['id'] = column.getAttribute('itemname')\n dico['title'] = column.getElementsByTagName(\"columnheader\")[0].getAttribute('title')\n dico['position'] = position\n position += 1\n \n # get the Formula attribute for this column\n if column.getElementsByTagName('code') != []:\n codeColumns = column.getElementsByTagName('code')[0]\n if codeColumns.getAttribute('event') == 'value':\n dico['formula'] ='plominoDocument.' + \\\n codeColumns.getElementsByTagName('formula')[0].firstChild.nodeValue\n else:\n dico['formula'] ='plominoDocument.' + dico['id']\n \n # TODO: cherche si la formule matche avec un field connu\n # utiliser les regex pourrait être un bon moyen\n # comment récupérer les champs field ? \n # par self.getFields ou vérifier que self.getField(attValue) existe ?\n # mais comment récupérer les bon form sans perdre de temps à tout parcourir ?\n \n extractedCols.append(dico)\n \n return extractedCols", "def paises_limitrofes ( self , pais ) :\n\n return self . limitrofes [ pais ]\n if 17 - 17: o0oOOo0O0Ooo\n if 64 - 64: Ii1I % i1IIi % OoooooooOO", "def contar_fichas(self):\n j1 = 0\n j2 = 0\n vacio = 0\n\n for x in range(6):\n for y in range(6):\n if self.tablero[x][y] == 1:\n j1 = j1 + 1\n elif self.tablero[x][y] == 2:\n j2 = j2 + 1\n elif self.tablero[x][y] == 0 or self.tablero[x][y] == 3:\n vacio = vacio + 1\n\n return j1, j2, vacio", "def load_docs(self, path):\n df = pd.read_csv(path)\n df['numero_PL'] = df['numero_fecha_PL'].apply(lambda x: x.split('-')[0][-4:]) # keeps only the last 4 digits of the PL number\n df['texto'] = df['texto'].apply(lambda x: self.cleanup_text(x))\n # print(df.head(10))\n return df", "def getdata(data,vers='dr2',posn_match=30,verbose=True) :\n\n tab=Table()\n tab.add_column(Column(data['APOGEE_ID'],name='twomass'))\n tab.add_column(Column(data['RA'],name='apogee_ra'))\n tab.add_column(Column(data['DEC'],name='apogee_dec'))\n #if type(data['APOGEE_ID'][0]) is str or type(data['APOGEE_ID'][0]) is np.str_ : \n try:\n j=np.where(np.core.defchararray.find(data['APOGEE_ID'],'2M') == 0)[0]\n out,ind=np.unique(np.core.defchararray.replace(data['APOGEE_ID'][j],'2M',''),return_index=True)\n except :\n j=np.where(np.core.defchararray.find(data['APOGEE_ID'],b'2M') == 0)[0]\n out,ind=np.unique(np.core.defchararray.replace(data['APOGEE_ID'][j],b'2M',b''),return_index=True)\n tab['twomass'][ind] = out\n #tab.add_column(Column(out,name='twomass'))\n #tab.add_column(Column(data['RA'][ind],name='apogee_ra'))\n #tab.add_column(Column(data['DEC'][ind],name='apogee_dec'))\n xmlfilename= tempfile.mktemp('.xml',dir=os.getcwd())\n tab.write(xmlfilename,format='votable',overwrite=True)\n if vers == 'dr2' :\n try :\n job= Gaia.launch_job_async(\n \"\"\"SELECT tmass_match.original_ext_source_id, g.source_id, g.ra, g.dec, g.parallax, g.parallax_error, \n g.pmra, g.pmra_error, g.pmdec, g.pmdec_error, g.ref_epoch,\n g.phot_g_mean_mag, g.phot_bp_mean_mag, g.phot_rp_mean_mag, \n g.radial_velocity, g.radial_velocity_error, g.a_g_val, g.e_bp_min_rp_val, \n dist.r_est, dist.r_lo, dist.r_hi\n FROM gaiadr2.gaia_source AS g\n INNER JOIN gaiadr2.tmass_best_neighbour AS tmass_match ON tmass_match.source_id = g.source_id\n INNER JOIN tap_upload.my_table as ids on ids.twomass = tmass_match.original_ext_source_id\n LEFT OUTER JOIN external.gaiadr2_geometric_distance as dist ON g.source_id = dist.source_id\"\"\",\n upload_resource=xmlfilename,upload_table_name='my_table',verbose=verbose)\n twomass_gaia = job.get_results()\n except:\n print(\"error with gaia 2mass search\")\n twomass_gaia = None\n else : twomass_gaia = None\n\n try: \n if vers == 'dr2' :\n job= Gaia.launch_job_async(\n \"\"\"SELECT g.source_id, g.ra, g.dec, g.parallax, g.parallax_error, \n g.pmra, g.pmra_error, g.pmdec, g.pmdec_error, g.ref_epoch,\n g.phot_g_mean_mag, g.phot_bp_mean_mag, g.phot_rp_mean_mag, \n g.radial_velocity, g.radial_velocity_error, g.a_g_val, g.e_bp_min_rp_val, \n dist.r_est, dist.r_lo, dist.r_hi,\n distance(\n point('', ids.apogee_ra, ids.apogee_dec),\n point('', g.ra, g.dec)\n ) * 3600 as dist_arcsec\n FROM gaiadr2.gaia_source as g\n JOIN tap_upload.my_table as ids on 1 = contains(\n point('', ids.apogee_ra, ids.apogee_dec),\n circle('', g.ra, g.dec, {:f})\n )\n LEFT OUTER JOIN external.gaiadr2_geometric_distance as dist ON g.source_id = dist.source_id\"\"\".format(posn_match/3600.),\n upload_resource=xmlfilename,upload_table_name='my_table',verbose=verbose)\n posn_gaia = job.get_results()\n print('returned ', len(posn_gaia))\n elif vers == 'edr3' :\n service = pyvo.dal.TAPService(\"https://dc.zah.uni-heidelberg.de/tap\")\n # this used to work but stopped\n #posn_gaia = service.search(\n # \"\"\"SELECT * FROM gedr3dist.litewithdist as g\n # JOIN TAP_UPLOAD.coords as coords \n # ON contains(POINT('ICRS', g.ra, g.dec),CIRCLE('ICRS',coords.apogee_ra, coords.apogee_dec,{:f})) = 1\"\"\".format(posn_match/3600.),\n # uploads={'coords' : tab})\n # Markus at GAVO recommended:\n posn_gaia = service.search(\n \"\"\"WITH withpar AS (\n SELECT *\n FROM gaia.edr3lite AS db\n JOIN TAP_UPLOAD.coords AS coords\n ON distance(db.ra, db.dec, coords.apogee_ra, coords.apogee_dec)< {:f}) \n SELECT * from withpar\n JOIN gedr3dist.main as dist using (source_id)\n \"\"\".format(posn_match/3600.), uploads={'coords' : tab},maxrec=1000000)\n print('pyvo returned: ',len(posn_gaia))\n\n #m1,m2=match.match(posn_gaia_archive['source_id'],posn_gaia['source_id'])\n #print(len(m1),len(m2))\n\n except: \n print(\"error with gaia position search\")\n posn_gaia = None\n finally: os.remove(xmlfilename)\n\n return twomass_gaia, posn_gaia", "def provincia(row):\n return PROV[str(row[\"Codice ISTAT\"][:3])]", "def filtrarCsvPorIgual(df,diccionario): \n for valor in diccionario:\n try:\n df = df[df[valor] == diccionario[valor]]\n \n except:\n print (f\"ARCHIVO NO FILTRADO.ERROR AL FILTRAR POR INGRESAR {valor}\")\n \n return df", "def obtenerPDFAlumno(idAsignacion, idAlumno, idDocumento):\n\tsql = \"select nombre, documento \" \\\n\t\t\"from documentosalumnos where idDocumentoAlumno=%s and idAsignacion=%s and noControl=%s;\"\n\tdatos = (idDocumento, idAsignacion, idAlumno)\n\tfilas = executeQueryWithData(sql, datos)\n\tfila = filas[0]\n\ttitulo = fila['nombre']\n\tarchivo = fila['documento']\n\tpdf = utils.generaVistaPDFConTitulo(archivo, f\"{titulo}-{idAlumno}\")\n\treturn pdf", "def datosProyecto(self, proyecto):\n thead = self.estiloHoja['Heading5']\n thead.alignment=TA_CENTER\n tbody = self.estiloHoja[\"BodyText\"]\n tbody.alignment=TA_LEFT\n contenido=[]\n contenido.append([Paragraph('Nombre de Proyecto',thead),Paragraph(proyecto.nombre,tbody)])\n tabla = Table(contenido)\n lider = MgrProyecto().getLider(proyecto.nombre)\n contenido.append([Paragraph('Lider de Proyecto',thead),Paragraph(lider,tbody)])\n contenido.append([Paragraph('Estado de Proyecto',thead),Paragraph(proyecto.estado,tbody)])\n contenido.append([Paragraph('Presupuesto de Proyecto',thead),Paragraph(str(proyecto.presupuesto),tbody)])\n contenido.append([Paragraph('Fecha de Creacion de Proyecto',thead),Paragraph(str(proyecto.fechaDeCreacion),tbody)])\n contenido.append([Paragraph('Descripcion del Proyecto',thead),Paragraph(proyecto.descripcion,tbody)])\n comite = MgrComite().search(proyecto.nombre)\n contenido.append([Paragraph('Nombre de Comite del Proyecto',thead),Paragraph(comite.nombre,tbody)])\n contenido.append([Paragraph('Cantidad de Miembros',thead),Paragraph(str(comite.cantMiembro),tbody)])\n tabla = Table(contenido)\n tabla.setStyle(self.tablaStyle)\n return tabla", "def padrones_x_estudio(id_estudioc): \r\n cursor = connection.cursor()\r\n cursor.execute(\"SELECT c.id_padron,c.padron,c.nombre as nombreResp,t.abreviatura as tipoTributo,count(c.id_padron) as cant_cuotas\\\r\n FROM dri_estudio_padron dep \\\r\n JOIN cuotas c on (c.id_padron=dep.id_padron) \\\r\n JOIN tributo t on (c.tributo=t.id_tributo) \\\r\n WHERE (dep.id_estudioc = %s)and(t.id_tributo=6) GROUP BY c.id_padron,c.padron order by c.nombre,c.padron\",[id_estudioc])\r\n padrones = dictfetchall(cursor)\r\n return padrones", "def readCsv(path, avg_data, min_data, search_factor_data, detailed, ramais, km_de_conduta, pesquisa_ramais_data, pesquisa_km_data):\n \n\n \n \n data = pandas.read_csv(path, delimiter=';', decimal=',',skiprows=2)\n\n x_avg_data=[]\n y_avg_data=[]\n \n x_min_data=[]\n y_min_data=[]\n \n x_search_factor_data=[]\n y_search_factor_data=[]\n \n if ramais!=0 and km_de_conduta!=0:\n x_pesquisa_ramais_data=[] \n y_pesquisa_ramais_data=[]\n \n x_pesquisa_km_data=[]\n y_pesquisa_km_data=[]\n \n lastDate=0\n\n for index, row in data.iterrows():\n \n date = row['Data']\n read_value = row['Leitura']\n flow = row['Caudal']\n \n currentDate=datetime.strptime(date, '%d/%m/%Y %H:%M').date()\n #new date read or end of file\n if currentDate!=lastDate or index==data.iloc[-1].name :\n #if this is not the first row of the document and date is changed execute the calculations\n if lastDate!=0:\n \n avg_flow=round(tot_flow_current_day/days,2)\n y_avg_data.insert(0,avg_flow)\n x_avg_data.insert(0,lastDate)\n \n \n x_min_data.insert(0,min_time)\n y_min_data.insert(0,min_flow)\n \n current_day_search_factor=round(min_flow/avg_flow,2)\n x_search_factor_data.insert(0,lastDate)\n y_search_factor_data.insert(0,current_day_search_factor)\n \n if detailed:\n x_pesquisa_ramais_data.insert(0,lastDate) \n y_pesquisa_ramais_data.insert(0,round(min_flow/ramais,3))\n \n x_pesquisa_km_data.insert(0,lastDate) \n y_pesquisa_km_data.insert(0,round(min_flow/km_de_conduta,3))\n \n \n \n lastDate=currentDate\n tot_flow_current_day=flow\n \n min_flow=flow\n min_time=lastDate\n \n days=1\n \n #processing data of the same date \n else: \n \n tot_flow_current_day+=float(flow)\n days+=1\n \n if flow<min_flow:\n min_flow=flow\n min_time=lastDate\n \n avg_data=PlotData(x_avg_data,y_avg_data)\n min_data=PlotData(x_min_data,y_min_data)\n search_factor_data=PlotData(x_search_factor_data,y_search_factor_data)\n \n if detailed:\n pesquisa_ramais_data=PlotData(x_pesquisa_ramais_data,y_pesquisa_ramais_data)\n pesquisa_km_data=PlotData(x_pesquisa_km_data,y_pesquisa_km_data)\n \n return avg_data, min_data, search_factor_data, pesquisa_ramais_data, pesquisa_km_data", "def cantidad_paises ( self ) :\n\n return len ( self . _paises )\n if 78 - 78: OoO0O00\n if 18 - 18: O0 - iII111i / iII111i + ooOoO0o % ooOoO0o - IiII", "def continente_pais(self, pais):\n return self.paises[pais].continente" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a string, return a list of all substrings of that string with a given length. For example, substrings_of_len(2, "ABC") returns ["AB", "BC"].
def substrings_of_length(length, string): # You could also use a generator here, but I don't want to overcomplicate # things. substrings = [] for i in range(len(string) - length): substrings.append(string[i : i + length]) return substrings
[ "def substrings(s, minlength=30):\n maxsize = current = len(s)\n result = []\n while current >= minlength:\n result.extend([s[start:start+current] \n for start in range(maxsize-current+1)])\n # range(5) is [0,1,2,3,4]\n current -= 1\n return set(result) # set() removes duplicates", "def subs_listset(string_list, sub_len):\r\n return [set(subs(x, sub_len)) for x in string_list]", "def all_substrings(strings, minlength=30):\n result = set()\n for s in strings:\n result |= substrings(s, minlength)\n # \"|=\" is the set union operator\n return result", "def vigenere_split_substrings(ciphertext, keylength):\n\n substring_list = [''] * keylength\n substring_index = 0\n offset = 0\n\n # split the ciphertext into substrings\n for letter in ciphertext:\n # offset the letter by which key iteration it is on\n new_letter_value = ord(letter) - offset\n\n # Can't use modulo, so put it back in range 65-90\n while new_letter_value < 65:\n new_letter_value += 26\n\n # add it to the list, continue\n substring_list[substring_index] += chr(new_letter_value)\n substring_index += 1\n # If we've gone past the keylength, reset to 0 and increase offset\n if substring_index == keylength:\n substring_index = 0\n offset += 1\n\n return substring_list", "def get_substrings(text):\n return [text[x:y] for x, y in combinations(range(len(text) + 1), r=2)]", "def getSubstrings(a, n):\n\n # Get substrings from string\n substrings = set()\n for i in range(0, len(a) - n + 1):\n substrings.add(a[i:i + n])\n\n return substrings", "def subs(s, count):\r\n return [s[i:(i + count)] for i in range(len(s) - count + 1)]", "def extract_sub_sequences(sequence, window_size):\n if window_size <= 0:\n return \"Window size must be a positive integer\"\n if window_size > len(sequence):\n return \"Window size is larger than sequence length\"\n result = []\n nr_windows = len(sequence) - window_size + 1\n for i in range(nr_windows):\n sub_sequence = sequence[i:i + window_size]\n result.append(sub_sequence)\n return result", "def split_subsequences(iterable, length=2, overlap=0, \r\n join_substr=True):\r\n isstring = isinstance(iterable, str) and join_substr\r\n it = iter(iterable)\r\n results = list(itertools.islice(it, length))\r\n while len(results) == length:\r\n yield ''.join(results) if isstring else results\r\n results = results[length - overlap:]\r\n results.extend(itertools.islice(it, length - overlap))\r\n if results:\r\n yield ''.join(results) if isstring else results", "def get_subsets(string: str) -> Set:\n strings = set()\n str_len = len(string) + 1\n [strings.add(string[start:stop]) for start in range(str_len) for stop in range(str_len) if stop > start]\n return strings", "def substring_split(string, n):\n\n substrings = []\n for i in range(len(string) - n + 1):\n substrings.append(string[i:i + n])\n\n return substrings", "def get_strings(max_len=0, limit=0):\n return _limit_helper(_fuzzdb_get_strings(max_len), limit)", "def slice_string(s, slc = 1000, cut_off = True):\n N = len(s)\n if slc > N:\n \"string insufficient length\"\n return s\n else:\n n = slc + 1\n slc_len = int(math.ceil(N/n))\n output = []\n for i in range(0,N,slc_len):\n output.append(s[i:(i+slc_len)])\n if cut_off & len(output[-1]) != slc_len:\n del output[-1]\n return output", "def slices(sequence, length):\n\n if length > len(sequence) or length == 0:\n raise ValueError('Length is greater than sequence')\n\n slices = []\n\n index_counter = 0\n\n while index_counter + length <= len(sequence):\n slices.append([int(i) for i in sequence[index_counter:index_counter+length]])\n index_counter += 1\n\n return slices", "def find_all_substring_indexes(string: str, substring: str) -> list:\n start = 0\n while True:\n start = string.find(substring, start)\n if start == -1:\n return\n yield start\n start += len(substring)", "def split_in_substrings(s, n):\n\n output = []\n\n # for each line in s\n for line_in_s in s:\n # split the line in substrings of size n\n for i in range(len(line_in_s) - n + 1):\n output.append(line_in_s[i:i + n])\n\n return output", "def BreakString( s, maxLen ):\n\n quot, rem = divmod( len( s ), maxLen )\n r = [ s[i*maxLen:(i+1)*maxLen] for i in range( quot ) ]\n if len( s ) % maxLen:\n r.append( s[-rem:] )\n\n return r", "def get_random_strings(number_of_strings=10, string_length_range=(1, 5), max_alphabet_len=None):\n\n min_string_length, max_string_length = string_length_range\n\n string_legnths = [\n random.randint(min_string_length, max_string_length)\n for _ in range(number_of_strings)\n ]\n\n return [random_string(string_len, max_alphabet_len) for string_len in string_legnths]", "def getWordsForSubstring(self, sub, language=DEFAULT_LANGUAGE):\n if not isinstance(sub, unicode):\n raise LexiconError('Substring must be unicode (%s)' % sub)\n tree = self._getTree(language)\n return [word for word in tree.keys() if sub in word]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function for generating transition probability matrix. Takes a current position (row, col) and an action and returns the new state, the reward for the state and whether the agent is done (won or fell in hole)
def update_prob_matrix(row, col, action): # Get next field coordinates with boundary checks new_row, new_col = increment(row, col, action) # Convert coordinates to state ID new_state = self.coords_to_state_idx[(new_row, new_col)] # Get new coordinate type f_type = self.lake[row][column] # Check whether we reached the goal or fell in hole done = f_type == '$' or f_type == '#' # Reward = 1 if agent is at goal, 0 otherwise reward = float(f_type == '$') return new_state, reward, done
[ "def step(self, action):\n turn_continue = True\n while turn_continue:\n prob = np.random.random()\n probs = self.T[action, self.current_state, :]\n # print(prob)\n # print(probs)\n # print(probs.sum())\n # print('where')\n # print(np.where(probs > prob))\n probs = probs.cumsum()\n new_state = np.where(probs >= prob)[0][0]\n done = self.is_gameover(*self.STATELIST[new_state])\n self.current_state = new_state\n # print('new state', self.STATELIST[self.current_state])\n turn_continue = (action == 0) and (not done)\n reward = self.R[new_state]\n return new_state, reward, done", "def move(action, state):\n # Create new_state\n new_state = copy.deepcopy(state)\n \n # Get the current location of player.\n player_index = np.where(new_state[PLAYER_DEPTH]==1)\n p_row = player_index[0][0]\n p_col = player_index[1][0]\n\n # Get the Max rows and cols of state.\n max_row = new_state[PLAYER_DEPTH].shape[0]\n max_col = new_state[PLAYER_DEPTH].shape[1]\n\n if action == 0: # DOWN \n if p_row + 1 < max_row:\n new_state[PLAYER_DEPTH][p_row + 1][p_col] = 1\n new_state[PLAYER_DEPTH][p_row][p_col] = 0\n if action == 1: # UP\n if p_row - 1 >= 0:\n new_state[PLAYER_DEPTH][p_row - 1][p_col] = 1\n new_state[PLAYER_DEPTH][p_row][p_col] = 0\n if action == 2: # LEFT\n if p_col - 1 >= 0:\n new_state[PLAYER_DEPTH][p_row][p_col - 1] = 1\n new_state[PLAYER_DEPTH][p_row][p_col] = 0\n if action == 3: # RIGHT\n if p_col + 1 < max_col:\n new_state[PLAYER_DEPTH][p_row][p_col + 1] = 1\n new_state[PLAYER_DEPTH][p_row][p_col] = 0\n \n return new_state, get_reward(new_state), is_terminal(new_state)", "def transition_prob_vector(self, action):\n matrixRow = []\n nextPossible = self.next_states(action)\n curState = deepcopy(self)\n for nextState in nextPossible:\n index = (curState, action, nextState)\n if index not in GameState.tpm:\n GameState.tpm[index] = self.transition_prob(action, nextState)\n matrixRow.append(GameState.tpm[index])\n return matrixRow", "def make_state_transition(self, action):\n self.player.perform_action(action)\n new_state = self.board.get_binary_state() # get space efficient binary state to share with RL agent\n new_reward = self.get_reward() # get reward of action to share with RL agent\n return new_state, new_reward", "def get_outcome(self, state, action):\n next_state = None\n reward = 0\n if state in [53, 131]: # end of MDP\n return next_state, reward\n if action == 0: # move right\n next_state = state + 1\n if state == 38: # goal state 1\n next_state = 53\n reward = 100\n elif state == 158: # goal state 2\n next_state = 131\n reward = 100\n elif state == 1: # cliff\n next_state = None\n reward = -100\n elif 7 <= state <= 51 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 29\n elif state in [63, 64, 65]: # room 1 wind\n next_state = state + 15\n elif 10 <= state <= 68 and (state % 14 == 10 or state % 14 == 11 or state % 14 == 12): # room 1 wind\n next_state = state + 15\n elif 113 <= state <= 157 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state - 13\n elif 130 <= state <= 160 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 27\n elif state in [116, 117, 118]: # room 2 wind\n next_state = state - 13\n elif 5 <= state <= 75 and state % 14 == 5: # room 1 left border\n next_state = state\n elif 105 <= state <= 147 and state % 14 == 7: # room 2 right border\n next_state = state\n elif state % 14 == 13: # world right border\n next_state = state\n elif action == 1: # move up\n next_state = state - 14\n if state in [16, 17, 18, 84]: # cliff\n next_state = None\n reward = -100\n elif 21 <= state <= 65 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 14\n elif state in [7, 8, 9]: # room 1 wind\n next_state = state + 28\n elif state in [77, 78, 79]: # room 1 wind\n next_state = state\n elif 24 <= state <= 82 and (state % 14 == 10 or state % 14 == 11 or state % 14 == 12): # room 1 wind\n next_state = state\n elif state in [10, 11, 12]: # room 1 wind\n next_state = state + 14\n elif 127 <= state <= 157 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state - 28\n elif 144 <= state <= 160 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 42\n elif state in [130, 131, 132]: # room 2 wind\n next_state = state - 28\n elif 90 <= state <= 96: # room 1 bottom border\n next_state = state\n elif 98 <= state <= 105: # room 2 top border\n next_state = state\n elif 0 <= state <= 13: # world top border\n next_state = state\n elif action == 2: # move left\n next_state = state - 1\n if state == 40: # goal state 1\n next_state = 53\n reward = 100\n elif state == 160: # goal state 2\n next_state = 131\n reward = 100\n elif state in [29, 43, 57, 71, 5]: # cliff\n next_state = None\n reward = -100\n elif 7 <= state <= 51 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 27\n elif state in [63, 64, 65]: # room 1 wind\n next_state = state + 13\n elif 10 <= state <= 68 and (state % 14 == 10 or state % 14 == 11 or state % 14 == 12): # room 1 wind\n next_state = state + 13\n elif 113 <= state <= 157 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state - 15\n elif state == 99: # room 2 wind\n next_state = state - 15\n elif 130 <= state <= 160 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 29\n elif state in [116, 117, 118]: # room 2 wind\n next_state = state - 15\n elif 6 <= state <= 76 and state % 14 == 6: # room 1 left border\n next_state = state\n elif 106 <= state <= 148 and state % 14 == 8: # room 2 right border\n next_state = state\n elif state % 14 == 0: # world left border\n next_state = state\n elif action == 3: # move down\n next_state = state + 14\n if state == 25: # goal state 1\n next_state = 53\n reward = 100\n elif state == 145: # goal state 2\n next_state = 131\n reward = 100\n elif state == 14: # cliff\n next_state = None\n reward = -100\n elif 7 <= state <= 37 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 42\n elif state in [49, 50, 51]: # room 1 wind\n next_state = state + 28\n elif 99 <= state <= 143 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state\n elif state in [155, 156, 157]: # room 2 wind\n next_state = state - 14\n elif 116 <= state <= 146 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 14\n elif state in [102, 103, 104]: # room 2 wind\n next_state = state\n elif state in [158, 159, 160]: # room 2 wind\n next_state = state - 28\n elif 76 <= state <= 82: # room 1 bottom border\n next_state = state\n elif 84 <= state <= 91: # room 2 top border\n next_state = state\n elif 154 <= state <= 167: # world bottom border\n next_state = state\n else:\n print(\"Action must be between 0 and 3.\")\n next_state = None\n reward = None\n return int(next_state) if next_state is not None else None, reward", "def get_outcome(self, state, action):\n next_state = None\n reward = 0\n if state in [53, 131]: # end of MDP\n return next_state, reward\n if action == 0: # move right\n next_state = state + 1\n if state == 38: # goal state 1\n next_state = 53\n reward = 100\n elif state == 158: # goal state 2\n next_state = 131\n reward = 100\n elif state == 1: # cliff\n next_state = None\n reward = -100\n elif 7 <= state <= 51 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 29\n elif state in [63, 64, 65]: # room 1 wind\n next_state = state + 15\n elif 10 <= state <= 68 and (state % 14 == 10 or state % 14 == 11 or state % 14 == 12): # room 1 wind\n next_state = state + 15\n elif 113 <= state <= 157 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state - 13\n elif 130 <= state <= 160 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 27\n elif state in [116, 117, 118]: # room 2 wind\n next_state = state - 13\n elif 19 <= state <= 75 and state % 14 == 5: # room 1 left border\n next_state = state\n elif 105 <= state <= 161 and state % 14 == 7: # room 2 right border\n next_state = state\n elif state % 14 == 13: # world right border\n next_state = state\n elif action == 1: # move up\n next_state = state - 14\n if state in [16, 17, 18, 84]: # cliff\n next_state = None\n reward = -100\n elif 21 <= state <= 65 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 14\n elif state in [7, 8, 9]: # room 1 wind\n next_state = state + 28\n elif state in [77, 78, 79]: # room 1 wind\n next_state = state\n elif 24 <= state <= 82 and (state % 14 == 10 or state % 14 == 11 or state % 14 == 12): # room 1 wind\n next_state = state\n elif state in [10, 11, 12]: # room 1 wind\n next_state = state + 14\n elif 127 <= state <= 157 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state - 28\n elif 144 <= state <= 160 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 42\n elif state in [130, 131, 132]: # room 2 wind\n next_state = state - 28\n elif 90 <= state <= 97: # room 1 bottom border\n next_state = state\n elif 99 <= state <= 105: # room 2 top border\n next_state = state\n elif 0 <= state <= 13: # world top border\n next_state = state\n elif action == 2: # move left\n next_state = state - 1\n if state == 40: # goal state 1\n next_state = 53\n reward = 100\n elif state == 160: # goal state 2\n next_state = 131\n reward = 100\n elif state in [29, 43, 57, 71, 5]: # cliff\n next_state = None\n reward = -100\n elif 7 <= state <= 51 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 27\n elif state in [63, 64, 65]: # room 1 wind\n next_state = state + 13\n elif 10 <= state <= 68 and (state % 14 == 10 or state % 14 == 11 or state % 14 == 12): # room 1 wind\n next_state = state + 13\n elif 113 <= state <= 157 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state - 15\n elif state == 99: # room 2 wind\n next_state = state - 15\n elif 130 <= state <= 160 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 29\n elif state in [116, 117, 118]: # room 2 wind\n next_state = state - 15\n elif 20 <= state <= 76 and state % 14 == 6: # room 1 left border\n next_state = state\n elif 106 <= state <= 162 and state % 14 == 8: # room 2 right border\n next_state = state\n elif state % 14 == 0: # world left border\n next_state = state\n elif action == 3: # move down\n next_state = state + 14\n if state == 25: # goal state 1\n next_state = 53\n reward = 100\n elif state == 145: # goal state 2\n next_state = 131\n reward = 100\n elif state == 14: # cliff\n next_state = None\n reward = -100\n elif 7 <= state <= 37 and (state % 14 == 7 or state % 14 == 8 or state % 14 == 9): # room 1 wind\n next_state = state + 42\n elif state in [49, 50, 51]: # room 1 wind\n next_state = state + 28\n elif 99 <= state <= 143 and (state % 14 == 1 or state % 14 == 2 or state % 14 == 3): # room 2 wind\n next_state = state\n elif state in [155, 156, 157]: # room 2 wind\n next_state = state - 14\n elif 116 <= state <= 146 and (state % 14 == 4 or state % 14 == 5 or state % 14 == 6): # room 2 wind\n next_state = state - 14\n elif state in [102, 103, 104]: # room 2 wind\n next_state = state\n elif state in [158, 159, 160]: # room 2 wind\n next_state = state - 28\n elif 76 <= state <= 83: # room 1 bottom border\n next_state = state\n elif 85 <= state <= 91: # room 2 top border\n next_state = state\n elif 154 <= state <= 167: # world bottom border\n next_state = state\n else:\n print(\"Action must be between 0 and 3.\")\n next_state = None\n reward = None\n return int(next_state) if next_state is not None else None, reward", "def step(self, state, action, Time_matrix):\n next_state, time_to_arrive_at_pickup, ride_time, wait_time_till_next_slot = self.next_state_func(state, action, Time_matrix)\n reward = self.reward_func(time_to_arrive_at_pickup, ride_time, wait_time_till_next_slot)\n \n return next_state, reward, time_to_arrive_at_pickup+ride_time+wait_time_till_next_slot", "def reward(self, state, action):\n return self.reward_matrix[state][action]", "def lookup_transition_prob_matrix(self, action, nextState):\n curState = deepcopy(self)\n action = tuple(action)\n if (curState, action, nextState) in GameState.tpm:\n return GameState.tpm[(curState, action, nextState)]\n else:\n prob = self.transition_prob(curState, action, nextState)\n GameState.tpm[(curState, action, nextState)] = prob\n return prob", "def take_action(state, action):\n row = np.where(state.board[:, action]==0)[0].min()\n ns = State(state.board.copy(), -state.player)\n ns.board[row, action] = state.player\n return ns", "def reward(self, action: str):\n\n # reward agent alot for moving to and staying on square and punish for\n # not going next or on square\n if self.agent == self.square[0] and action == \"stay\":\n return 200\n elif self.agent == self.square[0] and action == \"left\":\n return -100\n elif self.agent == self.square[0] and action == \"right\":\n return -100\n elif self.agent == self.square[0] - 1 and action == \"right\":\n return 100\n elif self.agent == self.square[0] + 1 and action == \"left\":\n return 100\n else:\n return -50", "def _generate_possible_actions():\n action_increment = {\n 'U': (+1,0),\n 'D': (-1,0),\n 'R': (0,+1),\n 'L': (0,-1)\n }\n actions = {}\n for i in range(n_rows):\n for j in range(n_cols):\n current_cell = (i,j)\n # If current cell is a reward_cell (terminal state) or a banned cell (not allowed cell),\n # don't add it to action dictionay.\n if _is_reward_cell(current_cell) or _is_banned_cell(current_cell):\n continue\n feasible_action_list = []\n for act in action_increment:\n increment = action_increment[act]\n next_cell = (i+increment[0], j+increment[1])\n if not _is_banned_cell(next_cell) and not _out_of_bounds(next_cell):\n feasible_action_list.append(act)\n actions[current_cell] = feasible_action_list\n return actions", "def reward_func(self, state, action, Time_matrix):\n reward = 0\n if action == (0, 0):\n reward = C * (-1)\n else:\n location, time, day = state\n start_loc, end_loc = action\n\n cost = 0\n time_to_reach_start_location = 0\n\n if location != start_loc:\n # find time required to reach start location\n time_to_reach_start_location = Time_matrix[location][start_loc][time][day]\n\n #now to get actual start time, add this time to original time\n time = int(time + time_to_reach_start_location)\n\n # if new time > 23, its next day. add 1 to day and reset time at 24\n time, day = CabDriver.get_time_day(time, day)\n \n # time required to go from start_location to end_location with new time and day\n action_time = Time_matrix[start_loc][end_loc][time][day]\n\n # final cost = Cost_per_hour * ( action_time + time_to_reach_start_location )\n cost = C * ( action_time + time_to_reach_start_location )\n\n # reward = Reward_per_hour * action_time - cost\n reward = R * action_time - cost\n\n return reward", "def step(self, state, action, Time_matrix):\n time_taken, next_state = self.next_state_func(state, action, Time_matrix)\n reward = self.reward_func(state, action, Time_matrix)\n \n return next_state, reward, time_taken", "def step(self, action):\n\n if self.environment_type == 'deterministic':\n # Describing the outcomes of the various possible actions.\n if action == 0:\n self.agent_pos[0] += 1 # This action causes the agent to go right.\n if action == 1:\n self.agent_pos[0] -= 1 # This action causes the agent to go left.\n if action == 2:\n self.agent_pos[1] += 1 # This action causes the agent to go up.\n if action == 3:\n self.agent_pos[1] -= 1 # This action causes the agent to go down.\n\n if self.environment_type == 'stochastic':\n # Describing the outcomes of the various possible actions.\n if action == 0: # This action causes the agent to go right with 0.9 probability and remain in the same\n # position with 0.1 probability.\n probability = random.uniform(0, 1)\n if probability > 0.1:\n self.agent_pos[0] += 1\n if action == 1: # This action causes the agent to go left with 0.9 probability and remain in the same\n # position with 0.1 probability.\n probability = random.uniform(0, 1)\n if probability > 0.1:\n self.agent_pos[0] -= 1\n if action == 2: # This action causes the agent to go up with 0.9 probability and remain in the same\n # position with 0.1 probability.\n probability = random.uniform(0, 1)\n if probability > 0.1:\n self.agent_pos[1] += 1\n if action == 3: # This action causes the agent to go down with 0.9 probability and remain in the same\n # position with 0.1 probability.\n probability = random.uniform(0, 1)\n if probability > 0.1:\n self.agent_pos[1] -= 1\n\n # Ensuring that the agent doesn't go out of the environment.\n self.agent_pos = np.clip(self.agent_pos, a_min=0, a_max=3)\n\n new_gold_distance = self.compute_distance(self.agent_pos, self.gold_pos) # Computing the new distance of the\n # agent from the Gold.\n\n # Giving the agent different rewards if its distance to the Gold increases, decreases or remains the same.\n if new_gold_distance > self.gold_distance: # If the agent moves away from the Gold it gets reward -1.\n reward = -1\n self.gold_distance = new_gold_distance\n\n elif new_gold_distance < self.gold_distance: # If the agent moves closer to the Gold it gets reward 1.\n reward = 1\n self.gold_distance = new_gold_distance\n\n else: # If the agent's distance to the Gold doesn't change it gets reward 0.\n reward = 0\n\n observation = self.render()\n\n self.timesteps += 1 # Increasing the total number of steps taken by the agent.\n\n # Setting the reward to 10 if the agent reaches the gold.\n if (self.agent_pos == self.gold_pos).all() and self.gold_quantity > 0:\n self.gold_quantity -= 1\n reward = 10\n\n for i in range(len(self.pit_pos)): # Setting the reward to -1 if the agent falls in the pit.\n if (self.agent_pos == self.pit_pos[i]).all():\n reward = -1\n\n if (self.agent_pos == self.wumpus_pos).all(): # Setting the reward to -1 if the agent is killed by Wumpus.\n reward = -1\n\n # The episode terminates when the agent reaches the Gold, or is killed by the Wumpus, falls into the pit, or\n # takes more than 10 steps.\n if self.gold_quantity == 0 or \\\n (self.agent_pos == self.wumpus_pos).all():\n done = True\n else:\n done = False\n for i in range(len(self.pit_pos)):\n if (self.agent_pos == self.pit_pos[i]).all():\n done = True\n if self.timesteps == self.max_timesteps:\n done = True\n info = {}\n\n return observation, reward, done, info", "def make_transition_matrix(self):\n n_states = State.max_id + 1 # last state is death\n n, m = self.n, self.m\n T = np.zeros((n_states, 4, n_states), np.float64)\n S = self.markov_chain()\n M = self.moving_markov_chain()\n # ────────────────────────── for each state ────────────────────────── #\n for sw in range(2):\n for tr in range(3):\n for p in range(n * m):\n i, j = p // m, p % m\n s = State(sw, tr, p)\n cell = self.map[i, j]\n # ───────── find the transitions from that state ───────── #\n if cell == Cell.magic_portal or cell == Cell.moving_platform:\n transitions = self.special_transition(S, M, s)\n else:\n transitions = S[s.id, :]\n # ─────── find the state - actions that lead to it ─────── #\n for ((k, l), direction) in self.map.neighbors(i, j):\n # if (k,l) is ↑ of (i, j), (i, j) is ↓ of (k, l)\n s.position = k * m + l\n reverse_dir = direction.reverse\n T[s.id, reverse_dir.to_int, :] = transitions\n # ─────────── any action not yet found is to stay inplace ──────────── #\n for sid in range(n_states):\n for a in Direction:\n s = State(s_id=sid)\n if sum(T[s.id, a.to_int]) == 0:\n mu = np.zeros(n_states, np.float64)\n mu[s.id] = 1\n T[s.id, a.to_int, :] = S.iterate(mu)\n return T", "def reward_func(self, state, action, Time_matrix):\n if (action[0] == 0 and action[1] == 0):\n reward = -C\n else:\n reward = R * (Time_matrix[action[0]-1][action[1]-1][state[1]][state[2]]) - C * ((Time_matrix[action[0]-1][action[1]-1][state[1]][state[2]]) + (Time_matrix[state[0]-1][action[0]-1][state[1]][state[2]]))\n return reward", "def act(self):\n self.logger.info('Picking action according to rule set')\n\n # computing state variable\n state, state_np = get_state(self)\n x, y, _, bombs_left, score = self.game_state['self']\n arena, bomb_map = state_np\n \n # determine valid actions\n directions = [(x,y), (x+1,y), (x-1,y), (x,y+1), (x,y-1)]\n valid_tiles, valid_actions = [], []\n for d in directions:\n if (((arena[d] == 0) or (arena[d] == 2) ) and\n (self.game_state['explosions'][d] <= 1) and\n (bomb_map[d] > 0)):\n valid_tiles.append(d)\n if (x-1,y) in valid_tiles: valid_actions.append('LEFT')\n if (x+1,y) in valid_tiles: valid_actions.append('RIGHT')\n if (x,y-1) in valid_tiles: valid_actions.append('UP')\n if (x,y+1) in valid_tiles: valid_actions.append('DOWN')\n if (x,y) in valid_tiles: valid_actions.append('WAIT')\n if (bombs_left > 0): valid_actions.append('BOMB')\n self.logger.debug(f'Valid actions: {valid_actions}')\n \n if len(valid_actions) == 0:\n return # we're fucked -> can only happen in last step of an episode\n \n # prepare state by stacking the the current state on top of 3 past states\n old_stack = self.state_hist[-1] if len(self.state_hist) > 0 else torch.from_numpy(np.array([np.nan]))\n stacked_state = stack(old_stack,state)\n\n # decide next action\n action= get_action(self, stacked_state, valid_actions)\n self.next_action = action\n \n # save state and action such that they are available in reward_update for learning\n self.action_hist.append(action)\n self.state_hist.append(stacked_state)", "def getTransitionStatesAndProbs(self, state, action):\n\n if action not in self.getPossibleActions(state):\n raise \"Illegal action!\"\n\n if state == self.terminalState:\n return []\n\n row, col = state\n\n if type(self.grid[row][col]) == int or type(self.grid[row][col]) == float:\n return [(self.terminalState, 1.0)]\n\n successors = []\n\n northState = (self.__isAllowed(row-1,col) and (row-1,col)) or state\n westState = (self.__isAllowed(row,col-1) and (row,col-1)) or state\n southState = (self.__isAllowed(row+1,col) and (row+1,col)) or state\n eastState = (self.__isAllowed(row,col+1) and (row,col+1)) or state\n\n if action == 'north' or action == 'south':\n if action == 'north':\n successors.append((northState,1-self.noise))\n else:\n successors.append((southState,1-self.noise))\n\n massLeft = self.noise\n successors.append((westState,massLeft/2.0))\n successors.append((eastState,massLeft/2.0))\n\n if action == 'west' or action == 'east':\n if action == 'west':\n successors.append((westState,1-self.noise))\n else:\n successors.append((eastState,1-self.noise))\n\n massLeft = self.noise\n successors.append((northState,massLeft/2.0))\n successors.append((southState,massLeft/2.0))\n\n successors = self.__aggregate(successors)\n\n return successors" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts chain information from PDB file returns a list of the chain characters
def getchains(pdbfile): try: read = open(pdbfile,'r') except IOError: print("getchains: Couldn't open file %s"%(pdbfile)) raise else: result = [] for line in read: if line[0:4]=='ATOM': if line[21] not in result and line[21].isalnum(): result.append(line[21]) elif "_" not in result and not line[21].isalnum(): result.append("_") read.close() return result
[ "def getChainIDsFromPDB(cls, filename, qparent=None):\n extension = filename.split('.')[-1].lower()\n if extension == 'pdb':\n linelist = []\n for line in open(filename, 'U'):\n if line[:6] == 'COMPND' and line[10:70].split(':')[0].strip() == 'CHAIN':\n linelist = line[17:].split(', ')\n linelist[0] = linelist[0].strip()\n if ';' in linelist[-1]:\n linelist[-1] = linelist[-1].split(';')[0]\t#removes the terminating semicolon and extra whitespace\n while True:\n try: linelist.remove('NULL')\n except: break\n return linelist\n if linelist == []:\n return []\n else:\n raise NotImplementedError, 'NYI'", "def ExtractChainText(file_name):\n\n pdb_file = open(file_name, 'r')\n\n chain_atoms_found = {}\n chain_text = {}\n\n for line in pdb_file:\n if line[0:6] == 'ATOM ':\n chainID = line[21:22]\n if (not chainID in chain_atoms_found):\n chain_atoms_found[chainID] = {}\n chain_text[chainID] = []\n for atom_name in heavy_atoms:\n chain_atoms_found[chainID][atom_name] = False\n\n chain_text[chainID].append(line)\n\n atom_type = line[12:16]\n res_type = line[17:20]\n if res_type in res_types:\n #if ((atom_type in atoms_found) and (not atoms_found[atom_type])):\n # print('found atom_type=\\\"'+atom_type+'\\\", in res_type=\\\"'+res_type+'\\\"')\n chain_atoms_found[chainID][atom_type] = True\n\n\n for chainID in chain_atoms_found:\n search_criteria_satisfied = True\n for atom_type in chain_atoms_found[chainID]:\n if (not chain_atoms_found[chainID][atom_type]):\n search_criteria_satisfied = False\n if search_criteria_satisfied:\n sys.stderr.write(\" Chain \\\"\"+chainID+\"\\\" contains DNA.\\n\")\n # Then create a new PDB file with a name similar to the original:\n pdb_file_chain_name = file_name\n i = pdb_file_chain_name.lower().rfind('.pdb')\n if i != -1:\n pdb_file_chain_name = (pdb_file_chain_name[:i] +\n '_' + chainID +\n pdb_file_chain_name[i:])\n else:\n pdb_file_chain_name = file_name + '_' + chainID\n sys.stderr.write(' Creating file \\\"'+pdb_file_chain_name+'\\\"\\n')\n pdb_file_chain = open(pdb_file_chain_name, 'w')\n pdb_file_chain.write(''.join(chain_text[chainID]))\n pdb_file_chain.close()\n\n pdb_file.close()", "def get_pdb_info(pdb_files):\n\tp = PDBParser(PERMISSIVE=1)#initialize pdb parser\n\n\tstructures = []\n\tchains = []\n\tn = 0\n\t#get structures for each pdb file\n\tfor f in pdb_files:\n\t\tn += 1\n\t\tstr = p.get_structure(n, f)\n\t\tstructures.append(str)\n\n\tfor str in structures:\n\t\tstr_id = str.get_id()\n\t\tfor model in str:\n\t\t\tfor chain in model:\n\t\t\t\tfor residue in chain:\n\t\t\t\t\tif residue.id[0] != ' ':\n\t\t\t\t\t\tchain.detach_child(residue.id)\n\t\t\t\tif len(chain) >= 10:\n\t\t\t\t\tchains.append(chain)\n\n\treturn chains", "def extract_chain(pdb_path, chain_id_arg='first'):\n pdb_name = os.path.basename(pdb_path) # With .pdb extension\n pdb_id = os.path.splitext(pdb_name)[0] # Without .pdb extension\n out_filename = \"results/\" + pdb_id + chain_id_arg + '.pdb'\n\n with open(pdb_path, 'r') as pdb_in, \\\n open(out_filename, 'w') as pdb_out:\n i = 0\n\n for line in pdb_in:\n resName = line[17:20].strip()\n resID_pdb = line[22:26]\n\n if (line[0:4] == \"ATOM\") or ((line[0:6] == \"HETATM\") and\n ( (resName == \"MET\") or resName == \"MSE\") ):\n chain_ID = line[21:22].strip()\n i += 1\n\n if chain_id_arg == 'first':\n if i == 1: # If it is the 1st ATOM line read\n first_chain_id = chain_ID\n\n if chain_ID == first_chain_id:\n pdb_out.write(line)\n else:\n break\n\n else:\n if chain_ID == chain_id_arg:\n pdb_out.write(line)\n\n if not os.stat(out_filename).st_size: # If the file is empty\n print(\"ERROR! The chain ID you specified does not belong to \" +\n pdb_path + ' !\\n')\n os.remove(out_filename) # Clean the empty file\n sys.exit(1)\n\n # Rename file, in the case where no chain had been specified:\n if chain_id_arg == 'first':\n os.system(\"mv \" + out_filename + \" results/\" + pdb_id +\n first_chain_id + '.pdb')\n return (pdb_id + first_chain_id + '.pdb', pdb_id + first_chain_id)\n\n return (pdb_id + chain_id_arg + '.pdb', pdb_id + chain_id_arg)", "def parse_pdb(path):\n\n pdb_dict = defaultdict(lambda: defaultdict(list))\n res_dict = defaultdict(list)\n with open(path) as o:\n lines = o.readlines()\n for line in lines:\n if line[:4] == 'ATOM':\n atom_info = process_atom_info(line)\n identifier = '{}{}'.format(\n atom_info['res_name'],\n atom_info['res_no']\n )\n pdb_dict[atom_info['chain']][identifier].append(atom_info)\n if identifier not in res_dict[atom_info['chain']]:\n res_dict[atom_info['chain']].append(identifier)\n return pdb_dict,res_dict", "def separate_chains(filename):\n pdb_parser = Bio.PDB.PDBParser()\n io = Bio.PDB.PDBIO()\n structure = pdb_parser.get_structure(\"structure\", filename)\n for model in structure:\n for chain in model:\n io.set_structure(chain)\n io.save(filename + \"_chain{}.pdb\".format(chain.id))", "def get_pdb_coords(pdbname):\n coords = []\n for line in open(pdbname,\"r\"):\n if line[:3] in ['TER','END']:\n break\n else:\n if line[:4] == \"ATOM\":\n coords.append([float(line[31:39]),float(line[39:47]),float(line[47:55])]) \n\n return np.array(coords)", "def get_all_chains_from_files_in_dir(input_dir):\n data_dir = input_dir\n pdb_files = [p.join(data_dir, f) for f in os.listdir(data_dir)]\n complete_biounits = []\n\n for fname in pdb_files:\n logger.info('current pdb file %s' % fname)\n if fname.endswith('.gz') and not p.exists(p.splitext(fname)[0]):\n call(['gzip', '-d', fname])\n logger.info('zipped pdb file extracted' % fname)\n fname = p.splitext(fname)[0]\n with open(fname, 'r') as f:\n text = f.read()\n pdb_id = p.basename(p.splitext(fname)[0])\n dbrefs = get_dbrefs(text)\n bunits = extract_biological_units(pdb_id, text, dbrefs)\n logger.info('found %d complete units' % len(bunits))\n complete_biounits += bunits\n all_chains_df = pd.concat(\n [bunit.as_dataframe() for bunit in complete_biounits])\n\n n_pdb_ids = len(all_chains_df.pdb_id.drop_duplicates())\n logger.info(\n 'found a total of %d complete biological units belonging '\n 'to %d pdb entries'\n % (len(complete_biounits), n_pdb_ids))\n\n return all_chains_df", "def GetPdbCoordinates( filename,\n select_atom = (\"CA\",),\n select_chain = None,\n renumber = None,\n only_coordinates = None):\n\n if not os.path.exists(filename):\n raise \"pdb file %s does not exist\" % filename\n\n if filename[-3:] == \".gz\":\n lines = os.popen(\"gunzip < %s\" % filename).readlines()\n else:\n lines = open(filename,\"r\").readlines()\n\n result = []\n\n current_number = 1\n \n for line in lines:\n if line[:6] not in (\"ATOM \", \"HETATM\"): continue\n\n chain = line[21]\n number = line[22:26]\n aa = line[17:20]\n atom = string.strip(line[13:17])\n \n x,y,z = map(string.atof, (line[30:38], line[38:46], line[46:54]))\n\n if select_chain and chain not in select_chain: continue\n if select_atom and atom not in select_atom: continue\n \n if renumber:\n number = current_number\n current_number += 1\n\n if AMINOACIDS.has_key(aa):\n aminoacid = AMINOACIDS[aa]\n else:\n sys.stderr.write( \"# error in PdbCoordinates: aminoacid %s not known\\n\" % aa )\n continue\n\n if only_coordinates:\n result.append( (x, y, z) )\n else:\n result.append( (number, aminoacid, x, y, z) ) \n \n return result", "def get_nucleic(self):\n with open(self.filename) as pdb:\n atoms = [atom(line) for line in pdb if re.search\n ('(^ATOM)\\s*\\S*\\s*\\S*\\s*'\n '(DA5|DA3|DA|DT5|DT3|DT|DG5|DG3|DG|DC5|DC3|DC)', line)]\n return atoms", "def get_pose_from_pdb_with_chain(path, chain):\n p = PDBParser()\n struct = p.get_structure('TEST', path)\n c = struct[0][chain]\n io = PDBIO()\n io.set_structure(c)\n # Yuck - we have to save in PDB state\n io.save('/tmp/mypdb.pdb')\n pose = pose_from_pdb('/tmp/mypdb.pdb')\n os.remove('/tmp/mypdb.pdb')\n return pose", "def _print_pdb(sorted_data, filename):\n file_pdb = open(filename,\"w\")\n num_at = 0\n num_res = 0\n for one_result in sorted_data:\n chains = set()\n for r in one_result[0]:\n r = r.strip(\"_BCK\")\n chains.add(r.split(\":\")[1])\n cen_str = \"\"\n for r in one_result[1]:\n crd_center = \"{:.8s}\".format(str(round(float(r),3)))\n if len(crd_center)<8:\n crd_center = \" \"*(8-len(crd_center)) + crd_center\n cen_str += crd_center\n else:\n cen_str += crd_center\n num_at += 1\n num_res += 1\n for ch in chains:\n file_pdb.write(\"ATOM\" +\" \"*(7-len(str(num_at))) + \"%s HE SLN %s\" %(num_at, ch))\n file_pdb.write(\" \"*(3-len(str(num_res))) + \"%s %s 1.00 0.00 HE\\n\" %(num_res, cen_str))\n for prob in one_result[4]:\n num_at += 1\n prb_str = \"\"\n for p in prob:\n prb_center = \"{:.8s}\".format(str(round(float(p),3)))\n if len(prb_center)<8:\n prb_center = \" \"*(8-len(prb_center)) + prb_center\n prb_str += prb_center\n else:\n prb_str += prb_center\n for ch in chains:\n file_pdb.write(\"ATOM\" +\" \"*(7-len(str(num_at))) + \"%s XE SLN %s\" %(num_at, ch))\n file_pdb.write(\" \"*(3-len(str(num_res))) + \"%s %s 1.00 0.00 XE\\n\" %(num_res, prb_str))\n file_pdb.close()", "def test_chains(self):\n self.input_file = os.path.join('data', '1A1X.pdb') # one chain\n self.input_structure = PDBParser(open(self.input_file))\n res = contact.contacts_xtra(self.input_structure)\n self.assertTrue(res == {})\n self.input_file = os.path.join('data', '2E12.pdb') # one chain\n self.input_structure = PDBParser(open(self.input_file))\n res = contact.contacts_xtra(self.input_structure)\n self.assertTrue(res)\n self.assertFloatEqual(\\\n res[('2E12', 0, 'B', ('THR', 17, ' '), ('OG1', ' '))]['CONTACTS']\\\n [('2E12', 0, 'A', ('ALA', 16, ' '), ('CB', ' '))][0], 5.7914192561064004)", "def createCcpnChainInformation(self,chains):\n \n self.ccpnChainInfo = []\n \n for chain in chains:\n \n molType = chain.molecule.molType\n seqString = None \n seqTuple = None\n\n seqList = []\n resTypeList = []\n for residue in chain.sortedResidues():\n seqList.append((residue.seqId,residue.ccpCode))\n resTypeList.append(residue.molType)\n \n if len(seqList) == 1:\n seqTuple = (seqList[0][-1].upper(),)\n elif molType == 'other':\n # Just make sure it's not 'other' because of some unknown residues...\n if resTypeList.count('other') > len(seqList) * 0.8:\n seqTuple = tuple([seqEl[-1].upper() for seqEl in seqList])\n\n # Only do this for polymers... \n if not seqTuple:\n\n if not molType:\n for tmpMolType in ('protein','DNA','RNA'):\n if resTypeList.count(tmpMolType) > len(seqList) * 0.8:\n molType = tmpMolType\n break\n \n seqString = createOneLetterSequence(molType,seqList)\n \n self.ccpnChainInfo.append((molType,chain.code,seqTuple,seqString))", "def chainReaction(genome1,genome2):\n chainIndex = root_dir + \"/RGV2/ChainConvert.dat\"\n dChain={}\n assoName = genome1+'To'+genome2.upper()[0]+genome2[1:]\n fileIn = open(chainIndex,'r')\n for lines in fileIn.readlines():\n fileName = lines.split('\\t')[0]\n dChain[fileName] = []\n lfilesUsed = lines.split('\\t')[1]\n if ';' in lfilesUsed :\n for files in lfilesUsed.split(';'):\n dChain[fileName].append(files.replace(\"\\n\",\"\"))\n else :\n dChain[fileName].append(lfilesUsed.replace(\"\\n\",\"\"))\n fileIn.close()\n return dChain[assoName]", "def get_dbrefs(text):\n\n regex = re.compile(\n r\"^DBREF\\s+(?P<pdb_id>\\w+)\\s+(?P<chain_id>\\w+)\\s+(?P<seq_begin>\\d+)\\s+(?P<insert_begin>\\d+)\\s+(?P<db_id>\\w+)\\s+(?P<db_acc>\\w+)\\s+(?P<seq_db_code>\\w+)\\s+(?P<seq_start>\\d+)\\s+(?P<seq_end>\\d+).*$\",\n re.MULTILINE\n )\n info = {}\n matches = regex.finditer(text)\n for m in matches:\n chain_id = m.group('chain_id')\n if m.group('db_id') == 'UNP':\n info[chain_id] = {\n 'protein': m.group('db_acc'),\n 'seq_start': m.group('seq_start'),\n 'seq_end': m.group('seq_end')\n }\n return info", "def get_chains_info(ph, selection_list=None):\n\n chains_info = {}\n # asc = ph.atom_selection_cache()\n model = ph.models()[0]\n # build chains_info from hierarchy\n # print \"in get_chains_info\"\n for ch in model.chains():\n # print \"ch_id\", ch.id\n gr = True\n if not chains_info.has_key(ch.id):\n chains_info[ch.id] = Chains_info()\n gr = False\n # This is very time-consuming\n # ph_sel = ph.select(asc.selection(\"chain '%s'\" % ch.id))\n # coc = flex.vec3_double([ph_sel.atoms().extract_xyz().mean()])\n # chains_info[ch.id].center_of_coordinates = coc\n chains_info[ch.id].center_of_coordinates = None\n chains_info[ch.id].chains_atom_number += ch.atoms_size()\n conf = ch.conformers()[0]\n len_conf = len(ch.conformers())\n # Warning devs: the following assert fails when there is no main conf\n # in a residue\n # assert len(ch.residue_groups()) == len(conf.residues())\n for rg, res in zip(ch.residue_groups(), conf.residues()):\n chains_info[ch.id].resid.append(rg.resid())\n chains_info[ch.id].res_names.append(rg.atom_groups()[0].resname)\n # atoms = res.atoms()\n ag0 = rg.atom_groups()[0]\n atoms = ag0.atoms()\n present_anames = [a.name for a in atoms]\n # print \"rg.atom_groups_size()\", rg.atom_groups_size()\n if rg.atom_groups_size() > 1:\n for add_rgs in rg.atom_groups()[1:]:\n for a in add_rgs.atoms():\n # print \" getting atom '%s'\" % a.name, a.name not in present_anames\n if a.name not in present_anames:\n atoms.append(a)\n present_anames.append(a.name)\n chains_info[ch.id].atom_names.append(list(atoms.extract_name()))\n chains_info[ch.id].atom_selection.append(list(atoms.extract_i_seq()))\n chains_info[ch.id].no_altloc.append(not rg.have_conformers() or len_conf==1)\n chains_info[ch.id].gap_residue.append(gr)\n # print \" \", rg.id_str(), rg.have_conformers(), not res.is_pure_main_conf, \"|noaltloc:\", (not rg.have_conformers() or len_conf==1), \"size:\", atoms.size(), \"gr:\", gr\n # for a in atoms:\n # print \" \", a.id_str()\n gr = False\n return chains_info", "def dumpChains(chain_aminos, protein_name):\n\n print protein_name + \":\"\n print \"{\",\n\n for group in chains[protein_name]:\n for chain in group:\n sys.stdout.write(\"'\" + chain + \"':\" + '\"')\n\n for amino in chain_aminos[chain]:\n sys.stdout.write(amino[0])\n\n print '\",',\n\n print \"}\"", "def test_fetch_pdb_chain_existing_file_pass(self):\n success_msg = re.compile(\n r'^Found local copy of.*',\n re.IGNORECASE\n )\n\n chain_fp = os.path.join(\n self.test_data_dp,\n 'data',\n 'initial_filtering_data',\n 'tsv_data',\n 'pdb_chain_uniprot.tsv')\n with captured_stdout() as stdout:\n fetch_pdb_chain_uniprot(chain_fp)\n result = stdout.getvalue().strip()\n print(result)\n self.assertTrue(success_msg.search(result))\n return None" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
print the style info necessary for collapsible portion
def printStyle(): print('<style type="text/css">') print('.row { vertical-align: top; height:auto !important; }') print('.list {display:none; }') print('.show { display: none; }') print('.hide:target + .show {display: inline; }') print('.hide:target {display: none; }') print('.hide:target ~ .list {display:inline; }') print('@media print { .hide, .show { display: none; } }') print('</style>')
[ "def getStyle(self):", "def style(self):\n return self.get_page().style", "def print_info(self) :\n\n print('-'*80)\n print('Material: %s' % self._material_name)\n print('Parameters: %s' % self._parameters)\n print('Material class: %s, ' % self._material_class)\n print('Properties: incompressible (%s), inverse (%s), active (%s)'\n % (self._incompressible, self._inverse, self._active))\n print('-'*80)", "def style(self):\n\treturn self.m_style", "def print_header():\n\n print('------------------------------------')\n print(' CAT FACTORY')\n print('------------------------------------')", "def setup_status(self):\n\n self.result_separator = \"+\"\n for (_, length, _, skip) in self.element_info:\n if skip:\n continue\n self.result_separator += '-' * (1 + length + 1) + \"+\"\n\n self.description_line = \"+\"\n for (field, length, _, skip) in self.element_info:\n if skip:\n continue\n self.description_line += (\" \" +\n field +\n ' ' * (length - len(field)) +\n \" +\")\n\n index = 0\n self.format_line = \"|\"\n for (_, length, special_fmt, skip) in self.element_info:\n if skip:\n continue\n if special_fmt is int:\n self.format_line += \" {%d:<%d} |\" % (index, length)\n elif special_fmt is str:\n self.format_line += \" {%d:%d} |\" % (index, length)\n elif special_fmt is float:\n self.format_line += \" {%d:<%d.%d} |\" \\\n % (index, length, length - 2)\n index += 1", "def info_headers(style: styles.NamedStyle):\n info_headers_row = str(xl(self.POSITION['info_header_row']))\n for info_header_col in range(xl(self.POSITION['first_sample_col']), xl(self.vehicle_desc_mark_up_col)):\n info_header_cell = '{}{}'.format(utils.get_column_letter(info_header_col), info_headers_row)\n self.ws[info_header_cell].style = style", "def print_info(self):\n\n print \"\"\"src_port: %d\\t dst_port: %d\\t sequence_num: %d\\t ack_num: %d\n data_offset: %d\\t urg: %d\\t ack: %d\\t psh: %d\\t rst: %d\\t syn: %d\\t fin: %d\\t\n window_size: %d\\t checksum: %s\\t urgent_pointer: %s\\t opt_paddings: %s\"\"\" % (\n self.src_port, self.dst_port, self.sequence_num,\n self.ack_num, self.data_offset, self.flag_urg, \n self.flag_ack, self.flag_psh, self.flag_rst, \n self.flag_syn, self.flag_fin, self.window_size, \n self.checksum, self.urgent_pointer, self.opt_paddings)", "def print_infoheader():\n\tprint(\" _______.__ _______.\")\n\tprint(\"|_ _|__|.-----.--.--.| __|.----.----.-----.-----.-----.\")\n\tprint(\" | | | || | | ||__ || __| _| -__| -__| |\")\n\tprint(\" |___| |__||__|__|___ ||_______||____|__| |_____|_____|__|__|\")\n\tprint(\" |_____| © P.Bartels - https://www.kangafoo.de\\n\")", "def print_summary(self):\n sets = ['parts', 'areas', 'lines', 'points', 'elements', 'faces',\n 'nodes']\n spacer = '----------------------------------'\n print(spacer)\n print(\"View's currently selected items:\")\n for sel_type in sets:\n items = getattr(self, sel_type)\n print(' %s: %i selected' % (sel_type, len(items)))\n print(spacer)", "def collapse_card(n_clicks, style):\r\n if style['visibility'] == 'visible':\r\n style['visibility'] = 'hidden'\r\n else:\r\n style['visibility'] = 'visible'\r\n\r\n return style", "def display(self):\r\n print(\"\\nCop name : \", self.cop_name)\r\n print(\"Cop age : \", self.cop_age)\r\n print(\"Cop work experience : \", self.work_exp)\r\n print(\"Cop designation : \", self.designation)", "def showShadingGroupAttrEditor():\n pass", "def print_status(self):\n print(f\"\"\"The coffee machine has:\n {self.water} of water\n {self.milk} of milk\n {self.beans} of coffee beans\n {self.cups} of disposable cups\n {self.money} of money\"\"\")", "def _print_statusline(self):\n statusline_top = self._print(\n ('{:%s}'%self.term_width).format(' {} ({}x{}) zoom:{:.1f}x'.format(\n self.image.fname, self.image._image.shape[1], self.image._image.shape[0],\n self.image.get_zoom()\n # int(100 * self.image.w / self.image._image.shape[1])\n )),\n 0,0,\n curses.COLOR_WHITE, 0\n )\n statusline_bottom = self._print(\n ('{:%s}'%self.term_width).format(' c:color e:edges r:refresh q:quit +/-:zoom hjkl:move 0:reset'),\n 0,self.term_height-1,\n curses.COLOR_WHITE, 0\n )\n self._write(statusline_top)\n self._write(statusline_bottom)\n self._set_default_colors()\n sys.stdout.flush()", "def isCustomStyled():", "def style(self):\r\n style = self.data.get('style', None)\r\n if style:\r\n return style['category']['name']\r\n else:\r\n return None", "def menuFormat(self):\n \n pass", "def infoheader():\n clear()\n print(\"=^.^= WEBCAT =^.^=\")\n print(\"-\"*50)\n print(\"->> Target: %s\" %(options.target))\n print(\"-\"*50)", "def __init__(self):\n if sys.stdout.isatty():\n self.HEADER = '\\033[95m'\n self.OKBLUE = '\\033[94m'\n self.OKGREEN = '\\033[92m'\n self.WARNING = '\\033[93m'\n self.FAIL = '\\033[91m'\n self.ENDC = '\\033[0m'\n self.BOLD = '\\033[1m'\n self.UNDERLINE = '\\033[4m'" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
print the first part of the collapsible portion
def collapseHead(): print('<div class="row">') print(' <a href="#hide1" class="hide" id="hide1">Show advanced options</a>') print(' <a href="#show1" class="show" id="show1">Hide advanced options</a>') print(' <div class="list">')
[ "def print_header():\n\n print('------------------------------------')\n print(' CAT FACTORY')\n print('------------------------------------')", "def print_element(self):\n\t\tif self.state == DISCOVERED:\n\t\t\tif self.content != \"0\":\n\t\t\t\treturn self.content\n\t\t\telse :\t\t\t\t\n\t\t\t\treturn \" \"\n\t\telse :\n\t\t\treturn self.state", "def print_header():\n txt = 'breadth of dirs examined longest pathname deepest directory'\n sys.stdout.write(txt + linesep)", "def print_header():\n print(\"STEM Center Temperature Project\")\n print(\"Shaotong Wen\")", "def print_summary(self):\n sets = ['parts', 'areas', 'lines', 'points', 'elements', 'faces',\n 'nodes']\n spacer = '----------------------------------'\n print(spacer)\n print(\"View's currently selected items:\")\n for sel_type in sets:\n items = getattr(self, sel_type)\n print(' %s: %i selected' % (sel_type, len(items)))\n print(spacer)", "def print_header():\r\n\tprint('\\n')\r\n\tprint('======================================================================')\r\n\tprint('######## ## ## ######## ## ####### ## ## #### ######## ')\r\n\tprint(' ## ## ## ## ## ## ## ## ## ## ## ')\r\n\tprint(' ## ## ## ## ## ## ## ## ## ## ## ')\r\n\tprint(' ## ## ## ## ## ## ## ##### ## ## ')\r\n\tprint(' ## ## ## ## ## ## ## ## ## ## ## ')\r\n\tprint(' ## ## ## ## ## ## ## ## ## ## ## ')\r\n\tprint(' ## ####### ## ######## ####### ## ## #### ## ')\r\n\tprint('======================================================================')\r\n\tprint('\\n')", "def display1(self):\r\n print(\"The mission of the Cop : \", self.mission)", "def build_title(dirpath, level):\n\n if level == 1:\n # do not print the first-level title\n return \"\"\n sl = str(level)\n sn = '<img class=\"hicon\" src=\"'+collapseicon+'\"/>'\n sn += os.path.basename(dirpath)\n if level < 7:\n title = '<h' + sl + ' onclick=\"collapse(this.children[0])\">'\n title += sn + '</h' + sl + '>\\n'\n else:\n title = '<div class=\"h' + sl + '\" onclick=\"collapse(this.children[0])\">'\n title += sn + '</div>\\n'\n return title", "def print_infoheader():\n\tprint(\" _______.__ _______.\")\n\tprint(\"|_ _|__|.-----.--.--.| __|.----.----.-----.-----.-----.\")\n\tprint(\" | | | || | | ||__ || __| _| -__| -__| |\")\n\tprint(\" |___| |__||__|__|___ ||_______||____|__| |_____|_____|__|__|\")\n\tprint(\" |_____| © P.Bartels - https://www.kangafoo.de\\n\")", "def first_child():\n return \"Hi, I am Emma\"", "def summary_func(self):\n return('The description of this major is' + ': ' + self.summ)", "def print_text_generation_header():\n logging.debug(\"print_text_generation_header\")\n logging.info(\"\\n\")\n logging.info(\"┌{:─^111}┐ Generating random text from learned state\")", "def print(self):\n print('(', end='')\n self.printBST()\n print(')', end=' ')", "def printLandscape(self):\n for row in self.sections:\n print(\"New row:\")\n for col in row:\n print(col.id)\n print(\"Number of individuals: %d\" % (len(col.individuals)))", "def prologue(_indent):\n return \"\"", "def extract_brief(func):\n # TODO: implement\n return \"\"", "def section(heading=None):\n if heading is None:\n section_break_heading = \"\"\n else:\n section_break_heading = \"### {} \".format(heading)\n print(\"\\n\\n{:#<79}\\n\".format(section_break_heading))", "def infoheader():\n clear()\n print(\"=^.^= WEBCAT =^.^=\")\n print(\"-\"*50)\n print(\"->> Target: %s\" %(options.target))\n print(\"-\"*50)", "def print_start(self, branch):\n\n print()\n print(f\"Cleaning for branch '{branch}' ...\")", "def head(self):\n if hasattr(self.view, 'head'):\n print(self.view.head())\n else:\n print(\"No data view set.\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates the parameters file from the data read from the form
def makeParameters(form,out): chainset = False chains = 'CHAIN ' checkboxes = ['reducing','molscript','hlfe','fing'] for value in form: if "chain_" in value: chains = "%s%s"%(chains,form[value].value) chainset = True else: if value not in checkboxes: try: out.write("%s %s\n"%(value.upper(),form[value].value)) except KeyError: out.write("%s 0\n"%(value.upper())) for value in checkboxes: try: if form[value].value == 'on': out.write('%s 1\n'%(value.upper())) else: out.write("%s 0\n"%(value.upper())) #out.write("%s %s\n"%(value.upper(),form[value].value)) except KeyError: out.write("%s 0\n"%(value.upper())) if not chainset: chains += '.' out.write("%s\n"%(chains)) out.close()
[ "def makeParameters(form,out):\n chainset = False\n chains = 'CHAIN '\n checkboxes = ['reducing','molscript','hlfe','fing']\n for value in form:\n if \"chain_\" in value:\n chains = \"%s%s\"%(chains,form[value].value)\n chainset = True\n else:\n try:\n out.write(\"%s %s\\n\"%(value.upper(),form[value].value))\n except KeyError:\n out.write(\"%s 0\\n\"%(value.upper()))\n for value in checkboxes:\n try:\n out.write(\"%s %s\\n\"%(value.upper(),form[value].value))\n except KeyError:\n out.write(\"%s 0\\n\"%(value.upper()))\n if not chainset:\n chains += '.'\n out.write(\"%s\\n\"%(chains))\n out.close()", "def make_param_file(self):\n t = self.get_t_out()\n t_timeunits = t.to(self.timeUnit)\n t_steps = t_timeunits / self.dDelta\n\n print(\"t_steps = \" + str(t_steps))\n achInFile = self.writename\n\n # write data in a file.\n file = open(self.writename + \".param\", \"w\")\n L = [\"nSteps = \" + str(round(t_steps.value)) + \"\\n\",\n \"dTheta = 0.7 \\n\",\n \"dEta = .03 \\n\",\n \"dDelta = \" + str(self.dDelta) + \" \\n\",\n \"iOutInterval = \" + str(round(t_steps.value / 5)) + \" \\n\",\n \"achInFile = \" + achInFile + \" \\n\",\n \"achOutName = \" + self.writename + \" \\n\",\n \"iLogInterval = 1 \\n\",\n \"dMsolUnit = \" + str(self.dMsolUnit.value) + \" \\n\",\n \"dKpcUnit = \" + str(self.dKpcUnit.value) + \" \\n\",\n \"dDumpFrameStep = 25 \\n\",\n \"iDirector = 1 \\n\",\n \"bGasAdiabatic = 1\"]\n\n file.writelines(L)\n file.close()", "def get_parameters_form():", "def make_parm_files(self):\n self.call_sortie_function('generate_parm')", "def saveParameters(self):\n\n name = 'Hyteresis_Measurement_Parameters.txt'\n file = open(name, 'w') # Trying to create a new file or open one\n file.write(\"Voltage: {} V\\n\".format(str(Parameters['Voltage'])))\n file.write(\"Loops: {} \\n\".format(str(LoopParams['Loops'])))\n file.write(\"Measurementpoints: {} \\n\".format(\n str(LoopParams['MeasurementPoints'])))\n file.write(\"Set Fluenz: {} \\n\".format(\n str(MeasParams['Fluence'])))\n file.write(\"TimeZero: {} \\n\".format(\n str(MeasParams['timeZero'])))\n file.write(\"Pump-Angle: {} \\n\".format(\n str(MeasParams['angle'])))\n file.write(\"Samplename: {} \\n\".format(\n str(MeasParams['sampleName'])))\n\n if not self.Stage_ReadFromFile:\n file.write(\"StartPoint: {} ps\\n\".format(\n str(StageParams_ps['StartPoint'])))\n file.write(\"End Point: {} ps\\n\".format(\n str(StageParams_ps['EndPoint'])))\n file.write(\"Stepwidth: {} ps\\n\".format(\n str(StageParams_ps['StepWidth'])))\n file.write(\"Stage Velocity: {} \\n\".format(\n str(Stage_SpeedParams['Velocity'])))\n file.write(\"Stage Acceleration: {} \\n\".format(\n str(Stage_SpeedParams['Acceleration'])))\n\n if self.Stage_ReadFromFile:\n file.write(\"Start \\t Stop \\t Stepwidth ps\\n\")\n for idx, val in enumerate(self.saveVector):\n entry = ' '.join(str(e) for e in self.saveVector[idx])\n file.write(\"{}\\n\".format(entry))\n\n if self.Hysteresis_Check.isChecked():\n file.write(\"StartPoint: {} ps\\n\".format(\n str(HysteresisParameters['Stepwidth'])))\n file.write(\"Amplitude: {} ps\\n\".format(\n str(HysteresisParameters['Amplitude'])))\n file.write(\"@StageDelay\")\n for idx, val in enumerate(self.hystDelayVector_ps):\n entry = ' '.join(str(val))\n file.write(\"{}\\n\".format(entry))\n\n file.close()", "def para_gen(filename, tasks_models, data, count, modify_words = None):\n # Generate parameters from command line\n if count > 1:\n f_old = open(\"./parameters/\" + filename + \"_\" + str(count-1) + \".dat\",'r')\n else:\n f_old = open(\"./parameters/\" + filename + \".dat\",'r')\n\n para_temp_data = PARA_TEMP_DATA()\n\n task_file = False # Whether this is a task file\n model_file = False # Whether this is a model file\n\n if (data.task is not None) and (filename == data.task.lower()):\n task_file = True\n elif (data.model is not None) and (filename == data.model.lower()):\n model_file = True\n\n f_new = open(\"./parameters/\" + filename + \"_\" + str(count) + \".dat\",'w')\n print bcolors.BOLD + '\\n' + filename.upper() + bcolors.ENDC\n print bcolors.FAIL + \"By directly pressing enter, default/previous values will be used.\\n\" + bcolors.ENDC\n\n for line in f_old:\n if (line.startswith(\"//\")) is True:\n f_new.write(line)\n else:\n comment_start = line.find(\"//\")\n\n # Get lines after //\n comment = \" \".join(line[comment_start+2:].split())\n\n name = line.split()[0]\n var = line.split()[1]\n\n valid_var = False\n var_option = None\n\n if modify_words is not None: # Check whether it needs modification\n if name not in modify_words:\n if name != \"left_size\":\n valid_var = True\n var_temp = var\n\n if valid_var is False:\n choice = exception(name,data, para_temp_data)\n if choice is not None: # This variable may be skipped\n valid_var = True\n if choice == \"Previous\":\n var_temp = var\n else:\n var_temp = choice\n valid_var, var_option = para_check(name, var, var_temp, tasks_models)\n\n while valid_var is not True:\n var_temp = raw_input(name+\": (previous: \" + var +\" ) \" + bcolors.OKBLUE +\n comment + bcolors.ENDC+ '\\n')\n if var_temp == '':\n var_temp = var\n valid_var, var_option = para_check(name, var, var_temp, tasks_models)\n if valid_var is not True:\n print bcolors.FAIL + \"Error: \" + var_option + bcolors.ENDC\n\n if name == \"task\":\n data.task = var_temp\n elif name == \"model\":\n data.model = var_temp\n elif name == \"threads_N\":\n data.num_threads = var_temp\n elif name == \"size\":\n data.size = var_temp\n elif name == \"log_time\":\n para_temp_data.log_time = value_table[var_temp]\n elif name == \"Entropy_Per_Model\":\n para_temp_data.ent_cal = value_table[var_temp]\n if (modify_words is not None) and (\"left_size\" not in modify_words):\n para_temp_data.ent_half_chain = True\n\n # Obtain strings for parameters\n if (model_file is True):\n if (data.model.find(\"Flo\") > -1) and (name == \"J\"):\n data.model_para += \"_J_\" + str(var_temp)\n elif (task_file is True):\n if data.task.find(\"Time_Evolution\") > -1:\n if name == \"time_step\":\n data.task_para += \"_time_step_\" + str(var_temp)\n elif name == \"init_func_name\":\n data.task_para += \"_init_\" + var_temp\n if data.task.find(\"Multi\") > -1:\n if name == \"model_num\":\n data.task_para += \"_model_num_\" + str(var_temp)\n\n\n f_new.write(name + \" \" + var_temp + \" // \" + comment + '\\n')\n\n f_old.close()\n f_new.close()", "def _paramsFileHead():\n\n str = \\\n\"\"\"\n# ----------------------------------------------------------------------\n# Numenta Platform for Intelligent Computing (NuPIC)\n# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from\n# Numenta, Inc. a separate commercial license for this software code, the\n# following terms and conditions apply:\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License version 3 as\n# published by the Free Software Foundation.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n# See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see http://www.gnu.org/licenses.\n#\n# http://numenta.org/licenses/\n# ----------------------------------------------------------------------\n\n## This file defines parameters for a prediction experiment.\n\n###############################################################################\n# IMPORTANT!!!\n# This params file is dynamically generated by the RunExperimentPermutations\n# script. Any changes made manually will be over-written the next time\n# RunExperimentPermutations is run!!!\n###############################################################################\n\n\nfrom nupic.frameworks.opf.expdescriptionhelpers import importBaseDescription\n\n# the sub-experiment configuration\nconfig ={\n\"\"\"\n\n return str", "def build_param_file( self, param_dict, directory=None ):\n if self.command and \"$param_file\" in self.command:\n fd, param_filename = tempfile.mkstemp( dir=directory )\n os.close( fd )\n f = open( param_filename, \"wt\" )\n for key, value in param_dict.items():\n # parameters can be strings or lists of strings, coerce to list\n if type(value) != type([]):\n value = [ value ]\n for elem in value:\n f.write( '%s=%s\\n' % (key, elem) ) \n f.close()\n param_dict['param_file'] = param_filename\n return param_filename\n else:\n return None", "def _save(self):\n conf = {}\n for param in self.params:\n name, value = param.read()\n conf[name] = value\n\n self.fh.save(self.conf_name, conf)", "def prepare_params_file(args,prefix,name_main_ldscore,params_file='/mnt/data/params.ldcts'):\n with open(params_file, 'w') as file:\n logging.debug('Save parameter file with prefix: ' + prefix + ' and ldscore: /mnt/data/outld/' + name_main_ldscore)\n file.write(prefix + \"\\t\" + '/mnt/data/outld/' + name_main_ldscore + '\\n')", "def _defineParams(self, form):\n form.addSection(label='Input')\n form.addParam('inputParticles', PointerParam, \n pointerClass='SetOfParticles', pointerCondition='hasCTF',\n label=\"Input particles with CTF\", \n help='Select the input particles. \\n '\n 'they should have information about the CTF (hasCTF=True)')\n form.addParam('ctfGroupMaxDiff', FloatParam, default=1,\n label='Error for grouping', validators=[GE(1.,'Error must be greater than 1')],\n help='Maximum error when grouping, the higher the more groups'\n 'This is a 1D program, only defocus U is used\\n '\n 'The frequency at which the phase difference between the CTFs\\n'\n 'belonging to 2 particles is equal to Pi/2 is computed \\n '\n 'If this difference is less than 1/(2*factor*sampling_rate)\\n' \n 'then images are placed in different groups')", "def check_params(filename):\n \n if not os.path.isfile(filename):\n print(\"Parameters file not found.\")\n sys.exit(0)\n \n filename = open(filename)\n \n parameters = dict()\n for line in filename: \n line = line.split(\"=\")\n line[0] = line[0].lower()\n parameters[line[0]] = line[1].rstrip().lower() \n \n filename.close()\n \n # Check for essential parameters \n \n if \"metadata\" not in parameters:\n raise NameError(\"Metadata file not found in parameters.\")\n elif not os.path.isfile(parameters[\"metadata\"]):\n raise NameError(str(parameters[\"metadata\"]) + \" not found.\")\n \n if \"abundance_data\" not in parameters:\n raise NameError(\"Abundance data not found in parameters.\")\n elif not os.path.isfile(parameters[\"abundance_data\"]):\n raise NameError(str(parameters[\"abundance_data\"]) + \" not found.\")\n \n # Check for non-essential parameters \n \n if \"name\" not in parameters:\n parameters[\"name\"]=\"n/a\"\n \n if \"year\" not in parameters:\n parameters[\"year\"]=\"n/a\"\n \n if \"sequence_type\" not in parameters:\n parameters[\"sequence_type\"]=\"n/a\"\n \n if \"collaborator\" not in parameters:\n parameters[\"collaborator\"]=\"n/a\" \n \n if \"metadata_header\" not in parameters:\n parameters[\"metadata_header\"]=\"true\"\n \n if \"metadata_label\" not in parameters:\n parameters[\"metadata_label\"]=\"n/a\"\n \n if \"pca\" not in parameters:\n parameters[\"pca\"] = \"n\"\n \n if \"pcoa\" not in parameters:\n parameters[\"pcoa\"] = \"n\"\n \n if \"pcoa\" in parameters and \"dist_type\" not in parameters:\n parameters[\"dist_type\"] = \"braycurtis\"\n \n if \"normalization\" not in parameters:\n parameters[\"normalization\"] = \"none\"\n \n if \"output_dir\" not in parameters:\n parameters[\"output_dir\"] = \"current\"\n \n if \"enrichment\" not in parameters:\n parameters[\"enrichment\"] = \"f\"\n elif \"enrichment_test\" not in parameters:\n parameters[\"enrichment_test\"] = \"ttest\"\n \n if \"pairwise\" in parameters and \"correction_type\" not in parameters:\n parameters[\"correction_type\"] = \"bonferroni\"\n \n if \"multiple_comparisons\" not in parameters:\n parameters[\"multiple_comparisons\"] = \"false\"\n elif \"pairwise\" not in parameters:\n parameters[\"pairwise\"] = \"false\"\n \n if \"area_plot\" not in parameters:\n parameters[\"area_plot\"] = \"false\"\n if \"plot_individual_classes\" not in parameters:\n parameters[\"plot_individual_classes\"] = \"false\" \n \n if \"to_html\" not in parameters:\n parameters[\"to_html\"] = \"false\"\n if \"open_page\" not in parameters:\n parameters[\"open_page\"] = \"false\"\n \n return parameters", "def create_material_file(self):\n\t # create and open the material.dat file\n\t with open(self.userPath + '/material.dat', 'w') as material_file:\n\t # for each material\n\t for material in self.materials:\n\t # write the type of the material\n\t line = 'material ' + material['MaterialType'] + ' [ \\n'\n\t material_file.write(line)\n\t #write the name of the material\n\t line = 'name='+material['name'] +'\\n'\n\t material_file.write(line)\n\t # for each parameter we write it in the material file\n\t # except if this is a range a value\n\t for key, value in material.items():\n\t \tprint(key)\n\t if key != 'MaterialType' and key != 'name':\n\t if type(value) != dict:\n\t line = key + '=' + str(value) + '\\n'\n\t material_file.write(line)\n\t else:\n\t # define a key so that we can create the job for this\n\t # parameter in this specific material\n\t new_key = 'Material_'+material['name'] + '_' + key\n\t # define the range from the infos in the json file\n\t range_values = self.define_range(value)\n\t # append this new variable in the parametric space\n\t self.parametric_space[new_key] = range_values\n\t # and we define a standard value for this parameter in the file\n\t # we will take the first value of the range\n\t default_value = range_values[0]\n\t line = key + '=' + str(default_value) + '\\n'\n\t material_file.write(line)\n\t material_file.write(']')", "def create_ini(self, p, filename):\n output = collections.defaultdict(list)\n for param, x in zip(self.varied_params, p):\n output[param.section].append(\"%s = %r %r %r\\n\" % (\n param.name, param.limits[0], x, param.limits[1]))\n for param in self.fixed_params:\n output[param.section].append(\"%s = %r\\n\" % (param.name, param.start))\n ini = open(filename, 'w')\n for section, params in sorted(output.items()):\n ini.write(\"[%s]\\n\"%section)\n for line in params:\n ini.write(line)\n ini.write(\"\\n\")\n ini.close()", "def create_config_file(self):\n\t with open(self.userPath + '/config.py', 'w') as config_file:\n\t lines = ['#!/bin/env python \\n', 'import BlackDynamite as BD \\n','import re,os\\n',\n\t 'myrun, myjob = BD.getRunFromScript() \\n']\n\n\t for key, value in self.parametric_space.items():\n\t\t\t\tprint(\"key = \" +str(key))\n\t\t\t\tif 'Material' in key:\n\t\t\t\t\t# find the material name\n\t\t\t\t\tm = re.search(\n\t\t\t\t\t r\"Material_(?P<name>\\w+)_(?P<param>\\w+)\", key)\n\t\t\t\t\tmaterial_name = m.group('name')\n\t\t\t\t\t# find the parameter concerned\n\t\t\t\t\tparameter = m.group('param')\n\t\t\t\t\t# config opens material file and reads its content\n\t\t\t\t\tlines.append('file = open(\\\"material.dat\\\", \\\"r\\\")\\n')\n\t\t\t\t\tlines.append('lines = file.readlines()\\n')\n\t\t\t\t\t# then config close it to open it later in write mode\n\t\t\t\t\tlines.append('file.close()\\n')\n\t\t\t\t\t# config initializes a variable to know if it is in the right material\n\t\t\t\t\t# and to find the indexes where the change will be made\n\t\t\t\t\tlines.append('in_material=False\\n')\n\t\t\t\t\tlines.append('ind=0\\n')\n\t\t\t\t\tlines.append('for line in lines:\\n')\n\t\t\t\t\t# config file need to search the parameter\n\t\t\t\t\tlines.append(self.tab+'m=re.search(\\'{}\\',line)\\n'.format(\n\t\t\t\t\t material_name.lower()))\n\t\t\t\t\t# if it finds it, it needs to search the parameter\n\t\t\t\t\tlines.append(self.tab+'if m is not None:\\n')\n\t\t\t\t\tlines.append(self.tab+self.tab+'in_material=True\\n')\n\t\t\t\t\tlines.append(self.tab+'m=re.search(\\'{}=\\',line)\\n'.format(\n\t\t\t\t\t parameter))\n\t\t\t\t\tlines.append(self.tab+'if m is not None and in_material == True:\\n')\n\t\t\t\t\tlines.append(self.tab+self.tab+'lines[ind]=\\'{}=\\' + str(myjob.{}_{}_{}) + \\'\\\\n\\'\\n'.format(parameter,'material',material_name.lower(),parameter.lower()))\n\t\t\t\t\t# config has found the vaiable so we are moving to another parameter\n\t\t\t\t\tlines.append(self.tab+self.tab+'in_material=False \\n')\n\t\t\t\t\t# write the line\n\t\t\t\t\tlines.append(self.tab+'ind = ind+1\\n')\n\t\t\t\t\t# write the lines\n\t\t\t\t\tlines.append('file = open(\\\"material.dat\\\", \\\"w+\\\")\\n')\n\t\t\t\t\tlines.append('file.writelines(lines)\\n')\n\t\t\t\t\tlines.append('file.close()\\n')\n\n\t lines.append('myrun.start()\\n')\n\t # TODO push values\n\t lines.append('myrun.finish()\\n')\n\n\t # write file\n\t config_file.writelines(lines)", "def load_fixed_params(self, entry_browse, grid):\n filename = tkFileDialog.askopenfilename(initialdir=\"./\", title=\"Select file\",\n filetypes=((\"csv files\", \"*.csv\"), (\"all files\", \"*.*\")))\n if filename:\n entry_browse.insert(0, filename)\n helpers.destroy_slaves(grid)\n self.model.fixed_params = helpers.read_fixed_params_from_file(filename, [\"Name, Values, Units\"])\n helpers.create_entry_table(self.model.fixed_params, grid)", "def saveParameters(self, filepath) -> retval:\n ...", "def save_calibration_parameters(self):\n if self.plant_db.tmp_dir is None:\n directory = self.dir\n else:\n directory = self.plant_db.tmp_dir\n with open(directory + self.parameters_file, 'w') as oututfile:\n json.dump(self.calibration_params, oututfile)", "def inputProperties(self):\n \n #wType - String defining the type of waves to be generated.\n #Can be one of: 'noWave', 'noWaveCIC', 'regular', 'regularCIC','irregular',\n #'spectrumImport', and 'etaImport' \n #(Default = 'NOT DEFINED').\n self.wType = 'NOT DEFINED'\n \n #T - [s] Wave period, peak wave period or BEM period.\n #Wave period (regular waves), peak period (irregular waves), or period of \n #BEM data used for hydrodynamic coefficients ('noWave') \n #(Default = 'NOT DEFINED'). \n self.T = 'NOT DEFINED'\n \n #H - % [m] Wave height or significant wave height for irregular\n #Wave height (regular waves) or significant wave height (irregular waves) \n #(Default = 'NOT DEFINED'). \n self.H = 'NOT DEFINED'\n \n #spectrumType - String containing the wave spectrum type\n #Can be one of : 'PM', 'BS', and 'JS' \n #(Default = 'NOT DEFINED'). \n self.spectrumType = 'NOT DEFINED'\n \n #gamma - Only used for 'JS' spectrum type to define gamma \n #(Default = 3.3)\n self.gamma = 3.3\n \n #phaseSeed - Only used for irregular waves \n #if equal to 1,2,3,...,etc, the waves phase is seeded.\n #(Default = 0)\n self.phaseSeed = 0\n \n #spectrumDataFile - Data file that contains the spectrum data file\n #(Default = 'NOT DEFINED')\n self.spectrumDataFile = 'NOT DEFINED'\n \n #etaDataFile - Data file that contains the times-series data file\n #(Default = 'NOT DEFINED')\n self.etaDataFile = 'NOT DEFINED'\n \n #freqRange - Min and max frequency for irregular waves. \n #array with two values, rad/s, (default = frequency range in BEM data)\n #(Default = [])\n #eg. [0.3,0.5]\n self.freqRange = []\n \n #numFreq - of interpolated wave frequencies \n #Number of frequencies used, varies depending on method:\n #Traditional = 1000, EqualEnergy = 500 or 'Imported'\n #(Default = 0)\n self.numFreq = 0\n \n #waveDir - [deg] Incident wave direction(s)\n #Should be defined as a column vector for more than one wave direction \n #For multiple wave direction it will be an array of angle in degree\n #[20,45,60,80]\n #(Default = 0)\n self.waveDir = [0]\n \n #waveSpread - Wave Spread probability associated with wave direction(s)\n #Should be defined as a column vector for more than one wave direction\n #For multiple wave direction it will be an array that corresponds to \n #wave direction [20,45,60,80]\n #(Default = [1])\n self.waveSpread = [1]\n \n #viz - Dictionary defining visualization options\n #Should be a dictionary containing the fields 'numPointsX' and 'numPointsY'. \n #numPointsX is the number of visualization points in x direction, and \n #numPointsY the number of visualization points in y direction\n self.viz = {'numPointsX': 50,'numPointsY': 50 }\n \n #statisticsDataLoad - File name from which to load wave statistics data\n #(Default = [])\n self.statisticsDataLoad = []\n \n #freqDisc - Method of frequency discretization for irregular waves. \n #Options for this variable are 'EqualEnergy' or 'Traditional'.\n #(Default = 'EqualEnergy').\n self.freqDisc = 'EqualEnergy'\n \n #wavegauge1loc - [m] Wave gauge 1 [x,y] location\n #(Default = [0,0]).\n self.wavegauge1loc = [0,0]\n \n #wavegauge2loc - [m] Wave gauge 2 [x,y] location\n #(Default = [0,0]).\n self.wavegauge2loc = [0,0]\n \n #wavegauge3loc - [m] Wave gauge 3 [x,y] location\n #(Default = [0,0]).\n self.wavegauge3loc = [0,0]\n \n #currentSpeed - [m/s] Surface current speed that is uniform along the \n #water column.\n #(Default = 0).\n self.currentSpeed = 0\n \n #currentDirection - [deg] Surface current direction.\n #(Default = 0).\n self.currentDirection = 0\n \n #currentOption - [-] Define the sub-surface current model to be used in \n #WEC-Sim.\n #(Default = 0)\n #0 : Depth-independent model\n #1 : 1/7 power law variation with depth\n #2 : linear variation with depth\n #3 : no current\n self.currentOption = 3\n \n #currentDepth - [m] Define the depth over which the sub-surface current is \n #modeled.\n #For options (1) and (2) the currentDepth must be defined. The\n #current is not calculated for any depths greater than the\n #specified currentDepth. (Default = 0).\n self.currentDepth = 0" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This script determines what parts of GeoFold need to be rerun and will send the results to secondScript
def fourthScript(form): oldParameters = {} changeParameters = ['REDUCING','BREAKCUT','PIVOTCUT','HINGECUT','SEAMCUT','BREAKPOINTENTROPY','HINGEPOINTENTROPY','TEMPERATURE','VOIDENTROPY','SOLIDITY','HBONDENERGY','HAMMONDSCALE','SIDECHAINENTROPY','HINGEBARRIER','PIVOTBARRIER','WATER','MAXSPLIT','MINSEG','CAVITATION','FLORY','FLORYW'] Parameters = {} runGeoFold = '0' #Read in old parameters oldParFile = open(form['oldParameters'].value,'r') for line in oldParFile: if len(line) != 1: line = line.split() oldParameters[line[0]] = " ".join(line[1:]) oldParFile.close() #Check if any parameters have changed for parameter in changeParameters: if oldParameters[parameter] != form.getvalue(parameter.lower(),'0'): runGeoFold = '1' #form.add_field('rungeofold', runGeoFold) #Everything else is the same as secondScript, so copypasta #directories and basic settings waitimage = "http://www.bioinfo.rpi.edu/bystrc/pub/mpeg/peptide.gif" #set directories basedir = "/bach1/home/flex" gdir = "%s/server/geofold"%(basedir) urldir = "/bach1/home/flex/public_html/geofold" tmpdir = "%s/tmp"%(gdir) #default parameters file paramfile = "%s/server/geofold/bin/parameters"%(basedir) #pdb repository pdbdir = "%s/server/data/pdb/"%(basedir) pdbunit = "%s/server/data/pdb1/"%(basedir) settings= "settings.html" pid = os.getpid() outdir = "output/" jobdir = "%s/jobs"%(gdir) #set url name try: lname = form["lname"].value except KeyError: lname = "%s.%s"%(form["keyword"].value,form["pdbcode"].value) url = "%s/%s%s/%s.html"%(urldir,outdir,lname,lname) urlwrite = "http://www.bioinfo.rpi.edu/geofold/%s%s/%s.html"%(outdir,lname,lname) #write HTML output os.environ["JOBURL"] = urlwrite print('<meta http-equiv="refresh" content="4;url=%s">'%(urlwrite)) print('</head><body><h4>Creating GeoFOLD job. Please wait...</h4><br>') #new URL settings #reset url name url = "%s/%s.html"%(lname,lname) #write-out parameters file file = open("%s/%s.par"%(tmpdir,lname),'w+') makeParameters(form,file) write_param = open('%s/%s.par'%(tmpdir,lname),'a') write_param.write("RUNGEOFOLD "+runGeoFold) write_param.close() #get chain info for html results chains = '' for value in form: if "chain_" in value: chains+=form[value].value else: chains = '.' #Write out initial HTML results page print('<h4>Your GeoFold job is in the queue but has not yet started.</h4>\n') print('<p>Your input coordinates were uploaded as filename %s chains %s\n'%(form["pdbcode"].value,chains)) print('<p>Notifications will be sent to %s\n'%(form["email"].value)) print('<p><a href="%s">BOOKMARK THIS PAGE</a>:\n'%(url)) print('<p>Stay on this page, or return to this page to see your results,') print('which will include the following:<br><ul>\n') print('<li>The timecourse of unfolding as concentrations of Folded, Unfolded, and Intermediate states.</li>\n') print('<li>An unfolding pathway in the form of a clickable pathway tree.</li>\n') print('<li>An Age Plot expressing the order of contact loss during unfolding.</li>\n') print('<li>Unfolding/folding kinetics simulations and associated plots.</li>\n') print('</ul>') print('<p>You will see results for multiple values of &omega; (virtual denaturant).\n') print('<p>You will have the option to Do Over, changing the &omega; values or any other parameters.\n') print('<p><a href="http://www.bioinfo.rpi.edu/bystrc/geofold/settings.html">Click on this page') print('to see a brief explanation of the parameters.</a>\n') print('<p><a href="http://www.bioinfo.rpi.edu/bystrc/geofold/howtoreadit.htm">Click on this page') print('to see a guide to GeoFold output.</a>\n') print('<p><img src="%s"><br>\n'%(waitimage)) print('</body></html>') #out.close() #write job file job = open("%s/%s.job"%(jobdir,lname),'w+') job.write('%s %s %s'%(form["pdbcode"].value,chains,lname)) try: oname = form["oname"].value except KeyError: oname = '' job.write(' %s'%(oname)) job.close() #deprotect files commands.getstatusoutput('chmod 0777 %s/%s'%(outdir,url)) commands.getstatusoutput('chmod 0777 %s/%s.job'%(jobdir,lname)) commands.getstatusoutput('chmod 0777 %s/%s.par'%(tmpdir,lname))
[ "def main():\n\t#set the conditionals for the calibrators and the hubble flow \n\tif input_params['fitcalib']:\n\t\tcalib_fits = fit_multiple_gps(gl=calib, out_direc='paper_plots/calib/', out_direc_fits='calib_lcs/fits/')\n\n\tif input_params['fitcalib'] and input_params['writecalib']:\n\t\tnp.savetxt('calib_fromscript.dat', calib_fits, fmt='%s', delimiter='\\t')\n\n\tif input_params['fithubble']:\n\t\t#fit the hubble flow objects\n\t\thflow_fits = list(fit_multiple_gps(gl=hflow))\n\t\t\n\t\t#fit the objects that need the parameters to be changed\n\t\thflow_fits = fit_tuned([])\n\t\thflow_fits = np.array(hflow_fits)\n\n\t\t#sort by the SN name\n\t\thflow_fits = hflow_fits[hflow_fits[:,0].argsort()]\n\n\t#if the option to write is set, use savetxt to save the fits\t\n\tif input_params['fithubble'] and input_params['writehubble']:\n\t\tnp.savetxt('hubbleflow_fromscript.dat', hflow_fits, fmt='%s', delimiter='\\t')", "def a2744_glassdatareduction(workdir='/Users/kschmidt/work/JWST/grizly_A2744/Prep',clobber=True):\n print(' - Reducing A2744 GLASS data using ')\n print(' - Grizli version '+grizli.__version__)\n try:\n os.chdir(workdir)\n print(' - Moved to directory '+os.getcwd())\n except:\n sys.exit('Working directory '+workdir+' does not exists')\n\n files = glob.glob('../RAW/*flt.fits')\n info = grizli.utils.get_flt_info(files)\n ascii.write(info,'./rawFLTfileinfo.txt')\n visits, filters = grizli.utils.parse_flt_files(info=info, use_visit=False, uniquename=True)\n\n for i in range(len(visits)):\n print(dict(visits[i]))\n\n gotoextraction = True # <------------------------------------------------------------------- Keyword for skipping\n if not gotoextraction:\n print(' ----------------------- Master Pre-processing ----------------------- ')\n from grizli.prep import process_direct_grism_visit\n print(' - defining visit pairs to process (NEEDS TO BE UPDATED TO INCLUE ALL OBS)')\n visitpairs = [[visits[0],visits[4]],[visits[2],visits[6]],[visits[7],visits[11]], [visits[9],visits[13]]]\n\n runmaster = False # <--------------------------------------------------------------------- Keyword for skipping\n if runmaster:\n for vv, visit in enumerate(visits):\n print(' ----- Visit No. '+str(vv+1)+' ----- ')\n visitfiles = visits[vv]['files']\n print(' Files: '+str(visitfiles))\n for vf in visitfiles:\n infoent = np.where(info['FILE'] == vf)[0]\n print(' '+vf+' infofilter = '+str(info['FILTER'][infoent][0]))\n\n for vp in visitpairs:\n status = process_direct_grism_visit(direct=vp[0], grism=vp[1],\n radec='../hst_a2744_60mas_merged_radec_F140Wlt24.txt',\n align_mag_limits=[14,23])\n else:\n print('Skipping master pre-processing')\n\n shiftlogs = glob.glob('*shifts.log')\n print(' - For info on shifts, check '+''.join(shiftlogs))\n # !ls *shifts.log\n # print('')\n # !cat *shifts.log\n\n print(' ----------------------- Grouping FLTs ----------------------- ')\n all_grism_files = []\n grismvisits = [vp[1] for vp in visitpairs]\n for i in range(len(grismvisits)):\n all_grism_files.extend(grismvisits[i]['files'])\n\n print(' - Grism files (all_grism_files) to group: '+str(all_grism_files))\n refimgpath = '/Users/kschmidt/work/images_MAST/images_fullfov/'\n grp = GroupFLT(grism_files=all_grism_files, direct_files=[],\n ref_file=refimgpath+'refimage_hlsp_frontier_hst_wfc3-60mas_abell2744_f140w_v1.0_drz.fits',\n seg_file=refimgpath+'refimage_hlsp_frontier_hst_wfc3-60mas_abell2744_f140w_v1.0_drz_seg.fits',\n catalog='/Users/kschmidt/work/catalogs/GLASScatalogs/GLASScatalog_A2744_150515.cat',\n cpu_count=8)\n\n\n print(' ----------------------- Generate Continuum Model ----------------------- ')\n genmodels = False # <------------------------------------------------------------------- Keyword for skipping\n if genmodels:\n grp.compute_full_model(mag_limit=25)\n\n print(' - Plotting: Show FLT residuals')\n fig = plt.figure(figsize=[12,6])\n ax = fig.add_subplot(121)\n ax.imshow(grp.FLTs[0].grism['SCI'] - grp.FLTs[0].model, vmin=-0.02, vmax=0.2, cmap='cubehelix_r',\n interpolation='Nearest', origin='lower')\n ax.set_title('G102, %s' %(grp.FLTs[0].grism.parent_file))\n\n ax = fig.add_subplot(122)\n ax.imshow(grp.FLTs[4].grism['SCI'] - grp.FLTs[4].model, vmin=-0.02, vmax=0.2, cmap='cubehelix_r',\n interpolation='Nearest', origin='lower')\n ax.set_title('G141, %s' %(grp.FLTs[4].grism.parent_file))\n\n for ax in fig.axes:\n #ax.set_xlim(500,700); ax.set_ylim(500,700)\n ax.set_xlim(100,1500); ax.set_ylim(100,1500)\n fig.savefig('./FLTresiduals_continuum_model.pdf')\n\n else:\n print('Skipping continuum model')\n\n\n print(' ----------------------- Generate Polynomial Model ----------------------- ')\n if genmodels:\n grp.refine_list(poly_order=2, mag_limits=[16, 24], verbose=False)\n\n\n print(' - Plotting: Show FLT residuals')\n fig = plt.figure(figsize=[12,6])\n ax = fig.add_subplot(121)\n ax.imshow(grp.FLTs[0].grism['SCI'] - grp.FLTs[0].model, vmin=-0.02, vmax=0.2, cmap='cubehelix_r',\n interpolation='Nearest', origin='lower')\n ax.set_title('G102, %s' %(grp.FLTs[0].grism.parent_file))\n\n ax = fig.add_subplot(122)\n ax.imshow(grp.FLTs[4].grism['SCI'] - grp.FLTs[4].model, vmin=-0.02, vmax=0.2, cmap='cubehelix_r',\n interpolation='Nearest', origin='lower')\n ax.set_title('G141, %s' %(grp.FLTs[4].grism.parent_file))\n\n for ax in fig.axes:\n #ax.set_xlim(500,700); ax.set_ylim(500,700)\n ax.set_xlim(100,1500); ax.set_ylim(100,1500)\n fig.savefig('./FLTresiduals_polynomial_model.pdf')\n else:\n print('Skipping Polynomial model')\n\n\n print(' ----------------------- Save Models ----------------------- ')\n if genmodels:\n grp.save_full_data()\n else:\n print(' did not generate models, so did not save models to disk')\n\n else:\n print('\\n NB\\n - Going directly to spectral extraction...')\n\n print(' ----------------------- Prepare Fitting Spectra ----------------------- ')\n all_grism_files = ['ica501u3q_flt.fits', 'ica501uaq_flt.fits', 'ica501uhq_flt.fits', 'ica501uoq_flt.fits',\n 'ica501tbq_flt.fits', 'ica501tiq_flt.fits', 'ica501tpq_flt.fits', 'ica501twq_flt.fits',\n 'ica503fwq_flt.fits', 'ica503g3q_flt.fits', 'ica503gaq_flt.fits', 'ica503ghq_flt.fits',\n 'ica503ecq_flt.fits', 'ica503ejq_flt.fits', 'ica503eqq_flt.fits', 'ica503f5q_flt.fits']\n\n print(' - Grism files (all_grism_files) to group: '+str(all_grism_files))\n refimgpath = '/Users/kschmidt/work/images_MAST/images_fullfov/'\n grp = GroupFLT(grism_files=all_grism_files, direct_files=[],\n ref_file=refimgpath+'refimage_hlsp_frontier_hst_wfc3-60mas_abell2744_f140w_v1.0_drz.fits',\n seg_file=refimgpath+'refimage_hlsp_frontier_hst_wfc3-60mas_abell2744_f140w_v1.0_drz_seg.fits',\n catalog='/Users/kschmidt/work/catalogs/GLASScatalogs/GLASScatalog_A2744_150515.cat',\n cpu_count=8)\n\n print(' ----------------------- Setting up templates for fits ----------------------- ')\n # First is set with combined emission line complexes for the redshift fit\n # (don't allow infinite freedom) of the line ratios / fluxes\n templ0 = grizli.utils.load_templates(fwhm=1200, line_complexes=True, stars=False,\n full_line_list=None, continuum_list=None,\n fsps_templates=True)\n\n # Second set has individual line templates for fitting the line fluxes\n templ1 = grizli.utils.load_templates(fwhm=1200, line_complexes=False, stars=False,\n full_line_list=None, continuum_list=None,\n fsps_templates=True)\n\n # Show the template names / dictionary keys\n fmt = '{0:<36s} {1:<36s}'\n print(fmt.format('templ0', 'templ1'))\n print(fmt.format('------', '------'))\n\n for i in range(len(templ1)):\n if i > len(templ0)-1:\n print(fmt.format('', list(templ1.keys())[i]))\n else:\n print(fmt.format(list(templ0.keys())[i], list(templ1.keys())[i]))\n\n # Parameters for drizzled line maps\n pline = {'kernel': 'point', 'pixfrac': 0.2, 'pixscale': 0.1, 'size': 8, 'wcs': None}\n\n\n print(' ----------------------- Pull out individual objects ----------------------- ')\n # grp `GroupFLT` object created as defined in WFC3IR_Reduction from the WFC3 ERS grism data\n target = 'glass_a2744'\n\n # ELs Cont Cont\n ids = [161, 316, 694]\n\n for id in ids:\n # Pull out the 2D cutouts\n beams = grp.get_beams(id, size=80)\n mb = grizli.multifit.MultiBeam(beams, fcontam=0.5, group_name=target, psf=False)\n\n # Save a FITS file with the 2D cutouts (beams) from the individual exposures\n mb.write_master_fits()\n\n # Fit polynomial model for initial continuum subtraction\n wave = np.linspace(2000,2.5e4,100)\n poly_templates = grizli.utils.polynomial_templates(wave, order=7)\n pfit = mb.template_at_z(z=0, templates=poly_templates, fit_background=True,\n fitter='lstsq', get_uncertainties=2)\n\n # Drizzle grisms / PAs\n hdu, fig = mb.drizzle_grisms_and_PAs(fcontam=0.2, flambda=False, kernel='point',\n size=32, zfit=pfit)\n\n # Save drizzle figure FITS file\n fig.savefig('{0}_{1:05d}.stack.png'.format(target, id))\n hdu.writeto('{0}_{1:05d}.stack.fits'.format(target, id), clobber=True)\n\n\n print(' ----------------------- Run wrapper on object '+str(id)+'----------------------- ')\n # High-level wrapper script for doing everything (redshift fits, line fluxes, drizzled line\n # maps). More explanation of the details of individual steps TBD.\n #\n # Needs to be able to find {target}_{id:05d}.beams.fits and {target}_{id:05d}.stack.fits\n # generated above\n out = grizli.fitting.run_all(id, t0=templ0, t1=templ1, fwhm=1200,\n zr=[0.1, 1.7], dz=[0.004, 0.0005],\n fitter='nnls', group_name=target, prior=None, fcontam=0.,\n pline=pline, mask_sn_limit=7, fit_beams=True, fit_stacks=False,\n root=target+'_', fit_trace_shift=False, verbose=False,\n phot=None, scale_photometry=False, show_beams=True)\n\n\n print(\" - For analyzing fit output see\\n\"\n \" https://github.com/gbrammer/grizli/blob/master/examples/NewSpectrumFits.ipynb\")", "def main(self, run_step=0):\n\n self.copy_files()\n\n if run_step < 1:\n print(\"Creating a dta file with bundles and measure for the legacy stata process. Also an rei/acause map to bundle_id\")\n self.create_bundle_file()\n\n write_acause_rei_to_bundle_map(self.run_id)\n\n if run_step < 2:\n print(\"Sending out the master script to process MS data to the individual level\")\n run_marketscan(self.run_id)\n self.job_holder(job_name=\"ms_group\")\n\n if run_step < 3:\n print(\"Qsubbing the legacy Stata code to aggregate before noise reduction\")\n self.pre_nr_agg()\n self.job_holder(job_name=\"pre_nr_\")\n\n if run_step < 4:\n print(\"Qsubbing the legacy Stata code to run Noise Reduction on inpatient data\")\n self.ms_nr(\"inp\")\n self.job_holder(job_name=\"stata_submit\")\n self.job_holder(job_name=\"ms_nr\")\n\n if run_step < 5:\n print(\"Qsubbing the legacy Stata code to run Noise Reduction on U(inpatient, outpatient) data\")\n\n\n self.ms_nr(\"all\")\n self.job_holder(job_name=\"stata_submit\")\n self.job_holder(job_name=\"ms_nr\")\n\n print(\"The claims process has finished running. Inputs for the CFs should be ready and NR\"\\\n \" estimates are available in FILEPATH\"\\\n format(self.run_id))\n print(\"Sending out the job to format the final bundle level estimates for upload.\")\n warnings.warn(\"we're applying the asfr adjustment for maternal data. Maternal Bundles are hard coded and decomp step is hardcoded\")\n self.decomp_step = 'step1'\n self.write_bundle_csv()\n return", "def main():\n # Efforts to obtain name of pwscf input file for given md run\n try:\n pw_input = sys.argv[1]\n except IndexError:\n try:\n pw_input = glob.glob('input.*.pw')[0]\n except:\n print '\\nMake sure you are in the proper directory, exiting now...\\n'\n\t sys.exit(0)\n\n # Move any previous analysis\n if 'analysis/' in glob.glob('*/'):\n print 'Moving previous analysis... '\n if 'previous_analysis/' in glob.glob('*/'):\n os.system('rm -rf previous_analysis/')\n os.system('mv -f analysis/ previous_analysis')\n print 'done'\n os.system('rm -f output/fake.out output/output.out')\n\n # Put output.out into the output directory\n try:\n f = open('output.out','r')\n f.close()\n os.system('mv -f output.out output/')\n except:\n pass\n\n # Retrieve timestep (au) and lattice constants from input file\n rs = os.getcwd().split('/')[-1]\n step_in_au = int(commands.getoutput(\"grep dt \"+pw_input+\" | awk '{print $3}'\")) * 2\n celldm = commands.getoutput(\"grep celldm \"+pw_input+\" | awk '{print $3}'\").split()\n natom = int(commands.getoutput(\"grep nat \"+pw_input+\" | awk '{print $3}'\"))\n a = str( float(celldm[0]) * 0.5291772 )\n b, c = a, a\n\n # Extract band energy information (w/ or w/o smearing)\n print 'Analyzing bands...'\n if len(commands.getoutput(\"grep smearing \"+pw_input).split()) > 0:\n os.system('fermi_bands_histogram.py > bands.out')\n else:\n os.system('bands_histogram.py > bands.out') \n print 'done'\n \n# # Retrieve run information (w/ or w/o smearing)\n# print 'Running pw_monitor.py... '\n# if len(commands.getoutput(\"grep smearing \"+pw_input).split()) > 0:\n# os.system('fermi_pw_monitor.py')\n# else:\n# os.system('pw_monitor.py')\n# print 'done'\n\n # Extract thermodynamic quantities\n print 'Extracting T, P, & E and averaging...'\n os.system('pw_temperature.py')\n os.system('tail -'+str(nFinalConfigs)+' temperature.dat > T.dat')\n os.system('blocker T.dat 3 > temperature.blocker')\n os.system('pw_pressure.py')\n os.system('tail -'+str(nFinalConfigs)+' pressure.dat > P.dat')\n os.system('blocker P.dat 3 > pressure.blocker')\n os.system('pw_energy.py')\n os.system('tail -'+str(nFinalConfigs)+' energy.dat > E.dat')\n os.system('blocker E.dat 3 > energy.blocker')\n os.system('rm -f T.dat P.dat E.dat')\n print 'done'\n\n # Create the xyz file from the pwscf output files\n print 'Extracting xyz file... '\n os.system('xyz_from_pwscf.py '+pw_input)\n\n # Remove trailing incomplete configuration\n TRAJEC_trim('TRAJEC.xyz')\n print 'done'\n\n # Take the last nFinalConfigs configurations for further analysis\n fnameFinal = 'FINAL-'+str(nFinalConfigs)+'.xyz'\n nFinalLines = (natom + 2)*nFinalConfigs\n os.system('tail -'+str(nFinalLines)+' TRAJEC.xyz > '+fnameFinal)\n\n # Write an input file for cbn_from_xyz.x\n out = open('cbn.in','w')\n out.write(fnameFinal+'\\n')\n out.write(celldm[0]+','+celldm[0]+','+celldm[0]+'\\n')\n out.close()\n\n # Create the cbn file\n print 'Extracting cbn file...'\n os.system('cbn_from_xyz.x < cbn.in > cbn.out')\n os.system('rm -f cbn.out')\n print 'done'\n\n # Create TRAJEC.cnn and nn_average.hist files\n print 'Extracting cnn file and calculating nn_average.hist...'\n Nbins = 200\n os.system('nn_distance_distributions_cnn.py '+str(Nbins)+' '+celldm[0]+' '+celldm[0]+' ' \\\n\t +celldm[0]+' '+fnameFinal+' > nn.out')\n os.system('rm -f nn.out')\n print 'done'\n\n # Calculate angle distributions out to 3rd neighbors\n print 'Calculating angle distributions...'\n os.system('nn_angle_distributions.py 100 1 2 TRAJEC.cnn > angle1.out &')\n os.system('nn_angle_distributions.py 100 1 3 TRAJEC.cnn > angle2.out &')\n os.system('nn_angle_distributions.py 100 2 3 TRAJEC.cnn > angle3.out')\n os.system('rm -f angle*.out')\n print 'done'\n\n # Calculate lifetimes of clusters of 2, 3, & 4 atoms\n print 'Calculating cluster lifetimes...'\n os.system('bonding_lifetime_n_body.py TRAJEC.cnn 1 '+str(nFinalConfigs/2)+' > cluster1.out &')\n os.system('bonding_lifetime_n_body.py TRAJEC.cnn 2 '+str(nFinalConfigs/2)+' > cluster2.out &')\n os.system('bonding_lifetime_n_body.py TRAJEC.cnn 3 '+str(nFinalConfigs/2)+' > cluster3.out &')\n os.system('bonding_lifetime_n_body.py TRAJEC.cnn 4 '+str(nFinalConfigs/2)+' > cluster4.out &')\n os.system('bonding_lifetime_n_body.py TRAJEC.cnn 5 '+str(nFinalConfigs/2)+' > cluster5.out')\n os.system('rm -f cluster*.out')\n print 'done'\n \n # Calculate the coordination of the atoms\n print 'Calculating coordination of atoms...'\n os.system('get_coord.pl TRAJEC.cnn '+gr_min(rs))\n os.system('av_coor_to_column.py av_coordination_rc_'+gr_min(rs)+'.dat')\n print 'done'\n\n# # Calculate bond frequencies/periods, and lengths from cbn file\n# print 'Performing bond analysis...'\n# os.system('bond_freq.py TRAJEC.cbn '+str(step_in_au))\n# print 'done'\n\n # Construct RDF input file\n print 'Calculating RDF, MSD, & VACF... '\n out = open('RDF.in','w')\n out.write(fnameFinal+'\\n')\n out.write('RDF.dat\\n')\n out.write('N\\nN\\n')\n out.write(str(float(a)/2.0)+'\\n')\n out.write('0.02\\n')\n out.write('0\\n')\n out.write(str(a)+', '+str(b)+', '+str(c)+'\\n')\n out.close()\n\n # Construct MSD input files\n out = open('MSD.in','w')\n out.write('TRAJEC.xyz\\n')\n out.write('MSD.dat\\n')\n out.write(str(step_in_au)+'\\n')\n out.write('1\\n')\n out.write('1\\n')\n out.write('N\\n')\n out.close()\n out = open('msd.in','w')\n out.write('TRAJEC.xyz\\n')\n out.close()\n\n # Construct VACF input file\n out = open('VACF.in','w')\n out.write(fnameFinal+'\\n')\n out.write('VACF.dat\\n')\n out.write(str(step_in_au)+'\\n')\n out.write('1\\n')\n out.write('1\\n')\n out.write('ALL\\n')\n out.close()\n\n # Calculate RDF, MSD & VACF\n os.system('RDF < RDF.in > RDF.out')\n os.system('MSD < MSD.in > MSD.out')\n os.system('msd.x < msd.in > msd.out')\n os.system('VACF < VACF.in > VACF.out')\n os.system('rm -f RDF.out MSD.out msd.out msd.in VACF.out fort.*')\n print 'done'\n\n # Calculate PSD of VACF\n print 'Taking PSD of VACF...'\n os.system('PSD.py VACF.dat')\n os.system('mv PSD.dat VACF.psd')\n print 'done'\n\n # Calculate diffusion\n print 'Calculating diffusion...'\n os.system('diffusion.py MSD.dat DIFFUSION.dat')\n os.system('diffusion.py msd.dat diffusion.dat')\n print 'done'\n\n # Put everything in a separate analysis sub-directory\n print 'Finalizing... '\n os.system('date > date')\n os.system('rm -f temp.xyz')\n os.system('mkdir analysis')\n if 'tmp/pwscf.msd.dat' in glob.glob('tmp/pwscf.msd.dat'):\n os.system('mv -f tmp/pwscf.msd.dat analysis/')\n os.system('mv -f RDF.in RDF.dat MSD.in MSD.dat msd.dat VACF.in VACF.dat VACF.psd DiffCoef.data \\\n DIFFUSION.dat diffusion.dat *.blocker temperature.dat pressure.dat energy.dat \\\n\t\t bands* *.hist cbn.in diss.dat correlator_*nn.dat TRAJEC.xyz TRAJEC.cbn TRAJEC.cnn \\\n\t av_coordination_rc* coordination_rc_*.dat date '+fnameFinal+' analysis/')\n # Copy any relevant plotting scripts to analysis/\n os.system('cp /home/boates/data/nitrogen/pwscf/remote/gnuplot_scripts/* analysis/')\n print 'Analysis complete'", "def refine4grid(self, nb_event):\n self.nb_refine += 1\n \n precision = nb_event\n\n self.opts = dict([(key,value[1]) for (key,value) in \\\n self._survey_options.items()])\n \n # initialize / remove lhapdf mode\n # self.configure_directory() # All this has been done before\n self.cluster_mode = 0 # force single machine\n\n # Store seed in randinit file, to be read by ranmar.f\n self.save_random()\n \n self.update_status('Refine results to %s' % precision, level=None)\n logger.info(\"Using random number seed offset = %s\" % self.random)\n\n refine_opt = {'err_goal': nb_event, 'split_channels': False,\n 'ngran':self.granularity, 'readonly': self.readonly} \n x_improve = gen_ximprove.gen_ximprove_gridpack(self, refine_opt)\n x_improve.launch() # create the ajob for the refinment and run those!\n self.gscalefact = x_improve.gscalefact #store jacobian associate to the gridpack \n \n \n #bindir = pjoin(os.path.relpath(self.dirbin, pjoin(self.me_dir,'SubProcesses')))\n #print 'run combine!!!'\n #combine_runs.CombineRuns(self.me_dir)\n \n return\n #update html output\n Presults = sum_html.collect_result(self)\n cross, error = Presults.xsec, Presults.xerru\n self.results.add_detail('cross', cross)\n self.results.add_detail('error', error)\n \n \n #self.update_status('finish refine', 'parton', makehtml=False)\n #devnull.close()\n \n \n \n return\n self.total_jobs = 0\n subproc = [P for P in os.listdir(pjoin(self.me_dir,'SubProcesses')) if \n P.startswith('P') and os.path.isdir(pjoin(self.me_dir,'SubProcesses', P))]\n devnull = open(os.devnull, 'w')\n for nb_proc,subdir in enumerate(subproc):\n subdir = subdir.strip()\n Pdir = pjoin(self.me_dir, 'SubProcesses',subdir)\n bindir = pjoin(os.path.relpath(self.dirbin, Pdir))\n \n logger.info(' %s ' % subdir)\n # clean previous run\n for match in misc.glob('*ajob*', Pdir):\n if os.path.basename(match)[:4] in ['ajob', 'wait', 'run.', 'done']:\n os.remove(pjoin(Pdir, match))\n \n\n logfile = pjoin(Pdir, 'gen_ximprove.log')\n misc.call([pjoin(bindir, 'gen_ximprove')],\n stdin=subprocess.PIPE,\n stdout=open(logfile,'w'),\n cwd=Pdir)\n\n if os.path.exists(pjoin(Pdir, 'ajob1')):\n alljobs = misc.glob('ajob*', Pdir)\n nb_tot = len(alljobs) \n self.total_jobs += nb_tot\n for i, job in enumerate(alljobs):\n job = os.path.basename(job)\n self.launch_job('%s' % job, cwd=Pdir, remaining=(nb_tot-i-1), \n run_type='Refine number %s on %s (%s/%s)' %\n (self.nb_refine, subdir, nb_proc+1, len(subproc)))\n if os.path.exists(pjoin(self.me_dir,'error')):\n self.monitor(html=True)\n raise MadEventError, \\\n 'Error detected in dir %s: %s' % \\\n (Pdir, open(pjoin(self.me_dir,'error')).read())\n self.monitor(run_type='All job submitted for refine number %s' % \n self.nb_refine)\n \n self.update_status(\"Combining runs\", level='parton')\n try:\n os.remove(pjoin(Pdir, 'combine_runs.log'))\n except Exception:\n pass\n \n bindir = pjoin(os.path.relpath(self.dirbin, pjoin(self.me_dir,'SubProcesses')))\n combine_runs.CombineRuns(self.me_dir)\n \n #update html output\n cross, error = self.make_make_all_html_results()\n self.results.add_detail('cross', cross)\n self.results.add_detail('error', error)\n \n \n self.update_status('finish refine', 'parton', makehtml=False)\n devnull.close()", "def process_elm_roundup_sampled(options):\n\t\n results_dir = 'working/runs/Jun25_2/'\n\tc_arg = ''\n\tif options.process_elm_roundup_sampled.get('picloud', False): c_arg = '-c'\n\t\n sh('python sample_from_clusters.py '\n + 'results/Homo_Mus_Pan_Rat_Bos_Can_Gal_Tae_Dan_Mac.roundup.parsed '\n + 'data/roundup_all/ '\n + results_dir)\n \n\tfor genome in ('H_sapiens', 'M_musculus', 'Pan_troglodytes', \n 'R_norvegicus', 'Gallus_gallus', 'Taeniopygia_guttata',\n 'Canis_familiaris', 'Bos_taurus'):\n\t\tofile = os.path.join(results_dir, 'elmdict_'+genome+'.init')\n\t\tifile = os.path.join(results_dir, genome+'.fa')\n\t\tif not os.path.exists(ofile) or options.process_elm_roundup_sampled.get('forcenew', False):\n\t\t\t# only do if missing or FORCING\n\t\t\tsh('python makeELMdict.py %(c)s -o %(out)s %(infile)s' % {'out':ofile, \n\t\t\t\t\t\t\t\t\t\t 'c':c_arg, 'infile': ifile})", "def run_dr(project, input_file):\n root_dir = conf.get('root_dir','') \n proj_dir = os.path.join (root_dir,project)\n sbatch_template = ('#!/bin/bash -l\\n'\n '#SBATCH -A b2012025\\n'\n '#SBATCH -J {name}_peakcall\\n'\n '#SBATCH -p core -n 1 \\n'\n '#SBATCH -t 5:00:00\\n'\n '#SBATCH -o '+proj_dir+'/{rep1}_Vs_{rep2}/scripts/{name}_idr.stdout\\n'\n '#SBATCH -e '+proj_dir+'/{rep1}_Vs_{rep2}/scripts/{name}_idr.stderr\\n'\n '#SBATCH --mail-type=FAIL\\n'\n '#SBATCH --mail-user=\\'ashwini.jeggari@scilifelab.se\\'\\n\\n'\n 'module load bioinfo-tools\\n'\n 'sort -k 8,8nr {rep1_dir}/*.narrowPeak > {rep1_dir}/tmp.regionPeak\\n'\n 'intersectBed -a {rep1_dir}/tmp.regionPeak -b {mm10_blacklisted-regions.bed} > {rep1_dir}/cleanedpeaks.regionPeak\\n'\n 'sort -k 8,8nr {rep2_dir}/*.narrowPeak > {rep2_dir}/tmp.regionPeak\\n'\n 'intersectBed -a {rep2_dir}/tmp.regionPeak -b {mm10_blacklisted-regions.bed} > {rep2_dir}/cleanedpeaks.regionPeak\\n' \n 'Rscript batch-consistency-analysis.r rep1,rep2 -1 idr_op 0 F p.value {mm10.genome}\\n'\n\n)\n\n\n pk_file = open(input_file,'r')\n pk_file.next()\n for ln in iter(pk_file): \n ln = ln.strip()\n ln = ln.split('\\t')\n rep1 = ln[0]\n rep2 = ln[1]\n name = \"{}_Vs_{}\".format(rep1,rep2)\n rep1_dir = ''.join(glob(\"{}/{}/macs2_*\".format(proj_dir,rep1)))\n peaks_dir = os.path.join(proj_dir,treat,\"{}_{}\".format(peak_call,mode))\n if not os.path.exists(peaks_dir):\n os.makedirs(peaks_dir)\n job_fl = os.path.join(proj_dir,treat,\"scripts\",\"{}_peakcall.sh\".format(name))\n template_pc = sbatch_template + template\n with open(job_fl,'w') as jb_fl:\n jb_fl.write(template_pc.format(name=name,treat=treat, treatment=treat_fl, control=control_fl,peaks_dir=peaks_dir))\n subprocess.check_call(['sbatch',job_fl])", "def collect_the_results(self,options,req_acc,jobs_to_run,jobs_to_collect,\\\n integration_step,mode,run_mode,fixed_order=True):\n# Get the results of the current integration/MINT step\n self.append_the_results(jobs_to_run,integration_step)\n self.cross_sect_dict = self.write_res_txt_file(jobs_to_collect,integration_step)\n# Update HTML pages\n if fixed_order:\n cross, error = self.make_make_all_html_results(folder_names=['%s*' % run_mode], \n jobs=jobs_to_collect)\n else:\n name_suffix={'born' :'B' , 'all':'F'}\n cross, error = self.make_make_all_html_results(folder_names=['G%s*' % name_suffix[run_mode]])\n self.results.add_detail('cross', cross)\n self.results.add_detail('error', error)\n# Combine grids from split fixed order jobs\n if fixed_order:\n jobs_to_run=self.combine_split_order_run(jobs_to_run)\n# Set-up jobs for the next iteration/MINT step\n jobs_to_run_new=self.update_jobs_to_run(req_acc,integration_step,jobs_to_run,fixed_order)\n # IF THERE ARE NO MORE JOBS, WE ARE DONE!!!\n if fixed_order:\n # Write the jobs_to_collect directory to file so that we\n # can restart them later (with only-generation option)\n with open(pjoin(self.me_dir,\"SubProcesses\",\"job_status.pkl\"),'wb') as f:\n pickle.dump(jobs_to_collect,f)\n# Print summary\n if (not jobs_to_run_new) and fixed_order:\n # print final summary of results (for fixed order)\n scale_pdf_info=self.collect_scale_pdf_info(options,jobs_to_collect)\n self.print_summary(options,integration_step,mode,scale_pdf_info,done=True)\n return jobs_to_run_new,jobs_to_collect\n elif jobs_to_run_new:\n # print intermediate summary of results\n scale_pdf_info=[]\n self.print_summary(options,integration_step,mode,scale_pdf_info,done=False)\n else:\n # When we are done for (N)LO+PS runs, do not print\n # anything yet. This will be done after the reweighting\n # and collection of the events\n scale_pdf_info=[]\n# Prepare for the next integration/MINT step\n if (not fixed_order) and integration_step+1 == 2 :\n # Write the jobs_to_collect directory to file so that we\n # can restart them later (with only-generation option)\n with open(pjoin(self.me_dir,\"SubProcesses\",\"job_status.pkl\"),'wb') as f:\n pickle.dump(jobs_to_collect,f)\n # next step is event generation (mint_step 2)\n jobs_to_run_new,jobs_to_collect_new= \\\n self.check_the_need_to_split(jobs_to_run_new,jobs_to_collect)\n self.prepare_directories(jobs_to_run_new,mode,fixed_order)\n self.write_nevents_unweighted_file(jobs_to_collect_new,jobs_to_collect)\n self.write_nevts_files(jobs_to_run_new)\n else:\n if fixed_order and self.run_card['iappl'] == 0 \\\n and self.run_card['req_acc_FO'] > 0:\n jobs_to_run_new,jobs_to_collect= \\\n self.split_jobs_fixed_order(jobs_to_run_new,jobs_to_collect)\n self.prepare_directories(jobs_to_run_new,mode,fixed_order)\n jobs_to_collect_new=jobs_to_collect\n return jobs_to_run_new,jobs_to_collect_new", "def run_experiment():\n \n print_instructions(instructions)\n print_instructions(instructions2)\n run_blocks(PRACTICE_BLOCKS, f, True) \n print_instructions(instructions3)\n run_blocks(BLOCKS, f)\n print_instructions(exit_message)\n save_and_quit(f)", "def RetMapBash(delLead, keepVol, infile_all, cond_all,\n SUBJECTS_DIR, openfmriDir,brainmask,prefix=\"\",nscans=4.\n bashscript='studyforrest-data-retinotopy/code/process_retmap'): \n \n #TODO: - convert bash to nipype -> write a RetinoProc wrapper\n import subprocess\n import os \n from HA_extFunctions import _findfile\n \n # for fslmaths: create a gauss kernel of sigma mm and perform mean filtering\n smooth = 4\n \n ## define inputs and bash script path itself ##\n #\n # Takes list of cond_all and infiles for all scans and selects the\n # number of cond and infiles depending on nscans\n infile_all = infile_all[:nscans]\n cond_all = cond_all[:nscans]\n # extract the actual subj from the filepath:\n subj = infile_all[0].split(\"/\")[-3]\n \n # transform list of strings of infile_all into one string #\n infiles = ' '.join(infile_all)\n cond_all = ' '.join(cond_all)\n \n # add quotation marks to the strings to make it readable as a list from the bash script\n infiles = ''.join([\"'\",infiles,\"'\"])\n cond_all = ''.join([\"'\",cond_all,\"'\"])\n \n # EPIdir depending on nscans\n EPInewDir = os.path.abspath(\"\") # to save the stuff in nipype workdir\n \n # merge script and all its inputs # \n cmd = ' '.join([bashscript,\n subj,\n infile_all[0],\n infile_all[2],\n infile_all[3],\n infile_all[1],\n str(True),\n brainmask[0],\n str(smooth), \n EPInewDir,\n str(True), str(0.0), str(0.0), str(101.25), str(-281.25),\n str(False), \"''\",\"''\", \"''\",\n str(True)\n ])\n\n # run script and get 0 if finished without errors #\n out0 = subprocess.call([cmd],shell=True)\n \n # grab files written by HA_RetMap_Flow_severalScans.sh as output #\n #outdir = os.path.join(openfmriDir,subj,'BOLD',EPIdir)\n here = os.path.abspath(\"\")\n phaseFilesPath = os.path.join(here,subj,'post_processing')\n preprocScansPath = os.path.join(here,subj,'pre_processing')\n \n preprocScans = _findfile(preprocScansPath,'*filt_masked.nii.gz')\n phaseFiles = _findfile(phaseFilesPath,'combined_*.nii.gz')\n print '.. Finished with node: RetMapBash'\n \n # if bash-script didn't finsh clean. throw Erroer\n if out0 != 0:\n #break\n print \">> ERROR <<\"\n else: \n return preprocScans, os.path.abspath(\"\"), phaseFiles", "def novel_polyAs_2(dsets, super_3utr, settings):\n\n my_novel_polyAs = []\n\n print('\\n'+'-'*70+'\\n')\n ## 1) How many total annotated poly(A) sites (and tian tb sites)\n #cmd1 = ['slopBed', '-b', '200', '-i', settings.annot_polyA_path, '-g',\n #settings.hg19_path]\n\n #f1 = Popen(cmd1, stdout=PIPE, bufsize=-1)\n\n #cmd2 = ['mergeBed', '-s', '-i', 'stdin'] # read from stdin\n\n #f2 = Popen(cmd2, stdin=f1.stdout, stdout=PIPE, bufsize=-1)\n\n all_annot_polyA = sum(1 for i in open(settings.annot_polyA_path))\n tian_db = sum(1 for i in open(settings.polyA_DB_path))\n\n print('Number of GENCODE annotated poly(A) sites: '\\\n '{0}\\n'.format(all_annot_polyA))\n print('Number of poly(A) sites in polyA_db: '\\\n '{0}\\n'.format(tian_db))\n\n # 2) How many annotated poly(A) sites in \"my\" 3UTRs. How many of these do I\n # recover? How many new do I find?\n cmd = ['intersectBed', '-u', '-a', settings.annot_polyA_path, '-b',\n settings.utr_exons_path]\n\n f = Popen(cmd, stdout=PIPE)\n # The number of annotated poly(A) sites in YOUR 3utrs\n my_annot = sum(1 for i in f.stdout)\n print('Number of GENCODE annotated poly(A) sites in \"our\" 3UTRS: '\\\n '{0}\\n'.format(my_annot))\n\n # 3)\n # The number of annotated pol(A) sites that I recover\n my_recover = 0\n # The number of novel poly(A) sites in 'my' 3UTRs\n my_novel = 0\n for utr_id, utr in super_3utr.iteritems():\n for super_polyA, cell_dict in utr.super_cover.items():\n has_annot = False\n enough_covrg = False\n # Trust if you find pA in more than 1 cell line\n if len(cell_dict) > 1:\n enough_covrg = True\n for c_line, comp_dict in cell_dict.items():\n # Trust if you find pA in more than 1 compartment\n if len(comp_dict) > 1:\n enough_covrg = True\n for comp, polyA in comp_dict.items():\n if polyA.annotated_polyA_distance != 'NA':\n has_annot = True\n # Trust if you find pA with more than 1 read\n if polyA.nr_support_reads > 1:\n enough_covrg = True\n\n if has_annot:\n my_recover += 1\n if enough_covrg:\n my_novel += 1\n\n # Save the novel polyA sites to a list\n if len(super_polyA.split('+')) == 2:\n my_novel_polyAs.append(tuple(super_polyA.split('+') + ['+']))\n else:\n my_novel_polyAs.append(tuple(super_polyA.split('-') + ['-']))\n\n print('Number of \"our\" poly(A) sites that are also in the GENCODe annotation: '\\\n '{0}\\n'.format(my_recover))\n print('Number of \"our\" poly(A) sites that are new to GENCODE: '\\\n '{0}\\n'.format(my_novel))\n\n #4) How many of these have been detected with ESTs/cDNA?\n #expand the polyA_db.bed-file and unique-intersect with a bedfile you write\n #of all your poly(A) sites\n # i) write these novel polyAs to bedfile\n out_dir = os.path.dirname(settings.annot_polyA_path)\n temp_path = os.path.join(out_dir, 'novel_polyA.bed')\n temp_handle = open(temp_path, 'wb')\n\n for nov in my_novel_polyAs:\n out = '\\t'.join([nov[0], nov[1], str(int(nov[1])+1), nov[2]]) + '\\n'\n temp_handle.write(out)\n\n temp_handle.close()\n\n # ii) Expand all entries in annotated polyAs with 2 nt, merge these entries,\n # and feed this into an overlapper with novel_polyA.bed; count the number of\n # overlaps\n cmd1 = ['slopBed', '-b', '20', '-i', settings.polyA_DB_path, '-g',\n settings.hg19_path]\n\n f1 = Popen(cmd1, stdout=PIPE, bufsize=-1)\n\n cmd2 = ['mergeBed', '-s', '-i', 'stdin'] # read from stdin\n\n f2 = Popen(cmd2, stdin=f1.stdout, stdout=PIPE, bufsize=-1)\n\n cmd3 = ['intersectBed', '-a', temp_path, '-b', 'stdin']\n\n f3 = Popen(cmd3, stdin=f2.stdout, stdout=PIPE, bufsize=-1)\n\n # the number of my novel poly(A) sites that are in Tian's database\n in_tian = sum(1 for i in f3.stdout)\n\n print('Number of \"our\" novel poly(A) sites that are also in polyA_db: '\\\n '{0}\\n'.format(in_tian))\n\n print('-'*70+'\\n')", "def fourth_part():\n result_dir = args.outdirname\n logger.info('Part 4: Processing recent HGT detection...')\n strain_result_dir = os.path.join(result_dir, 'strain_pair_result')\n (ani_matrix, matrix_strain_dict) = load_ani()\n tmp_result_dir = os.path.join(result_dir, 'tmp')\n if not os.path.exists(tmp_result_dir):\n os.makedirs(tmp_result_dir)\n else:\n shutil.rmtree(tmp_result_dir)\n os.makedirs(tmp_result_dir)\n for root, dirs, files in os.walk(strain_result_dir):\n for each_file in files:\n f_name = os.path.splitext(each_file)[0]\n f_path = os.path.join(strain_result_dir, each_file)\n pairs = f_name.split('_')\n # pair_name = str(pairs[0]) + ' ~ ' + str(pairs[1])\n pair_ani = ani_matrix[matrix_strain_dict[pairs[0]]][matrix_strain_dict[pairs[1]]]\n if pair_ani < 94:\n tmp_file = os.path.join(tmp_result_dir, each_file)\n shutil.copy(f_path, tmp_file)\n r_script = os.path.join(src_dir_name, 'rHGT_alpha.R')\n param_min = 40.0\n param_max = 98.0\n devnull = open(os.devnull, 'w')\n result_file = os.path.join(result_dir, 'recent_HGT_results.txt')\n try:\n subprocess.call(['Rscript', r_script, tmp_result_dir, result_file,\n str(param_min), str(param_max)], stdout=devnull, stderr=devnull)\n except OSError:\n logger.info('Try to run {0} but failed, please check.'.format(r_script))\n logger.error(last_exception())\n sys.exit(1)\n shutil.rmtree(tmp_result_dir)\n message = 'Recent HGT detections have been finished.'\n return message", "def main():\n\n \"Calls on the population function\"\n chr_population = population()\n\n \"Calls on the fitness function\"\n chr_pop_fitness, chr_best_fitness_index = fitness(chr_pop=chr_population)\n\n \"Calls on the rank function to generate ranking\"\n chr_ranked_population = ranking(chr_pop_fitness=chr_pop_fitness, pop=chr_population)\n\n \"Calls on the crossover and mutation function\"\n chr_crossover_mutated_population = dna(chr_pop_fitness=chr_pop_fitness,\n ranked_population=chr_ranked_population, chr_best_fitness_index=\n chr_best_fitness_index, last_pop=chr_population)\n\n show_plot(best_chromosome=chr_crossover_mutated_population[0])\n\n while not Config.stop_generation:\n\n prev_best_fit = chr_pop_fitness[chr_best_fitness_index[0], 0]\n\n chr_pop_fitness, chr_best_fitness_index = fitness(\n chr_pop=chr_crossover_mutated_population)\n\n chr_ranked_population = ranking(chr_pop_fitness=chr_pop_fitness, \n pop=chr_crossover_mutated_population)\n\n chr_crossover_mutated_population = dna(chr_pop_fitness=chr_pop_fitness,\n ranked_population=chr_ranked_population, chr_best_fitness_index=\n chr_best_fitness_index, last_pop=chr_crossover_mutated_population)\n \n print(\"Best chromosome is:\", chr_crossover_mutated_population[chr_best_fitness_index[0]]) \n \n if prev_best_fit == chr_pop_fitness[chr_best_fitness_index[0], 0]:\n Config.stop_criteria += 1\n else:\n Config.stop_criteria = 0\n\n if Config.stop_criteria >= 5:\n Config.stop_generation = True\n\n show_plot(best_chromosome=chr_crossover_mutated_population[0])\n progress = []\n for i in range(0, Config.generations+1):\n progress.append(sum(chr_crossover_mutated_population[chr_best_fitness_index[i]]))\n ave = []\n for i in range(0, Config.generations+1):\n ave.append(mean(chr_pop_fitness[i]))\n\n Config.generations += 1\n\n show_plot(best_chromosome=chr_crossover_mutated_population[0], inf_time=True)\n evolution_plot(progress)\n average_plot(ave)", "def main(police, clinics, courts, shelters, province, crime_data, outpath, name):\n\n # get_script_path = os.path.realpath(__file__)\n # script_folder = os.path.split(get_script_path)[0]\n # script_folder = os.path.abspath(script_folder)\n\n # set in and out-file paths and names\n police = os.path.abspath(police)\n clinics = os.path.abspath(clinics)\n courts = os.path.abspath(courts)\n shelters = os.path.abspath(shelters)\n province = os.path.abspath(province)\n crime_data = os.path.abspath(crime_data)\n\n outpath = os.path.abspath(outpath)\n name = name\n outfile = os.path.join(outpath, name)\n\n # process csv_infiles to dataframes\n geo_points_data_police_df = csv_to_geo_dataframe(police)\n geo_points_data_clinics_df = csv_to_geo_dataframe(clinics)\n geo_points_data_courts_df = csv_to_geo_dataframe(courts)\n geo_points_data_shelters_df = csv_to_geo_dataframe(shelters)\n\n outpath = os.path.abspath(outpath)\n name = name + \".html\"\n outfile = os.path.join(outpath, name)\n\n # combine crime stats and province dataframes\n crime_data = pd.read_csv(crime_data, sep=',', header=0)\n crime_data_df = pd.DataFrame(crime_data)\n crime_data_df.fillna(method='ffill', inplace=True)\n\n province_shape_df = gpd.read_file(province)\n province_shape_df.rename(columns={'PROVINCE': 'Province'}, inplace=True)\n province_shapes_incidence_gdf = pd.merge(province_shape_df, crime_data_df, how='inner', on=\"Province\")\n province_shapes_incidence_gdf[\"geoid\"] = province_shapes_incidence_gdf.index.astype(str)\n\n basic_map = name == 'basic.html'\n\n # plot the data\n map = plot_folium(province_shapes_incidence_gdf, geo_points_data_police_df, geo_points_data_clinics_df,\n geo_points_data_courts_df, geo_points_data_shelters_df, outfile, basic_map)\n\n print(\"we are done here\")\n return map", "def get_su2_results(cpacs_path,cpacs_out_path,wkdir):\n\n tixi = cpsf.open_tixi(cpacs_path)\n\n # TODO Check and reactivate that\n # save_timestamp(tixi,SU2_XPATH) <-- ceaf.replace by get get_execution_date()\n\n if not os.path.exists(wkdir):\n raise OSError('The working directory : ' + wkdir + 'does not exit!')\n\n os.chdir(wkdir)\n dir_list = os.listdir(wkdir)\n\n # Get and save Wetted area\n wetted_area = get_wetted_area(wkdir)\n\n wetted_area_xpath = '/cpacs/toolspecific/CEASIOMpy/geometry/analysis/wettedArea'\n cpsf.create_branch(tixi, wetted_area_xpath)\n\n tixi.updateDoubleElement(wetted_area_xpath,wetted_area,'%g')\n\n\n # Save aeroPerformanceMap\n su2_aeromap_xpath = SU2_XPATH + '/aeroMapUID'\n aeromap_uid = cpsf.get_value(tixi,su2_aeromap_xpath)\n\n # Check if loads shoud be extracted\n check_extract_loads_xpath = SU2_XPATH + '/results/extractLoads'\n check_extract_loads = cpsf.get_value_or_default(tixi, check_extract_loads_xpath,False)\n\n # Create an oject to store the aerodynamic coefficients\n apmf.check_aeromap(tixi,aeromap_uid)\n\n # TODO: create a function to earase previous results...\n Coef2 = apmf.get_aeromap(tixi, aeromap_uid)\n Coef = apmf.AeroCoefficient()\n Coef.alt = Coef2.alt\n Coef.mach = Coef2.mach\n Coef.aoa = Coef2.aoa\n Coef.aos = Coef2.aos\n\n case_dir_list = [dir for dir in dir_list if 'Case' in dir]\n\n for config_dir in sorted(case_dir_list):\n if os.path.isdir(config_dir):\n os.chdir(config_dir)\n force_file_name = 'forces_breakdown.dat'\n if not os.path.isfile(force_file_name):\n raise OSError('No result force file have been found!')\n\n fixed_cl_xpath = SU2_XPATH + '/fixedCL'\n fixed_cl = cpsf.get_value_or_default(tixi,fixed_cl_xpath,'NO')\n\n if fixed_cl == 'YES':\n force_file_name = 'forces_breakdown.dat'\n cl_cd, aoa = get_efficiency_and_aoa(force_file_name)\n\n # Save the AoA found during the fixed CL calculation\n Coef.aoa = [aoa]\n apmf.save_parameters(tixi,aeromap_uid,Coef)\n\n # Save cl/cd found during the fixed CL calculation\n # TODO: maybe save cl/cd somewhere else\n lDRatio_xpath = '/cpacs/toolspecific/CEASIOMpy/ranges/lDRatio'\n cpsf.create_branch(tixi, lDRatio_xpath)\n tixi.updateDoubleElement(lDRatio_xpath,cl_cd,'%g')\n\n\n # Read result file\n with open(force_file_name) as f:\n for line in f.readlines():\n if 'Total CL:' in line:\n cl = float(line.split(':')[1].split('|')[0])\n if 'Total CD:' in line:\n cd = float(line.split(':')[1].split('|')[0])\n if 'Total CSF:' in line:\n cs = float(line.split(':')[1].split('|')[0])\n # TODO: Check which axis name corespond to waht: cml, cmd, cms\n if 'Total CMx:' in line:\n cmd = float(line.split(':')[1].split('|')[0])\n if 'Total CMy:' in line:\n cms = float(line.split(':')[1].split('|')[0])\n if 'Total CMz:' in line:\n cml = float(line.split(':')[1].split('|')[0])\n if ('Free-stream velocity' in line and 'm/s' in line):\n velocity = float(line.split(' ')[7])\n\n # Damping derivatives\n rotation_rate_xpath = SU2_XPATH + '/options/rotationRate'\n rotation_rate = cpsf.get_value_or_default(tixi,rotation_rate_xpath,1.0)\n ref_xpath = '/cpacs/vehicles/aircraft/model/reference'\n ref_len = cpsf.get_value(tixi,ref_xpath + '/length')\n adim_rot_rate = rotation_rate * ref_len / velocity\n\n if '_dp' in config_dir:\n dcl = (cl-Coef.cl[-1])/adim_rot_rate\n dcd = (cd-Coef.cd[-1])/adim_rot_rate\n dcs = (cs-Coef.cs[-1])/adim_rot_rate\n dcml = (cml-Coef.cml[-1])/adim_rot_rate\n dcmd = (cmd-Coef.cmd[-1])/adim_rot_rate\n dcms = (cms-Coef.cms[-1])/adim_rot_rate\n Coef.damping_derivatives.add_damping_der_coef(dcl,dcd,dcs,dcml,dcmd,dcms,'_dp')\n\n elif '_dq' in config_dir:\n dcl = (cl-Coef.cl[-1])/adim_rot_rate\n dcd = (cd-Coef.cd[-1])/adim_rot_rate\n dcs = (cs-Coef.cs[-1])/adim_rot_rate\n dcml = (cml-Coef.cml[-1])/adim_rot_rate\n dcmd = (cmd-Coef.cmd[-1])/adim_rot_rate\n dcms = (cms-Coef.cms[-1])/adim_rot_rate\n Coef.damping_derivatives.add_damping_der_coef(dcl,dcd,dcs,dcml,dcmd,dcms,'_dq')\n\n elif '_dr' in config_dir:\n dcl = (cl-Coef.cl[-1])/adim_rot_rate\n dcd = (cd-Coef.cd[-1])/adim_rot_rate\n dcs = (cs-Coef.cs[-1])/adim_rot_rate\n dcml = (cml-Coef.cml[-1])/adim_rot_rate\n dcmd = (cmd-Coef.cmd[-1])/adim_rot_rate\n dcms = (cms-Coef.cms[-1])/adim_rot_rate\n Coef.damping_derivatives.add_damping_der_coef(dcl,dcd,dcs,dcml,dcmd,dcms,'_dr')\n\n elif '_TED_' in config_dir:\n\n config_dir_split = config_dir.split('_')\n ted_idx = config_dir_split.index('TED')\n ted_uid = config_dir_split[ted_idx+1]\n defl_angle = float(config_dir.split('_defl')[1])\n\n try:\n print(Coef.IncrMap.dcl)\n except AttributeError:\n Coef.IncrMap = apmf.IncrementMap(ted_uid)\n\n # TODO: still in development, for now only 1 ted and 1 defl\n print(ted_uid,defl_angle)\n\n dcl = (cl-Coef.cl[-1])\n dcd = (cd-Coef.cd[-1])\n dcs = (cs-Coef.cs[-1])\n dcml = (cml-Coef.cml[-1])\n dcmd = (cmd-Coef.cmd[-1])\n dcms = (cms-Coef.cms[-1])\n\n control_parameter = -1\n\n Coef.IncrMap.add_cs_coef(dcl,dcd,dcs,dcml,dcmd,dcms,ted_uid,control_parameter)\n\n else: # No damping derivative or control surfaces case\n Coef.add_coefficients(cl,cd,cs,cml,cmd,cms)\n\n if check_extract_loads:\n results_files_dir = os.path.join(wkdir,config_dir)\n extract_loads(results_files_dir)\n\n os.chdir(wkdir)\n\n # Save object Coef in the CPACS file\n apmf.save_coefficients(tixi,aeromap_uid,Coef)\n\n cpsf.close_tixi(tixi,cpacs_out_path)", "def get_allWGS_runInfo_fromSRA_forDivision(fileprefix, taxID_division, reference_genome, taxIDs_to_exclude=set(), replace=False, min_coverage=30):\n\n SRA_runInfo_df_file = \"%s.SRA_runInfo_df.py\"%fileprefix\n\n if file_is_empty(SRA_runInfo_df_file) or replace is True:\n print_if_verbose(\"Getting WGS for %i\"%taxID_division)\n\n # define the WGS fastq filters\n WGS_filters = '(\"biomol dna\"[Properties] AND \"strategy wgs\"[Properties] AND \"library layout paired\"[Properties] AND \"platform illumina\"[Properties] AND \"strategy wgs\"[Properties] OR \"strategy wga\"[Properties] OR \"strategy wcs\"[Properties] OR \"strategy clone\"[Properties] OR \"strategy finishing\"[Properties] OR \"strategy validation\"[Properties])'\n\n # define the esearch query\n esearch_query = \"(txid%i[Organism:exp]) AND %s\"%(taxID_division, WGS_filters) \n\n # add the taxIDs_to_exclude \n if len(taxIDs_to_exclude)>0: esearch_query += \" NOT (%s)\"%(\" OR \".join([\"(txid%i[Organism:exp])\"%ID for ID in taxIDs_to_exclude]))\n\n print_if_verbose(\"This is the esearch query (you can check it against the SRA):\\n\\n %s \\n\\n\"%esearch_query)\n\n # get esearch\n esearch_outfile = \"%s.esearch_output.txt\"%fileprefix\n esearch_stderr = \"%s.stderr\"%esearch_outfile\n efetch_outfile = \"%s.efetch_output.txt\"%fileprefix\n efetch_stderr = \"%s.stderr\"%efetch_outfile\n\n columns_efetch = \"Run,ReleaseDate,LoadDate,spots,bases,spots_with_mates,avgLength,size_MB,AssemblyName,download_path,Experiment,LibraryName,LibraryStrategy,LibrarySelection,LibrarySource,LibraryLayout,InsertSize,InsertDev,Platform,Model,SRAStudy,BioProject,Study_Pubmed_id,ProjectID,Sample,BioSample,SampleType,TaxID,ScientificName,SampleName,g1k_pop_code,source,g1k_analysis_group,Subject_ID,Sex,Disease,Tumor,Affection_Status,Analyte_Type,Histological_Type,Body_Site,CenterName,Submission,dbgap_study_accession,Consent,RunHash,ReadHash\".split(\",\")\n\n # get the esearch\n print_if_verbose(\"running esearch. The stderr is in %s\"%esearch_stderr)\n run_cmd(\"%s -db sra -query '%s' > %s 2>%s\"%(esearch, esearch_query, esearch_outfile, esearch_stderr))\n remove_file(esearch_stderr)\n\n # get the number of rows\n nresults = [int(l.split(\"<Count>\")[1].split(\"<\")[0]) for l in open(esearch_outfile, \"r\").readlines() if \"<Count>\" in l and \"</Count>\" in l][0]\n print_if_verbose(\"There are %i results in esearch\"%nresults)\n\n if nresults==0: SRA_runInfo_df = pd.DataFrame(columns=columns_efetch)\n else:\n\n # run efetch\n print_if_verbose(\"running efetch. The stderr is in %s\"%efetch_stderr)\n run_cmd(\"cat %s | %s -db sra --format runinfo | egrep -v '^Run' | egrep 'https' > %s 2>%s\"%(esearch_outfile, efetch, efetch_outfile, efetch_stderr))\n remove_file(efetch_stderr)\n\n # get into df\n SRA_runInfo_df = pd.read_csv(efetch_outfile, sep=\",\", header=None, names=columns_efetch)\n\n save_object(SRA_runInfo_df, SRA_runInfo_df_file)\n\n else: SRA_runInfo_df = load_object(SRA_runInfo_df_file)\n\n # return if empty \n if len(SRA_runInfo_df)==0: return SRA_runInfo_df\n\n # filter out the undesired taxIDs\n SRA_runInfo_df = SRA_runInfo_df[~SRA_runInfo_df.TaxID.isin(taxIDs_to_exclude)]\n\n # return if empty \n if len(SRA_runInfo_df)==0: return SRA_runInfo_df\n\n # define the expected coverage\n length_genome = sum(get_chr_to_len(reference_genome).values())\n SRA_runInfo_df[\"expected_coverage\"] = SRA_runInfo_df.apply(lambda r: (r[\"spots_with_mates\"]*r[\"avgLength\"])/length_genome,axis=1)\n\n # plot the number of spots\n filename = \"%s.distribution_parameters.pdf\"%fileprefix\n if file_is_empty(filename):\n\n fig = plt.figure(figsize=(5,13))\n for I, field in enumerate([\"spots\", \"spots_with_mates\", \"avgLength\", \"InsertSize\", \"size_MB\", \"expected_coverage\"]):\n ax = plt.subplot(6, 1, I+1)\n sns.distplot(SRA_runInfo_df[field], kde=False, rug=True)\n ax.set_xlabel(field)\n\n fig.tight_layout() # otherwise the right y-label is slightly \n fig.savefig(filename, bbox_inches='tight');\n plt.close(fig)\n\n # keep only those that have at least a coverage of min_coverage \n SRA_runInfo_df = SRA_runInfo_df[SRA_runInfo_df[\"expected_coverage\"]>=min_coverage]\n\n print_if_verbose(\"There are %i SRRs ready to use with at least %ix coverage\"%(len(SRA_runInfo_df), min_coverage))\n\n return SRA_runInfo_df", "def main():\n\n\tname = \"SS_pyNN_closedLoop_webots\"\n\teesAmplitudes = [\"1\",\"240\"]\n\teesFrequency = \"40\"\n\tdelay = \"2\"\n\tweights_1 = np.linspace(0.05,0.1,5)\n\tweights_2 = np.linspace(0.01,0.05,5)\n\tweights_3 = np.linspace(0.01,0.1,10)\n\n\tw4 = -0.00145\n\tw5 = -0.0045\n\n\tsimTime = \"3000\"\n\tnSim = len(weights_1)*len(weights_2)*len(weights_3)*len(eesAmplitudes)\n\tcount=0.\n\tpercLastPrint=0.\n\tprintPeriod = 0.05\n\n\tfor w1 in weights_1:\n\t\tfor w2 in weights_2:\n\t\t\tfor w3 in weights_3:\n\t\t\t\tfor eesAmplitude in eesAmplitudes:\n\t\t\t\t\tresultName = name+\"_eesAmp_%d_w1_%f_w2_%f_w3_%f_w4_%f_w5_%f\" % (int(eesAmplitude),w1,w2,w3,w4,w5)\n\t\t\t\t\tresultFile = gt.find(\"*\"+resultName+\"*.p\",pathToResults)\n\t\t\t\t\tif not resultFile:\n\t\t\t\t\t\tinputFile = \"generatedStructures/ss_cl_w1_%f_w2_%f_w3_%f_w4_%f_w5_%f.txt\" % (w1,w2,w3,w4,w5)\n\t\t\t\t\t\ttls.modify_network_structure(\"templateClosedLoop2Dof.txt\",inputFile,delay,[w1,w2,w3,w4,w5])\n\t\t\t\t\t\tprogram = ['python','./scripts/runClosedLoopSim.py',eesFrequency,eesAmplitude,\"hanging\",\"mouse\",simTime,resultName,inputFile]\n\t\t\t\t\t\tgt.run_subprocess(program)\n\n\t\t\t\t\tcount+=1\n\t\t\t\t\tif count/nSim-percLastPrint>=printPeriod:\n\t\t\t\t\t\tpercLastPrint=count/nSim\n\t\t\t\t\t\tprint str(round(count/nSim*100))+\"% of simulations performed...\"", "def speculate(t=0): \n global G_C,G_T,n_pos_before, x_factor, n_latches_before, last_verify_time, trim_allowed, n_pos_before\n global t_init, j_last, sec_sw, A_name, B_name, sec_options, po_map, sweep_time, sims, cex_list, n_pos_proved,ifpord1\n global last_cx, total_spec_refine_time, skip_spec\n## print 'sec_options = %s'%sec_options\n if skip_spec:\n return Undecided_no_reduction\n add_trace('speculate')\n if t > 0:\n total_spec_refine_time = t\n abc('scl') #make sure no dangling flops\n abc('orpos')\n last_cx = 0\n ifpord1 = 1\n initial_po_size = last_srm_po_size = n_pos()\n initial_sizes = [n_pis(),n_pos(),n_latches(),n_ands()]\n if sec_sw:\n print 'A_name = %s, B_name = %s, f_name = %s, sec_options = %s'%(A_name, B_name, f_name, sec_options)\n#temp for yen-sheng's examples\n## elif n_ands() > 40000 and sec_options == '':\n#### add_trace('sec options g')\n## sec_options = 'g'\n## print 'sec_options set to \"g\"'\n#### add_trace('sec_options =\"g\"')\n \n def refine_with_cex():\n \"\"\"Refines the gore file to reflect equivalences that go away because of cex\"\"\"\n global f_name\n abc('write_status %s_before_refine.status'%f_name)\n abc('&r -s %s_gore.aig; &resim -m'%f_name)\n## run_command('&ps')\n## cex_stats()\n filter(sec_options)\n run_command('&w %s_gore.aig'%f_name)\n return\n\n def refine_without_cex(L=[]):\n \"\"\"removes the POs in the current SRM in the list L. Alters the equivalence classes in the\n gore file accordingly.\n \"\"\"\n global f_name\n if L == []:\n return\n print 'Entered refine_without_cex'\n abc('write_status %s_before_refine.status'%f_name)\n create_abc_array(L)\n print 'wrote array'\n abc('&r -s %s_gore.aig; &equiv_filter'%f_name)\n print 'filtered gore using L'\n filter(sec_options)\n print 'filtered with %s'%sec_options\n run_command('&w %s_gore.aig'%f_name)\n return\n \n def set_cex(lst):\n \"\"\" assumes only onecex in lst for now\"\"\"\n for j in range(len(lst)):\n cx = lst[j]\n if cx == None:\n continue\n else:\n cex_put(cx)\n break\n \n def retry(t):\n add_trace('retrying')\n print 'retrying winner cex which did not refine'\n abc('r %s_gsrm_before.aig'%f_name) #restore previous gsrm\n abc('w %s_beforerpm.aig'%f_name)\n rep_change = reparam() #must be paired with reconcile below if cex\n if rep_change:\n add_trace('reparam')\n abc('w %s_afterrpm.aig'%f_name)\n if last_winner == 'RareSim':\n simulate2(t)\n elif last_winner == 'PDR':\n pdr(t)\n elif last_winner == 'BMC':\n bmc(t)\n elif last_winner == 'INTRP':\n intrp(t)\n elif last_winner == 'PDRM':\n pdrm(t)\n elif last_winner == 'BMC3':\n bmc3(t)\n elif last_winner == 'PDR_sd':\n pdrseed(t)\n elif last_winner == 'PDRM_sd':\n pdrmm(t)\n elif last_winner == 'INTRPm':\n intrpm(t)\n elif last_winner == 'REACHY':\n reachy(t)\n elif last_winner == 'BMC_J':\n bmc_j(t)\n elif last_winner == 'PDRa':\n pdra(t)\n else:\n reconcile(rep_change)\n return False\n reconcile(rep_change)\n if not is_sat():\n return False\n abc('&r -s %s_gore_before.aig ;&w %s_gore.aig'%(f_name,f_name)) #restore old gore file\n return True\n \n def generate_srm():\n \"\"\"generates a speculated reduced model (srm) from the gore file\"\"\"\n global f_name, po_map, sec_sw, A_name, B_name, sec_options, n_pos_proved\n## print 'Generating'\n pos = n_pos()\n ab = n_ands()\n abc('w %s_oldsrm.aig'%f_name) #save for later purposes\n if sec_sw:\n run_command('&r -s %s_gore.aig; &srm2 -%s %s.aig %s.aig; r gsrm.aig; w %s_gsrm.aig'%(f_name,sec_options,A_name,B_name,f_name))\n else:\n abc('&r -s %s_gore.aig; &srm -A %s_gsrm.aig ; r %s_gsrm.aig'%(f_name,f_name,f_name)) #do we still need to write the gsrm file\n## ps()\n po_map = range(n_pos())\n ps()\n n_pos_proved = 0\n return 'OK'\n\n n_pos_before = n_pos()\n n_pos_proved = 0\n n_latches_before = n_latches() \n set_globals()\n## t = max(1,.5*G_T)#irrelevant\n## r = max(1,int(t))\n t = 1000\n j_last = 0\n J = slps+sims+pdrs+bmcs+intrps\n J = modify_methods(J,1)\n print 'sec_options = %s'%sec_options \n funcs = [eval('(pyabc_split.defer(initial_speculate)(\"%s\"))'%sec_options)]\n funcs = create_funcs(J,10000)+funcs #want other functins to run until initial speculate stops\n mtds = sublist(methods,J) + ['initial_speculate'] #important that initial_speculate goes last\n print mtds\n res = fork_last(funcs,mtds) #break when last initial_speculate ends\n print 'init_spec return = ',\n print res\n if res == None:\n add_trace('de_speculate')\n return Undecided_no_reduction\n if res[0] == 'UNSAT':\n add_trace('UNSAT by filter \"%s\" inside initial_speculate'%res[1])\n return Unsat\n if res[0] == 'UNDECIDED' or res[0] == None:\n add_trace('de_speculate')\n return Undecided_no_reduction # even one of the initial speculations too hard\n if res[1] in ['f','g','']:\n sec_options = res[1]\n add_trace('sec_options = %s'%sec_options)\n add_trace('Number of POs: %d'%n_pos())\n## ps()\n if not res[0] == None: # None indicates all srms were SAT and need to be refined.\n if is_unsat():\n return Unsat\n if is_sat():\n return Sat_true\n if n_pos_before == n_pos():\n print 'No new outputs. Quitting speculate'\n add_trace('de_speculate')\n return Undecided_no_reduction # return result is unknown\n if n_eff_pos() > 1999:\n print 'Too many POs'\n add_trace('de_speculate')\n return Undecided_no_reduction\n abc('r %s_gsrm.aig'%f_name)\n print 'Initial speculation: ',\n ps()\n abc('w %s_initial_gsrm.aig'%f_name)\n if n_eff_pos() > max_pos:\n print 'Too many new outputs. Quitting speculate'\n add_trace('de_speculate')\n return Undecided_no_reduction # return result is unknown\n if n_pos() <= n_pos_before + 2:\n print 'Too few new outputs. Quitting speculate'\n add_trace('de_speculate')\n return Undecided_no_reduction # return result is unknown\n if n_latches() > .9*n_latches_before:\n print 'not enough reduction in SRM'\n add_trace('de_speculate')\n return Undecided_no_reduction\n if n_latches() == 0:\n return check_sat() \n if use_pms: #\n p,q,r=par_multi_sat(0)\n q = indices(r,1)\n print sumsize(r)\n tot = len(r)\n ud = count_less(r,0) #undecided L=-1 means undecided, L=0 means unsat, L=1 means sat\n us = count_less(r,1)-ud #unsat\n sa = count_less(r,2) - (ud+us) #sat\n if sa > .5*tot or sa >.3*ud:\n print 'too many POs are already SAT'\n add_trace('de_speculate')\n return Undecided_no_reduction\n if sec_options == 'l' and sec_sw:\n sec_options = 'ab' #finished with initial speculate with the 'l' option\n print \"sec_options set to 'ab'\"\n elif sec_options == 'l':\n sec_options = 'f'\n print \"sec_options set to 'f'\"\n po_map = range(n_pos()) #we need this because the initial_speculate is done in parallel and po_map is not passed back.\n npi = n_pis()\n set_globals()\n if is_sat():\n return Sat_true\n simp_sw = init = True\n add_trace('speculative refinement')\n print '\\nIterating speculation refinement'\n sims_old = sims\n sims = sims[:1] \n## J = slps+sims+pdrs+intrps+bmcs\n J = slps+sims+pdrs+bmcs #changed for hwmcc15\n J = modify_methods(J)\n print 'Parallel refinement methods = ',\n print sublist(methods,J)\n t = max(50,max(1,2*G_T))\n last_verify_time = t\n ### temp\n last_verify_time = total_spec_refine_time\n ###\n print 'Verify time set to %d'%last_verify_time\n reg_verify = True\n ref_time = time.time()\n sweep_time = 2\n ifpord1=1\n par_verify = re_try = False\n## total_spec_refine_time = 150\n while True: ##################### refinement loop\n set_globals()\n yy = time.time()\n time_used = (yy-ref_time)\n print 'Time_used = %0.2f'%time_used\n if time_used > total_spec_refine_time:\n print 'Allotted speculation refinement time is exceeded'\n add_trace('de_speculate')\n return Undecided_no_reduction\n if n_latches() > .9 * n_latches_before:\n print 'Not enough reduction in flop count in SRM'\n add_trace('de_speculate')\n return Undecided_no_reduction\n if not init:\n abc('r %s_gsrm.aig'%f_name) #this is done only to set the size of the previous gsrm.\n abc('w %s_gsrm_before.aig'%f_name)\n set_size()\n result = generate_srm()\n if n_pos() <= n_pos_before + 1: #heuristic that if only have one equivalence, then not worth it\n abc('r %s.aig'%f_name) #revert to previous aig\n sims = sims_old\n print 'UNDECIDED'\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n add_trace('de_speculate')\n return Undecided_no_reduction\n if n_latches() > 9.*n_latches_before:\n print 'Allotted speculation refinement time is exceeded'\n add_trace('de_speculate')\n return Undecided_no_reduction\n last_srm_po_size = n_pos()\n yy = time.time()\n # if the size of the gsrm did not change after generating a new gsrm\n # and if the cex is valid for the gsrm, then the only way this can happen is if\n # the cex_po is an original one.\n if check_size(): #same size before and after\n if check_cex(): #valid cex failed to refine possibly\n if 0 <= cex_po() and cex_po() < (n_pos_before - n_pos_proved): #original PO\n print 'Found cex in original output number = %d'%cex_po()\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n return Sat_true\n elif check_same_gsrm(f_name): #if two gsrms are same, then failed to refine\n print 'CEX failed to refine'\n add_trace('de_speculate')\n return Error\n else:\n print 'not a valid cex'\n print 'Last winner = %s'%last_winner\n print 're_try = %d'%re_try\n if re_try:\n add_trace('de_speculate')\n return Error #abort speculation\n re_try = True\n else:\n re_try = False # just got a valid refinement so reset.\n if n_latches() == 0:\n print 'Number of latches reduced to 0'\n print 'CEX refined incorrectly'\n abc('r %s.aig'%f_name) #revert to previous aig\n sims = sims_old\n add_trace('de_speculate')\n return Error\n init = False # make it so that next time it is not the first time through\n if not t == last_verify_time: # heuristic that if increased last verify time,\n # then try pord_all \n t = last_verify_time\n if reg_verify:\n t_init = (time.time() - yy)/2 #start poor man's concurrency at last cex fime found\n t_init = min(10,t_init)\n t = last_verify_time\n print 'Verify time set to %d'%t\n if not re_try:\n## abc('w %s_beforerpm.aig'%f_name)\n## rep_change = reparam() #must be paired with reconcile below if cex\n#### if rep_change:\n#### add_trace('reparam')\n## abc('w %s_afterrpm.aig'%f_name)\n rep_change = False #TEMP\n if reg_verify:\n if par_verify:\n S,L_sat_POs,s = par_multi_sat(120)\n L_sat_POs = indices(s,1)\n## L_sat_POs = L[1]\n L=[]\n for j in range(len(L_sat_POs)): #eliminate any of the original POs\n if L_sat_POs[j] >= (n_pos_before-n_pos_proved):\n L=L+[L_sat_POs[j]]\n L_sat_POs = L\n print L\n if not L_sat_POs == []:\n ress = [1,[['multi_sat']]]\n add_trace(['multi_sat'])\n else:\n reg_verify = False\n ress = pord_1_2(t)\n add_trace(ress[1])\n else:\n ttt = time.time() #find time it takes to find a cex\n ress = verify(J,t)\n t_last_verify = time.time() - ttt\n else:\n ress = pord_1_2(t)\n## print ress\n add_trace(ress[1])\n result = ress[0]\n## add_trace(ress[1])\n else:\n if not retry(100):\n add_trace('de_speculate')\n return Error\n result = get_status()\n## print result\n if result == Unsat:\n add_trace('UNSAT by %s'%ress[1])\n print 'UNSAT'\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n return Unsat\n if result < Unsat:\n abc('&r -s %s_gore.aig;&w %s_gore_before.aig'%(f_name,f_name)) #we are making sure that none of the original POs fail\n if par_verify:\n refine_without_cex(L_sat_POs)\n print 'refining without cex done'\n continue\n if not reg_verify:\n set_cex(cex_list)\n## if not re_try:\n#### rec = reconcile(rep_change) #end of pairing with reparam()TEMP\n#### if rec == 'error':\n#### add_trace('de_speculate')\n#### return Error\n## (npi == n_cex_pis()),'ERROR: #pi = %d, #cex_pi = %d'%(npi,n_cex_pis())\n abc('&r -s %s_gore.aig;&w %s_gore_before.aig'%(f_name,f_name)) #we are making sure that none of the original POs fail\n if reg_verify:\n PO = set_cex_po(0) #testing the regular space\n else:\n abc('&r -s %s_gsrm.aig'%f_name)\n PO = set_cex_po(1) # test against the &space.\n print 'cex_PO is %d, '%PO,\n if (-1 < PO and PO < (n_pos_before-n_pos_proved)):\n print 'Found cex in original output %d'%cex_po()\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n return Sat_true\n if PO == -1:\n add_trace('de_speculate')\n return Error\n refine_with_cex() #change the number of equivalences\n if not par_verify and t_last_verify > 2500:\n par_verify = True #switch to finding many POs at a time\n continue\n elif (is_unsat() or n_pos() == 0):\n print 'UNSAT'\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n return Unsat\n else: #if undecided, record last verification time\n print 'Refinement returned undecided in %d sec.'%t\n last_verify_time = t\n #########################added\n if reg_verify: #try one last time with parallel POs cex detection (find_cex_par) if not already tried\n print 'aig size after initial refinement = ',\n ps() \n## abc('r %s_beforerpm.aig'%f_name) # to continue refinement, need to restore original\n## print 'beforermp aig size = ',\n## ps()\n t_init = min(last_verify_time,(time.time() - yy)/2) #start poor man's concurrency at last cex fime found\n t_init = min(10,t_init)\n reg_verify = False\n t = last_verify_time # = 2*last_verify_time\n abc('w %s_beforerpm.aig'%f_name)\n rep_change = reparam() #must be paired with reconcile()below\n abc('w %s_afterrpm.aig'%f_name)\n print 'entering pord_1_2 ,',\n ps()\n ress = pord_1_2(t) #main call to verification\n print ress\n result = ress[0]\n add_trace(ress[1])\n if result == Unsat:\n print 'UNSAT'\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n return Unsat\n if is_sat() or result == Sat:\n## assert result == get_status(),'result: %d, status: %d'%(result,get_status())\n print 'result: %d, status: %d'%(result,get_status())\n set_cex(cex_list)\n rec = reconcile(rep_change)\n if rec == 'error':\n add_trace('de_speculate')\n return Error\n abc('&r -s %s_gsrm.aig'%f_name)\n PO = set_cex_po(1) #testing the & space\n if (-1 < PO and PO < (n_pos_before-n_pos_proved)):\n print 'Found cex in original output %d'%cex_po()\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n return Sat_true\n if PO == -1:\n add_trace('de_speculate')\n return Error\n refine_with_cex() #change the number of equivalences\n continue\n else: #if undecided, record last verification time\n last_verify_time = t\n print 'UNDECIDED'\n break\n ################### added\n else:\n break\n sims = sims_old\n print 'UNDECIDED'\n print 'Refinement time = %0.2f'%(time.time() - ref_time)\n## if last_srm_po_size == initial_po_size: #essentially nothing happened. last_srm_po_size will be # POs in last srm.\n if initial_sizes == [n_pis(),n_pos(),n_latches(),n_ands()]:\n abc('r %s.aig'%f_name)\n add_trace('de_speculate')\n return Undecided_no_reduction #thus do not write spec file\n else: #file was changed, so some speculation happened. If we find a cex later, need to know this.\n write_file('spec')\n return Undecided_reduction", "def main():\n\n ocp = None\n for initial_guess in InterpolationType:\n print(f\"Solving problem using {initial_guess} initial guess\")\n ocp = prepare_ocp(\n \"models/cube.bioMod\", n_shooting=30, final_time=2, random_init=False, initial_guess=initial_guess\n )\n\n sol = ocp.solve()\n print(\"\\n\")\n\n # Print the last solution\n sol.animate()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a git diff either from stdin or against a base.
def getDiff(base: Union[str, bool] = '') -> Iterable[str]: if type(base) is bool and base is True: if not sys.stdin.isatty(): return (line.rstrip('\n').rstrip('\r') for line in sys.stdin.readlines()) elif type(base) is str: cmd = ['git', 'diff'] if base: cmd += [str(base)] return run(cmd) return []
[ "def diff(self, base=\"commit\"):\n if base == \"commit\":\n base = None\n if base == \"dependencies\":\n branch = self.git.current_branch()\n try:\n self.gather(self.trac.dependencies())\n self.git.diff(\"%s..%s\"%(HEAD,branch))\n finally:\n self.git.checkout(branch)\n else:\n self.git.execute(\"diff\", base)", "def git_diff(*args):\n command = (['git', '--no-pager', 'diff'] + list(args) + [\n '--', 'requirements.txt', 'misc/requirements/requirements-*.txt'])\n proc = subprocess.run(command,\n stdout=subprocess.PIPE,\n encoding='utf-8',\n check=True)\n return proc.stdout.splitlines()", "def gitdiff():\n if len(sys.argv) < 2:\n _usage_diffgit()\n sys.exit(1)\n\n #diffprog = sys.argv[1]\n filenames = sys.argv[1:]\n old_files = []\n for filename in filenames:\n failure, output = commands.getstatusoutput('git log %s' % filename)\n if not failure:\n commits = re.findall(r'^commit\\s+(.+)$', output,\n flags=re.MULTILINE)\n dates = re.findall(r'^Date:\\s+(.+)\\d\\d:\\d\\d:\\d\\d .+$', output,\n flags=re.MULTILINE)\n system('git checkout %s %s' % (commits[1], filename))\n old_filename = '__' + dates[1].replace(' ', '_') + filename\n shutil.copy(filename, old_filename)\n system('git checkout %s %s' % (commits[0], filename))\n old_files.append(old_filename)\n print 'doconce diff', old_filename, filename\n #pydiff(filenames, old_files)", "def gitext_diff(external):\n from git_externals import iter_externals\n for _ in iter_externals(external):\n click.echo(git('diff'))", "def generate_commit_patch(self, new_commit_hash, prev_commit_hash):\n\n if self.git_diff is None:\n std_out, std_err = self._git_diff(new_commit_hash, prev_commit_hash)\n else:\n # we cached the \"git diff\" command. use the cached version\n std_out = self.git_diff[0]\n\n return std_out", "def run_diff(self, src, dst, deref=False):\n deref_str = \"\"\n if not deref:\n deref_str = \"--no-dereference\"\n\n cmd = \"diff -r {} '{}' '{}'\".format(\n deref_str, src, dst)\n self.execute_cmd(cmd)", "def git_diff(filepath, since):\n html_diff = None\n commits = git_commits(filepath, since)\n if commits:\n cmd = ('git', '--no-pager', 'diff', commits[-1]+'^', '--',\n filepath)\n stdout, stderr = execute(cmd)\n\n if stdout:\n html_diff = highlight(stdout, lexers.DiffLexer(),\n HtmlFormatter())\n\n # print(' '.join(cmd))\n # print(diff)\n # print('\\n')\n\n return html_diff", "def main_git():\n proc = subprocess.Popen([\"git\", \"diff\", \"scala\"], stdout=subprocess.PIPE)\n out = proc.communicate()[0].decode()\n\n RE = re.compile(\"([-+])Subproject commit (.*)\")\n frm = None\n to = None\n for mode, commit in RE.findall(out):\n if mode == \"-\":\n frm = commit\n elif mode == \"+\":\n to = commit\n else:\n raise ValueError(\"Unkown mode: %s\" % mode)\n if frm is None or to is None:\n raise ValueError(\"Cannot calculate diff from %s to %s\" % (frm, to))\n\n if \"dirty\" in to:\n to = []\n else:\n to = [to]\n proc = subprocess.Popen([\"git\", \"-C\", \"scala\", \"diff\", \"-U1\", frm] + to,\n stdout=subprocess.PIPE)\n diff = proc.communicate()[0].decode()\n fname = None\n\n for path, start1, lines1, start2, lines2 in DIFFRE.findall(diff):\n if path:\n fname = path\n else:\n # We already applied previous changes, so the new start value\n # (that is, start2) is the one we are interested in.\n apply_hunk(\"scala/\" + fname, int(start2),\n int(start2) + int(lines1),\n int(start2) + int(lines2))", "def get_git_diff(upstream_branch: str) -> str:\n\n subprocess.run(shlex.split(f\"git fetch origin {upstream_branch}\"), check=True)\n completed_process = subprocess.run(\n shlex.split(f\"git diff origin/{upstream_branch} --name-only\"),\n check=True,\n stdout=subprocess.PIPE,\n )\n return completed_process.stdout.decode(\"utf-8\")", "def do_diff(self, cmd, repository_info=None):\n diff = execute(cmd, split_lines=True)\n diff = self.handle_renames(diff)\n diff = self.convert_to_absolute_paths(diff, repository_info)\n\n return ''.join(diff)", "def test_with_multi_commit_diff(self):\n reader = DiffXReader(io.BytesIO(\n b'#diffx: encoding=utf-8, version=1.0\\n'\n b'#.change:\\n'\n b'#..preamble: indent=4, length=49, mimetype=text/markdown\\n'\n b' Summary of the _first_ commit in the series.\\n'\n b'#..meta: format=json, length=244\\n'\n b'{\\n'\n b' \"author\": \"Test User <test@example.com>\",\\n'\n b' \"committer\": \"Test User <test@example.com>\",\\n'\n b' \"committer date\": \"2021-06-02T13:12:06-07:00\",\\n'\n b' \"date\": \"2021-06-01T19:26:31-07:00\",\\n'\n b' \"id\": \"a25e7b28af5e3184946068f432122c68c1a30b23\"\\n'\n b'}\\n'\n b'#..file:\\n'\n b'#...meta: format=json, length=166\\n'\n b'{\\n'\n b' \"path\": \"file1\",\\n'\n b' \"revision\": {\\n'\n b' \"new\": \"eed8df7f1400a95cdf5a87ddb947e7d9c5a19cef\",\\n'\n b' \"old\": \"c8839177d1a5605aa60abe69db95c84183f0eebe\"\\n'\n b' }\\n'\n b'}\\n'\n b'#...diff: length=60\\n'\n b'--- /file1\\n'\n b'+++ /file1\\n'\n b'@@ -498,7 +498,7 @@\\n'\n b' ... diff content\\n'\n b'#.change:\\n'\n b'#..preamble: indent=4, length=52\\n'\n b' Summary of commit #2\\n'\n b'\\n'\n b' Here\\'s a description.\\n'\n b'#..meta: format=json, length=244\\n'\n b'{\\n'\n b' \"author\": \"Test User <test@example.com>\",\\n'\n b' \"committer\": \"Test User <test@example.com>\",\\n'\n b' \"committer date\": \"2021-06-02T19:46:25-07:00\",\\n'\n b' \"date\": \"2021-06-01T19:46:22-07:00\",\\n'\n b' \"id\": \"91127b687f583184144161f432222748c1a30b23\"\\n'\n b'}\\n'\n b'#..file:\\n'\n b'#...meta: format=json, length=166\\n'\n b'{\\n'\n b' \"path\": \"file2\",\\n'\n b' \"revision\": {\\n'\n b' \"new\": \"a2ccb0cb48383472345d41a32afde39a7e6a72dd\",\\n'\n b' \"old\": \"1b7af7f97076effed5db722afe31c993e6adbc78\"\\n'\n b' }\\n'\n b'}\\n'\n b'#...diff: length=80\\n'\n b'--- a/file2\\n'\n b'+++ b/file2\\n'\n b'@@ -66,7 +66,8 @@\\n'\n b' ... diff content for commit 2, file2\\n'\n b'#..file:\\n'\n b'#...meta: format=json, length=166\\n'\n b'{\\n'\n b' \"path\": \"file3\",\\n'\n b' \"revision\": {\\n'\n b' \"new\": \"0d4a0fb8d62b762a26e13591d06d93d79d61102f\",\\n'\n b' \"old\": \"be089b7197974703c83682088a068bef3422c6c2\"\\n'\n b' }\\n'\n b'}\\n'\n b'#...diff: length=82\\n'\n b'--- a/file3\\n'\n b'+++ b/file3\\n'\n b'@@ -258,7 +258,8 @@\\n'\n b' ... diff content for commit 2, file3\\n'\n ))\n\n self.assertEqual(list(reader), [\n {\n 'level': 0,\n 'line': 0,\n 'options': {\n 'encoding': 'utf-8',\n 'version': '1.0',\n },\n 'section': Section.MAIN,\n 'type': 'diffx',\n },\n {\n 'level': 1,\n 'line': 1,\n 'options': {},\n 'section': Section.CHANGE,\n 'type': 'change',\n },\n {\n 'level': 2,\n 'line': 2,\n 'options': {\n 'indent': 4,\n 'length': 49,\n 'mimetype': 'text/markdown',\n },\n 'section': Section.CHANGE_PREAMBLE,\n 'text': 'Summary of the _first_ commit in the series.\\n',\n 'type': 'preamble',\n },\n {\n 'level': 2,\n 'line': 4,\n 'metadata': {\n 'author': 'Test User <test@example.com>',\n 'committer': 'Test User <test@example.com>',\n 'committer date': '2021-06-02T13:12:06-07:00',\n 'date': '2021-06-01T19:26:31-07:00',\n 'id': 'a25e7b28af5e3184946068f432122c68c1a30b23',\n },\n 'options': {\n 'format': 'json',\n 'length': 244,\n },\n 'section': Section.CHANGE_META,\n 'type': 'meta',\n },\n {\n 'level': 2,\n 'line': 12,\n 'options': {},\n 'section': Section.FILE,\n 'type': 'file',\n },\n {\n 'level': 3,\n 'line': 13,\n 'metadata': {\n 'path': 'file1',\n 'revision': {\n 'new': 'eed8df7f1400a95cdf5a87ddb947e7d9c5a19cef',\n 'old': 'c8839177d1a5605aa60abe69db95c84183f0eebe',\n },\n },\n 'options': {\n 'format': 'json',\n 'length': 166,\n },\n 'section': Section.FILE_META,\n 'type': 'meta',\n },\n {\n 'level': 3,\n 'line': 21,\n 'options': {\n 'length': 60,\n },\n 'section': Section.FILE_DIFF,\n 'diff': (\n b'--- /file1\\n'\n b'+++ /file1\\n'\n b'@@ -498,7 +498,7 @@\\n'\n b' ... diff content\\n'\n ),\n 'type': 'diff',\n },\n {\n 'level': 1,\n 'line': 26,\n 'options': {},\n 'section': Section.CHANGE,\n 'type': 'change',\n },\n {\n 'level': 2,\n 'line': 27,\n 'options': {\n 'indent': 4,\n 'length': 52,\n },\n 'section': Section.CHANGE_PREAMBLE,\n 'text': (\n \"Summary of commit #2\\n\"\n \"\\n\"\n \"Here's a description.\\n\"\n ),\n 'type': 'preamble',\n },\n {\n 'level': 2,\n 'line': 31,\n 'metadata': {\n 'author': 'Test User <test@example.com>',\n 'committer': 'Test User <test@example.com>',\n 'committer date': '2021-06-02T19:46:25-07:00',\n 'date': '2021-06-01T19:46:22-07:00',\n 'id': '91127b687f583184144161f432222748c1a30b23',\n },\n 'options': {\n 'format': 'json',\n 'length': 244,\n },\n 'section': Section.CHANGE_META,\n 'type': 'meta',\n },\n {\n 'level': 2,\n 'line': 39,\n 'options': {},\n 'section': Section.FILE,\n 'type': 'file',\n },\n {\n 'level': 3,\n 'line': 40,\n 'metadata': {\n 'path': 'file2',\n 'revision': {\n 'new': 'a2ccb0cb48383472345d41a32afde39a7e6a72dd',\n 'old': '1b7af7f97076effed5db722afe31c993e6adbc78',\n },\n },\n 'options': {\n 'format': 'json',\n 'length': 166,\n },\n 'section': Section.FILE_META,\n 'type': 'meta',\n },\n {\n 'level': 3,\n 'line': 48,\n 'options': {\n 'length': 80,\n },\n 'section': Section.FILE_DIFF,\n 'diff': (\n b'--- a/file2\\n'\n b'+++ b/file2\\n'\n b'@@ -66,7 +66,8 @@\\n'\n b' ... diff content for commit 2, file2\\n'\n ),\n 'type': 'diff',\n },\n {\n 'level': 2,\n 'line': 53,\n 'options': {},\n 'section': Section.FILE,\n 'type': 'file',\n },\n {\n 'level': 3,\n 'line': 54,\n 'metadata': {\n 'path': 'file3',\n 'revision': {\n 'new': '0d4a0fb8d62b762a26e13591d06d93d79d61102f',\n 'old': 'be089b7197974703c83682088a068bef3422c6c2',\n },\n },\n 'options': {\n 'format': 'json',\n 'length': 166,\n },\n 'section': Section.FILE_META,\n 'type': 'meta',\n },\n {\n 'level': 3,\n 'line': 62,\n 'options': {\n 'length': 82,\n },\n 'section': Section.FILE_DIFF,\n 'diff': (\n b'--- a/file3\\n'\n b'+++ b/file3\\n'\n b'@@ -258,7 +258,8 @@\\n'\n b' ... diff content for commit 2, file3\\n'\n ),\n 'type': 'diff',\n },\n ])", "def diffed_files(a, b):\n git = Popen([\"git\", \"diff\", \"--name-only\", a, b], stdout=PIPE, stderr=PIPE)\n out, err = git.communicate()\n\n return out.split()", "def make_svn_diff(self, merge_base, diff_lines):\n rev = self._execute([self.git, 'svn', 'find-rev', merge_base]).strip()\n\n if not rev:\n return None\n\n diff_data = b''\n original_file = b''\n filename = b''\n newfile = False\n\n for i, line in enumerate(diff_lines):\n if line.startswith(b'diff '):\n # Grab the filename and then filter this out.\n # This will be in the format of:\n #\n # diff --git a/path/to/file b/path/to/file\n info = line.split(b' ')\n diff_data += b'Index: %s\\n' % info[2]\n diff_data += b'=' * 67\n diff_data += b'\\n'\n elif line.startswith(b'index '):\n # Filter this out.\n pass\n elif line.strip() == b'--- /dev/null':\n # New file\n newfile = True\n elif (line.startswith(b'--- ') and i + 1 < len(diff_lines) and\n diff_lines[i + 1].startswith(b'+++ ')):\n newfile = False\n original_file = line[4:].strip()\n diff_data += b'--- %s\\t(revision %s)\\n' % (original_file, rev)\n elif line.startswith(b'+++ '):\n filename = line[4:].strip()\n if newfile:\n diff_data += b'--- %s\\t(revision 0)\\n' % filename\n diff_data += b'+++ %s\\t(revision 0)\\n' % filename\n else:\n # We already printed the \"--- \" line.\n diff_data += b'+++ %s\\t(working copy)\\n' % original_file\n elif (line.startswith(b'new file mode') or\n line.startswith(b'deleted file mode')):\n # Filter this out.\n pass\n elif line.startswith(b'Binary files '):\n # Add the following so that we know binary files were\n # added/changed.\n diff_data += b'Cannot display: file marked as a binary type.\\n'\n diff_data += b'svn:mime-type = application/octet-stream\\n'\n else:\n diff_data += line\n\n return diff_data", "def test_base_filediff_and_interfilediff(self):\n repository = self.create_repository(tool_name='Git')\n review_request = self.create_review_request(repository=repository,\n create_with_history=True)\n review_request.target_people.add(review_request.submitter)\n\n diffset = self.create_diffset(review_request, draft=True)\n diffset_commits = [\n self.create_diffcommit(diffset=diffset, commit_id='r1',\n parent_id='r0'),\n self.create_diffcommit(diffset=diffset, commit_id='r2',\n parent_id='r1'),\n ]\n\n filediff = diffset_commits[1].files.get()\n base_filediff = diffset_commits[0].files.get()\n\n diffset.finalize_commit_series(\n cumulative_diff=self.DEFAULT_GIT_FILEDIFF_DATA_DIFF,\n validation_info=None,\n validate=False,\n save=True)\n review_request.publish(user=review_request.submitter)\n\n interdiffset = self.create_diffset(review_request, draft=True)\n interdiffset_commit = self.create_diffcommit(\n diffset=interdiffset, commit_id='r1', parent_id='r0')\n\n interdiffset.finalize_commit_series(\n cumulative_diff=self.DEFAULT_GIT_FILEDIFF_DATA_DIFF,\n validation_info=None,\n validate=False,\n save=True)\n review_request.publish(user=review_request.submitter)\n\n interfilediff = interdiffset_commit.files.get()\n\n rsp = self.client.get(\n local_site_reverse(\n 'view-diff-fragment',\n kwargs={\n 'review_request_id': review_request.display_id,\n 'revision': diffset.revision,\n 'interdiff_revision': interdiffset.revision,\n 'filediff_id': filediff.pk,\n 'interfilediff_id': interfilediff.pk,\n }),\n data={'base-filediff-id': base_filediff.pk})\n\n self.assertEqual(rsp.status_code, 500)\n self.assertIn(\n b'Cannot generate an interdiff when base FileDiff ID is '\n b'specified.',\n rsp.content)", "def test_base_filediff_and_interfilediff(self):\n\t\trepository = self.create_repository(tool_name=\"Git\")\n\t\treview_request = self.create_review_request(repository=repository, create_with_history=True)\n\t\treview_request.target_people = [review_request.submitter]\n\t\tdiffset = self.create_diffset(review_request, draft=True)\n\t\tdiffset_commits = [self.create_diffcommit(diffset=diffset, commit_id=\"r1\", parent_id=\"r0\"), self.create_diffcommit(diffset=diffset, commit_id=\"r2\", parent_id=\"r1\")]\n\t\tfilediff = diffset_commits[1].files.get()\n\t\tbase_filediff = diffset_commits[0].files.get()\n\t\tdiffset.finalize_commit_series(cumulative_diff=self.DEFAULT_GIT_FILEDIFF_DATA_DIFF, validation_info=None, validate=False, save=True)\n\t\treview_request.publish(user=review_request.submitter)\n\t\tinterdiffset = self.create_diffset(review_request, draft=True)\n\t\tinterdiffset_commit = self.create_diffcommit(diffset=interdiffset, commit_id=\"r1\", parent_id=\"r0\")\n\t\tinterdiffset.finalize_commit_series(cumulative_diff=self.DEFAULT_GIT_FILEDIFF_DATA_DIFF, validation_info=None, validate=False, save=True)\n\t\treview_request.publish(user=review_request.submitter)\n\t\tinterfilediff = interdiffset_commit.files.get()\n\t\trsp = self.client.get(local_site_reverse(\"view-diff-fragment\", kwargs={\"review_request_id\": review_request.display_id, \"revision\": diffset.revision, \"interdiff_revision\": interdiffset.revision, \"filediff_id\": filediff.pk, \"interfilediff_id\": interfilediff.pk}), data={\"base-filediff-id\": base_filediff.pk})\n\t\tself.assertEqual(rsp.status_code, 500)\n\t\tself.assertIn(b\"Cannot generate an interdiff when base FileDiff ID is \" b\"specified.\", rsp.content)", "def build_diff(self):\n return self._main_vcs.merged_diff(self.base_revision,\n self.arguments.new_revision,\n self.arguments.unified_lines)", "def diff(cls, src, dst, paths=None):\n path = self._repo._depot_path()\n # TODO paths format\n \n with self._repo._init_client() as p4c:\n oldtaggedvalue = p4c.tagged\n diff = '\\n'.join(p4c.run(\"diff2\", \n \"-u\", \n path + \"@\" + src.properties.revision_id,\n path + \"@\" + dst.properties.revision_id))\n p4c.tagged = oldtaggedvalue\n \n return RevisionDiff(diff)", "def on_check_diff_tool(self, process):\n output = process.output()\n if output:\n util.debug('difftool \"' + output + '\" found, select branch to diff with')\n self.select_branch_to_diff()\n else:\n util.debug('no difftool defined')\n sublime.message_dialog('No difftool defined by git. Please run:\\n\\ngit config --global diff.tool meld')", "def get_diff_raw(self, paths=None, staging=False):\n if paths is not None and not isinstance(paths, (tuple, list)):\n paths = [paths]\n\n if staging:\n return self.repo.git.diff(paths, cached=True)\n return self.repo.git.diff(paths)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares and sends Mailgun API call Returns dict with response status
def sendMailgun(self): apiURI = app.config['MAILGUN_API'] auth = ('api', app.config.get('MAILGUN_KEY')) data = { "from": self.from_name + " <" + self.from_addr + ">", "to": self.to_name + " <" + self.to_addr + ">", "subject": self.subject, "text": self.body } response = self.sendPost(apiURI=apiURI, data=data, auth=auth).json() if response.get('id'): return {"success": "true"} else: return { "success": "false", "reason": "Mailgun: " + response.get('message') }
[ "def test_mailgun():\n\n status, message = mailgun.send('marco.zingales@gmail.com', ['marzi@dtu.dk'], ['hello there'], [], 'test1',\n 'testcontent1')\n _test(\"mailgun works\", status == 0)", "def mailgun(to, subject, body, mailgun_api_key, mailgun_endpoint):\n ctx_obj = click.get_current_context().obj\n subject = try_context(ctx_obj, subject, \"subject\", \"release_subject\")\n body = try_context(ctx_obj, body, \"body\", \"release_notes\")\n return requests.post(\n \"{endpoint}/messages\".format(endpoint=mailgun_endpoint),\n auth=(\"api\", mailgun_api_key),\n data={\"from\": \"RPC-Jenkins@rackspace.com\",\n \"to\": [to],\n \"subject\": subject,\n \"text\": body\n }\n )", "def test_sendmail_with_mailgun_from_db_config(fake_post_request):\n app = create_ctfd()\n with app.app_context():\n app.config[\"MAILGUN_API_KEY\"] = \"key-1234567890-file-config\"\n app.config[\"MAILGUN_BASE_URL\"] = \"https://api.mailgun.net/v3/file.faked.com\"\n\n # db values should take precedence over file values\n set_config(\"mailgun_api_key\", \"key-1234567890-db-config\")\n set_config(\"mailgun_base_url\", \"https://api.mailgun.net/v3/db.faked.com\")\n\n to_addr = \"user@user.com\"\n msg = \"this is a test\"\n\n sendmail(to_addr, msg)\n\n fake_response = Mock()\n fake_post_request.return_value = fake_response\n fake_response.status_code = 200\n\n status, message = sendmail(to_addr, msg)\n\n args, kwargs = fake_post_request.call_args\n assert args[0] == \"https://api.mailgun.net/v3/db.faked.com/messages\"\n assert kwargs[\"auth\"] == (\"api\", \"key-1234567890-db-config\")\n assert kwargs[\"timeout\"] == 1.0\n assert kwargs[\"data\"] == {\n \"to\": [\"user@user.com\"],\n \"text\": \"this is a test\",\n \"from\": \"CTFd <noreply@examplectf.com>\",\n \"subject\": \"Message from CTFd\",\n }\n\n assert fake_response.status_code == 200\n assert status is True\n assert message == \"Email sent\"\n destroy_ctfd(app)", "def test_send_attaches_anymail_status(self):\n response_content = b\"\"\"{\n \"id\": \"<12345.67890@example.com>\",\n \"message\": \"Queued. Thank you.\"\n }\"\"\"\n self.set_mock_response(raw=response_content)\n msg = mail.EmailMessage(\n \"Subject\",\n \"Message\",\n \"from@example.com\",\n [\"to1@example.com\"],\n )\n sent = msg.send()\n self.assertEqual(sent, 1)\n self.assertEqual(msg.anymail_status.status, {\"queued\"})\n self.assertEqual(msg.anymail_status.message_id, \"<12345.67890@example.com>\")\n self.assertEqual(\n msg.anymail_status.recipients[\"to1@example.com\"].status, \"queued\"\n )\n self.assertEqual(\n msg.anymail_status.recipients[\"to1@example.com\"].message_id,\n \"<12345.67890@example.com>\",\n )\n self.assertEqual(msg.anymail_status.esp_response.content, response_content)", "def test_bounce_api_request(self):\n url = '/status/418' # teapot\n self.client.credentials(HTTP_HOST='httpbin.org')\n response = self.client.get(url)\n self.assertEqual(response.status_code, 418)\n self.assertIn('teapot', response.content.decode('utf-8'))", "def test_sendmail_with_mailgun_from_config_file(fake_post_request):\n app = create_ctfd()\n with app.app_context():\n app.config[\"MAILGUN_API_KEY\"] = \"key-1234567890-file-config\"\n app.config[\"MAILGUN_BASE_URL\"] = \"https://api.mailgun.net/v3/file.faked.com\"\n\n to_addr = \"user@user.com\"\n msg = \"this is a test\"\n\n sendmail(to_addr, msg)\n\n fake_response = Mock()\n fake_post_request.return_value = fake_response\n fake_response.status_code = 200\n\n status, message = sendmail(to_addr, msg)\n\n args, kwargs = fake_post_request.call_args\n assert args[0] == \"https://api.mailgun.net/v3/file.faked.com/messages\"\n assert kwargs[\"auth\"] == (\"api\", \"key-1234567890-file-config\")\n assert kwargs[\"timeout\"] == 1.0\n assert kwargs[\"data\"] == {\n \"to\": [\"user@user.com\"],\n \"text\": \"this is a test\",\n \"from\": \"CTFd <noreply@examplectf.com>\",\n \"subject\": \"Message from CTFd\",\n }\n\n assert fake_response.status_code == 200\n assert status is True\n assert message == \"Email sent\"\n destroy_ctfd(app)", "def test_sendForwardEmailMessage() -> json:\r\n\r\n # SetUp\r\n recipient = CONTACT_PK\r\n body = 'This is a Forward email by Python API test'\r\n subject = 'This is a Python api test'\r\n attachId = \"\"\r\n status = False\r\n result = ''\r\n\r\n # Action\r\n _, emails = u.getEmailFolder(1, \"\")\r\n if len(emails) > 0 and 'Error' not in emails:\r\n status, result = u.sendForwardEmailMessage(emails[-1], recipient, body, subject, attachId)\r\n else:\r\n raise Exception(\"There is no emails, or got Error on request\")\r\n\r\n # Assertion\r\n AssertNotEmptyOrError(status, result)", "def get_status():\n # Only accept JSON\n if not request.json:\n resp = create_response(\"Input should be specified in valid JSON format only\",400)\n return resp\n \n validate_get_status_input(request.json)\n\n name, email_address = MailerUtils.get_name_email_tuple(request.json.get('email'))\n\n # Get the job associated with the given ID from the Queue\n job_id = request.json['id']\n job = q.fetch_job(job_id)\n \n if(job is None):\n resp = create_response(\"Cannot find result for supplied ID and email\", 404)\n return resp\n\n # Get relevant metadata from the job\n mailer_name = job.meta['handled_by'] # Which mailer was used\n messages_info = job.meta['messages_info'] # Info about all recepients and underlying provider specific ID for the request\n\n # Get info about the relevant message\n single_message_info = next(message_info for message_info in messages_info if message_info.get('email_address') == email_address)\n if(single_message_info is None):\n resp = create_response(\"Cannot find message sent to {0} during request with ID {1}\".format(email_address,job_id),404)\n return resp\n\n relevant_mailer = available_mailers[mailer_name]\n status_info = relevant_mailer.get_message_status(single_message_info)\n \n if(status_info is None):\n # Must have timed out\n resp = create_response(\"This request cannot be served right now. Please try again.\", 503)\n return resp\n\n resp = create_response(None, 200, status_info)\n return resp", "def test_api_v1_messages_resend_email_verification_post(self):\n pass", "def _send_cmd_and_verify(self, request_func, verify_func,\n request_success_msg='', rargs=[], vargs=[]):\n resp = {}\n start = time.time()\n request_needed = True\n verify_needed = True\n\n while request_needed or verify_needed:\n if time.time() - start >= self.request_timeout:\n raise RequestRetryTimeout(timeout=self.request_timeout)\n\n if request_needed:\n resp = request_func(*rargs)\n if not resp['message']:\n # XG requests will return None for a message if no message\n # string is passed int the raw response\n resp['message'] = ''\n if not resp['code'] and request_success_msg in resp['message']:\n # XG request func was completed\n request_needed = False\n self._fatal_error_code(resp)\n\n elif verify_needed:\n success = verify_func(*vargs)\n if success:\n # XG verify func was completed\n verify_needed = False\n else:\n # try sending the request again\n request_needed = True\n\n return resp", "def test_self_mailer_retrieve_with_custom_headers(self):\n self.mock_api.self_mailer_retrieve = MagicMock(return_value={\n \"id\": \"sfm_fakeId\"\n })\n retrieved_self_mailer = self.mock_api.self_mailer_retrieve(\"sfm_fakeId\", _content_type=\"application/json\")\n self.assertEqual(retrieved_self_mailer[\"id\"], \"sfm_fakeId\")", "def signed_request(self, method, api_url, **payload):\n\n payload['api_key'] = self.key\n full_url = self.create_uri(api_url)\n payload = self.get_signed(payload)\n r = {}\n\n try:\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'\n }\n r = requests.post(full_url, data=payload, headers=headers, timeout=5)\n r.raise_for_status()\n except requests.exceptions.HTTPError as err:\n # print(err)\n print(r.text)\n finally:\n pass\n\n if r.status_code == 200:\n print(str(r.json()))\n return r.json()", "def api_request(api_response):\n\n\tclass FakeApiRequestObject:\n\t\tdef __call__(self, *args, **kwargs):\n\t\t\treturn api_response\n\n\t\tsend = __call__\n\n\treturn FakeApiRequestObject()", "def post(self):\n api_payload = api.payload\n output = mail_sender.send_confirm_reimbursement_mail(\n email_type=MAIL_TYPE.confirm_reimbursement.value,\n user_id=api_payload.get('user_id'),\n from_mail=MAIL_DEFAULT.from_default.value,\n to_mail=api_payload.get('to_mail'),\n subject=api_payload.get('subject'),\n ticket_params=api_payload.get('params'))\n return {'message': 'colocado na fila!'}, 200", "def bounce_check(self):\n\n conn = http.client.HTTPSConnection(\"api.sendgrid.com\")\n\n payload = \"{}\"\n\n headers = {'authorization': \"Bearer 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\"}\n\n conn.request(\"GET\", \"/v3/suppression/bounces/\" + self.to_email + \"\", payload, headers)\n\n res = conn.getresponse()\n data = res.read()\n\n bounce_msg = json.loads(data.decode(\"utf-8\"))\n if bounce_msg:\n self.bounce_msg = bounce_msg[0]['reason']\n\n else:\n self.bounce_msg = \"This Email Is Not Bounced\"", "def stub_status(self):\n stub_body = ''\n stub = {}\n stub_time = int(time.time())\n\n # get stub status body\n try:\n stub_body = context.http_client.get(self.object.stub_status_url, timeout=1, json=False, log=False)\n except GreenletExit:\n # we caught an exit signal in the middle of processing so raise it.\n raise\n except:\n context.log.error('failed to check stub_status url %s' % self.object.stub_status_url)\n context.log.debug('additional info', exc_info=True)\n stub_body = None\n\n if not stub_body:\n return\n\n # parse body\n try:\n gre = STUB_RE.match(stub_body)\n if not gre:\n raise AmplifyParseException(message='stub status %s' % stub_body)\n for field in ('connections', 'accepts', 'handled', 'requests', 'reading', 'writing', 'waiting'):\n stub[field] = int(gre.group(field))\n except:\n context.log.error('failed to parse stub_status body')\n raise\n\n # store some variables for further use\n stub['dropped'] = stub['accepts'] - stub['handled']\n\n # gauges\n self.object.statsd.gauge('nginx.http.conn.current', stub['connections'])\n self.object.statsd.gauge('nginx.http.conn.active', stub['connections'] - stub['waiting'])\n self.object.statsd.gauge('nginx.http.conn.idle', stub['waiting'])\n self.object.statsd.gauge('nginx.http.request.writing', stub['writing'])\n self.object.statsd.gauge('nginx.http.request.reading', stub['reading'])\n self.object.statsd.gauge('nginx.http.request.current', stub['reading'] + stub['writing'])\n\n # counters\n counted_vars = {\n 'nginx.http.request.count': 'requests',\n 'nginx.http.conn.accepted': 'accepts',\n 'nginx.http.conn.dropped': 'dropped'\n }\n for metric_name, stub_name in counted_vars.items():\n stamp, value = stub_time, stub[stub_name]\n prev_stamp, prev_value = self.previous_counters.get(metric_name, (None, None))\n\n if isinstance(prev_value, (int, float, complex)) and prev_stamp and prev_stamp != stamp:\n value_delta = value - prev_value\n self.object.statsd.incr(metric_name, value_delta)\n\n self.previous_counters[metric_name] = [stamp, value]", "def GET_request(action):\n\n # OAuth token of the user that requests will be made on behalf of\n\n\n # Login of the advertising agency client\n # Required parameter if requests are made on behalf of an advertising agency\n clientLogin = 'marketingdigital@zara.com'\n\n headers = {\n # OAuth token. The word Bearer must be used\n \"Authorization\": 'OAuth AQAAAABDFBfdAAcVB0yqdlcRyEzIu8BBs1TTLuE',\n # Login of the advertising agency client\n \"Client-Login\": clientLogin,\n # Language for response messages\n \"Accept-Language\": \"en\",\n # Mode for report generation\n \"processingMode\": \"auto\"\n # Format for monetary values in the report\n # \"returnMoneyInMicros\": \"false\",\n # Don't include the row with the report name and date range in the report\n # \"skipReportHeader\": \"true\",\n # Don't include the row with column names in the report\n # \"skipColumnHeader\": \"true\",\n # Don't include the row with the number of statistics rows in the report\n # \"skipReportSummary\": \"true\"\n }\n\n\n API_URL = 'https://api.webmaster.yandex.net/v4'\n\n\n\n retry_count = 0\n retry_max = 1\n\n try:\n resp = requests.get(API_URL + action, headers=headers)\n except Exception as message:\n if \"400\" or \"401\" in message:\n logging.error(f\"Could not retrieve html, authentication or token error: {message}\")\n sys.exit(1)\n elif retry_count < retry_max:\n print(f\"Retrying ... (count {retry_count})\")\n # sleep for fifteen minutes\n time.sleep(10)\n\n # increase the counter\n retry_count = retry_count + 1\n\n else:\n logging.error(f\"Could not retrieve response: {message}\")\n raise Exception(str(message))\n\n return resp.json()", "def ok():\n return {\n \"statusCode\": 200,\n \"body\": dumps({\"message\": \"OK\"}),\n \"headers\": {\"Content-Type\": \"application/json\"},\n }", "def success(status_code=204):\n response = make_response()\n response.status_code = status_code\n return response" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares and sends Mandrill API call Returns dict with response status
def sendMandrill(self): headers = {'content-type': 'application/json'} apiURI = app.config['MANDRILL_API'] data = { "key": app.config.get('MANDRILL_KEY'), "message": { "from_email": self.from_addr, "from_name": self.from_name, "to": [ { "email": self.to_addr, "name": self.to_name, "type": "to" } ], "subject": self.subject, "text": self.body } } data = json.dumps(data) response = self.sendPost(apiURI=apiURI, data=data, headers=headers).json()[0] if (response.get('status') == 'sent'): return {"success": "true"} else: return { "success": "false", "reason": "Mandrill: " + response.get('status') }
[ "def rp(success=False, message=None, payload=None):\n return{\n 'success': success,\n 'message': message, \n 'payload': payload,\n }", "def GET_request(action):\n\n # OAuth token of the user that requests will be made on behalf of\n\n\n # Login of the advertising agency client\n # Required parameter if requests are made on behalf of an advertising agency\n clientLogin = 'marketingdigital@zara.com'\n\n headers = {\n # OAuth token. The word Bearer must be used\n \"Authorization\": 'OAuth AQAAAABDFBfdAAcVB0yqdlcRyEzIu8BBs1TTLuE',\n # Login of the advertising agency client\n \"Client-Login\": clientLogin,\n # Language for response messages\n \"Accept-Language\": \"en\",\n # Mode for report generation\n \"processingMode\": \"auto\"\n # Format for monetary values in the report\n # \"returnMoneyInMicros\": \"false\",\n # Don't include the row with the report name and date range in the report\n # \"skipReportHeader\": \"true\",\n # Don't include the row with column names in the report\n # \"skipColumnHeader\": \"true\",\n # Don't include the row with the number of statistics rows in the report\n # \"skipReportSummary\": \"true\"\n }\n\n\n API_URL = 'https://api.webmaster.yandex.net/v4'\n\n\n\n retry_count = 0\n retry_max = 1\n\n try:\n resp = requests.get(API_URL + action, headers=headers)\n except Exception as message:\n if \"400\" or \"401\" in message:\n logging.error(f\"Could not retrieve html, authentication or token error: {message}\")\n sys.exit(1)\n elif retry_count < retry_max:\n print(f\"Retrying ... (count {retry_count})\")\n # sleep for fifteen minutes\n time.sleep(10)\n\n # increase the counter\n retry_count = retry_count + 1\n\n else:\n logging.error(f\"Could not retrieve response: {message}\")\n raise Exception(str(message))\n\n return resp.json()", "def send_apt_info_email_to_consumer(consumer_info, nav_info, scheduled_appointment, post_errors):\n\n try:\n mandrill_client = mandrill.Mandrill('1veuJ5Rt5CtLEDj64ijXIA')\n message_content = \"Hello, you have an appointment scheduled with {!s} {!s} at {!s}. They will be contacting you at {!s}. We look forward to speaking with you!\".format(nav_info[\"First Name\"], nav_info[\"Last Name\"], scheduled_appointment[\"Appointment Date and Time\"], consumer_info[\"Phone Number\"])\n message = {'auto_html': None,\n 'auto_text': None,\n 'from_email': 'tech@piccares.org',\n 'from_name': 'Patient Innovation Center',\n 'headers': {'Reply-To': nav_info[\"Email\"]},\n 'html': '<p>{!s}</p>'.format(message_content),\n 'important': True,\n 'subject': scheduled_appointment[\"Appointment Title\"],\n # 'text': 'Example text content',\n 'to': [{'email': consumer_info[\"Email\"],\n 'name': '{!s} {!s}'.format(consumer_info[\"First Name\"], consumer_info[\"Last Name\"]),\n 'type': 'to'}],}\n result = mandrill_client.messages.send(message=message)\n '''\n [{'_id': 'abc123abc123abc123abc123abc123',\n 'email': 'recipient.email@example.com',\n 'reject_reason': 'hard-bounce',\n 'status': 'sent'}]\n '''\n\n except mandrill.Error:\n # Mandrill errors are thrown as exceptions\n post_errors.append('A mandrill error occurred')\n # A mandrill error occurred: <class 'mandrill.UnknownSubaccountError'> - No subaccount exists with the id 'customer-123'", "def post(self):\n api_payload = api.payload\n output = mail_sender.send_confirm_reimbursement_mail(\n email_type=MAIL_TYPE.confirm_reimbursement.value,\n user_id=api_payload.get('user_id'),\n from_mail=MAIL_DEFAULT.from_default.value,\n to_mail=api_payload.get('to_mail'),\n subject=api_payload.get('subject'),\n ticket_params=api_payload.get('params'))\n return {'message': 'colocado na fila!'}, 200", "def send_message(self, payload):\n self.validate_payload(payload)\n payload = self.get_plain_text(payload)\n data = {\n Mandrill.REQ_KEY: self.provider[Provider.PROVIDER_API_KEY],\n Mandrill.REQ_MESS: {\n Mandrill.REQ_TEXT: payload[Provider.PAYLOAD_TEXT],\n Mandrill.REQ_SUBJECT: payload[Provider.PAYLOAD_SUBJECT],\n Mandrill.REQ_FROM: payload[Provider.PAYLOAD_FROM],\n Mandrill.REQ_FROM_NAME: payload[Provider.PAYLOAD_FROM_NAME],\n Mandrill.REQ_TO: [\n {\n Mandrill.REQ_TO_EMAIL: payload[Provider.PAYLOAD_TO],\n Mandrill.REQ_TO_NAME: payload[Provider.PAYLOAD_TO_NAME],\n Mandrill.REQ_TYPE: Mandrill.REQ_TYPE_TO\n }\n ]\n }\n }\n return requests.post(\n self.provider[Provider.PROVIDER_URL],\n data=json.dumps(data))", "def _send_cmd_and_verify(self, request_func, verify_func,\n request_success_msg='', rargs=[], vargs=[]):\n resp = {}\n start = time.time()\n request_needed = True\n verify_needed = True\n\n while request_needed or verify_needed:\n if time.time() - start >= self.request_timeout:\n raise RequestRetryTimeout(timeout=self.request_timeout)\n\n if request_needed:\n resp = request_func(*rargs)\n if not resp['message']:\n # XG requests will return None for a message if no message\n # string is passed int the raw response\n resp['message'] = ''\n if not resp['code'] and request_success_msg in resp['message']:\n # XG request func was completed\n request_needed = False\n self._fatal_error_code(resp)\n\n elif verify_needed:\n success = verify_func(*vargs)\n if success:\n # XG verify func was completed\n verify_needed = False\n else:\n # try sending the request again\n request_needed = True\n\n return resp", "def test_initiate_bulk_charge(self):\n\n httpretty.register_uri(\n httpretty.POST,\n self.endpoint_url(\"/bulkcharge\"),\n content_type='applicationn/json',\n body='{\"status\": true, \"message\": \"Charges have been queued\"}',\n status=200,\n )\n\n response = BulkCharge.initiate_bulk_charge(\n bulkcharge=[\n {\"authorization\": \"AUTH_n95vpedf\", \"amount\": 2500}, \n {\"authorization\": \"AUTH_ljdt4e4j\", \"amount\": 1500}\n ]\n )\n\n self.assertTrue(response['status'])", "def get_status():\n # Only accept JSON\n if not request.json:\n resp = create_response(\"Input should be specified in valid JSON format only\",400)\n return resp\n \n validate_get_status_input(request.json)\n\n name, email_address = MailerUtils.get_name_email_tuple(request.json.get('email'))\n\n # Get the job associated with the given ID from the Queue\n job_id = request.json['id']\n job = q.fetch_job(job_id)\n \n if(job is None):\n resp = create_response(\"Cannot find result for supplied ID and email\", 404)\n return resp\n\n # Get relevant metadata from the job\n mailer_name = job.meta['handled_by'] # Which mailer was used\n messages_info = job.meta['messages_info'] # Info about all recepients and underlying provider specific ID for the request\n\n # Get info about the relevant message\n single_message_info = next(message_info for message_info in messages_info if message_info.get('email_address') == email_address)\n if(single_message_info is None):\n resp = create_response(\"Cannot find message sent to {0} during request with ID {1}\".format(email_address,job_id),404)\n return resp\n\n relevant_mailer = available_mailers[mailer_name]\n status_info = relevant_mailer.get_message_status(single_message_info)\n \n if(status_info is None):\n # Must have timed out\n resp = create_response(\"This request cannot be served right now. Please try again.\", 503)\n return resp\n\n resp = create_response(None, 200, status_info)\n return resp", "def _get_headers():\n return {\"content-type\": \"application/json\", \"user-agent\": \"Mandrill-Python/1.0.57\"}", "def test_flow_triggered(self):\n message = Mock()\n message.id = \"test-id\"\n message.data = {\"_vnd\": {\"v1\": {\"chat\": {\"owner\": \"27820001001\"}}}}\n tasks.rapidpro = TembaClient(\"textit.in\", \"test-token\")\n responses.add(\n responses.GET,\n \"http://engage/v1/contacts/27820001001/messages\",\n json={\n \"messages\": [\n {\n \"_vnd\": {\n \"v1\": {\n \"direction\": \"outbound\",\n \"author\": {\n \"id\": \"2ab15df1-082a-4420-8f1a-1fed53b13eba\",\n \"type\": \"OPERATOR\",\n },\n }\n },\n \"from\": \"27820001002\",\n \"id\": message.id,\n \"text\": {\"body\": \"Operator response\"},\n \"timestamp\": \"1540803363\",\n \"type\": \"text\",\n },\n {\n \"_vnd\": {\"v1\": {\"direction\": \"inbound\", \"labels\": []}},\n \"from\": \"27820001001\",\n \"id\": \"ABGGJ3EVEUV_AhALwhRTSopsSmF7IxgeYIBz\",\n \"text\": {\"body\": \"Inbound question\"},\n \"timestamp\": \"1540802983\",\n \"type\": \"text\",\n },\n ]\n },\n )\n responses.add(\n responses.GET,\n \"https://textit.in/api/v2/contacts.json?urn=whatsapp:27820001001\",\n json={\n \"results\": [\n {\n \"uuid\": \"contact-id\",\n \"name\": \"\",\n \"language\": \"zul\",\n \"groups\": [],\n \"fields\": {\"facility_code\": \"123456\"},\n \"blocked\": False,\n \"stopped\": False,\n \"created_on\": \"2015-11-11T08:30:24.922024+00:00\",\n \"modified_on\": \"2015-11-11T08:30:25.525936+00:00\",\n \"urns\": [\"tel:+27820001001\"],\n }\n ],\n \"next\": None,\n },\n )\n responses.add(\n responses.POST,\n \"https://textit.in/api/v2/contacts.json?urn=whatsapp:27820001001\",\n json={},\n )\n responses.add(responses.POST, \"http://jembi/ws/rest/v1/helpdesk\", json={})\n\n handle_operator_message(message)\n [jembi_request] = JembiSubmission.objects.all()\n jembi_request.request_data.pop(\"eid\")\n self.assertEqual(\n jembi_request.request_data,\n {\n \"class\": \"Unclassified\",\n \"cmsisdn\": \"+27820001001\",\n \"data\": {\"answer\": \"Operator response\", \"question\": \"Inbound question\"},\n \"dmsisdn\": \"+27820001001\",\n \"encdate\": \"20181029084943\",\n \"faccode\": \"123456\",\n \"mha\": 1,\n \"op\": \"56748517727534413379787391391214157498\",\n \"repdate\": \"20181029085603\",\n \"sid\": \"contact-id\",\n \"swt\": 4,\n \"type\": 7,\n },\n )", "def sendMailgun(self):\n apiURI = app.config['MAILGUN_API']\n auth = ('api', app.config.get('MAILGUN_KEY'))\n data = {\n \"from\": self.from_name + \" <\" + self.from_addr + \">\",\n \"to\": self.to_name + \" <\" + self.to_addr + \">\",\n \"subject\": self.subject,\n \"text\": self.body\n }\n response = self.sendPost(apiURI=apiURI, data=data, auth=auth).json()\n if response.get('id'):\n return {\"success\": \"true\"}\n else:\n return {\n \"success\": \"false\",\n \"reason\": \"Mailgun: \" + response.get('message')\n }", "def _executeSMSApi(self, smsApiMethod, params): \n\n result = {}\n try:\n result.update(smsApiMethod(**params))\n except WebFault, e:\n result['error_webfault'] = unicode(e.fault['faultstring'])\n finally:\n return self._flatenResult(result)", "def req(method, path, data, param_data):\n if not TOKEN:\n get_token()\n response = requests.request(method, URL + path, json=data, params=param_data, headers=HEADERS, verify=VERIFY)\n if response.status_code != requests.codes.ok: # pylint: disable=no-member\n text = response.text\n if response.headers.get('x-redlock-status'):\n try:\n statuses = json.loads(response.headers.get('x-redlock-status')) # type: ignore\n for status in statuses:\n text += '\\n%s [%s]' % (status.get('i18nKey', ''), status.get('subject', ''))\n # Handle case for no remediation details\n if status['i18nKey'] == 'remediation_unavailable':\n return False\n if status['i18nKey'] == 'alert_no_longer_in_expected_state':\n return False\n except Exception:\n pass\n raise Exception('Error in API call to RedLock service [%d] - %s' % (response.status_code, text))\n if not response.text:\n return {}\n return response.json()", "def test_sendForwardEmailMessage() -> json:\r\n\r\n # SetUp\r\n recipient = CONTACT_PK\r\n body = 'This is a Forward email by Python API test'\r\n subject = 'This is a Python api test'\r\n attachId = \"\"\r\n status = False\r\n result = ''\r\n\r\n # Action\r\n _, emails = u.getEmailFolder(1, \"\")\r\n if len(emails) > 0 and 'Error' not in emails:\r\n status, result = u.sendForwardEmailMessage(emails[-1], recipient, body, subject, attachId)\r\n else:\r\n raise Exception(\"There is no emails, or got Error on request\")\r\n\r\n # Assertion\r\n AssertNotEmptyOrError(status, result)", "def test_sending_and_accepting_request(self):\n\n self.send_request()\n\n request_response_id = RequestResponse.list(\n self._API_CONTEXT,\n self._USER_ID,\n self._MONETARY_ACCOUNT_ID2\n ).value[self._FIRST_INDEX].id_\n\n self.accept_request(request_response_id)", "def _send_cmd_and_verify(self, request_func, verify_func,\n request_success_msgs='', rargs=None, vargs=None):\n resp = {}\n start = time.time()\n request_needed = True\n verify_needed = True\n\n if isinstance(request_success_msgs, six.string_types):\n request_success_msgs = [request_success_msgs, ]\n\n rargs = rargs if rargs else []\n vargs = vargs if vargs else []\n\n while request_needed or verify_needed:\n if time.time() - start >= self.config.violin_request_timeout:\n raise exception.ViolinRequestRetryTimeout(\n timeout=self.config.violin_request_timeout)\n\n if request_needed:\n resp = request_func(*rargs)\n\n if not resp['msg']:\n # XG requests will return None for a message if no message\n # string is passed in the raw response\n resp['msg'] = ''\n\n for msg in request_success_msgs:\n if resp['success'] and msg in resp['msg']:\n request_needed = False\n break\n\n if not resp['success']:\n self._check_error_code(resp)\n request_needed = False\n\n elif verify_needed:\n success = verify_func(*vargs)\n if success:\n # XG verify func was completed\n verify_needed = False\n\n return resp", "def status_payments_server(self):", "def test_send_attaches_anymail_status(self):\n response_content = b\"\"\"{\n \"id\": \"<12345.67890@example.com>\",\n \"message\": \"Queued. Thank you.\"\n }\"\"\"\n self.set_mock_response(raw=response_content)\n msg = mail.EmailMessage(\n \"Subject\",\n \"Message\",\n \"from@example.com\",\n [\"to1@example.com\"],\n )\n sent = msg.send()\n self.assertEqual(sent, 1)\n self.assertEqual(msg.anymail_status.status, {\"queued\"})\n self.assertEqual(msg.anymail_status.message_id, \"<12345.67890@example.com>\")\n self.assertEqual(\n msg.anymail_status.recipients[\"to1@example.com\"].status, \"queued\"\n )\n self.assertEqual(\n msg.anymail_status.recipients[\"to1@example.com\"].message_id,\n \"<12345.67890@example.com>\",\n )\n self.assertEqual(msg.anymail_status.esp_response.content, response_content)", "def test_api_v1_messages_resend_email_verification_post(self):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A pair of (xmin, xmax).
def xrange(self): return (self.xmin, self.xmax)
[ "def bbox(self) -> Tuple[Tuple[float, float], Tuple[float, float]]:\n minx, miny, maxx, maxy = self.polygon.bounds\n return (minx, miny), (maxx, maxy)", "def bbox(points):\n assert len(points) > 0\n x_min, y_min = points[0]\n x_max, y_max = points[0]\n for pt in points:\n x,y = pt\n if x < x_min: x_min = x\n if y < y_min: y_min = y\n if x > x_max: x_max = x\n if y > y_max: y_max = y\n log.debug(\"Points bounded by ({},{}) and ({},{})\"\n .format(x_min, y_min, x_max, y_max))\n return (x_min, y_min), (x_max, y_max)", "def bounding_box(self):\n x1 = self.X.min()\n x2 = self.X.max()\n y1 = self.Y.min()\n y2 = self.Y.max()\n return [x1,x2,y1,y2]", "def boundingBox(self):\n xpos = self.xpos\n\n minXY = np.array([xpos - self.box_width / 2, self._bpdata.min * 0.95])\n maxXY = np.array([xpos + self.box_width / 2, self._bpdata.max * 1.05])\n return minXY, maxXY", "def bounds(self) -> Tuple[Optional[Number], Optional[Number]]:\n return self.lower_bound, self.upper_bound", "def bounds(self):\n xmin, ymax = self.top_left\n nrow, ncol = self.shape\n xmax = xmin + ncol * self.resolution\n ymin = ymax - nrow * self.resolution\n return xmin, ymin, xmax, ymax", "def int_pair(self):\n return tuple([int(self.x), int(self.y)])", "def __get_param_range(self, paramLow, paramHigh, step):\n if paramLow == paramHigh:\n return (paramLow, )\n else:\n preAnswer = []\n param = paramLow\n while param <= paramHigh:\n preAnswer.append(param)\n param += step\n if preAnswer[-1] != paramHigh:\n preAnswer.append(paramHigh)\n return tuple(preAnswer)", "def bbox (pol):\n\n xmin = pol[0][0]\n xmax = pol[0][0]\n ymin = pol[0][1]\n ymax = pol[0][1]\n\n for pnt in pol:\n if pnt[0] < xmin:\n xmin = pnt[0]\n elif pnt[0] > xmax:\n xmax = pnt[0]\n\n if pnt[1] < ymin:\n ymin = pnt[1]\n elif pnt[1] > ymax:\n ymax = pnt[1]\n\n return [xmin,ymin,xmax,ymax]", "def tuple(self):\n return self.start.coordinates[0], self.start.coordinates[1], self.end.coordinates[0], self.end.coordinates[1]", "def _get_max_min(self, that):\n maxstart = max(self.start, that.start)\n minstop = min(self.stop, that.stop)\n return (maxstart, minstop)", "def MinMax(arg1, arg2):\n return min(arg1, arg2), max(arg1, arg2)", "def max_and_min(list):\n\n # return tuple containig max and min of list\n return (max(list), min(list))", "def box_selection():\n\n style = UI.Selection.PickBoxStyle.Enclosing\n data = uidoc.Selection.PickBox(style, 'select two point')\n return data.Min, data.Max", "def split(self, x=None, y=None): ###\n b = None\n if x == None and y == None:\n if self.internal == None:\n x = 0.5\n else:\n x = 0.5 * (self.internal.left + self.internal.right)\n if x != None and y != None:\n return tuple([b.split(x=x) for b in self.split(y=y)])\n if x != None:\n x = self.map(val=x, attr=\"x\")\n b = [self.copy(), self.copy()]\n b[0].right = x\n b[1].left = x\n if y != None:\n y = self.map(val=y, attr=\"y\")\n b = [self.copy(), self.copy()]\n b[0].bottom = y\n b[1].top = y\n if b != None:\n b = tuple(b)\n return b", "def _getbbox(coords):\n minx = float('NaN')\n miny = float('NaN')\n maxx = float('NaN')\n maxy = float('NaN')\n for part in coords:\n for x, y in part:\n minx = min(x, minx)\n miny = min(y, miny)\n maxx = max(x, maxx)\n maxy = max(y, maxy)\n return [minx, miny, maxx, maxy]", "def bbox_for_points(coords):\n bbox = min(coords), max(coords)\n return bbox", "def get_min_max_values(self):\n\n min_val = min(self.array_like)\n max_val = max(self.array_like)\n\n self.min_max_val = (min_val, max_val)", "def minimum_bounding_rectangle(points):\n\n mbr = [0,0,0,0]\n\n x_list=[]\n y_list=[]\n for x,y in points:\n x_list.append(x)\n y_list.append(y)\n mbr=[min(x_list),min(y_list),max(x_list),max(y_list)]\n\n return mbr", "def _coords(self, x, y):\n return y, x * 2" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The height of the region.
def height(self): return self.ymax - self.ymin
[ "def getHeight( self ):\n return self.height", "def height(self):\n return capi.get_band_ysize(self.ptr)", "def get_height(self):\n\t\treturn self.y[1] - self.y[0]", "def Height(self):\n return _handle.OperatorHandle_Height(self)", "def _get_height(self) -> \"int\" :\n return _core.Palette__get_height(self)", "def _get_height(self) -> \"double\" :\n return _core.OrientedBoundingBox3D__get_height(self)", "def height_in(self):\n return self._height_in", "def height(self):\n return self.image.height", "def get_block_height(self):\n return self._block_height", "def height(self) -> int:\n return self.winfo_height()", "def get_height(self):\n return self.textsurf.get_height()", "def get_height(self):\n try:\n return self.image.height\n except Exception:\n return 0", "def _get_height(self) -> \"int\" :\n return _core.Viewport__get_height(self)", "def inner_height_in(self):\n return self._inner_height_in", "def get_height(self):\n assert self.__texture is not None\n return self.__height", "def height(self):\n return len(self._rows)", "def get_height(self):\n print(len(self.array))", "def getHeight(self) -> \"float\":\n return _coin.SbViewVolume_getHeight(self)", "def height(self) -> int:\n node = self.root\n return self.height_help(node)", "def frame_height(self):\n # type: () -> int\n return self._frame_height" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A pair of (ymax, ymin). Inverted so as to work well with `matplotib`.
def yrange(self): return (self.ymax, self.ymin)
[ "def test_ymin_ymax(self):\n for font in self.fonts:\n head_table = font['head']\n self.assertEqual(head_table.yMin, EXPECTED_YMIN)\n self.assertEqual(head_table.yMax, EXPECTED_YMAX)", "def get_ylimits(data):\n min_overlaps = min(\n numpy.min(m[\"gradient_curvature_overlap\"]) for m in traverse(data)\n )\n min_trivial = min(m[\"gradient_trivial_overlap\"] for m in traverse(data))\n\n # logscale, no 0\n if min_trivial == 0.0:\n ymin = min_overlaps\n else:\n ymin = min(min_trivial, min_overlaps)\n\n max_overlaps = max(\n numpy.max(m[\"gradient_curvature_overlap\"]) for m in traverse(data)\n )\n max_trivial = max(m[\"gradient_trivial_overlap\"] for m in traverse(data))\n\n # logscale, no 0\n if max_trivial == 0.0:\n ymax = max_overlaps\n else:\n ymax = max(max_trivial, max_overlaps)\n\n return ymin, ymax", "def PlotBoundsMinY(self) -> float:", "def scale_y(y):\n ymax = y.max()\n return y/ymax, ymax", "def bbox (pol):\n\n xmin = pol[0][0]\n xmax = pol[0][0]\n ymin = pol[0][1]\n ymax = pol[0][1]\n\n for pnt in pol:\n if pnt[0] < xmin:\n xmin = pnt[0]\n elif pnt[0] > xmax:\n xmax = pnt[0]\n\n if pnt[1] < ymin:\n ymin = pnt[1]\n elif pnt[1] > ymax:\n ymax = pnt[1]\n\n return [xmin,ymin,xmax,ymax]", "def get_ydata_limits(self, axes):\n lines = axes.get_lines()\n ymin, ymax = [], []\n for line in lines:\n y = line.get_ydata()\n ymin.append(np.nanmin(y))\n ymax.append(np.nanmax(y))\n return np.nanmin(ymin), np.nanmax(ymax)", "def boundingBox(self):\n xpos = self.xpos\n\n minXY = np.array([xpos - self.box_width / 2, self._bpdata.min * 0.95])\n maxXY = np.array([xpos + self.box_width / 2, self._bpdata.max * 1.05])\n return minXY, maxXY", "def get_range_log(self, models):\n data = self.get_series(models)\n try:\n ymin = min([min(d) for d in data])\n except:\n ymin = 1e-30\n ymax = max([max(d) for d in data])\n return (ymin, ymax)", "def graph_y(self, y):\n \n return self.ymax - (y * (self.ymax - self.ymin) / float(self.height))", "def bbox(self) -> Tuple[Tuple[float, float], Tuple[float, float]]:\n minx, miny, maxx, maxy = self.polygon.bounds\n return (minx, miny), (maxx, maxy)", "def PlotWindowMinY(self) -> float:", "def get_range_linear(self, models):\n data = self.get_series(models)\n ymin = min([min(d) for d in data])\n ymax = max([max(d) for d in data])\n return (ymin, ymax)", "def larger_axlim(axlim):\n axmin, axmax = axlim\n axrng = axmax - axmin\n new_min = axmin + 0.1 * axrng\n new_max = axmax - 0.1 * axrng\n return new_min, new_max", "def larger_axlim(axlim):\n axmin, axmax = axlim\n axrng = axmax - axmin\n new_min = axmin + 0.1 * axrng\n new_max = axmax - 0.1 * axrng\n return new_min, new_max", "def get_plot_borders(cls, x): # pylint: disable=C0103\n xmin = np.min(x)\n xmax = np.max(x)\n gap = (xmax - xmin) * 0.1\n return xmin - gap, xmax + gap", "def bounds(self):\n xmin, ymax = self.top_left\n nrow, ncol = self.shape\n xmax = xmin + ncol * self.resolution\n ymin = ymax - nrow * self.resolution\n return xmin, ymin, xmax, ymax", "def get_extent(gtws):\n\n minx = float(\"inf\")\n miny = float(\"inf\")\n maxx = float(\"-inf\")\n maxy = float(\"-inf\")\n\n for gtw in gtws:\n if gtws[gtw][0] < minx:\n minx = gtws[gtw][0]\n if gtws[gtw][0] > maxx:\n maxx = gtws[gtw][0]\n if gtws[gtw][1] < miny:\n miny = gtws[gtw][1]\n if gtws[gtw][1] > maxy:\n maxy = gtws[gtw][1]\n\n # print (minx, miny, maxx, maxy)\n return minx, miny, maxx, maxy", "def test_glyphs_ymin_ymax(self):\n for font_file, font in zip(self.font_files, self.fonts):\n glyf_table = font['glyf']\n for glyph_name in glyf_table.glyphOrder:\n try:\n y_min = glyf_table[glyph_name].yMin\n y_max = glyf_table[glyph_name].yMax\n except AttributeError:\n continue\n\n self.assertTrue(\n EXPECTED_YMIN <= y_min and y_max <= EXPECTED_YMAX,\n ('The vertical metrics for glyph %s in %s exceed the '\n 'acceptable range: yMin=%d, yMax=%d' % (\n glyph_name, font_file, y_min, y_max)))", "def _ecg_rest_ylims(yrange, yplot):\n deltas = [-1.0, 1.0]\n extremes = np.array([np.min(yplot), np.max(yplot)])\n delta_ext = extremes[1] - extremes[0]\n yrange = np.max([yrange, delta_ext * 1.10])\n ylim_min = -yrange / 2.0\n ylim_max = yrange / 2.0\n if ((extremes[0] - ylim_min) < yrange * 0.2) or (\n (ylim_max - extremes[1]) < yrange * 0.2\n ):\n ylim_min = extremes[0] - (yrange - delta_ext) / 2.0\n ylim_max = extremes[1] + (yrange - delta_ext) / 2.0\n return ylim_min, ylim_max", "def getTentativeBB(self):\n\t\treturn self.minx, self.miny, self.maxx, self.maxy" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method to aid in constructing a new instance centred on the given location, with a given width and/or height. If only one of the width or height is specified, the aspect ratio is used.
def from_centre(x, y, xsize=None, ysize=None, aspect=1.0): if xsize is None and ysize is None: raise ValueError("Must specify at least one of width and height") x, y, aspect = float(x), float(y), float(aspect) if xsize is not None: xsize = float(xsize) if ysize is not None: ysize = float(ysize) if xsize is None: xsize = ysize * aspect if ysize is None: ysize = xsize / aspect xmin, xmax = x - xsize / 2, x + xsize / 2 ymin, ymax = y - ysize / 2, y + ysize / 2 return (xmin, xmax, ymin, ymax)
[ "def __init__(self, w=20, h=10, centerPt=None):\n if not isinstance(w, (int,float)):\n raise TypeError('Width must be a number')\n if w <= 0:\n raise ValueError('The width must be positive.')\n if not isinstance(h, (int,float)):\n raise TypeError('Height must be a number')\n if h <= 0:\n raise ValueError('The height must be positive.')\n if centerPt and not isinstance(centerPt,Point):\n raise TypeError('center must be specified as a Point')\n\n FillableShape.__init__(self) # intentionally not sending center point\n\n if not centerPt:\n centerPt = Point(0,0)\n\n self._transform = _Transformation( (w, 0., 0., h, centerPt.getX(), centerPt.getY()) )", "def setAspectRatio(*args, **kwargs):\n \n pass", "def center( self, center=True ):\n\tself.centerAround = center", "def __init__(self, width, min_long, min_lat, max_long, max_lat):\n self.width = width\n self.min_long = min_long\n self.min_lat = min_lat\n self.max_long = max_long\n self.max_lat = max_lat\n self.height = int(Plot.proportional_height(self.width, (self.max_long-self.min_long), (self.max_lat-self.min_lat)))\n self.im = Image.new(\"RGB\", (self.width, self.height), (255, 255, 255))", "def centered_rect(*args, **kwargs): # real signature unknown; restored from __doc__\n pass", "def aspectRatio(x:int, y:int, w:int=None, h:int=None) -> float:\r\n return w/h==x/y if w and h else (w, (w*(y/x))) if w else ((h*(x/y)), h) if h else x/y", "def __init__(self, width, min_long, min_lat, max_long, max_lat):\n self.width = width\n self.min_long = min_long\n self.min_lat = min_lat\n self.max_long = max_long\n self.max_lat = max_lat\n new_height = int(self.proportional_height(width, (max_lat-min_lat), (max_long-min_long)))\n self.new_height = new_height\n self.image = Image.new(\"RGB\", (width, new_height), (255, 255, 255))", "def set_center(self, x, y):\n self.rect.center = (x, y)", "def center(*args, **kwargs): # real signature unknown; restored from __doc__\n pass", "def FixAspectRatio(widget, aspect_ratio=None, relx=0.5, rely=0.5, anchor='center'):\r\n if aspect_ratio == None: aspect_ratio = float(widget['height']) / float(widget['width'])\r\n\r\n def EnforceAspectRatio(event):\r\n desired_width = event.width\r\n desired_height = int(0.5 + event.width * float(aspect_ratio))\r\n if desired_height > event.height:\r\n desired_height = event.height\r\n desired_width = int(0.5 + event.height / float(aspect_ratio))\r\n widget.place(relx=relx, rely=rely, anchor=anchor, width=desired_width, height=desired_height)\r\n\r\n widget.master.bind(\"<Configure>\", EnforceAspectRatio)\r\n return widget", "def __init__(self, size=10, centerPt=None):\n if not isinstance(size, (int,float)):\n raise TypeError('size must be a number')\n if size <= 0:\n raise ValueError(\"The size must be positive.\")\n if centerPt and not isinstance(centerPt,Point):\n raise TypeError('center must be specified as a Point')\n\n Rectangle.__init__(self, size, size, centerPt)", "def setCenter(self, *args, **kwargs):\n cen = galsim.utilities.parse_pos_args(args, kwargs, 'xcen', 'ycen', integer=True)\n self._shift(cen - self.image.bounds.center())", "def centerOnScreen(self):\n resolution = QtGui.QDesktopWidget().screenGeometry()\n self.move((resolution.width() / 2) - (self.frameSize().width() / 2),\n (resolution.height() / 2) - (self.frameSize().height() / 2))", "def __init__(\n self, x: float, y: float, width: float, height: float, *, padding: float = 0\n ):\n self.x = x - padding\n self.y = y - padding\n self.width = width + padding * 2\n self.height = height + padding * 2\n if self.width < 0 or self.height < 0:\n raise ValueError(f\"Rect must have width and height >= 0: {self}\")", "def resize_bbox(left, top, right, bottom, target_ar=1.):\r\n width = right - left\r\n height = bottom - top\r\n aspect_ratio = height / width\r\n center_x = (left + right) / 2\r\n center_y = (top + bottom) / 2\r\n if aspect_ratio > target_ar:\r\n new_width = height * (1 / target_ar)\r\n new_left = center_x - 0.5 * new_width\r\n new_right = center_x + 0.5 * new_width\r\n new_top = top\r\n new_bottom = bottom\r\n else:\r\n new_height = width * target_ar\r\n new_left = left\r\n new_right = right\r\n new_top = center_y - 0.5 * new_height\r\n new_bottom = center_y + 0.5 * new_height\r\n\r\n d = {\r\n 'bbox': [new_left, new_top, new_right, new_bottom],\r\n 'c': np.array([center_x, center_y]),\r\n 's': np.array([(new_right - new_left) / SIZE, (new_bottom - new_top) / SIZE])\r\n }\r\n return d", "def __init__(self,\n anchor_size,\n scales,\n aspect_ratios,\n stride,\n clip_boxes=False):\n self.anchor_size = anchor_size\n self.scales = scales\n self.aspect_ratios = aspect_ratios\n self.stride = stride\n self.clip_boxes = clip_boxes", "def center_window(self):\n window_width = 1100\n window_height = 850\n\n screen_width = self.winfo_screenwidth()\n screen_height = self.winfo_screenheight()\n\n x = screen_width / 2 - window_width / 2\n y = (screen_height / 2 - window_height / 2) - 40\n self.geometry(\"%dx%d+%d+%d\" % (window_width, window_height, x, y))", "def contained_rect(image_width, image_height, center_point, aspect_ratio):\n width = min(center_point.x, image_width - center_point.x)\n height = min(center_point.y, image_height - center_point.y)\n if (width / height) > aspect_ratio:\n # too wide\n width = aspect_ratio * height\n else:\n height = width / aspect_ratio\n return Point(center_point.x - width, center_point.y - height), Point(center_point.x + width, center_point.y + height)", "def __init__(\n self,\n x: COORDINATE_TYPE = 0,\n y: COORDINATE_TYPE = 0, # pylint: disable=C0103\n width: COORDINATE_TYPE = 0,\n height: COORDINATE_TYPE = 0,\n ):\n if any((isinstance(x, float), isinstance(y, float), isinstance(width, float), isinstance(height, float))):\n self.coreRect = CoreRectF(x, y, width, height)\n else:\n self.coreRect = CoreRectI(x, y, width, height)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new instance with the same midpoint, but with the width/ height divided by `scale`. So `scale=2` will zoom in.
def _with_scaling(self, scale): midx = (self._xmin + self._xmax) / 2 midy = (self._ymin + self._ymax) / 2 xs = (self._xmax - self._xmin) / scale / 2 ys = (self._ymax - self._ymin) / scale / 2 return (midx - xs, midx + xs, midy - ys, midy + ys)
[ "def scale(self, x_scale, y_scale):\n return Size(float(self.width) * x_scale, float(self.height) * y_scale)", "def multiply(self, scale):\n scale = up_tuple(scale, 3)\n c = self.copy()\n c.extent = tuple((l * t, r * t) for (l, r), t in zip(c.extent, scale))\n return c", "def set_scale(self, new_scale: int) -> None:\n self.scale = new_scale\n self.this_sprite_image = pygame.transform.scale(Asteroid.SPRITE_IMAGE, (self.scale, self.scale))\n self.radius = self.scale // 2 - self.scale//32 # Collision radius is 1/32 smaller than the sprite to help player\n self.rect = self.this_sprite_image.get_rect()", "def scale(scale):\n # type: (str/int/float) -> Function\n\n def _scale(img):\n return img * float(scale)\n\n return _scale", "def applyScale(self, scale):\n pass", "def createMagnified(self, scale):\n ret = self.copy()\n ret.applyTransformation(galsim.Ellipse(np.log(scale)))\n return ret", "def scaledBy(self, scale):\n scaled = deepcopy(self)\n \n if type(scaled.value) in (int, float):\n scaled.value *= scale\n elif isinstance(scaled.value, numbers):\n scaled.value.values = tuple(v * scale for v in scaled.value.values)\n\n return scaled", "def set_scale(self, scale):\n def dofancyresize(imgsize, scale):\n if scale < 1.0:\n return True\n else:\n return False\n if scale <= 0.1:\n # Set limit on zooming-out\n return\n\n self.scale = scale\n # Rescale img bitmap\n w, h = self.img_pil.size\n w_scaled, h_scaled = int(round(w*scale)), int(round(h*scale))\n if dofancyresize((w,h), scale):\n rescaled_img = self.img_pil.resize((w_scaled, h_scaled), resample=Image.ANTIALIAS)\n else:\n rescaled_img = self.img_pil.resize((w_scaled, h_scaled))\n self.img_resize_pil = rescaled_img\n self.img_bitmap = util_gui.PilImageToWxBitmap(rescaled_img)\n self._setup_scrollbars()", "def create_scale(self, from_=500, to=100000, resolution=500, **kwargs):\n # if scale_list is None:\n # scale_list = [*range(500, 500, 10000)]\n\n return tk.Scale(\n self,\n from_=from_,\n resolution=resolution,\n to=to,\n variable=self.var_scale,\n # command=self.print_option,\n command=lambda evt: self.update_var(self.var_scale.get()) or self.print_option(),\n orient=tk.HORIZONTAL,\n **kwargs,\n )", "def scale(p, scale):\n return (p[0] * scale[0], p[1] * scale[1])", "def setSegmentScale(self,scale):\n if not scale is None:\n if not isinstance(scale,_dat.Data):\n scale = _dat.Data(scale)\n if isinstance(scale,_scr.Scalar):\n scale = _cmp.MULTIPLY(_cmp.dVALUE(),scale)\n elif isinstance(scale,_arr.Array):\n fac,nn = scale,scale.size\n scale = None\n for n in range(nn-1,-1,-1):\n if n>1:\n next = _cmp.MULTIPLY(_cmp.POWER(_cmp.dVALUE(),n),fac[n])\n if n==1:\n next = _cmp.MULTIPLY(_cmp.dVALUE(),fac[n])\n else:\n next = fac[n]\n if scale is None:\n scale = next\n else:\n scale = _cmp.ADD(scale,next)\n _exc.checkStatus(\n _TreeShr._TreeSetSegmentScale(self.ctx,\n self._nid,\n _dat.Data.byref(scale)))", "def get_scale(self, **kwargs):", "def scale(cls, sx, sy=None, sz=None):\n if sy is None:\n sy = sx\n if sz is None:\n sz = sx\n\n return cls([\n float(sx), 0., 0., 0.,\n 0., float(sy), 0., 0.,\n 0., 0., float(sz), 0.,\n 0., 0., 0., 1.\n ])", "def scale(x, y):\n return affine(x, 0, 0, 0, y, 0)", "def scaleCoords(coord, height, scale):\n return coord[0] * scale, (coord[1] * -1 + height) * scale", "def DrawingScale(self) -> float:", "def newfig(scale=1.0, ratio=0):\n\n #width in x*\\textwidth scale (0,1]\n fig = plt.figure(figsize=figsize(scale, ratio))\n ax = fig.add_subplot(111)\n return fig, ax", "def setScale(self, scale):\n self.__mainAxis.setScale(scale)", "def scale(self, scale):\n self.tf_.scale = scale\n self.sdf.tf_.scale = scale\n if self.mesh_ is not None:\n self.mesh_.tf_.scale = scale", "def setScale(self, *args):\n return _coin.SbMatrix_setScale(self, *args)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new instance translated by this amount. The values are relative to the current size, so `dx==1` means translate one whole rectangle size (to the right).
def with_translation(self, dx, dy): dx = dx * (self._xmax - self._xmin) dy = dy * (self._ymax - self._ymin) return self.with_absolute_translation(dx, dy)
[ "def enlarge(self, dx):\n self.inf -= dx\n self.sup += dx\n return self", "def adjusted(self, dx: COORDINATE_TYPE, dy: COORDINATE_TYPE, dw: COORDINATE_TYPE, dh: COORDINATE_TYPE) -> \"Rect\":\n newRect = Rect()\n newRect.coreRect = self.coreRect.adjusted(dx, dy, dw, dh)\n return newRect", "def move(self, dx, dy):\n if not isinstance(dx, (int,float)):\n raise TypeError('dx must be numeric')\n if not isinstance(dy, (int,float)):\n raise TypeError('dy must be numeric')\n self._transform = _Transformation( (1.,0.,0.,1.,dx,dy)) * self._transform\n self._objectChanged(True,False,False)", "def createShifted(self, dx, dy):\n ret = self.copy()\n ret.applyShift(dx, dy)\n return ret", "def adjust(\n self,\n dx: COORDINATE_TYPE,\n dy: COORDINATE_TYPE,\n dw: COORDINATE_TYPE, # pylint: disable=C0103\n dh: COORDINATE_TYPE,\n ) -> None:\n self.coreRect.adjust(dx, dy, dw, dh)", "def translate(self, dx: float, dy: float, dz: float) -> 'Point':\n self.dxf.location = Vector(dx, dy, dz) + self.dxf.location\n return self", "def translate(self, dx: float, dy: float, dz: float) -> Insert:\n ocs = self.ocs()\n self.dxf.insert = ocs.from_wcs(Vec3(dx, dy, dz) + ocs.to_wcs(self.dxf.insert))\n for attrib in self.attribs:\n attrib.translate(dx, dy, dz)\n return self", "def translate(self, dx, dy):\n self.affine = self.affine * translate(dx,dy)\n self.ps('%f %f translate' % (dx,dy))", "def inset(self, dx, dy=None):\n dy = dy if dy is not None else dx\n origin = IntPoint(y=self.top + dy, x=self.left + dx)\n size = IntSize(height=self.height - dy * 2, width=self.width - dx * 2)\n return IntRect(origin, size)", "def translate(self, delta):\n return Position(self.get_x() + delta[0], self.get_y() + delta[1])", "def offset(self, dx, dy):\n return Location(self.x+dx, self.y+dy)", "def translate(self, dx, dy):\n\t\tincr_xs = map(lambda p: Point(p.x + dx, p.y), self.point_list)\n\t\tincr_ys = map(lambda p: Point(p.x, p.y + dy), incr_xs)\n\t\tself.point_list = incr_ys", "def translate(\n self,\n dx: float = 0.0,\n dy: float = 0.0,\n inplace: bool = False,\n ) -> \"Polygon\":\n polygon = self if inplace else self.copy()\n polygon.points = affinity.translate(self.polygon, xoff=dx, yoff=dy)\n return polygon", "def set_translation(self, dx=0.0, dy=0.0):\n self.dx = dx\n self.dy = dy", "def shift(self, dx, dy=None):\n try: dx, dy = dx # accept an x/y tuple as 1st arg\n except: dy = dx if dy is None else dy # also accept a single float and copy it\n return Region(NSOffsetRect(self, dx, dy))", "def translate(self, dx: float, dy: float, dz: float) -> Ellipse:\n self.dxf.center = Vec3(dx, dy, dz) + self.dxf.center\n # Avoid Matrix44 instantiation if not required:\n if self.is_post_transform_required:\n self.post_transform(Matrix44.translate(dx, dy, dz))\n return self", "def update_pos(self, dx, dy):\n self.x += dx\n self.y += dy\n self.center_x = self.x + self.offset[0]\n self.center_y = self.y + self.offset[1]", "def grow_by(self, factor):\n gx = self.extent_x * factor\n gy = self.extent_y * factor\n return BBox(\n self.minx - gx, self.miny - gy, self.maxx + gx, self.maxy + gy\n )", "def left(self, dx):\n return Location(self.x-dx, self.y)", "def move_rectangle_copy(rect, dx, dy):\n new_rect = copy.deepcopy(rect)\n new_rect.corner.x += dx\n new_rect.corner.y += dy\n return new_rect" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The least x coordinate in tile space we need to cover the region.
def xtilemin(self): return int(2 ** self._zoom * self._extent.xmin)
[ "def LayoutBoundsMinX(self) -> float:", "def get_lowest_x_coordinate(self):\n lowest_x = self.player_tetraminos[0].xcor()\n for tetramino in self.player_tetraminos:\n if (tetramino.xcor() < lowest_x):\n lowest_x = tetramino.xcor()\n return lowest_x", "def min_x(self):\n return self.origin[0]", "def PlotBoundsMinX(self) -> float:", "def find_tile(x,tiling):\n\treturn np.argmin(np.linalg.norm(tiling - x, axis=1))", "def get_min_x(self):\n\n return self.x0", "def _min(self):\n mat = self._unweight()\n mat = self._factorize(mat, self.xdef)\n mat = self._rdc_x(mat, self.xdef)\n if 0 not in self.xdef:\n np.place(mat[:, 0], mat[:, 0] == 0, np.NaN)\n ysects = self._by_ysect(mat, self.ydef)\n return np.expand_dims([np.nanmin(mat[:, 0]) for mat in ysects], 1).T", "def getMinX(self):\n #---+----|----+----|----+----|----+----|----+----|----+----|----+----|\n assert self.getNumSamples() > 0, 'must draw at least one sample before calling getMinX()'\n return SliceSamplerBase.getMinX(self)", "def MaxBoundsX(self) -> float:", "def DisplayMinX(self) -> float:", "def smallest_x(self):\n return min(map(lambda v: v.x, self.vertices)) # was TODO", "def ytilemin(self):\n return int(2 ** self._zoom * self._extent._ymin)", "def test_lower_left_tile(self):\n gmp = GlobalMercatorProfile()\n tile = Tile(0, 1)\n zoom = 1\n result_tile = gmp.lower_left_tile(tile, zoom)\n assert result_tile.tx == tile.tx and \\\n result_tile.ty == tile.ty", "def PrintableBoundsX(self) -> float:", "def get_min_x(sticks: list[Matchstick]) -> float:\n min_x = None\n for stick in sticks:\n if min_x is None or stick.h_pos < min_x:\n min_x = stick.h_pos\n return min_x", "def leftmost(pts):\n return withmin(xcoord, pts)", "def min_x(self):\n return min(point.x for point in self.points)", "def valid_tile(self, x, y):\n\t\treturn x >= 0 and y >= 0 and x < self.width and y < self.height", "def _getTopLeft(self, tileId):\r\n if tileId < 10:\r\n return (longPlus[9-tileId], longPlus[9])\r\n elif tileId < 20:\r\n return (0, longPlus[19-tileId])\r\n elif tileId == 20:\r\n return (0, 0)\r\n elif tileId < 31:\r\n return (longPlus[tileId-21], 0)\r\n elif tileId < 40:\r\n return (longPlus[9], longPlus[tileId-31])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The least y coordinate in tile space we need to cover the region.
def ytilemin(self): return int(2 ** self._zoom * self._extent._ymin)
[ "def y(self):\n return Tile.SIZE * (3 / 2) * self.r", "def MaxBoundsY(self) -> float:", "def LayoutBoundsMinY(self) -> float:", "def min_y(self):\n return self.origin[1]", "def PlotBoundsMinY(self) -> float:", "def get_lowest_y_coordinate(self):\n lowest_y = self.player_tetraminos[0].ycor()\n for tetramino in self.player_tetraminos:\n if tetramino.ycor() < lowest_y:\n lowest_y = tetramino.ycor()\n return lowest_y", "def max_y(self):\n return self.origin[1] + self.size[1]", "def top(self):\n return self.height * Tile.HEIGHT", "def ytilemax(self):\n return int(2 ** self._zoom * self._extent._ymax)", "def get_y(self, layer):\n return 125 + self.row_height * layer", "def top_y(self): \n if self._top_y is None:\n min_y = None\n \n for line_obj in self.line_objs:\n if min_y is None or line_obj.y1 < min_y:\n min_y = line_obj.y1\n \n if min_y is None or line_obj.y2 < min_y:\n min_y = line_obj.y2\n \n if min_y is None:\n self._top_y = None\n else:\n self._top_y = int(min_y)\n \n return self._top_y", "def get_ycoord(self, y):\n return (y - self.ylimits[0]) / self.dy", "def RasterYOrigin(self):\n return self._ImageShape__origin[1]", "def DisplayMinY(self) -> float:", "def LayoutBoundsMaxY(self) -> float:", "def PrintableBoundsY(self) -> float:", "def get_min_y(self):\n\n return self.y0", "def PlotBoundsMaxY(self) -> float:", "def get_base_y(self, row, col, placement='middle'):\n if placement == 'bottom':\n return (self.cell_height + self.ygap) * row\n elif placement == 'top':\n return (self.cell_height + self.ygap) * row + self.cell_height\n else:\n return (self.cell_height + self.ygap) * row + self.cell_height / 2" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The greatest y coordinate in tile space we need to cover the region.
def ytilemax(self): return int(2 ** self._zoom * self._extent._ymax)
[ "def MaxBoundsY(self) -> float:", "def y(self):\n return Tile.SIZE * (3 / 2) * self.r", "def max_y(self):\n return self.origin[1] + self.size[1]", "def LayoutBoundsMaxY(self) -> float:", "def PlotBoundsMaxY(self) -> float:", "def ytilemin(self):\n return int(2 ** self._zoom * self._extent._ymin)", "def DisplayMaxY(self) -> float:", "def get_ycoord(self, y):\n return (y - self.ylimits[0]) / self.dy", "def LayoutBoundsMinY(self) -> float:", "def get_height(self):\n\t\treturn self.y[1] - self.y[0]", "def PrintableBoundsY(self) -> float:", "def get_y(self, layer):\n return 125 + self.row_height * layer", "def get_y(self):\n\n return math.floor(self.position.y)", "def top(self):\n return self.height * Tile.HEIGHT", "def PlotBoundsMinY(self) -> float:", "def get_base_y(self, row, col, placement='middle'):\n if placement == 'bottom':\n return (self.cell_height + self.ygap) * row\n elif placement == 'top':\n return (self.cell_height + self.ygap) * row + self.cell_height\n else:\n return (self.cell_height + self.ygap) * row + self.cell_height / 2", "def max_y(self):\n return max(point.y for point in self.points)", "def obtain_max_region_xy(region_left_up,region_right_down,orthophoto_dir,nadir_image):\n\n pixelPair_left_up=latLonToPixel(img_addr,region_left_up)\n pixelPair_right_down=latLonToPixel(img_addr,region_right_down)\n region_size=pixelPair_right_down-pixelPair_left_up\n max_region=np.max(region_size,axis=0)+[mag*2,mag*2] \n return max_region", "def get_y_top(self) -> float:\n sheets = max(self.deck_sheets, self.flange_sheets)\n return self.web_height + self.thickness * sheets - self.y_bar" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use these settings to assemble tiles into a single image. Will always return an image which is a whole number of tiles width and height; the exact extent will be a subrectangle of the image.
def as_one_image(self, allow_large = False): if not allow_large: self._check_download_size() size = self._tile_provider.tilesize xs = size * (self.xtilemax + 1 - self.xtilemin) ys = size * (self.ytilemax + 1 - self.ytilemin) out = _Image.new("RGBA", (xs, ys)) for x in range(self.xtilemin, self.xtilemax + 1): for y in range(self.ytilemin, self.ytilemax + 1): tile = self._tile_provider.get_tile(x, y, self.zoom) xo = (x - self.xtilemin) * size yo = (y - self.ytilemin) * size out.paste(tile, (xo, yo)) return out
[ "def tile(dimensions, src, hwRatio=0.6667, paddingPercent=0.05, \n borderBg=(255,255,255), pageBg=(0,0,0), outsideBorderPercent=0.1, \n applyCrop=False):\n\n nw, nh = dimensions\n iw, ih = src.size\n\n if applyCrop == True:\n #calculate aspect ratio of image within photo\n #depending on tile orientation, this is not the\n #same as the photo (paper) aspect ratio\n imageRatio = hwRatio * dimensions[0] / dimensions[1]\n src = src.crop(cropimage((iw, ih), imageRatio))\n elif applyCrop == 'SQUARE':\n #print 'square crop requested'\n imageRatio = 1 #square\n src = src.crop(cropimage((iw, ih), imageRatio))\n\n #print iw, ih\n iw, ih = src.size\n #print iw, ih\n\n pp = paddingPercent\n # padding is a fraction of the source image size\n pah = int(math.ceil(pp * iw))\n paw = int(math.ceil(pp * iw))\n # optimal image dimensions\n # img = B1+B2+IMG+B2+B1+B2+IMG+B2+B1\n niw = iw * nw + paw * (4+3*(nw-1))\n nih = ih * nh + pah * (4+3*(nh-1))\n # compute min image size that has the correct AR\n fw, fh = resize((niw, nih), hwRatio)\n #print niw,fw, nih,fh\n # outside border as fraction of the total size\n fw = int(fw * (1+ outsideBorderPercent));\n fh = int(fh * (1+ outsideBorderPercent));\n # calculate offsets for the image to center the tiles in the output image\n woff, hoff = int((fw-niw)/2.0), int((fh-nih)/2.0)\n dest = Image.new('RGB', (fw,fh),pageBg)\n border = Image.new('RGB', (iw+2*paw, ih+2*pah),borderBg)\n for w in range(nw):\n for h in range(nh):\n dx = paw + woff + w * (iw + paw*3)\n dy = pah + hoff + h * (ih + pah*3)\n dest.paste(border, (dx, dy))\n dest.paste(src, (dx+paw, dy+pah))\n return dest", "def generateImage(self, **kwargs):\n\n start_x = kwargs.get('start_x', None)\n start_y = kwargs.get('start_y', None)\n tile_width = kwargs.get('tile_width', 5)\n tile_height = kwargs.get('tile_height', 5)\n\n # Check that we have x and y tile coordinates\n if start_x == None or start_y == None :\n start_x, start_y = self.getXY()\n\n # Determine the size of the image\n width, height = 256 * tile_width, 256 * tile_height\n\n #Create a new image of the size require\n map_img = Image.new('RGB', (width,height))\n sat_img = Image.new('RGB', (width,height))\n\n for x in range(0, tile_width):\n for y in range(0, tile_height) :\n if True:\n if args.label:\n # Store the image with labels\n url = 'https://mt0.google.com/vt/lyrs=y&?x=' + str(start_x + x) + '&y=' + str(start_y + y) + '&z=' + str( self._zoom)\n if args.debug: print(url)\n else:\n url = 'https://mt0.google.com/vt/lyrs=s&?x=' + str(start_x + x) + '&y=' + str(start_y + y) + '&z=' + str( self._zoom)\n if args.debug: print(url)\n current_tile = str(x)+'-'+str(y)\n urllib.request.urlretrieve(url, current_tile)\n\n im = Image.open(current_tile)\n sat_img.paste(im, (x*256, y*256))\n\n os.remove(current_tile)\n\n\n if True:\n if args.label:\n url = 'https://mt0.google.com/vt?x='+str(start_x+x)+'&y='+str(start_y+y)+'&z='+str(self._zoom)\n if args.debug: print(url)\n else:\n url = 'https://mt0.google.com/vt?x='+str(start_x+x)+'&y='+str(start_y+y)+'&z='+str(self._zoom) # work needs to be done\n if args.debug: print(url)\n\n current_tile = str(x)+'-'+str(y)\n urllib.request.urlretrieve(url, current_tile)\n\n im = Image.open(current_tile)\n map_img.paste(im, (x*256, y*256))\n\n os.remove(current_tile)\n\n return map_img, sat_img", "def doTiling(tiling, elms, path=None, size=256, mask=15, base=\"%s\", imagesTo=False):\n\tpath = defaultPath\n\tresults = \"Results[%d]\" % (size)\n\tjio.File(path, results).mkdirs()\n\timgFiles = []\n\tfor elm in elms:\n\t\timgFiles.append((\"%s[%d].png\" % (base % element(elm), mask), size))\n\timgFiles.append((\"Analytic Total[%d].png\" % mask, size))\n\timgFiles.append((\"K-ratio map[%d].png\" % mask, size))\n\tif imagesTo:\n\t\timgFiles.append((\"Image[0][Ch1].png\", 1024,))\n\t\timgFiles.append((\"Image[0][Ch2].png\", 1024,))\n\tfor baseImg, imgDim in imgFiles:\n\t\tnullImage = \"%s/null%d.png\" % (nullImagePath, imgDim)\n\t\tr, c = -1, -1\n\t\trows, imgs = [], None\n\t\tfor i, tile in enumerate(tiling):\n\t\t\tif terminated:\n\t\t\t\tbreak\n\t\t\tti = tile.getTileIndex()\n\t\t\tif ti[0] <> r:\n\t\t\t\tif imgs:\n\t\t\t\t\trows.append(imgs)\n\t\t\t\timgs = []\n\t\t\t\tr = ti[0]\n\t\t\t\tc = -1\n\t\t\tfor col in range(c, ti[1] - 1):\n\t\t\t\timgs.append(nullImage)\n\t\t\taddThis = \"%s/Tile[%s]/%s\" % (path, tile.getIndex(), baseImg)\n\t\t\timgs.append((addThis if jio.File(addThis).exists() else nullImage))\n\t\t\tc = ti[1]\n\t\tif imgs:\n\t\t\trows.append(imgs)\n\t\tmaxLen = 0\n\t\tfor row in rows:\n\t\t\tmaxLen = max(maxLen, len(row))\n\t\tfor row in rows:\n\t\t\twhile len(row) < maxLen:\n\t\t\t\trow.append(nullImage)\n\t\tfinal = \"\\\"%s\\\\montage.exe\\\" -tile 1x%d -geometry +0+0 \" % (IMAGE_MAGICK, len(rows))\n\t\tfor i, row in enumerate(rows):\n\t\t\ttmp = \"\"\n\t\t\tfor img in row:\n\t\t\t\ttmp = \"\\\"%s\\\" %s\" % (img, tmp)\n\t\t\ttmp = \"\\\"%s\\\\montage.exe\\\" -tile %dx1 -geometry +0+0 %s \\\"%s\\\\row[%d].png\\\"\" % (IMAGE_MAGICK, maxLen, tmp, path, i)\n\t\t\tprint tmp\n\t\t\texecute(tmp.replace(\"/\", \"\\\\\"), True)\n\t\t\t# result = \"%s%s\\n\" % (result, tmp.replace(\"/\",\"\\\\\"))\n\t\t\tfinal = \"%s \\\"%s\\\\row[%d].png\\\"\" % (final, path, i)\n\t\tfinal = \"%s \\\"%s\\\\%s\\\\%s\\\"\" % (final, path, results, baseImg)\n\t\tprint final\n\t\texecute(final.replace(\"/\", \"\\\\\"), True)\n\t\t# result = \"%s%s\\n\" % (result, final.replace(\"/\",\"\\\\\"))", "def make_tiles(self, x_size, y_size, x_step, y_step, output_path, verbose=True):\n\n fig, ax = self.make_figure()\n x = self.doc.header['$EXTMIN'][0]\n y = self.doc.header['$EXTMIN'][1]\n\n # Slide until the bottom edge of the window is above the top of\n # the elements in the doc\n while y < self.doc.header['$EXTMAX'][1]:\n\n # Get window into document\n xlim = (x, x + x_size)\n ylim = (y, y + y_size)\n ax.set_xlim(xlim)\n ax.set_ylim(ylim)\n\n # to check if image is empty\n # import cv2\n # im = cv2.imread('2.jpg')\n # if im is None:\n # Print(\"Image is empty\")\n\n # to get percentage of empty space in image\n # from PIL import Image\n # image = Image.open(\"pepper.png\")\n # bg = image.getpixel((0,0))\n # width, height = image.size\n # bg_count = next(n for n,c in image.getcolors(width*height) if c==bg)\n # img_count = width*height - bg_count\n # img_percent = img_count*100.0/width/height\n\n filename = \"%s_x_%s_%s_y_%s_%s.png\" % (\"tile_\", xlim[0], xlim[1], ylim[0], ylim[1])\n if verbose:\n print('Writing: %s' % filename)\n fig.savefig(os.path.join(output_path, filename), dpi=self.dpi)\n\n # Step\n x += x_step\n if x > self.doc.header['$EXTMAX'][0]:\n x = self.doc.header['$EXTMIN'][0]\n y += y_step", "def make_tiles(self):\n num_tiles = self._puzzle_height * self._puzzle_width\n #subsurface is a ract(left, top, width, height\n \n for idx in xrange(num_tiles):\n self._tiles.append(self._tiles_sprite.subsurface(\n (idx * TILE_SIZE, 0, TILE_SIZE, TILE_SIZE)))", "def image(self):\r\n px_width, px_height = self.tile_canvas.size\r\n\r\n sw_big, ne_big = self.tile_bounds\r\n sw, ne = self.bounds\r\n\r\n lat_rng = ne_big.lat - sw_big.lat\r\n lng_rng = ne_big.lng - sw_big.lng\r\n\r\n lat_lower = sw.lat - sw_big.lat\r\n lat_upper = ne.lat - sw_big.lat\r\n\r\n lng_left = sw.lng - sw_big.lng\r\n lng_right = ne.lng - sw_big.lng\r\n\r\n lower = px_height - int(lat_lower / lat_rng * px_height)\r\n upper = px_height - int(lat_upper / lat_rng * px_height)\r\n left = int(lng_left / lng_rng * px_width)\r\n right = int(lng_right / lng_rng * px_width)\r\n\r\n crop_box = left, upper, right, lower\r\n logger.debug(f'crop_box:{crop_box}')\r\n\r\n return self.tile_canvas.crop(box=crop_box)", "def generate_base_tiles(self):\n\n print 'Generating Base Tiles:'\n\n if self.options.verbose:\n\n # mx, my = self.out_gt[0], self.out_gt[3] # OriginX, OriginY\n # px, py = self.mercator.MetersToPixels( mx, my, self.tmaxz)\n # print \"Pixel coordinates:\", px, py, (mx, my)\n\n print ''\n print 'Tiles generated from the max zoom level:'\n print '----------------------------------------'\n print ''\n\n # Set the bounds\n\n (tminx, tminy, tmaxx, tmaxy) = self.tminmax[self.tmaxz]\n\n # Just the center tile\n # tminx = tminx+ (tmaxx - tminx)/2\n # tminy = tminy+ (tmaxy - tminy)/2\n # tmaxx = tminx\n # tmaxy = tminy\n\n ds = self.out_ds\n tilebands = self.dataBandsCount + 1\n querysize = self.querysize\n\n if self.options.verbose:\n print ('dataBandsCount: ', self.dataBandsCount)\n print ('tilebands: ', tilebands)\n\n # print tminx, tminy, tmaxx, tmaxy\n\n tcount = (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy - tminy))\n\n # print tcount\n\n ti = 0\n\n tz = self.tmaxz\n yrange = range(tmaxy, tminy - 1, -1)\n if self.options.leaflet:\n yrange = range(tminy, tmaxy + 1)\n\n for ty in yrange:\n for tx in range(tminx, tmaxx + 1):\n\n if self.stopped:\n break\n ti += 1\n tilefilename = os.path.join(self.output, str(tz),\n str(tx), '%s.%s' % ((2**tz-1-ty), self.tileext))\n if self.options.verbose:\n print (ti, '/', tcount, tilefilename) # , \"( TileMapService: z / x / y )\"\n\n if self.options.resume and os.path.exists(tilefilename):\n if self.options.verbose:\n print 'Tile generation skiped because of --resume'\n else:\n self.progressbar(ti / float(tcount))\n continue\n\n # Create directories for the tile\n\n if not os.path.exists(os.path.dirname(tilefilename)):\n os.makedirs(os.path.dirname(tilefilename))\n\n if self.options.profile == 'mercator':\n\n # Tile bounds in EPSG:900913\n\n b = self.mercator.TileBounds(tx, ty, tz)\n elif self.options.profile == 'geodetic':\n b = self.geodetic.TileBounds(tx, ty, tz)\n\n # print \"\\tgdalwarp -ts 256 256 -te %s %s %s %s %s %s_%s_%s.tif\" % ( b[0], b[1], b[2], b[3], \"tiles.vrt\", tz, tx, ty)\n\n # Don't scale up by nearest neighbour, better change the querysize\n # to the native resolution (and return smaller query tile) for scaling\n\n if self.options.profile in ('mercator', 'geodetic'):\n (rb, wb) = self.geo_query(ds, b[0], b[3], b[2],\n b[1])\n nativesize = wb[0] + wb[2] # Pixel size in the raster covering query geo extent\n if self.options.verbose:\n print ('\\tNative Extent (querysize',\n nativesize, '): ', rb, wb)\n\n # Tile bounds in raster coordinates for ReadRaster query\n\n (rb, wb) = self.geo_query(\n ds,\n b[0],\n b[3],\n b[2],\n b[1],\n querysize=querysize,\n )\n\n (rx, ry, rxsize, rysize) = rb\n (wx, wy, wxsize, wysize) = wb\n else:\n\n # 'raster' profile:\n\n tsize = int(self.tsize[tz]) # tilesize in raster coordinates for actual zoom\n xsize = self.out_ds.RasterXSize # size of the raster in pixels\n ysize = self.out_ds.RasterYSize\n if tz >= self.nativezoom:\n querysize = self.tilesize # int(2**(self.nativezoom-tz) * self.tilesize)\n\n rx = tx * tsize\n rxsize = 0\n if tx == tmaxx:\n rxsize = xsize % tsize\n if rxsize == 0:\n rxsize = tsize\n\n rysize = 0\n if ty == tmaxy:\n rysize = ysize % tsize\n if rysize == 0:\n rysize = tsize\n if self.options.leaflet:\n ry = ty * tsize\n else:\n ry = ysize - ty * tsize - rysize\n\n (wx, wy) = (0, 0)\n (wxsize, wysize) = (int(rxsize / float(tsize)\n * self.tilesize), int(rysize / float(tsize)\n * self.tilesize))\n if not self.options.leaflet:\n if wysize != self.tilesize:\n wy = self.tilesize - wysize\n\n if self.options.verbose:\n print ('\\tReadRaster Extent: ', (rx, ry, rxsize,\n rysize), (wx, wy, wxsize, wysize))\n\n # Query is in 'nearest neighbour' but can be bigger in then the tilesize\n # We scale down the query to the tilesize by supplied algorithm.\n\n # Tile dataset in memory\n\n dstile = self.mem_drv.Create('', self.tilesize,\n self.tilesize, tilebands)\n data = ds.ReadRaster(\n rx,\n ry,\n rxsize,\n rysize,\n wxsize,\n wysize,\n band_list=list(range(1, self.dataBandsCount + 1)),\n )\n alpha = self.alphaband.ReadRaster(\n rx,\n ry,\n rxsize,\n rysize,\n wxsize,\n wysize,\n )\n\n if self.tilesize == querysize:\n\n # Use the ReadRaster result directly in tiles ('nearest neighbour' query)\n dstile.WriteRaster(\n wx,\n wy,\n wxsize,\n wysize,\n data,\n band_list=list(range(1, self.dataBandsCount\n + 1)),\n )\n dstile.WriteRaster(\n wx,\n wy,\n wxsize,\n wysize,\n alpha,\n band_list=[tilebands],\n )\n else:\n \n # Note: For source drivers based on WaveLet compression (JPEG2000, ECW, MrSID)\n # the ReadRaster function returns high-quality raster (not ugly nearest neighbour)\n # TODO: Use directly 'near' for WaveLet files\n # Big ReadRaster query in memory scaled to the tilesize - all but 'near' algo\n\n dsquery = self.mem_drv.Create('', querysize,\n querysize, tilebands)\n\n # TODO: fill the null value in case a tile without alpha is produced (now only png tiles are supported)\n # for i in range(1, tilebands+1):\n # dsquery.GetRasterBand(1).Fill(tilenodata)\n\n dsquery.WriteRaster(\n wx,\n wy,\n wxsize,\n wysize,\n data,\n band_list=list(range(1, self.dataBandsCount\n + 1)),\n )\n dsquery.WriteRaster(\n wx,\n wy,\n wxsize,\n wysize,\n alpha,\n band_list=[tilebands],\n )\n\n # print('-'+tilefilename+'-')\n self.scale_query_to_tile(dsquery, dstile,\n tilefilename)\n del dsquery\n\n del data\n\n if self.options.resampling != 'antialias':\n\n # Write a copy of tile to png/jpg\n\n self.out_drv.CreateCopy(tilefilename, dstile,\n strict=0)\n\n del dstile\n\n # Create a KML file for this tile.\n\n if self.kml:\n kmlfilename = os.path.join(self.output, str(tz),\n str(tx), '%d.kml' % ty)\n if not self.options.resume \\\n or not os.path.exists(kmlfilename):\n f = open(kmlfilename, 'w')\n f.write(self.generate_kml(tx, ty, tz))\n f.close()\n\n if not self.options.verbose:\n self.progressbar(ti / float(tcount))", "def generate_overview_tiles(self):\n\n print 'Generating Overview Tiles:'\n\n tilebands = self.dataBandsCount + 1\n\n # Usage of existing tiles: from 4 underlying tiles generate one as overview.\n\n tcount = 0\n for tz in range(self.tmaxz - 1, self.tminz - 1, -1):\n (tminx, tminy, tmaxx, tmaxy) = self.tminmax[tz]\n tcount += (1 + abs(tmaxx - tminx)) * (1 + abs(tmaxy\n - tminy))\n\n ti = 0\n\n # querysize = tilesize * 2\n\n for tz in range(self.tmaxz - 1, self.tminz - 1, -1):\n (tminx, tminy, tmaxx, tmaxy) = self.tminmax[tz]\n yrange = range(tmaxy, tminy - 1, -1)\n if self.options.leaflet:\n yrange = range(tminy, tmaxy + 1)\n for ty in yrange:\n for tx in range(tminx, tmaxx + 1):\n\n if self.stopped:\n break\n\n ti += 1\n tilefilename = os.path.join(self.output, str(tz),\n str(tx), '%s.%s' % (2**tz-1-ty, self.tileext))\n\n if self.options.verbose:\n print (ti, '/', tcount, tilefilename) # , \"( TileMapService: z / x / y )\"\n\n if self.options.resume \\\n and os.path.exists(tilefilename):\n if self.options.verbose:\n print 'Tile generation skiped because of --resume'\n else:\n self.progressbar(ti / float(tcount))\n continue\n\n # Create directories for the tile\n\n if not os.path.exists(os.path.dirname(tilefilename)):\n os.makedirs(os.path.dirname(tilefilename))\n\n dsquery = self.mem_drv.Create('', 2\n * self.tilesize, 2 * self.tilesize,\n tilebands)\n\n # TODO: fill the null value\n # for i in range(1, tilebands+1):\n # dsquery.GetRasterBand(1).Fill(tilenodata)\n\n dstile = self.mem_drv.Create('', self.tilesize,\n self.tilesize, tilebands)\n\n # TODO: Implement more clever walking on the tiles with cache functionality\n # probably walk should start with reading of four tiles from top left corner\n # Hilbert curve\n\n children = []\n\n # Read the tiles and write them to query window\n\n for y in range(2 * ty, 2 * ty + 2):\n for x in range(2 * tx, 2 * tx + 2):\n (minx, miny, maxx, maxy) = self.tminmax[tz\n + 1]\n if x >= minx and x <= maxx and y >= miny \\\n and y <= maxy:\n # print(os.path.join(self.output,str(tz + 1), str(x), '%s.%s'% (2**(tz+1)-1-y, self.tileext)))\n dsquerytile = \\\n gdal.Open(os.path.join(self.output,\n str(tz + 1), str(x), '%s.%s'\n % (2**(tz+1)-1-y, self.tileext)),\n gdal.GA_ReadOnly)\n\n if self.options.leaflet:\n if ty:\n tileposy = y % (2 * ty) \\\n * self.tilesize\n elif ty == 0 and y == 1:\n tileposy = self.tilesize\n else:\n tileposy = 0\n else:\n if ty == 0 and y == 1 or ty != 0 \\\n and y % (2 * ty) != 0:\n tileposy = 0\n else:\n tileposy = self.tilesize\n\n if tx:\n tileposx = x % (2 * tx) \\\n * self.tilesize\n elif tx == 0 and x == 1:\n tileposx = self.tilesize\n else:\n tileposx = 0\n dsquery.WriteRaster(\n tileposx,\n tileposy,\n self.tilesize,\n self.tilesize,\n dsquerytile.ReadRaster(0, 0,\n self.tilesize, self.tilesize),\n band_list=list(range(1, tilebands\n + 1)),\n )\n children.append([x, y, tz + 1])\n\n self.scale_query_to_tile(dsquery, dstile,\n tilefilename)\n\n # Write a copy of tile to png/jpg\n\n if self.options.resampling != 'antialias':\n\n # Write a copy of tile to png/jpg\n\n self.out_drv.CreateCopy(tilefilename, dstile,\n strict=0)\n\n if self.options.verbose:\n print (\n '\\tbuild from zoom',\n tz + 1,\n ' tiles:',\n (2 * tx, 2 * ty),\n (2 * tx + 1, 2 * ty),\n (2 * tx, 2 * ty + 1),\n (2 * tx + 1, 2 * ty + 1),\n )\n\n # Create a KML file for this tile.\n\n if self.kml:\n f = open(os.path.join(self.output,\n '%d/%d/%d.kml' % (tz, tx, ty)), 'w')\n f.write(self.generate_kml(tx, ty, tz, children))\n f.close()\n\n if not self.options.verbose:\n self.progressbar(ti / float(tcount))", "def tile_canvas(self):\r\n if not self._tile_canvas:\r\n\r\n # make blank tile_canvas\r\n self._tile_canvas = Image.new(\"RGBA\", (\r\n (np.ptp(self._X) + 1) * TILE_SIZE,\r\n (np.ptp(self._Y) + 1) * TILE_SIZE)) # (x,y) peak to peak = number of tiles * TILE_SIZE\r\n logger.debug(f\"tile_canvas size:{self._tile_canvas.size}\")\r\n\r\n # paint tile_canvas from tiles\r\n for tile in self.tiles:\r\n px_x = (tile.x - min(self._X)) * TILE_SIZE\r\n px_y = (tile.y - min(self._Y)) * TILE_SIZE\r\n self._tile_canvas.paste(tile.img, (px_x, px_y))\r\n\r\n return self._tile_canvas", "def download_tile_tms(tile, imagery, folder, zoom, supertile):\n\n image_format = get_image_format(imagery['url'])\n r = requests.get(url(tile.split('-'), imagery['url']))\n tile_img = op.join(folder, '{}{}'.format(tile, image_format))\n tile = tile.split('-')\n\n #super-tile special case\n if supertile:\n new_zoom = zoom + 1 #get zoom from ml-enabler database\n # get children\n child_tiles = children(int(tile[0]), int(tile[1]), int(tile[2]), zoom=new_zoom)\n child_tiles.sort()\n\n new_dim = 256 * (2 * (new_zoom - zoom))\n\n w_lst = []\n for i in range (2 * (new_zoom - zoom)):\n for j in range(2 * (new_zoom - zoom)):\n window = Window(i * 256, j * 256, 256, 256)\n w_lst.append(window)\n\n # request children\n with rasterio.open(tile_img, 'w', driver='jpeg', height=new_dim,\n width=new_dim, count=3, dtype=rasterio.uint8) as w:\n for num, t in enumerate(child_tiles):\n t = [str(t[0]), str(t[1]), str(t[2])]\n r = requests.get(url(t, imagery['url']))\n img = np.array(Image.open(io.BytesIO(r.content)), dtype=np.uint8)\n try:\n img = img.reshape((256, 256, 3)) # 4 channels returned from some endpoints, but not all\n except ValueError:\n img = img.reshape((256, 256, 4))\n img = img[:, :, :3]\n img = np.rollaxis(img, 2, 0)\n w.write(img, window=w_lst[num])\n else:\n r = requests.get(url(tile, imagery['url']))\n with open(tile_img, 'wb')as w:\n w.write(r.content)\n return tile_img", "def _prep_tiles(self):\r\n # todo: write this. expected output is a flat iterable.\r\n # todo: explore turning flatten() into generator\r\n\r\n if self._bounds and not self._tiles:\r\n # build tile list from bounds\r\n self._zoom = self._detail + Pin.find_span_zoom(self._bounds)\r\n self._tiles = Tile.from_pins(self._bounds, self._zoom) # get the tiles covering the span\r\n Tile.new_tile_q.join() # wait for tiles to arrive\r\n\r\n if self._tiles and not self._bounds:\r\n sw_pin = Pin.from_tile_coord(np.min(self._X), np.max(self._Y) + 1, self._zoom)\r\n ne_pin = Pin.from_tile_coord(np.max(self._X) + 1, np.min(self._Y), self._zoom)\r\n self._bounds = sw_pin, ne_pin\r\n\r\n assert all(isinstance(t, Tile) for t in self._tiles), f'{self._tiles}' # all objects must be tiles\r\n self._X, self._Y, zooms = np.asarray(list(self._tiles)).T # asarray won't work on sets. ugh.\r\n assert all(zooms == zooms[0]) # all zooms must be the same\r\n self._zoom = zooms[0]", "def test_get_more_tiles(self):\n get_map(2016, range(75078, 75080), range(74956, 74957), \".\")\n self.assertEqual(os.path.exists(\"../74956_75078.png\"), True)\n self.assertEqual(os.path.exists(\"../74956_75079.png\"), True)\n img1 = Image.open(\"../74956_75078.png\")\n img2 = Image.open(\"../74956_75079.png\")\n img1.verify()\n img2.verify()\n os.remove(\"../74956_75078.png\")\n os.remove(\"../74956_75079.png\")", "def stich_tiles(panoid, tiles, directory, final_directory):\n\n tile_width = 512\n tile_height = 512\n\n panorama = Image.new('RGB', (26*tile_width, 13*tile_height))\n\n for x, y, fname, url in tiles:\n\n fname = directory + \"/\" + fname\n tile = Image.open(fname)\n\n panorama.paste(im=tile, box=(x*tile_width, y*tile_height))\n\n del tile\n\n# print fname\n\n panorama.save(final_directory + (\"/%s.jpg\" % panoid))\n del panorama", "def make_image(tilestates: List[TileState]) -> List[str]:\n data = []\n\n width = int(len(tilestates) ** 0.5)\n tile_width = len(tilestates[0].data[0])\n\n for tile_row in range(0, width):\n tile_data = [\n t.data for t in tilestates[tile_row * width : tile_row * width + width]\n ]\n\n for i in range(1, tile_width - 1):\n row = \"\"\n for td in tile_data:\n row += td[i][1:-1]\n data.append(row)\n\n return data", "def init_tiles(self):\n for simple in [Game.TILE_SIMPLE_DOT, Game.TILE_SIMPLE_BAMBOO, Game.TILE_SIMPLE_CHAR]:\n for value in range(Game.SIZE_SIMPLE):\n self.tiles += [(simple, value) for i in range(4)]\n\n for value in ['east', 'west', 'north', 'south']:\n self.tiles += [(Game.TILE_HONOR_WIND, value) for i in range(4)]\n self.tiles += [(Game.TILE_BONUS_FLOWER, value)]\n self.tiles += [(Game.TILE_BONUS_SEASON, value)]\n\n for value in ['red', 'green', 'white']:\n self.tiles += [(Game.TILE_HONOR_DRAGON, value) for i in range(4)]\n\n random.shuffle(self.tiles)\n return", "def buildTiles(self, items, attributes):\n matrix = {}\n\n def addItem(tx, ty, px, py, **itemparams):\n if '{}|{}'.format(tx, ty) not in matrix:\n matrix['{}|{}'.format(tx, ty)] = []\n matrix['{}|{}'.format(tx, ty)].append([px, py, itemparams])\n\n params = {}\n\n for zoom in self.ZOOMLEVELS:\n\n if not os.path.exists('{}/{}'.format(self.DESTPATH, zoom)): # create directory\n os.makedirs('{}/{}'.format(self.DESTPATH, zoom))\n\n for item in items:\n _last = None\n for node in item.parameters['nodes']:\n coord = deg2num(float(node['lat']), float(node['lon']), zoom)\n\n if _last is not None:\n\n if _last[0] <= coord[0]: # eval tiles in x direction\n dx = range(_last[0], coord[0] + 1)\n else:\n dx = range(_last[0], coord[0] - 1, -1)\n\n if _last[1] <= coord[1]: # eval tiles in y direction\n dy = range(_last[1], coord[1] + 1)\n else:\n dy = range(_last[1], coord[1] - 1, -1)\n\n for x in dx: # loop through tiles\n for y in dy:\n lstart = (_last[2] + (_last[0] - x) * 256, _last[3] + (_last[1] - y) * 256) # start point\n lend = (coord[2] + (coord[0] - x) * 256, coord[3] + (coord[1] - y) * 256) # end point\n\n if os.path.exists('{}/{}/{}-{}.png'.format(self.DESTPATH, zoom, x, y)):\n img = Image.open('{}/{}/{}-{}.png'.format(self.DESTPATH, zoom, x, y))\n else:\n img = Image.new('RGBA', (256, 256))\n draw = ImageDraw.Draw(img)\n\n draw.line([lstart, lend], fill=self.LINECOLOR, width=(zoom - 15) * 2) # draw line\n img.save('{}/{}/{}-{}.png'.format(self.DESTPATH, zoom, x, y))\n\n _last = coord", "def test_tiler_make_tiles(create_data):\n\n data = Tiler.make_tiles(\n image_path=create_data['tiffile'],\n link_base=create_data['out_path'],\n output_folder=create_data['out_path'],\n zoom=[7, 8],\n quiet=False,\n nodata=[0],\n # convert=True\n )\n\n assert(os.path.isfile(create_data['tiffile']))\n assert(len(data) == 2)\n assert(data[0] == create_data['out_path_check'])\n assert(os.path.exists(data[0]))\n assert(os.path.isfile(data[1]))\n\n zoom_7 = os.path.join(data[0], '7')\n zoom_8 = os.path.join(data[0], '8')\n zoom_9 = os.path.join(data[0], '9')\n\n assert(os.path.exists(zoom_7))\n assert(os.path.exists(zoom_8))\n assert(not os.path.exists(zoom_9))", "def load_tile(path, tile_size):\n img = pyglet.resource.image(path)\n img.width = tile_size\n img.height = tile_size\n return img", "def populate_extractor(self, file_name, tile_size):\n png_file = open(file_name)\n if not png_file:\n print('TileExtractor: No file at path {0}!'.format(file_name))\n return\n\n png_reader = png.Reader(file=png_file)\n image_data = png_reader.asRGB8()\n size = None\n iter_map = None\n\n # search the returned tuple for important information\n for elm in image_data:\n if isinstance(elm, itertools.imap):\n iter_map = elm\n elif isinstance(elm, dict) and elm.get('size'):\n size = elm['size']\n\n if size is None or size[0] % tile_size != 0 or size[1] % tile_size != 0:\n print('Invalid image size! {0}'.format(size))\n return\n\n print('Valid image size: {0} for tile size ({1}), extracting unique tiles...'.format(size, tile_size))\n\n # See comment at top of page to understand structure layout of tiles\n self.tiles = []\n\n # This is an index list of the used tiles in order so we can export a tile map file to use in tiled.\n # Note: Indices are 1 based so the +1s are intentional\n self.tile_indices = []\n\n self.tile_size = tile_size\n\n self.tiles_width = int(size[0] / tile_size)\n self.tiles_height = int(size[1] / tile_size)\n\n cur_slice_y = 0\n work_percentage_stack = []\n \"\"\"\n We populate the tile list like this:\n 1) grab tile_size rows in an iterator slice\n 2) grab (width / tile_size) tiles in that slice\n 3) compare new tiles vs current tiles and throw away duplicates\n 4) grab next slice\n \"\"\"\n while cur_slice_y < size[1]:\n # Initialize tile list\n new_tiles = [[] for _ in range(0, size[0] / self.tile_size)]\n\n # We go through each row of pixels grabbing tile_size iterator slices\n it_slice = itertools.islice(iter_map, 0, self.tile_size)\n\n # Run through every tile_size * tile_size tile\n for elm in it_slice:\n cur_new_tile = 0\n cur_slice_x = 0\n while cur_slice_x < size[0]:\n # Get the row of pixels [R,G,B, R,G,B, R,G,B]\n tile_row = list(elm[cur_slice_x * 3:cur_slice_x * 3 + self.tile_size * 3])\n\n # Append the row to one of the new tiles\n new_tiles[cur_new_tile].append(tile_row)\n\n # Iterate to next section of row\n cur_slice_x += self.tile_size\n cur_new_tile += 1\n\n num_new_tiles = 0\n # Go through new tile list and see if any of the tiles are duplicates.\n # If there are duplicates, they are not added to the master list of tiles.\n for new_tile in new_tiles:\n found_tile = False\n for master_tile_index in range(0, len(self.tiles)):\n if self.compare_tiles(self.tiles[master_tile_index], new_tile):\n self.tile_indices.append(master_tile_index + 1)\n found_tile = True\n break\n\n if not found_tile:\n self.tiles.append(copy.deepcopy(new_tile))\n self.tile_indices.append(len(self.tiles))\n num_new_tiles += 1\n\n # print('{0} tiles added for row {1}. Tile count = {2}'.format(num_new_tiles,\n # cur_slice_y / self.tile_size, len(self.tiles)))\n cur_slice_y += self.tile_size\n self.print_tile_work_percentage(cur_slice_y, size[1], work_percentage_stack)\n print('') # new line after percentage indicator\n # Close the file, we have extracted what we need\n png_file.close()" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use these settings to plot the tiles to a `matplotlib` axes. This
def plot(self, ax, allow_large = False, **kwargs): tile = self.as_one_image(allow_large) scale = 2 ** self.zoom x0, y0 = self.extent.project(self.xtilemin / scale, self.ytilemin / scale) x1, y1 = self.extent.project((self.xtilemax + 1) / scale, (self.ytilemax + 1) / scale) ax.imshow(tile, interpolation="lanczos", extent=(x0,x1,y1,y0), **kwargs) ax.set(xlim = self.extent.xrange, ylim = self.extent.yrange)
[ "def heatmap(self):\n plt.imshow(self.M)\n plt.yticks([])\n plt.xticks(np.arange(self.size[1]))\n plt.show()", "def visualise_grid(self, *args, **kwargs):\n\n plt.figure(figsize=(20,15))\n sns.heatmap(self.grid, xticklabels=False, yticklabels=False,\n *args, **kwargs)", "def plotPanel(xmin, xmax, yMinSets, yMaxSets, xSets, ySets, xname, yname, entLabels, ofile, mksize=1.0, lwidth=1.5):\n#\n#--- close all opened plot\n#\n plt.close('all')\n#\n#---- set a few parameters\n#\n mpl.rcParams['font.size'] = 9\n props = font_manager.FontProperties(size=9)\n plt.subplots_adjust(hspace=0.08)\n\n tot = len(entLabels)\n#\n#--- start plotting each data\n#\n for i in range(0, len(entLabels)):\n axNam = 'ax' + str(i)\n#\n#--- setting the panel position\n#\n j = i + 1\n if i == 0:\n line = str(tot) + '1' + str(j)\n else:\n line = str(tot) + '1' + str(j) + ', sharex=ax0'\n line = str(tot) + '1' + str(j)\n\n exec(\"%s = plt.subplot(%s)\" % (axNam, line))\n exec(\"%s.set_autoscale_on(False)\" % (axNam))\n exec(\"%s.set_xbound(xmin ,xmax)\" % (axNam))\n\n exec(\"%s.set_xlim(left=%s, right=%s, auto=False)\" % (axNam, str(xmin), str(xmax)))\n exec(\"%s.set_ylim(bottom=%s, top=%s, auto=False)\" % (axNam, str(yMinSets[i]), str(yMaxSets[i])))\n\n xdata = xSets[i]\n ydata = ySets[i]\n#\n#---- actual data plotting\n#\n p, = plt.plot(xdata, ydata, color=colorList[i], marker='.', markersize=mksize, lw = lwidth)\n#\n#--- add legend\n#\n leg = legend([p], [entLabels[i]], prop=props, loc=2)\n leg.get_frame().set_alpha(0.5)\n\n exec(\"%s.set_ylabel(yname, size=8)\" % (axNam))\n#\n#--- add x ticks label only on the last panel\n#\n for i in range(0, tot):\n ax = 'ax' + str(i)\n\n if i != tot-1: \n line = eval(\"%s.get_xticklabels()\" % (ax))\n for label in line:\n label.set_visible(False)\n else:\n pass\n xlabel(xname)\n#\n#--- set the size of the plotting area in inch (width: 10.0in, height 2.08in x number of panels)\n#\n fig = matplotlib.pyplot.gcf()\n height = (2.00 + 0.08) * tot\n fig.set_size_inches(10.0, height)\n#\n#--- save the plot in png format\n#\n plt.savefig(ofile, format='png', dpi=200)", "def generateGridSettings(self):\n tiles = TiledRenderer(self.window, self.map)\n mw = tiles.tmx_data.width\n mh = tiles.tmx_data.height\n self.grid_dim = (mw, mh)\n w, h, gm = self.window.width, self.window.height, 0\n self.grid_margin = gm\n ssize = tiles.tmx_data.tilewidth\n self.squaresize = ssize\n self.window.offset_x = (w - self.grid_dim[0] * (ssize + gm)) // 2\n self.window.offset_y = (h - self.grid_dim[1] * (ssize + gm)) // 2\n self.window.tile_renderer = tiles", "def set_fancy_plot(plt):\n\n plt.rcParams.update({\n 'font.size': 14, \n 'font.family': 'serif',\n\n 'lines.linewidth': 1,\n 'lines.markersize': 8.0,\n 'figure.subplot.wspace': 0.,\n 'axes.linewidth': 0.5,\n 'axes.formatter.use_mathtext': True,\n\n 'axes.edgecolor': '#111',\n 'axes.facecolor': '#fafafa',\n\n\n 'axes.xmargin': 0.1,\n 'xtick.direction': 'in',\n 'xtick.major.size': 9.,\n 'xtick.major.pad': 5.,\n 'xtick.minor.size': 4.,\n 'xtick.top': True,\n 'xtick.minor.visible': True,\n 'xtick.major.width': 0.5,\n 'xtick.minor.width': 0.5,\n\n 'axes.ymargin': 0.1,\n 'ytick.direction': 'in',\n 'ytick.major.size': 9,\n 'ytick.major.pad': 5.,\n 'ytick.minor.size': 4,\n 'ytick.right': True,\n 'ytick.minor.visible': True,\n 'ytick.major.width': 0.5,\n 'ytick.minor.width': 0.5,\n })", "def show(self):\r\n # Initialise the spider plot\r\n plt.clf()\r\n axis_pic = plt.subplot(111, polar=True)\r\n axis_pic.spines['polar'].set_visible(False)\r\n axis_pic.set_yticklabels([])\r\n\r\n # If you want the first axis to be on top:\r\n axis_pic.set_theta_offset(pi / 2)\r\n axis_pic.set_theta_direction(-1)\r\n\r\n # Draw one axe per variable + add labels labels yet\r\n plt.xticks(self._angles[:-1], self._metrics_name)\r\n\r\n # Draw y labels\r\n axis_pic.set_rlabel_position(0)\r\n if self._scale == 'hide':\r\n plt.yticks([0.0], color=\"grey\", size=7)\r\n elif self._scale == 'norm':\r\n plt.yticks([0.2, 0.4, 0.6, 0.8],\r\n [\"0.2\", \"0.4\", \"0.6\", \"0.8\"],\r\n color=\"grey\", size=7)\r\n elif self._scale == 'sparse':\r\n plt.yticks([0.5], [\"0.5\"], color=\"grey\", size=7)\r\n elif self._scale == 'dense':\r\n ticks = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\r\n labels = [\"0.1\", \"0.2\", \"0.3\", \"0.4\", \"0.5\", \"0.6\",\r\n \"0.7\", \"0.8\", \"0.9\"]\r\n plt.yticks(ticks, labels, color=\"grey\", size=7)\r\n else:\r\n # default\r\n plt.yticks([0.0], color=\"grey\", size=7)\r\n plt.ylim(0, 1)\r\n\r\n # plot border\r\n axis_pic.plot(self._angles, [1]*(self._nb_var + 1), color='grey',\r\n linewidth=1, linestyle='solid')\r\n\r\n for i in range(len(self._labels)):\r\n axis_pic.plot(self._angles, self._metrics_data[i], linewidth=1,\r\n linestyle='solid', label=self._labels[i])\r\n axis_pic.fill(self._angles, self._metrics_data[i], alpha=0.1)\r\n\r\n # Add legend\r\n plt.legend(loc='upper right', bbox_to_anchor=(0., 0.))\r\n plt.title(self._title, y=1.1, color='g')\r\n plt.show()", "def draw_axes(self):\n\n origx, origy = self.pixel() # Origin\n w, h = self.width, self.height\n midx, midy = sum(self.xbounds) / 2, sum(self.ybounds) / 2\n axescol, axesth = self.axescolor, self.axesthick\n\n if 0 <= origy < self.height:\n orig = [(midx, 0)] # Fake \"origin\" to draw axis from\n self.graphs[\"x-axis\"] = PointsImage(orig, axescol, [w, axesth])\n if 0 <= origx < self.width:\n orig = [(0, midy)]\n self.graphs[\"y-axis\"] = PointsImage(orig, axescol, [axesth, h])\n\n x_ticks, y_ticks = [], []\n for xpix in xrange(self.width + 1):\n xcoord = round(self.coord(xpix)[0], self.round)\n if xcoord % self.xscl < self.tickprec:\n x_ticks.append([xcoord, 0])\n\n for ypix in xrange(self.height + 1):\n ycoord = round(self.coord(y=ypix)[1], self.round)\n if ycoord % self.yscl < self.tickprec:\n y_ticks.append([0, ycoord])\n\n if self.grid:\n x_ticks = [(point[0], midy) for point in x_ticks]\n y_ticks = [(midx, point[1]) for point in y_ticks]\n tkx, tky = [axesth - 1, h], [w, axesth - 1]\n else:\n tkx, tky = [axesth - 1, self.tick], [self.tick, axesth - 1]\n\n self.graphs[\"x-ticks\"] = PointsImage(x_ticks, axescol, tkx)\n self.graphs[\"y-ticks\"] = PointsImage(y_ticks, axescol, tky)\n\n self.gimg.save(self.fname)", "def config_axis(self, axis, ticks, labels=None):\n if axis == \"x\":\n self.ax.set_xticks(ticks)\n if labels:\n self.ax.set_xticklabels(labels, minor=False)\n if axis == \"y\":\n self.ax.set_yticks(ticks)\n if labels:\n self.ax.set_yticklabels(labels, minor=False)", "def initialize_plot(self):\n pyplot.axis(self.map_limits)\n pyplot.ion()\n pyplot.show()", "def fig_temporal_heatmap():\n\t\n\tfig = plt.figure()\n\tfig.set_size_inches(5.5, 2)\n\t\n\tplt.xticks(sp.arange(-10, 10, 0.5), fontsize=18)\n\tplt.yticks(sp.arange(1, 15, 2), fontsize=18)\n\t\n\treturn fig", "def configure_axes(fig, x_axis_kwargs, y_axis_kwargs):\n fig.update_xaxes(showline=True, linewidth=1, linecolor='black',\n ticks='outside')\n if x_axis_kwargs:\n fig.update_xaxes(**x_axis_kwargs)\n fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='#CCC')\n fig.update_yaxes(showline=True, linewidth=1, linecolor='black',\n ticks='outside')\n if y_axis_kwargs:\n fig.update_yaxes(**y_axis_kwargs)", "def heatmap_layout(fig, tickvals, ticktext, dates_xaxis):\n fig.update_layout(\n height=550,\n margin=dict(l=0, r=0, t=8, b=42),\n yaxis=dict(\n tickvals=tickvals,\n ticktext=ticktext,\n fixedrange=True),\n xaxis=dict(\n range=[dates_xaxis[-1], dates_xaxis[0]]\n ),\n font_family=\"Consolas\",\n )\n return fig", "def setup_axes(*axes, **kwargs):\n\n # Handle some shortcut syntaxes\n if not_empty(kwargs, 'xticks') and not not_empty(kwargs, 'xticklabels'):\n kwargs['xticklabels'] = kwargs['xticks']\n\n if not_empty(kwargs, 'yticks') and not not_empty(kwargs, 'yticklabels'):\n kwargs['yticklabels'] = kwargs['yticks']\n\n if not_empty(kwargs, 'xticks'):\n try:\n kwargs['xticks'] = [float(x) for x in kwargs['xticks'].split()]\n except (AttributeError):\n pass\n\n if not_empty(kwargs, 'xticklabels'):\n try:\n kwargs['xticklabels'] = kwargs['xticklabels'].split()\n except (AttributeError, KeyError):\n pass\n\n if not_empty(kwargs, 'yticks'):\n try:\n kwargs['yticks'] = [float(x) for x in kwargs['yticks'].split()]\n except (AttributeError, KeyError):\n pass\n if not_empty(kwargs, 'yticklabels'):\n try:\n kwargs['yticklabels'] = kwargs['yticklabels'].split()\n except (AttributeError, KeyError):\n pass\n \n if not_empty(kwargs, 'rticks'):\n try:\n kwargs['rticks'] = [float(x) for x in kwargs['rticks'].split()]\n except (AttributeError, KeyError):\n pass\n if not_empty(kwargs, 'rticklabels'):\n try:\n kwargs['rticklabels'] = kwargs['rticklabels'].split()\n except (AttributeError, KeyError):\n pass\n \n # Setup each axis\n for ax in axes:\n if not_empty(kwargs, 'title') and ax.primary:\n # Only put title on the top set of axes\n ax.set_title(kwargs['title'])\n\n if ax.ratio:\n # Use ratio y-axis values\n if not_empty(kwargs, 'rmin'):\n ax.set_ylim(bottom=kwargs['rmin'])\n if not_empty(kwargs, 'rmax'):\n ax.set_ylim(top=kwargs['rmax'])\n if not_empty(kwargs, 'rlabel'):\n ax.set_ylabel(kwargs['rlabel'], y=1, ha='right')\n else:\n # Use normal y-axis values\n if not_empty(kwargs, 'ymin'):\n ax.set_ylim(bottom=float(kwargs['ymin']))\n if not_empty(kwargs, 'ymax'):\n ax.set_ylim(top=float(kwargs['ymax']))\n if not_empty(kwargs, 'ylabel'):\n ax.set_ylabel(kwargs['ylabel'], y=1, ha='right')\n if not_empty(kwargs, 'yticks'):\n ax.set_yticks(kwargs['yticks'])\n if not_empty(kwargs, 'yticklabels'):\n if 'ytickrot' in kwargs:\n ax.set_yticklabels(kwargs['yticklabels'], rotation=kwargs['ytickrot'])\n else:\n ax.set_yticklabels(kwargs['yticklabels'])\n\n if not_empty(kwargs, 'xmin'):\n ax.set_xlim(left=float(kwargs['xmin']))\n if not_empty(kwargs, 'xmax'):\n ax.set_xlim(right=float(kwargs['xmax']))\n\n if not_empty(kwargs, 'xlabel'):\n ax.set_xlabel(kwargs['xlabel'], x=1, ha='right') \n if not_empty(kwargs, 'xticks'):\n ax.set_xticks(kwargs['xticks'])\n if not_empty(kwargs, 'xticklabels'):\n if 'xtickrot' in kwargs:\n ax.set_xticklabels(kwargs['xticklabels'], rotation=kwargs['xtickrot'])\n else:\n ax.set_xticklabels(kwargs['xticklabels'])\n\n if ax.get_xscale() != 'log':\n ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())\n if ax.get_yscale() != 'log':\n if 'yticks' not in kwargs or not kwargs['yticks']:\n ax.yaxis.set_major_locator(ticker.MaxNLocator(5, prune='upper' if (not ax.ratio and not ax.primary) else None))\n ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())\n ax.yaxis.set_label_coords(-0.15,1)\n for spine in ax.spines.values(): \n spine.set_zorder(100)\n\n # Clean up for ratio plots\n if axes[-1].ratio:\n for ax in axes[:-1]:\n for tick in ax.get_xticklabels():\n tick.set_visible(False)\n ax.set_xlabel(\"\")\n axes[-1].yaxis.set_major_locator(ticker.MaxNLocator(4, prune='upper'))\n # Show a line at 1.0 if it's in range\n if axes[-1].get_ylim()[0] < 1.0 < axes[-1].get_ylim()[1]:\n axes[-1].plot(axes[-1].get_xlim(), [1.0,1.0], color='#B3B3B3', linewidth=2.0,linestyle='--')\n axes[-1].yaxis.grid(True) # Show lines on tick marks\n if not_empty(kwargs, 'ratio_sb') and kwargs['ratio_sb']:\n axes[-1].yaxis.get_major_formatter().set_powerlimits((-1,1))\n if not_empty(kwargs, 'rticks'):\n axes[-1].set_yticks(kwargs['rticks'])\n if not_empty(kwargs, 'rticklabels'):\n axes[-1].set_yticklabels(kwargs['rticklabels'])", "def myGMexPlotsettings():\n #------------ geography\n # Global plot\n glo= False\n\n xlim=(-100,-75)\n ylim=(15,32)\n\n # Coaslines\n coastL=False\n coastC=True\n coastLand=True\n\n #------------ color shading\n # type of plot \n typlo='pcolormesh'\n\n # min/max values\n vmin=-0.5\n vmax=0.5\n\n # number of color segments in the colormap\n Nincr=50\n\n # color of the values smaller than vmin\n su='#EFF5FB'\n # color of the values larger than vmax\n so='#F8E0E0'\n\n # colorbar label \n labelplt= \"SLA\"\n\n # number of labels on the colorbar\n Nbar=5\n\n #------------ plot output\n # plot format\n pltty = \".png\"\n\n # plot resolution (dpi)\n dpifig=300\n\n # output directory for plots\n diro=\"./\"\n return glo,xlim,ylim,coastL,coastC,coastLand,typlo,vmin,vmax,Nincr,su,so,labelplt,Nbar,pltty,dpifig,diro", "def _set_ax_subplot(self, axes, x_var, y_var, row, col, omp,\n x_scale, y_scale):\n ax = axes[row, col]\n nrows = axes.shape[0]\n ncols = axes.shape[1]\n\n if col == 0:\n self._set_ax_text(ax=ax, omp=omp, fixed_var='omp')\n if self.scaling_type == 'strong':\n self._set_ax_legend(ax=ax)\n\n if row == 0:\n self._set_ax_title(ax=ax)\n if self.scaling_type == 'weak':\n self._set_ax_legend(ax=ax)\n\n if row == nrows - 1:\n ax.set_xlabel(self.config['plot']['labels'][x_var])\n\n ax.set_ylabel(self.config['plot']['labels'][y_var])\n\n self._set_ax_scale(ax=ax, x_var=x_var, y_var=y_var,\n x_scale=x_scale, y_scale=y_scale)\n self._set_ax_xticks(ax=ax)\n self._set_ax_dashed(ax=ax, y_var=y_var)", "def heatmap_headmap(df_obj,sensorData,epoch_no):\n voltmatrix,subID = avgVolt_stimulus(df_obj,sensorData,epoch_no)\n\n fig = plt.figure(1,figsize=(6.5,5.5))\n gridspec.GridSpec(3,3)\n\n #1\n plt.subplot2grid((3,3),(0,0), colspan=2,rowspan=3)\n ax = sns.heatmap(voltmatrix, xticklabels=stimulus,cmap='RdBu_r', vmin=-1, vmax=1)\n ax.set(yticklabels=[])\n ax.set(xlabel='stimulus', ylabel='<-- channels')\n ax.set_title('sub '+str(subID)+' Epoch '+str(epoch_no).zfill(3))\n #2\n ax1 = plt.subplot2grid((3,3),(0,2))\n mask,xi,yi,zi = interpolate_mesh(sensorData,voltmatrix[:,0])\n snapPlots = plot_head(ax1,mask,xi,yi,zi,stimulus[0],sensorData)\n #3\n ax2 = plt.subplot2grid((3,3),(1,2))\n mask,xi,yi,zi = interpolate_mesh(sensorData,voltmatrix[:,1])\n snapPlots = plot_head(ax2,mask,xi,yi,zi,stimulus[1],sensorData)\n #4\n ax3 = plt.subplot2grid((3,3),(2,2))\n mask,xi,yi,zi = interpolate_mesh(sensorData,voltmatrix[:,2])\n snapPlots = plot_head(ax3, mask,xi,yi,zi,stimulus[2],sensorData)\n\n fig.tight_layout()\n fig.savefig(subID+'_Epoch_eegSensors_'+str(epoch_no).zfill(4)+'.png')", "def __set_exp_plot(self):\n y_ticks = []\n for i in range(-5, 6):\n y_ticks.append(i)\n self.ax.set_yticks(y_ticks)", "def plot_replica_maps_grid(dataset, plotspecs):\n cwd = os.getcwd()\n grid_dims = plotspecs[\"grid_dims\"]\n for t in range(len(dataset.topologies)):\n names = dataset.top_names[t]\n for n in range(len(names)):\n # Plot whatever for a protein\n pairs = dataset.pairs[t][n]\n N = dataset.prot_sizes[t][n]\n print dataset.top_names[t][n]\n for j in range(len(dataset.b_values)):\n print \" b-values:\", dataset.b_values[j]\n fig, axes = plt.subplots(*grid_dims, sharex=True, sharey=True, figsize=(12,10))\n if len(dataset.ydata[t][n][j]) > 0:\n for rep in range(len(dataset.ydata[t][n][j])):\n ax = axes[rep / grid_dims[0], rep % grid_dims[0]]\n\n vals = dataset.ydata[t][n][j][0]\n C = np.zeros((N, N))\n for m in range(len(pairs)):\n if m < dataset.prot_n_native[t][n]:\n C[pairs[m, 1], pairs[m, 0]] = vals[m]\n else:\n C[pairs[m, 1], pairs[m, 0]] = -vals[m]\n\n # plot native and non-native contacts in different colors\n vmin, vmax = plotspecs[\"vminmax\"]\n pa = ax.pcolormesh(np.ma.array(C, mask=(C == 0)), cmap=\"bwr_r\", vmin=vmin, vmax=vmax)\n\n ax.annotate(\"rep = \" + str(rep + 1),\n xy=(0,0), xytext=plotspecs[\"xytext\"],\n bbox={\"boxstyle\":\"square\",\"facecolor\":\"w\",\"edgecolor\":\"k\"},\n xycoords=\"axes fraction\", textcoords=\"axes fraction\")\n ax.plot(np.arange(0, N), np.arange(0, N), 'k', lw=2)\n\n ax.set_xlim(0, N)\n ax.set_ylim(0, N)\n ax.set_aspect(\"equal\")\n\n plt.subplots_adjust(wspace=0, hspace=0)\n big_ax = fig.add_subplot(111)\n big_ax.grid(False)\n big_ax.set_axis_bgcolor('none')\n big_ax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')\n big_ax.set_ylabel(plotspecs[\"ylabel\"])\n big_ax.set_xlabel(plotspecs[\"xlabel\"])\n big_ax.set_title(plotspecs[\"title\"] + \" b = \" + dataset.b_values[j])\n\n if not (plotspecs[\"saveas\"] is None):\n savedir = \"{}/{}/b_{}/plots\".format(dataset.topologies[t], \n dataset.top_names[t][n], dataset.b_values[j])\n \n if not os.path.exists(savedir):\n os.mkdir(savedir)\n os.chdir(savedir)\n for format in plotspecs[\"saveas_formats\"]:\n plt.savefig(plotspecs[\"saveas\"] + \".\" + format, bbox_inches=\"tight\")\n os.chdir(cwd)", "def allAntennaMultiPlot(xData, yData, antennaList, xMin = None, xMax = None,\n yMin = None, yMax = None, \\\n orientation = 'portrait', plotTitle = \"\", xLabel = \"x-axis\", \\\n yLabel = \"y-axis\", infoTextLeft = \"\", infoTextRight = \"\",\n showGrid = True, showPlot = True, axisStyle = 'lin', \\\n lineStyles = ('bo-', 'rx--', 'gv-.'), legends = None, \\\n plotFileName = \"\", makePdf = False, makePng = False) :\n#\n error = False\n plt.ioff()\n\n# Number of line styles provided\n numStyles = len(lineStyles)\n\n# Various page and geometry dimensions in inches\n topMargin = 0.1\n bottomMargin = 0.1\n leftMargin = 0.2\n rightMargin = 0.2\n\n if orientation == 'landscape' :\n pageWidth = 11.0\n pageHeight = 8.5\n else :\n pageWidth = 8.5\n pageHeight = 11.0\n\n# Plot panel geometry\n numPlotCols = 3\n numPlotRows = maxAntennas / numPlotCols\n\n plotLeftDist = 0.75\n plotRightDist = 0.5\n plotTopDist = 1.0\n plotBotDist = 1.0\n\n plotHeight = (pageHeight - plotTopDist - plotBotDist) / numPlotRows\n plotWidth = (pageWidth - plotLeftDist - plotRightDist) / numPlotCols\n\n# Some handy font definitions\n tickFont = {'family' : 'sans-serif',\n 'weight' : 'normal',\n 'size' : 8,\n }\n generalFont = {'family' : 'sans-serif',\n 'weight' : 'normal',\n 'size' : 11,\n }\n plt.rc('font', **generalFont) # pass in the font dict as kwargs\n\n titleFontSize = 14\n labelFontSize = 11\n tickFontSize = 8\n infoFontSize = 8\n legendFontSize = 8\n\n# Start a new figure\n try:\n figure = plt.figure(figsize = (pageWidth, pageHeight))\n except :\n printError(\"allAntennaMultiPlot: Not an Xterm? Cannot plot\")\n plt.rc({'backend' : 'Agg'})\n error = True\n return error\n\n# Title for the plots\n titleOffset = 0.05\n x = (0.5 * (pageWidth + plotLeftDist - plotRightDist)) / pageWidth\n y = 1.0 - (plotTopDist - titleOffset) / pageHeight\n plt.figtext(x, y, plotTitle, fontsize = titleFontSize, \\\n va = 'bottom', ha = 'center', variant = 'small-caps')\n\n# Left info box\n left = leftMargin / pageWidth\n top = 1.0 - topMargin / pageHeight\n plt.figtext(left, top, infoTextLeft, fontsize = infoFontSize, va = 'top')\n\n# Right info box\n right = 1.0 - rightMargin / pageWidth\n top = 1.0 - topMargin / pageHeight\n\n plt.figtext(right, top, infoTextRight, fontsize = infoFontSize, va = 'top', \\\n ha = 'right')\n\n# Array of plot panels. Start at top left and work left to right\n# The array (list of lists) of y values is assumed to be a multiple of the number\n# of antennas, with the values for each antenna adjacent\n plotsPerAntenna = len(yData) / maxAntennas\n bot = (pageHeight - plotTopDist - plotHeight) / pageHeight\n ant = 1\n ny = 0\n\n for row in range(numPlotRows) :\n left = plotLeftDist / pageWidth\n for col in range(numPlotCols) :\n ax = plt.axes([left, bot, plotWidth / pageWidth, plotHeight / pageHeight])\n if showGrid :\n ax.grid(True, color = 'gray')\n plt.figtext(left + plotWidth / pageWidth - 0.01, bot + 0.01, \\\n \"C%d\" % ant, fontsize = 10, ha = 'right')\n if isinstance(xData[0], list) :\n xd = xData[ant - 1]\n else :\n xd = xData\n if ant in antennaList :\n for nplt in range(plotsPerAntenna) :\n if axisStyle == 'logx' :\n plt.semilogx(xd, yData[ny], lineStyles[nplt % numStyles])\n elif axisStyle == 'logy' :\n plt.semilogy(xd, yData[ny], lineStyles[nplt % numStyles])\n elif axisStyle == 'loglog' :\n plt.loglog(xd, yData[ny], lineStyles[nplt % numStyles])\n else :\n plt.plot(xd, yData[ny], lineStyles[nplt % numStyles])\n ny += 1\n else :\n plt.figtext(left + 0.5 * plotWidth / pageWidth, \\\n bot + 0.5 * plotHeight / pageHeight, \"NOT PRESENT\", \\\n va = 'center', ha = 'center', color = 'gray', fontsize = 8)\n ny += plotsPerAntenna\n\n # Insert legend if required\n if (col == 0) and (row == numPlotRows -1) and legends :\n x = -(plotLeftDist - leftMargin) / plotWidth\n y = -(plotBotDist - bottomMargin) / plotHeight\n plt.legend(legends, loc = (x, y), \\\n prop = FontProperties(size = legendFontSize), labelspacing = 0.0)\n\n # Set up x-axis\n plt.xlim(xMin, xMax)\n if row < numPlotRows - 1 :\n for tick in ax.xaxis.get_major_ticks() :\n tick.label1On = False\n else :\n if (col < numPlotCols - 1) :\n ticks = ax.xaxis.get_major_ticks()\n ticks[len(ticks) - 1].label1On = False\n plt.xticks(**tickFont)\n\n # Set up y-axis\n plt.ylim(yMin, yMax)\n if col > 0 :\n for tick in ax.yaxis.get_major_ticks() :\n tick.label1On = False\n else :\n if (row > 0) :\n ticks = ax.yaxis.get_major_ticks()\n ticks[len(ticks) - 1].label1On = False\n plt.yticks(**tickFont)\n\n if (col == numPlotCols - 1) and (row == numPlotRows - 1) :\n plt.xlabel(xLabel)\n if (col == 0) and (row == 0) :\n plt.ylabel(yLabel)\n left += plotWidth / pageWidth\n ant += 1\n bot -= plotHeight / pageHeight\n\n # Where plot output is to be directed\n if plotFileName :\n if makePdf :\n try :\n plt.savefig(plotFileName + \".pdf\")\n except :\n error = True\n printError(\"Cannot make PDF file\")\n if makePng :\n try :\n plt.savefig(plotFileName + \".png\")\n except :\n error = True\n printError(\"Cannot make PNG file\")\n if showPlot :\n plt.ioff()\n plt.show()\n\n return error" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the geometry from the passed data frame, looks for point objects and extracts the coordinates. Useful for ploting, as doing this is usually much faster than using the geoPandas `plot` methods. The dataframe must either have no projection set (`frame.crs == None`)
def points_from_frame(frame): proj = _parse_crs(frame.crs) xcs, ycs = [], [] if proj == _NATIVE_LONLAT: for point in frame.geometry: c = project(*point.coords[0]) xcs.append(c[0]) ycs.append(c[1]) else: for point in frame.geometry: xcs.append(point.coords[0][0]) ycs.append(point.coords[0][1]) return xcs, ycs
[ "def _convert_geodataframe(self):\r\n\r\n value = self._frame\r\n\r\n c1_field, c2_field, c3_field, geometry_field = Series(), Series(), Series(), Series()\r\n try:\r\n c1_field = self._frame['coord_field1']\r\n c2_field = self._frame['coord_field2']\r\n c3_field = self._frame['coord_field3']\r\n except KeyError:\r\n pass\r\n\r\n try:\r\n print(self._frame.columns)\r\n print(self._frame)\r\n geometry_field = self._frame['geometry']\r\n except KeyError:\r\n pass\r\n\r\n crs = self.__dict__.get('crs', None)\r\n to_crs = self.__dict__.get('to_crs', None)\r\n\r\n if isinstance(value, GeoDataFrame):\r\n if not geometry_field.empty:\r\n if not c1_field.empty or not c2_field.empty or not c3_field.empty:\r\n warnings.warn('Coordinate fields should not be passed with a geometry field. This process will '\r\n 'continue assuming the geometry field takes precedence.')\r\n value = geodataframe_from_geometry(value, crs=crs)\r\n\r\n # is this part even necessary?\r\n elif (not c1_field.empty and not c2_field.empty) or (\r\n not c1_field.empty and not c2_field.empty and not c3_field.empty):\r\n if geometry_field is not None:\r\n raise GeoDataSetInfoError('Geometry field should not be passed along with longitude and '\r\n 'latitude fields.')\r\n value = geodataframe_from_coordinates(value, z=(not c3_field.empty), crs=crs)\r\n\r\n elif isinstance(value, DataFrame):\r\n try:\r\n value = geodataframe_from_coordinates(value, z=(not c3_field.empty), crs=crs)\r\n except KeyError:\r\n value = geodataframe_from_geometry(value, crs=crs)\r\n\r\n else:\r\n raise GeoDataSetFrameError(\"Your frame must be a valid GeoDataFrame!\")\r\n\r\n if value.empty:\r\n raise GeoDataSetInfoError(\"The frame can not be empty!\")\r\n\r\n if not value.crs:\r\n warnings.warn(\"A crs has not been set. This can be dangerous when performing spatial operations...\")\r\n elif to_crs:\r\n value.to_crs(crs=to_crs, inplace=True)\r\n\r\n self._finalize_frame(value)", "def create_geodataframe(list_of_datasets):\n\n #df = pd.DataFrame(list_of_datasets).dropna(subset=[df.spatial])\n df = pd.DataFrame(list_of_datasets)\n df.dropna(subset=['spatial'], inplace=True)\n\n # create a new column to store the original 'spatial' column (which is GeoJSON format):\n df['spatial_geojson'] = df.spatial\n\n # convert the 'spatial' column from GeoJSON to Shapely geometry for GeoPandas compatibility:\n df.spatial = df.spatial.apply(lambda x: shape(geojson.loads(x)))\n\n\n\n # Create a new 'spatial_point' column of Shapely geometry objects that converts any geometries where the difference between lat/lon min and max is < .0001 degree to Point, and retains all the others as Polygon:\n\n # the approach below uses abs() account for postive/negative lat/lon coordinates to perform the calculation correctly for all quadrants on the globe (or for features crossing meridian/equator)\n df['spatial_point'] = df.apply(lambda row: row.spatial if abs(abs(float(row['bbox-west-long'])) - abs(float(row['bbox-east-long']))) > 0.0001 and abs(abs(float(row['bbox-north-lat'])) - abs(float(row['bbox-south-lat']))) > 0.0001 else Point(float(row['bbox-east-long']), float(row['bbox-south-lat'])), axis=1)\n\n # same as above but without using abs():\n #df['spatial_point'] = df.apply(lambda row: row.spatial if float(row['bbox-east-long']) - float(row['bbox-west-long']) > 0.0001 and float(row['bbox-north-lat']) - float(row['bbox-south-lat']) > 0.0001 else Point(float(row['bbox-east-long']), float(row['bbox-south-lat'])), axis=1)\n\n # this just converts every tow to a Point object:\n #df['#spatial_point'] = df.apply(lambda row: Point(float(row['bbox-east-long']), float(row['bbox-south-lat'])), axis=1)\n\n\n # GeoPandas GeoDataFrame:\n # Create a GeoPandas GeoDataFrame from the regular Pandas DataFrame. Assign geometry column.\n gdf = geopandas.GeoDataFrame(df)\n #gdf.set_geometry(\"spatial\", inplace=True, crs=\"EPSG:4326\")\n gdf.set_geometry(\"spatial_point\", inplace=True, crs=\"EPSG:4326\")\n\n # print the name of the GeoPandas geometry column name:\n print(gdf.geometry.name)\n\n return gdf", "def get_gdf_coords(gdf):\n return np.array([[p.geometry.x, p.geometry.y] for p in gdf.itertuples()])", "def LatLon_to_point(df):\n \n df['geometry'] = df.apply(lambda x: Point((float(x.STOP_LON), float(x.STOP_LAT))), axis=1)\n stops = gp.GeoDataFrame(df, geometry='geometry', crs = {'init':'epsg:4326'})\n \n return stops", "def dataframe_to_points(dataframe):\n # Get the columns names of the data frame and put them as labels\n # Note that the call to plt is saved into context and will be used when\n # calling plt.plot() to display the graph with clusters\n col_names = list(dataframe)\n plt.xlabel(col_names[1])\n plt.ylabel(col_names[2])\n\n # Add each row of the dataframe into a list of Point objects and return it\n points = []\n for index, value in dataframe.iterrows():\n points.append(Point(value[0], value[1], value[2]))\n return points", "def convert_dataframe_to_coords(\n df: pd.DataFrame,\n coordinate_cols: List[str],\n frame_col: str = \"frame\",\n validate_frame: bool = True,\n) -> List[NumArray]:\n grps = list(df.groupby(frame_col, sort=True))\n if validate_frame:\n assert np.array_equal(np.arange(df[frame_col].max() + 1), [g[0] for g in grps])\n coords = [grp[list(coordinate_cols)].values for _frame, grp in grps]\n return coords", "def matching_df_from_geoms(df, geoms): \n geom_col = geometry_column_name(df)\n return pd.DataFrame(geoms, columns=[geom_col])", "def convertPointsDfToFc(df,projection=None,lat_name='latitude',lon_name='longitude'):\n feature_collection_list = []\n for i,row in df.iterrows():\n geometry = ee.Geometry.Point([row[lon_name],row[lat_name]],projection)\n row_dict = row.to_dict()\n row_feature = ee.Feature(geometry,row_dict)\n feature_collection_list.append(row_feature)\n return ee.FeatureCollection(feature_collection_list)", "def load_points_df(points_fpath):\n df = pd.read_csv(points_fpath)\n for service in Config.services:\n # service_df = df[[f'x_{service}', f'y_{service}']]\n # service_df['geometry'] = service_df.apply(lambda x: Point(x[f'x_{service}'], x[f'y_{service}']), axis=1)\n service_gdf = gpd.GeoDataFrame(\n df[[f'x_{service}', f'y_{service}']],\n geometry=gpd.points_from_xy(df[f'x_{service}'], df[f'y_{service}']),\n crs=f'epsg:{Config.source_crs}'\n )\n # service_gdf = gpd.GeoDataFrame(service_df, geometry='geometry', crs=f'epsg:{config.source_crs}')\n # print(service_df.geometry.crs, f'epsg:{config.source_crs}')\n # service_gdf.crs = f'epsg:{config.source_crs}'\n service_gdf = service_gdf.to_crs(f'epsg:{Config.target_crs}')\n df[f'lon_{service}'] = service_gdf.apply(lambda x: x.geometry.x, axis=1)\n df[f'lat_{service}'] = service_gdf.apply(lambda x: x.geometry.y, axis=1)\n return df", "def to_featureset(df):\r\n if hasattr(df, 'spatial'):\r\n fs = df.spatial.__feature_set__\r\n return FeatureSet.from_dict(fs)\r\n return None", "def extract_more_coordinates(df, df_has_loc_info=True):\n df = df.loc[df.Location.isna() == False]\n df_wo_coords = df.loc[df.Latitude == 99999.0]\n locations = impute_coordinates(df_wo_coords, df_has_loc_info)\n df_wo_coords = df_wo_coords.merge(\n locations[[\"Ticket number\", \"LAT\", \"LON\"]], on=\"Ticket number\", how=\"left\"\n )\n df_wo_coords = df_wo_coords.drop([\"Latitude\", \"Longitude\"], axis=1).rename(\n {\"LAT\": \"Latitude\", \"LON\": \"Longitude\"}, axis=1\n )\n logging.info(df_wo_coords.head())\n df_wo_coords.dropna(subset=[\"Latitude\", \"Longitude\"], inplace=True)\n return pd.concat([df_wo_coords, df], axis=0).drop_duplicates(\n subset=[\"Ticket number\"], keep=\"first\"\n )", "def representative_points(geometry: gpd.GeoSeries) -> gpd.GeoSeries:\n return geometry.map(lambda x: x.representative_point())", "def filter_coords(df):\n lon_l, lon_r = -74.1, -73.7\n lat_l, lat_r = 40.65, 40.85\n\n for c in filter(lambda c: c.endswith('_Lon'), df.columns):\n df = df[(df[c] <= lon_r) & (df[c] >= lon_l)]\n\n for c in filter(lambda c: c.endswith('_Lat'), df.columns):\n df = df[(df[c] <= lat_r) & (df[c] >= lat_l)]\n\n return df", "def get_geom_column_info(self):\n\n get_column_name_and_srid_stmt = f'''\n select f_geometry_column, srid from geometry_columns\n where f_table_schema = '{self.enterprise_schema}' and f_table_name = '{self.enterprise_dataset_name}'\n '''\n # Identify the geometry column values\n self.logger.info('Running get_column_name_and_srid_stmt' + get_column_name_and_srid_stmt)\n self.pg_cursor.execute(get_column_name_and_srid_stmt)\n\n #col_name = self.pg_cursor.fetchall()[0]\n col_name1 = self.pg_cursor.fetchall()\n \n # If the result is empty, there is no shape field and this is a table.\n # return empty dict that will evaluate to False.\n if not col_name1: \n return {}\n self.logger.info(f'Got shape field and SRID back as: {col_name1}')\n\n col_name = col_name1[0]\n # Grab the column names\n header = [h.name for h in self.pg_cursor.description]\n # zip column names with the values\n geom_column_and_srid = dict(zip(header, list(col_name)))\n geom_column = geom_column_and_srid['f_geometry_column']\n srid = geom_column_and_srid['srid']\n\n # Get the type of geometry, e.g. point, line, polygon.. etc.\n # docs on this SDE function: https://desktop.arcgis.com/en/arcmap/latest/manage-data/using-sql-with-gdbs/st-geometrytype.htm\n # NOTE!: if the entreprise_schema is empty, e.g. this is a first run, this will fail, as a backup get the value from XCOM\n # Which will be populated by our \"get_geomtype\" task.\n geom_type_stmt = f'''\n select public.st_geometrytype({geom_column}) as geom_type \n from {self.enterprise_schema}.{self.enterprise_dataset_name}\n where st_isempty({geom_column}) is False\n limit 1\n '''\n self.logger.info('Running geom_type_stmt: ' + geom_type_stmt)\n self.pg_cursor.execute(geom_type_stmt)\n result = self.pg_cursor.fetchone()\n if result is None:\n geom_type_stmt = f'''\n select geometry_type('{self.enterprise_schema}', '{self.enterprise_dataset_name}', '{geom_column}')\n '''\n self.logger.info('Running geom_type_stmt: ' + geom_type_stmt)\n self.pg_cursor.execute(geom_type_stmt)\n geom_type = self.pg_cursor.fetchone()[0]\n\n #geom_type = ti.xcom_pull(key=xcom_task_id_key + 'geomtype')\n assert geom_type\n #self.logger.info(f'Got our geom_type from xcom: {geom_type}') \n else:\n geom_type = result[0].replace('ST_', '').capitalize()\n\n # Figure out if the dataset is 3D with either Z (elevation) or M (\"linear referencing measures\") properties\n # Grabbing this text out of the XML definition put in place by ESRI, can't find out how to do\n # it with PostGIS, doesn't seem to be a whole lot of support or awareness for these extra properties.\n has_m_or_z_stmt = f'''\n SELECT definition FROM sde.gdb_items\n WHERE name = 'databridge.{self.enterprise_schema}.{self.enterprise_dataset_name}'\n '''\n self.logger.info('Running has_m_or_z_stmt: ' + has_m_or_z_stmt)\n self.pg_cursor.execute(has_m_or_z_stmt)\n result = self.pg_cursor.fetchone()\n if result is None:\n # NO xml definition is in the sde.gdb_items yet, assume false\n self.m = False\n self.z = False\n else:\n xml_def = result[0]\n\n m = re.search(\"<HasM>\\D*<\\/HasM>\", xml_def)[0]\n if 'false' in m:\n self.m = False\n elif 'true' in m:\n self.m = True\n\n z = re.search(\"<HasZ>\\D*<\\/HasZ>\", xml_def)[0]\n if 'false' in z:\n self.z = False\n elif 'true' in z:\n self.z = True\n\n # This will ultimpately be the data type we create the table with,\n # example data type: 'shape geometry(MultipolygonZ, 2272)\n if self.m:\n geom_type = geom_type + 'M'\n if self.z:\n geom_type = geom_type + 'Z'\n \n\n self.geom_info = {'geom_field': geom_column,\n 'geom_type': geom_type,\n 'srid': srid}\n print(f'self.geom_info: {self.geom_info}')\n\n #return {'geom_field': geom_column, 'geom_type': geom_type, 'srid': srid}", "def get_points(df):\n points = [df[[f'x_{service}', f'y_{service}']].to_numpy() for service in Config.services]\n points = np.vstack(points)\n\n return points", "def as_geodataframe(self):\n return gpd.GeoDataFrame(geometry=list(self.geometries),crs=self.crs)", "def single_point_populater(df, prep_method, aggregate_method, verbose=False):\n if verbose:\n print(\"Running single_point_populater().\")\n df, info = prep_method(df, verbose=verbose)\n points = zip(df.longitude, df.latitude)\n for lon, lat in points:\n fetched_data = single_fetch(lon, lat, collection=info[\"collection\"], verbose=verbose)\n values = aggregate_method(fetched_data, lon, lat, info[\"fetch_cols\"], verbose=verbose)\n df.loc[(df[\"latitude\"] == lat) & (df[\"longitude\"] == lon), info[\"agg_cols\"]] = [values]\n return df", "def drop_duplicate_geometries(df, keep='first'): \n\n mask = df.geometry.apply(lambda geom: shapely.to_wkb(geom))\n # use dropped duplicates index to drop from actual dataframe\n return df.iloc[mask.drop_duplicates(keep).index]", "def geoid_included(self, coord):\n\n geoid = ''\n p = Point(coord)\n failed = True\n for j in range(len(self.df_c1_shape)):\n if p.within(self.df_c1_shape.iloc[j]['geometry']):\n geoid = self.df_c1_shape.index[j]\n failed = False\n break\n if failed:\n return geoid\n self.df_c2_shape_c = self.df_c2_shape.filter(like=geoid, axis=0)\n failed = True\n for j in range(len(self.df_c2_shape_c)):\n if p.within(self.df_c2_shape_c.iloc[j]['geometry']):\n geoid = self.df_c2_shape_c.index[j]\n failed = False\n break\n if failed:\n return ''\n self.df_c3_shape_c = self.df_c3_shape.filter(like=geoid, axis=0)\n failed = True\n for j in range(len(self.df_c3_shape_c)):\n if p.within(self.df_c3_shape_c.iloc[j]['geometry']):\n geoid = self.df_c3_shape_c.index[j]\n failed = False\n break\n if failed:\n return ''\n self.df_c0_c = self.df_c0.filter(like=geoid, axis=0)\n failed = True\n for j in range(len(self.df_c0_c)):\n if p.within(self.df_c0_c.iloc[j]['geometry']):\n geoid = self.df_c0_c.index[j]\n failed = False\n break\n if failed:\n return ''\n return geoid" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testing if the default value will be used when the pathurl argument is skipped
def test_pathurl_argument_is_skipped(self): f = File() self.assertEqual('', f.pathurl)
[ "def build_url(self):\n url = super().build_url()\n if '/None/' in url:\n return url.replace('/None/', '/')\n else:\n return url", "def default_validation(url):\n return bool(urlparse(url).scheme)", "def build_url(self):\n url = super().build_url()\n if '/None/' in url:\n return url.replace('/None/', '')\n else:\n return url", "def test_pathurl_argument_is_working_properly(self):\n f = File(pathurl='shot2')\n self.assertEqual('file://localhost/shot2', f.pathurl)", "def test_use_default_url():\n data = Restaurant(name='Restaurant', menu='My Menu')\n payload = build_query_payload(data)\n\n title_block = payload['blocks'][0]\n title_text = title_block['text']['text']\n\n assert data.name in title_text\n assert f'|{data.name}>' not in title_text, \"Should not construct link without URL\"", "def default(self, value, **kwargs):\n if isinstance(value, str):\n if value == nwd:\n # nwd is of type str but will be converted to pathlib.Path\n return pathlib.Path(kwargs[\"nwd\"])\n return value.replace(nwd, pathlib.Path(kwargs[\"nwd\"]).as_posix())\n elif isinstance(value, pathlib.Path):\n return pathlib.Path(\n value.as_posix().replace(nwd, pathlib.Path(kwargs[\"nwd\"]).as_posix())\n )\n elif value is None:\n return value\n else:\n raise ValueError(\n f\"replace_nwd_placeholder is not implemented for {type(value)}\"\n )", "def _get_url_param(self, category):\n res = get_nested(ATTR_CONFIG, category)\n\n if type(res) == dict and 'default' in res:\n return res[\"default\"] # for the root value\n else:\n return res", "def get_url(endpoint_or_url):\n try: \n return url_for(endpoint_or_url)\n except: \n return endpoint_or_url", "def test_default_base_endpoint():\n parser = create_parser()\n parsed_arguments = parser.parse_args([])\n assert parsed_arguments.base_endpoint == DEFAULT_BASE_ENDPOINT, \"Wrong endpoint\"", "def _get_request_arg_bool(self, key, default=False):\n if isinstance(default, bool) is False:\n raise ValueError(\"invalid value for default parameter\")\n\n if key not in request.args:\n return default\n return request.args.get(key).lower() == \"true\"", "def test_pathurl_attribute_is_working_properly(self):\n f = File(pathurl='shot1')\n test_value = 'shot2'\n expected_value = 'file://localhost/shot2'\n self.assertNotEqual(test_value, f.pathurl)\n f.pathurl = test_value\n self.assertEqual(expected_value, f.pathurl)", "def test_url_not_passed(self):\n user_request = self.client.post('/', data={'url': ''})\n self.assertContains(user_request, \"Invalid URL\")", "def get_optional_param(param_name: str, default: str) -> str:\n value = request.args.get(param_name)\n if not value:\n return default\n return value", "def is_base_url(s: str = None) -> bool:\n return base_url() == (s or current_url(True))", "def get_default_path(self, default_path=''):\n return default_path if default_path else os.path.dirname(self.last_path)", "def test_default_route_absolute_path(self):\n path = '/absolute/path'\n def_route = DefaultRoute(path)\n assert path in def_route.default_handler_args['path']", "def test_init_missing_url(self):\n # noinspection PyBroadException\n try:\n setup_config(self.writer, CONFIG_MISSING_URL)\n self.assertTrue(False)\n except Exception as e:\n self.assertEqual(str(e), \"KairosDBURI not defined\")", "def test_default_route_bad_path(self, caplog):\n path = '../missing_path'\n def_route = DefaultRoute(path)\n assert path in def_route.default_handler_args['path']\n\n assert log_message_seen(caplog, logging.WARNING,\n 'Default handler static path does not exist')", "def default_empty(default):\n\n def get_value(test_value):\n if test_value:\n return test_value\n else:\n return default\n\n return get_value" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testing if a TypeError will be raised when the pathurl argument is not a string instance
def test_pathurl_argument_is_not_a_string(self): with self.assertRaises(TypeError) as cm: File(pathurl=123) self.assertEqual( cm.exception.message, 'File.pathurl should be a string, not int' )
[ "def test_pathurl_attribute_is_not_a_string(self):\n f = File(pathurl='shot1')\n with self.assertRaises(TypeError) as cm:\n f.pathurl = 123\n\n self.assertEqual(\n cm.exception.message,\n 'File.pathurl should be a string, not int'\n )", "def test_get_page_raises_type_error_for_non_string_url(value):\n from .context import mangasource\n source = mangasource.MangaSource('test', 'www.test.com', '_')\n with pytest.raises(TypeError):\n scr.Scraper._get_page(value, source)", "def test_convert_full_path_to_file_link_full_path_is_not_a_string(self):\n with self.assertRaises(TypeError) as cm:\n self.test_media_manager.convert_full_path_to_file_link(1)\n\n self.assertEqual(\n '\"full_path\" argument in '\n 'MediaManager.convert_full_path_to_file_link() method should be '\n 'a str, not int',\n str(cm.exception)\n )", "def test_convert_file_link_to_full_path_link_path_is_not_a_string(self):\n with self.assertRaises(TypeError) as cm:\n self.test_media_manager.convert_file_link_to_full_path(1)\n\n self.assertEqual(\n '\"link_path\" argument in '\n 'MediaManager.convert_file_link_to_full_path() method should be '\n 'a str, not int',\n str(cm.exception)\n )", "def test_invalidArguments(self):\n class Unexpected(object):\n def __str__(self):\n return \"wrong\"\n def __repr__(self):\n return \"<unexpected>\"\n defaultExpectation = \"unicode\" if bytes is str else \"str\"\n def assertRaised(raised, expectation, name):\n self.assertEqual(str(raised.exception),\n \"expected {} for {}, got {}\".format(\n expectation,\n name, \"<unexpected>\"))\n\n def check(param, expectation=defaultExpectation):\n with self.assertRaises(TypeError) as raised:\n URL(**{param: Unexpected()})\n assertRaised(raised, expectation, param)\n check(\"scheme\")\n check(\"host\")\n check(\"fragment\")\n check(\"rooted\", \"bool\")\n check(\"userinfo\")\n check(\"port\", \"int or NoneType\")\n\n with self.assertRaises(TypeError) as raised:\n URL(path=[Unexpected(),])\n assertRaised(raised, defaultExpectation, \"path segment\")\n with self.assertRaises(TypeError) as raised:\n URL(query=[(u\"name\", Unexpected()),])\n assertRaised(raised, defaultExpectation + \" or NoneType\",\n \"query parameter value\")\n with self.assertRaises(TypeError) as raised:\n URL(query=[(Unexpected(), u\"value\"),])\n assertRaised(raised, defaultExpectation, \"query parameter name\")\n # No custom error message for this one, just want to make sure\n # non-2-tuples don't get through.\n with self.assertRaises(TypeError):\n URL(query=[Unexpected()])\n with self.assertRaises(ValueError):\n URL(query=[(u'k', u'v', u'vv')])\n with self.assertRaises(ValueError):\n URL(query=[(u'k',)])\n\n url = URL.fromText(\"https://valid.example.com/\")\n with self.assertRaises(TypeError) as raised:\n url.child(Unexpected())\n assertRaised(raised, defaultExpectation, \"path segment\")\n with self.assertRaises(TypeError) as raised:\n url.sibling(Unexpected())\n assertRaised(raised, defaultExpectation, \"path segment\")\n with self.assertRaises(TypeError) as raised:\n url.click(Unexpected())\n assertRaised(raised, defaultExpectation, \"relative URL\")", "def test_technicallyTextIsIterableBut(self):\n with self.assertRaises(TypeError) as raised:\n URL(path=u'foo')\n self.assertEqual(\n str(raised.exception),\n \"expected iterable of text for path, not: {}\"\n .format(repr(u'foo'))\n )", "def test_get_file_not_string(self):\r\n\r\n snippet = {'get_file': ['file:///tmp/foo.yaml']}\r\n tmpl = parser.Template(hot_tpl_empty)\r\n stack = parser.Stack(utils.dummy_context(), 'param_id_test', tmpl)\r\n notStrErr = self.assertRaises(TypeError, self.resolve,\r\n snippet, tmpl, stack)\r\n self.assertEqual(\r\n 'Argument to \"get_file\" must be a string',\r\n six.text_type(notStrErr))", "def test_pathurl_argument_is_skipped(self):\n f = File()\n self.assertEqual('', f.pathurl)", "def test_listr_string_error(self):\n with pytest.raises(TypeError, match=\"Strings cannot be passed\"):\n _listr(\"abc\")", "def test_void_get_path(self):\r\n self.assertRaises(ValueError,self._httpc.do_get,\"\")", "def check_directory_url_type(url):\n if not isinstance(url, URL):\n raise TypeError(\n 'ACME directory URL should be a twisted.python.url.URL, '\n 'got {!r} instead'.format(url))", "def path_type(val):\n if not path.exists(val):\n raise ValueError('{!r} does not exists'.format(val))\n return val", "def test_invalid(self):\n # memento_client raises 'Exception', not a subclass.\n with self.assertRaisesRegex(\n ValueError, 'Only HTTP URIs are supported'):\n self._get_archive_url('invalid')", "def test_get_page_raises_type_error_for_bad_mangasource(value):\n with pytest.raises(TypeError):\n scr.Scraper._get_page('www.test.com', value)", "def url_or_error(url):\n # if it's not unicode, it must be utf8, otherwise fail\n if not isinstance(url, unicode):\n try:\n url = url.decode('utf8') # noqa - we check if decoding works here\n except Exception as e:\n logging.exception(e)\n return None\n\n # Convert URI to URL if necessary\n try:\n url = ensure_url(url)\n except Exception as e:\n logging.exception(e)\n return None\n\n # Validate URL\n if not validate_url(url):\n msg = 'bad url: {} '.format(url)\n logging.error(msg)\n return None\n\n return url", "def _is_path(s):\n if isinstance(s, string_types):\n return op.exists(s)\n else:\n return False", "def test_returns_string_if_inputs_are_valid(self):\n\n # use a real connection here as a sanity check\n ret = get_presigned_upload_url(\n \"a/b/abc.jpg\", \"aBc\", 10, 1, storage=self.STORAGE, client=None\n )\n url = ret[\"uploadURL\"]\n\n assert isinstance(url, str)", "def test_invalid_file_like_types(file):\n with pytest.raises(ValueError) as e:\n WeldxFile(file)\n assert \"path\" in e.value.args[0]", "def is_url(self, path):\n # FIXME: cover more URL types ...\n return path[:7] == \"http://\"" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testing if a TypeError will be raised when the pathurl attribute is set to a value other than a string
def test_pathurl_attribute_is_not_a_string(self): f = File(pathurl='shot1') with self.assertRaises(TypeError) as cm: f.pathurl = 123 self.assertEqual( cm.exception.message, 'File.pathurl should be a string, not int' )
[ "def test_pathurl_argument_is_not_a_string(self):\n with self.assertRaises(TypeError) as cm:\n File(pathurl=123)\n\n self.assertEqual(\n cm.exception.message,\n 'File.pathurl should be a string, not int'\n )", "def test_pathurl_argument_is_skipped(self):\n f = File()\n self.assertEqual('', f.pathurl)", "def test_get_page_raises_type_error_for_non_string_url(value):\n from .context import mangasource\n source = mangasource.MangaSource('test', 'www.test.com', '_')\n with pytest.raises(TypeError):\n scr.Scraper._get_page(value, source)", "def test_pathurl_argument_is_working_properly(self):\n f = File(pathurl='shot2')\n self.assertEqual('file://localhost/shot2', f.pathurl)", "def validate_path(self, path: str) -> bool:\n pass", "def test_void_get_path(self):\r\n self.assertRaises(ValueError,self._httpc.do_get,\"\")", "def is_url(self, path):\n # FIXME: cover more URL types ...\n return path[:7] == \"http://\"", "def test_url_is_pattern_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_pattern())\n # when an invalid url is passed, False should be returned\n self.item.url = 'http://test.com'\n self.assertFalse(self.item.url_is_pattern())\n # when a valid url is passed, True should be returned\n self.item.url = 'admin:auth_user_changelist'\n self.assertTrue(self.item.url_is_pattern())", "def test_url_is_valid_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_valid())\n # when an invalid url is passed, False should be returned\n self.item.url = 'test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = '/test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = 'http://'\n self.assertFalse(self.item.url_is_valid())\n # when a valid url is passed, True should be returned\n self.item.url = 'http://test.com/test'\n self.assertTrue(self.item.url_is_valid())", "def test_invalidArguments(self):\n class Unexpected(object):\n def __str__(self):\n return \"wrong\"\n def __repr__(self):\n return \"<unexpected>\"\n defaultExpectation = \"unicode\" if bytes is str else \"str\"\n def assertRaised(raised, expectation, name):\n self.assertEqual(str(raised.exception),\n \"expected {} for {}, got {}\".format(\n expectation,\n name, \"<unexpected>\"))\n\n def check(param, expectation=defaultExpectation):\n with self.assertRaises(TypeError) as raised:\n URL(**{param: Unexpected()})\n assertRaised(raised, expectation, param)\n check(\"scheme\")\n check(\"host\")\n check(\"fragment\")\n check(\"rooted\", \"bool\")\n check(\"userinfo\")\n check(\"port\", \"int or NoneType\")\n\n with self.assertRaises(TypeError) as raised:\n URL(path=[Unexpected(),])\n assertRaised(raised, defaultExpectation, \"path segment\")\n with self.assertRaises(TypeError) as raised:\n URL(query=[(u\"name\", Unexpected()),])\n assertRaised(raised, defaultExpectation + \" or NoneType\",\n \"query parameter value\")\n with self.assertRaises(TypeError) as raised:\n URL(query=[(Unexpected(), u\"value\"),])\n assertRaised(raised, defaultExpectation, \"query parameter name\")\n # No custom error message for this one, just want to make sure\n # non-2-tuples don't get through.\n with self.assertRaises(TypeError):\n URL(query=[Unexpected()])\n with self.assertRaises(ValueError):\n URL(query=[(u'k', u'v', u'vv')])\n with self.assertRaises(ValueError):\n URL(query=[(u'k',)])\n\n url = URL.fromText(\"https://valid.example.com/\")\n with self.assertRaises(TypeError) as raised:\n url.child(Unexpected())\n assertRaised(raised, defaultExpectation, \"path segment\")\n with self.assertRaises(TypeError) as raised:\n url.sibling(Unexpected())\n assertRaised(raised, defaultExpectation, \"path segment\")\n with self.assertRaises(TypeError) as raised:\n url.click(Unexpected())\n assertRaised(raised, defaultExpectation, \"relative URL\")", "def test_valid_endpoint_uri(test_endpoint):\n\n with pytest.raises(ValueError):\n test_endpoint.uri = False", "def test_convert_full_path_to_file_link_full_path_is_not_a_string(self):\n with self.assertRaises(TypeError) as cm:\n self.test_media_manager.convert_full_path_to_file_link(1)\n\n self.assertEqual(\n '\"full_path\" argument in '\n 'MediaManager.convert_full_path_to_file_link() method should be '\n 'a str, not int',\n str(cm.exception)\n )", "def path_type(val):\n if not path.exists(val):\n raise ValueError('{!r} does not exists'.format(val))\n return val", "def test_get_page_raises_type_error_for_bad_mangasource(value):\n with pytest.raises(TypeError):\n scr.Scraper._get_page('www.test.com', value)", "def test_invalid(self):\n # memento_client raises 'Exception', not a subclass.\n with self.assertRaisesRegex(\n ValueError, 'Only HTTP URIs are supported'):\n self._get_archive_url('invalid')", "def test_technicallyTextIsIterableBut(self):\n with self.assertRaises(TypeError) as raised:\n URL(path=u'foo')\n self.assertEqual(\n str(raised.exception),\n \"expected iterable of text for path, not: {}\"\n .format(repr(u'foo'))\n )", "def test_pathurl_attribute_is_working_properly(self):\n f = File(pathurl='shot1')\n test_value = 'shot2'\n expected_value = 'file://localhost/shot2'\n self.assertNotEqual(test_value, f.pathurl)\n f.pathurl = test_value\n self.assertEqual(expected_value, f.pathurl)", "def test_convert_file_link_to_full_path_link_path_is_not_a_string(self):\n with self.assertRaises(TypeError) as cm:\n self.test_media_manager.convert_file_link_to_full_path(1)\n\n self.assertEqual(\n '\"link_path\" argument in '\n 'MediaManager.convert_file_link_to_full_path() method should be '\n 'a str, not int',\n str(cm.exception)\n )", "def validate(cls, url: str) -> typing.Optional[\"URL\"]:\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testing if the pathurl argument value is correctly passed to the pathurl attribute
def test_pathurl_argument_is_working_properly(self): f = File(pathurl='shot2') self.assertEqual('file://localhost/shot2', f.pathurl)
[ "def test_pathurl_argument_is_skipped(self):\n f = File()\n self.assertEqual('', f.pathurl)", "def test_pathurl_attribute_is_working_properly(self):\n f = File(pathurl='shot1')\n test_value = 'shot2'\n expected_value = 'file://localhost/shot2'\n self.assertNotEqual(test_value, f.pathurl)\n f.pathurl = test_value\n self.assertEqual(expected_value, f.pathurl)", "def is_url(self, path):\n # FIXME: cover more URL types ...\n return path[:7] == \"http://\"", "def validate_path(self, path: str) -> bool:\n pass", "def check_path(self,path) :\n return self.path == path", "def test_url_is_pattern_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_pattern())\n # when an invalid url is passed, False should be returned\n self.item.url = 'http://test.com'\n self.assertFalse(self.item.url_is_pattern())\n # when a valid url is passed, True should be returned\n self.item.url = 'admin:auth_user_changelist'\n self.assertTrue(self.item.url_is_pattern())", "def test_pathIterable(self):\n url = URL(path=[u'hello', u'world'])\n self.assertEqual(url.path, (u'hello', u'world'))", "def test_url_is_valid_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_valid())\n # when an invalid url is passed, False should be returned\n self.item.url = 'test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = '/test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = 'http://'\n self.assertFalse(self.item.url_is_valid())\n # when a valid url is passed, True should be returned\n self.item.url = 'http://test.com/test'\n self.assertTrue(self.item.url_is_valid())", "def validate_url_tab(request, path):\n if request.GET.get('t') not in path:\n raise Http404", "def parm_is_fspath(kwargs):\n r = False\n try:\n p = get_all_parms(kwargs)[0]\n v = p.evalAsString().strip()\n r = p.parmTemplate().type()==hou.parmTemplateType.String and v!=\"\"\n except:\n print(\"ERROR: %s\" % traceback.format_exc())\n return r", "def parm_is_fspath(kwargs):\n r = False\n try:\n p = get_all_parms(kwargs)[0]\n v = p.evalAsString().strip()\n r = p.parmTemplate().type()==hou.parmTemplateType.String and v!=\"\"\n except:\n print \"ERROR: %s\" % traceback.format_exc()\n return r", "def _check_input_path(self, input_path):", "def validateURL(url):", "def is_url(path):\n return path.startswith('http') or \\\n path.startswith('https') or \\\n path.startswith('ftp') or \\\n path.startswith('ftps')", "def isAbsolutePath(*args, **kwargs):\n \n pass", "def test_reformat_weburl_2(self):\n url = ''\n self.assertEqual(self.cmd.reformat_weburl(url), 'Not available')", "def _valid_path(key: str) -> bool:\n if not key.isascii():\n return False\n if set(key) - set(ascii_letters + digits + \"/.-_\"):\n return False\n\n if (\n not key.startswith(\"data/\")\n and (not key.startswith(\"meta/\"))\n and (not key == \"zarr.json\")\n ):\n raise ValueError(f\"keys starts with unexpected value: `{key}`\")\n # todo likely more logics to add there.\n return True", "def _is_path(s):\n if isinstance(s, string_types):\n return op.exists(s)\n else:\n return False", "def test_url_not_passed(self):\n user_request = self.client.post('/', data={'url': ''})\n self.assertContains(user_request, \"Invalid URL\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testing if setting the pathurl attribute will also set the id attribute
def test_pathurl_will_set_the_id_attribute(self): f = File() self.assertEqual(f.id, '') f.pathurl = 'shot2' self.assertEqual(f.id, 'shot2')
[ "def test_pathurl_attribute_is_working_properly(self):\n f = File(pathurl='shot1')\n test_value = 'shot2'\n expected_value = 'file://localhost/shot2'\n self.assertNotEqual(test_value, f.pathurl)\n f.pathurl = test_value\n self.assertEqual(expected_value, f.pathurl)", "def test_setting_href_from_url(self):\n # when url is unset, href should not be set as well.\n self.item.url = ''\n self.item.save()\n self.assertEqual(self.item.href, '')\n # when an absolute url is set for url field href should take it.\n self.item.url = 'http://test.com'\n self.item.save()\n self.assertEqual(self.item.href, self.item.url)\n # when a django url pattern is set for url field href should be set to its path.\n self.item.url = 'admin:auth_user_changelist'\n self.item.save()\n self.assertEqual(self.item.href, '/admin/auth/user/')\n # when url field set to a relative, href take the same value.\n self.item.url = '/test'\n self.item.save()\n self.assertEqual(self.item.href, self.item.url)\n # when the url field is set and valid as well as content_object, href should prioritize url field.\n self.item.content_object = self.item\n self.item.save()\n self.assertEqual(self.item.href, self.item.url)\n # when the url field is not set or valid but content_object is set, href should be equal to the conten_object\n # get_absolute_url() value.\n self.item.url = ''\n self.item.save()\n self.assertEqual(self.item.href, self.item.get_absolute_url())", "def test_pathurl_argument_is_working_properly(self):\n f = File(pathurl='shot2')\n self.assertEqual('file://localhost/shot2', f.pathurl)", "def test_id_is_generated_from_pathurl(self):\n f = File(\n pathurl='file://localhost/S:/KKS/Sequences/SEQ001/001A_TNGE/Shots'\n '/Seq001_001A_TNGE_0010/Comp/Outputs/Main/v001/exr/'\n 'KKS_Seq001_001A_TNGE_0010_Comp_Main_v001.%5B000-379%5D'\n '.exr'\n )\n expected_result = 'KKS_Seq001_001A_TNGE_0010_Comp_Main_v001.' \\\n '[000-379].exr'\n self.assertEqual(expected_result, f.id)", "def path_id(self, path_id: str):\n\n self._path_id = path_id", "def assign_url(context):", "def test_init_uses_generic_url_name(self):\n with patch.object(self.Widget, 'generic_url_name'):\n self.Widget.generic_url_name = ''\n self.assertEqual(self.Widget(model_name='genre')._url, '')\n self.Widget.generic_url_name = 'this-is-the-default'\n self.assertEqual(self.Widget(model_name='genre')._url, 'this-is-the-default')\n self.assertEqual(self.Widget(model_name='genre', url='nocapture')._url, 'nocapture')", "def test_pathIterable(self):\n url = URL(path=[u'hello', u'world'])\n self.assertEqual(url.path, (u'hello', u'world'))", "def test_pathurl_argument_is_skipped(self):\n f = File()\n self.assertEqual('', f.pathurl)", "def check_path(self,path) :\n return self.path == path", "def setURI(*args, **kwargs):\n \n pass", "def test_thumbnail_url_if_set(self):\n img = ImageFactory()\n eq_(img.file.url, img.thumbnail_url_if_set())\n\n generate_thumbnail(img, 'file', 'thumbnail')\n eq_(img.thumbnail.url, img.thumbnail_url_if_set())", "def test_get_resource_path_for_existing_resources(self):\n self.assertEqual(\n \"http://localhost/first\", self.descriptor.get_resource_path(\"first-red\")\n )\n self.assertEqual(\n \"http://localhost/second\", self.descriptor.get_resource_path(\"second-blue\")\n )", "def test_url_endpoint(self):\n url = url_for('view_activities')\n assert url == '/activities/'", "def setHref(self, href):", "def test_patch_obj_id_get(self):\n pass", "def set_custom_url(self, url):\n i = self.identifiers.filter(database=EXTERNAL_LINK).first()\n if i:\n i.url = url\n i.save()\n else:\n unique_id = Identifiers.get_max_external_id() + 1\n self.identifiers.add(\n Identifiers.objects.create(\n database=EXTERNAL_LINK, unique_id=unique_id, url=url))", "def _append_id_name(self, url, value):\n return '{}/id/{}'.format(url, value) if self._is_int(value) else '{}/name/{}'.format(url, value)", "def test_url_is_pattern_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_pattern())\n # when an invalid url is passed, False should be returned\n self.item.url = 'http://test.com'\n self.assertFalse(self.item.url_is_pattern())\n # when a valid url is passed, True should be returned\n self.item.url = 'admin:auth_user_changelist'\n self.assertTrue(self.item.url_is_pattern())" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testing if the pathurl attribute value can be correctly changed
def test_pathurl_attribute_is_working_properly(self): f = File(pathurl='shot1') test_value = 'shot2' expected_value = 'file://localhost/shot2' self.assertNotEqual(test_value, f.pathurl) f.pathurl = test_value self.assertEqual(expected_value, f.pathurl)
[ "def test_pathurl_argument_is_working_properly(self):\n f = File(pathurl='shot2')\n self.assertEqual('file://localhost/shot2', f.pathurl)", "def test_pathurl_will_set_the_id_attribute(self):\n f = File()\n self.assertEqual(f.id, '')\n f.pathurl = 'shot2'\n self.assertEqual(f.id, 'shot2')", "def test_setting_href_from_url(self):\n # when url is unset, href should not be set as well.\n self.item.url = ''\n self.item.save()\n self.assertEqual(self.item.href, '')\n # when an absolute url is set for url field href should take it.\n self.item.url = 'http://test.com'\n self.item.save()\n self.assertEqual(self.item.href, self.item.url)\n # when a django url pattern is set for url field href should be set to its path.\n self.item.url = 'admin:auth_user_changelist'\n self.item.save()\n self.assertEqual(self.item.href, '/admin/auth/user/')\n # when url field set to a relative, href take the same value.\n self.item.url = '/test'\n self.item.save()\n self.assertEqual(self.item.href, self.item.url)\n # when the url field is set and valid as well as content_object, href should prioritize url field.\n self.item.content_object = self.item\n self.item.save()\n self.assertEqual(self.item.href, self.item.url)\n # when the url field is not set or valid but content_object is set, href should be equal to the conten_object\n # get_absolute_url() value.\n self.item.url = ''\n self.item.save()\n self.assertEqual(self.item.href, self.item.get_absolute_url())", "def test_url_is_pattern_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_pattern())\n # when an invalid url is passed, False should be returned\n self.item.url = 'http://test.com'\n self.assertFalse(self.item.url_is_pattern())\n # when a valid url is passed, True should be returned\n self.item.url = 'admin:auth_user_changelist'\n self.assertTrue(self.item.url_is_pattern())", "def test_url_is_valid_validation(self):\n # when url is unset, False should be returned.\n self.item.url = ''\n self.assertFalse(self.item.url_is_valid())\n # when an invalid url is passed, False should be returned\n self.item.url = 'test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = '/test.com'\n self.assertFalse(self.item.url_is_valid())\n self.item.url = 'http://'\n self.assertFalse(self.item.url_is_valid())\n # when a valid url is passed, True should be returned\n self.item.url = 'http://test.com/test'\n self.assertTrue(self.item.url_is_valid())", "def double_slash_testing(self):\n if \"//\" in self.url:\n self.doubleSlashWeight = 1\n return\n self.doubleSlashWeight = 0\n return", "def check_path(self,path) :\n return self.path == path", "def test_pathurl_argument_is_skipped(self):\n f = File()\n self.assertEqual('', f.pathurl)", "def is_url(self, path):\n # FIXME: cover more URL types ...\n return path[:7] == \"http://\"", "def test_pathIterable(self):\n url = URL(path=[u'hello', u'world'])\n self.assertEqual(url.path, (u'hello', u'world'))", "def test_patch_path(self):\n self.assertEqual(\n utils.patch_path(\n '/Users/sudeep.agarwal/src/squiddy/api/v0.1',\n '/Users/sudeep.agarwal/src/squiddy/api/v0.1/swagger.yaml',\n ), '/Users/sudeep.agarwal/src/squiddy/api/v0.1/swagger.yaml')", "def test_reformat_weburl_2(self):\n url = ''\n self.assertEqual(self.cmd.reformat_weburl(url), 'Not available')", "def test_cloneUnchanged(self):\n urlpath = URL.fromText('https://x:1/y?z=1#A')\n self.assertEqual(\n urlpath.replace(urlpath.scheme,\n urlpath.host,\n urlpath.path,\n urlpath.query,\n urlpath.fragment,\n urlpath.port),\n urlpath)\n self.assertEqual(\n urlpath.replace(),\n urlpath)", "def testSetPath(self):\n original = mib.path()\n current = original + \":/some/other/directory\"\n try:\n mib.path(current)\n self.assertEqual(mib.path(), current)\n finally:\n mib.path(original)", "def test_valid_endpoint_uri(test_endpoint):\n\n with pytest.raises(ValueError):\n test_endpoint.uri = False", "def validate_path(self, path: str) -> bool:\n pass", "def set_path(self, path):\n self.url = parse.urlparse(self.url)._replace(path=path).geturl()", "def test_url(self):\n self.assertEqual(['http://url/'], self.__report.metric_source_urls('http://url/'))", "def test_returns_false_if_request_path_doesnt_match_regexp(self):\n self.request_mock.path = '/some_other_path/foobar'\n self.assertFalse(self.path_matches(self.get_response_mock, self.request_mock))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
testing if the id attribute is generated from pathurl and it is equal to the file name
def test_id_is_generated_from_pathurl(self): f = File( pathurl='file://localhost/S:/KKS/Sequences/SEQ001/001A_TNGE/Shots' '/Seq001_001A_TNGE_0010/Comp/Outputs/Main/v001/exr/' 'KKS_Seq001_001A_TNGE_0010_Comp_Main_v001.%5B000-379%5D' '.exr' ) expected_result = 'KKS_Seq001_001A_TNGE_0010_Comp_Main_v001.' \ '[000-379].exr' self.assertEqual(expected_result, f.id)
[ "def test_pathurl_will_set_the_id_attribute(self):\n f = File()\n self.assertEqual(f.id, '')\n f.pathurl = 'shot2'\n self.assertEqual(f.id, 'shot2')", "def check_id(self):\n\n is_file = os.path.isfile(self.id_path)\n is_valid = self.validate_id_file()\n return bool(is_file and is_valid)", "def validate_id_file(self):\n\n try:\n f_id = open(self.id_path, \"r\")\n except IOError:\n return False\n\n is_valid = bool(re.search(get_id_re(), f_id.read()))\n\n f_id.close()\n\n return is_valid", "def id_file(cls, user):\n try:\n return user.files.filter(filetype=cls.ID_FILE).latest('created')\n except cls.DoesNotExist:\n return False", "def test_api_v3_files_file_public_id_get(self):\n pass", "def test_get_identifier(self):\n loader = Loader('/path/to/data/identifier_example.npz')\n self.assertEqual(loader.get_identifier(), 'identifier')", "def file_id():\n return uuid4()", "def file_exists(self, resource: GenomicResource, filename: str) -> bool:", "def parse_id(filename):\n match = re.search('B[0-9]{2}-[0-9]{3}', filename) \n if match:\n return match.group()\n return None", "def get_id_from_filename(html_filename):\n\treturn html_filename[ html_filename.rindex('_') + 1 : -len('.html') ]", "def file_id(file_path):\n file_id = file_path.split(\"/\")[-1]\n file_id = file_id.split(\".\")[0]\n return file_id", "def test_api_v3_linked_files_linked_file_public_id_get(self):\n pass", "def _load_ID_file(self):\n if not os.path.exists(self._test_IDs_file):\n return False\n\n # Read in the IDs and build paths to predicted labels\n with open(self._test_IDs_file, 'r') as f:\n self._test_IDs = f.readlines()\n self._test_IDs = [ID.rstrip() for ID in self._test_IDs]\n\n # Build file and folder paths\n self._sem_labels_paths = [self._test_folder + '/' + idx + '/pred_sem_label/' + idx + '.png' for idx in self._test_IDs]\n sub_folder = '/pred_contours_{}px/'.format(self.options['contour_thickness'])\n self._sem_contours_paths = [self._test_folder + '/' + idx + sub_folder + idx + '.png' for idx in self._test_IDs]\n self._labeled_mask_paths = [self._test_folder + '/' + idx + '/pred_labeled_mask/' + idx + '.png' for idx in self._test_IDs]\n self._inst_masks_folders = [self._test_folder + '/' + idx + '/pred_inst_masks/' for idx in self._test_IDs]\n\n return True", "def _is_by_id_path(path: str):\n dev_by_id_dir = \"/dev/disk/by-id\"\n by_id_paths = parse_ls_output(ls(dev_by_id_dir), dev_by_id_dir)\n return path in [posixpath.join(dev_by_id_dir, id_path.full_path) for id_path in by_id_paths]", "def exists(self, file_id):\n raise NotImplementedError", "def hasfilename(self):\n return self._filename is not None and (os.path.exists(self._filename) or isRTSPurl(self._filename) or isRTMPurl(self._filename))", "def test_get_image_id_by_name_in_uuid(self):\r\n my_image = self.m.CreateMockAnything()\r\n img_id = str(uuid.uuid4())\r\n img_name = str(uuid.uuid4())\r\n my_image.id = img_id\r\n my_image.name = img_name\r\n self.glance_client.images = self.m.CreateMockAnything()\r\n self.glance_client.images.get(img_name).AndRaise(\r\n glance_exceptions.NotFound(404))\r\n filters = {'name': img_name}\r\n self.glance_client.images.list(filters=filters).MultipleTimes().\\\r\n AndReturn([my_image])\r\n self.m.ReplayAll()\r\n\r\n self.assertEqual(img_id, glance_utils.get_image_id(self.glance_client,\r\n img_name))\r\n self.m.VerifyAll()", "def test_unique_filename_format(self):\n # Confirm that the format of the filename is correct\n result = uniqify_filename('hey.png')\n self.assertTrue(\n re.search(\n r'^[0-9a-f]{32}\\.png$',\n result\n )\n )", "def path2IdName(cls, path):\n idname = path.split('/')[-1]\n if idname.endswith('.html'):\n idname = '.'.join(idname.split('.')[:-1])\n return idname" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the configuration for a given word.
def get_conf(self, word): return self.__provider.get_conf(word)
[ "def get_word(self):\n # Todo get a list of words fron somewhere\n pass", "def get_word(self, word_str):\n return self.words[word_str]", "def get_conf(self, comp, conf_name):\r\n for cfg in comp.configuration_sets[0].configuration_data:\r\n if cfg.name == conf_name:\r\n return cfg.data\r\n return None", "def _getconf(self, directory=None):\n if directory is None:\n directory = self.curdir\n path = os.path.abspath(os.path.join(self.curdir, directory))\n return self.configs.get(path, {})", "def define(word):\n word = word.lower()\n url = base_url + word\n results = get_json_data.grab_json_data(url, True, app_id, app_key)\n define_word = []\n get_def = results[\"results\"][0][\"lexicalEntries\"][0][\"entries\"][0][\"senses\"]\n for things in get_def:\n define_word.extend(things[\"definitions\"])\n return define_word", "def word_definition(word):\n wdef_endpoint=\"/word/{0}/definitions?api_key={1}\".format(word,api_key)\n data = requester(wdef_endpoint)\n \n definition = list()\n \n if(data['status'] == 200): \n for i in data['data']:\n definition.append(i['text'])\n else: \n definition.append('No Definitions for the word'.format(word))\n \n return definition", "def get(self, name: str, default=None):\n if name in self.__config:\n return self.__config[name]\n if '.' in name:\n names = name.split('.')\n cur = self.__config\n for name in names:\n if type(cur) is dict and name in cur:\n cur = cur[name]\n else:\n return default\n return cur\n return default", "def get(self, botconf, cat=None):\n setting = botconf.get(self.name)\n return setting if (setting is not None) else self.default", "def get_word(self, word):\n\n\t\ttry:\n\t\t\tword_file = open(DICTIONARY_DB_PATH + word + \".dict\", \"rb\")\n\t\t\tword_object = pickle.load(word_file)\n\t\t\tword_file.close()\n\n\t\texcept IOError as err:\n\t\t\tword_object = self._crawl(word)\n\n\t\tself._save()\n\t\treturn word_object", "def getWordAndLanguage(self, wid):\n return self._wids.get(wid, None)", "def get_word(self, sol : str) -> Word:\n for w in self.words:\n if str(w) == sol:\n return w\n print(\"Error: Word not found.\")\n return None", "def get_config(name: str):\n # 1. Check environment variables\n env_name = name.replace(\"_\", \"__\").replace(\".\", \"_\").upper()\n env_val = os.getenv(\"IOT_\" + env_name)\n if env_val:\n if \";\" in env_val:\n return [v.strip() for v in env_val.split(\";\")]\n return env_val\n\n # 2. Check config file\n keys = name.split(\".\")\n val = _CONFIG_YAML\n for k in keys:\n if isinstance(val, dict):\n val = val.get(k, {})\n\n if val:\n return val\n raise ValueError(f'\"{name} not found')", "def get_word(word=None):\n url = WORDS_URL\n if word is None or word == \"\":\n url += WORDS_RANDOM\n\n else:\n url += word\n headers = {'X-Mashape-Key': os.environ['MASHAPE_KEY']}\n\n r = requests.get(url, headers=headers)\n r.raise_for_status()\n return r.json()", "def get_conf(self, name='global'):\n return self.cluster_configuration_manager.get_object(name)", "async def wordnik_define(self, ctx, *, word):\r\n wordApi = WordApi.WordApi(Dictionary.WordClient)\r\n\r\n parts_of_speech = {'noun': 'n.', 'verb': 'v.', 'adjective': 'adj.', 'adverb': 'adv.',\r\n 'interjection': 'interj.', 'conjunction': 'conj.', 'preposition': 'prep.', 'pronoun': 'pron.'}\r\n\r\n result = wordApi.getDefinitions(word)\r\n\r\n if not result:\r\n return await ctx.send(\"Sorry, couldn't find that one.\")\r\n\r\n final_result = result[0]\r\n\r\n for pos in parts_of_speech:\r\n if pos in final_result.partOfSpeech.split('-'):\r\n word_pos = parts_of_speech[pos]\r\n break\r\n else:\r\n word_pos = final_result.partOfSpeech\r\n\r\n await ctx.send(f'{word.title()} _{word_pos}_ `{final_result.text}`')", "def getWord(self, wid):\n try:\n return self._wids.get(wid)[0]\n except KeyError:\n return None", "async def define(self, word: str):\n api_key = \"e02fb0b8-5f3e-4d5c-b868-87dd7de88974\"\n\n # Checks for mutliple words and only uses first\n if \" \" in word:\n word = word.split(\" \")[0]\n\n url = \"http://www.dictionaryapi.com/api/v1/references/collegiate/xml/{}?key={}\".format(word.lower(), api_key)\n\n response = requests.get(url)\n results = ElementTree.fromstring(response.text)\n\n \"\"\"\n Tag descriptions:\n\n entry_list - root\n entry - ( ͡° ͜ʖ ͡°)\n fl - word type\n def - contains date and definitions\n dt - sub tag of def, contains definitions\n\n suggestion - returns if the word can't be found\n \"\"\"\n\n suggestions = []\n\n for entry in islice(results, 0, 3):\n # Add suggestions to list if the word isn't found\n if entry.tag == \"suggestion\":\n suggestions.append(entry.text)\n continue\n word = entry.find(\"ew\").text\n word_type = entry.find(\"fl\").text\n word_def = entry.find(\"def\").find(\"dt\").text\n\n try:\n # First definition sometimes returns blank results for some\n # reason, skipping to the next description tag fixes it.\n if word_def == \":\":\n word_def = entry.find(\"def\").findall(\"dt\")[1].text\n\n await self.bot.say(\"**{}**\\n*{}*\\n{}\".format(\n word, word_type, word_def)\n )\n except IndexError:\n continue\n\n if suggestions:\n await self.bot.say(\n \"That's not a word, maybe you meant: {}\".format(\n \", \".join(suggestions)\n )\n )", "def get_word_index(self, word):\n if self.contain(word):\n return self.dict[word]\n else:\n raise ValueError('Cannot find the word: {0}'.format(word))", "def get(name):\n value = Configuration.settings.get(name, None)\n\n if value is None:\n raise ConfigurationNotFound(name)\n\n return value" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the TestLooperHttpServer testManager a TestManager.TestManager object httpPortOverride the port to listen on for http requests
def __init__(self, portConfig, httpServerConfig, serverConfig, testManager, machine_management, artifactStorage, src_ctrl, event_log ): self.testManager = testManager self.machine_management = machine_management self.httpServerConfig = httpServerConfig self.httpPort = portConfig.server_https_port self.src_ctrl = src_ctrl self.eventLog = event_log self.eventLog.addLogMessage("test-looper", "TestLooper initialized") self.defaultCoreCount = 4 self.artifactStorage = artifactStorage self.certs = serverConfig.path_to_certs.val if serverConfig.path_to_certs.matches.Value else None self.address = ("https" if self.certs else "http") + "://" + portConfig.server_address + ":" + str(portConfig.server_https_port) self.websocket_address = ("wss" if self.certs else "ws") + "://" + portConfig.server_address + ":" + str(portConfig.server_https_port) self.accessTokenHasPermission = {} self.regular_renderer = TestLooperHtmlRendering.Renderer(self) self.linuxOnly = serverConfig.linuxOnly
[ "def setUp(self):\n\n self.testport = random.randint(40000, 65530)\n self.server = TServer.TSimpleServer(TestService.Processor(self),\n EzSSLServerSocket(host='localhost', \n port=self.testport,\n certfile=SERVER_CRT,\n ca_certs=CA_CERT,\n keyfile=SERVER_KEY))\n self.serverThread = threading.Thread(target=TServer.TSimpleServer.serve, args=(self.server,))\n self.serverThread.setDaemon(True)\n self.serverThread.start()", "def setUp(self):\n self.realm = TestRealm()\n self.portal = portal.Portal(self.realm)\n self.factory = ConnectionNotifyServerFactory(self.portal)\n self.port = reactor.listenTCP(0, self.factory, interface=\"127.0.0.1\")\n self.portno = self.port.getHost().port", "async def test_server_init() -> None:\n requester = UpnpTestRequester(RESPONSE_MAP)\n server = AiohttpNotifyServer(requester, (\"192.168.1.2\", 8090))\n assert server._loop is not None\n assert server.listen_host == \"192.168.1.2\"\n assert server.listen_port == 8090\n assert server.callback_url == \"http://192.168.1.2:8090/notify\"\n assert server.event_handler is not None\n\n server = AiohttpNotifyServer(\n requester, (\"192.168.1.2\", 8090), \"http://1.2.3.4:8091/\"\n )\n assert server.callback_url == \"http://1.2.3.4:8091/\"", "def __init__(self, ip='', ds = Datastore(), pm = Portmanager(50000,1000)):\n shared = Server.Shared(ds, pm, str(ip))\n self.http = ThreadedHttpServer((str(ip), http_port()), HttpHandler, shared)\n self.http.daemon_threads = True\n self.rh = RequestHandler(ip, multicast_port(), shared)\n self.rh.setDaemon(True)", "def setUp(self):\n self.daemon = TransmissionClient(SOCKETPATH)", "def set_test_env(self):\n test_urls = getattr(self, \"test_urls\", [])\n test_headers = getattr(self, \"test_headers\", {})\n if not test_urls:\n logging.error(\"test urls were not set in Worker class, exit\")\n else:\n logging.info(\"test_urls %s \" % \",\".join(test_urls))\n\n req_d = init_req_data(self.crawler_name)\n resp_d = init_resp_data(self.crawler_name)\n\n resp_arr = []\n for url in test_urls:\n resp = requests.get(url, headers=test_headers)\n req_d = init_req_data(self.crawler_name)\n resp_d = init_resp_data(self.crawler_name)\n resp_d[\"html\"] = resp.content\n resp_d[\"url\"] = resp.url\n resp_d[\"status_code\"] = resp.status_code\n resp_d[\"reason\"] = resp.status_code\n resp_d[\"headers\"] = {}\n req_d[\"url\"] = url\n resp_d[\"http_request\"] = json.dumps(req_d)\n for k, v in resp.headers.items():\n resp_d[\"headers\"][k] = v\n resp_arr.append(json.dumps(resp_d))\n\n rabbitmq_conn = create_conn(self.cfg)\n ch = rabbitmq_conn.channel()\n resp_q = ResponseQueue(\n self.crawler_name,\n ssdb_clients=self.ssdb_clients\n )\n for resp_data in resp_arr:\n resp = Response()\n resp.from_json(resp_data)\n resp_key = 'http_response:%s:%s' % (self.crawler_name, resp.url)\n resp_q.push_cache(resp, resp_key)\n resp_q.push(resp_key, ch)\n ch.close()\n rabbitmq_conn.close()", "def runserver(args):\n TestServer().run(args.port)", "def __init__(self, port: str = '8000', **kwargs: Any) -> None:\n super(PrometheusMonitor, self).__init__(**kwargs)\n start_http_server(int(port))\n self.state: Dict[str, Any] = {}", "async def start(self):\n self._app = web.Application(\n loop=self._loop, middlewares=self._middlewares\n )\n for resource in self._nyuki.HTTP_RESOURCES:\n resource.RESOURCE_CLASS.register(self._nyuki, self._app.router)\n log.info(\"Starting the http server on {}:{}\".format(self._host, self._port))\n self._handler = self._app.make_handler(access_log=access_log)\n self._server = await self._loop.create_server(\n self._handler, host=self._host, port=self._port\n )", "def setUpModule():\n global WEBDRIVER_SERVER_URL\n global WEBDRIVER_PROCESS\n if not WEBDRIVER_SERVER_URL:\n WEBDRIVER_SERVER_URL = 'http://localhost:%d' % WEBDRIVER_PORT\n WEBDRIVER_PROCESS = subprocess.Popen([WEBDRIVER_EXE,\n '--port=%d' % WEBDRIVER_PORT])\n time.sleep(3)", "def __init__(self, host, port):\n self.base_url = \"http://{}:{:d}{}\".format(host, port, self.ENDPOINT)\n self.root = Proxy(self, \"\")\n self.session = requests.Session()", "def setUpClass(cls) -> None:\n with allure.step(\"Get args from CLI\"):\n # cls.args = get_args()\n pass\n\n with allure.step(\"Set test URL\"):\n cls.URL = 'http://127.0.0.1:5000'\n\n with allure.step(\"Start REST API Service\"):\n print(\"\\nOS: {}\\n\".format(platform.system()))\n\n if platform.system() == 'Windows':\n os.system(\"start /B start cmd.exe @cmd /k python ../api/cars_app.py\")\n time.sleep(5)\n\n if platform.system() == 'Linux':\n # os.system(\"python ../cars_app.py &\")\n pass", "def start_http_server(port, addr=''):\n class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):\n pass\n class PrometheusMetricsServer(threading.Thread):\n def run(self):\n httpd = ThreadingSimpleServer((addr, port), MetricsHandler)\n httpd.serve_forever()\n t = PrometheusMetricsServer()\n t.daemon = True\n t.start()", "def __init__(self, config, multi=True):\n self.port = config['logging']['port'] \\\n or logging.handlers.DEFAULT_TCP_LOGGING_PORT\n self.host = 'localhost'\n self.config = config\n self.multi = multi", "def setUp(self):\n\n\t\tself.app = tiny.TinyApp()\n\t\t\n\t\thandler = lambda x: tiny.TinyResponse('test')\n\t\tself.app.add_route('/index', handler, ['GET', 'POST'])", "def setUp(self):\n\n\t\tself.app = tiny.TinyApp()\n\t\tself.environ = create_environ('/index', 'GET')\n\t\tself.request = tiny.TinyRequest(self.environ)", "def __init__( self, url = None ):\n Client.__init__( self )\n self.setServer( 'DataManagement/DataLogging' )\n if url:\n self.setServer( url )\n self.setTimeout( 120 )", "def run(self):\n self.server = HTTPServer(('', HttpServer.serverPort), HttpHandler)\n self.server.timeout = HttpServer.timeout\n self.server.msg_queue = self.msg_queue\n logger.warning(\"HTTP server running\")\n try:\n while True:\n self.server.handle_request()\n try:\n msg: HttpMessage = self.msg_queue.get(False)\n self.update_state(msg)\n logger.debug(\"HTTP message received\")\n except Empty:\n pass\n except Exception:\n print(sys.exc_info())\n\n logger.warning(\"HTTP server terminating\")", "def create_servers(self):\n port = tempesta.upstream_port_start_from()\n self.servers = [deproxy.Server(port=port)]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Script that takes the file name "input.csv" and convert it into a .json file named output.json The first row of the csv file is the field name, the other rows are the values
def main(): filepath = "input.csv" delim = ";" if len(sys.argv) > 1: filepath = sys.argv[1] if len(sys.argv) > 2: delim = ";" conversion(filepath, delim, "output.json")
[ "def to_json(filename, csv_input):\n if not filename.endswith(\".json\"):\n if filename == \"\":\n filename = \"output\"\n filename += filename + \".json\"\n\n with open(os.path.join(os.path.realpath('..'), 'src', filename), 'w+') as json_file:\n json_output = json.dumps(csv_input, sort_keys=True)\n json_file.write(json_output)", "def make_json(csvFilePath, jsonFilePath):\n \n \n data = {}\n \n # Open a csv reader called DictReader\n with open(csvFilePath, encoding='utf-8') as csvf:\n csvReader = csv.DictReader(csvf)\n \n # Convert each row into a dictionary and add it to data\n for rows in csvReader:\n \n key = rows['id']\n data[key] = rows\n \n \n with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:\n jsonf.write(json.dumps(data, indent=4))", "def conversion(path, delim, json_filename):\n csv_input = []\n\n try:\n #Conversion csv to json\n with open(path,\"rt\") as csv_file:\n reader = csv.reader(csv_file, delimiter=delim, quoting=csv.QUOTE_ALL)\n fieldnames = next(reader)\n reader = csv.DictReader(csv_file, delimiter=delim, fieldnames=fieldnames)\n for row in reader:\n if row[fieldnames[0]] != '':\n csv_input.append(row)\n to_json(json_filename, csv_input)\n\n except FileNotFoundError:\n print(path +\" was not found\")", "def json2csv(input_file, output_file=None, header_values=None):\n file_out = open_fr(input_file, encoding=ENCODING)\n # set output file name and write header\n if output_file is None:\n output_file = os.path.splitext(os.path.basename(input_file))[0] + \".csv\"\n csv_out = open_fw(output_file, encoding=ENCODING)\n if os.name == 'nt':\n outfile = csv.DictWriter(csv_out, dialect='excel', escapechar=\"\\\\\",\n lineterminator='\\n',\n fieldnames=header_values)\n else:\n outfile = csv.DictWriter(csv_out, dialect='excel',\n escapechar=\"\\\\\", fieldnames=header_values)\n raw_data = json.loads(file_out.read())\n outfile.writeheader()\n\n for item in raw_data:\n outfile.writerow(item)\n file_out.close()\n subprocess.call(['rm', '-r', input_file])\n return output_file", "def write_input_csv_to_file(in_csv):\n return", "def write_json(input, output, id, league):\n\n with open(input, newline='') as data:\n reader = csv.DictReader(data)\n file_w = open(output, 'w')\n json_list = {}\n headers = reader.fieldnames\n\n # For every line create a key and its attributes.\n for line in reader:\n # Select items from correct league\n if line['League'] == league:\n child = {}\n for item in headers:\n # Skip id\n if item != id:\n child[item] = line[item].replace(',', '')\n json_list[line[id]] = child\n\n json.dump(json_list, file_w, indent=2)\n data.close()\n file_w.close()", "def convert_json_to_csv(path_in=\"./Auc-ScanData.json\", path_out=\"./Auc-ScanData.csv\"):\n print \"--------------------\"\n print \"convert_json_to_csv\" # TODO: refactor to py3\n print \"--------------------\"\n print \"Reading in\", path_in # TODO: refactor to py3\n with open(path_in, \"r\") as f:\n content = json.load(f)\n\n data = content['scans']['Mograine']['ropes'][0]\n data = data.lstrip(\"return \")\n data = data.replace(\"{\", \"\")\n data = data.replace(\"},\", \"\\n\")\n\n print \"Writing to\", path_out # TODO: refactor to py3\n with open(path_out, \"w\") as out: \n out.write(data.encode('utf-8'))", "def read_and_write_file(json_file_path, csv_file_path, column_names):\n with open(csv_file_path, 'w') as fout:\n csv_file = csv.writer(fout)\n csv_file.writerow(list(column_names))\n with open(json_file_path) as fin:\n for line in fin:\n line_contents = json.loads(line)\n csv_file.writerow(get_row(line_contents, column_names))", "def collateJSONfilesToSingleCSV(inputJsonDir, outputCsvFile):\n\n # First combine into <tmpJsonFile> the processed outputs from <inputJsonDir>\n tmpJsonFile = outputCsvFile.replace('.csv', '-tmp.json')\n count = 0\n with open(tmpJsonFile, 'w') as fSummary:\n for fStr in glob.glob(inputJsonDir + \"*.json\"):\n if fStr == tmpJsonFile:\n continue\n with open(fStr) as f:\n if count == 0:\n fSummary.write('[')\n else:\n fSummary.write(',')\n fSummary.write(f.read().rstrip())\n count += 1\n fSummary.write(']')\n\n # Convert temporary json file into csv file\n dict = json.load(open(tmpJsonFile, \"r\"), object_pairs_hook=OrderedDict) # read json\n df = pd.DataFrame.from_dict(dict) # create pandas object from json dict\n refColumnItem = next((item for item in dict if item['quality-goodWearTime'] == 1), None)\n dAcc = df[list(refColumnItem.keys())] # maintain intended column ordering\n # infer participant ID\n dAcc['eid'] = dAcc['file-name'].str.split('/').str[-1].str.replace('.CWA', '.cwa').str.replace('.cwa', '')\n dAcc.to_csv(outputCsvFile, index=False)\n # remove tmpJsonFile\n os.remove(tmpJsonFile)\n print('Summary of', str(len(dAcc)), 'participants written to:', outputCsvFile)", "def transform_csv_file(input_path, output_path):\n print('Transforming {} to {}.'.format(input_path, output_path))\n # Convert the rows to a usable format.\n rows = convert_input_file_to_output_rows(input_path=input_path)\n # Write the rows to the output file.\n with open(output_path, 'w+', encoding='latin-1') as file:\n writer = csv.DictWriter(file, fieldnames=OUTPUT_COLUMNS)\n writer.writeheader()\n writer.writerows(rows)", "def csv_to_geojson(in_csv, out_geojson, x=\"longitude\", y=\"latitude\"):\n import pandas as pd\n import geopandas as gpd\n\n if not os.path.exists(in_csv):\n raise FileNotFoundError(\"The input csv does not exist.\")\n\n if not out_geojson.lower().endswith(\".geojson\"):\n raise ValueError(\"out_geojson must have the .geojson file extension.\")\n\n out_dir = os.path.dirname(out_geojson)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n df = pd.read_csv(in_csv)\n col_names = df.columns.values.tolist()\n\n if x not in col_names:\n raise ValueError(f\"x must be one of the following: {', '.join(col_names)}\")\n\n if y not in col_names:\n raise ValueError(f\"y must be one of the following: {', '.join(col_names)}\")\n\n gdf = gpd.GeoDataFrame(\n df, crs=\"epsg:4326\", geometry=gpd.points_from_xy(df[x], df[y])\n )\n gdf.to_file(out_geojson, driver=\"GeoJSON\")", "def convert_business_json_file_to_csv(json_file_path, csv_file_path):\n write_dir = os.path.dirname(csv_file_path)\n if not os.path.isdir(write_dir):\n os.mkdir(write_dir)\n with io.open(csv_file_path, 'w', encoding='utf-8') as new_f:\n new_f.write(u'biz_id,name,neighborhood,address,city,state,postal_code,latitude,longitude,'\n u'stars,is_open,'\n u'gf_dessert,gf_dinner,gf_latenight,gf_lunch,gf_breakfast,gf_brunch,'\n u'has_tv,has_delivery,accept_credit_cards,outdoor_seating,takes_reservations,'\n u'monday_hours,tuesday_hours,wednesday_hours,thursday_hours,friday_hours,'\n u'saturday_hours,sunday_hours\\n')\n with open(json_file_path, 'r') as old_f:\n for line in old_f:\n biz_json = json.loads(line)\n if 'GoodForMeal' in biz_json['attributes']:\n biz_csv = u'{biz_id},{name},{neighborhood},{address},{city},{state},' \\\n u'{postal_code},{latitude},{longitude},{stars},{is_open},' \\\n u'{gf_dessert},{gf_dinner},{gf_latenight},{gf_lunch},{gf_breakfast},{gf_brunch},' \\\n u'{has_tv},{has_delivery},{accept_credit_cards},{outdoor_seating},{takes_reservations},' \\\n u'{mon_hours},{tues_hours},{wed_hours},{thurs_hours},{fri_hours},{sat_hours},' \\\n u'{sun_hours}\\n'.format(\n biz_id=biz_json['business_id'].replace(',', ' '),\n name=biz_json['name'].replace(',', ' '),\n neighborhood=biz_json['neighborhood'].replace(',', ' '),\n address=biz_json['address'].replace(',', ' '),\n city=biz_json['city'].replace(',', ' '),\n state=biz_json['state'].replace(',', ' '),\n postal_code=biz_json['postal_code'].replace(',', ' '),\n latitude=biz_json['latitude'],\n longitude=biz_json['longitude'],\n stars=biz_json['stars'],\n is_open=biz_json['is_open'],\n gf_dessert=biz_json['attributes']['GoodForMeal'].get('dessert', ''),\n gf_dinner=biz_json['attributes']['GoodForMeal'].get('dinner', ''),\n gf_latenight=biz_json['attributes']['GoodForMeal'].get('latenight', ''),\n gf_lunch=biz_json['attributes']['GoodForMeal'].get('lunch', ''),\n gf_breakfast=biz_json['attributes']['GoodForMeal'].get('breakfast', ''),\n gf_brunch=biz_json['attributes']['GoodForMeal'].get('brunch', ''),\n has_tv=biz_json['attributes'].get('HasTV', ''),\n has_delivery=biz_json['attributes'].get('RestaurantsDelivery', ''),\n accept_credit_cards=biz_json['attributes'].get('BusinessAcceptsCreditCards', ''),\n outdoor_seating=biz_json['attributes'].get('OutdoorSeating', ''),\n takes_reservations=biz_json['attributes'].get('RestaurantsReservations', ''),\n mon_hours=biz_json['hours'].get('Monday', ''),\n tues_hours=biz_json['hours'].get('Tuesday', ''),\n wed_hours=biz_json['hours'].get('Wednesday', ''),\n thurs_hours=biz_json['hours'].get('Thursday', ''),\n fri_hours=biz_json['hours'].get('Friday', ''),\n sat_hours=biz_json['hours'].get('Saturday', ''),\n sun_hours=biz_json['hours'].get('Sunday', ''))\n new_f.write(biz_csv)", "def get_processed_csv(inputfile, outputfile):\n\n with open(inputfile, 'r') as csv_file:\n reader = csv.DictReader(csv_file)\n header = reader.fieldnames\n list_r = []\n for row in reader:\n data = (dict(row))\n list_r.append(data)\n\n fieldnames = []\n for each_field in header:\n\n formatted_header = each_field.lower().\\\n replace('/', '_').replace(' ', '_').\\\n strip('?').strip('\\n')\n fieldnames.append(formatted_header)\n fieldnames.append('month_joined')\n\n for item in list_r:\n item['url'] = item.pop('URL')\n item['name_alias'] = item.pop('Name/Alias')\n item['appearances'] = item.pop('Appearances')\n item['current'] = item.pop('Current?')\n item['gender'] = item.pop('Gender')\n item['probationary_introl'] = item.pop('Probationary Introl')\n item['full_reserve_avengers_intro'] = \\\n item.pop('Full/Reserve Avengers Intro')\n item['year'] = item.pop('Year')\n item['years_since_joining'] = item.pop('Years since joining')\n item['honorary'] = item.pop('Honorary')\n item['death1'] = item.pop('Death1')\n item['return1'] = item.pop('Return1')\n item['death2'] = item.pop('Death2')\n item['return2'] = item.pop('Return2')\n item['death3'] = item.pop('Death3')\n item['return3'] = item.pop('Return3')\n item['death4'] = item.pop('Death4')\n item['return4'] = item.pop('Return4')\n item['death5'] = item.pop('Death5')\n item['return5'] = item.pop('Return5')\n item['notes'] = item.pop('Notes')\n\n for item in list_r:\n item['appearances'] = int(item['appearances'])\n item['current'] = item['current'] == 'YES'\n item['year'] = int(item['year'])\n item['years_since_joining'] = int(2018-item['year'])\n item['death1'] = item['death1'] == 'YES'\n item['return1'] = item['return1'] == 'YES'\n item['death2'] = item['death2'] == 'YES'\n item['return2'] = item['return2'] == 'YES'\n item['death3'] = item['death3'] == 'YES'\n item['return3'] = item['return3'] == 'YES'\n item['death4'] = item['death4'] == 'YES'\n item['return4'] = item['return4'] == 'YES'\n item['death5'] = item['death5'] == 'YES'\n item['return5'] = item['return5'] == 'YES'\n\n for item in list_r:\n item['month_joined'] = item['full_reserve_avengers_intro']\n item['month_joined'] = re.sub(\"[^a-zA-Z]+\", \"\", item['month_joined'])\n if item['month_joined'] == '':\n item['month_joined'] = 'No Month Provided'\n else:\n item['month_joined'] = strptime(item['month_joined'], '%b').tm_mon\n\n\n with open(outputfile, 'w', encoding='utf-8', newline=\"\") as csv_file_w:\n writer = csv.DictWriter(csv_file_w, fieldnames=fieldnames)\n writer.writeheader()\n for each_row in list_r:\n writer.writerow(each_row)\n return outputfile", "def to_primary_key(csv_path, json_path, primary_key):\n data = {}\n\n with open(csv_path, encoding='utf8') as csv_file:\n reader = csv.DictReader(csv_file)\n\n for rows in reader:\n key = rows[primary_key]\n data[key] = rows\n\n with open(json_path, 'w', encoding='utf8') as json_file:\n json_file.write(json.dumps(data, indent=2, ensure_ascii=False))", "def export_csv(json_data, file_name='CSV.csv'):\n import csv\n\n filename = '.\\\\CSV\\\\' + file_name\n headers = json_data[0].keys()\n\n with open(filename, 'w', encoding='utf-16') as csv_file:\n csvwriter = csv.writer(csv_file, delimiter='\\t', lineterminator='\\n')\n csvwriter.writerow(headers)\n for row in json_data:\n csvwriter.writerow(row.values())", "def json_directory_to_csv(json_path, csv_subdir):\n\n # # Obtain all json files within subdirectory\n # json_files = json_subdir.glob('**/*.json')\n #\n # json_counter = 0\n # for json_path in json_files:\n # Finds the two digits just before the underscore\n # These digits represent the day of the month in the filename\n # match: str = re.search('([0-9]){2}(?=_)', json_path.name)\n # day_of_month = int(match.group(0))\n # if day_of_month < start_end_days[0] or day_of_month > start_end_days[1]:\n # continue\n\n print(f\"Processing {json_path}\")\n # print(f\"Planning to write to {csv_subdir}\")\n try:\n json_path = Path(json_path)\n with open(json_path) as infile:\n data = json.load(infile)\n\n with open((csv_subdir / json_path.stem).with_suffix('.csv'), 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, quoting=csv.QUOTE_NONNUMERIC)\n # TODO: remove all '0x00' characters\n\n for i, segment in enumerate(data):\n\n # Skip Userinfo row\n if i == 0:\n continue\n\n else:\n for j, observation in enumerate(segment):\n\n # Write Header\n if j == 0:\n csvwriter.writerow(observation.keys())\n csvwriter.writerow(observation.values())\n\n else:\n csvwriter.writerow(observation.values())\n \n except AttributeError:\n print('Found a string')\n\n time.sleep(1)", "def load_to_csv(input_file, output_file, weight_change):\n with open(input_file, \"r\") as product_info_file, \\\n open(output_file, \"w\", newline='') as product_info_csv:\n product_info = json.load(product_info_file)\n cleaned_info = []\n for product in product_info:\n row = {\n \"name\": product.get(\"name\").replace(\"\\n\", \" \"),\n \"weight\": float(product.get(\"weight\").replace(\"oz\", \"\"))*weight_change,\n \"blend\": product.get(\"blend\"),\n \"price\": product.get(\"price\"),\n \"length\": product.get(\"length\").split(\"yds\")[0],\n }\n cleaned_info.append(row)\n writer = csv.DictWriter(product_info_csv, [\"name\", \"blend\", \"weight\", \"price\", \"length\"])\n writer.writeheader()\n writer.writerows(cleaned_info)", "def convert_lua_to_json(path_in=\"./Auc-ScanData.lua\", path_out=\"./Auc-ScanData.json\"):\n print \"--------------------\"\n print \"convert_lua_to_json\" # TODO: refactor to py3\n print \"--------------------\"\n os.system(\"./bin/convert.sh\" + \" \" + path_in + \" \" + path_out)", "def generate_csv_input_file(filename=\"data/ex1.csv\"):\n with open(filename, \"w\") as f:\n res = \"\"\n f.writelines(res)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the csv file from path into an output.json delim is used to specify the delimiters of the csv file
def conversion(path, delim, json_filename): csv_input = [] try: #Conversion csv to json with open(path,"rt") as csv_file: reader = csv.reader(csv_file, delimiter=delim, quoting=csv.QUOTE_ALL) fieldnames = next(reader) reader = csv.DictReader(csv_file, delimiter=delim, fieldnames=fieldnames) for row in reader: if row[fieldnames[0]] != '': csv_input.append(row) to_json(json_filename, csv_input) except FileNotFoundError: print(path +" was not found")
[ "def to_json(filename, csv_input):\n if not filename.endswith(\".json\"):\n if filename == \"\":\n filename = \"output\"\n filename += filename + \".json\"\n\n with open(os.path.join(os.path.realpath('..'), 'src', filename), 'w+') as json_file:\n json_output = json.dumps(csv_input, sort_keys=True)\n json_file.write(json_output)", "def main():\n filepath = \"input.csv\"\n delim = \";\"\n\n if len(sys.argv) > 1:\n filepath = sys.argv[1]\n if len(sys.argv) > 2:\n delim = \";\"\n\n conversion(filepath, delim, \"output.json\")", "def make_json(csvFilePath, jsonFilePath):\n \n \n data = {}\n \n # Open a csv reader called DictReader\n with open(csvFilePath, encoding='utf-8') as csvf:\n csvReader = csv.DictReader(csvf)\n \n # Convert each row into a dictionary and add it to data\n for rows in csvReader:\n \n key = rows['id']\n data[key] = rows\n \n \n with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:\n jsonf.write(json.dumps(data, indent=4))", "def convert_json_to_csv(path_in=\"./Auc-ScanData.json\", path_out=\"./Auc-ScanData.csv\"):\n print \"--------------------\"\n print \"convert_json_to_csv\" # TODO: refactor to py3\n print \"--------------------\"\n print \"Reading in\", path_in # TODO: refactor to py3\n with open(path_in, \"r\") as f:\n content = json.load(f)\n\n data = content['scans']['Mograine']['ropes'][0]\n data = data.lstrip(\"return \")\n data = data.replace(\"{\", \"\")\n data = data.replace(\"},\", \"\\n\")\n\n print \"Writing to\", path_out # TODO: refactor to py3\n with open(path_out, \"w\") as out: \n out.write(data.encode('utf-8'))", "def json2csv(input_file, output_file=None, header_values=None):\n file_out = open_fr(input_file, encoding=ENCODING)\n # set output file name and write header\n if output_file is None:\n output_file = os.path.splitext(os.path.basename(input_file))[0] + \".csv\"\n csv_out = open_fw(output_file, encoding=ENCODING)\n if os.name == 'nt':\n outfile = csv.DictWriter(csv_out, dialect='excel', escapechar=\"\\\\\",\n lineterminator='\\n',\n fieldnames=header_values)\n else:\n outfile = csv.DictWriter(csv_out, dialect='excel',\n escapechar=\"\\\\\", fieldnames=header_values)\n raw_data = json.loads(file_out.read())\n outfile.writeheader()\n\n for item in raw_data:\n outfile.writerow(item)\n file_out.close()\n subprocess.call(['rm', '-r', input_file])\n return output_file", "def read_and_write_file(json_file_path, csv_file_path, column_names):\n with open(csv_file_path, 'w') as fout:\n csv_file = csv.writer(fout)\n csv_file.writerow(list(column_names))\n with open(json_file_path) as fin:\n for line in fin:\n line_contents = json.loads(line)\n csv_file.writerow(get_row(line_contents, column_names))", "def jsonl_to_csv(jsonl_file, csv_path=\"\"):\n print(\"Reading the input\")\n bad_lines = 0\n if jsonl_file is not None:\n try:\n with open(jsonl_file) as inputf:\n with open(csv_path, 'w') as result:\n print(\"-------------- start writing to csv -----------------\")\n print(f\"write to {csv_path}\")\n data_writer = csv.writer(result, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n headers = ['line_id', 'model_id', 'decoded', 'reference', 'coherence', 'consistency',\n 'fluency',\n 'relevance', 'summary_path', 'id', 'text']\n data_writer.writerow(headers)\n row_id = 0\n for count, line in enumerate(inputf):\n try:\n data = json.loads(line)\n if len(data['decoded']) == 0:\n print(f\"bad line: {data['id']}\")\n bad_lines += 1\n raise ValueError(\"data id error!\")\n if data.get(\"reference\", None):\n reference = data['reference']\n else: # there are 10 additional references added, the first is the orginal\n reference = data[\"references\"][0]\n # article = data['text']\n annotation_stats = get_expert_annoation_stats(data['expert_annotations'])\n if not annotation_stats or annotation_stats == -1:\n raise ValueError(\"avg_expert is -1!!!\")\n row_item = [row_id, data['model_id'], data['decoded'], reference, *annotation_stats,\n data['summary_path'], data['id'], data['text']]\n data_writer.writerow(row_item)\n row_id += 1\n except:\n bad_lines += 1\n raise ValueError(\"error when reading inputf!\")\n print(f\"write total rows: {row_id}\")\n print(\"-------------- finish writing to csv -----------------\")\n except Exception as e:\n print(\"Input did not match required format\")\n print(e)\n sys.exit()\n print(f\"This many bad lines encountered during loading: {bad_lines}\")", "def write_input_csv_to_file(in_csv):\n return", "def convert_business_json_file_to_csv(json_file_path, csv_file_path):\n write_dir = os.path.dirname(csv_file_path)\n if not os.path.isdir(write_dir):\n os.mkdir(write_dir)\n with io.open(csv_file_path, 'w', encoding='utf-8') as new_f:\n new_f.write(u'biz_id,name,neighborhood,address,city,state,postal_code,latitude,longitude,'\n u'stars,is_open,'\n u'gf_dessert,gf_dinner,gf_latenight,gf_lunch,gf_breakfast,gf_brunch,'\n u'has_tv,has_delivery,accept_credit_cards,outdoor_seating,takes_reservations,'\n u'monday_hours,tuesday_hours,wednesday_hours,thursday_hours,friday_hours,'\n u'saturday_hours,sunday_hours\\n')\n with open(json_file_path, 'r') as old_f:\n for line in old_f:\n biz_json = json.loads(line)\n if 'GoodForMeal' in biz_json['attributes']:\n biz_csv = u'{biz_id},{name},{neighborhood},{address},{city},{state},' \\\n u'{postal_code},{latitude},{longitude},{stars},{is_open},' \\\n u'{gf_dessert},{gf_dinner},{gf_latenight},{gf_lunch},{gf_breakfast},{gf_brunch},' \\\n u'{has_tv},{has_delivery},{accept_credit_cards},{outdoor_seating},{takes_reservations},' \\\n u'{mon_hours},{tues_hours},{wed_hours},{thurs_hours},{fri_hours},{sat_hours},' \\\n u'{sun_hours}\\n'.format(\n biz_id=biz_json['business_id'].replace(',', ' '),\n name=biz_json['name'].replace(',', ' '),\n neighborhood=biz_json['neighborhood'].replace(',', ' '),\n address=biz_json['address'].replace(',', ' '),\n city=biz_json['city'].replace(',', ' '),\n state=biz_json['state'].replace(',', ' '),\n postal_code=biz_json['postal_code'].replace(',', ' '),\n latitude=biz_json['latitude'],\n longitude=biz_json['longitude'],\n stars=biz_json['stars'],\n is_open=biz_json['is_open'],\n gf_dessert=biz_json['attributes']['GoodForMeal'].get('dessert', ''),\n gf_dinner=biz_json['attributes']['GoodForMeal'].get('dinner', ''),\n gf_latenight=biz_json['attributes']['GoodForMeal'].get('latenight', ''),\n gf_lunch=biz_json['attributes']['GoodForMeal'].get('lunch', ''),\n gf_breakfast=biz_json['attributes']['GoodForMeal'].get('breakfast', ''),\n gf_brunch=biz_json['attributes']['GoodForMeal'].get('brunch', ''),\n has_tv=biz_json['attributes'].get('HasTV', ''),\n has_delivery=biz_json['attributes'].get('RestaurantsDelivery', ''),\n accept_credit_cards=biz_json['attributes'].get('BusinessAcceptsCreditCards', ''),\n outdoor_seating=biz_json['attributes'].get('OutdoorSeating', ''),\n takes_reservations=biz_json['attributes'].get('RestaurantsReservations', ''),\n mon_hours=biz_json['hours'].get('Monday', ''),\n tues_hours=biz_json['hours'].get('Tuesday', ''),\n wed_hours=biz_json['hours'].get('Wednesday', ''),\n thurs_hours=biz_json['hours'].get('Thursday', ''),\n fri_hours=biz_json['hours'].get('Friday', ''),\n sat_hours=biz_json['hours'].get('Saturday', ''),\n sun_hours=biz_json['hours'].get('Sunday', ''))\n new_f.write(biz_csv)", "def transform_csv_file(input_path, output_path):\n print('Transforming {} to {}.'.format(input_path, output_path))\n # Convert the rows to a usable format.\n rows = convert_input_file_to_output_rows(input_path=input_path)\n # Write the rows to the output file.\n with open(output_path, 'w+', encoding='latin-1') as file:\n writer = csv.DictWriter(file, fieldnames=OUTPUT_COLUMNS)\n writer.writeheader()\n writer.writerows(rows)", "def process_csv(self, file_name: str):", "def write_json(input, output, id, league):\n\n with open(input, newline='') as data:\n reader = csv.DictReader(data)\n file_w = open(output, 'w')\n json_list = {}\n headers = reader.fieldnames\n\n # For every line create a key and its attributes.\n for line in reader:\n # Select items from correct league\n if line['League'] == league:\n child = {}\n for item in headers:\n # Skip id\n if item != id:\n child[item] = line[item].replace(',', '')\n json_list[line[id]] = child\n\n json.dump(json_list, file_w, indent=2)\n data.close()\n file_w.close()", "def main(csv_path: str) -> None:\n real_csv_path = Path(csv_path)\n\n deviant_sorted_books = _process_csv_export(real_csv_path)\n print(json.dumps([_.as_record() for _ in deviant_sorted_books]))", "def export_csv(json_data, file_name='CSV.csv'):\n import csv\n\n filename = '.\\\\CSV\\\\' + file_name\n headers = json_data[0].keys()\n\n with open(filename, 'w', encoding='utf-16') as csv_file:\n csvwriter = csv.writer(csv_file, delimiter='\\t', lineterminator='\\n')\n csvwriter.writerow(headers)\n for row in json_data:\n csvwriter.writerow(row.values())", "def test_output_csv_delimiter(self):\n self.convert.start(self.CSV_TEST_FILE_PATH, self.OUTPUT_BASE_FILE_PATH+'.csv', '{\"output_csv_delimiter\": \"|\"}')\n with open(self.OUTPUT_BASE_FILE_PATH+'.csv', 'r') as test_file:\n test_file_content = test_file.readlines()\n self.assertIn(self.TESTS_DATA[3][0]+'|', test_file_content[3])\n self.assertEqual(len(self.TESTS_DATA[2]) - 1, test_file_content[2].count('|'))\n test_file.close()", "def generate_csv_input_file(filename=\"data/ex1.csv\"):\n with open(filename, \"w\") as f:\n res = \"\"\n f.writelines(res)", "def csv_writer(data, path):\r\n #with open(path, \"wb\") as csv_file:\r\n with open(path, \"w\") as csv_file:\r\n writer = csv.writer(csv_file, delimiter=',')\r\n for line in data:\r\n writer.writerow(line)", "def write_csv(data, filepath):\n pass #TODO implement", "def to_csv(self, path=None, separator=',', **kwargs):\n from ..parsing.csv import isotherm_to_csv\n return isotherm_to_csv(self, path, separator, **kwargs)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a json file from a csv_input
def to_json(filename, csv_input): if not filename.endswith(".json"): if filename == "": filename = "output" filename += filename + ".json" with open(os.path.join(os.path.realpath('..'), 'src', filename), 'w+') as json_file: json_output = json.dumps(csv_input, sort_keys=True) json_file.write(json_output)
[ "def make_json(csvFilePath, jsonFilePath):\n \n \n data = {}\n \n # Open a csv reader called DictReader\n with open(csvFilePath, encoding='utf-8') as csvf:\n csvReader = csv.DictReader(csvf)\n \n # Convert each row into a dictionary and add it to data\n for rows in csvReader:\n \n key = rows['id']\n data[key] = rows\n \n \n with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:\n jsonf.write(json.dumps(data, indent=4))", "def conversion(path, delim, json_filename):\n csv_input = []\n\n try:\n #Conversion csv to json\n with open(path,\"rt\") as csv_file:\n reader = csv.reader(csv_file, delimiter=delim, quoting=csv.QUOTE_ALL)\n fieldnames = next(reader)\n reader = csv.DictReader(csv_file, delimiter=delim, fieldnames=fieldnames)\n for row in reader:\n if row[fieldnames[0]] != '':\n csv_input.append(row)\n to_json(json_filename, csv_input)\n\n except FileNotFoundError:\n print(path +\" was not found\")", "def main():\n filepath = \"input.csv\"\n delim = \";\"\n\n if len(sys.argv) > 1:\n filepath = sys.argv[1]\n if len(sys.argv) > 2:\n delim = \";\"\n\n conversion(filepath, delim, \"output.json\")", "def write_json(input, output, id, league):\n\n with open(input, newline='') as data:\n reader = csv.DictReader(data)\n file_w = open(output, 'w')\n json_list = {}\n headers = reader.fieldnames\n\n # For every line create a key and its attributes.\n for line in reader:\n # Select items from correct league\n if line['League'] == league:\n child = {}\n for item in headers:\n # Skip id\n if item != id:\n child[item] = line[item].replace(',', '')\n json_list[line[id]] = child\n\n json.dump(json_list, file_w, indent=2)\n data.close()\n file_w.close()", "def write_input_csv_to_file(in_csv):\n return", "def create_geojson(csv_file_open_path, file_save_path_name):\n data = []\n with open(csv_file_open_path,'r') as f:\n reader = csv.reader(f)\n for record in reader:\n data.append(record)\n\n data = data[1::]\n \n for record in data:\n # shorten latitude to 4 decimal places\n lat = record[1].split('.')\n lat_diff = len(lat[1])-4\n lat[1] = lat[1][0:len(lat[1])-lat_diff]\n record[1] = float(lat[0] + '.' + lat[1])\n \n # shorten longitude to 4 decimal places\n long = record[2].split('.')\n long_diff = len(long[1])-4\n long[1] = long[1][0:len(long[1])-long_diff]\n record[2] = float(long[0] + '.' + long[1])\n \n record[4] = record[4].replace(',', ', ')\n record[7] = record[7].replace(',', ', ')\n \n data_file = {\"type\": \"FeatureCollection\"}\n data_file[\"crs\"] = {\"type\":\"name\",\"properties\":{\"name\":\"urn:ogc:def:crs:OGC:1.3:CRS84\"}}\n features_list = []\n \n for coop in data:\n features_list.append(create_feature_dict(coop))\n \n data_file[\"features\"] = features_list\n \n with open(file_save_path_name, 'w') as ff:\n ff.write(json.dumps(data_file))", "def json2csv(input_file, output_file=None, header_values=None):\n file_out = open_fr(input_file, encoding=ENCODING)\n # set output file name and write header\n if output_file is None:\n output_file = os.path.splitext(os.path.basename(input_file))[0] + \".csv\"\n csv_out = open_fw(output_file, encoding=ENCODING)\n if os.name == 'nt':\n outfile = csv.DictWriter(csv_out, dialect='excel', escapechar=\"\\\\\",\n lineterminator='\\n',\n fieldnames=header_values)\n else:\n outfile = csv.DictWriter(csv_out, dialect='excel',\n escapechar=\"\\\\\", fieldnames=header_values)\n raw_data = json.loads(file_out.read())\n outfile.writeheader()\n\n for item in raw_data:\n outfile.writerow(item)\n file_out.close()\n subprocess.call(['rm', '-r', input_file])\n return output_file", "def main(csv_path: str) -> None:\n real_csv_path = Path(csv_path)\n\n deviant_sorted_books = _process_csv_export(real_csv_path)\n print(json.dumps([_.as_record() for _ in deviant_sorted_books]))", "def jsonl_to_csv(jsonl_file, csv_path=\"\"):\n print(\"Reading the input\")\n bad_lines = 0\n if jsonl_file is not None:\n try:\n with open(jsonl_file) as inputf:\n with open(csv_path, 'w') as result:\n print(\"-------------- start writing to csv -----------------\")\n print(f\"write to {csv_path}\")\n data_writer = csv.writer(result, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n headers = ['line_id', 'model_id', 'decoded', 'reference', 'coherence', 'consistency',\n 'fluency',\n 'relevance', 'summary_path', 'id', 'text']\n data_writer.writerow(headers)\n row_id = 0\n for count, line in enumerate(inputf):\n try:\n data = json.loads(line)\n if len(data['decoded']) == 0:\n print(f\"bad line: {data['id']}\")\n bad_lines += 1\n raise ValueError(\"data id error!\")\n if data.get(\"reference\", None):\n reference = data['reference']\n else: # there are 10 additional references added, the first is the orginal\n reference = data[\"references\"][0]\n # article = data['text']\n annotation_stats = get_expert_annoation_stats(data['expert_annotations'])\n if not annotation_stats or annotation_stats == -1:\n raise ValueError(\"avg_expert is -1!!!\")\n row_item = [row_id, data['model_id'], data['decoded'], reference, *annotation_stats,\n data['summary_path'], data['id'], data['text']]\n data_writer.writerow(row_item)\n row_id += 1\n except:\n bad_lines += 1\n raise ValueError(\"error when reading inputf!\")\n print(f\"write total rows: {row_id}\")\n print(\"-------------- finish writing to csv -----------------\")\n except Exception as e:\n print(\"Input did not match required format\")\n print(e)\n sys.exit()\n print(f\"This many bad lines encountered during loading: {bad_lines}\")", "def to_primary_key(csv_path, json_path, primary_key):\n data = {}\n\n with open(csv_path, encoding='utf8') as csv_file:\n reader = csv.DictReader(csv_file)\n\n for rows in reader:\n key = rows[primary_key]\n data[key] = rows\n\n with open(json_path, 'w', encoding='utf8') as json_file:\n json_file.write(json.dumps(data, indent=2, ensure_ascii=False))", "def convert_business_json_file_to_csv(json_file_path, csv_file_path):\n write_dir = os.path.dirname(csv_file_path)\n if not os.path.isdir(write_dir):\n os.mkdir(write_dir)\n with io.open(csv_file_path, 'w', encoding='utf-8') as new_f:\n new_f.write(u'biz_id,name,neighborhood,address,city,state,postal_code,latitude,longitude,'\n u'stars,is_open,'\n u'gf_dessert,gf_dinner,gf_latenight,gf_lunch,gf_breakfast,gf_brunch,'\n u'has_tv,has_delivery,accept_credit_cards,outdoor_seating,takes_reservations,'\n u'monday_hours,tuesday_hours,wednesday_hours,thursday_hours,friday_hours,'\n u'saturday_hours,sunday_hours\\n')\n with open(json_file_path, 'r') as old_f:\n for line in old_f:\n biz_json = json.loads(line)\n if 'GoodForMeal' in biz_json['attributes']:\n biz_csv = u'{biz_id},{name},{neighborhood},{address},{city},{state},' \\\n u'{postal_code},{latitude},{longitude},{stars},{is_open},' \\\n u'{gf_dessert},{gf_dinner},{gf_latenight},{gf_lunch},{gf_breakfast},{gf_brunch},' \\\n u'{has_tv},{has_delivery},{accept_credit_cards},{outdoor_seating},{takes_reservations},' \\\n u'{mon_hours},{tues_hours},{wed_hours},{thurs_hours},{fri_hours},{sat_hours},' \\\n u'{sun_hours}\\n'.format(\n biz_id=biz_json['business_id'].replace(',', ' '),\n name=biz_json['name'].replace(',', ' '),\n neighborhood=biz_json['neighborhood'].replace(',', ' '),\n address=biz_json['address'].replace(',', ' '),\n city=biz_json['city'].replace(',', ' '),\n state=biz_json['state'].replace(',', ' '),\n postal_code=biz_json['postal_code'].replace(',', ' '),\n latitude=biz_json['latitude'],\n longitude=biz_json['longitude'],\n stars=biz_json['stars'],\n is_open=biz_json['is_open'],\n gf_dessert=biz_json['attributes']['GoodForMeal'].get('dessert', ''),\n gf_dinner=biz_json['attributes']['GoodForMeal'].get('dinner', ''),\n gf_latenight=biz_json['attributes']['GoodForMeal'].get('latenight', ''),\n gf_lunch=biz_json['attributes']['GoodForMeal'].get('lunch', ''),\n gf_breakfast=biz_json['attributes']['GoodForMeal'].get('breakfast', ''),\n gf_brunch=biz_json['attributes']['GoodForMeal'].get('brunch', ''),\n has_tv=biz_json['attributes'].get('HasTV', ''),\n has_delivery=biz_json['attributes'].get('RestaurantsDelivery', ''),\n accept_credit_cards=biz_json['attributes'].get('BusinessAcceptsCreditCards', ''),\n outdoor_seating=biz_json['attributes'].get('OutdoorSeating', ''),\n takes_reservations=biz_json['attributes'].get('RestaurantsReservations', ''),\n mon_hours=biz_json['hours'].get('Monday', ''),\n tues_hours=biz_json['hours'].get('Tuesday', ''),\n wed_hours=biz_json['hours'].get('Wednesday', ''),\n thurs_hours=biz_json['hours'].get('Thursday', ''),\n fri_hours=biz_json['hours'].get('Friday', ''),\n sat_hours=biz_json['hours'].get('Saturday', ''),\n sun_hours=biz_json['hours'].get('Sunday', ''))\n new_f.write(biz_csv)", "def new_csv_as_dict(csv_path, fieldnames):\n\n f = open(csv_path, 'w', encoding='latin1', newline='')\n c = csv.DictWriter(f, fieldnames=fieldnames)\n return c", "def convert_json_to_csv(path_in=\"./Auc-ScanData.json\", path_out=\"./Auc-ScanData.csv\"):\n print \"--------------------\"\n print \"convert_json_to_csv\" # TODO: refactor to py3\n print \"--------------------\"\n print \"Reading in\", path_in # TODO: refactor to py3\n with open(path_in, \"r\") as f:\n content = json.load(f)\n\n data = content['scans']['Mograine']['ropes'][0]\n data = data.lstrip(\"return \")\n data = data.replace(\"{\", \"\")\n data = data.replace(\"},\", \"\\n\")\n\n print \"Writing to\", path_out # TODO: refactor to py3\n with open(path_out, \"w\") as out: \n out.write(data.encode('utf-8'))", "def read_and_write_file(json_file_path, csv_file_path, column_names):\n with open(csv_file_path, 'w') as fout:\n csv_file = csv.writer(fout)\n csv_file.writerow(list(column_names))\n with open(json_file_path) as fin:\n for line in fin:\n line_contents = json.loads(line)\n csv_file.writerow(get_row(line_contents, column_names))", "def csv_to_geojson(in_csv, out_geojson, x=\"longitude\", y=\"latitude\"):\n import pandas as pd\n import geopandas as gpd\n\n if not os.path.exists(in_csv):\n raise FileNotFoundError(\"The input csv does not exist.\")\n\n if not out_geojson.lower().endswith(\".geojson\"):\n raise ValueError(\"out_geojson must have the .geojson file extension.\")\n\n out_dir = os.path.dirname(out_geojson)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n df = pd.read_csv(in_csv)\n col_names = df.columns.values.tolist()\n\n if x not in col_names:\n raise ValueError(f\"x must be one of the following: {', '.join(col_names)}\")\n\n if y not in col_names:\n raise ValueError(f\"y must be one of the following: {', '.join(col_names)}\")\n\n gdf = gpd.GeoDataFrame(\n df, crs=\"epsg:4326\", geometry=gpd.points_from_xy(df[x], df[y])\n )\n gdf.to_file(out_geojson, driver=\"GeoJSON\")", "def generate_csv_input_file(filename=\"data/ex1.csv\"):\n with open(filename, \"w\") as f:\n res = \"\"\n f.writelines(res)", "def POST_csv_data_to_db(csv_path):\n with open(csv_path, \"r\") as csv_file:\n\n # make list of headers off first line in csv\n headers = csv_file.readline().strip().lower().split(\",\")\n\n # need to skip data type line in csv\n _ = csv_file.readline()\n\n for line in csv_file:\n # turns headers and line values into \"header:line_value\" dict used in POST\n POST_data = dict(zip(headers, line.strip().split(\",\")))\n\n r = requests.post(\"http://localhost:8000/movies/\", data=POST_data)\n\n # raises error in script if request returns 400s or 500s\n r.raise_for_status()\n\n return", "def csv_input_output_stream_config():\n return load_configuration_from_json_file(file_name='csv_input_output_stream_mode_enabled_configuration.json')", "def load_to_csv(input_file, output_file, weight_change):\n with open(input_file, \"r\") as product_info_file, \\\n open(output_file, \"w\", newline='') as product_info_csv:\n product_info = json.load(product_info_file)\n cleaned_info = []\n for product in product_info:\n row = {\n \"name\": product.get(\"name\").replace(\"\\n\", \" \"),\n \"weight\": float(product.get(\"weight\").replace(\"oz\", \"\"))*weight_change,\n \"blend\": product.get(\"blend\"),\n \"price\": product.get(\"price\"),\n \"length\": product.get(\"length\").split(\"yds\")[0],\n }\n cleaned_info.append(row)\n writer = csv.DictWriter(product_info_csv, [\"name\", \"blend\", \"weight\", \"price\", \"length\"])\n writer.writeheader()\n writer.writerows(cleaned_info)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that generate_rows handles errors while queryin the API
def test_generate_rows_error(mocker, sc, ds, error_result): mocker.patch.object(SalesforceConnector, 'make_request', return_value=error_result) with pytest.raises(SalesforceApiError): sc.generate_rows(Session(), ds, 'https://salesforce.is.awsome', 'bla')
[ "def test_row_intuition_rowgen(self):\n from csv import DictReader\n\n with open(df('rowgen_sources.csv')) as f:\n for e in DictReader(f):\n print(e['name'])\n gen = get_generator(e['url'])\n\n rows = list(gen)\n\n self.assertEquals(int(e['n_rows']), len(rows))\n\n try:\n ri = RowIntuiter()\n ri.run(rows)\n except RowIntuitError as exc:\n print(\"Error: \", e, exc)\n\n if e['expect_start']:\n self.assertEqual(int(e['expect_start']), ri.start_line)\n\n if e['expect_headers']:\n self.assertEquals(e['expect_headers'], ','.join(str(e) for e in ri.header_lines))", "def test_bad_row(self):\n mock_filefield = generate_filefield('bad_row_csv.csv')\n\n with self.assertRaisesRegexp(\n ValidationError, 'One or more OCD IDs not found. First found: Row: '\n '3 ID: BAD ROW NON OCD ID'):\n validate_geodataset_upload(mock_filefield)", "def test_query_grants_fail(cb):\n query = cb.select(Grant)\n with pytest.raises(ApiError):\n list(query)", "def test_genus_required_error(self):\n schema = self.schema_with_2_columns_genus()\n dataset = self.assert_create_dataset(schema)\n # Genus is required\n self.assertTrue(dataset.schema.get_field_by_name('Genus').required)\n\n # provides 3 records with no Genus (row=2,3,4)\n records = [\n ['Genus', 'Species', 'When', 'Latitude', 'Longitude'],\n [None, 'lupus', '2018-01-25', -32.0, 115.75],\n ['', 'lupus', '2018-01-25', -32.0, 115.75],\n [' ', 'lupus', '2018-01-25', -32.0, 115.75]\n ]\n resp = self._upload_records_from_rows(records, dataset_pk=dataset.pk, strict=False)\n self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)\n received = resp.json()\n # expected: array of report by row\n self.assertIsInstance(received, list)\n self.assertEqual(len(received), 3)\n # this what an report should look like\n expected_row_report = {\n 'row': 3,\n 'errors': {'Genus': 'Field \"Genus\" has constraint \"required\" which is not satisfied for value \"None\"'},\n 'warnings': {}}\n for row_report in received:\n self.assertIn('errors', row_report)\n errors = row_report.get('errors')\n self.assertIn('Genus', errors)\n msg = errors.get('Genus')\n self.assertEqual(msg, expected_row_report['errors']['Genus'])", "def test_query(self):\n # want to check 1) length of result and 2) that all values in result \n # are in the generator, although it would be pretty hard for them not\n # to be\n width = True #we'll only do one here since it really doesn't matter\n gen = self.db.init_insert(101, 101, width, True)\n compareresult = self.gen_to_list(gen)\n self.sequential_inserter(width)\n \n records = 10\n streams = 10\n result = self.db.query(records, streams, True)\n self.assertEqual(len(result), records*streams)\n for x in result:\n self.assert_(x in compareresult)\n \n print(\"test_query passed\")", "def test_bulk_get_duplicate(self):\n case_ids = [self.case_ids[0], 'missing', self.case_ids[2], 'missing', self.case_ids[1], self.case_ids[2]]\n self._call_get_api_check_results(case_ids, matching=4, missing=2)", "def row_errors(self) -> Sequence['outputs.ImportRowErrorResponse']:\n return pulumi.get(self, \"row_errors\")", "def test_process_batch_errors(self):\n # This happens if the 'server' sends data with the wrong media\n # type.\n self.lookup_client.queue_response(\n 200, {'content-type': 'json/application'}, '{ \"title\": \"It broke.\" }'\n )\n\n id1 = self._identifier()\n id2 = self._identifier()\n with pytest.raises(BadResponseException) as excinfo:\n self.provider.process_batch([id1, id2])\n assert 'Wrong media type' in str(excinfo.value)\n assert [] == id1.coverage_records\n assert [] == id2.coverage_records\n\n # Of if the 'server' sends an error response code.\n self.lookup_client.queue_response(\n 500, {'content-type': OPDSFeed.ACQUISITION_FEED_TYPE},\n 'Internal Server Error'\n )\n with pytest.raises(BadResponseException) as excinfo:\n self.provider.process_batch([id1, id2])\n assert \"Got status code 500\" in str(excinfo.value)\n assert [] == id1.coverage_records\n assert [] == id2.coverage_records\n\n # If a message comes back with an unexpected status, a\n # CoverageFailure is created.\n data = sample_data('unknown_message_status_code.opds', 'opds')\n valid_id = self.opds_feed_identifiers()[0]\n self.lookup_client.queue_response(\n 200, {'content-type': OPDSFeed.ACQUISITION_FEED_TYPE}, data\n )\n [result] = self.provider.process_batch([valid_id])\n assert True == isinstance(result, CoverageFailure)\n assert valid_id == result.obj\n assert '418: Mad Hatter' == result.exception\n\n # The OPDS importer didn't know which Collection to associate\n # with this CoverageFailure, but the CoverageProvider does,\n # and it set .collection appropriately.\n assert self.provider.collection == result.collection", "def upload_rows(bigquery_client, bigquery_table, rows_to_upload, collection_to_watch, operation_type):\n for row in rows_to_upload:\n row['time_archived'] = time.time()\n row['operationType'] = operation_type\n errors = bigquery_client.create_rows(bigquery_table, rows_to_upload, skip_invalid_rows=True)\n if errors:\n for i in xrange(len(errors)):\n # Add the actual failing document to the error so we can debug this at all\n errors[i]['document'] = rows_to_upload[errors[i]['index']]\n logging.error(\"Row insert failed: Updating table \" + collection_to_watch['bigquery_table'] + \" failed: \" + str(errors[i]))\n return errors", "def _validate_rows(dsv_reader, manifest_column_names_to_validators, line_limit=None):\n rows_are_valid = True\n for line_number, row in enumerate(dsv_reader, 2):\n row_items = row.items()\n if len(row_items) != len(dsv_reader.fieldnames):\n logging.warning(\n f\"line {line_number}, number of fields ({len(row_items)}) in row is unequal to number of column names in manifest ({len(dsv_reader.fieldnames)})\"\n )\n\n for column_name, value in row_items:\n if column_name in manifest_column_names_to_validators:\n validator = manifest_column_names_to_validators[column_name]\n try:\n validator.validate(value)\n except EmptyWarning:\n logging.warning(\n f'line {line_number}, \"{column_name}\" field is empty'\n )\n except MultiValueError as e:\n rows_are_valid = False\n logging.error(f'line {line_number}, \"{column_name}\" values {e}')\n except ValueError as e:\n rows_are_valid = False\n logging.error(f'line {line_number}, \"{column_name}\" value {e}')\n\n if line_number == line_limit:\n break\n\n return rows_are_valid", "def test_bad_request():\n apocrypha = LHorizon(\"Arisia\", \"Velantia III\")\n try:\n apocrypha.table()\n raise RuntimeError(\"that shouldn't have worked!\")\n except ValueError:\n pass", "def testGetIndexError(self):\n self.assertRaises(sqlresult.FieldError, self.row.__getitem__, 4)\n self.assertRaises(sqlresult.FieldError, self.row.__getitem__, 'badkey')", "def get_rows(self):\n conn = psycopg2.connect(**API_JSONDB_CONFIG)\n with conn.cursor() as cursor:\n cursor.execute(self.get_query())\n for obj, in cursor:\n yield {\"action\": \"harmonize\", \"object\": obj}", "def _validate_fields(self):\n cleaned_data = {}\n errors = []\n\n for row_num, row in enumerate(self.rows):\n expected_fields = self._get_validators_for_row(row)\n if len(row) != len(expected_fields):\n raise serializers.ValidationError(\n \"Row: %s - Incorrect number of columns should be %s \"\n \"actually %s\" % (row_num + 1, len(expected_fields), len(row))\n )\n\n for idx, field_name in enumerate(expected_fields):\n field_value = row[idx]\n validators = expected_fields[field_name]\n try:\n cleaned_data[field_name] = self._validate_field(\n field_name, field_value.strip(), idx, row_num, validators\n )\n except serializers.ValidationError as ve:\n # this will be a list not an individual error message\n errors.extend(ve.detail)\n except (AssertionError, TypeError) as e:\n errors.append(e)\n try:\n # Global Validation\n applicable_contract = self._get_applicable_contract_for_row(row)\n self.cleaned_data.append(self._validate_data(cleaned_data, row_num, applicable_contract))\n except serializers.ValidationError as ve:\n errors.extend(ve.detail)\n\n if len(errors):\n raise serializers.ValidationError(errors)", "def filter_datainsert(self, num_rows):\n try:\n self.furbished = self.strip_data_identifier(num_rows)\n #print self.furbished\n self.pi_code = self.extract_at_index(self.furbished, 0)\n self.bi_code = self.extract_at_index(self.furbished, 1)\n self.client_code = self.extract_at_index(self.furbished, 2)\n\n self.saved_pi = self.query_or_save(self.pi_code)\n #print \"SAVED PI \", self.saved_pi\n self.saved_bi = self.query_or_save_bi(self.saved_pi, self.bi_code)\n \n self.remaining_data = self.strip_data_identifier(self.furbished, index=3)\n try:\n self.search_number = self.search_clientnumber(self.client_code)\n self.save_legacy(self.remaining_data, self.search_number, self.saved_pi, self.saved_bi)\n except datamodels.CREDIT_APPLICATION.DoesNotExist as e:\n print e, self.client_code\n pass \n \n except Exception as e:\n print \"BC ERROR \", e\n pass \n #raise", "def test_load_all_gen(testapp):\n user_inserts = list(get_inserts('master-inserts', 'user'))\n lab_inserts = list(get_inserts('master-inserts', 'lab'))\n award_inserts = list(get_inserts('master-inserts', 'award'))\n # the total number of items we expect\n expected = len(user_inserts) + len(lab_inserts) + len(award_inserts)\n data = {'store': {'user': user_inserts, 'lab': lab_inserts, 'award': award_inserts},\n 'itype': ['user', 'lab', 'award']}\n with mock.patch(f'snovault.loadxl.get_app') as mocked_app:\n mocked_app.return_value = testapp.app\n # successful load cases\n gen1 = loadxl.load_all_gen(testapp, data['store'], None,\n itype=data['itype'], from_json=True)\n res1 = b''.join([v for v in gen1]).decode()\n assert res1.count('POST:') == expected\n assert res1.count('PATCH:') == expected\n assert res1.count('SKIP:') == 0\n assert res1.count('ERROR:') == 0\n # do the same with LoadGenWrapper\n # items should be SKIP instead of POST, since they were already POSTed\n gen2 = loadxl.load_all_gen(testapp, data['store'], None,\n itype=data['itype'], from_json=True)\n catch2 = loadxl.LoadGenWrapper(gen=gen2)\n res2 = b''.join([v for v in catch2]).decode()\n assert catch2.caught is None # no Exception hit\n assert res2.count('POST:') == 0\n assert res2.count('PATCH:') == expected\n assert res2.count('SKIP:') == expected\n assert res1.count('ERROR:') == 0\n # now handle error cases, both with using LoadGenWrapper and without\n # let's use an bad directory path to cause Exception\n bad_dir = resource_filename('encoded', 'tests/data/not-a-fdn-dir/')\n gen3 = loadxl.load_all_gen(testapp, bad_dir, None)\n res3 = b''.join([v for v in gen3]).decode()\n assert res3.count('POST:') == 0\n assert res3.count('PATCH:') == 0\n assert res3.count('SKIP:') == 0\n assert res3.count('ERROR:') == 1\n assert 'Failure loading inserts' in res3\n # the LoadGenWrapper will give use access to the Exception\n gen4 = loadxl.load_all_gen(testapp, bad_dir, None)\n catch4 = loadxl.LoadGenWrapper(gen=gen4)\n res4 = b''.join([v for v in catch4]).decode()\n assert res4.count('POST:') == 0\n assert res4.count('PATCH:') == 0\n assert res4.count('SKIP:') == 0\n assert res4.count('ERROR:') == 1\n assert 'Failure loading inserts' in res4\n assert isinstance(catch4.caught, basestring)\n assert 'Failure loading inserts' in catch4.caught", "def test_exceptions_during_batch_fn(\n batch_executor, batch_fn, expect_partial_results):\n batch_executor.batch_fn = batch_fn\n request_batch = [\n _Request(\n future=Future(),\n input_data=i)\n for i in range(10)\n ]\n batch_executor._on_requests_ready(request_batch)\n for i, request in enumerate(request_batch):\n if expect_partial_results and i < 5:\n result = request.future.result(timeout=5)\n assert result == request.input_data * 100, \\\n \"The result for this future doesn't match the input that \" \\\n \"was supposed to have been routed to it!\"\n else:\n with pytest.raises(RuntimeError):\n request.future.result(timeout=5)", "def retryingIter(queryGenerator):\n lastCursor = None\n for i in range(100):\n query = queryGenerator()\n if lastCursor:\n query.with_cursor(lastCursor)\n try:\n for item in query:\n lastCursor = query.cursor()\n yield item\n except Timeout:\n logging.info('Attempt #%d failed', i)", "def test_error_when_invalid_transcription_values(self, mock_client):\n iri = 'example.com'\n rc = ResultCollection(iri)\n task = TaskFactory()\n required = ['target', 'value', 'tag']\n invalid = ['', None]\n for key in required:\n for bad_value in invalid:\n values = {k: 'foo' for k in required}\n values[key] = bad_value\n with assert_raises(ValueError) as exc:\n rc.add_transcription(task, **values)\n err_msg = exc.exception.message\n assert_equal(err_msg, '\"{}\" is a required value'.format(key))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print error message `err_msg` and full trace of the error.
def full_trace_error(err_msg): import sys, traceback print(err_msg) exc_type, exc_value, exc_traceback = sys.exc_info() print("*** print_tb:") traceback.print_tb(exc_traceback, file=sys.stdout) print("*** print_exception:") traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout) sys.stdout.flush()
[ "def print_err(self, msg):\n if self.time_writer:\n self.time_writer.print_stderr_message(msg)\n else:\n print(\"Error: %s\" % msg)", "def print_err( msg, exit=True ):\n LINE = inspect.currentframe().f_back.f_lineno\n FILE = os.path.basename( inspect.getfile( inspect.currentframe().f_back ) )\n\n sys.stderr.write( \"ERROR [{}:{}] --> {}\\n\".format( FILE, LINE, msg ) )\n\n if exit:\n sys.exit( 1 )", "def dump_error(err_message):\n print(formatter.Formatter(err_message).print_error(), file=sys.stderr)", "def log_trace(errmsg=None):\r\n from twisted.python import log\r\n print errmsg\r\n\r\n tracestring = traceback.format_exc()\r\n if tracestring:\r\n for line in tracestring.splitlines():\r\n log.msg('[::] %s' % line)\r\n if errmsg:\r\n try:\r\n errmsg = to_str(errmsg)\r\n except Exception, e:\r\n errmsg = str(e)\r\n for line in errmsg.splitlines():\r\n log.msg('[EE] %s' % line)", "def printErrorMsg(text):\r\n\tprint >> stderr, text", "def log_trace(errmsg=None):\n tracestring = format_exc()\n try:\n if tracestring:\n for line in tracestring.splitlines():\n log.msg('[::] %s' % line)\n if errmsg:\n try:\n errmsg = str(errmsg)\n except Exception, e:\n errmsg = str(e)\n for line in errmsg.splitlines():\n log.msg('[EE] %s' % line)\n except Exception:\n log.msg('[EE] %s' % errmsg)", "def log_trace(errmsg=None):\r\n tracestring = format_exc()\r\n try:\r\n if tracestring:\r\n for line in tracestring.splitlines():\r\n log.msg('[::] %s' % line)\r\n if errmsg:\r\n try:\r\n errmsg = str(errmsg)\r\n except Exception, e:\r\n errmsg = str(e)\r\n for line in errmsg.splitlines():\r\n log.msg('[EE] %s' % line)\r\n except Exception:\r\n log.msg('[EE] %s' % errmsg)", "def error(msg,code=None,exception=None):\n if DEBUG:\n raise Exception(msg) from exception\n elif not QUIET:\n print(f\"ERROR [{EXENAME}]: {msg}\",file=sys.stderr)\n if type(code) is int:\n exit(code)", "def _err(message):\n sys.stderr.write('ERROR: file: %s, step: %s, line: %s\\n' \\\n % (FILENAME, STEPNO, LINENO))\n sys.stderr.write('ERROR: %s\\n' % message)\n raise SystemExit(1)", "def debugmsg(msg):\r\n import sys\r\n line = sys._getframe().f_back.f_lineno\r\n simple_debug(\"[module: %-20s][line: %-4s] - %s\" % (name, line, msg))", "def printErr(err, str):\r\n\r\n\tprint \"Error fetching {}:\".format(str), err\r\n\tsys.exit(1)", "def error(msg):\n message(msg, flag='e')", "def tik_exception_process(loc, msg):\n if loc is None:\n print(\"Error: {}\\n\".format(msg.rstrip(\"\\n\")))\n return\n print(\"\\n\".join(get_context_msg(loc.file, int(loc.column), msg)))", "def log_err(s):\n print(\"[ {0}][-] {1}\".format(get_curr_time_str(), s))", "def _exc_info_to_string(self, err):\n exctype, value, tb = err\n msgLines = traceback.format_exception(exctype, value, tb)\n return ''.join(msgLines)", "def print_usage(err_msg, usage):\n print(usage)\n print('Error: ' + err_msg)", "def printerr(*args, **kwargs):\n\tprint(*args, file=sys.stderr, **kwargs)", "def error(msg):\n global logger\n logger.error(msg)", "def _error(exc=None):\n if exc is None:\n exc = format_exc()\n print('* confspec:', file=stderr)\n for line in exc.split('\\n'):\n print('* ', line, file=stderr)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert the vertex storing the y_pos and x_pos
def insert_vertex(self, x_pos, y_pos): v = Vertex(x_pos, y_pos) self._vertices.append(v) return v
[ "def add_vertex(self, v):\n pass", "def append_vertex(self, vertex):", "def insertVertex(self, index, v):\n self.vertexList.insert(index, v)\n \n if self.augVertexList is None:\n self.augVertexList = {generator: \\\n [StackingVertex(vertex, [], [], [], []) for vertex in self.vertexList]\\\n for generator in self.complex.oneCells}\n \n else:\n for generator in self.augVertexList.keys():\n self.augVertexList[generator].insert( \\\n index, StackingVertex(v, [], [], [], []))", "def add_vertex(self, vertex):\r\n self.vertices.append(vertex)", "def add_point(self, point):\n\t\tself.vertices.append(point)", "def _add_vertex(self,x):\n\n vnum = self.vnum\n self.X[vnum,:] = x\n z = get_z(x,ZONES)\n self.ZV[z].append(vnum)\n self.VZ[vnum] = z\n\n self.vnum += 1\n return self.vnum-1", "def insert_vertex(self, x=None):\n v = self.Vertex(x)\n self._outgoing[v] = { }\n if self.is_directed():\n self._incoming[v] = { } # need distinct map for incoming edges\n return v", "def insert(self, x: \"Vertex\"):\n self._data.append(x)\n self.build_heap()", "def add_vertex(self, v):\n if v not in self.vertices.keys(): \n self.vertices[v] = [False,[],0]", "def _add_vertex_segment(self,x,a):\n\n v = self._add_vertex(x)\n self._add_segment(v,a)", "def add_vertex(self):\n u = self.g.add_vertex()\n return u", "def insertVertex(self, point, index):\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _validate_prim_vertex_index(self, index)\n\n # Insert the vertex.\n _cpp_methods.insertVertex(geometry, self.number(), point.number(), index)\n\n return self.vertex(index)", "def insert_vertex(self, val=None):\n count = self.count_vertices()\n u = self._Vertex(val)\n u._index = count if count != 0 else u._index\n self._out[u] = {}\n\n if self.is_directed():\n self._in[u] = {}\n\n return u", "def add_vertex(self, vertex):\n\n\t\tself.vertices.append(vertex)", "def insert_vertex(self, i1, i2, inew):\n for face in self.faces:\n if i1 in face and i2 in face:\n p1 = face.index(i1)\n p2 = face.index(i2)\n if abs(p1-p2) == 1:\n face.insert(min(p1, p2)+1, inew)", "def addPos(self, xyz):\n x, y, z = xyz\n self.path.append((x, y, z))", "def insert(self, pos: int, point: Sequence[float]):\n size = self.VERTEX_SIZE\n if len(point) != size:\n raise DXFValueError('point requires exact {} components.'.format(size))\n\n pos = self._index(pos) * size\n _insert = self.value.insert\n for value in reversed(point):\n _insert(pos, value)", "def createVertex(self, _pos):\n vertex_obj = gobjects.GraphVertex()\n vertex_obj.setPosition(render_engine.pos2dTo3dIsoPos(_pos))\n vertex_obj.setState(Object.OS_Normal)\n \n return vertex_obj", "def addPoint(self, i_posX, i_posY, i_posZ):\n o_point = pm.dt.Point(i_posX+self._voxelSize/2, i_posY+self._voxelSize/2, i_posZ+self._voxelSize/2)\n self._voxelsPosList.append([i_posX+self._voxelSize/2, i_posY+self._voxelSize/2, i_posZ+self._voxelSize/2])", "def addPoint(self,x,y,z):\n self.x = x\n self.y = y\n self.z = z" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts the edge between vertex u and v. We're going to assume in this assignment that all vertices given to this will already exist in the graph.
def insert_edge(self, u, v): e = Edge(u, v) # Check that the edge doesn't already exist for i in u.edges: if i == e: # Edge already exists. raise EdgeAlreadyExists("Edge already exists between vertex!") # Add the edge to both nodes. u.add_edge(e) v.add_edge(e)
[ "def addEdge(self, u, v):\r\n self.graph[u].append(v)", "def insert_edge(self, u, v, w):\n # make sure the vertices are in the graph\n if not self.vertices[u] or not self.vertices[v]:\n raise IndexError\n # if they're not connected, increase size,\n if not self.are_connected(u, v):\n self.size += 1\n # update information in vertices list and adjacency matrix\n self.vertices[u].connections[v] = w\n self.vertices[v].connections[u] = w\n self.adjacency_mat[u][v] = w\n self.adjacency_mat[v][u] = w", "def insert_edge(self, u, v, val=None):\n edge = self._Edge(u, v, val)\n\n self._out[u][v] = edge\n self._in[v][u] = edge\n\n return edge", "def set_edge(self, u, v):\n if u == v:\n raise ValueError(\"Self Loops not allowed.\")\n self.g.add_edge(u, v)", "def add_directed_edge(self, u, v, weight):\n # add u to v\n curr_edge = Edge(u, v, weight)\n curr_vertex = self.vertices[u]\n curr_vertex.add_edge(curr_edge)", "def add_vertex(self, v):\n pass", "def add_edges(self, u, v, data=None, etype=None):\n # TODO(xiangsx): block do not support add_edges\n u = utils.prepare_tensor(self, u, 'u')\n v = utils.prepare_tensor(self, v, 'v')\n\n if etype is None:\n if self._graph.number_of_etypes() != 1:\n raise DGLError('Edge type name must be specified if there are more than one '\n 'edge types.')\n\n # nothing changed\n if len(u) == 0 or len(v) == 0:\n return\n\n assert len(u) == len(v) or len(u) == 1 or len(v) == 1, \\\n 'The number of source nodes and the number of destination nodes should be same, ' \\\n 'or either the number of source nodes or the number of destination nodes is 1.'\n\n if len(u) == 1 and len(v) > 1:\n u = F.full_1d(len(v), F.as_scalar(u), dtype=F.dtype(u), ctx=F.context(u))\n if len(v) == 1 and len(u) > 1:\n v = F.full_1d(len(u), F.as_scalar(v), dtype=F.dtype(v), ctx=F.context(v))\n\n u_type, e_type, v_type = self.to_canonical_etype(etype)\n # if end nodes of adding edges does not exists\n # use add_nodes to add new nodes first.\n num_of_u = self.number_of_nodes(u_type)\n num_of_v = self.number_of_nodes(v_type)\n u_max = F.as_scalar(F.max(u, dim=0)) + 1\n v_max = F.as_scalar(F.max(v, dim=0)) + 1\n\n if u_type == v_type:\n num_nodes = max(u_max, v_max)\n if num_nodes > num_of_u:\n self.add_nodes(num_nodes - num_of_u, ntype=u_type)\n else:\n if u_max > num_of_u:\n self.add_nodes(u_max - num_of_u, ntype=u_type)\n if v_max > num_of_v:\n self.add_nodes(v_max - num_of_v, ntype=v_type)\n\n # metagraph is not changed\n metagraph = self._graph.metagraph\n num_nodes_per_type = []\n for ntype in self.ntypes:\n num_nodes_per_type.append(self.number_of_nodes(ntype))\n # update graph idx\n relation_graphs = []\n for c_etype in self.canonical_etypes:\n # the target edge type\n if c_etype == (u_type, e_type, v_type):\n old_u, old_v = self.edges(form='uv', order='eid', etype=c_etype)\n hgidx = heterograph_index.create_unitgraph_from_coo(\n 1 if u_type == v_type else 2,\n self.number_of_nodes(u_type),\n self.number_of_nodes(v_type),\n F.cat([old_u, u], dim=0),\n F.cat([old_v, v], dim=0),\n ['coo', 'csr', 'csc'])\n relation_graphs.append(hgidx)\n else:\n # do nothing\n # Note: node range change has been handled in add_nodes()\n relation_graphs.append(self._graph.get_relation_graph(self.get_etype_id(c_etype)))\n\n hgidx = heterograph_index.create_heterograph_from_relations(\n metagraph, relation_graphs, utils.toindex(num_nodes_per_type, \"int64\"))\n self._graph = hgidx\n\n # handle data\n etid = self.get_etype_id(etype)\n if data is None:\n self._edge_frames[etid].add_rows(len(u))\n else:\n self._edge_frames[etid].append(data)\n self._reset_cached_info()", "def add_vertex(self, v):\n if v not in self.vertices.keys(): \n self.vertices[v] = [False,[],0]", "def add_vertex(self, v):\n self.v_sources.add(v)", "def fix_edge(self, u: Vertex, v: Vertex) -> bool:\n\n # TODO implement me please.\n if v is None:return False\n if u is None:return False\n if u not in self.vertices or v not in self.vertices:return False\n if u in v.edges:return False\n if v in u.edges:return False\n u.add_edge(v)\n v.add_edge(u)\n return True", "def fix_edge(self, u: Vertex, v: Vertex) -> bool:\n\n # Andre's explanation of fix_edge\n # fix_edge fixes a blocked edge (i.e., adds it) if it doesn't exist yet: \"Fixes an edge between two vertices, u and v. \n # If an edge already exists, or the edge is invalid, then this operation should return False.\"\n\n #Checking if these vertices are valid\n if (u is None or v is None):\n return False\n\n # Checking if these vertices exist in this graph\n if (u not in self.vertices or v not in self.vertices):\n return False\n\n while u is not None or v is not None:\n # If edge doesn't exist\n if (v not in u.edges or u not in v.edges):\n u.add_edge(v) # Fixing edge\n v.add_edge(u) # Fixing edge\n # Checking if add_edge was successful\n if (v not in u.edges or u not in v.edges):\n return False\n else:\n return True\n else:\n return False", "def insert_vertex(self, x=None):\n v = self.Vertex(x)\n self._outgoing[v] = { }\n if self.is_directed():\n self._incoming[v] = { } # need distinct map for incoming edges\n return v", "def add_edge(self, u, v, weight=1.0, directed: bool = False):\n # if u and v are strings, look up their index\n u = self.__lookup_vertex_index(u)\n v = self.__lookup_vertex_index(v)\n\n # Add the edge to the ajacency matrix. Default is 1.0, meaning connected.\n # If weight is > 1, then it's a weighted edge.\n # This operation is O(1)\n self.matrix[u][v] = float(weight)\n\n Logger.log(Logger.LogLevel.DEBUG, f\"Adding edge: {u}->{v} = {weight}\")\n\n # If the edge being added is undirected, then add the mirror image (AB <-> BA).\n if not directed:\n self.add_edge(\n v, u, weight, True\n ) # pass True for directed to avoid more than one recursive call", "def insertVertex(self, index, v):\n self.vertexList.insert(index, v)\n \n if self.augVertexList is None:\n self.augVertexList = {generator: \\\n [StackingVertex(vertex, [], [], [], []) for vertex in self.vertexList]\\\n for generator in self.complex.oneCells}\n \n else:\n for generator in self.augVertexList.keys():\n self.augVertexList[generator].insert( \\\n index, StackingVertex(v, [], [], [], []))", "def add_edge(self, v1, v2):\n self.__graph[v1].append(v2)", "def add_edge(self, v_from, v_to):\n self.v_sources.add(v_from)\n self.v_stocks.add(v_to)\n if v_from in self.edges:\n self.edges[v_from].append(v_to)\n else:\n self.edges[v_from] = [v_to,]", "def addVertex(self, v: 'SbVec3f', data: 'void *') -> \"void\":\n return _coin.SbTesselator_addVertex(self, v, data)", "def insert_vertex(self, val=None):\n count = self.count_vertices()\n u = self._Vertex(val)\n u._index = count if count != 0 else u._index\n self._out[u] = {}\n\n if self.is_directed():\n self._in[u] = {}\n\n return u", "def add_vertex(self, id, vertex):\n \n # Check if vertex with given id already exists.\n if id in self.vertices:\n return\n \n # Check if each vertex in adjacent_to exists.\n for i in vertex.adjacent_to:\n if not i in self.vertices:\n return\n \n # Add given vertex at given id.\n self.vertices[id] = vertex\n \n # Add id to adjacent_to of each vertex in vertex's adjacent_to.\n for i in vertex.adjacent_to:\n self.vertices[i].add_edge(id)", "def add_edge(self, v1, v2, weight):" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the vertex V from the graph.
def remove_vertex(self, v): # Remove it from the list del self._vertices[self._vertices.index(v)] # Go through and remove all edges from that node. while len(v.edges) != 0: e = v.edges.pop() u = self.opposite(e, v) u.remove_edge(e)
[ "def remove_vertex(self, vertex):\n self.remove_vertices([vertex])", "def remove_vertex(self):\r\n if len(self.vertices) > 0:\r\n self.vertices.pop()", "def remove_vertex(self, vertex: T) -> None:\n self._ensure_vertices(vertex)\n neighbors = self._adjacencies[vertex]\n # removing a vertex implies removing the edges connected to that vertex\n for neighbor in neighbors:\n self._adjacencies[neighbor].remove(vertex)\n del self._adjacencies[vertex]", "def remove_vertex(self):\r\n\t\t\tif not self.is_empty():\r\n\t\t\t\tself.vertices.pop()", "def remove_vertex(self):\r\n if self.is_empty():\r\n return None\r\n self.vertices.pop()", "def remove_vertex(self, vertex):\n\n for other_vertex in self.adjacency_dict[vertex]:\n self.adjacency_dict[other_vertex].discard(vertex)\n\n self.adjacency_dict.pop(vertex)", "def remove_edge(self, u, v):\n if u not in self.d or v not in self.d:\n raise KeyError(\"one or both nodes are not in Graph\")\n else:\n EdgeSet = self.d[u]\n EdgeSet.remove(v)\n EdgeSet = self.d[v]\n EdgeSet.remove(u)\n # print(\"removing edge\")", "def removeVertice(self, vertice):\n # Checking if the vertice is existing in the graph\n try:\n if vertice in self.graph:\n # Deleting first all edges from neighbours to the vertice...\n for neighbour in self.graph[vertice]:\n del self.graph[neighbour][vertice]\n # ... and at the end all edges from vertice to its neighbours\n del self.graph[vertice]\n except KeyError:\n print 'Oooops! ' + str(vertice) + ' does not exsist in the graph!'", "def test_directed_graph_remove_vertex(self):\n g = DirectedGraph()\n g.add_vertex(v_val='v0')\n g.add_vertex(v_val='v1')\n g.add_vertex(v_val='v2')\n g.add_edge(('v0', 'v1'))\n g.add_edge(('v1', 'v2'))\n\n g.remove_vertex('v0')\n\n self.assertFalse(g.has_vertex('v0'))\n self.assertTrue(g.has_vertex('v1'))\n self.assertTrue(g.has_vertex('v2'))\n self.assertFalse(g.has_edge(('v0', 'v1')))\n self.assertFalse(g.has_edge(('v1', 'v0')))\n self.assertTrue(g.has_edge(('v1', 'v2')))\n\n g.remove_vertex('v1')\n\n self.assertFalse(g.has_vertex('v0'))\n self.assertFalse(g.has_vertex('v1'))\n self.assertTrue(g.has_vertex('v2'))\n self.assertFalse(g.has_edge(('v0', 'v1')))\n self.assertFalse(g.has_edge(('v1', 'v1')))\n self.assertFalse(g.has_edge(('v1', 'v2')))", "def remove_vertex(self, id):\n \n # Check if vertex with given id exists\n if not id in self.vertices:\n return\n \n # Remove edges going to the vertex with the given id\n for i in self.vertices[id].adjacent_to:\n self.vertices[i].remove_edge(id)\n \n # Remove the vertex\n del self.vertices[id]", "def deleteVertex(self, index):\n geometry = self.geometry()\n\n # Make sure the geometry is not read only.\n if geometry.isReadOnly():\n raise hou.GeometryPermissionError()\n\n _validate_prim_vertex_index(self, index)\n\n # Delete the vertex.\n _cpp_methods.deleteVertex(geometry, self.number(), index)", "def popvertex(self, pred=None):\n if len(self) == 0:\n return\n\n w = None\n if pred:\n for v in self:\n if pred(v):\n w = v\n break\n if not w:\n return\n else:\n w = self._vertices.pop()\n\n for u in self.neighbors(w):\n self.removeedge(u, w)\n\n return w", "def remove_vertices(self, vertices=[]):\n vertices = set(vertices)\n for vertex in vertices:\n self._edges.pop(vertex, None)\n for entry in self._edges:\n self._edges[entry] -= vertices", "def remove_vertices(self, vertices):\n raise NotImplementedError(\"Not implemented on backend \" + type(self).backend)", "def delete(self, x: \"Vertex\"):\n self._data.remove(x)\n self.build_heap()", "def remove_edge(self, v1, v2):\n if v2 in self._transition_matrix[v1]:\n self._transition_matrix[v1].remove(v2)", "def update_vertex(self, v, overwrite=True):\n orig_prop = self._g.nodes.get(v.vertex_id, None)\n if not orig_prop:\n self._add_vertex(v)\n return\n\n merged_props = \\\n self._merged_properties(orig_prop, v.properties, overwrite)\n self._g.nodes[v.vertex_id].update(merged_props)\n\n for prop, value in v.properties.items():\n if value is None:\n del self._g.nodes[v.vertex_id][prop]", "def _remove(self, u) :\r\n assert u.has_index()\r\n self.adj[u.get_index()]=None\r\n self.size-=1", "def update_vertex(self, v, overwrite=True):\n pass", "def removeOneKnotInV(*args, **kwargs):\n \n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the distance between vertex u and v.
def distance(u, v): # Euclidean Distance # sqrt( (x2-x1)^2 + (y2-y1)^2 ) return math.sqrt(((v.x_pos - u.x_pos)**2) + ((v.y_pos - u.y_pos)**2))
[ "def distance(self, u, v):\n # TODO: Implement the distance function between vectors u and v]\n # Note: you can also think of this as computing a similarity measure\n\n pass", "def cityblock_distance(u, v):\n return abs(u-v).sum()", "def distanceV(vector1, vector2):\n\treturn vector1[1] - vector2[1]", "def correlation(u, v):\n u = _validate_vector(u)\n v = _validate_vector(v)\n umu = u.mean()\n vmu = v.mean()\n um = u - umu\n vm = v - vmu\n dist = 1.0 - np.dot(um, vm) / (norm(um) * norm(vm))\n return dist", "def distances(self, v1, v2):\n v1_2 = v1.unsqueeze(1).expand(v1.size(0), v2.size(0), v1.size(1))\n v2_2 = v2.unsqueeze(0).expand(v1.size(0), v2.size(0), v1.size(1))\n return torch.sqrt(torch.pow(v2_2 - v1_2, 2).sum(2) + 0.000000001)", "def __calculate_vector_distance(vector_x, vector_y):\n return math.fabs(math.sqrt(((vector_y[0]-vector_x[0])**2)+(vector_y[1]-vector_x[1])**2))", "def distance(v, w):\n return ((v[\"lat\"] - w[\"lat\"])**2 + (v[\"long\"] - w[\"long\"])**2)**.5", "def uvdist(self):\n return np.sqrt(np.sum(self._uvw**2, axis=-1))", "def minkowski(u, v, p):\n u = _validate_vector(u)\n v = _validate_vector(v)\n if p < 1:\n raise ValueError(\"p must be at least 1\")\n dist = norm(u - v, ord=p)\n return dist", "def degenerate_triangle_equation(self, u, v, w):\n return self.lam(u,v) - self.lam(u,w) - self.lam(w,v)", "def v(self):\n return self.centroid_velocity_tangent / np.linalg.norm(\n self.centroid_velocity_tangent\n )", "def distance(self, v2):\n if len(self.coordinates) == len(v2.coordinates):\n result = 0\n summe = 0\n for i in range(0, len(v2.coordinates)):\n summe = summe + (self.coordinates[i] - v2.coordinates[i]) ** 2\n result = math.sqrt(summe)\n return result\n else:\n raise ValueError(\"Arrays not of the same dimension!\")", "def dot(u, v):\n return u.x*v.x + u.y*v.y", "def metricCommonEuclidean(u,v):\r\n\r\n where_common = (~np.isnan(u)) * (~np.isnan(v))\r\n\r\n return np.sqrt(((u[where_common] - v[where_common]) ** 2).sum())", "def vectorLength(v):\n return math.sqrt(sum([e*e for e in v])) # really: sqrt of dotProduct(v,v)", "def vec_dist(v1, v2):\n dist = 0\n j = 0\n for i in range(len(v1)):\n while j<len(v2) and v1[i][0]>v2[j][0]:\n dist = dist + v2[j][1]**2\n j = j + 1\n p = v1[i][1]**2 if j>=len(v2) or v2[j][0]>v1[i][0] \\\n else (v2[j][1]-v1[i][1])**2\n dist = dist + p\n if len(v1)==0:\n dist = sum(v[1]**2 for v in v2)\n return dist", "def di_dv(self, v: float) -> float:\n raise NotImplementedError", "def degree(self, v):\n return len(self.neighbors(v))", "def compute_vec2vec_projection(self, u, v):\n return (np.dot(u, v) / np.linalg.norm(v)) * v", "def cosine_similarity(u, v):\n\n cosine_similarity = np.dot(u, v) / (np.sqrt(np.sum(np.square(u))) * np.sqrt(np.sum(np.square(v))))\n return cosine_similarity" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a path from vertex B to vertex S, such that the distance from B to every vertex in the path is within R. If there is no path between B and S within R, then return None.
def find_path(self, b, s, r): start = b path = [] visited = {} for node in self._vertices: visited.update({node: False}) return self.path_finder(start, b, s, r, path, visited)
[ "def distance(R, S):\n t1 = clock()\n if R == None:\n return 0\n if S == None: \n return 0\n if len(S)==1:\n S = S[0]\n if len(R)==1:\n R = R[0]\n condition_s = not(isinstance(S[0], list))\n condition_r = not(isinstance(R[0], list))\n if condition_r and condition_s:#distance btw 2 points\n result = 0\n dim = len(R)\n for i in range(dim):\n result += (R[i] - S[i])**2\n return result\n elif condition_s:\n copie = R\n R = S\n S = copie\n if not(isinstance(R[0], list)):#transformation of a point in a rect\n R1 = [R, R]\n return distance(R1, S)\n\n p_min = []\n p_max = []\n \n dim = len(R[0])\n for i in range(dim):#definition of volumetric distance\n p_min.append(min([R[0][i], R[1][i], S[0][i], S[1][i]]))\n p_max.append(max([R[0][i], R[1][i], S[0][i], S[1][i]]))\n t2 = clock()\n #print(\"tps calcul distance : \", t2 - t1)\n return distance(p_min, p_max)", "def option0_routing(self, S, D, L):\n if self.has_path(S, D): \n Shortest_path = nx.dijkstra_path(self.G, S, D, weight='w') \n return Shortest_path \n else:\n self.logger.info('No path from %s to %s', S, D)\n Shortest_path = []\n return Shortest_path", "def all_paths(self,node, destination, dist, path):\n path = path + [node]\n if len(path)==int(dist)+1:\n if node == destination:\n return path\n else:\n return None\n final_paths=[]\n r=0\n while r<len(self.neighbour):\n if self.neighbour[r][0]==node:\n if self.neighbour[r][1] not in path:\n ans=self.all_paths(self.neighbour[r][1],destination,dist,path)\n if ans is not None:\n if isinstance(ans[0],list):\n final_paths=final_paths+ans\n else:\n final_paths.append(ans)\n r=r+1\n # final_paths have all paths of distance two between two nodes\n if len(final_paths) != 0:\n return final_paths\n else:\n return None", "def find_path(self, start_node, previous_node, destination_node):\r\n opened = []\r\n closed = []\r\n\r\n start_node.heuristic_cost = 0\r\n start_node.f = 0\r\n start_node.g = 0\r\n opened.append(start_node)\r\n\r\n while len(opened) > 0:\r\n minimum_node = None\r\n minimum_f = None\r\n for each_candidate in opened:\r\n if minimum_node is None or minimum_f > each_candidate.f:\r\n minimum_node = each_candidate\r\n minimum_f = each_candidate.f\r\n\r\n\r\n opened.remove(minimum_node)\r\n closed.append(minimum_node)\r\n successors = minimum_node.get_neighbors()\r\n for each_successor in successors:\r\n if each_successor == destination_node:\r\n # found goal\r\n each_successor.parent = minimum_node\r\n break\r\n\r\n # get h value for successor\r\n each_successor.heuristic_cost = Pathfinder.get_estimated_cost(each_successor, destination_node)\r\n # update g value for successor\r\n each_successor.g = minimum_node.g + 1\r\n # determine successor's f value\r\n each_successor.f = each_successor.g + each_successor.heuristic_cost\r\n\r\n # only add to list if it's not in there\r\n if each_successor not in opened and each_successor not in closed:\r\n each_successor.parent = minimum_node\r\n opened.append(each_successor)\r\n\r\n if destination_node.parent is None:\r\n raise Exception('Completed search without finding valid path to destination.')\r\n\r\n return Pathfinder.get_path(destination_node)", "def extract_nearest_path(self):\n\n if not self.remaining_paths:\n return None\n\n path_index = 0\n (path_distance, index_path, index_other_path) = compute_paths_distance(\n self.path,\n self.remaining_paths[0])\n\n for (path_idx, path) in izip(count(1), self.remaining_paths[1:]):\n (dist, idx1, idx2) = compute_paths_distance(self.path, path)\n if dist < path_distance:\n path_distance = dist\n index_path = idx1\n index_other_path = idx2\n path_index = path_idx\n\n # Removing nearest path\n path_to_return = self.remaining_paths.pop(path_index)\n\n return (path_to_return, index_path, index_other_path)", "def get_path(self, node1, node2):\n # If nodes already connected, return edge path\n X_prm, U_prm, V_prm = [], [], 0\n if (node1, node2) in self.edges:\n return self.edges[(node1, node2)]\n shortest_path = self.astar(node1, node2)\n if shortest_path is None:\n return None\n\n print('\\nSHORTEST PATH:', shortest_path)\n for i in range(len(shortest_path)-1):\n pair = shortest_path[i], shortest_path[i+1]\n X_edge, U_edge, V_edge = self.edges[pair]\n X_prm.append(X_edge)\n U_prm.append(U_edge)\n V_prm += V_edge\n\n X_prm = resample(np.vstack(X_prm), MAXTRAJLENGTH)\n U_prm = resample(np.vstack(U_prm), MAXTRAJLENGTH)\n\n return X_prm, U_prm, V_prm", "def rnni_findpath(T, R):\n d = 0\n T1 = T.copy()\n # path = [T1.copy()]\n for k in range(len(R) - 1):\n Ck = R[k]\n r = rank(T1, Ck)\n while r > k:\n v = T1[r]\n u = T1[r - 1]\n if bitwise_subset(u, v):\n # u is a child of v, so do a NNI to reduce rank(T1, Ck).\n w = v - u\n # Find children of u.\n # XXX: assumes binary trees\n leaves = np.nonzero(u)[0]\n if len(leaves) == 2:\n # Both children are leaves.\n x = np.zeros_like(u)\n x[leaves[0]] = 1\n else:\n for x in reversed(T1[: r - 1]):\n if bitwise_subset(x, u):\n # x is a child of u\n break\n else:\n raise ValueError(f\"{u} has no children in {T1}\")\n y = u - x\n # Currently we have u = x + y, and the two NNI options are:\n # u = x + w, or,\n # u = y + w.\n # Only one of these will reduce rank(T1, Ck).\n if bitwise_subset(Ck, x + w):\n T1[r - 1] = x + w\n else:\n T1[r - 1] = y + w\n else:\n # Swap nodes v and u.\n T1[[r, r - 1]] = T1[[r - 1, r]]\n r -= 1 # Both operations reduce the rank by 1.\n d += 1\n # path.append(T1.copy())\n return d # , path", "def a_star_euclidean(self):\r\n visited = set()\r\n parent = {}\r\n path = []\r\n\r\n _queue = queue.PriorityQueue()\r\n current_cost = {}\r\n i = 0\r\n\r\n _queue.put((0,self.start_point))\r\n visited.add(self.start_point)\r\n current_cost[self.start_point] = 0\r\n\r\n while not _queue.empty():\r\n if _queue.qsize() > i:\r\n i = _queue.qsize()\r\n\r\n current_node = _queue.get()\r\n coordinate_current_node = current_node[1]\r\n if coordinate_current_node == self.end_point:\r\n path = self.buildpath(parent)\r\n self.maze.solution = dict(find_path_or_not=\"YES\",\r\n number_of_nodes_visited=len(visited),\r\n visited_nodes=visited,\r\n path_length=len(path),\r\n path=path,\r\n max_fringe_size=i)\r\n return\r\n for child_node in self.maze.neighbor(coordinate_current_node):\r\n next_cost = current_cost[coordinate_current_node] + 1\r\n if child_node not in visited:\r\n current_cost[child_node] = next_cost\r\n parent[child_node] = coordinate_current_node\r\n visited.add(child_node)\r\n # cost so far + h\r\n h = math.sqrt(\r\n (child_node[0] - self.end_point[0]) ** 2 +\r\n (child_node[1] - self.end_point[1]) ** 2\r\n )\r\n\r\n total_cost = h + next_cost\r\n _queue.put((total_cost,child_node))\r\n\r\n self.maze.solution = dict(find_path_or_not=\"NO\",\r\n number_of_nodes_visited=0,\r\n visited_nodes=visited,\r\n path_length=len(path),\r\n path=path,\r\n max_fringe_size=0)\r\n return", "def find_path(\n self,\n s: Vertex,\n t: Vertex,\n k: int\n ) -> Union[List[Vertex], None]:\n\n # TODO implement me please\n path=[]\n n=k\n result=self.dfs(s,t,k,n,path)\n if len(result)==0 or result==None:\n return None\n else:\n return result", "def find_path(self, start_vertex, end_vertex, path=[]):\n graph = self.__graph_dict\n path = path + [start_vertex]\n if start_vertex == end_vertex:\n return path\n if start_vertex not in graph:\n return None\n for vertex, _ in graph[start_vertex]:\n if vertex not in path:\n extended_path = self.find_path(vertex, end_vertex, path)\n if extended_path:\n return extended_path\n return None", "def _search(self, start: Node, goal: Node) -> tuple:\n\n queue = PriorityQueue()\n start.path_weight = 0\n queue.put((0, start))\n\n calculate_heuristic = self.get_weight_function()\n\n while not queue.empty():\n weight, current_node = queue.get()\n print('Visiting node {}, weight {}'.format(current_node.node_name, weight))\n\n if current_node == goal:\n final_path = current_node.path\n final_path += (current_node,)\n return final_path\n\n node_path = current_node.path\n node_path += (current_node,)\n\n for c_weight, c_node in current_node.connections:\n\n weight_so_far = current_node.path_weight + c_weight\n estimated_weight = weight_so_far + calculate_heuristic(c_node, goal)\n\n self._add_to_queue(weight_so_far, estimated_weight, c_node, queue, node_path)\n\n raise ValueError('No paths found')", "def find_path(self):\n nei = self.check_neighbor_options()\n\n self.check_end() # At the finish line, no more work to be done\n\n # Dead End\n if len(nei) == 0:\n self.crossroads(nei)\n\n # Crossroad\n elif len(nei) > 1:\n self.crossroads(nei)\n\n else:\n while len(nei) == 1:\n # If only one direction to move, move it!\n self.move_bot(nei[0])\n nei = self.check_neighbor_options()", "def find_path(self, node1, node2, path=[]):\n\n path = path + [node1]\n if node1 == node2:\n return path\n if node1 not in self.__graph:\n return None\n for node in self.__graph[node1]:\n if node not in path:\n new_path = self.find_path(node, node2, path)\n if new_path:\n return new_path\n return None", "def find_path(self):\n\n found_end = 0\n while found_end == 0:\n\n # Check if the open list is empty, if so send code to nofity that the\n # goal was not found\n if len(self.open_list) == 0:\n found_end = 2\n\n else:\n eval_node = heapq.heappop(self.open_list)\n\n # Check if current node is the goal, if so send code to notify that\n # the goal was found\n if self.check_for_goal(eval_node):\n found_end = 1\n self.goal_node = eval_node\n self.closed_list.append(eval_node)\n\n # Otherwise add the current node to the closed list and evaluate\n # its 8 neighbors\n else:\n self.closed_list.append(eval_node)\n self.analyze_neighbors(eval_node)\n\n return found_end", "def shortest_path (self, from_):\n if from_ not in self.places:\n return None\n\n from_ = self.places[from_]\n\n # Initialization\n self.__initialize()\n \n from_data = from_.get_data()\n from_data.update({'distance': 0})\n result = {}\n\n while True:\n nearest = {'distance': self.__max_distance_value}\n from_data = from_.get_data()\n from_data.update({'found': True})\n #print 'Node %s distance %d path' % (from_data['name'], from_data['distance']),\n #print map(lambda x: x.get_data()['name'], from_data['path'])\n #print from_data['path']\n for adjacent, edge in from_.get_adjacent_edge():\n adjacent_data = adjacent.get_data()\n edge_data = edge.get_data()\n #print 'Check edge (%s, %s) distance %d' % (from_data['name'], adjacent_data['name'], edge_data['distance'])\n if adjacent_data['found'] != True and adjacent_data['distance'] > from_data['distance'] + edge_data['distance']:\n adjacent_data.update({'distance': from_data['distance'] + edge_data['distance'],\n 'path': from_data['path'] + [from_data['name']]})\n #print 'Adjacent %s distance %d' % (adjacent_data['name'], adjacent_data['distance'])\n\n #return {}\n\n for vertex in self.vertice:\n vertex_data = vertex.get_data()\n #print 'Choose: node %s distance %d (min distance %d)' % (vertex_data['name'], vertex_data['distance'], nearest['distance'])\n if vertex_data['found'] != True and vertex_data['distance'] < nearest['distance']:\n nearest = vertex_data\n from_ = vertex\n #return {}\n if nearest['distance'] == self.__max_distance_value:\n break\n else:\n result.update({nearest['name']: {'distance': nearest['distance'], 'path': nearest['path'] + [nearest['name']]}})\n\n\n return result", "def find_fastest_route(self, from_vertex, to_vertex):\n\n if from_vertex not in self.vert_dict or to_vertex not in self.vert_dict:\n raise KeyError(\"One of the vertex doesn't exist!\")\n\n start_vertex = self.vert_dict[from_vertex]\n\n # if the goal and destination at the same vertex\n if from_vertex == to_vertex:\n return [start_vertex], 0\n\n # Initialize our priority queue and path\n queue = PriorityQueue()\n queue.put(PriorityEntry(0, start_vertex))\n path = {start_vertex.data: (0, None)}\n\n # Enqueue all vertices in the graph\n for vert_key, vert in self.vert_dict.items():\n if vert_key != start_vertex.data:\n path[vert_key] = (float(\"inf\"), None)\n queue.put(PriorityEntry(float(\"inf\"), vert))\n\n # While the queue isn't empty\n while not queue.empty():\n\n # Grab the piece of data from the queue and get it's current weight\n curr_vert = queue.get().data\n curr_vert_weight, _ = path[curr_vert.data]\n # Iterate through the neighbors of the current vertex\n for neighbor, weight in curr_vert.neighbors.items():\n\n # Get the neighbors weight\n prev_neighbor_weight, _ = path[neighbor.data]\n total_weight = weight + curr_vert_weight\n\n # Check if the new total weight is greater than what the\n # neighbors previous weight is\n if total_weight < prev_neighbor_weight:\n path[neighbor.data] = (total_weight, curr_vert)\n queue.put(PriorityEntry(total_weight, neighbor))\n\n # No path was found to the vertex, infinite weight away.\n total_weight, prev = path[to_vertex]\n if total_weight == float(\"inf\"):\n return [], total_weight\n\n # Recreate the path\n goal = self.vert_dict[to_vertex]\n minimal_path = [goal]\n\n while prev:\n minimal_path.append(prev)\n _, prev = path[prev.data]\n\n # grab only vertex data to make it easy to visualize\n minimal_path = [node.data for node in minimal_path]\n\n return minimal_path[::-1], total_weight", "def find_path(self, start_vertex, end_vertex, path=None):\n if path == None:\n path = []\n \n graph = self.graph\n \n path = path + [start_vertex]\n \n if start_vertex == end_vertex:\n return path\n \n if start_vertex not in graph:\n return None\n \n for vertex in graph[start_vertex]:\n if vertex not in path:\n extended_path = self.find_path(vertex, \n end_vertex, \n path)\n if extended_path: \n return extended_path\n return None", "def solve(self):\n # add starting cell to open heap queue\n heapq.heappush(self.opened, (self.start.f, self.start))\n while len(self.opened):\n # pop cell from heap queue\n f, cell = heapq.heappop(self.opened)\n # add cell to closed list so we don't process it twice\n self.closed.add(cell)\n # if ending cell, return found path\n if cell is self.end:\n self.path = self.get_path()\n pathlen = np.shape(self.path)[0]\n return self.path, pathlen\n # get adjacent cells for cell\n adj_cells = self.get_adjacent_cells(cell)\n for adj_cell in adj_cells:\n if not adj_cell.iswall and adj_cell not in self.closed:\n if (adj_cell.f, adj_cell) in self.opened:\n # if adj cell in open list, check if current path is\n # better than the one previously found\n # for this adj cell.\n if adj_cell.g > cell.g + 1:\n self.update_cell(adj_cell, cell)\n else:\n self.update_cell(adj_cell, cell)\n # add adj cell to open list\n heapq.heappush(self.opened, (adj_cell.f, adj_cell))\n if len(self.opened)==0:\n print \"Warning: impossible maze!\"\n return None, 0", "def computeShortestPath(self):\n for row in range(len(self.graph)):\n # track row, which vertices to compute greedy Dijkstra\n v = self.graph[row][0][0] # key to sd list\n\n for ele in range(1, len(self.graph[row])):\n if len(self.graph[row][ele]) == 2:\n self.computeGreedyDijkstra(v, self.graph[row][ele])" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the minimum range required to go from Vertex B to Vertex S.
def minimum_range(self, b, s): path = [] final_paths = [] visited = {} for node in self._vertices: visited.update({node: False}) shortest = None max_ranges = [] output = self.minimum_finder(b, s, final_paths, path, visited) for lists in output: max_ranges.append(self.range_finder(lists)) return min(max_ranges)
[ "def smallestRangeI(self, nums, k):\r\n minval = sys.maxsize\r\n maxval = - sys.maxsize\r\n for elem in nums:\r\n minval = min( minval, elem )\r\n maxval = max( maxval, elem )\r\n \r\n if minval + k >= maxval - k:\r\n return 0\r\n else:\r\n return ( maxval - k ) - ( minval + k )", "def start_minimum_spanning_tree(self):\n #create list of vertices, only first vertex is active\n selected_vector=[False if x!=0 else True for x in range(0,self.num_vertices)]\n weight=0\n connections_between_vertices=0\n #if there are less connections between vertices than number vertices-1,perform operations\n while connections_between_vertices<self.num_vertices-1:\n index_of_row_minimum_value=0\n index_of_column_minimum_value=0\n minimum=math.inf\n for row in range(0,self.num_vertices):\n if selected_vector[row]:\n for column in range(0,self.num_vertices):\n if (self.matrix[row][column]>0 and not selected_vector[column]):\n if self.matrix[row][column]<minimum:\n minimum=self.matrix[row][column]\n index_of_row_minimum_value=row\n index_of_column_minimum_value=column\n #if value of edges is chosen,we change the value on 0\n self.matrix[index_of_row_minimum_value][index_of_column_minimum_value]=0\n self.matrix[index_of_column_minimum_value][index_of_row_minimum_value]=0\n #added minimum value to weight\n weight+=minimum\n #we activate vector which is bound by edge which we selected\n selected_vector[index_of_column_minimum_value]=True\n #added minimum value to edges next vector which was selected\n for value in range(0,self.num_vertices):\n if self.matrix[index_of_column_minimum_value][value]!=0:\n self.matrix[index_of_column_minimum_value][value]+=minimum\n print(f\"Edge ({index_of_row_minimum_value}-{index_of_column_minimum_value}) and weight of edge={minimum}. All weight of edges={weight}\")\n selected_vector[index_of_column_minimum_value]=True\n #added minimum value to weight vertices which are selected\n connections_between_vertices+=1\n print(f'Minimum spanning tree weight={weight}')", "def smallest_x(self):\n return min(map(lambda v: v.x, self.vertices)) # was TODO", "def find_min_edge(self):\n m = utils.inf\n for d in self.graph.graph_dict.values():\n local_min = min(d.values())\n m = min(m, local_min)\n return m", "def _get_max_min(self, that):\n maxstart = max(self.start, that.start)\n minstop = min(self.stop, that.stop)\n return (maxstart, minstop)", "def lower_bound(self):\n return self.__lower_bound", "def getMin( self ):\n return min( self.getBinLefts() )", "def find_start_goal(graph, start, goal): \n start = np.array(start)\n goal = np.array(goal)\n \n dist_to_start = []\n dist_to_end = []\n \n for node in graph.nodes:\n dist_to_start.append(np.linalg.norm(np.subtract(node, start)))\n dist_to_end.append(np.linalg.norm(np.subtract(node, goal)))\n \n# print(np.argmin(dist_to_start))\n# print(np.argmin(dist_to_end))\n near_start = list(graph.nodes)[np.argmin(dist_to_start)]\n near_goal = list(graph.nodes)[np.argmin(dist_to_end)]\n\n return near_start, near_goal", "def GetMinPoint(self):\n ...", "def get_min_bounded(*args, low, high):\n minValue = high\n\n for i in args:\n if i > low and i < high and i < minValue:\n minValue = i\n\n return minValue", "def minRange(self):\n if len(self._cells) > 0:\n minRow = self._cells[0].row\n minCol = self._cells[0].col\n for element in self._cells:\n if element.row < minRow:\n minRow = element.row\n if element.col < minCol:\n minCol = element.col\n minRow = int(minRow)\n minCol = int(minCol)\n return (minRow,minCol)\n else:\n return (0,0)", "def _minspan(self,(x,y)):\n\t\talignment_links = [j for (i,j) in self.alignment if (i >= x and i <= y)]\n\t\tif alignment_links == []:\n\t\t\treturn -1\n\t\telse:\n\t\t\treturn min(alignment_links)", "def minimal_step(X):\n return min(abs(X[i+1] - X[i]) for i in range(len(X)-1))", "def find_min(Q, shortest):\n min_v = 0\n min_w = 100000\n\n for v in Q:\n if shortest[v] <= min_w:\n min_v = v\n min_w = shortest[v]\n\n return min_v", "def _calc_min(self):\n return np.min(self.get_points()) - 1", "def smallestRangeII(self, nums, k):\r\n n = len(nums)\r\n nums = sorted(nums)\r\n res = nums[-1] - nums[0]\r\n for i in range(1, n):\r\n minval = min( nums[0]+k, nums[i] - k )\r\n maxval = max( nums[-1]-k, nums[i-1] + k )\r\n res = min( res, maxval - minval )\r\n return res", "def _get_buffering_subregion_minmax(ip, pmin, pmax, rmax):\n if ip == -1:\n smin, smax = pmin - rmax, pmin\n elif ip == 0:\n smin, smax = pmin, pmax\n elif ip == 1:\n smin, smax = pmax, pmax + rmax\n return smin, smax", "def lower_bound(x):\n\n return x[0]", "def smooth_min(a, b, eps=1e-4):\n expr = smooth_minmax(a, b, eps, sense='min')\n return expr" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the defined vertex. If there is already a vertex there, do nothing.
def move_vertex(self, v, new_x, new_y): #Check if vertex exists at position for u in self._vertices: if u.x_pos != new_x and u.y_pos != new_y: v.move_vertex(new_x, new_y)
[ "def update_vertex(self, v, overwrite=True):\n pass", "def _move(self, vertex, word):\n for w in word:\n vertex = self._vtable[vertex][w]\n return vertex", "def remove_vertex(self):\r\n\t\t\tif not self.is_empty():\r\n\t\t\t\tself.vertices.pop()", "def remove_vertex(self):\r\n if self.is_empty():\r\n return None\r\n self.vertices.pop()", "def remove_vertex(self):\r\n if len(self.vertices) > 0:\r\n self.vertices.pop()", "def polyMoveVertex(localDirectionZ=\"string\", scale=float, rotateX=int, localTranslateX=\"string\", localTranslateZ=\"string\", localTranslateY=\"string\", worldSpace=bool, scaleZ=float, pivotY=\"string\", random=float, pivotX=\"string\", translate=\"string\", translateX=\"string\", caching=bool, name=\"string\", localDirectionX=\"string\", translateY=\"string\", localDirection=\"string\", localDirectionY=\"string\", pivot=\"string\", pivotZ=\"string\", rotate=int, rotateY=int, translateZ=\"string\", nodeState=int, scaleY=float, rotateZ=int, scaleX=float, localTranslate=\"string\", constructionHistory=bool):\n pass", "def update_vertex(self, v, overwrite=True):\n orig_prop = self._g.nodes.get(v.vertex_id, None)\n if not orig_prop:\n self._add_vertex(v)\n return\n\n merged_props = \\\n self._merged_properties(orig_prop, v.properties, overwrite)\n self._g.nodes[v.vertex_id].update(merged_props)\n\n for prop, value in v.properties.items():\n if value is None:\n del self._g.nodes[v.vertex_id][prop]", "def add_vertex(self, v):\n if v not in self.vertices.keys(): \n self.vertices[v] = [False,[],0]", "def toggle_snap_to_vertex():\r\n pass", "def remove_vertex(self, vertex):\n self.remove_vertices([vertex])", "def resolve(self, vertex_to):\n if self.is_resolved:\n raise Exception(\"Re-assigning vertex is not allowed.\")\n self.vertex_to = vertex_to\n self.is_resolved = True", "def add_vertex(self, vertex):\n if isinstance(vertex, Vertex) and vertex.name not in self.vertices:\n self.vertices[vertex.name] = vertex\n return True\n else:\n return False", "def add_vertex(self, vertex):\n if vertex.label not in self.vertices():\n self.__graph_dict[vertex.label] = vertex", "def add_vertex(self, v):\n pass", "def insert_vertex(self, x=None):\n v = self.Vertex(x)\n self._outgoing[v] = { }\n if self.is_directed():\n self._incoming[v] = { } # need distinct map for incoming edges\n return v", "def test_directed_graph_remove_vertex(self):\n g = DirectedGraph()\n g.add_vertex(v_val='v0')\n g.add_vertex(v_val='v1')\n g.add_vertex(v_val='v2')\n g.add_edge(('v0', 'v1'))\n g.add_edge(('v1', 'v2'))\n\n g.remove_vertex('v0')\n\n self.assertFalse(g.has_vertex('v0'))\n self.assertTrue(g.has_vertex('v1'))\n self.assertTrue(g.has_vertex('v2'))\n self.assertFalse(g.has_edge(('v0', 'v1')))\n self.assertFalse(g.has_edge(('v1', 'v0')))\n self.assertTrue(g.has_edge(('v1', 'v2')))\n\n g.remove_vertex('v1')\n\n self.assertFalse(g.has_vertex('v0'))\n self.assertFalse(g.has_vertex('v1'))\n self.assertTrue(g.has_vertex('v2'))\n self.assertFalse(g.has_edge(('v0', 'v1')))\n self.assertFalse(g.has_edge(('v1', 'v1')))\n self.assertFalse(g.has_edge(('v1', 'v2')))", "def update(self, new_priority, vertex):\n node = self.__locator.pop(vertex.id) # delete from dictionary\n node[-1] = None # invalidate old node\n self.push(new_priority, vertex) # push new node", "def add_vertex(self, vertex):\r\n self.vertices.append(vertex)", "def moveVertexAlongDirection(vDirection=\"string\", magnitude=\"string\", uDirection=\"string\", uvNormalDirection=\"string\", normalDirection=\"string\", direction=float):\n pass" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The connection preference to use for this service attachment. Valid values include "ACCEPT_AUTOMATIC", "ACCEPT_MANUAL".
def connection_preference(self) -> pulumi.Input[str]: return pulumi.get(self, "connection_preference")
[ "def connection_preference(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"connection_preference\")", "def AutoNegotiation(self):\r\n\t\treturn self._get_attribute('autoNegotiation')", "def preferred_autoattach_pod_interface(self):\n return self._preferred_autoattach_pod_interface", "def preference_set(self) -> str:\n return pulumi.get(self, \"preference_set\")", "def preferred_autoattach_graphics_device(self):\n return self._preferred_autoattach_graphics_device", "def user_preference(self):\n return self._user_preference", "def GetPreferWiredNetwork(self):\n return self.prefer_wired", "def _get_networkPreferences(self) -> \"adsk::core::Ptr< adsk::core::NetworkPreferences >\" :\n return _core.Preferences__get_networkPreferences(self)", "def share_mode(self):\n return self._share_mode", "def connection_requested(self):\n return self._connection_requested", "def preferred_autoattach_input_device(self):\n return self._preferred_autoattach_input_device", "def _get_default_connection(self) -> PublicId:\n return self._default_connection", "def clientMode(self):\n\n return internals.blpapi_SessionOptions_clientMode(self.__handle)", "def preference(self):\n # We use the ``price_per_share`` variable here since the\n # original investment vehicle may have been a convertible\n # and the original cash paid may not be relevant.\n # Note: this is an important concept which can affect future\n # financings. The term is called \"liquidation overhang\"\n # and you should learn more about it. Yokum Taku at WSGR\n # has proposed solutions to avoid it and you should\n # read about them here:\n # http://www.startupcompanylawyer.com/category/convertible-note-bridge-financing/\n if self.security.security_type == SECURITY_TYPE_PREFERRED:\n return (\n self.outstanding\n * self.security.price_per_share\n * self.security.liquidation_preference)\n elif self.security.security_type == SECURITY_TYPE_CONVERTIBLE:\n try:\n # If the stock converts it will share the same preference\n # as its parent security.\n return self.outstanding_debt * self.liquidation_preference\n # But if there is no parent then it reverts to the debt itself\n # This basically means that the preference is calling\n # the loan itself due and payable (with interest.)\n except:\n return self.accrued\n else:\n return 0", "def getClientMode(self):\n return self.request('getClientMode')", "def BgpLsOverridePeerAsSetMode(self):\n return self._get_attribute('bgpLsOverridePeerAsSetMode')", "def get_conn(self) -> ClientConfig:\n return self.client_config", "def prefer(self):\n for pc in PersistantConnection.objects.filter(reporter=self.reporter):\n pc.preferred = True if pc == self else False\n pc.save()", "def _get_appearanceOverride(self) -> \"adsk::core::Ptr< adsk::core::Appearance >\" :\n return _core.MaterialPreferences__get_appearanceOverride(self)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If true, enable the proxy protocol which is for supplying client TCP/IP address data in TCP connections that traverse proxies on their way to destination servers.
def enable_proxy_protocol(self) -> pulumi.Input[bool]: return pulumi.get(self, "enable_proxy_protocol")
[ "def _set_networkProxySetting(self, *args) -> \"bool\" :\n return _core.NetworkPreferences__set_networkProxySetting(self, *args)", "def __setHTTPProxy():\n\n global proxyHandler\n\n if not conf.proxy: \n if conf.hostname in ('localhost', '127.0.0.1') or conf.ignoreProxy:\n proxyHandler = urllib2.ProxyHandler({})\n return\n\n debugMsg = \"setting the HTTP proxy to pass by all HTTP requests\"\n logger.debug(debugMsg)\n\n __proxySplit = urlparse.urlsplit(conf.proxy)\n __hostnamePort = __proxySplit[1].split(\":\")\n\n __scheme = __proxySplit[0]\n __hostname = __hostnamePort[0]\n __port = None\n\n if len(__hostnamePort) == 2:\n try:\n __port = int(__hostnamePort[1])\n except:\n pass #drops into the next check block\n\n if not __scheme or not __hostname or not __port:\n errMsg = \"proxy value must be in format 'http://url:port'\"\n raise sqlmapSyntaxException, errMsg\n\n __proxyString = \"%s:%d\" % (__hostname, __port)\n\n # Workaround for http://bugs.python.org/issue1424152 (urllib/urllib2:\n # HTTPS over (Squid) Proxy fails) as long as HTTP over SSL requests\n # can't be tunneled over an HTTP proxy natively by Python (<= 2.5)\n # urllib2 standard library\n if conf.scheme == \"https\":\n proxyHandler = ProxyHTTPSHandler(__proxyString)\n else:\n proxyHandler = urllib2.ProxyHandler({\"http\": __proxyString})", "def supports_proxy(self):\n return # boolean", "def enable_proxy(proxy_name: str, configuration: Configuration = None):\n return modify_proxy(\n proxy_name=proxy_name, enabled=True, configuration=configuration\n )", "def enable_https_proxy(self, value):\n self._set_property('enable_https_proxy', value)", "def useProxy(self, config, logger=None):\n return self.use_proxy", "def use_system_proxy_setting(self):\n return \"true\" == self.get(\"network\", \"use_system_proxy_settings\", \"true\").lower()", "def set_proxy(proxy: str) -> bool:\n resp = get_config()\n if not resp:\n return False\n data = resp[\"result\"]\n path = resp[\"path\"]\n data[\"proxy\"] = proxy\n with open(path, \"w\") as file:\n json.dump(data, file, sort_keys=True, indent=\"\")\n return True", "def use_client_proxy(request):\n if (\n config.DEPLOYMENT.get(\"proxy\")\n or config.DEPLOYMENT.get(\"disconnected\")\n or config.ENV_DATA.get(\"private_link\")\n ) and config.ENV_DATA.get(\"client_http_proxy\"):\n log.info(f\"Configuring client proxy: {config.ENV_DATA['client_http_proxy']}\")\n os.environ[\"http_proxy\"] = config.ENV_DATA[\"client_http_proxy\"]\n os.environ[\"https_proxy\"] = config.ENV_DATA[\"client_http_proxy\"]", "def useproxyport(self) :\n try :\n return self._useproxyport\n except Exception as e:\n raise e", "def setproxy(self,proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):\r\n self.__proxy = (proxytype,addr,port,rdns,username,password)", "def can_make_proxy():\n return core.dependency_is_installed(\"voms-clients-cpp\") or server_is_installed()", "def modify_proxy(\n proxy_name: str,\n listen_address: str = None,\n upstream_address: str = None,\n enabled: bool = None,\n configuration: Configuration = None,\n):\n json = {}\n if listen_address is not None:\n json[\"listen\"] = listen_address\n if upstream_address is not None:\n json[\"upstream\"] = upstream_address\n if enabled is not None:\n json[\"enabled\"] = enabled\n logger.debug(\"Modifying proxy with the following data: {}\".format(str(json)))\n proxy = toxiproxyapi.modify_proxy(\n proxy_name=proxy_name, proxy_json=json, configuration=configuration\n )\n if not proxy:\n logger.error(\"Unable to modify proxy {}\".format(proxy_name))\n raise AssertionError\n return_port = proxy[\"listen\"].split(\":\")[-1]\n config_key = \"{}_PORT\".format(proxy_name)\n entry = return_port\n configuration[config_key] = entry\n environ[config_key] = entry\n return True", "def enable_https_proxy(self):\n # type: () -> int\n return self._get_property('enable_https_proxy')", "def get_useproxyport(self):\n return self.options['useproxyport']", "def proxy(self):\n if self._proxy is not None:\n if self._proxy[:7] == \"http://\":\n self._proxy = {'http://': self._proxy}\n Color.pl(\"{+} Proxy: %s\" % self._proxy['http://'])\n elif self._proxy[:8] == \"https://\":\n self._proxy = {'https://': self._proxy}\n Color.pl(\"{+} Proxy: %s\" % self._proxy['https://'])\n elif self._proxy[:3] == \"ftp\":\n self._proxy = {'ftp': self._proxy}\n Color.pl(\"{+} Proxy: %s\" % self._proxy['ftp'])\n else:\n self._proxy = \"\"\n return self._proxy", "def send_enable_forwarding(self):\n pass", "def alter_proxy(proxy):\n # Default case where 'proxy' key is not set -- do nothing\n proxy_value = proxy.lower()\n # python-swift client takes into account both\n # upper and lower case proxies so clear them all\n os.environ.pop(\"http_proxy\", None)\n os.environ.pop(\"https_proxy\", None)\n os.environ.pop(\"HTTP_PROXY\", None)\n os.environ.pop(\"HTTPS_PROXY\", None)\n if proxy_value.startswith('http://') or \\\n proxy_value.startswith('https://'):\n LOG.info('Using proxy {0}'.format(proxy_value))\n os.environ['HTTP_PROXY'] = str(proxy_value)\n os.environ['HTTPS_PROXY'] = str(proxy_value)\n else:\n raise Exception('Proxy has unknown scheme')", "def supports_proxy(self):\n # Implemented from template for\n # osid.resource.ResourceProfile.supports_resource_lookup\n return 'supports_proxy' in profile.SUPPORTS" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An array of subnets that is provided for NAT in this service attachment.
def nat_subnets(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: return pulumi.get(self, "nat_subnets")
[ "def _get_subnets(self) -> List[dict]:\n print('Getting subnets...')\n\n return self._run_az([\n 'network', 'vnet', 'subnet', 'list',\n '--resource-group', self._selected_resource_group['name'],\n '--vnet-name', self._selected_virtual_network['name']\n ])", "def allowed_subnets(self) -> Sequence['outputs.GetVirtualNetworkAllowedSubnetResult']:\n return pulumi.get(self, \"allowed_subnets\")", "def get_subnet_list(self, environment):\n if environment != 'uncategorized':\n subnets_with_instances = self.aws_moduleobj.get_information(environment, subnets_with_instances='true')\n subnet_list = []\n for subnet, stack_list in subnets_with_instances.iteritems():\n for attribute, attr_details in self.module_config_data['stack_attributes'].iteritems():\n if attr_details['stack'] == 'all' or set(attr_details['stack']).issubset(set(stack_list)):\n if subnet not in subnet_list: subnet_list.append(subnet)\n return subnet_list", "def subnet_names(self) -> Sequence[str]:\n return pulumi.get(self, \"subnet_names\")", "def get_restricted_subnets(self):\n self.navigate_to(self.CONFIGURE, self.CONFIGURE_GUEST_ACCESS)\n\n #@author: Jane.Guo @since: 2013-09 adapt to 9.8 guest access improvement\n edit_span = self.info['loc_cfg_guest_access_edit_span'] % DEFAULT_GUEST_ACCESS_NAME\n time.sleep(2)\n self.s.click_and_wait(edit_span)\n self.s.click_and_wait(self.info['loc_cfg_guest_access_restrict_list'])\n \n subnet_list = []\n i = 1\n while True:\n i = i + 1\n locator = self.info['loc_cfg_restricted_rule_row']\n locator = locator.replace(\"$_$\", str(i))\n time.sleep(3)\n if self.s.is_element_present(locator):\n locator = self.info['loc_cfg_restricted_subnets_textbox']\n locator = locator.replace(\"$_$\", str(i))\n subnet = self.s.get_text(locator)\n subnet_list.append(subnet)\n\n else:\n break\n self.s.click_and_wait(self.info['loc_cfg_guest_access_cancel'])\n time.sleep(1)\n\n return subnet_list", "def _provide_subnets(self):\n if not self.cfg.aws.subnet:\n logging.debug(\"Subnets are not provided\")\n # Try to get subnet from default VPC or VPC set in aws-vpc config parameter\n vpc = self._provide_vpc()\n if vpc:\n subnet_list = vpc.subnets.all()\n self.vpc_id = vpc.id\n self.subnets = ','.join(map(lambda x: x.id, subnet_list))\n else:\n # Ensure that VPC is set and that subnets provided belong to it\n subnets = [x.strip() for x in self.cfg.aws.subnet.split(',')]\n # If aws-vpc parameter is set, use this VPC, otherwise use VPC of the\n # first subnet\n logging.debug(f\"Subnets are provided: {' ,'.join(subnets)}\")\n vpc = None\n if self.vpc_id:\n if self.vpc_id.lower() == 'none':\n return None\n vpc = self.ec2.Vpc(self.vpc_id)\n for subnet_name in subnets:\n subnet = self.ec2.Subnet(subnet_name)\n if not vpc:\n vpc = subnet.vpc # if subnet is invalid - will throw an exception botocore.exceptions.ClientError with InvalidSubnetID.NotFound\n else:\n if subnet.vpc != vpc:\n raise UserReportError(returncode=INPUT_ERROR, message=\"Subnets set in aws-subnet parameter belong to different VPCs\")\n self.vpc_id = vpc.id\n self.subnets = ','.join(subnets)\n logging.debug(f\"Using VPC {self.vpc_id}, subnet(s) {self.subnets}\")", "def test_azure_service_api_network_subnets_get(self):\n pass", "def test_vmware_service_resources_subnets_get(self):\n pass", "def multi_subnet_ip_configurations(self) -> Optional[Sequence['outputs.MultiSubnetIpConfigurationResponse']]:\n return pulumi.get(self, \"multi_subnet_ip_configurations\")", "def load_excluded_subnets():\n \n control_networks = list()\n with open('/etc/map/testbed-control-subnets.txt') as f:\n for line in f:\n subnet = ipaddress.ip_network(line.strip())\n control_networks.append(subnet)\n\n return control_networks", "def private_subnet(template):\n return template.resources[\"PrivateSubnet\"]", "def get_subnets(connection, vpc_id):\n return connection.get_all_subnets(filters={'vpc_id': vpc_id})", "def validate_subnets(subnet_spec):\n exit_if_none(subnet_spec, \"Missing subnets\")\n actual_subnets = {}\n paginator = boto3.client('ec2').get_paginator('describe_subnets')\n for page in paginator.paginate():\n for subnet in page['Subnets']:\n actual_subnets[subnet['SubnetId']] = subnet['VpcId']\n subnets = []\n vpcs = set()\n for subnet_id in subnet_spec.split(\",\"):\n vpc_id = actual_subnets.get(subnet_id)\n exit_if_none(vpc_id, f\"invalid subnet: {subnet_id}\")\n subnets.append(subnet_id)\n vpcs.add(vpc_id)\n if (len(vpcs) > 1):\n exit_if_none(None, \"subnets belong to different VPCs\")\n return subnets", "def get_subnet(self, subnet_id):", "def get_subnets(self, ec2, client):\n filters = [{'Name': 'vpc-id', 'Values': [self.vpc_id]}]\n self.subnets = list(ec2.subnets.filter(Filters=filters))\n public_subnets = OrderedDict()\n private_subnets = OrderedDict()\n\n for subnet in self.subnets:\n subnet_full = client.describe_subnets(\n SubnetIds=[subnet.id]).get('Subnets')[0]\n tag_dict = {t['Key'] : t['Value'] for t in subnet_full['Tags']}\n try:\n network = tag_dict['Network']\n except KeyError:\n network = None\n name = tag_dict['Name']\n if name[:6].lower() == 'public':\n public_subnets[tag_dict['Name']] = {'Name' : name, 'id' : subnet.id}\n elif name[:7].lower() == 'private':\n private_subnets[tag_dict['Name']] = {'Name': name, 'id': subnet.id}\n sorted_public_subnets = [public_subnets[x] for x in sorted(public_subnets)]\n sorted_private_subnets = [private_subnets[x] for x in sorted(private_subnets)]\n self.public_subnets = sorted_public_subnets\n self.private_subnets = sorted_private_subnets", "def subnet_overrides(self) -> Sequence['outputs.GetVirtualNetworkSubnetOverrideResult']:\n return pulumi.get(self, \"subnet_overrides\")", "def networks(self) -> pulumi.Input[List[pulumi.Input['ManagedZonePrivateVisibilityConfigNetworkArgs']]]:\n return pulumi.get(self, \"networks\")", "def find_subnets(self, display_name):\n _logger.debug('%s', where_am_i())\n dn_re = re.compile(display_name)\n subnets = []\n for subnet in self.all_subnets():\n res = dn_re.search(subnet.get_display_name())\n if res is not None:\n subnets.append(subnet)\n return subnets", "def instance_subnet_tags(self):\n # uses dict() here to make a copy, just to be safe\n return dict(self._unit.received.get(\"instance-subnet-tags\", {}))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The connection preference to use for this service attachment. Valid values include "ACCEPT_AUTOMATIC", "ACCEPT_MANUAL".
def connection_preference(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "connection_preference")
[ "def connection_preference(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"connection_preference\")", "def AutoNegotiation(self):\r\n\t\treturn self._get_attribute('autoNegotiation')", "def preferred_autoattach_pod_interface(self):\n return self._preferred_autoattach_pod_interface", "def preference_set(self) -> str:\n return pulumi.get(self, \"preference_set\")", "def preferred_autoattach_graphics_device(self):\n return self._preferred_autoattach_graphics_device", "def user_preference(self):\n return self._user_preference", "def GetPreferWiredNetwork(self):\n return self.prefer_wired", "def _get_networkPreferences(self) -> \"adsk::core::Ptr< adsk::core::NetworkPreferences >\" :\n return _core.Preferences__get_networkPreferences(self)", "def share_mode(self):\n return self._share_mode", "def connection_requested(self):\n return self._connection_requested", "def preferred_autoattach_input_device(self):\n return self._preferred_autoattach_input_device", "def _get_default_connection(self) -> PublicId:\n return self._default_connection", "def clientMode(self):\n\n return internals.blpapi_SessionOptions_clientMode(self.__handle)", "def preference(self):\n # We use the ``price_per_share`` variable here since the\n # original investment vehicle may have been a convertible\n # and the original cash paid may not be relevant.\n # Note: this is an important concept which can affect future\n # financings. The term is called \"liquidation overhang\"\n # and you should learn more about it. Yokum Taku at WSGR\n # has proposed solutions to avoid it and you should\n # read about them here:\n # http://www.startupcompanylawyer.com/category/convertible-note-bridge-financing/\n if self.security.security_type == SECURITY_TYPE_PREFERRED:\n return (\n self.outstanding\n * self.security.price_per_share\n * self.security.liquidation_preference)\n elif self.security.security_type == SECURITY_TYPE_CONVERTIBLE:\n try:\n # If the stock converts it will share the same preference\n # as its parent security.\n return self.outstanding_debt * self.liquidation_preference\n # But if there is no parent then it reverts to the debt itself\n # This basically means that the preference is calling\n # the loan itself due and payable (with interest.)\n except:\n return self.accrued\n else:\n return 0", "def getClientMode(self):\n return self.request('getClientMode')", "def BgpLsOverridePeerAsSetMode(self):\n return self._get_attribute('bgpLsOverridePeerAsSetMode')", "def get_conn(self) -> ClientConfig:\n return self.client_config", "def prefer(self):\n for pc in PersistantConnection.objects.filter(reporter=self.reporter):\n pc.preferred = True if pc == self else False\n pc.save()", "def _get_appearanceOverride(self) -> \"adsk::core::Ptr< adsk::core::Appearance >\" :\n return _core.MaterialPreferences__get_appearanceOverride(self)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing ServiceAttachment resource's state with the given name, id, and optional extra properties used to qualify the lookup.
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, connected_endpoints: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ServiceAttachmentConnectedEndpointArgs']]]]] = None, connection_preference: Optional[pulumi.Input[str]] = None, consumer_accept_lists: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ServiceAttachmentConsumerAcceptListArgs']]]]] = None, consumer_reject_lists: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, description: Optional[pulumi.Input[str]] = None, domain_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, enable_proxy_protocol: Optional[pulumi.Input[bool]] = None, fingerprint: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, nat_subnets: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, project: Optional[pulumi.Input[str]] = None, reconcile_connections: Optional[pulumi.Input[bool]] = None, region: Optional[pulumi.Input[str]] = None, self_link: Optional[pulumi.Input[str]] = None, target_service: Optional[pulumi.Input[str]] = None) -> 'ServiceAttachment': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = _ServiceAttachmentState.__new__(_ServiceAttachmentState) __props__.__dict__["connected_endpoints"] = connected_endpoints __props__.__dict__["connection_preference"] = connection_preference __props__.__dict__["consumer_accept_lists"] = consumer_accept_lists __props__.__dict__["consumer_reject_lists"] = consumer_reject_lists __props__.__dict__["description"] = description __props__.__dict__["domain_names"] = domain_names __props__.__dict__["enable_proxy_protocol"] = enable_proxy_protocol __props__.__dict__["fingerprint"] = fingerprint __props__.__dict__["name"] = name __props__.__dict__["nat_subnets"] = nat_subnets __props__.__dict__["project"] = project __props__.__dict__["reconcile_connections"] = reconcile_connections __props__.__dict__["region"] = region __props__.__dict__["self_link"] = self_link __props__.__dict__["target_service"] = target_service return ServiceAttachment(resource_name, opts=opts, __props__=__props__)
[ "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n alb_target_group_arn: Optional[pulumi.Input[str]] = None,\n autoscaling_group_name: Optional[pulumi.Input[str]] = None,\n elb: Optional[pulumi.Input[str]] = None,\n lb_target_group_arn: Optional[pulumi.Input[str]] = None) -> 'Attachment':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _AttachmentState.__new__(_AttachmentState)\n\n __props__.__dict__[\"alb_target_group_arn\"] = alb_target_group_arn\n __props__.__dict__[\"autoscaling_group_name\"] = autoscaling_group_name\n __props__.__dict__[\"elb\"] = elb\n __props__.__dict__[\"lb_target_group_arn\"] = lb_target_group_arn\n return Attachment(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n enabled: Optional[pulumi.Input[bool]] = None,\n entity_guid: Optional[pulumi.Input[str]] = None,\n monitor_id: Optional[pulumi.Input[str]] = None,\n name: Optional[pulumi.Input[str]] = None,\n policy_id: Optional[pulumi.Input[int]] = None,\n runbook_url: Optional[pulumi.Input[str]] = None) -> 'AlertCondition':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _AlertConditionState.__new__(_AlertConditionState)\n\n __props__.__dict__[\"enabled\"] = enabled\n __props__.__dict__[\"entity_guid\"] = entity_guid\n __props__.__dict__[\"monitor_id\"] = monitor_id\n __props__.__dict__[\"name\"] = name\n __props__.__dict__[\"policy_id\"] = policy_id\n __props__.__dict__[\"runbook_url\"] = runbook_url\n return AlertCondition(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'Service':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = dict()\n\n __props__[\"correlation_scheme\"] = None\n __props__[\"default_move_cost\"] = None\n __props__[\"etag\"] = None\n __props__[\"location\"] = None\n __props__[\"name\"] = None\n __props__[\"partition_description\"] = None\n __props__[\"placement_constraints\"] = None\n __props__[\"provisioning_state\"] = None\n __props__[\"service_kind\"] = None\n __props__[\"service_load_metrics\"] = None\n __props__[\"service_package_activation_mode\"] = None\n __props__[\"service_placement_policies\"] = None\n __props__[\"service_type_name\"] = None\n __props__[\"tags\"] = None\n __props__[\"type\"] = None\n return Service(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n force: Optional[pulumi.Input[str]] = None,\n havip_id: Optional[pulumi.Input[str]] = None,\n instance_id: Optional[pulumi.Input[str]] = None,\n instance_type: Optional[pulumi.Input[str]] = None,\n status: Optional[pulumi.Input[str]] = None) -> 'HAVipAttachment':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _HAVipAttachmentState.__new__(_HAVipAttachmentState)\n\n __props__.__dict__[\"force\"] = force\n __props__.__dict__[\"havip_id\"] = havip_id\n __props__.__dict__[\"instance_id\"] = instance_id\n __props__.__dict__[\"instance_type\"] = instance_type\n __props__.__dict__[\"status\"] = status\n return HAVipAttachment(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n policy_id: Optional[pulumi.Input[str]] = None,\n target_id: Optional[pulumi.Input[str]] = None,\n target_type: Optional[pulumi.Input[str]] = None) -> 'PolicyAttachment':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _PolicyAttachmentState.__new__(_PolicyAttachmentState)\n\n __props__.__dict__[\"policy_id\"] = policy_id\n __props__.__dict__[\"target_id\"] = target_id\n __props__.__dict__[\"target_type\"] = target_type\n return PolicyAttachment(resource_name, opts=opts, __props__=__props__)", "async def get_attachment_by_id(self, _id):\n\n async with self.postgres.acquire() as conn:\n async with conn.cursor() as curs:\n await curs.execute('''\n SELECT * FROM attachment\n WHERE id=%s;\n ''',\n (_id,))\n attachment_record = await curs.fetchone()\n\n attachment = await self.get_attachment_by_selector({\"sha256\": attachment_record[2]})\n\n return {\n \"_id\": attachment_record[0],\n \"content\": attachment[\"content\"],\n \"filename\": attachment[\"filename\"],\n \"tags\": attachment[\"tags\"],\n \"sha256\": attachment[\"sha256\"]}", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n desired_state: Optional[pulumi.Input[str]] = None,\n properties: Optional[pulumi.Input[str]] = None,\n role_arn: Optional[pulumi.Input[str]] = None,\n schema: Optional[pulumi.Input[str]] = None,\n type_name: Optional[pulumi.Input[str]] = None,\n type_version_id: Optional[pulumi.Input[str]] = None) -> 'Resource':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _ResourceState.__new__(_ResourceState)\n\n __props__.__dict__[\"desired_state\"] = desired_state\n __props__.__dict__[\"properties\"] = properties\n __props__.__dict__[\"role_arn\"] = role_arn\n __props__.__dict__[\"schema\"] = schema\n __props__.__dict__[\"type_name\"] = type_name\n __props__.__dict__[\"type_version_id\"] = type_version_id\n return Resource(resource_name, opts=opts, __props__=__props__)", "def get_by_id(self, _id):\n return File(self.context, ServiceOperationPath(\"getById\", [_id], self.resource_path))", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n device: Optional[pulumi.Input[str]] = None,\n instance_id: Optional[pulumi.Input[str]] = None,\n multiattach: Optional[pulumi.Input[bool]] = None,\n region: Optional[pulumi.Input[str]] = None,\n vendor_options: Optional[pulumi.Input[pulumi.InputType['VolumeAttachVendorOptionsArgs']]] = None,\n volume_id: Optional[pulumi.Input[str]] = None) -> 'VolumeAttach':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _VolumeAttachState.__new__(_VolumeAttachState)\n\n __props__.__dict__[\"device\"] = device\n __props__.__dict__[\"instance_id\"] = instance_id\n __props__.__dict__[\"multiattach\"] = multiattach\n __props__.__dict__[\"region\"] = region\n __props__.__dict__[\"vendor_options\"] = vendor_options\n __props__.__dict__[\"volume_id\"] = volume_id\n return VolumeAttach(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n name: Optional[pulumi.Input[str]] = None,\n settings: Optional[pulumi.Input[pulumi.InputType['ExchangeSettingsArgs']]] = None,\n vhost: Optional[pulumi.Input[str]] = None) -> 'Exchange':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _ExchangeState.__new__(_ExchangeState)\n\n __props__.__dict__[\"name\"] = name\n __props__.__dict__[\"settings\"] = settings\n __props__.__dict__[\"vhost\"] = vhost\n return Exchange(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'ExtendedDatabaseBlobAuditingPolicy':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = ExtendedDatabaseBlobAuditingPolicyArgs.__new__(ExtendedDatabaseBlobAuditingPolicyArgs)\n\n __props__.__dict__[\"audit_actions_and_groups\"] = None\n __props__.__dict__[\"is_azure_monitor_target_enabled\"] = None\n __props__.__dict__[\"is_managed_identity_in_use\"] = None\n __props__.__dict__[\"is_storage_secondary_key_in_use\"] = None\n __props__.__dict__[\"name\"] = None\n __props__.__dict__[\"predicate_expression\"] = None\n __props__.__dict__[\"queue_delay_ms\"] = None\n __props__.__dict__[\"retention_days\"] = None\n __props__.__dict__[\"state\"] = None\n __props__.__dict__[\"storage_account_subscription_id\"] = None\n __props__.__dict__[\"storage_endpoint\"] = None\n __props__.__dict__[\"type\"] = None\n return ExtendedDatabaseBlobAuditingPolicy(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n argument: Optional[pulumi.Input[str]] = None,\n binding_key: Optional[pulumi.Input[str]] = None,\n binding_type: Optional[pulumi.Input[str]] = None,\n destination_name: Optional[pulumi.Input[str]] = None,\n instance_id: Optional[pulumi.Input[str]] = None,\n source_exchange: Optional[pulumi.Input[str]] = None,\n virtual_host_name: Optional[pulumi.Input[str]] = None) -> 'Binding':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _BindingState.__new__(_BindingState)\n\n __props__.__dict__[\"argument\"] = argument\n __props__.__dict__[\"binding_key\"] = binding_key\n __props__.__dict__[\"binding_type\"] = binding_type\n __props__.__dict__[\"destination_name\"] = destination_name\n __props__.__dict__[\"instance_id\"] = instance_id\n __props__.__dict__[\"source_exchange\"] = source_exchange\n __props__.__dict__[\"virtual_host_name\"] = virtual_host_name\n return Binding(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n archive_size_bytes: Optional[pulumi.Input[int]] = None,\n creation_timestamp: Optional[pulumi.Input[str]] = None,\n description: Optional[pulumi.Input[str]] = None,\n disk_size_gb: Optional[pulumi.Input[int]] = None,\n family: Optional[pulumi.Input[str]] = None,\n guest_os_features: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ImageGuestOsFeatureArgs']]]]] = None,\n image_encryption_key: Optional[pulumi.Input[pulumi.InputType['ImageImageEncryptionKeyArgs']]] = None,\n label_fingerprint: Optional[pulumi.Input[str]] = None,\n labels: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,\n licenses: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n name: Optional[pulumi.Input[str]] = None,\n project: Optional[pulumi.Input[str]] = None,\n raw_disk: Optional[pulumi.Input[pulumi.InputType['ImageRawDiskArgs']]] = None,\n self_link: Optional[pulumi.Input[str]] = None,\n source_disk: Optional[pulumi.Input[str]] = None,\n source_image: Optional[pulumi.Input[str]] = None,\n source_snapshot: Optional[pulumi.Input[str]] = None,\n storage_locations: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None) -> 'Image':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _ImageState.__new__(_ImageState)\n\n __props__.__dict__[\"archive_size_bytes\"] = archive_size_bytes\n __props__.__dict__[\"creation_timestamp\"] = creation_timestamp\n __props__.__dict__[\"description\"] = description\n __props__.__dict__[\"disk_size_gb\"] = disk_size_gb\n __props__.__dict__[\"family\"] = family\n __props__.__dict__[\"guest_os_features\"] = guest_os_features\n __props__.__dict__[\"image_encryption_key\"] = image_encryption_key\n __props__.__dict__[\"label_fingerprint\"] = label_fingerprint\n __props__.__dict__[\"labels\"] = labels\n __props__.__dict__[\"licenses\"] = licenses\n __props__.__dict__[\"name\"] = name\n __props__.__dict__[\"project\"] = project\n __props__.__dict__[\"raw_disk\"] = raw_disk\n __props__.__dict__[\"self_link\"] = self_link\n __props__.__dict__[\"source_disk\"] = source_disk\n __props__.__dict__[\"source_image\"] = source_image\n __props__.__dict__[\"source_snapshot\"] = source_snapshot\n __props__.__dict__[\"storage_locations\"] = storage_locations\n return Image(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n attachments: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VolumeV1AttachmentArgs']]]]] = None,\n availability_zone: Optional[pulumi.Input[str]] = None,\n description: Optional[pulumi.Input[str]] = None,\n image_id: Optional[pulumi.Input[str]] = None,\n metadata: Optional[pulumi.Input[Mapping[str, Any]]] = None,\n name: Optional[pulumi.Input[str]] = None,\n region: Optional[pulumi.Input[str]] = None,\n size: Optional[pulumi.Input[int]] = None,\n snapshot_id: Optional[pulumi.Input[str]] = None,\n source_vol_id: Optional[pulumi.Input[str]] = None,\n volume_type: Optional[pulumi.Input[str]] = None) -> 'VolumeV1':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _VolumeV1State.__new__(_VolumeV1State)\n\n __props__.__dict__[\"attachments\"] = attachments\n __props__.__dict__[\"availability_zone\"] = availability_zone\n __props__.__dict__[\"description\"] = description\n __props__.__dict__[\"image_id\"] = image_id\n __props__.__dict__[\"metadata\"] = metadata\n __props__.__dict__[\"name\"] = name\n __props__.__dict__[\"region\"] = region\n __props__.__dict__[\"size\"] = size\n __props__.__dict__[\"snapshot_id\"] = snapshot_id\n __props__.__dict__[\"source_vol_id\"] = source_vol_id\n __props__.__dict__[\"volume_type\"] = volume_type\n return VolumeV1(resource_name, opts=opts, __props__=__props__)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'ServicePatch':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = ServicePatchArgs.__new__(ServicePatchArgs)\n\n __props__.__dict__[\"api_version\"] = None\n __props__.__dict__[\"kind\"] = None\n __props__.__dict__[\"metadata\"] = None\n __props__.__dict__[\"spec\"] = None\n __props__.__dict__[\"status\"] = None\n return ServicePatch(resource_name, opts=opts, __props__=__props__)", "def get_endpoint_attachment(endpoint_attachment_id: Optional[str] = None,\n location: Optional[str] = None,\n project: Optional[str] = None,\n opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEndpointAttachmentResult:\n __args__ = dict()\n __args__['endpointAttachmentId'] = endpoint_attachment_id\n __args__['location'] = location\n __args__['project'] = project\n opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)\n __ret__ = pulumi.runtime.invoke('google-native:connectors/v1:getEndpointAttachment', __args__, opts=opts, typ=GetEndpointAttachmentResult).value\n\n return AwaitableGetEndpointAttachmentResult(\n create_time=pulumi.get(__ret__, 'create_time'),\n description=pulumi.get(__ret__, 'description'),\n endpoint_ip=pulumi.get(__ret__, 'endpoint_ip'),\n labels=pulumi.get(__ret__, 'labels'),\n name=pulumi.get(__ret__, 'name'),\n service_attachment=pulumi.get(__ret__, 'service_attachment'),\n update_time=pulumi.get(__ret__, 'update_time'))", "def get_service(self, id):\n return self._request('get', path='/services/{}'.format(id), value_only=True)", "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n description: Optional[pulumi.Input[str]] = None,\n force_delete: Optional[pulumi.Input[bool]] = None,\n groups: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n monitor_ids: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]] = None,\n name: Optional[pulumi.Input[str]] = None,\n query: Optional[pulumi.Input[pulumi.InputType['ServiceLevelObjectiveQueryArgs']]] = None,\n tags: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,\n target_threshold: Optional[pulumi.Input[float]] = None,\n thresholds: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ServiceLevelObjectiveThresholdArgs']]]]] = None,\n timeframe: Optional[pulumi.Input[str]] = None,\n type: Optional[pulumi.Input[str]] = None,\n validate: Optional[pulumi.Input[bool]] = None,\n warning_threshold: Optional[pulumi.Input[float]] = None) -> 'ServiceLevelObjective':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = _ServiceLevelObjectiveState.__new__(_ServiceLevelObjectiveState)\n\n __props__.__dict__[\"description\"] = description\n __props__.__dict__[\"force_delete\"] = force_delete\n __props__.__dict__[\"groups\"] = groups\n __props__.__dict__[\"monitor_ids\"] = monitor_ids\n __props__.__dict__[\"name\"] = name\n __props__.__dict__[\"query\"] = query\n __props__.__dict__[\"tags\"] = tags\n __props__.__dict__[\"target_threshold\"] = target_threshold\n __props__.__dict__[\"thresholds\"] = thresholds\n __props__.__dict__[\"timeframe\"] = timeframe\n __props__.__dict__[\"type\"] = type\n __props__.__dict__[\"validate\"] = validate\n __props__.__dict__[\"warning_threshold\"] = warning_threshold\n return ServiceLevelObjective(resource_name, opts=opts, __props__=__props__)", "def get_attachment(session, attachment_id, note, user):\n check_permission(session, PermissionType.READ, user, note)\n attachment = session.query(Attachment).filter_by(id=attachment_id).one()\n\n return attachment" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If true, enable the proxy protocol which is for supplying client TCP/IP address data in TCP connections that traverse proxies on their way to destination servers.
def enable_proxy_protocol(self) -> pulumi.Output[bool]: return pulumi.get(self, "enable_proxy_protocol")
[ "def enable_proxy_protocol(self) -> pulumi.Input[bool]:\n return pulumi.get(self, \"enable_proxy_protocol\")", "def _set_networkProxySetting(self, *args) -> \"bool\" :\n return _core.NetworkPreferences__set_networkProxySetting(self, *args)", "def __setHTTPProxy():\n\n global proxyHandler\n\n if not conf.proxy: \n if conf.hostname in ('localhost', '127.0.0.1') or conf.ignoreProxy:\n proxyHandler = urllib2.ProxyHandler({})\n return\n\n debugMsg = \"setting the HTTP proxy to pass by all HTTP requests\"\n logger.debug(debugMsg)\n\n __proxySplit = urlparse.urlsplit(conf.proxy)\n __hostnamePort = __proxySplit[1].split(\":\")\n\n __scheme = __proxySplit[0]\n __hostname = __hostnamePort[0]\n __port = None\n\n if len(__hostnamePort) == 2:\n try:\n __port = int(__hostnamePort[1])\n except:\n pass #drops into the next check block\n\n if not __scheme or not __hostname or not __port:\n errMsg = \"proxy value must be in format 'http://url:port'\"\n raise sqlmapSyntaxException, errMsg\n\n __proxyString = \"%s:%d\" % (__hostname, __port)\n\n # Workaround for http://bugs.python.org/issue1424152 (urllib/urllib2:\n # HTTPS over (Squid) Proxy fails) as long as HTTP over SSL requests\n # can't be tunneled over an HTTP proxy natively by Python (<= 2.5)\n # urllib2 standard library\n if conf.scheme == \"https\":\n proxyHandler = ProxyHTTPSHandler(__proxyString)\n else:\n proxyHandler = urllib2.ProxyHandler({\"http\": __proxyString})", "def supports_proxy(self):\n return # boolean", "def enable_proxy(proxy_name: str, configuration: Configuration = None):\n return modify_proxy(\n proxy_name=proxy_name, enabled=True, configuration=configuration\n )", "def enable_https_proxy(self, value):\n self._set_property('enable_https_proxy', value)", "def useProxy(self, config, logger=None):\n return self.use_proxy", "def use_system_proxy_setting(self):\n return \"true\" == self.get(\"network\", \"use_system_proxy_settings\", \"true\").lower()", "def set_proxy(proxy: str) -> bool:\n resp = get_config()\n if not resp:\n return False\n data = resp[\"result\"]\n path = resp[\"path\"]\n data[\"proxy\"] = proxy\n with open(path, \"w\") as file:\n json.dump(data, file, sort_keys=True, indent=\"\")\n return True", "def use_client_proxy(request):\n if (\n config.DEPLOYMENT.get(\"proxy\")\n or config.DEPLOYMENT.get(\"disconnected\")\n or config.ENV_DATA.get(\"private_link\")\n ) and config.ENV_DATA.get(\"client_http_proxy\"):\n log.info(f\"Configuring client proxy: {config.ENV_DATA['client_http_proxy']}\")\n os.environ[\"http_proxy\"] = config.ENV_DATA[\"client_http_proxy\"]\n os.environ[\"https_proxy\"] = config.ENV_DATA[\"client_http_proxy\"]", "def useproxyport(self) :\n try :\n return self._useproxyport\n except Exception as e:\n raise e", "def setproxy(self,proxytype=None,addr=None,port=None,rdns=True,username=None,password=None):\r\n self.__proxy = (proxytype,addr,port,rdns,username,password)", "def can_make_proxy():\n return core.dependency_is_installed(\"voms-clients-cpp\") or server_is_installed()", "def modify_proxy(\n proxy_name: str,\n listen_address: str = None,\n upstream_address: str = None,\n enabled: bool = None,\n configuration: Configuration = None,\n):\n json = {}\n if listen_address is not None:\n json[\"listen\"] = listen_address\n if upstream_address is not None:\n json[\"upstream\"] = upstream_address\n if enabled is not None:\n json[\"enabled\"] = enabled\n logger.debug(\"Modifying proxy with the following data: {}\".format(str(json)))\n proxy = toxiproxyapi.modify_proxy(\n proxy_name=proxy_name, proxy_json=json, configuration=configuration\n )\n if not proxy:\n logger.error(\"Unable to modify proxy {}\".format(proxy_name))\n raise AssertionError\n return_port = proxy[\"listen\"].split(\":\")[-1]\n config_key = \"{}_PORT\".format(proxy_name)\n entry = return_port\n configuration[config_key] = entry\n environ[config_key] = entry\n return True", "def enable_https_proxy(self):\n # type: () -> int\n return self._get_property('enable_https_proxy')", "def get_useproxyport(self):\n return self.options['useproxyport']", "def proxy(self):\n if self._proxy is not None:\n if self._proxy[:7] == \"http://\":\n self._proxy = {'http://': self._proxy}\n Color.pl(\"{+} Proxy: %s\" % self._proxy['http://'])\n elif self._proxy[:8] == \"https://\":\n self._proxy = {'https://': self._proxy}\n Color.pl(\"{+} Proxy: %s\" % self._proxy['https://'])\n elif self._proxy[:3] == \"ftp\":\n self._proxy = {'ftp': self._proxy}\n Color.pl(\"{+} Proxy: %s\" % self._proxy['ftp'])\n else:\n self._proxy = \"\"\n return self._proxy", "def send_enable_forwarding(self):\n pass", "def alter_proxy(proxy):\n # Default case where 'proxy' key is not set -- do nothing\n proxy_value = proxy.lower()\n # python-swift client takes into account both\n # upper and lower case proxies so clear them all\n os.environ.pop(\"http_proxy\", None)\n os.environ.pop(\"https_proxy\", None)\n os.environ.pop(\"HTTP_PROXY\", None)\n os.environ.pop(\"HTTPS_PROXY\", None)\n if proxy_value.startswith('http://') or \\\n proxy_value.startswith('https://'):\n LOG.info('Using proxy {0}'.format(proxy_value))\n os.environ['HTTP_PROXY'] = str(proxy_value)\n os.environ['HTTPS_PROXY'] = str(proxy_value)\n else:\n raise Exception('Proxy has unknown scheme')", "def supports_proxy(self):\n # Implemented from template for\n # osid.resource.ResourceProfile.supports_resource_lookup\n return 'supports_proxy' in profile.SUPPORTS" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the first value associated with key in PriorityQueue. Raises KeyError if key is not present.
def __getitem__(self, key): for value, item in self.heap: if item == key: return value raise KeyError(str(key) + " is not in the priority queue")
[ "def get(self, key: str):\r\n\r\n index = self.hash(key)\r\n\r\n if self.array[index] is None:\r\n return None\r\n else:\r\n # Loop through all the key/value pairs at this index, and find if\r\n # our key exists. If it does, return the value.\r\n\r\n for kvp in self.array[index]:\r\n if kvp[0] == key:\r\n return kvp[1]\r\n\r\n return None", "def get_value(self, key: str) -> Any:\r\n if self.get_index(key) is None:\r\n return None\r\n return self.hash_table[self.get_index(key)][1]", "def get_value(self, key):\r\n index = self.horner_hash(key)\r\n j = 0\r\n for i in range(0, self.table_size):\r\n j = (index + i ** 2) % self.table_size\r\n if self.hash_table[j] and self.hash_table[j].key == key:\r\n return self.hash_table[j].value\r\n return None", "def get(self, key):\n hash_ = self._hashing(key)\n for i, item in enumerate(self.hashtable[hash_]):\n if item[0] == key:\n return item[1]\n raise KeyError('Key not in hash table.')", "def get_item(self, key):\n\t\tif not key in self.items: return None\n\t\treturn self.items[ key ]", "def get_item_by_priority(items_dict: dict, keys_by_priority: list) -> Union[str, None]:\n value = None\n for key in keys_by_priority:\n if key in items_dict and items_dict[key] != '':\n value = items_dict[key]\n break\n if value is None:\n foo = 1\n return value", "def __getitem__(self, key):\n hash_val = self._hash(key)\n if self.table[hash_val] != self.defVal and (isinstance(self.table[hash_val], tuple) and \n self.table[hash_val][0] == key and\n self.table[hash_val][2] == True):\n return self.table[hash_val][1]\n else:\n key_found = False\n iter_count = 0\n while not key_found:\n if hash_val >= self.capacity:\n hash_val = 0\n if self.table[hash_val] == self.defVal:\n \tbreak\n if self.table[hash_val][0] == key:\n if self.table[hash_val][2] == True:\n return self.table[hash_val][1]\n hash_val += 1\n iter_count += 1\n return self.defVal", "def get(self, key):\n return next(\n requirement for requirement in self if requirement.key == key\n )", "def get_elem(self, key):\n\n the_hash = self._hash(key)\n\n for index in self._index_gen(the_hash):\n\n # Is this location occupied?\n contents = self.data[index]\n if contents is None:\n\n # This key has not been entered into the hash table\n return None\n\n # There are contents, but do they match the hash and key?\n elif contents[0] == the_hash and contents[1] == key:\n # We found the desired value!\n return contents[2]\n\n print(\"WARNING: We couldn't find the key or an empty spot\")\n return None", "def get(self, k):\n hc = hash(k) % self.M # First place it could be\n entry = self.table[hc]\n while entry:\n if entry.key == k:\n return entry.value\n entry = entry.next\n return None # Couldn't find", "def __getitem__(self, key):\n query = select([self.store.c.value]).where(self.store.c.key == key)\n result = self.conn.execute(query).fetchone()\n if result:\n return result['value']\n raise KeyError", "def get(self):\n\n while self.heap:\n priority, node = heapq.heappop(self.heap)\n if node is not self.REMOVED:\n del self.entry_finder[node]\n self.size -= 1\n return node\n raise KeyError('pop from an empty priority queue')", "def get(self, key):\n #return none if the item isn't in the cache\n if key not in self.items:\n return None\n\n #retrieve the item from the dictionary\n item = self.items[key]\n\n #move it to the front of the list since it is the\n #most recently accessed item\n self._move_to_head(item)\n return item", "def get(self, key):\r\n\t\tstartslot = self.hashfunction(key, len(self.slots))\r\n\t\tdata = None\r\n\t\tstop = False\r\n\t\tfound = False\r\n\t\tposition = startslot\r\n\r\n\t\twhile self.slots[position] != None and not stop and not found:\r\n\t\t\tif self.slots[position] == key:\r\n\t\t\t\tfound = True\r\n\t\t\t\tdata = self.data[position]\r\n\t\t\telse:\r\n\t\t\t\tposition = self.rehash(position,len(self.slots))\r\n\t\t\t\tif position == startslot: #Eventually after several modulo, position would again be equal to startslot\r\n\t\t\t\t\tstop = True #This means no element was found\r\n\t\treturn data", "def top(self):\n try:\n node = self._heap[0]\n except IndexError:\n raise KeyError('pqdict is empty')\n return node.key", "def __getitem__(self, key):\n # BEGIN SOLUTION\n # current version:\n cur = self.root_versions[-1]\n\n # find element\n def find(t, x):\n # if None, so not there, return False\n if not t:\n return False\n # if val equals x, then returns true.\n if t.val == x:\n return True\n # if val is grater then key, then get left.\n if t.val > x:\n return find(t.left, x)\n # if val is less then key, then get right.\n if t.val < x:\n return find(t.right, x)\n\n # result of find\n result = find(cur, key)\n\n if result:\n return key\n else:\n raise KeyError\n\n # END SOLUTION", "def get_element_with_highest_priority(queue):\n\n priority = -1\n while True:\n priority += 1\n for i in range(len(queue)):\n if queue[i]['priority'] == priority:\n return queue.pop(i)", "def __getitem__(self, key):\n # This is a degenerate case of wait_each(). Construct a tuple\n # containing only this 'key'. wait_each() will yield exactly one (key,\n # value) pair. Return just its value.\n for _, value in self.wait_each((key,)):\n return value", "def get(self, key):\n return next(package for package in self if package.key == key)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return tanuki's distance (a positive distance) from an enemy if it is in the same row as tanuki. Return 999 if the current row is free of enemies.
def dist_enemy(row, col): for enemy in self.game.enemy_list: if enemy.gridR == row and enemy.isActive: return abs(col - enemy.gridC) return 999
[ "def distance(board: np.array) -> int:\n total_distance = 0\n boxes_pos = np.argwhere(board == TYPE_LOOKUP['box not on target'])\n targets_pos = np.argwhere(board == TYPE_LOOKUP['box target']).tolist()\n\n for box in boxes_pos:\n distance_from_each_target = []\n for target in targets_pos:\n # Compute Manhattan distance with every empty target\n distance_from_each_target.append(np.sum(abs(box - target)))\n targets_pos.remove(targets_pos[np.argmin(distance_from_each_target)])\n total_distance += np.min(distance_from_each_target)\n\n return total_distance", "def get_dangerous_enemy_distances(self):\n dangerous_enemy_pos_list = [bot.current_pos for bot in self.enemy_bots if bot.is_destroyer]\n\n #Perhaps no enemies are safe to attack. In that case, return None\n if len(dangerous_enemy_pos_list) == 0:\n return None\n else:\n return self.get_distances(dangerous_enemy_pos_list)", "def get_safe_enemy_distances(self):\n safe_enemy_pos_list = [bot.current_pos for bot in self.enemy_bots if not bot.in_own_zone]\n\n #Perhaps no enemies are safe to attack. In that case, return None\n if len(safe_enemy_pos_list) == 0:\n return None\n else:\n return self.get_distances(safe_enemy_pos_list)", "def row_distance(self, row1, row2):\n diffs = [(x - y) ** 2 for x, y in zip(self.data[row1], self.data[row2])\n if (x is not None) and (y is not None)]\n if len(diffs) > 0:\n return sqrt(sum(diffs) / len(diffs))\n else:\n pass", "def get_closest_dangerous_enemy(self):\n dangerous_enemy_dict = self.get_dangerous_enemy_distances()\n if dangerous_enemy_dict:\n return self.get_closest_item(dangerous_enemy_dict)\n else:\n return None", "def get_closest_safe_enemy(self):\n safe_enemy_dict = self.get_safe_enemy_distances()\n if safe_enemy_dict:\n return self.get_closest_item(safe_enemy_dict)\n else:\n return None", "def _manhattan_distance_to_closest_ghost(self, state, row, col):\n\n \treturn self.distances[row][col]", "def closest_dirt(self):\r\n position = self.bot_pos\r\n dirts = self.get_dirts(position[0],position[1])\r\n if dirts:\r\n i, j = min(dirts,\r\n key=lambda dirt_pos:((position[0]-dirt_pos[0])**2+(position[1]-dirt_pos[1])**2)**0.5\r\n )\r\n return (i,j)", "def delta_goal_distance_engineer(row) -> float:\n to_return = None\n # First, perform necessary calculation to arrive at feature value.\n middle_goal_line_point_arr = np.array([100, 50])\n\n starting_point_arr = np.array([row[0].get(\"x\"),\n row[0].get(\"y\")])\n try:\n ending_point_arr = np.array([row[1].get(\"x\"),\n row[1].get(\"y\")])\n except IndexError:\n # If the ending field position of the event was NOT tracked. Upon\n # investigation of the data, this only occurs when a foul is\n # committed which makes sense since the ball cannot advance any\n # further from where it started which is where the foul was\n # committed (there are a handful of cases where an ending point\n # was not specified for a pass, but there are so few that we elect\n # to ignore these cases).\n ending_point_arr = starting_point_arr\n\n starting_goal_dist = np.linalg.norm(\n middle_goal_line_point_arr - starting_point_arr\n )\n ending_goal_dist = np.linalg.norm(\n middle_goal_line_point_arr - ending_point_arr\n )\n\n goal_delta_dist = ending_goal_dist - starting_goal_dist\n\n # Validate and return the result.\n to_return = goal_delta_dist\n\n return to_return", "def distance_to_enemies(env_expanded):\n enemy_pos = [env_expanded._read_mem(mem) for mem in [0x04B0, 0x04B1, 0x04B2, 0x04B3,\n 0x04B4, 0x04B5, 0x04B6, 0x04B7,\n 0x04B8, 0x04B9, 0x04BA, 0x04BB,\n 0x04BC, 0x04BD, 0x04BE, 0x04BF,\n 0x04C0, 0x04C1, 0x04C2, 0x04C3]]\n\n mario_pos = get_mario_pos(env_expanded)\n\n return [enemy_pos[2] - mario_pos[2], enemy_pos[1] - mario_pos[1],\n enemy_pos[6] - mario_pos[2], enemy_pos[5] - mario_pos[1],\n enemy_pos[10] - mario_pos[2], enemy_pos[9] - mario_pos[1],\n enemy_pos[14] - mario_pos[2], enemy_pos[13] - mario_pos[1],\n enemy_pos[18] - mario_pos[2], enemy_pos[17] - mario_pos[1]]", "def get_closest_enemy(self, state):\n distance = float('inf')\n closest_enemy = self.enemy_ids[0]\n\n for enemy_id in self.enemy_ids:\n enemy_distance = self.get_distance_to_agent(enemy_id)\n\n if enemy_distance < distance:\n distance = enemy_distance\n closest_enemy = enemy_id\n\n return closest_enemy", "def manhattan_distance(row0, col0, row1, col1):\n return (abs(row0 - row1)) + (abs(col0 - col1))", "def get_distance(self, train):\n grid_nr = self.get_grid_nr(train)\n if grid_nr == 'error' or 'distance' not in self.points[grid_nr]:\n return 0\n dist = self.points[grid_nr]['distance']\n if 'x' in self.points[grid_nr]:\n x_dist = train['x']-self.points[grid_nr]['x']\n y_dist = train['y']-self.points[grid_nr]['y']\n if self.points[grid_nr]['incoming'] == 0: # top\n y_dist += 30\n elif self.points[grid_nr]['incoming'] == 1: # bottom\n y_dist -= 30\n elif self.points[grid_nr]['incoming'] == 2: # left\n x_dist += 30\n elif self.points[grid_nr]['incoming'] == 3: # right\n x_dist -= 30\n dist += np.sqrt(np.power(x_dist, 2)+np.power(y_dist, 2))/100\n return dist", "def findNearestEnemyUnit(self,unit,target_player=None):\n eu=[]\n for eunit in self.player.game.getUnits():\n if not target_player:\n if eunit.getOwner() != self.player:\n eu.append(eunit)\n else:\n if eunit.getOwner()==target_player:\n eu.append(eunit)\n \n nearest=False\n\n if eu.__len__()==0:\n debug(\"ouch, no units found!\")\n \n for eunit in eu:\n dis=math.sqrt(math.pow((eunit.x-unit.x),2)+math.pow((eunit.y-unit.y),2))\n if nearest:\n if dis < nearest[1]:\n nearest=(eunit,dis)\n else:\n nearest=(eunit,dis)\n \n return nearest", "def death_eval(self, cur_token, enemy_token):\n w = 50\n distance = cur_token.euclidean_distance([cur_token.r, cur_token.q], \n [enemy_token.r, enemy_token.q])\n if distance == 0:\n return w\n return 0", "def euclidean_distance(self):\n\t\treturn math.sqrt(math.pow((self.goal[0]-self.pos.position.x),2) + math.pow((self.goal[1]-self.pos.position.y),2))", "def get_distance(self):\n assert self._distance_from_target != -1, \"Non e' ancora stata settata la distanza dal target\"\n\n return self._distance_from_target", "def manhattan_distance_to(self, x: int, y: int) -> int:\n return abs(self.location[0] - x) + abs(self.location[1] - y)", "def board_distance(game, player):\n center_x = game.width / 2.0\n center_y = game.height / 2.0\n player_x, player_y = game.get_player_location(player)\n dist_x = center_x - player_x\n dist_y = center_y - player_y\n return math.sqrt( math.pow(dist_x, 2) + math.pow(dist_y, 2) )" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method write datatime and scores in file.
def write_scores(filename, scores): curr_scores = read_scores(filename) now_datetime = str(datetime.datetime.now()) res = '{0}\nDate({1}): {2} scores'.format(curr_scores, now_datetime, scores) with open(filename, 'wb') as file: pickle.dump(res, file)
[ "def __writeToFile(self, score):\n with open(self.file, \"w\") as f:\n f.write(str(score))", "def write_score(self):\r\n file = open('scores.txt', 'a')\r\n row = \"{}: {}\\n\".format(self.name, self.score)\r\n file.write(row)", "def write_to_file(self, data):", "def store_to_files(self):\n core_stats = \"{}/core_stats.txt\".format(self.final_path)\n with open(core_stats, 'w') as f:\n for time, cores in izip(self.stats_time, self.num_cores):\n f.write(str(time) + ',' + str(cores) + '\\n')\n\n delay_stats = \"{}/delay_stats.txt\".format(self.final_path)\n with open(delay_stats, 'w') as f:\n for key, value in izip(self.keys, self.values):\n f.write(str(key) + ',' + str(value) + '\\n')", "def write(self, path):\n\n df_to_write = self.data.reset_index()[['tag_number', 'time', 'tag']]\n df_to_write.time = df_to_write.time.dt.strftime(\"%Y/%-m/%-d(%a)\\u3000%H:%M:%S\").str.lower()\n df_to_write.to_csv(path, header=None, index=None, line_terminator='\\n')", "def write_to_file(data:list):\r\n if not isinstance(data, list):\r\n raise TypeError\r\n\r\n with open('score_table.txt', 'w+') as table_file:\r\n table_file.write(str(data))", "def writeToFile(self, filename, dataUnit, timepoint):\n\t\tf = codecs.open(filename, \"wb\", \"latin1\")\n\t\tLogging.info(\"Saving statistics of tracking to file %s\"%filename, kw=\"processing\")\n\t\tw = csv.writer(f, dialect = \"excel\", delimiter = \";\")\n\n\t\theaders = [\"Track #\", \"# of timepoints\", \"Length (micrometers)\", \"Avg. speed (um/sec)\", \"Directional persistence\", \"Avg. angle\", \"Avg. angle std. error\", \"Avg. front speed (um/sec)\", \"Avg. rear speed (um/sec)\"]\n\t\tfor i in range(0, self.globalmax+1):\n\t\t\theaders.append(\"T%d com\"%i)\n\t\t\theaders.append(\"T%d front\"%i)\n\t\t\theaders.append(\"T%d rear\"%i)\n\n\t\tw.writerow(headers)\n\t\tfor i,track in enumerate(self.tracks):\n\t\t\ttps = self.tpCount[i]\n\t\t\tlength = self.lengths[i]\n\t\t\tspeed = self.speeds[i]\n\t\t\tdirection = self.dps[i]\n\t\t\tangle,anglestderr = self.angles[i]\n\t\t\tfrontSpeed = self.frontSpeeds[i]\n\t\t\trearSpeed = self.rearSpeeds[i]\n\t\t\trow = [str(i+1), str(tps), str(length), str(speed), str(direction), str(angle), str(anglestderr), str(frontSpeed), str(rearSpeed)]\n\t\t\t\n\t\t\tmintp, maxtp = track.getTimeRange()\n\t\t\tfor tp in range(0, maxtp + 1):\n\t\t\t\tif tp < mintp:\n\t\t\t\t\trow.append(\"\")\n\t\t\t\t\tcontinue\n\t\t\t\tval, pos = track.getObjectAtTime(tp)\n\t\t\t\tfrontCoord = track.getFrontCoordinatesAtTime(tp)\n\t\t\t\trearCoord = track.getRearCoordinatesAtTime(tp)\n\t\t\t\trow.append(pos)\n\t\t\t\trow.append(frontCoord)\n\t\t\t\trow.append(rearCoord)\n\t\t\tw.writerow(row)\n\n\t\t# Write totals and averages\n\t\tw.writerow([\"Totals\"])\n\t\tw.writerow([\"# of tracks\", \"Avg. timepoints\", \"Avg. length (micrometers)\", \"Avg. length std. error\", \"Avg. speed (um/sec)\", \"Avg. speed std. error\", \"Avg. directional persistence\", \"Avg. directional persistence std. error\", \"Avg. angle\", \"Avg. angle std. error\", \"Avg. front speed (um/sec)\", \"Avg. front speed std. error\", \"Avg. rear speed (um/sec)\", \"Avg. rear speed std. error\"])\n\t\tw.writerow([len(self.tracks), self.avgTpCount, self.avglen[0], self.avglen[2], self.avgspeed[0], self.avgspeed[2], self.avgdps[0], self.avgdps[2], self.avgang[0], self.avgang[2], self.avgFrontSpeeds[0], self.avgFrontSpeeds[2], self.avgRearSpeeds[0], self.avgRearSpeeds[2]])", "def update_scores(self) -> None:\n with open('highscores.txt', 'w') as f:\n for user, points in self.scores:\n f.write(f'{user},{points}\\n')", "def write_to_file(self):\n\n filename = self.entries[0].timestamp + \" workout log.txt\"\n with open(filename, mode=\"w\") as file:\n file.write(str(self) + \"\\n\")", "def write_score(score, name, scores, filename, sep=','):\n if score == '' or name == '' or sep in name:\n raise WriteError('Either the score({}) or name({}) was blank, or the file seperator ({}) was in the name.'.format(score, name, sep))\n score_tuple = (score,name)\n scores.append(score_tuple)\n with open(filename,'w') as f:\n for s in scores:\n f.write(sep.join(map(str, s)) + '\\n')", "def write_game_scores(self):\n for game_scores_dict in self._data:\n try:\n sql = \"\"\"INSERT INTO GOG_SCRAPPER_DB.game_scores\n (title_sku, \n score_quote_datetime,\n score)\n VALUES(%s,%s,%s) \n \"\"\"\n val = (game_scores_dict[config.KEYNAME_GAME_SKU],\n datetime.now().strftime(config.DATETIME_FORMAT),\n game_scores_dict[config.KEYNAME_GAME_SCORE]\n )\n self.cursor.execute(\"SET SESSION MAX_EXECUTION_TIME=9999\")\n self.cursor.execute(sql, val)\n except Exception:\n pass", "def Write2File(fileNum, data, time, chNum):\n f = open(\"Data%s.txt\" % fileNum, 'w+')\n for row in range(len(data) / chNum):\n for col in range(chNum):\n # f.write(\"%i %f \" % (data[row*chNum + col], time[row*chNum + col]))s\n f.write(\"%s \" % (data[row * chNum + col]))\n f.write(\"\\n\")\n f.close()", "def Write2File(self):\n\n\t\tif self.data:\n\t\t\theader = ['filename', 'date', 'uncertainty', 'mean_offset_wrt_refpts', \\\n\t\t\t 'trimmed_N', 'trimming_lb', 'trimming_up', 'refpts_file']\n\t\t\twith open(self.fpath, 'wb') as csvfile:\n\t\t\t\tcsvwriter = csv.writer(csvfile, delimiter=',')\n\t\t\t\tcsvwriter.writerow(header)\n\t\t\t\tfor row in self.data:\n\t\t\t\t\tcsvwriter.writerow(row)", "def write_counters_to_file(self):\n with open(os.path.join(self.cwd,'data/others/counters.txt'),'w') as outputfile:\n json.dump(CounterValues().last_counter,outputfile)\n return True \n return False", "def export():\n\n now = datetime.datetime.now()\n with open(\"Statistik_BlackJack.txt\", \"a\") as open_file:\n open_file.write(\"\\n\\nDatum und Zeit: \" + str(now.strftime(\"%d.%m.%Y %H:%M:%S\"))\n + \"\\nPlayer: \" + str(statistik.stat_player)\n + \"\\nDealer: \" + str(statistik.stat_dealer)\n + \"\\nUnentschieden: \" + str(statistik.stat_unentschieden))", "def write_tweets(self, path):\n with open(path, 'w') as f:\n for t in self.good:\n f.write(t + \"0\\n\")\n\n for t in self.bad:\n f.write(t + \"1\\n\")", "def printWithTime(data):\n\tprint (\"%s-->%s\" %(time.asctime(), data))\n\twriteToFile(data)", "def __add_time_stamp_to_file(self, file_path):\n f = open(file_path, \"a+\")\n f.write(\"\\n\"+\"#\"*80+\"\\n\")\n f.write(\" \"*30+self.__time_stamp(\":\")+\" \"*30)\n f.write(\"\\n\"+\"#\"*80+\"\\n\")\n f.close()", "def save(self, path):\n\n if len(self.voltage_data.shape) > 1:\n # two channel interleaved\n data_unleaved = np.array([self.voltage_data[0::2], self.voltage_data[1::2]]).transpose()\n # datetime stamp experiment here\n self.set_timestamp()\n np.savetxt(path,\n data_unleaved, fmt='%.11f', delimiter=',',\n header=self.get_header()) \n else:\n # datetime stamp experiment here\n self.set_timestamp()\n np.savetxt(path,\n self.voltage_data, fmt='%.11f', delimiter=',',\n header=self.get_header())" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get ball coordinates and x, y movement distinctions and calculated if ball hits the board returns True and if ball doesn't hit the board returns False.
def is_ball_hits_board(self, ball_coord, delta_x, delta_y): ball_x = delta_x + ball_coord[0] ball_y = delta_y + ball_coord[1] ball_r = ball_coord[2] x1 = self.board.get_rect().left - ball_x x2 = self.board.get_rect().right - ball_x y1 = self.board.get_rect().top - ball_y y2 = self.board.get_rect().top - ball_y dx = float(x2 - x1) dy = float(y2 - y1) dr = math.sqrt(dx ** 2 + dy ** 2) D = float(x1 * y2 - x2 * y1) discriminant = (ball_r ** 2) * (dr ** 2) - D ** 2 if discriminant < 0: return False x_intersect_1 = (((D * dy) - dx * sgn(dy) * math.sqrt(discriminant)) / dr ** 2) x_intersect_2 = (((D * dy) + dx * sgn(dy) * math.sqrt(discriminant)) / dr ** 2) if ((x1 <= x_intersect_1 and x_intersect_1 <= x2) or (x1 <= x_intersect_2 and x_intersect_2 <= x2)): return True else: return False
[ "def has_ball_moved(self, ball_1, ball_2):\r\n dist = dist_between_two_balls(ball_1, ball_2)\r\n if not self.white_is_moving:\r\n if dist > 0.1:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False", "def checkHitBall(ball, pad1, pad2, ballDirX):\r\n if ballDirX == -1 and pad1.right >= ball.left and pad1.top <= ball.top and pad1.bottom >= ball.bottom:\r\n return -1\r\n # ballDir = 1 -> pad2 may hit the ball\r\n # ball is hit when pad1.left == ball.right\r\n elif ballDirX == 1 and pad2.left <= ball.right and pad2.top <= ball.top and pad2.bottom >= ball.bottom:\r\n return -1\r\n else:\r\n return 1", "def collides(self, paddle: Paddle) -> bool:\n x_ball = self.xcor()\n if abs(x_ball - paddle.xcor()) < 12:\n y_ball = self.ycor()\n if y_ball < paddle.top and y_ball > paddle.bottom:\n if x_ball < 0 and x_ball >= paddle.xcor():\n return True\n elif x_ball > 0 and x_ball <= paddle.xcor():\n return True\n return False", "def step_ball(self):\n s = self.s\n\n if s[S.BALL_VX] > 0.:\n tt_x = (c.RIGHT - s[S.BALL_X]) / s[S.BALL_VX]\n elif s[S.BALL_VX] < 0.:\n tt_x = (c.LEFT - s[S.BALL_X]) / s[S.BALL_VX]\n else:\n tt_x = np.inf\n \n if s[S.BALL_VY] > 0.:\n tt_y = (c.TOP - s[S.BALL_Y]) / s[S.BALL_VY]\n elif s[S.BALL_VY] < 0.:\n tt_y = (c.BOTTOM - s[S.BALL_Y]) / s[S.BALL_VY]\n else:\n tt_y = np.inf\n\n if (tt_x > 1.) and (tt_y > 1.): # no collision\n self.advance_ball(1.)\n\n elif tt_x <= tt_y <= 1.: # collision on X then on Y\n self.advance_ball(tt_x)\n self.hit_x()\n self.advance_ball(tt_y - tt_x)\n self.hit_y()\n self.advance_ball(1. - tt_y)\n\n elif tt_y < tt_x <= 1.: # collision on Y then on X\n self.advance_ball(tt_y)\n self.hit_y()\n self.advance_ball(tt_x - tt_y)\n self.hit_x()\n self.advance_ball(1. - tt_x)\n\n elif tt_x <= 1.: # collision on X\n self.advance_ball(tt_x)\n self.hit_x()\n self.advance_ball(1. - tt_x)\n\n elif tt_y <= 1.: # collision on Y\n self.advance_ball(tt_y)\n self.hit_y()\n self.advance_ball(1. - tt_y)\n\n else: # ???\n raise RuntimeError(\"Weird\")", "def ballInGoal(self, ball):\n goalState = False\n #if the ball is horrizontally in the hoop\n if ball.pos[0] >= self.pos[0] and ball.pos[0]+ball.surface.get_width() <= self.pos[0]+self.surface.get_width() and ball.visible:\n\n #if the top of the ball is below the top surface and above the bottom surface of the goal\n if ball.pos[1] >= self .pos[0] and ball.pos[1] <= self.surface.get_height()+self.pos[1]:\n ballState = True\n print(\"goal\")\n #if the top of the ball is above the top surface and the bottom surface of the ball is below the bottom surface of the goal\n elif ball.pos[1] <= self .pos[0] and ball.pos[1]+ball.surface.get_height() >= self.surface.get_height()+self.pos[1]:\n ballState = True\n print(\"goal\")\n #if the bottom of the ball is below the top surface and above the bottom surface of the goal\n elif ball.pos[1]+ball.surface.get_height() >= self .pos[0] and ball.pos[1]+ball.surface.get_height() <= self.surface.get_height()+self.pos[1]:\n ballState = True\n print(\"goal\")\n else:\n ballState = False\n else:\n ballState = False", "def ball_collisions(self):\n up_l_corner = self.window.get_object_at(self.ball.x, self.ball.y)\n up_r_corner = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y)\n down_l_corner = self.window.get_object_at(self.ball.x, self.ball.y + self.ball.height)\n down_r_corner = self.window.get_object_at(self.ball.x + self.ball.width, self.ball.y + self.ball.height)\n\n # The situation that the ball hits the paddle.\n if down_l_corner == self.paddle:\n self.__dy = self.reverse_dy\n elif down_r_corner == self.paddle:\n self.__dy = self.reverse_dy\n\n # The situation that the ball hits bricks and remove them.\n if up_l_corner is not None and up_l_corner is not self.paddle and up_l_corner is not self.__board:\n self.__dy = -self.__dy\n self.window.remove(up_l_corner)\n self.__count -= 1\n self.__score += 1\n self.__board.text = 'Score: ' + str(self.__score)\n elif up_r_corner is not None and up_r_corner is not self.paddle and up_r_corner is not self.__board:\n self.__dy = -self.__dy\n self.window.remove(up_r_corner)\n self.__count -= 1\n self.__score += 1\n self.__board.text = 'Score: ' + str(self.__score)\n elif down_l_corner is not None and down_l_corner is not self.paddle and down_l_corner is not self.__board:\n self.__dy = -self.__dy\n self.window.remove(down_l_corner)\n self.__count -= 1\n self.__score += 1\n self.__board.text = 'Score: ' + str(self.__score)\n elif down_r_corner is not None and down_r_corner is not self.paddle and down_r_corner is not self.__board:\n self.__dy = -self.__dy\n self.window.remove(down_r_corner)\n self.__count -= 1\n self.__score += 1\n self.__board.text = 'Score: ' + str(self.__score)", "def collide(self):\n ball_y, ball_x = self.ball\n y1, y2, y3 = range(self.racquet_1[1], self.racquet_1[1] + self.pl_size)\n z1, z2, z3 = range(self.racquet_2[1], self.racquet_2[1] + self.pl_size)\n if ball_x == 1:\n if ball_y == y1:\n self.ball_dir = 0\n return 1\n elif ball_y == y2:\n self.ball_dir = 4\n return 1\n elif ball_y == y3:\n self.ball_dir = 1\n return 1\n else:\n return -10\n\n elif ball_x == self.matrix_size[1] - 2:\n if ball_y == z1:\n self.ball_dir = 2\n elif ball_y == z2:\n self.ball_dir = 5\n elif ball_y == z3:\n self.ball_dir = 3\n\n return 0", "def playerHitsBall(self):\n ball_mass = 20\n player_mass = 20\n\n collision_dist = math.sqrt((self.player.center[0] - self.ball_center[0])**2+\n (self.player.center[1] - self.ball_center[1])**2)\n\n #correct ball position if it overlaps with player\n if collision_dist < self.player_size+self.ball_size:\n #print \"collision dist = \"+str(collision_dist)\n #print \"correct dist = \"+str(self.player_size+self.ball_size)\n vector_multiplier = collision_dist/float(self.player_size+self.ball_size)\n #print \"vector multiplier = \"+str(vector_multiplier)\n if self.ball_center[1] > self.player.center[1]:\n #upper left quadrant\n if self.ball_center[0] < self.player.center[0]:\n \"\"\"\n print \"upper left\"\n print \"ball center x = \"+str(self.ball_center[0])\n print \"ball center x = \"+str(self.ball_center[1])\n \"\"\"\n self.ball_center[0] -= vector_multiplier * abs(self.player.center[0] - self.ball_center[0])\n self.ball_center[1] -= vector_multiplier * abs(self.player.center[1] - self.ball_center[1])\n \"\"\"\n print self.ball_center[0]\n print self.ball_center[1]\n \"\"\"\n #lower left quadrant\n else:\n \"\"\"\n print \"lower right\"\n print \"ball center x = \"+str(self.ball_center[0])\n print \"ball center x = \"+str(self.ball_center[1])\n \"\"\"\n self.ball_center[0] -= vector_multiplier * abs(self.player.center[0] - self.ball_center[0])\n self.ball_center[1] += vector_multiplier * abs(self.player.center[1] - self.ball_center[1])\n \"\"\"\n print self.ball_center[0]\n print self.ball_center[1]\n print \"final collision distance = \"+str(math.sqrt((self.player.center[0] - self.ball_center[0])**2+\n (self.player.center[1] - self.ball_center[1])**2))\n print \"correct collision distance = \"+str(self.player_size+self.ball_size)\n \"\"\"\n print self.dx\n print self.dy\n print \"end start\"\n collision_dist = math.sqrt((self.player.center[0] - self.ball_center[0])**2+\n (self.player.center[1] - self.ball_center[1])**2)\n n_x = (self.player.center[0] - self.ball_center[0]) / float(collision_dist)\n n_y = (self.player.center[1] - self.ball_center[1]) / float(collision_dist)\n p = 2 * (self.dx * n_x + self.dy * n_y) / (ball_mass + player_mass)\n #print self.dx\n #print self.dy\n self.dx = self.dx - p * ball_mass * n_x - p * player_mass * n_x\n self.dy = self.dy - p * ball_mass * n_y - p * player_mass * n_y\n #print self.dx\n #print self.dy\n\n #set player dy to zero\n self.player.player_dy = 0\n print \"ball vx = \"+str(self.dx)\n print \"ball vy = \"+str(self.dy)\n print \"ball velocity = \"+str(math.sqrt(self.dx**2+self.dy**2))", "def _check_collision(self, state):\n point = state[0:2]\n\n if len(self._obstacles) == 0:\n return False\n\n for i in range(len(self._obstacles)):\n obstacle = self._obstacles[i]\n center = obstacle[0:2]\n radius = obstacle[2]\n if np.linalg.norm(center-point) < radius:\n return True\n\n return False", "def paddle_interact(self):\n\n min_x, paddle_top, max_x, _ = self._model.get_paddle_box()\n\n ball_xs, ball_ys = self._model.get_ball_speed()\n ball_x, ball_y = self._model.get_ball_position()\n\n x1, y1 = ball_x + ball_xs, ball_y + ball_ys\n\n if y1 + self._radius <= paddle_top: # still in play above paddle\n return False\n\n if x1 + self._radius < min_x or x1 - self._radius > max_x: # sewer ball\n self._model.exit_ball()\n return False\n\n # ball still in play above paddle\n # will the ball also hit the wall at the same time?\n xs_sign, ys_sign = sign(ball_xs), sign(ball_ys)\n\n # the cell containing the ball centre\n r, c = self._grid_info.pos2rc(ball_x, ball_y)\n\n # If block exists in the adjacent column, ball will collide with wall\n if self._model.is_block_at((r, c + xs_sign)):\n p_x = ball_x + xs_sign * self._radius\n p_y = ball_y - ys_sign * self._radius\n p_xt, _ = self.times_to_cell_boundary(p_x, p_y, ball_xs, ball_ys,\n self._grid_info.rc2rect(r, c))\n\n if p_xt <= 1: # next to wall so bounce off wall and paddle\n ty = (paddle_top - (ball_y + self._radius)) / ball_ys\n self.do_reflect(p_xt, -1, ty, -1)\n\n return True\n\n # at this point the ball bounces off paddle and paddle not near wall\n self.do_paddle_reflect()\n\n return True", "def ball_in_area(self):\n ball_in_y = self.ball.y < self.window.height - self.ball.height\n return ball_in_y", "def check_walls(self, aim):\n k = 100\n points = []\n dy = (aim.y - self.y) / k\n dx = (aim.x - self.x) / k\n for i in range(k):\n points.append([self.x + math.ceil(i * dx), self.y + math.ceil(i * dy)])\n for i in self.cells:\n for j in i:\n for k in points:\n if (k[0] - j[0] > 0) and (k[0] - j[0] < self.cell_size) and (k[1] - j[1] > 0) and (\n k[1] - j[1] < self.cell_size):\n if j[2] == -1:\n return 1\n return 0", "def check_border_screen(screen, ball, player_1, player_2):\r\n # check collision between 1st player and ball at left and right side\r\n collision_with_p1 = pygame.sprite.collide_rect(player_1, ball)\r\n # check collision between 2st player and ball at left and right side\r\n collision_with_p2 = pygame.sprite.collide_rect(player_2, ball)\r\n\r\n screen_rect = screen.get_rect()\r\n # Bottom ball and screen border bottom\r\n if ball.rect.bottom == screen_rect.bottom:\r\n ball.directionY *= -1\r\n # Top ball and screen border top\r\n elif ball.rect.top == screen_rect.top:\r\n ball.directionY *= -1\r\n # Sprite ball and sprite player 1\r\n elif collision_with_p1:\r\n ball.directionX *= -1\r\n # Sprite ball and sprite player 2\r\n elif collision_with_p2:\r\n ball.directionX *= -1\r\n # Bottom ball and top player 1\r\n elif (ball.rect.bottom == player_1.rect.top and\r\n ball.rect.x == player_1.rect.x):\r\n ball.directionX *= -1\r\n # Top ball and bottom player 1\r\n elif (ball.rect.top == player_1.rect.bottom and\r\n ball.rect.x == player_1.rect.x):\r\n ball.directionX *= -1\r\n # Top ball and bottom player 2\r\n elif (ball.rect.top == player_2.rect.bottom and\r\n ball.rect.x == player_2.rect.x):\r\n ball.directionX *= -1\r\n # Bottom ball and top player 1\r\n elif (ball.rect.bottom == player_2.rect.top and\r\n ball.rect.x == player_2.rect.x):\r\n ball.directionX *= -1", "def ball_at_start(self):\n return self.ball.x == (self.window.width-self.ball.width)/2 and\\\n self.ball.y == (self.window.height-self.ball.height)/2", "def detect_collisions(balls):\n n_balls = len(balls)\n world_min_x = -200.0*n_balls**.5 # minimum x in world coordinates\n world_max_x = +200.0*n_balls**.5 # maximum x in world coordinates\n world_min_y = -200.0*n_balls**.5 # minimum y in world coordinates\n world_max_y = +200.0*n_balls**.5 # maximum y in world coordinates\n set_of_collisions = set()\n\n set_of_collisions_2 = set()\n\n# for i in range(len(balls)):\n# b1 = balls[i]\n# for j in range(i):\n# b2 = balls[j]\n# if gas.colliding(b1, b2):\n# set_of_collisions_2.add(gas.ball_pair(b1, b2))\n\n cloumn_num = int(math.ceil(400 * n_balls**.5 / 256))\n squared_list = [[] for x in range(cloumn_num) for y in range(cloumn_num)]\n total_num = cloumn_num * cloumn_num\n for i in range(n_balls):\n x_pos = int(math.floor((balls[i].x - world_min_x) / 256))\n y_pos = int(math.floor((balls[i].y - world_min_y) / 256))\n squared_list[x_pos * cloumn_num + y_pos].append(balls[i])\n\n for i in range(len(squared_list)):\n for j in range(len(squared_list[i])):\n b1 = squared_list[i][j]\n for k in range(j):\n b2 = squared_list[i][k]\n if gas.colliding(b1, b2):\n set_of_collisions.add(gas.ball_pair(b1, b2))\n # if(i >= cloumn_num):\n # list_collisions(squared_list[i], squared_list[i - cloumn_num],set_of_collisions)\n if(i < total_num - cloumn_num):\n list_collisions(squared_list[i], squared_list[i + cloumn_num],set_of_collisions)\n # if i % cloumn_num > 0:\n # list_collisions(squared_list[i], squared_list[i - 1],set_of_collisions)\n if i % cloumn_num < cloumn_num - 1:\n list_collisions(squared_list[i], squared_list[i + 1],set_of_collisions)\n\n if i < total_num - cloumn_num and i % cloumn_num > 0:\n list_collisions(squared_list[i], squared_list[i + cloumn_num - 1],set_of_collisions)\n\n if i < total_num - cloumn_num and i % cloumn_num < cloumn_num - 1:\n list_collisions(squared_list[i], squared_list[i + cloumn_num + 1],set_of_collisions)\n\n\n #print \"set_of_collisions_2 \", len(set_of_collisions_2)\n #print \"set_of_collisions \", len(set_of_collisions)\n return set_of_collisions", "def has_ball_stopped(self, ball_1, ball_2):\r\n dist = dist_between_two_balls(ball_1, ball_2)\r\n if self.white_is_moving:\r\n if dist <= 0.1:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False", "def has_move(self, x, y):\n origin = x, y\n return any(self.get_color(x, y) == EMPTY for x, y in self.edge_neighbours(origin))", "def GENmoving(ballObj):\n if ballObj.velocity == vector(0,0,0):\n return False\n else:\n return True", "def do_they_collide(ball1, ball2):\n\tif point_distance(ball1._x, ball2._x, ball1._y, ball2._y) < (ball1._radius + ball2._radius):\n\t\treturn True\n\telse:\n\t\treturn False" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a pd.DataFrame (nb_paths X nb_tosses), where p is the probability of getting a head.
def df_coinflip(nb_tosses, nb_paths, p=0.5): samples = np.random.rand(nb_paths, nb_tosses) col_idx = list(range(1+nb_tosses)) tosses = pd.DataFrame(np.where(samples<p, 1, 0), columns=col_idx[1:]) tosses[0] = 0 tosses = tosses[col_idx] cum_tosses = tosses.cumsum(axis=1) return cum_tosses
[ "def num_of_lattice_paths(length):\n numerator = math.factorial(length + length)\n denominator = math.factorial(length) * math.factorial(length)\n \n return numerator/denominator", "def path_length(self, X:np.ndarray) -> np.ndarray:\n nd_X = []\n for x_i in X:\n x_i_path_len = []\n for itree in self.trees:\n x_i_path_len.append(self.path(x_i, itree.root))\n nd_X.append(np.mean(x_i_path_len))\n return np.array(nd_X).reshape(len(X), 1)", "def number_of_triples(endpoint):\n return ask(endpoint, \"SELECT (COUNT(*) AS ?n) WHERE {?s ?p ?o}\")", "def table(freq_dist, columns=[\"n-gram\", \"count\"], n=20):\n items = [x for x in freq_dist.items()] if hasattr(freq_dist, \"items\") else freq_dist\n x, y = columns\n df = pd.DataFrame(items, columns=columns)\n return df.sort_values(y, ascending=False)[0:n]", "def distances_from_root(df):\n g = skeleton_df_to_nx(df, directed=False, with_distances=True, virtual_roots=True, root_dist=0.0)\n d = nx.shortest_path_length(g, -1, weight='distance')\n d = pd.Series(d, name='distance').rename_axis('rowId')\n df = df.merge(d, 'left', on='rowId')\n return df", "def pdframe_kmers(seq):\r\n K_obs = []\r\n for kmers_obs in range(1,len(seq)+1):\r\n kmers_obs_dct = {}\r\n all_kmers = len(seq) - kmers_obs + 1\r\n for x in range(all_kmers):\r\n kmers = seq[x:x+kmers_obs]\r\n if kmers not in kmers_obs_dct:\r\n kmers_obs_dct [kmers] = 0\r\n kmers_obs_dct[kmers] += 1\r\n k_obs.append(len(kmers_obs_dct))\r\n\r\n K_pos = []\r\n for w in range(1,len(seq)+1):\r\n if (len(seq) - w + 1) > (4**w):\r\n k_pos.append(4**w)\r\n else:\r\n k_pss.append(len(seq) - w + 1)\r\n k = list(range(1,len(seq)+1))\r\n K_pos_dct = {'k':k, 'k_observed':k_obs, 'k_possible':K_pos}\r\n return pdframe_kmers\r\n\r\n import pandas as pd\r\n pdframe_kmers = pd.DataFrame(obs_poss_dct, columns = ['k','kmers_obs', 'kmers_poss'])\r\n return pdframe_kmers", "def create_dataframe(rep, p_s, k_erreurs):\n df = pd.DataFrame();\n \n frames = [];\n for p in p_s:\n rep_dist = rep + \"/\"+ DATA_P_REP + str(p) + \"/\" + \"distribution\" +\"/\"\n df_p = fct_aux_viz.create_dataframe_data_revue(\n rep_dist, k_erreurs,\n DISTRIB_ROOT_FILE,\n DISTRIB_EXT_FILE, \n NAMES_HEADERS)\n df_p = df_p.groupby(\"num_graph\").mean();\n df_p[\"p\"] = p;\n frames.append(df_p);\n \n df = pd.concat(frames, axis = 0, ignore_index=True);\n dico_rename = {\"dc\":\"moy_dc\", \"dh\":\"moy_dh\"};\n df.rename(columns = dico_rename, inplace = True);\n \n return df;", "def get_dep_count_df(data):\n characteristics = data.get_dataframe('characteristics')\n\n # Format dep\n # Remove 0 at the end of dep number if the dep number is not DOM-TOM\n characteristics['dep'] = characteristics.apply(lambda x: x.dep//10 if x.dep<971 else x.dep, axis=1)\n # Add 0 in front of dep number if dep number is lower than 10\n characteristics['dep'] = characteristics.apply(lambda x: '0'+str(x.dep) if x.dep<10 else str(x.dep), axis=1)\n\n # Count values per dep\n dep_count = pd.DataFrame(characteristics['dep'].value_counts())\n dep_count.reset_index(level=0, inplace=True)\n dep_count.rename(columns={'index':'dep',\n 'dep':'count'},\n inplace=True)\n return dep_count", "def depth(self) -> pd.DataFrame:\n return self._load_fetch(self.DEPTH)", "def path_length(self, X:np.ndarray) -> np.ndarray:\n numX, numQ = X.shape\n avg_path_length_list = []\n for i in range(numX):\n obs = X[i, :]\n path_length_list = []\n for t in self.trees:\n current_path_length = 0\n path_length_list.append(\n self.onePathLength(obs, t, current_path_length))\n avg_path_length_list.append([np.mean(path_length_list)])\n return np.array(avg_path_length_list)", "def get_links_table(self):\n\n link_ids = []\n link_lengths = []\n link_lanes = []\n link_start = []\n link_end = []\n link_is_source = []\n link_is_sink = []\n # link_capacity = []\n # link_ffspeed = []\n # link_jamdensity = []\n # link_travel_time = []\n for link_id in self.otm.scenario().link_ids():\n link = self.otm.scenario().get_link(link_id)\n link_ids.append(link_id)\n link_lengths.append(link.get_full_length())\n link_lanes.append(link.get_full_lanes())\n link_start.append(link.get_start_node_id())\n link_end.append(link.get_end_node_id())\n link_is_source.append(link.get_is_source())\n link_is_sink.append(link.get_is_sink())\n # link_capacity.append(link.get_capacity_vphpl())\n # link_ffspeed.append(link.get_ffspeed_kph())\n # link_jamdensity.append(link.get_jam_density_vpkpl())\n # link_travel_time.append(link.get_full_length() * 3.6 / link.get_ffspeed_kph())\n\n return pd.DataFrame(data={'id': link_ids,'length_meter': link_lengths,'lanes': link_lanes,'start_node': link_start,'end_node': link_end,'is_source': link_is_source,'is_sink': link_is_sink}) #,'capacity_vphpl': link_capacity,'speed_kph': link_ffspeed,'max_vpl': link_jamdensity,'travel_time_sec': link_travel_time})", "def number_of_triples(endpoint):\n return int(next(ask(endpoint, \"SELECT (COUNT(*) AS ?n) WHERE {?s ?p ?o}\"))[0])", "def path_length(self):\n return np.sum([path.path_length for path in self.paths])", "def df_head(self):\n return self.features.raw_data()[self.features.features()].head().T", "def get_gap_table(lines: List[Line]) -> pd.DataFrame:\n records = {}\n for line in lines:\n for gap in line.gaps:\n records[(line.id_, gap.id_)] = gap.as_dict(line)\n\n gaps_df = pd.DataFrame.from_dict(records, \"index\")\n\n if not gaps_df.empty:\n gaps_df.index.names = [\"line_id\", \"gap_id\"]\n\n return gaps_df", "def get_num_cycles(data: pd.DataFrame):\n raise NotImplementedError(data)", "def num_sessions(cur):\n cur.execute(\"CREATE TEMPORARY TABLE constant_therapy.tmp_patientid SELECT DISTINCT patient_id FROM constant_therapy.sessions WHERE patient_id > 1000 AND patient_id NOT IN (SELECT DISTINCT patient_id FROM constant_therapy.sessions WHERE type = 'ASSISTED');\")\n sleep(.5)\n cur.execute(\"SELECT patient_id, COUNT(distinct id) AS num_sessions FROM constant_therapy.sessions WHERE patient_id IN (SELECT * FROM tmp_patientid) GROUP BY patient_id;\")\n result = cur.fetchall()\n r = pd.DataFrame(result, columns=['patient_id', 'num_sessions'])\n return r", "def make_calling_times_df(service: dict) -> pd.DataFrame:\n # Initiate the dataframe\n df_calling_points = pd.DataFrame(columns=[\"Calling_At\", \"Time\", \"Status\"])\n\n # Get all the information\n df_calling_points[\"Calling_At\"] = TrainInformation.calling_points(\n service, \"subsequentCallingPoints\"\n )\n df_calling_points[\"Time\"] = TrainInformation.calling_times(\n service, \"subsequentCallingPoints\"\n )\n df_calling_points[\"Status\"] = TrainInformation.calling_status(\n service, \"subsequentCallingPoints\"\n )\n\n return df_calling_points", "def sample_path_lengths(G, nodes=None, trials=1000):\n if nodes is None:\n nodes = list(G)\n else:\n nodes = list(nodes)\n\n pairs = np.random.choice(nodes, (trials, 2))\n lengths = [nx.shortest_path_length(G, *pair)\n for pair in pairs]\n\n return lengths" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Corresponds to the gate information for an AND gate.
def AND(): return {(0, 0): 0, (0, 1): 0, (1, 0): 0, (1, 1): 1}
[ "def instruction_AND(self, inst):\n\t\tsrc1 = self.getOperandOneWord(inst)\n\t\tsrc2 = self.getOperandTwoWord(inst)\n\t\tself.setDestinationWord(inst, src1 & src2)", "def enterLogicalExpressionAnd(self, ctx: RulesParser.LogicalExpressionAndContext):\n\n self.context.operator = LogicalOperator.AND\n self.context.left = ExpressionNode()\n self.context.left.parent = self.context\n self.context = self.context.left", "def __and__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseAnd, self, other)", "def bitwise_and_(self, e):\n return self.__lazy_operate(operator.and_, e)", "def bit_and(self, where: ir.BooleanValue | None = None) -> IntegerScalar:\n return ops.BitAnd(self, where).to_expr()", "def logical_and(self):\n\n expr = self.equality()\n while self.match(TokenType.AND):\n operator = self.previous()\n right = self.equality()\n expr = Logical(expr, operator, right)\n return expr", "def __and__(expr):", "def AND(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __and__(self, other):\n\n try:\n retval = ComposedAccessControl(self, other, logic='and')\n except TypeError:\n raise TypeError(\n f\"unsupported operand type(s) for &: '{type(self).__name__}' \"\n f\"and '{type(other).__name__}'\"\n )\n return retval", "def bool_and(self, truth_series_pair: List[Value]) -> ValueWithPlan:\n plans: List[str] = []\n truth_series_pair_values: List[Series] = []\n for i, value in enumerate(truth_series_pair):\n truth_series_pair_values.append(value.get_value())\n plans.append(value.get_plan_representation())\n\n return ValueWithPlan(\n truth_series_pair_values[0] & truth_series_pair_values[1],\n f\"{plans[0]} & {plans[1]}\",\n )", "def test_and(self):\n crit_0 = qml.BooleanFn(lambda x: x > 4)\n crit_1 = qml.BooleanFn(lambda x: x < 9)\n crit = crit_0 & crit_1\n assert not crit(-2)\n assert crit(6)\n assert not crit(10)", "def __and__(cond):", "def bitwise_and(src1, src2, dst=..., mask=...) -> dst:\n ...", "def AND(X:cpuByte,Y:cpuByte) -> cpuByte:\r\n returnable:cpuByte=cpuByte()\r\n for position in range(cpuByte._size):\r\n returnable._state[position] = X._state[position] & Y._state[position]\r\n return returnable", "def and_(*elements: QueryDictBool) -> QueryExpression:\n return QueryExpression({\"$and\": elements})", "def and_(*predicates: ir.BooleanValue) -> ir.BooleanValue:\n if not predicates:\n return literal(True)\n return functools.reduce(operator.and_, predicates)", "def test_and() -> None:\n v8 = TestValue(\"A\", IntType.u(8))\n v16 = TestValue(\"B\", IntType.u(16))\n litval = 0x1234\n lit = IntLiteral(litval)\n assert AndOperator(v8, v8).mask == 0xFF\n assert AndOperator(v16, v16).mask == 0xFFFF\n assert AndOperator(lit, lit).mask == litval\n assert AndOperator(v8, v16).mask == 0xFF\n assert AndOperator(v8, lit).mask == litval & 0xFF\n assert AndOperator(v16, lit).mask == litval\n assert AndOperator(v8, v16, lit).mask == litval & 0xFF", "def __and__(self, other):\r\n return self.intersection(other)", "def bitwise_and(*binaries):\n def bit_and(bit1, bit2):\n return '1' if int(bit1) & int(bit2) else '0'\n return bitwise_operation(bit_and, binaries)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Corresponds to the gate information for an OR gate.
def OR(): return {(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 1}
[ "def bitwise_or_(self, e):\n return self.__lazy_operate(operator.or_, e)", "def __or__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseOr, self, other)", "def enterLogicalExpressionOr(self, ctx: RulesParser.LogicalExpressionOrContext):\n self.context.operator = LogicalOperator.OR\n self.context.left = ExpressionNode()\n self.context.left.parent = self.context\n self.context = self.context.left", "def or_types(self):\n return self._or_types", "def test_negated_or(self):\n self.assert_to_cnf_transformation(\n '~(A || B)',\n r'~A /\\ ~B')", "def parse_gate_type(self, node):\r\n tag = node.tag\r\n if tag == 'or':\r\n return GateType.OR\r\n if tag == 'and':\r\n return GateType.AND\r\n if tag == 'atleast':\r\n return GateType.ATLEAST\r\n\r\n raise NotImplementedError('gate type unknown {}'.format(node.tag))", "def __or__(expr):", "def _separate_or_types(self, or_type):\n # special case 1: wild card\n if or_type == '*':\n return None, []\n\n # if OR base is a wildcard\n if or_type[0] == '*':\n return '*', re.findall(self.atom_reg, or_type[1:])\n\n # Split up decorators by RegEx strings for atoms\n split = re.findall(self.atom_reg, or_type)\n if len(split) == 0:\n return None, []\n\n base = split[0]\n decs = _remove_blanks_repeats(split[1:], ['',base])\n return base, decs", "def __or__(self, other):\n try:\n retval = ComposedAccessControl(self, other, logic='or')\n except TypeError:\n raise TypeError(\n f\"unsupported operand type(s) for |: '{type(self).__name__}' \"\n f\"and '{type(other).__name__}'\"\n )\n return retval", "def test_two_mode_gate(self):\n sf_prog = Program(4)\n\n with sf_prog.context as q:\n ops.BSgate(0.54, -0.324) | (q[3], q[0])\n\n xir_prog = io.to_xir(sf_prog)\n\n expected = [(\"BSgate\", [0.54, -0.324], (3, 0))]\n assert [(stmt.name, stmt.params, stmt.wires) for stmt in xir_prog.statements] == expected", "def orbits(self, original):\n if self.name == \"COM\":\n return 0\n else:\n planetoids[original].chain.append(self.name)\n return planetoids[self.around].orbits(original) + 1", "def __or__(self, other):\n\n @Parser\n def _or(tokens, s):\n try:\n return self.run(tokens, s)\n except NoParseError as e:\n return other.run(tokens, State(s.pos, e.state.max))\n\n _or.name = '(%s | %s)' % (self.name, other.name)\n return _or", "def opcode_set_register_bitwise_or(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n second_register = self.get_upper_nibble(opcode[1])\n first_register_value = self.registers[first_register]\n second_register_value = self.registers[second_register]\n result = first_register_value | second_register_value\n\n # Perform the instruction\n self.registers[first_register] = result\n logger.debug(f\"Execute Opcode {opcode.hex()}: Set the value of register {first_register} to the bitwise or of itself and the value of register {second_register} ({first_register_value} | {second_register_value} = {result}).\")", "def __or__(self, other):\n return ConjunctionDataType(self, other)", "def bool_or(self, truth_series_pair):\n return truth_series_pair[0] | truth_series_pair[1]", "def OrAlarmExpression(self, event_type_id, attributeName, operator, value) :\r\n \r\n or_expr = self.create('OrAlarmExpression')\r\n ex = self.EventAlarmExpression('%s.error' % event_type_id, 'red', 'vim.HostSystem', attributeName, operator, value)\r\n or_expr.expression.append(ex)\r\n\r\n ex = self.EventAlarmExpression('%s.warning' % event_type_id, 'yellow', 'vim.HostSystem', attributeName, operator, value)\r\n or_expr.expression.append(ex)\r\n\r\n ex = self.EventAlarmExpression('%s.info' % event_type_id, 'green', 'vim.HostSystem', attributeName, operator, value)\r\n or_expr.expression.append(ex)\r\n \r\n return or_expr", "def __or__(self,other):\n if isinstance(other,(float,int,complex)): return self*field_traits.conjugate(other)\t\t# calls __mul__ below (handles \"0\" case)\n elif isinstance(other,_operator_base): return self.space.traits.back_act_on_vec(self,other)\n else: return self.space.traits.dot(self,other)\t\t# checks that both are _member class", "def add_or_type(self, or_base, or_decorators):\n or_decorators = _remove_blanks_repeats(or_decorators, ['', or_base])\n self._or_types.append((or_base, or_decorators))", "def sv_or(val, state: dict):\n return Step.stateval_or(val, state)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Corresponds to the gate information for an XOR gate.
def XOR(): return {(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 0}
[ "def get_bprop_bitwisexor(self):\n\n def bprop(x, y, out, dout):\n return zeros_like(x), zeros_like(y)\n\n return bprop", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def test_negated_xor(self):\n self.assert_to_cnf_transformation(\n 'not (A xor B)',\n '(not A or B) and (A or not B)')", "def test_xor_gate(self):\n inputs = [[1.0, 1.0],\n [1.0, 0.0],\n [0.0, 1.0],\n [0.0, 0.0]]\n output_vector = [[0.0],\n [1.0],\n [1.0],\n [0.0]]\n inputs = np.array(inputs, dtype='float32')\n output_vector = np.array(output_vector)\n net = NeuralNetwork(inputs, output_vector)\n net.train()\n output = net.feed(np.array([[0, 1]], dtype='float32'))[0][0]\n output = round(output, 3)\n self.assertAlmostEqual(output, 1)\n output = net.feed(np.array([[1, 0]], dtype='float32'))[0][0]\n output = round(output, 3)\n self.assertAlmostEqual(output, 1)\n output = net.feed(np.array([[0, 0]], dtype='float32'))[0][0]\n output = round(output, 3)\n self.assertAlmostEqual(output, 0)\n output = net.feed(np.array([[1, 1]], dtype='float32'))[0][0]\n output = round(output, 3)\n self.assertAlmostEqual(output, 0)", "def __xor__(self, other):\n return self.XOR(other)", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def test_simple_xor(self):\n self.assert_to_cnf_transformation(\n 'A xor B',\n '(not B or not A) and (A or B)')", "def run_XOR():\n network = FFBPNetwork(2, 1)\n network.add_hidden_layer(3)\n\n xor_features = [[0, 0], [1, 0], [0, 1], [1, 1]]\n xor_labels = [[0], [1], [1], [0]]\n\n data = NNData(xor_features, xor_labels, 1)\n network.train(data, 10001, order=NNData.Order.RANDOM)", "def __xor__(self, other):\r\n return self.symmetric_difference(other)", "def __xor__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] ^ other.bits[i]]\n return UInt8(bits=bits)", "def _get_gate_values(self) -> Tensor:\n gate_values = (\n torch.sigmoid(self.log_alpha_param) * (self.upper_bound - self.lower_bound)\n + self.lower_bound\n )\n return gate_values", "def gate_way(self):\n return self._gate_way", "def inverse(self):\n return CSdgGate(ctrl_state=self.ctrl_state)", "def gate_names(self):\n return self.gg", "def cnot() -> np.ndarray:\n return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])", "def get_xor_trees(pt, xor_tree = None):\n xor_tree = xor_tree if xor_tree is not None else {}\n if pt.operator != None:\n for node in pt.children:\n if node.operator != None and node.operator == pt_op.XOR and not check_for_tau(node):\n xor_tree[f'X{len(xor_tree)+1}'] = node\n else:\n xor_tree = get_xor_trees(node, xor_tree)\n \n return xor_tree", "def __xor__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a ^ b for (a, b) in zip(self.bits, other.bits)]\n )))", "def test_bitwise_xor(self, _, a, b, skip_to_glow=False):\n utils.compare_tracing_methods(\n SimpleBitwiseXorModule(),\n a,\n b,\n fusible_ops={\"aten::bitwise_xor\"},\n )", "def xor(x, y):\r\n return ((x or y) and (not (x and y)))" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Organize configs for initializing components from registry.
def _organize_configs(self): # organize learner configs self.learner_cfg.args = self.args self.learner_cfg.env_info = self.env_info self.learner_cfg.hyper_params = self.hyper_params self.learner_cfg.log_cfg = self.log_cfg self.learner_cfg.head.configs.state_size = self.env_info.observation_space.shape self.learner_cfg.head.configs.output_size = self.env_info.action_space.n # organize worker configs self.worker_cfg.env_info = self.env_info self.worker_cfg.hyper_params = self.hyper_params self.worker_cfg.backbone = self.learner_cfg.backbone self.worker_cfg.head = self.learner_cfg.head self.worker_cfg.loss_type = self.learner_cfg.loss_type # organize logger configs self.logger_cfg.args = self.args self.logger_cfg.env_info = self.env_info self.logger_cfg.log_cfg = self.log_cfg self.logger_cfg.comm_cfg = self.comm_cfg self.logger_cfg.backbone = self.learner_cfg.backbone self.logger_cfg.head = self.learner_cfg.head
[ "def _load_configs(self):\n\n self._configs.clear()\n configs = config_utils.load(self._get_config_file_path())\n self._configs = configs.get('general')\n self._extract_test_roots()", "def configure(self):\n if self.name == 'ncm-ncd':\n self.configure_ncm_ncd()\n\n if self.name == 'maven-tools':\n self.configure_maven_tools()\n\n if self.name == 'CAF':\n self.configure_caf()\n\n if self.name == 'CCM':\n self.configure_ccm()\n\n if self.name == 'configuration-modules-grid':\n self.configure_components_grid()\n\n if self.name == 'configuration-modules-core':\n self.configure_components()\n\n if self.name == 'template-library-core':\n self.configure_template_library_core()", "def construct_config(self, config_path=None):\n self.config = Rofi()\n self.config.build(config_path)\n self.groups = {}\n for _, entry in self.config.config.items():\n if entry.group in self.groups:\n self.groups[entry.group].append(entry)\n else:\n self.groups[entry.group] = [entry]", "def __generate_registry(cls) -> None:\n if not os.path.isfile(cls.__config_root) and not os.path.splitext(cls.__config_root)[1].lower() in ['.yml', '.yaml']:\n raise ValueError('Path specified in config_root is not a valid file')\n\n # Get the directory name for the registry\n cls.__config_dir = os.path.dirname(cls.__config_root)\n\n next_entries = cls.__get_next_and_register_current(path=cls.__config_root)\n\n # A root configuration can point to additional configurations.\n while len(next_entries) > 0:\n new_next_entries = []\n\n # Iterate over all configuration entries. Additional entries will be added if there are _dependencies_ fields located in the configuration.\n # Otherwise only the configurations are added to the registry\n _ = [\n new_next_entries.extend(\n cls.__get_next_and_register_current(path=cls.__find_file(os.path.join(cls.__config_dir, entry['conf_type'])))\n )\n for entry in next_entries\n if cls.__validate_entry(entry)\n ]\n\n next_entries = new_next_entries", "def _load_configs(self, conn):\n\t\tfor (x,y), chip in self.chips.iteritems():\n\t\t\t# Select the chip to load the data into\n\t\t\tconn.selected_cpu_coords = (x,y,0)\n\t\t\t\n\t\t\t# Generate the chip's routing table (only loaded by a single core)\n\t\t\tnum_router_entries, router_entries = \\\n\t\t\t\tspinn_route.table_gen.spin1_table_gen(chip.router)\n\t\t\t\n\t\t\t# Ensure we don't have too many routing entries\n\t\t\tif num_router_entries > spinnaker_app.MAX_ROUTES_PER_CORE:\n\t\t\t\traise Exception(\"Too many router entries on a single core: %d (max %d)\"%(\n\t\t\t\t\tnum_router_entries, spinnaker_app.MAX_ROUTES_PER_CORE\n\t\t\t\t))\n\t\t\t\n\t\t\tfor index, core in enumerate(chip.cores.itervalues()):\n\t\t\t\t# Arbitarily choose one core to load the routing tables\n\t\t\t\tloads_router_enties = index == 0\n\t\t\t\t\n\t\t\t\t# Ensure we don't have too many sources/sinks\n\t\t\t\tif len(self.core_generators[core]) > spinnaker_app.MAX_SOURCES_PER_CORE:\n\t\t\t\t\traise Exception(\"Too many sources on a single core: %d (max %d)\"%(\n\t\t\t\t\t\tlen(self.core_generators[core]), spinnaker_app.MAX_SOURCES_PER_CORE\n\t\t\t\t\t))\n\t\t\t\tif len(self.core_consumers[core]) > spinnaker_app.MAX_SINKS_PER_CORE:\n\t\t\t\t\traise Exception(\"Too many sinks on a single core: %d (max %d)\"%(\n\t\t\t\t\t\tlen(self.core_consumers[core]), spinnaker_app.MAX_SINKS_PER_CORE\n\t\t\t\t\t))\n\t\t\t\t\n\t\t\t\t# The root block of the configuration \n\t\t\t\tconfig_root = spinnaker_app.config_root_t.pack(*spinnaker_app.config_root_tuple(\n\t\t\t\t\tcompletion_state = spinnaker_app.COMPLETION_STATE_RUNNING,\n\t\t\t\t\tseed = random.getrandbits(32),\n\t\t\t\t\ttick_microseconds = self._tick_period,\n\t\t\t\t\twarmup_duration = int(self._warmup/self.tick_period),\n\t\t\t\t\tduration = int(self._duration/self.tick_period),\n\t\t\t\t\trtr_drop_e = self._router_timeout_e,\n\t\t\t\t\trtr_drop_m = self._router_timeout_m,\n\t\t\t\t\tresult_dropped_packets = 0,\n\t\t\t\t\tresult_forwarded_packets = 0,\n\t\t\t\t\tnum_sources = len(self.core_generators[core]),\n\t\t\t\t\tnum_sinks = len(self.core_consumers[core]),\n\t\t\t\t\tnum_router_entries = num_router_entries if loads_router_enties else 0,\n\t\t\t\t))\n\t\t\t\t\n\t\t\t\t# Define the packet sources\n\t\t\t\tconfig_sources = \"\"\n\t\t\t\tfor route, gen in self.core_generators[core].iteritems():\n\t\t\t\t\t# Encode packet generator data\n\t\t\t\t\tif type(gen) is BernoulliGeneration:\n\t\t\t\t\t\ttemporal_dist = spinnaker_app.TEMPORAL_DIST_BERNOULLI\n\t\t\t\t\t\ttemporal_dist_data = spinnaker_app.bernoulli_packet_prob_t.pack(\n\t\t\t\t\t\t\t*spinnaker_app.bernoulli_packet_prob_tuple(\n\t\t\t\t\t\t\t\tbernoulli_packet_prob = gen.probability\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\telse:\n\t\t\t\t\t\traise Exception(\"Unknown packet generator %s.\"%repr(gen))\n\t\t\t\t\t\n\t\t\t\t\t# Encode this source\n\t\t\t\t\tconfig_sources += spinnaker_app.config_source_t.pack(*spinnaker_app.config_source_tuple(\n\t\t\t\t\t\trouting_key = route.key,\n\t\t\t\t\t\ttemporal_dist = temporal_dist,\n\t\t\t\t\t\ttemporal_dist_data = temporal_dist_data,\n\t\t\t\t\t\tresult_packets_generated = 0,\n\t\t\t\t\t\tresult_packets_sent = 0,\n\t\t\t\t\t))\n\t\t\t\t\n\t\t\t\t# Define the packet sinks (which must be supplied in ascending order of\n\t\t\t\t# routing key)\n\t\t\t\tconfig_sinks = \"\"\n\t\t\t\tfor route in sorted(self.core_consumers[core]):\n\t\t\t\t\tcon = self.core_consumers[core][route]\n\t\t\t\t\t\n\t\t\t\t\t# Encode packet generator data\n\t\t\t\t\tif type(con) is not InstantConsumption:\n\t\t\t\t\t\traise Exception(\"Unknown packet consumer %s.\"%repr(con))\n\t\t\t\t\t\n\t\t\t\t\t# Encode this sink\n\t\t\t\t\tconfig_sinks += spinnaker_app.config_sink_t.pack(*spinnaker_app.config_sink_tuple(\n\t\t\t\t\t\trouting_key = route.key,\n\t\t\t\t\t\tresult_packets_arrived = 0,\n\t\t\t\t\t))\n\t\t\t\t\n\t\t\t\t# Put all the configuration blocks together\n\t\t\t\tconfig = config_root + config_sources + config_sinks\n\t\t\t\t\n\t\t\t\tif loads_router_enties:\n\t\t\t\t\tconfig += router_entries\n\t\t\t\t\n\t\t\t\t# Load this core's configuration\n\t\t\t\taddr = spinnaker_app.config_root_sdram_addr(core.core_id)\n\t\t\t\tdata = config\n\t\t\t\tself._write_mem_with_retry(conn, addr, scp.TYPE_BYTE, data)", "def create_config(cls):\n return cls._config_registry", "def configs(self) -> Sequence[\"_SingleFileConfig\"]:", "def _load_config(self):\n\n channel_spec = self.spec.channels\n\n _spec_fields = (\n 'name', 'long', 'word_len', 'bit_mask', 'max_range', 'log_max',\n 'log_min', 'gain')\n\n ParamSpec = namedtuple('SPn', _spec_fields)\n\n self._config = {\n num: ParamSpec(*format_attr(self.spec.type_i, **channel_spec[num]))\n for num in channel_spec}\n\n self.par_ids = tuple(sorted(channel_spec.keys()))\n self.names = self.__get_ch_attr('name')\n self.__load_id_maps()", "def _configure(self):\n # Setup command line parser.\n argparser = argparse.ArgumentParser(description = self._description)\n argparser.add_argument('--config-file', help = 'name of the config file')\n argparser.add_argument('--inventory', help = 'name of the inventory file')\n argparser.add_argument('--group', help = 'name of the Ansible host group')\n argparser.add_argument('--fact-dir', help = 'name of the fact cache directory')\n argparser.add_argument('--ascii', help = 'print only ASCII characters (flag)', action = 'store_true', default = None)\n argparser.add_argument('--refresh', help = 'force host fact refresh (flag)', action = 'store_true', default = None)\n\n # Process command line arguments.\n self._config_cli = vars(argparser.parse_args())\n\n # IMPORTANT! Immediatelly rewrite the default value for configuration file\n # name, if the new value was received as command line argument.\n if not self._config_cli['config_file'] == None:\n self.config['config_file'] = self._config_cli['config_file']\n\n # Load configurations from external file.\n self._config_file = self.json_load(self.config.get('config_file'))\n\n # Merge all configurations together.\n self.config.update((k, v) for k, v in self._config_file.items() if v is not None)\n self.config.update((k, v) for k, v in self._config_cli.items() if v is not None)", "def generateAllConfigs():\n generateStepperConfig()\n generateProgramConfig()", "def load(self):\n base_config = {}\n\n for loader in self.loaders:\n loaded = loader()\n\n if loaded:\n base_config.update(loaded)\n\n self.config = base_config", "def loadConfig(self):\n pass", "def _prepare_config(self):\n find_or_create(find_or_create(self.config, \"global\"), self.type_tag)", "async def test_merge_split_component_definition(hass: HomeAssistant) -> None:\n packages = {\n \"pack_1\": {\"light one\": {\"l1\": None}},\n \"pack_2\": {\"light two\": {\"l2\": None}, \"light three\": {\"l3\": None}},\n }\n config = {config_util.CONF_CORE: {config_util.CONF_PACKAGES: packages}}\n await config_util.merge_packages_config(hass, config, packages)\n\n assert len(config) == 4\n assert len(config[\"light one\"]) == 1\n assert len(config[\"light two\"]) == 1\n assert len(config[\"light three\"]) == 1", "def configure(self):\n cfg = self.loader.cfg.load()\n for plugin in self.plugins:\n plugin_cfg = Bunch(pre_check={}, launcher={}, post_check={})\n for key, section in plugin_cfg.items():\n cfg_section = cfg.get(key.replace('_', '-'), {})\n section.update(cfg_section)\n section.update(cfg_section.get(plugin.name, {}))\n\n # Remove unrelated subsections\n for section in plugin_cfg.values():\n for key in section.keys()[:]:\n if isinstance(section[key], dict):\n del section[key]\n\n plugin.configure(plugin_cfg)", "def _map_configs(self):\n\n logger.info(\"Cross-matching interferometric and feather configs\")\n\n if 'interf_config' not in self._config_dict.keys():\n return()\n\n # Initialize\n for interf_config in self._config_dict['interf_config'].keys():\n\n self._config_dict['interf_config'][interf_config]['feather_config'] = None\n\n if 'feather_config' not in self._config_dict.keys():\n continue\n\n for feather_config in self._config_dict['feather_config'].keys():\n if self._config_dict['feather_config'][feather_config]['interf_config'] != interf_config:\n continue\n self._config_dict['interf_config'][interf_config]['feather_config'] = feather_config\n\n return()", "def setup(self):\n for name, annotation in self.config.__annotations__.items():\n if not getattr(self.config, name):\n annotation = annotation[5:-1]\n file, cls = annotation.rsplit('.', 1)\n loaded_cls = getattr(__import__(file, fromlist=[cls]), cls)\n setattr(self.config, name, loaded_cls)", "def setup(self):\n self._rl_modules = {}\n self.__check_module_configs(self.config.modules)\n for module_id, module_spec in self.config.modules.items():\n self._rl_modules[module_id] = module_spec.build()", "def populate_initial_config(self):\n try:\n with openstack.OpenStack() as client:\n self._populate_system_config(client)\n self._populate_load_config(client)\n self._populate_network_config(client)\n if self.kubernetes:\n self._populate_dns_config(client)\n self._populate_docker_config(client)\n controller = self._populate_controller_config(client)\n # ceph_mon config requires controller host to be created\n self._inventory_config_complete_wait(client, controller)\n self._populate_interface_config(client, controller)\n self._populate_default_storage_backend(client, controller)\n\n except (KeystoneFail, SysInvFail) as e:\n LOG.exception(e)\n raise ConfigFail(\"Failed to provision initial system \"\n \"configuration\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Spawn processes and run training loop.
def train(self): print("Spawning and initializing communication...") # Spawn processes self._spawn() # Initialize communication for proc in self.processes: proc.init_communication.remote() # Run main training loop print("Running main training loop...") run_procs = [proc.run.remote() for proc in self.processes] futures = ray.get(run_procs) # Retreive workers' data and write to wandb # NOTE: Logger logs the mean scores of each episode per update step if self.args.log: worker_logs = [f for f in futures if f is not None] self.logger.write_worker_log.remote( worker_logs, self.hyper_params.worker_update_interval ) print("Exiting training...")
[ "def do_training():\n train_cls = Train()\n train_cls.run()", "def main(self):\n # (i) Start Process: Statistics\n self.stats.start()\n\n # (ii) Start Process: Predictors\n if Config.TRAIN_MODE == 'policy' or (Config.TRAIN_MODE == 'selection' and not Config.LOAD_DATA):\n for env_id in Config.ENV_IDS:\n for _ in range(Config.PREDICTORS[env_id]):\n self.add_predictor(env_id)\n\n # (iii) Start Process: Workers\n if Config.TRAIN_MODE == 'policy' or (Config.TRAIN_MODE == 'selection' and not Config.LOAD_DATA):\n for env_id in Config.ENV_IDS:\n for i in range(Config.WORKERS[env_id]):\n self.add_worker(env_id, i)\n\n # (iv) Load selection data or start Process: Data\n if Config.TRAIN_MODE == 'selection':\n if not Config.LOAD_DATA:\n for env_id in Config.ENV_IDS:\n self.add_data(env_id)\n while self.data:\n self.wait_data()\n self._close_processes()\n self._load_selection_data()\n \n\n # (v) Start Process: Trainers \n for env_id in Config.ENV_IDS:\n for _ in range(Config.TRAINERS[env_id]):\n self.add_trainer(env_id)\n\n if Config.TRAIN_MODE == 'selection':\n self.stats.episode_count.value = 0\n while self.stats.episode_count.value < Config.MAX_EPISODES:\n\n # (vi) Save all models to file system.\n if Config.SAVE_MODELS:\n self._save_models()\n \n time.sleep(0.1)\n\n # (vii) Remove all Processes.\n self._close_processes()\n print('All processes have been closed, terminating statistics and end program.')\n # Terminate stats which is likely waiting for some queue.\n self.stats.terminate()", "def start_processes(self, rand_sleep):\n self.pids = self.manager.Array('l', range(len(self.testers)))\n\n for id in range(len(self.testers)):\n self.process_done.release()\n next_s = self.manager.Semaphore(0)\n\n p = Process(target=self.testers[id].run, args=(self.process_done, next_s, rand_sleep, self.lock, self.sub_proc, self.pids, id, self.queue))\n self.proc_ids.append(p)\n self.next_steps.append(next_s)\n p.start()\n self.pids[id] = p.pid", "def _spawn_processes(self, state):\r\n num_to_start = state.numprocesses - len(state.running)\r\n for i in range(num_to_start):\r\n self._spawn_process(state)", "def startup_processes(self):\n self.load_config()\n self.create_rotary()\n self.speed_off()", "def setup_class(self):\n try:\n set_start_method('spawn')\n except RuntimeError:\n pass\n self.poolSize = NUM_PROCESSES\n self.pool = Pool(processes=self.poolSize)\n self.pool.starmap(setup_ddp, [(rank, self.poolSize) for rank in range(self.poolSize)])", "def run(self):\n for instance in self.component_instances:\n instance_thread = instance.spawn()\n instance_thread.start()", "def _spawn(self):\n self._is_running = True\n self._pid = None\n self._kill_event = eventlet.event.Event()\n self._process, cmd = utils.create_process(self._cmd,\n run_as_root=self.run_as_root)\n self._watchers = []\n for reader in (self._read_stdout, self._read_stderr):\n # Pass the stop event directly to the greenthread to\n # ensure that assignment of a new event to the instance\n # attribute does not prevent the greenthread from using\n # the original event.\n watcher = eventlet.spawn(self._watch_process,\n reader,\n self._kill_event)\n self._watchers.append(watcher)", "def main():\n\n config = SimCLRConfig.parse_arguments()\n os.environ['CUDA_VISIBLE_DEVICES'] = ','.join([str(gpu) for gpu in config.gpus])\n num_gpus_per_node = len(config.gpus)\n world_size = config.num_nodes * num_gpus_per_node\n distributed = world_size > 1\n setattr(config, 'num_gpus_per_node', num_gpus_per_node)\n setattr(config, 'world_size', world_size)\n setattr(config, 'distributed', distributed)\n \n rich.print(config.__dict__)\n config.save()\n\n if config.distributed:\n rich.print(f\"Distributed training on {world_size} GPUs.\")\n mp.spawn(\n main_worker,\n nprocs=config.num_gpus_per_node,\n args=(config, )\n )\n else:\n rich.print(f\"Single GPU training.\")\n main_worker(0, config=config) # single machine, single gpu", "def start_core_process(self):\n # Create scanner engine process\n scanner_engine_process = multiprocessing.Process(target=self.scanner_engine_obj.start_scanner_engine)\n # Create monitor engine process\n monitor_engine_process = multiprocessing.Process(target=self.monitor_engine_obj.start_monitor_engine)\n\n # Add scanner process to process pool\n self.process_pool.append(scanner_engine_process)\n # Add monitor process to process pool\n self.process_pool.append(monitor_engine_process)\n\n # Start all the process\n for process in self.process_pool:\n process.start()\n\n # Complete (join) all the process\n for process in self.process_pool:\n process.join()", "def start_workers(self):\n for worker in self.workers:\n worker.start()", "def start_multiple_thread(ENV):\n\tpool = []\n\tfor num in range(forks):\n\t\tp = Process(target=work, args=(ENV,))\n\t\tp.start()\n\t\tpool.append(p)\n\t\tprint 'started worker thread'\n\t\t# Sleep briefly so polling connections do not happen at once\n\t\ttime.sleep(0.5)\n\treturn pool", "def __call__(self):\n # Initialize all workers\n self.initialize_workers()\n \n # Make tasks and assign each task to a worker\n tasks = self.make_tasks()\n assert len(tasks) <= self.num_worker, 'The number of tasks cannot exceed the number of workers.'\n self.assign_tasks(tasks)\n \n # Stop all workers and terminate all processes\n self.stop_workers()", "def main():\n\n # TODO: define:\n # step+noize\n # log scale instead of uniform\n\n # Define parametter: [min, max]\n dictParams = {\n \"batchSize\": [int, [1, 3]],\n \"learningRate\": [float, [1, 3]]\n }\n\n # Training multiple times with different parametters\n for i in range(10):\n # Generate the command line arguments\n trainingArgs = \"\"\n for keyArg, valueArg in dictParams:\n value = str(random(valueArg[0], max=valueArg[1]))\n trainingArgs += \" --\" + keyArg + \" \" + value\n\n # Launch the program\n os.run(\"main.py\" + trainingArgs)\n\n # TODO: Save params/results ? or already inside training args ?", "def do_main(self):\n self.pool.spawn_n(self._periodic_runner)\n super(Manager, self).do_main()", "def train():\n rank = MPI.COMM_WORLD.Get_rank()\n\n if rank == 0:\n logger.configure(folder=LOGDIR)\n\n else:\n logger.configure(format_strs=[])\n workerseed = SEED + 10000 * MPI.COMM_WORLD.Get_rank()\n set_global_seeds(workerseed)\n env = make_env(workerseed)\n\n env = bench.Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(rank)))\n env.seed(workerseed)\n\n model = PPO1(MlpPolicy, env, timesteps_per_actorbatch=4096, clip_param=0.2, entcoeff=0.0, optim_epochs=10,\n optim_stepsize=3e-4, optim_batchsize=64, gamma=0.99, lam=0.95, schedule='linear',\n verbose=1)\n\n eval_callback = EvalCallback(env, best_model_save_path=LOGDIR, log_path=LOGDIR, eval_freq=EVAL_FREQ, n_eval_episodes=EVAL_EPISODES)\n\n model.learn(total_timesteps=NUM_TIMESTEPS, callback=eval_callback)\n\n env.close()\n del env\n if rank == 0:\n model.save(os.path.join(LOGDIR, \"final_model\")) # probably never get to this point.", "def start(self):\n # 1st step: start processes\n self.start_dask_scheduler()\n self.start_dask_worker()\n self.client = distributed.Client(\"tcp://%s:%d\" % (self.ip_address, self.scheduler_port))\n\n # 2nd step: wait until all workers are started and connected to the scheduler\n while len(self.client.scheduler_info()[\"workers\"]) < self.ntasks:\n logging.debug(\"waiting for workers... (%d/%d)\" % (len(self.client.scheduler_info()[\"workers\"]), self.ntasks))\n sleep(1)\n\n # 3rd step: make sure that all workers have the same PYTHONPATH\n def set_python_path(first_element):\n sys.path.insert(0, first_element)\n self.client.run(set_python_path, sys.path[0])\n self.client.run_on_scheduler(set_python_path, sys.path[0])", "def run_train():\n parser = argparse.ArgumentParser(description=\"GPT training\")\n parser.add_argument('--device_id', type=int, default=0, help=\"Device id, default is 0.\")\n parser.add_argument(\"--device_num\", type=int, default=1, help=\"Use device nums, default is 1.\")\n parser.add_argument(\"--distribute\", type=str, default=\"false\", choices=[\"true\", \"false\"],\n help=\"Run distribute, default is false.\")\n parser.add_argument(\"--optimizer\", type=str, default=\"adam\", choices=[\"adam\", \"lamb\"],\n help=\"select which optimizer to be used, default adam\")\n parser.add_argument(\"--epoch_size\", type=int, default=10, help=\"Epoch size, default is 10.\")\n parser.add_argument(\"--warmup_step\", type=int, default=10000, help=\"Warmup step, default is 10000.\")\n parser.add_argument(\"--data_path\", type=str, default=\"\", help=\"Data path of your MindRecord files.\")\n parser.add_argument(\"--start_lr\", type=float, default=\"5e-5\", help=\"Start learning rate, default is 5e-5.\")\n parser.add_argument(\"--end_lr\", type=float, default=\"1e-10\", help=\"End learning rate, default is 1e-10.\")\n parser.add_argument(\"--sink_size\", type=int, default=100, help=\"Sink size for every iteration, default is 100\")\n parser.add_argument(\"--model_parallel_num\", type=int, default=8, help=\"Num of model parallel, default is 8\")\n\n\n args_opt = parser.parse_args()\n device_id = int(os.getenv(\"DEVICE_ID\", '0'))\n context.set_context(mode=context.GRAPH_MODE, device_target=\"Ascend\", device_id=device_id)\n if args_opt.distribute == \"true\":\n D.init()\n device_num = args_opt.device_num\n rank = device_id % device_num\n print(\"device_id is {}, rank_id is {}\".format(device_id, rank))\n\n context.reset_auto_parallel_context()\n context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True,\n device_num=device_num)\n\n else:\n rank = 0\n device_num = 1\n\n config = GPTConfig(batch_size=4,\n seq_length=1024,\n vocab_size=50257,\n embedding_size=1024,\n num_layers=24,\n num_heads=16,\n expand_ratio=4,\n post_layernorm_residual=False,\n dropout_rate=0.1,\n compute_dtype=mstype.float16,\n use_past=False)\n gpt = GPT(config)\n model_parallel_num = args_opt.model_parallel_num\n data_parallel_num = int(device_num / model_parallel_num)\n parallel_config = TransformerOpParallelConfig(data_parallel=data_parallel_num,\n model_parallel=model_parallel_num)\n loss = CrossEntropyLoss(parallel_config.dp_mp_config)\n gpt_with_loss = GPTWithLoss(gpt, loss)\n\n ds = create_dataset(config.batch_size, data_path=args_opt.data_path, device_num=device_num, rank=rank)\n\n\n epoch_num = args_opt.epoch_size\n step_per_epoch = ds.get_dataset_size()\n\n lr = LearningRate(learning_rate=args_opt.start_lr,\n end_learning_rate=args_opt.end_lr,\n warmup_steps=args_opt.warmup_step,\n decay_steps=epoch_num*step_per_epoch)\n\n decay_filter = lambda x: 'layernorm' not in x.name.lower() and \"bias\" not in x.name.lower()\n params = gpt.trainable_params()\n decay_params = list(filter(decay_filter, params))\n other_params = list(filter(lambda x: not decay_filter(x), params))\n group_params = [{'params': decay_params, 'weight_decay': 1e-2},\n {'params': other_params, 'weight_decay': 0.0},\n {'order_params': params}]\n\n if args_opt.optimizer == \"lamb\":\n optimizer = nn.Lamb(group_params, learning_rate=lr)\n else:\n optimizer = nn.AdamWeightDecay(group_params, learning_rate=lr)\n\n callback_size = args_opt.sink_size\n actual_epoch_num = int(epoch_num * step_per_epoch/callback_size)\n callback = [TimeMonitor(callback_size), LossMonitor(callback_size)]\n\n config_ck = CheckpointConfig(save_checkpoint_steps=step_per_epoch, keep_checkpoint_max=1)\n ckpoint_cb = ModelCheckpoint(prefix=\"GPT2\", config=config_ck)\n callback.append(ckpoint_cb)\n\n\n update_cell = DynamicLossScaleUpdateCell(loss_scale_value=1024,\n scale_factor=2,\n scale_window=1000)\n\n gpt_with_grads = GPTTrainOneStepWithLossScaleCell(gpt_with_loss, optimizer=optimizer,\n scale_update_cell=update_cell)\n\n\n model = Model(gpt_with_grads)\n model.train(actual_epoch_num, ds, callbacks=callback, dataset_sink_mode=True, sink_size=callback_size)", "def run(self):\n while True:\n config, count, node_type = self.queue.get()\n # launch_node is implemented in BaseNodeLauncher\n self.launch_node(config, count, node_type)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the IP address of the device
def get_IP_address(self): IP_address = self.device.get_IP_address() return IP_address
[ "def ip_address(self) -> str | None:\n return self._device.ip_address", "def getIpAddress():\n # type: () -> String\n return socket.gethostbyname(str(getHostName()))", "def get_ip(self) -> str:\n try:\n self.remote_exec(\"from network import WLAN\")\n self.remote_exec(\"wlan=WLAN()\")\n ret = self.remote_exec(\"print(wlan.ifconfig()[0])\")\n ip = ret.decode(\"utf-8\")\n return ip\n except Exception as err:\n debug(f\"Exception {err=}. Could not retrieve WLAN ip address\")\n return \"\"", "def get_ipaddr():\n return get('https://api.ipify.org').text", "def get_ip_address():\n ip_address = subprocess.check_output(\n [\"unit-get\", \"private-address\"])\n return ip_address.decode().strip()", "def get_ip_by_device(self, device_name):\n return self.netbox_con.get('/ipam/ip-addresses', device=device_name)", "def get_ip():\r\n if cfg.getServer('host'):\r\n IP = cfg.getServer('host')\r\n else:\r\n result = os.popen(\"hostname -I |awk '{print $1}'\").readlines()\r\n logger.debug(result)\r\n if result:\r\n IP = result[0].strip()\r\n logger.info(f'The IP address is {IP}')\r\n else:\r\n logger.warning('Server IP address not found!')\r\n IP = '127.0.0.1'\r\n\r\n return IP", "def interface_ip(self):\n try:\n ip_address = socket.inet_ntoa(struct.pack('>i', self._attribute('interface_ip', 0)))\n except Exception:\n ip_address = self._attribute('interface_ip', 0)\n\n return ip_address", "def get_addr(self):\n return self._ip + ':' + str(self._port)", "def get_ip(ifname):\n # TODO: what about AFINET6 / IPv6?\n return netifaces.ifaddresses(ifname)[netifaces.AF_INET][0]['addr']", "def get_my_ip():\n ip = socket.gethostbyname(socket.gethostname())\n # Some versions of Ubuntu may return 127.0.0.1\n if os.name != \"nt\" and ip.startswith(\"127.\"):\n import fcntl # not available on Windows\n import struct\n interfaces = [\"eth0\", \"eth1\", \"eth2\", \"wlan0\",\n \"wlan1\", \"wifi0\", \"ath0\", \"ath1\", \"ppp0\"]\n for ifname in interfaces:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', ifname[:15])\n )[20:24])\n break;\n except IOError:\n pass\n return ip", "def get_network_ip():\n comm = \"\"\" docker network inspect tada-gam_default | grep \"Gateway\" \"\"\"\n a = subprocess.Popen(comm, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]\n ip = a.split(\":\")[1].replace('\"', '').strip()\n return ip", "def get_ip(self, request):\r\n return request.META['REMOTE_ADDR']", "def ip(self) -> str:\n if self._flask_request.headers.getlist(\"X-Forwarded-For\"):\n return self._flask_request.headers.getlist(\"X-Forwarded-For\")[0]\n return self._flask_request.remote_addr", "def get_ip(self, host):\n try:\n nmc = NetworkManagementClient(self.credentials, self.subscription_id)\n ip = list(nmc.public_ip_addresses.list(group_name(host)))[0]\n return ip.ip_address\n except Exception:\n logger.error(\"Could not retrieve IP of host %s\", host.id)\n return None", "def getLocalIP():\n \n # get IPs from the data list returned by socket.getaddrinfo\n localIPs = [x[4][0] for x in socket.getaddrinfo(socket.gethostname(), 80)\n if isIPLocal(x[4][0])]\n \n # return the first IP\n if localIPs:\n return localIPs[0]\n \n # let the OS figure out which interface to use\n # create a standard UDP socket\n tempSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n # connect to one of Google's DNS servers\n tempSocket.connect(('8.8.8.8', 9))\n # get the interface used by the socket\n localIP = tempSocket.getsockname()[0]\n except socket.error:\n # return loopback address 127.0.0.1 if connection fails\n localIP = \"127.0.0.1\"\n finally:\n # close temporary socket\n tempSocket.close()\n return localIP", "def get_ip():\n try:\n r = requests.get('https://api.ipify.org').text\n return r\n except ConnectionError:\n return 'No Connection'", "def _obtain_ip(self, phone):\n\n args = [\n 'adb',\n '-s', phone['selector'],\n 'shell',\n 'ip', 'route'\n ]\n\n result = subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n ip_regex = re.compile(\n r'src (?P<ip>\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'\n )\n\n for line in result.stdout.decode('utf-8').splitlines():\n match = ip_regex.search(line)\n if match:\n return match.group('ip')", "def getip():\n\tsi='Address: '\n\tr=urlopen('http://checkip.dyndns.org').read()\n\ti=r.find(si)+len(si)\n\te=r.find('<',i)\n\treturn r[i:e]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Negate `self`. Returns NumericValue `self` negated
def __neg__(self) -> NumericValue: return self.negate()
[ "def __neg__(self):\n result = Scalar._create_raw()\n lib.crypto_core_ed25519_scalar_negate(result._ptr, self._ptr)\n return result", "def __neg__(self):\n return Ad_Var(-self._val, -self._ders)", "def negate(self):\n return Formula(\"not\", self)", "def neg(self) -> 'Tensor':\r\n return neg(self)", "def neg(self):\n return Rational(-self.numerator, self.denominator)", "def __neg__(self) -> \"SbVec4i32\":\n return _coin.SbVec4i32___neg__(self)", "def __invert__(self) -> IntegerValue:\n try:\n node = ops.BitwiseNot(self)\n except (IbisTypeError, NotImplementedError):\n return NotImplemented\n else:\n return node.to_expr()", "def negation(self):\n if self.is_negation():\n return Literal(self.value[1:])\n return Literal(NOT + self.value)", "def negated(self):\n return Literal(self.atom, not self.is_positive)", "def __neg__(self) -> \"SbVec3i32\":\n return _coin.SbVec3i32___neg__(self)", "def __neg__(self) -> \"SbVec4ui32\":\n return _coin.SbVec4ui32___neg__(self)", "def __neg__(self):\n neg = {k: -1 * v for k, v in self.der.items()}\n neg = Counter(neg)\n return AutoDiff(self.var, -self.val, neg)", "def __neg__(self) -> \"SbVec2i32\":\n return _coin.SbVec2i32___neg__(self)", "def __neg__(self) -> \"SbVec4b\":\n return _coin.SbVec4b___neg__(self)", "def __neg__(self) -> \"SbVec4d\":\n return _coin.SbVec4d___neg__(self)", "def __neg__(self) -> \"SbVec4ub\":\n return _coin.SbVec4ub___neg__(self)", "def __ne__(self, *args):\n return _snap.TIntHSI___ne__(self, *args)", "def __neg__(self) -> \"SbVec4s\":\n return _coin.SbVec4s___neg__(self)", "def __neg__(self) -> \"SbVec3b\":\n return _coin.SbVec3b___neg__(self)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return `NULL` if an expression is zero.
def nullifzero(self) -> NumericValue: return ops.NullIfZero(self).to_expr()
[ "def is_scalar_zero(expr):\n return is_scalar_x(expr, 0)", "def zeroifnull(self) -> NumericValue:\n return ops.ZeroIfNull(self).to_expr()", "def _get_zero_expr():\n expr = delay_model_pb2.DelayExpression()\n _set_constant_expression(expr, 0)\n return expr", "def is_scalar_minus_one(expr):\n return is_scalar_x(expr, -1)", "def is_matrix_zero(expr):\n return is_matrix_x(expr, 0)", "def get_zero_action() -> float:\n return 0.0", "def _visit_if_not_none(expr):\r\n if expr is not None:\r\n return self.visit(expr)\r\n return ast.copy_location(ast.Name(id='None', ctx=ast.Load()), node)", "def constant_zero():\n return AST.Constant('int', '0')", "def q_zero_point(self): # real signature unknown; restored from __doc__\n return 0", "def test_a22(self):\n self.assertEqual(transmaths.NULLITY ** -1, transmaths.NULLITY)", "def failIfNone(self, expr, msg=None):\n if expr is None:\n raise self.failureException, msg", "def test_carbon_dating_with_zero_value():\n assert get_age_carbon_14_dating(0) == None", "def zero(self):\n coord_express = {chart: chart.zero_function()\n for chart in self._domain.atlas()}\n zero = self.element_class(self,\n coord_expression=coord_express,\n name='zero', latex_name='0')\n zero._is_zero = True\n return zero", "def make_eq(expression):\n if \"=\" not in expression:\n expression += \" = 0\"\n return to_sympy(expression)", "def DecodeFloatZero(x) -> int:\n assert x == 0\n return 0", "def atLeastOne(expressions) :\n \"*** YOUR CODE HERE ***\"\n if len(expressions) == 1:\n return expressions[0]\n return logic.Expr(\"|\", *expressions)", "def calculate_equation(expression):\n return eval(expression[:-1])", "def test_mult_by_zero(self):\r\n exp = 0*self.a\r\n self.assertEqual(exp.value, 0)\r\n obj = Minimize(exp)\r\n p = Problem(obj)\r\n result = p.solve()\r\n self.assertAlmostEqual(result, 0)\r\n assert self.a.value is not None", "def default_to_zero(val):\n return 0 if val is None else val" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return zero if an expression is `NULL`.
def zeroifnull(self) -> NumericValue: return ops.ZeroIfNull(self).to_expr()
[ "def is_scalar_zero(expr):\n return is_scalar_x(expr, 0)", "def nullifzero(self) -> NumericValue:\n return ops.NullIfZero(self).to_expr()", "def is_scalar_minus_one(expr):\n return is_scalar_x(expr, -1)", "def _visit_if_not_none(expr):\r\n if expr is not None:\r\n return self.visit(expr)\r\n return ast.copy_location(ast.Name(id='None', ctx=ast.Load()), node)", "def is_matrix_zero(expr):\n return is_matrix_x(expr, 0)", "def test_a22(self):\n self.assertEqual(transmaths.NULLITY ** -1, transmaths.NULLITY)", "def failIfNone(self, expr, msg=None):\n if expr is None:\n raise self.failureException, msg", "def is_true_ufl_scalar(expression):\n return isinstance(expression, Expr) and \\\n not (expression.shape() or expression.free_indices())", "def is_null(i):\n return i == null()", "def int_if_not_none(value):\n ...", "def sum_if_not_none(x):\n s = 0\n for i in x:\n if i is None:\n return None\n s += i\n return s", "def _get_zero_expr():\n expr = delay_model_pb2.DelayExpression()\n _set_constant_expression(expr, 0)\n return expr", "def transform_null_stmt(self, node):\n return none", "def is_ufl_scalar(expression):\n return isinstance(expression, Expr) and not expression.shape()", "def __checkForImmediateExpression(self, op: str, \\\n lowerLimit=-sys.maxsize, upperLimit=sys.maxsize, \\\n recurse=True, recurseDepth=0, targetBits=16, orgpos=0):\n\n # simple cases\n if op == '$':\n return orgpos\n\n if op.isdigit():\n n = int(op, 10)\n if n is not None and n >= lowerLimit and n <= upperLimit:\n return n\n else:\n return None\n\n if op.upper().startswith('$') and all(c in string.hexdigits for c in op[1:]):\n n = int(op[1:], 16)\n if n is not None and n >= lowerLimit and n <= upperLimit:\n return n\n else:\n return None\n\n if op.upper().endswith('H') and all(c in string.hexdigits for c in op[:-1]):\n n = int(op[:-1], 16)\n if n is not None and n >= lowerLimit and n <= upperLimit:\n return n\n else:\n return None\n\n if op.upper().endswith(\"B\") and op[:-1].isdigit():\n n = int(op[:-1], 2)\n if n is not None and n >= lowerLimit and n <= upperLimit:\n return n\n else:\n return None\n\n if len(op) > 1 and ((op.startswith(\"'\") and op.endswith(\"'\")) or \\\n (op.startswith('\"') and op.endswith('\"'))) :\n n = ord(op[1])\n if n >= lowerLimit and n <= upperLimit:\n return n\n else:\n return None\n\n # check, if expression is actually simply a label\n lb = op.strip().upper()\n if lb in self.labels:\n found = self.labels[lb]\n res = None\n if found.kind == 'L':\n # without big magic, we should be able to take the direct value and give back\n res = found.directValue\n\n if found.kind == 'E':\n # do we already have a direct value for this label?\n if found.directValue != None:\n res = found.directValue\n else:\n # can access an intermediate expression?\n if found.expression != None:\n # before going into recursion, check if recurse depths has already been exceeded\n if recurseDepth > OPTIONS.maxRecurseDepth:\n raise LabelParseException(\"Reaching maximum recursion depth while evaluating expression!\")\n\n res = self.__checkForImmediateExpression(found.expression, lowerLimit=lowerLimit, \\\n upperLimit=upperLimit, targetBits=targetBits, \\\n recurse=True, recurseDepth=recurseDepth + 1) # TODO check recurse!\n \n # if there was an result, store it as direct\n if res != None:\n found.directValue = res\n\n # OK, res available?\n if res != None:\n # can take value, have to constrain\n res &= (1 << targetBits) - 1\n OPTIONS.debug(2, \".. eval label %s gave %d!\" % (found.tag, res))\n # to be square, also constrain to limits\n if res >= lowerLimit and res <= upperLimit:\n return res\n else:\n return None\n\n # complex case: suspect, that it is a nested expression!\n if recurse:\n l = self.tryParseExpression(op)\n OPTIONS.debugObject(2, \"PARSE:\", l)\n l = self.checkParsedExpression(l)\n if l is not None:\n OPTIONS.debug(2, \".. check parsed list passed!\")\n OPTIONS.indentTo(6)\n res = self.evaluateParsedExpression(l, targetBits=targetBits, recurseDepth=recurseDepth+1)\n if res is not None:\n OPTIONS.debug(2, \".. eval parsed list gave %d!\" % res)\n # to be square, also constrain to limits\n if res >= lowerLimit and res <= upperLimit:\n # TWO'S complement\n return Helper.toTwosComplement(res, targetBits=8)\n return None\n\n # no :-(\n return None", "def default_to_zero(val):\n return 0 if val is None else val", "def constant_zero():\n return AST.Constant('int', '0')", "def failUnlessNone(self, expr, msg=None):\n if expr is not None:\n raise self.failureException, msg", "def NullScalar(tp):\n return Scalar(_value_type=tp)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Floor divide `self` by `other`.
def __floordiv__( self, other: NumericValue, ) -> NumericValue: return _binop(ops.FloorDivide, self, other)
[ "def __floordiv__(self, other):\n return self.componentwise(other, operator.__floordiv__)", "def divide(self, other):\n return self.multiply(other.reciprocal())", "def __floordiv__(self, other):\n if isinstance(other, (int, float)):\n return Quaternion(\n self.real // other, self.i // other, self.j // other,\n self.k // other)\n else:\n return NotImplemented", "def div(self, other, qty=None, reverse=False):\n return self._operate(lambda a,b: a/b, other, qty, reverse, '/')", "def __divmod__(self, other):\n return (self.__floordiv__(other), self.__mod__(other))", "def divides(self, other):\n if not isinstance(other, NumberFieldIdeal):\n other = self.number_field().ideal(other)\n return (other / self).is_integral()", "def divide(self, other):\n new = ComplexNumber(self.get_real(), self.get_imaginary())\n if other.get_real() == 0.0 and other.get_imaginary() == 0.0:\n raise DisisionByNullException(\"Devision by null Error!\")\n\n other_bar_re = other.get_real() / ((other.get_real() **2) +\n (other.get_imaginary() **2))\n other_bar_im = (-1 * other.get_imaginary()) / ((other.get_real() ** 2) +\n (other.get_imaginary() ** 2))\n tmp = ComplexNumber(other_bar_re, other_bar_im)\n new.multiply(tmp)\n return new", "def divide(self, a, b):\r\n return a.__div__(b, context=self)", "def __div__(self, other):\n fiber = Fiber()\n fiber.r = numpy.divide(self.r, other)\n fiber.a = numpy.divide(self.a, other)\n fiber.s = numpy.divide(self.s, other)\n return fiber", "def __div__(self, other):\n if isinstance(other, BasicImage):\n if self == other:\n self.image /= other.image\n else:\n raise Exception(\"Different image parameters\")\n else:\n self.image /= other\n return self", "def __divmod__(self, other):\n return self.componentwise(other, divmod)", "def __mod__(self,other):\r\n self.Verificaciones(other)\r\n return self-(self//other)*other", "def __rtruediv__(self, other):\n\t\tnew_node = div(other, self)\n\t\treturn new_node", "def __div__(self, other):\n res = np.array(zip(*self.hero_and_value)[1]) / np.array(zip(*other.hero_and_value)[1], dtype=float)\n hero_and_value = zip(zip(*self.hero_and_value)[0], res)\n hs = HerosStats(self.stat_name, hero_and_value)\n return hs", "def __rdivmod__(self, other, context=None):\r\n other = _convert_other(other)\r\n if other is NotImplemented:\r\n return other\r\n return other.__divmod__(self, context=context)", "def __div__(self, other):\n twins = []\n OK = self.good\n if isinstance(other, CCD):\n OK = OK and other.good\n for win,owin in zip(self._data,other._data):\n twins.append(win / owin)\n else:\n other.good = True\n for win in self._data:\n twins.append(win / other)\n return CCD(twins, self.time, self.nxmax, self.nymax, OK, self.head)", "def __truediv__(self, other):\n\t\tnew_node = div(self, other)\n\t\treturn new_node", "def __div__(self, other):\n if(isinstance(other,UInt8)):\n remainder = UInt8(0)\n quotient = UInt8(0)\n dividend = self\n divisor = other\n\n for i in xrange(0, len(self)):\n remainder = remainder << 1\n remainder.bits[len(remainder)-1] = dividend.bits[0]\n boolTest = remainder >= divisor\n quotient = (quotient << 1)\n quotient.bits[len(quotient)-1] = boolTest\n tmpInt = UInt8(bits=[boolTest]*len(self))#This integer's bits will all be equal to boolTest, therefore in any case we can and it with the variable divisor, and it will emulate the code above\n remainder = remainder - (tmpInt & divisor)\n dividend = dividend << 1\n return quotient\n else:\n raise OpNotAllowedError(\"Cannot divide with something else than integer\")", "def __floordiv__(self, nextOperand): \r\n if not isinstance(nextOperand, int):\r\n raise ValueError(\"Division is only permitted with a one digit integer as divisor.\")\r\n auxiliary = 0\r\n newRepresentation = IntegerNumber(self.getNumericalBase(), repr(self))\r\n for i in reversed(range(0, len(newRepresentation))):\r\n auxiliary = newRepresentation.getNumericalBase() * auxiliary + newRepresentation[i]\r\n newRepresentation[i] = auxiliary // nextOperand\r\n auxiliary = auxiliary % nextOperand\r\n newRepresentation.removeLeadingZeros()\r\n return newRepresentation" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute `self` modulo `other`.
def __mod__(self, other: NumericValue) -> NumericValue: return _binop(ops.Modulus, self, other)
[ "def __mod__(self,other):\r\n self.Verificaciones(other)\r\n return self-(self//other)*other", "def __divmod__(self, other):\n return self.componentwise(other, divmod)", "def __mod__(self, other):\n if (isinstance(other, UInt8)):\n remainder = UInt8(0)\n quotient = UInt8(0)\n dividend = self\n divisor = other\n\n for i in xrange(0, len(self)):\n remainder = remainder << 1\n remainder.bits[len(remainder) - 1] = dividend.bits[0]\n boolTest = remainder >= divisor\n quotient = (quotient << 1)\n quotient.bits[len(quotient) - 1] = boolTest\n tmpInt = UInt8(bits=[boolTest] * len(\n self))\n remainder = remainder - (tmpInt & divisor)\n dividend = dividend << 1\n return remainder\n else:\n raise OpNotAllowedError(\"Cannot divide with something else than integer\")", "def __divmod__(self, other):\n return (self.__floordiv__(other), self.__mod__(other))", "def __rdivmod__(self, other, context=None):\r\n other = _convert_other(other)\r\n if other is NotImplemented:\r\n return other\r\n return other.__divmod__(self, context=context)", "def __mod__(self, other):\n other = coerceBigInt(other)\n if not other:\n return NotImplemented\n\n result = BigInt()\n librelic.bn_mod_abi(byref(result), byref(self), byref(other))\n return result", "def __rtruediv__(self, other):\n\t\tnew_node = div(other, self)\n\t\treturn new_node", "def __truediv__(self, other):\n\t\tnew_node = div(self, other)\n\t\treturn new_node", "def __sub__(self, other: int|Mod) -> Mod:\n other_mod = self.type_check(other)\n self.mod_check(other_mod)\n return Mod(self.value - other_mod.value, self.mod_value)", "def symmetric_mod(a,b):\n temp=a%b\n if temp > b/2.: temp-=b\n return temp", "def __floordiv__(self, other):\n return self.componentwise(other, operator.__floordiv__)", "def mydivmod(a, b):\r\n return a // b, a % b", "def __div__(self, other):\n if(isinstance(other,UInt8)):\n remainder = UInt8(0)\n quotient = UInt8(0)\n dividend = self\n divisor = other\n\n for i in xrange(0, len(self)):\n remainder = remainder << 1\n remainder.bits[len(remainder)-1] = dividend.bits[0]\n boolTest = remainder >= divisor\n quotient = (quotient << 1)\n quotient.bits[len(quotient)-1] = boolTest\n tmpInt = UInt8(bits=[boolTest]*len(self))#This integer's bits will all be equal to boolTest, therefore in any case we can and it with the variable divisor, and it will emulate the code above\n remainder = remainder - (tmpInt & divisor)\n dividend = dividend << 1\n return quotient\n else:\n raise OpNotAllowedError(\"Cannot divide with something else than integer\")", "def divide(self, other):\n return self.multiply(other.reciprocal())", "def __divmod__(self, other: float) -> Tuple[int, \"TS\"]:\n div, mod = super().__divmod__(other)\n return int(div), TS(mod)", "def div(self, other, qty=None, reverse=False):\n return self._operate(lambda a,b: a/b, other, qty, reverse, '/')", "def element_1_mod(self, other):\n if not self.is_integral():\n raise TypeError(\"%s is not an integral ideal\"%self)\n\n # Catch invalid inputs by making sure that we can make an ideal out of other.\n K = self.number_field()\n other = K.ideal(other)\n if not other.is_integral():\n raise TypeError(\"%s is not an integral ideal\"%other)\n\n if not self.is_coprime(other):\n raise TypeError(\"%s, %s are not coprime ideals\"%(self, other))\n\n bnf = K.pari_bnf()\n r = bnf.idealaddtoone(self.pari_hnf(), other.pari_hnf())[0]\n return K(r)", "def __mul__(self, other: int|Mod) -> Mod:\n other_mod = self.type_check(other)\n self.mod_check(other_mod)\n return Mod(self.value * other_mod.value, self.mod_value)", "def _mod(x, y):\n quotient = F.tensor_floordiv(x, y)\n prod = F.tensor_mul(y, quotient)\n return F.tensor_sub(x, prod)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a point constructed from the coordinate values. Constant coordinates result in construction of a `POINT` literal or column.
def point(self, right: int | float | NumericValue) -> ir.PointValue: return ops.GeoPoint(self, right).to_expr()
[ "def point(x: float, y: float, crs: MaybeCRS) -> Geometry:\n return Geometry({'type': 'Point', 'coordinates': [float(x), float(y)]}, crs=crs)", "def Point(lon, lat):\n return {\n 'type': 'Point',\n 'coordinates': [lon, lat]\n }", "def as_point(self):\n if self._geography.getType() == Geography.PTVAL:\n return PointWrapper(self._geography.get_ptVal())\n raise InvalidValueTypeException(\n \"expect Point type, but is \" + self._get_type_name()\n )", "def create_points_from_columns(self,\r\n\t\ttable_name,\r\n\t\tx_col,\r\n\t\ty_col,\r\n\t\tz_col=None,\r\n\t\tgeom_col=\"geom\",\r\n\t\twhere_clause=\"\",\r\n\t\tsrid=4326,\r\n\t\tdry_run=False):\r\n\t\tfrom collections import OrderedDict\r\n\t\trowid_wkt_dict = OrderedDict()\r\n\r\n\t\tcolumn_clause = [x_col, y_col, \"rowid\"]\r\n\t\tif z_col:\r\n\t\t\tcolumn_clause.append(z_col)\r\n\t\tfor rec in self.query(table_name, column_clause, where_clause=where_clause):\r\n\t\t\tif z_col:\r\n\t\t\t\twkt = \"POINTZ(%s %s %s)\" % (rec[x_col], rec[y_col], rec[z_col])\r\n\t\t\telse:\r\n\t\t\t\twkt = \"POINT(%s %s)\" % (rec[x_col], rec[y_col])\r\n\t\t\trowid_wkt_dict[rec[\"rowid\"]] = wkt\r\n\t\tself.set_geometry_from_wkt(table_name, rowid_wkt_dict, geom_col=geom_col,\r\n\t\t\t\t\t\t\t\t\tsrid=srid, dry_run=dry_run)", "def ogr_point(self):\n geom = ogr.Geometry(ogr.wkbPoint)\n geom.SetPoint(0, self.lon.decimal_degrees, self.lat.decimal_degrees)\n return geom", "def create(points): \r\n points = p2e._base._util.scale_1000(points)\r\n \r\n eco_id = Point._gen_object(\"point\", \"point\")\r\n if id == -1: return None\r\n return Point(eco_id, points)", "def createPointAtPosition(self, position):\n # Make sure the geometry is not read only.\n if self.isReadOnly():\n raise hou.GeometryPermissionError()\n\n result = _cpp_methods.createPointAtPosition(self, position)\n\n return self.iterPoints()[result]", "def get_point(self, row: int, column: int) -> Point:\n return self.field[row][column]", "def cell_to_point(self, cells: np.ndarray, cartesian: bool = True) -> np.ndarray:\n cells = np.atleast_1d(cells)\n\n if cells.size == 0:\n return np.zeros((0, self.dim))\n if cells.shape[-1] != self.num_axes:\n raise DimensionError(f\"Array of shape {cells.shape} cannot denote cells\")\n\n # convert from cells indices to grid coordinates\n points = (cells + 0.5) * self.discretization\n points[..., 1] += self.axes_bounds[1][0]\n if cartesian:\n return self.point_to_cartesian(points)\n else:\n return points # type: ignore", "def pos(self):\n return Point(*self.position())", "def point(obj):\n if isinstance(obj, Point):\n return obj\n if type(obj) is complex:\n return Point(obj.real, obj.imag)\n if type(obj) is tuple and len(obj) == 2:\n return Point(obj[0], obj[1])\n raise ValueError('can not convert {!r} to a Point'.format(obj))", "def tuple_to_point(t):\n return Point(t[0], t[1]) if t else None", "def create_geom_column(connection, table, field, projection):\n s = sql.select([sql.func.AddGeometryColumn('public', table, field, projection, 'POINT', 2)])\n connection.execute(s)", "def create_point(point_x, point_y, vertex_x, edge_y, scaling_factor=2):\n # TODO: Geometric mean??\n return (point_x + vertex_x) / scaling_factor, (point_y + edge_y) / scaling_factor", "def insert_point(self ,coord, SRID):\n sql_insert = \"SELECT ST_SetSRID(ST_MakePoint({0}, {1}),{2})\"\n\n executed_sql = sql_insert.format(coord[0], coord[1], SRID)\n\n return executed_sql", "def add_georss_point(self, handler, coords, w3c_geo=False):\n if w3c_geo:\n if self.is_input_latitude_first:\n lat, lon = coords[:2]\n else:\n lon, lat = coords[:2]\n handler.addQuickElement(u'geo:lat', u'%f' % lat)\n handler.addQuickElement(u'geo:lon', u'%f' % lon)\n else:\n handler.addQuickElement(u'georss:point', self.georss_coords((coords,)))", "def point(x=0.,y=0.,z=0.):\n return Formex([[[x,y,z]]])", "def __create_coord(self, position, representation, args):\n if len(position) < 2:\n raise CoordinateError(\"You need at least two coordinates\")\n if representation == 'unitspherical':\n return self.__create_unitspherical_coord(position, args)\n elif representation == 'spherical':\n return self.__create_spherical_coord(position, args)\n elif representation == 'cartesian':\n return self.__create_cartesian_coord(position, args)\n else:\n raise RepresentationError(\"The representation {0} is not yet supported\".format(self.repr))", "def from_coords(cls, curve_name, x, y):\n return EllipticCurvePoint(curve_name=curve_name, x_coord=x, y_coord=y)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the cumulative mean of the input.
def cummean(self) -> NumericColumn: return ops.CumulativeMean(self).to_expr()
[ "def running_mean(x, N): \n cumsum = np.cumsum(np.insert(x, 0, 0)) \n return (cumsum[N:] - cumsum[:-N]) / float(N)", "def calculate_mean(self):\n\t\t\t\t\t\n avg = 1.0 * sum(self.data) / len(self.data)\n\t\t\n self.mean = avg\n \n return self.mean", "def running_mean(x, N):\n # cumsum = np.cumsum(np.insert(x, 0, 0))\n # return (cumsum[N:] - cumsum[:-N]) / float(N)\n return uniform_filter1d(x, size=N)", "def mean(X):\n return(float(sum(X))/ len(X))", "def mean(self) -> float:\n return mean(self.iterable)", "def mean(self):\r\n\t\treturn np.mean(self.dataset)", "def update_mean(X):\n\n return X.sum(axis=0) / X.shape[0]", "def get_avg(self):\n\t\treturn self.sum / max(len(self.window), 1)", "def mean(self):\n nelem = 0\n sum = 0.\n for win in self._data:\n nelem += win.size\n sum += win.sum()\n return sum / float(nelem)", "def _mean(img):\n res = img - np.mean(img)\n res[res < 0] = 0\n return res", "def _mean(self):\n mat = self._factorize(self.matrix, self.xdef)\n mat = self._rdc_x(mat, self.xdef)\n ysects = self._by_ysect(mat, self.ydef)\n return np.expand_dims([np.nansum(ymat[:, 0] /\n np.nansum(ymat[:, -1]))\n for ymat in ysects], 1).T", "def running_mean(x, N):\n if len(np.shape(x)) == 1:\n cumsum = np.cumsum(np.insert(x, 0, 0))\n return (cumsum[N:] - cumsum[:-N]) / N\n elif len(np.shape(x)) == 2:\n # Apply same reasoning to the array row-by-row\n dmyi = 0\n for row in x:\n tmpsum = np.cumsum(np.insert(row, 0, 0))\n outrow = (tmpsum[N:] - tmpsum[:-N]) / N\n if dmyi == 0:\n outarray = np.zeros((np.shape(x)[0], len(outrow)), dtype=x.dtype)\n outarray[dmyi, :] = outrow\n dmyi += 1\n\n return outarray\n else:\n raise RuntimeError('Input array x in running_mean(x, N) must be 1d or 2d.')", "def mean(self):\n return self.get_samples().mean(0)", "def mean(self):\n return self.value", "def estimated_mean(self):\n estimands=scipy.array(list(itertools.chain(*self.estimands)))\n return sum(estimands)/float(len(estimands))", "def mean(self):\n return self.counts.mean()", "def mean(self):\n return np.mean(self.rate)", "def mean(a):\n return sum(a) / float(len(a))", "def running_mean(data, npoints): \n y = np.convolve(data,1.0/npoints*np.ones(npoints),mode=\"same\")\n return y[npoints/2:-npoints/2]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the cumulative sum of the input.
def cumsum(self) -> NumericColumn: return ops.CumulativeSum(self).to_expr()
[ "def cumsum(self, axis=0):\n return self.apply(lambda x: x.cumsum(), axis=axis)", "def cumsum(x, axis=0):\n\treturn tf.cumsum(x, axis=axis)", "def cumsum1(t):\n result = []\n for i in range(len(t)):\n stop = i + 1\n accu = sum(t[:stop])\n result.append(accu)\n return result", "def cumsum(self):\n cum = self.copy()\n for ncol in range(2, self.num_columns) :\n lbl = cum.labels[ncol]\n cum[lbl] = cum[ncol-1] + cum[ncol]\n return cum", "def cumsum(self, dim, dtype=None): # real signature unknown; restored from __doc__\n pass", "def cumsum(a, axis=None, dtype=None, out=None):\n return _math.scan_core(a, axis, _math.scan_op.SCAN_SUM, dtype, out)", "def cumsum(t):\n \n res = []\n cumulative_sum = 0\n for s in t:\n cumulative_sum += s\n res.append(cumulative_sum)\n return(res)", "def cumsum(array):\n if len(array) <= 1:\n return list(array)\n ret = list(array)\n for i in xrange(1, len(ret)):\n ret[i] += ret[i - 1]\n return ret", "def cumulative_sum(num_list):\n b = 0\n new_list = []\n for i in range(len(num_list)):\n b += num_list[i]\n new_list.append(b)\n return new_list", "def cumsum(\n self, axis, masked_as_zero=False, coordinate=None, inplace=False\n ):\n # TODODASKAPI\n if masked_as_zero:\n _DEPRECATION_ERROR_KWARGS(\n self,\n \"cumsum\",\n {\"masked_as_zero\": None},\n message=\"\",\n version=\"3.14.0\",\n removed_at=\"5.0.0\",\n ) # pragma: no cover\n\n # TODODASKAPI\n if coordinate is not None:\n _DEPRECATION_ERROR_KWARGS(\n self,\n \"cumsum\",\n {\"coordinate\": None},\n message=\"\",\n version=\"3.14.0\",\n removed_at=\"5.0.0\",\n ) # pragma: no cover\n\n # Retrieve the axis\n axis_key, domain_axis = self.domain_axis(\n axis, item=True, default=(None, None)\n )\n if axis_key is None:\n raise ValueError(f\"Invalid axis specifier: {axis!r}\")\n\n # Construct new field\n f = _inplace_enabled_define_and_cleanup(self)\n\n # Get the axis index\n axis_index = f.get_data_axes().index(axis_key)\n\n f.data.cumsum(axis_index, inplace=True)\n\n if domain_axis.get_size() > 1:\n # Update the bounds of the summed axis\n coord = f.dimension_coordinate(\n filter_by_axis=(axis_key,), default=None\n )\n if coord is not None and coord.has_bounds():\n bounds = coord.get_bounds_data(None)\n if bounds is not None:\n bounds[:, 0] = bounds[0, 0]\n\n # Add a cell method\n f._update_cell_methods(\n method=\"sum\", domain_axes={axis_key: domain_axis}\n )\n\n return f", "def cumulative_sum(values):\n cumulative_values = []\n cumulative_value = 0.0\n\n for value in values:\n cumulative_value += value\n cumulative_values.append(cumulative_value)\n\n return cumulative_values", "def cumsum(ls):\n \n acc = 0\n r = [0 for v in ls]\n for i,v in enumerate(ls):\n acc += v\n\tr[i] = acc\n return r", "def cumsum(name, checkpoint, num, gpu=None):\n # Setup output directories\n directory = cargan.EVAL_DIR / 'objective' / 'cumsum' / name\n directory.mkdir(exist_ok=True, parents=True)\n\n # Evaluate at various lengths\n results = {}\n for length in [1024, 2048, 4096, 8192, 'full']:\n\n # Setup RMSE metric\n l1 = cargan.evaluate.objective.metrics.L1()\n\n # Setup data loader\n loader = cargan.data.loaders('cumsum')[2]\n iterator = tqdm.tqdm(\n loader,\n dynamic_ncols=True,\n desc='Cumsum evaluation',\n total=num)\n for i, (cumsum_input, cumsum_output, _, _) in enumerate(iterator):\n\n # Stop once we've generated enough\n if i > num:\n break\n\n # Get directory to save results for this trial\n trial_directory = directory / str(i) / str(length)\n trial_directory.mkdir(exist_ok=True, parents=True)\n\n # Maybe truncate\n if length != 'full':\n cumsum_input = cumsum_input[:, :, :length]\n cumsum_output = cumsum_output[:, :, :length]\n\n # Infer\n cumsum_pred = cargan.from_features(cumsum_input, checkpoint, gpu)\n\n # Place target on device\n device = torch.device('cpu' if gpu is None else f'cuda:{gpu}')\n cumsum_output = cumsum_output.to(device)\n\n # Update metric\n l1.update(cumsum_output, cumsum_pred)\n\n # Save all for later plotting\n with cargan.data.chdir(trial_directory):\n torch.save(cumsum_input.cpu(), 'cumsum_input.pt')\n torch.save(cumsum_output.cpu(), 'cumsum_output.pt')\n torch.save(cumsum_pred.cpu(), 'cumsum_pred.pt')\n \n # Save result for this length\n results[str(length)] = l1()\n \n # Write results\n with open(directory / f'{name}.json', 'w') as file:\n json.dump(results, file, ensure_ascii=False, indent=4)\n\n # Print to stdout\n print(results)", "def sum(self):\n return sum(sum(r) for r in self.data)", "def reducer_cumsum(event, data):\n text = event[1]\n val = 0\n try:\n val=int(text)\n except Exception as e:\n action =('ERROR', 'not an int')\n return action, {}\n\n data.setdefault('cumsum',0)\n data['cumsum'] += val\n\n return (\"SEND\",f\"Sum is {data['cumsum']}\"), data", "def cumsum2_elem(t, pos):\n if pos == 0:\n return t[0]\n else:\n return cumsum2_elem(t, pos-1) + t[pos]", "def sum(x):\n\treturn np.sum(x)", "def sum(self):\n return np.sum(self.data)", "def exclusive_cumsum(xs):\n assert len(xs.size()) == 2\n return torch.cumsum(torch.cat([xs.new_ones(xs.size(0), 1), xs], dim=1)[:, :-1], dim=1)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute a histogram with fixed width bins.
def histogram( self, nbins: int | None = None, binwidth: float | None = None, base: float | None = None, eps: float = 1e-13, ): if nbins is not None and binwidth is not None: raise ValueError( f"Cannot pass both `nbins` (got {nbins}) and `binwidth` (got {binwidth})" ) if binwidth is None or base is None: if nbins is None: raise ValueError("`nbins` is required if `binwidth` is not provided") if base is None: base = self.min() - eps binwidth = (self.max() - base) / nbins return ((self - base) / binwidth).floor()
[ "def binarize(i, bins):\n\n hist, edges = np.histogram(i, bins=bins, range=[10, 2000], normed=True)\n edges = (edges[:-1] + edges[1:])/2\n hist *= edges\n\n return hist", "def get_bin_widths(hi):\n\n return [hi.GetBinWidth(i) for i in range(1, hi.GetNbinsX()+1)]", "def _calc_histogram_bins(count):\n max_bins, max_per_bin = 90, 10\n\n if not count:\n return 1\n if count <= 5:\n return 2\n if count <= 10:\n return 3\n if count <= 880:\n # note that math.ceil(881/10) + 1 equals 90\n return count // max_per_bin + 1\n\n return max_bins", "def _create_bins(self):\n min_conf = self.data[self.conf].min()\n max_conf = self.data[self.conf].max()\n\n if self.bin_width == -1:\n self.bin_width = (max_conf - min_conf)/100\n if self.bin_spacing == -1:\n self.bin_spacing = (max_conf - min_conf)/10\n\n # define the bins (according to width)\n self.bins = np.arange(min_conf, max_conf + self.bin_width, self.bin_spacing)\n return self.bins", "def histogram(self):\n out = Bin(len(self.values), self.low, self.high, self.quantity, None,\n self.underflow.copy(), self.overflow.copy(), self.nanflow.copy())\n out.entries = float(self.entries)\n for i, v in enumerate(self.values):\n out.values[i] = Count.ed(v.entries)\n return out.specialize()", "def binWidth(binBounds):\n return binBounds[1:] / binBounds[:-1]", "def plot_histogram(self, nbin=10, width=0.01,\n *args, **kwargs):\n\n adjuster = 0.00001\n bins = np.linspace(self.min - adjuster, self.max, nbin)\n ncols = []\n velocity = []\n lower_v = self.min - adjuster\n upper_v = 0\n\n for upper_v in bins:\n ncol = 0\n for v in self.velocity['velocity']:\n if lower_v < v <= upper_v:\n ncol += 1\n\n velocity.append((lower_v + upper_v)/2.)\n ncols.append(ncol)\n lower_v = upper_v - adjuster\n\n velocity.append(upper_v + adjuster)\n ncols.append(0)\n\n plt.bar(velocity, ncols, width, *args, **kwargs)", "def histogram(\n x: Tensor,\n bins: int = 10,\n low: float = 0.,\n upp: float = 0.,\n **kwargs,\n) -> Tensor:\n\n return histogramdd(x.view(-1, 1), bins, low, upp, **kwargs)", "def get_optimal_binning(hist, min_count=10, default_width=0.1, bin_prec=3, smooth_bkg=False):\n new_bins = [1]\n last_bin_edge = 1\n count = 0\n bin_numbers = list(range(1, hist.GetNbinsX() + 1))\n bin_numbers.reverse()\n first_merge = True\n last_count = 0\n for i in bin_numbers:\n count += hist.GetBinContent(i)\n bin_low_edge = round(hist.GetBinLowEdge(i), bin_prec)\n if count >= min_count and (not smooth_bkg or count >= last_count):\n current_bin_width = round(abs(last_bin_edge - bin_low_edge), bin_prec)\n if smooth_bkg or (first_merge or current_bin_width >= default_width):\n new_bins.append(bin_low_edge)\n last_bin_edge = bin_low_edge\n last_count = count\n count = 0\n first_merge = False\n if new_bins[-1] != -1: # last bin has to few entries\n new_bins[-1] = -1 # merge with previous bin\n new_bins.reverse()\n return new_bins", "def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:\n pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon)\n\n return pdf", "def hist(self, x, bins=10, normed=0, bottom=None,\n align='edge', orientation='vertical', width=None,\n log=False, **kwargs):\n if not self._hold: self.cla()\n n, bins = npy.histogram(x, bins, range=None, normed=normed)\n if width is None: width = 0.9*(bins[1]-bins[0])\n if orientation == 'horizontal':\n patches = self.barh(bins, n, height=width, left=bottom,\n align=align, log=log)\n elif orientation == 'vertical':\n patches = self.bar(bins, n, width=width, bottom=bottom,\n align=align, log=log)\n else:\n raise ValueError, 'invalid orientation: %s' % orientation\n for p in patches:\n p.update(kwargs)\n return n, bins, cbook.silent_list('Patch', patches)", "def make_bin_edges(numbins, center, binwidth):\n\n start = center - (numbins * binwidth / 2)\n stop = center + (numbins * binwidth / 2)\n\n bins_linspace = np.linspace(start=start, stop=stop, num=numbins + 1)\n\n return bins_linspace", "def histogram1d(x, bins, range):\n\n nx = bins\n xmin, xmax = range\n\n if not np.isfinite(xmin):\n raise ValueError(\"xmin should be finite\")\n\n\n if not np.isfinite(xmax):\n raise ValueError(\"xmax should be finite\")\n\n if xmax <= xmin:\n raise ValueError(\"xmax should be greater than xmin\")\n\n if nx <= 0:\n raise ValueError(\"nx should be strictly positive\")\n\n x = np.ascontiguousarray(x, np.float)\n\n return _histogram1d(x, nx, xmin, xmax)", "def histogram(*args):\n return _seb.histogram(*args)", "def bin_widths(self):\n if self._bin_widths is None:\n self._bin_widths = np.abs(np.diff(self.bin_edges.m)) * self.units\n return self._bin_widths", "def spectrum_bins(signal):\n len_arr = len(signal)\n return spectrum_bins_by_length(len_arr)", "def spectrum_bins_by_length(len_signal):\n freqs = fftfreq(len_signal)[:len_signal // 2]\n freqs[1:] = 1.0 / freqs[1:]\n return freqs", "def n_bins(self):\n return self.num", "def area_width_hist(self, data):\n hist, _, _ = np.histogram2d(\n np.log10(data['area']),\n np.log10(data['range_50p_area']),\n range=self.config['area_vs_width_bounds'],\n bins=self.config['area_vs_width_nbins'])\n return hist.T" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an integral UNIX timestamp to a timestamp expression.
def to_timestamp( self, unit: Literal["s", "ms", "us"] = "s", ) -> ir.TimestampValue: return ops.TimestampFromUNIX(self, unit).to_expr()
[ "def convert_to_unix(timestamp):\n return (timestamp - pd.Timestamp(\"1970-01-01\")) // pd.Timedelta('1s')", "def binary_time_to_unix_time(x):\n device_time_bytes = x[3:].strip()\n return float(struct.unpack(\"<L\", device_time_bytes)[0])", "def to_timestamp(val):\r\n # If we're given a number, give it right back - it's already a timestamp.\r\n if isinstance(val, numbers.Number):\r\n return val\r\n elif isinstance(val, six.string_types):\r\n dt = _parse_datetime_string(val)\r\n else:\r\n dt = val\r\n return time.mktime(dt.timetuple())", "def convert_unix_to_date(timestamp):\n return datetime.fromtimestamp(int(timestamp) / 1000).isoformat()", "def longunix_to_time(timestamp_ms):\r\n return datetime.fromtimestamp(timestamp_ms/1000)", "def convert_to_timestamp(unix):\n return pd.to_datetime(unix, unit='s')", "def _datetime_to_timestamp(input_date):\n return int(time.mktime(input_date.timetuple()))", "def _unix_time_2_normal(unix_date_time):\n\n unix_datetime_in_seconds = unix_date_time/1000 # For some reason they are given in miliseconds\n date = dt.datetime.fromtimestamp(int(unix_datetime_in_seconds))\n return date", "def timestamp(value, *args, timezone: str | None = None) -> ir.TimestampScalar:\n if isinstance(value, (numbers.Real, ir.IntegerValue)):\n if timezone:\n raise NotImplementedError(\"timestamp timezone not implemented\")\n if not args:\n raise TypeError(f\"Use ibis.literal({value}).to_timestamp() instead\")\n return ops.TimestampFromYMDHMS(value, *args).to_expr()\n elif isinstance(value, (Deferred, ir.Expr)):\n # TODO(kszucs): could call .cast(dt.timestamp) for certain value expressions\n raise NotImplementedError(\n \"`ibis.timestamp` isn't implemented for expression inputs\"\n )\n else:\n value = normalize_datetime(value)\n tzinfo = normalize_timezone(timezone or value.tzinfo)\n timezone = tzinfo.tzname(value) if tzinfo is not None else None\n return literal(value, type=dt.Timestamp(timezone=timezone))", "def timestamp_datetime(timestamp):\n return datetime.fromtimestamp(timestamp / 1000000000.0)", "def convert_timestamp_from_prtg(prtg_timestamp):\n datetime_value = datetime.fromtimestamp((float(prtg_timestamp)-25569)* 86400)\n return datetime_value", "def gen_ms_timestamp(timestamp: Union[float, int]) -> int:\n discovergy_ts = str(timestamp).replace(\".\", \"\")\n discovergy_ts = (discovergy_ts + \"000\")[:13]\n return int(discovergy_ts)", "def ms_timestamp_to_epoch_timestamp(ts: int) -> int:\n return int(ts / 1000)", "def str_to_timestamp( s ):\n time_tuple = datetime.datetime.strptime( s, '%Y-%m-%d').timetuple()\n return int( time.mktime( time_tuple ) ) * 1000", "def firefox_time(x):\n\ttry:\n\t\treturn (datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=x)).timestamp()\n\texcept TypeError:\n\t\treturn 0", "def TimestampFromTicks(ticks, micro=0):\n return Timestamp(*time.localtime(ticks)[:6] + (micro,))", "def epoch_timestamp_to_ms_timestamp(ts: int) -> int:\n return int(ts * 1000)", "def timestamp2datetime(x):\n return datetime.datetime.fromtimestamp(x)", "def unixepoch_millisec_to_humantime(unixepoch):\n return datetime.datetime.fromtimestamp(unixepoch / 1000)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an integer to an interval.
def to_interval( self, unit: Literal["Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ns"] = "s", ) -> ir.IntervalValue: return ops.IntervalFromInteger(self, unit).to_expr()
[ "def remap_interval(val,input_interval_start,input_interval_end,output_interval_start,output_interval_end):\n num = (float(val - input_interval_start) * float(output_interval_end - output_interval_start)) \n denom = float(input_interval_end - input_interval_start) \n scaled_val = (num/denom)+ output_interval_start\n return scaled_val", "def remap_interval(val,\n input_interval_start,\n input_interval_end,\n output_interval_start,\n output_interval_end):\n if(val > input_interval_end or val < input_interval_start): #checks val in input range\n return 0\n input_interval_length = input_interval_end - input_interval_start #take input difference\n output_interval_length = output_interval_end - output_interval_start #take output difference\n if(input_interval_length == 0 or output_interval_length == 0): # checks division by 0\n return 0\n input_interval_ratio = 1.0*(val - input_interval_start)/ input_interval_length #create the scaling factor\n \n return input_interval_ratio*output_interval_length + output_interval_start #scale input to output, and add output start", "def fromInt(num: np.int) -> int:\n return int(num)", "def str2interval(value: str) -> Union[interval, set]:\n _value = value.strip()\n\n INTERVAL_SEP = ':'\n BT_SEP = '>'\n ST_SEP = '<'\n if INTERVAL_SEP in _value:\n start, end = _value.split(INTERVAL_SEP)\n elif BT_SEP in _value:\n start = _value.split(BT_SEP)[-1]\n end = inf\n elif ST_SEP in _value:\n start = -inf\n end = _value.split(ST_SEP)[-1]\n else:\n raise ValueError('`{}` is not a proper interval'.format(value))\n\n try:\n if start != -inf:\n start = int(start)\n if end != inf:\n end = int(end)\n except ValueError:\n start = float(start)\n end = float(end)\n\n if isinstance(start, int) and isinstance(end, int):\n value_interval = set(range(start, end + 1))\n else:\n value_interval = interval[start, end]\n\n return value_interval", "def _get_interval_id(t):\n if t < MIN_TIME_BUDGET:\n return 0\n\n if ((t-MIN_TIME_BUDGET) % BUDGET_TIME_INTVL) == 0:\n return int((t-MIN_TIME_BUDGET) % BUDGET_TIME_INTVL)\n\n return int((t-MIN_TIME_BUDGET) % BUDGET_TIME_INTVL) + 1", "def convert_reps_to_int(val):\n return int(val)", "def _get_interval(x, intervals):\n n = len(intervals)\n if n < 2:\n return intervals[0]\n n2 = int(n / 2)\n if x < intervals[n2][0]:\n return spline._get_interval(x, intervals[:n2])\n else:\n return spline._get_interval(x, intervals[n2:])", "def parse(interval):\n if isinstance(interval, (list, tuple)):\n return Interval(*interval)\n elif isinstance(interval, Interval):\n return deepcopy(interval)\n else:\n raise TypeError(\"interval unrecognized\")", "def get_integer_format(self, optree):\n int_range = optree.get_interval()\n if int_range == None:\n return self.default_integer_format\n elif inf(int_range) < 0:\n # signed\n if sup(int_range) > 2**31-1 or inf(int_range) < -2**31:\n return ML_Int64\n else:\n return ML_Int32\n else:\n # unsigned\n if sup(int_range) >= 2**32-1:\n return ML_UInt64\n else:\n return ML_UInt32", "def int2Val(value):\n return Value('i', value, lock=False)", "def step_int(start: int, end: int, t: float) -> int:\n return int(start + (end - start) * t)", "def integers(min_value=None, max_value=None):\n\n check_valid_integer(min_value)\n check_valid_integer(max_value)\n check_valid_interval(min_value, max_value, 'min_value', 'max_value')\n\n from hypothesis.searchstrategy.numbers import IntegersFromStrategy, \\\n BoundedIntStrategy, WideRangeIntStrategy\n\n if min_value is None:\n if max_value is None:\n return (\n WideRangeIntStrategy()\n )\n else:\n return IntegersFromStrategy(0).map(lambda x: max_value - x)\n else:\n if max_value is None:\n return IntegersFromStrategy(min_value)\n else:\n assert min_value <= max_value\n if min_value == max_value:\n return just(min_value)\n elif min_value >= 0:\n return BoundedIntStrategy(min_value, max_value)\n elif max_value <= 0:\n return BoundedIntStrategy(-max_value, -min_value).map(\n lambda t: -t\n )\n else:\n return integers(min_value=0, max_value=max_value) | \\\n integers(min_value=min_value, max_value=0)", "def parse_interval(input):\r\n output = input.replace(']', '[').replace('(', '[').replace(')', '[').replace(',', '[').split('[')[-3:-1]\r\n if output[0] == 'lower':\r\n output[0] = -99999999999\r\n else:\r\n output[0] = float(output[0])\r\n if output[1] == 'higher':\r\n output[1] = 99999999999\r\n else:\r\n output[1] = float(output[1])\r\n\r\n return output", "def __new__(\n cls,\n lower_or_tuple: int | tuple[int, int],\n upper: int | None = None,\n ) -> CycleInterval:\n if upper is not None and not is_integer(upper):\n raise TypeError(\n f'Expected int or None for upper, got {type(upper)}.',\n )\n\n if isinstance(lower_or_tuple, tuple):\n if not CycleInterval.is_interval(lower_or_tuple):\n raise TypeError('Expected two integer arguments.')\n\n if upper is not None:\n raise ValueError('Unable to handle extra argument.')\n\n lower = lower_or_tuple[0]\n upper = lower_or_tuple[1]\n\n elif is_integer(lower_or_tuple) and is_integer(upper):\n lower = lower_or_tuple\n\n elif is_integer(lower_or_tuple) and upper is None:\n raise ValueError('Expected two integer arguments.')\n\n else:\n raise TypeError('Expected two integer arguments.')\n\n if lower > upper:\n raise ValueError(\n 'Expected lower to be <= upper, got {lower} <= {upper}.',\n )\n\n if lower < 0:\n raise ValueError(\n 'Expected positive integers, got {lower} and {upper}.',\n )\n\n return super().__new__(cls, (lower, upper)) # type: ignore", "def _adjust_to_interval(self, var):\n var = numpy.nan_to_num(var)\n\n try:\n dim = len(var)\n\n for num, d in izip(var, xrange(dim)):\n var[d] = max(min(self.interval[1], num), self.interval[0])\n except TypeError:\n var = max(min(self.interval[1], var), self.interval[0])\n\n return var", "def interval_to_large_switch(self, interval):\n pass", "def integer_interpolate(start, end, alpha):\n if alpha >= 1:\n return (end - 1, 1.0)\n if alpha <= 0:\n return (start, 0)\n value = int(interpolate(start, end, alpha))\n residue = ((end - start) * alpha) % 1\n return (value, residue)", "def asInt2(*args, **kwargs):\n \n pass", "def integerize(self, v):\n return v if type(v) == int else int(v)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise and `self` with `other`.
def __and__(self, other: IntegerValue) -> IntegerValue: return _binop(ops.BitwiseAnd, self, other)
[ "def AND(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __and__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n\n return bitlist(list(reversed(\n [a & b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __and__(self, other):\n bits = []\n for i in range (0,len(self)):\n bits += [self.bits[i] * other.bits[i]]\n return UInt8(bits=bits)", "def __and__(self, other):\n\n try:\n retval = ComposedAccessControl(self, other, logic='and')\n except TypeError:\n raise TypeError(\n f\"unsupported operand type(s) for &: '{type(self).__name__}' \"\n f\"and '{type(other).__name__}'\"\n )\n return retval", "def __or__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] + other.bits[i]]\n return UInt8(bits=bits)", "def __iand__(self, other):\r\n self.intersection_update(other)\r\n return self", "def __or__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a | b for (a, b) in zip(self.bits, other.bits)]\n )))", "def bitwise_and(src1, src2, dst=..., mask=...) -> dst:\n ...", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def andr(self, register1, register2):\n self.V[register1] = self.V[register1] & self.V[register2]", "def __or__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseOr, self, other)", "def __and__(self, other):\r\n return self.intersection(other)", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __xor__(self, other):\n return self.XOR(other)", "def __xor__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a ^ b for (a, b) in zip(self.bits, other.bits)]\n )))", "def AND(X:cpuByte,Y:cpuByte) -> cpuByte:\r\n returnable:cpuByte=cpuByte()\r\n for position in range(cpuByte._size):\r\n returnable._state[position] = X._state[position] & Y._state[position]\r\n return returnable", "def __add__(self, other):\n return self.componentwise(other, operator.__add__)", "def __xor__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] ^ other.bits[i]]\n return UInt8(bits=bits)", "def opcode_set_register_bitwise_and(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n second_register = self.get_upper_nibble(opcode[1])\n first_register_value = self.registers[first_register]\n second_register_value = self.registers[second_register]\n result = first_register_value & second_register_value\n\n # Perform the instruction\n self.registers[first_register] = result\n logger.debug(f\"Execute Opcode {opcode.hex()}: Set the value of register {first_register} to the bitwise and of itself and the value of register {second_register} ({first_register_value} & {second_register_value} = {result}).\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise or `self` with `other`.
def __or__(self, other: IntegerValue) -> IntegerValue: return _binop(ops.BitwiseOr, self, other)
[ "def __or__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a | b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __or__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] + other.bits[i]]\n return UInt8(bits=bits)", "def __or__(self, other):\r\n return self.union(other)", "def AND(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __and__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n\n return bitlist(list(reversed(\n [a & b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __or__(self, other):\n try:\n retval = ComposedAccessControl(self, other, logic='or')\n except TypeError:\n raise TypeError(\n f\"unsupported operand type(s) for |: '{type(self).__name__}' \"\n f\"and '{type(other).__name__}'\"\n )\n return retval", "def __rxor__(self, other):\n def result(**kwargs):\n \"\"\"Closure for the right exclusive or operator.\"\"\"\n return (\n other(**kwargs) and not self(**kwargs) or\n self(**kwargs) and not other(**kwargs))\n result.__name__ = \"%s ^ %s\" % (other.__name__, self.__name__)\n return alcool(result)", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __and__(self, other):\n bits = []\n for i in range (0,len(self)):\n bits += [self.bits[i] * other.bits[i]]\n return UInt8(bits=bits)", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def __xor__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a ^ b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __and__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseAnd, self, other)", "def __or__(i1, i2):\n return i1.__class__(i1._union(i1, i2))", "def __or__(self, other):\n return ConjunctionDataType(self, other)", "def __or__(self,other):\n if isinstance(other,(float,int,complex)): return self*field_traits.conjugate(other)\t\t# calls __mul__ below (handles \"0\" case)\n elif isinstance(other,_operator_base): return self.space.traits.back_act_on_vec(self,other)\n else: return self.space.traits.dot(self,other)\t\t# checks that both are _member class", "def __xor__(self, other):\n return self.XOR(other)", "def __and__(self, other):\n\n try:\n retval = ComposedAccessControl(self, other, logic='and')\n except TypeError:\n raise TypeError(\n f\"unsupported operand type(s) for &: '{type(self).__name__}' \"\n f\"and '{type(other).__name__}'\"\n )\n return retval", "def opcode_set_register_bitwise_or(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n second_register = self.get_upper_nibble(opcode[1])\n first_register_value = self.registers[first_register]\n second_register_value = self.registers[second_register]\n result = first_register_value | second_register_value\n\n # Perform the instruction\n self.registers[first_register] = result\n logger.debug(f\"Execute Opcode {opcode.hex()}: Set the value of register {first_register} to the bitwise or of itself and the value of register {second_register} ({first_register_value} | {second_register_value} = {result}).\")", "def __xor__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] ^ other.bits[i]]\n return UInt8(bits=bits)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise xor `self` with `other`.
def __xor__(self, other: IntegerValue) -> IntegerValue: return _binop(ops.BitwiseXor, self, other)
[ "def __xor__(self, other):\n return self.XOR(other)", "def __xor__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] ^ other.bits[i]]\n return UInt8(bits=bits)", "def __xor__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a ^ b for (a, b) in zip(self.bits, other.bits)]\n )))", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __xor__(self, other):\r\n return self.symmetric_difference(other)", "def xor(x, y):\r\n return ((x or y) and (not (x and y)))", "def __or__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a | b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __or__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] + other.bits[i]]\n return UInt8(bits=bits)", "def xor( a, b ):\n return bool( a ) != bool( b )", "def opcode_set_register_bitwise_xor(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n second_register = self.get_upper_nibble(opcode[1])\n first_register_value = self.registers[first_register]\n second_register_value = self.registers[second_register]\n result = first_register_value ^ second_register_value\n\n # Perform the instruction\n self.registers[first_register] = result\n logger.debug(f\"Execute Opcode {opcode.hex()}: Set the value of register {first_register} to the bitwise xor of itself and the value of register {second_register} ({first_register_value} ^ {second_register_value} = {result}).\")", "def __or__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseOr, self, other)", "def __eq__(self, other):\n raise OpNotAllowedError(\"A CryptoBit cannot be compared directly\")", "def __and__(self, other):\n bits = []\n for i in range (0,len(self)):\n bits += [self.bits[i] * other.bits[i]]\n return UInt8(bits=bits)", "def __and__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n\n return bitlist(list(reversed(\n [a & b for (a, b) in zip(self.bits, other.bits)]\n )))", "def AND(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __rxor__(self, other):\n def result(**kwargs):\n \"\"\"Closure for the right exclusive or operator.\"\"\"\n return (\n other(**kwargs) and not self(**kwargs) or\n self(**kwargs) and not other(**kwargs))\n result.__name__ = \"%s ^ %s\" % (other.__name__, self.__name__)\n return alcool(result)", "def __xor__(self, argument):\n argument = type(self)(argument)\n result = self._collection.__xor__(argument._collection)\n result = type(self)(result)\n return result", "def _xor(self, p2):\n if len(self.coeffs) > len(p2.coeffs):\n poly_long, poly_short = self, p2\n else:\n poly_long, poly_short = p2, self \n result = []\n for i, val_short in enumerate(poly_short.coeffs):\n if val_short == poly_long.coeffs[i]:\n result.append(0)\n else:\n result.append(1)\n result.extend(poly_long.coeffs[len(poly_short.coeffs):])\n return Polynomial2(result)", "def bytes_xor(a: bytes, b: bytes) -> bytes: # pylint: disable=invalid-name\n if len(a) != len(b):\n raise ValueError(\"Length of a and b must be equal.\")\n return (int.from_bytes(a, \"big\") ^ int.from_bytes(b, \"big\")).to_bytes(len(a), \"big\")" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise left shift `self` with `other`.
def __lshift__(self, other: IntegerValue) -> IntegerValue: return _binop(ops.BitwiseLeftShift, self, other)
[ "def __rlshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseLeftShift, other, self)", "def __lshift__(self, other):\n newBits = []\n testOverflow = PlainBit(False)\n for i in xrange(0,len(self)-other):\n newBits += [self.bits[i+other]]\n for i in xrange(i+1,len(self)):\n testOverflow += self.bits[len(self)-1-i]\n newBits += [PlainBit(False)]\n newInt = UInt8(bits=newBits)\n newInt.testOverflow = testOverflow\n return newInt", "def __rshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseRightShift, self, other)", "def __rrshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseRightShift, other, self)", "def __rshift__(self, other):\n newBits = []\n for i in xrange(0, other+1):\n newBits += [self.bits[0]]\n for i in xrange(i + 1, len(self)):\n newBits += [self.bits[i-other]]\n newInt = UInt8(bits=newBits)\n return newInt", "def __and__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n\n return bitlist(list(reversed(\n [a & b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __and__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseAnd, self, other)", "def AND(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __and__(self, other):\n bits = []\n for i in range (0,len(self)):\n bits += [self.bits[i] * other.bits[i]]\n return UInt8(bits=bits)", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def test_left_shift(self):\n shifted = self.leet << 3\n self.assertEqual(shifted, bitmath.Bit(10696))", "def __or__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a | b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __or__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] + other.bits[i]]\n return UInt8(bits=bits)", "def opcode_bit_shift_right(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n first_register_value = self.registers[first_register]\n bit_shift = first_register_value >> 1\n least_significant_bit = first_register_value & 1\n\n # Perform the instruction\n self.registers[first_register] = bit_shift\n self.registers[15] = least_significant_bit\n logger.debug(f\"Execute Opcode {opcode.hex()}: Shift the value of register {first_register} to the right by 1 ({first_register_value} >> 1 = {bit_shift}, previous least significant bit = {least_significant_bit}).\")", "def __lshift__(self, val):\n if isinstance(val, numbers.Number):\n new = self.copy()\n new._abscissa_vals -= val\n new._abscissa.support = new._abscissa.support << val\n return new\n else:\n raise TypeError(\"unsupported operand type(s) for <<: {} and {}\".format(str(type(self)), str(type(val))))", "def __xor__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a ^ b for (a, b) in zip(self.bits, other.bits)]\n )))", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __xor__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] ^ other.bits[i]]\n return UInt8(bits=bits)", "def __iadd__(self, other):\n for k, v in other.store.items():\n self.store[k] |= v\n\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise left shift `self` with `other`.
def __rlshift__(self, other: IntegerValue) -> IntegerValue: return _binop(ops.BitwiseLeftShift, other, self)
[ "def __lshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseLeftShift, self, other)", "def __lshift__(self, other):\n newBits = []\n testOverflow = PlainBit(False)\n for i in xrange(0,len(self)-other):\n newBits += [self.bits[i+other]]\n for i in xrange(i+1,len(self)):\n testOverflow += self.bits[len(self)-1-i]\n newBits += [PlainBit(False)]\n newInt = UInt8(bits=newBits)\n newInt.testOverflow = testOverflow\n return newInt", "def __rshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseRightShift, self, other)", "def __rrshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseRightShift, other, self)", "def __rshift__(self, other):\n newBits = []\n for i in xrange(0, other+1):\n newBits += [self.bits[0]]\n for i in xrange(i + 1, len(self)):\n newBits += [self.bits[i-other]]\n newInt = UInt8(bits=newBits)\n return newInt", "def __and__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n\n return bitlist(list(reversed(\n [a & b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __and__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseAnd, self, other)", "def AND(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __and__(self, other):\n bits = []\n for i in range (0,len(self)):\n bits += [self.bits[i] * other.bits[i]]\n return UInt8(bits=bits)", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def test_left_shift(self):\n shifted = self.leet << 3\n self.assertEqual(shifted, bitmath.Bit(10696))", "def __or__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a | b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __or__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] + other.bits[i]]\n return UInt8(bits=bits)", "def opcode_bit_shift_right(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n first_register_value = self.registers[first_register]\n bit_shift = first_register_value >> 1\n least_significant_bit = first_register_value & 1\n\n # Perform the instruction\n self.registers[first_register] = bit_shift\n self.registers[15] = least_significant_bit\n logger.debug(f\"Execute Opcode {opcode.hex()}: Shift the value of register {first_register} to the right by 1 ({first_register_value} >> 1 = {bit_shift}, previous least significant bit = {least_significant_bit}).\")", "def __lshift__(self, val):\n if isinstance(val, numbers.Number):\n new = self.copy()\n new._abscissa_vals -= val\n new._abscissa.support = new._abscissa.support << val\n return new\n else:\n raise TypeError(\"unsupported operand type(s) for <<: {} and {}\".format(str(type(self)), str(type(val))))", "def __xor__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a ^ b for (a, b) in zip(self.bits, other.bits)]\n )))", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __xor__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] ^ other.bits[i]]\n return UInt8(bits=bits)", "def __iadd__(self, other):\n for k, v in other.store.items():\n self.store[k] |= v\n\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise right shift `self` with `other`.
def __rshift__(self, other: IntegerValue) -> IntegerValue: return _binop(ops.BitwiseRightShift, self, other)
[ "def __rrshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseRightShift, other, self)", "def __rshift__(self, other):\n newBits = []\n for i in xrange(0, other+1):\n newBits += [self.bits[0]]\n for i in xrange(i + 1, len(self)):\n newBits += [self.bits[i-other]]\n newInt = UInt8(bits=newBits)\n return newInt", "def __rlshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseLeftShift, other, self)", "def __lshift__(self, other):\n newBits = []\n testOverflow = PlainBit(False)\n for i in xrange(0,len(self)-other):\n newBits += [self.bits[i+other]]\n for i in xrange(i+1,len(self)):\n testOverflow += self.bits[len(self)-1-i]\n newBits += [PlainBit(False)]\n newInt = UInt8(bits=newBits)\n newInt.testOverflow = testOverflow\n return newInt", "def __lshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseLeftShift, self, other)", "def opcode_bit_shift_right(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n first_register_value = self.registers[first_register]\n bit_shift = first_register_value >> 1\n least_significant_bit = first_register_value & 1\n\n # Perform the instruction\n self.registers[first_register] = bit_shift\n self.registers[15] = least_significant_bit\n logger.debug(f\"Execute Opcode {opcode.hex()}: Shift the value of register {first_register} to the right by 1 ({first_register_value} >> 1 = {bit_shift}, previous least significant bit = {least_significant_bit}).\")", "def __or__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a | b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __or__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] + other.bits[i]]\n return UInt8(bits=bits)", "def __or__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseOr, self, other)", "def shift_bits_right(binary, amount):\n sign_bit = binary[0]\n return (sign_bit * amount) + binary[:-amount]", "def __and__(self, other):\n bits = []\n for i in range (0,len(self)):\n bits += [self.bits[i] * other.bits[i]]\n return UInt8(bits=bits)", "def __and__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n\n return bitlist(list(reversed(\n [a & b for (a, b) in zip(self.bits, other.bits)]\n )))", "def right_of(self, other):\n\n if not self.is_valid_range(other):\n raise TypeError(\n f\"Right of is not supported for {other.__class__.__name__}, provide a proper range class\"\n )\n\n return other.left_of(self)", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def __rlshift__(self, other: Union[\"TaskMixin\", Sequence[\"TaskMixin\"]]):\n self.__rshift__(other)\n return self", "def __rshift__(self, val):\n if isinstance(val, numbers.Number):\n new = self.copy()\n new._abscissa_vals += val\n new._abscissa.support = new._abscissa.support >> val\n return new\n else:\n raise TypeError(\"unsupported operand type(s) for >>: {} and {}\".format(str(type(self)), str(type(val))))", "def shift(x,y):\n n1 = b2d(x)\n n2 = b2d(y)\n a = n1 << n2\n res = d2b(a,2*len(x))\n return res", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __rrshift__(self, other: Union[\"TaskMixin\", Sequence[\"TaskMixin\"]]):\n self.__lshift__(other)\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise right shift `self` with `other`.
def __rrshift__(self, other: IntegerValue) -> IntegerValue: return _binop(ops.BitwiseRightShift, other, self)
[ "def __rshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseRightShift, self, other)", "def __rshift__(self, other):\n newBits = []\n for i in xrange(0, other+1):\n newBits += [self.bits[0]]\n for i in xrange(i + 1, len(self)):\n newBits += [self.bits[i-other]]\n newInt = UInt8(bits=newBits)\n return newInt", "def __rlshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseLeftShift, other, self)", "def __lshift__(self, other):\n newBits = []\n testOverflow = PlainBit(False)\n for i in xrange(0,len(self)-other):\n newBits += [self.bits[i+other]]\n for i in xrange(i+1,len(self)):\n testOverflow += self.bits[len(self)-1-i]\n newBits += [PlainBit(False)]\n newInt = UInt8(bits=newBits)\n newInt.testOverflow = testOverflow\n return newInt", "def __lshift__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseLeftShift, self, other)", "def opcode_bit_shift_right(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n first_register_value = self.registers[first_register]\n bit_shift = first_register_value >> 1\n least_significant_bit = first_register_value & 1\n\n # Perform the instruction\n self.registers[first_register] = bit_shift\n self.registers[15] = least_significant_bit\n logger.debug(f\"Execute Opcode {opcode.hex()}: Shift the value of register {first_register} to the right by 1 ({first_register_value} >> 1 = {bit_shift}, previous least significant bit = {least_significant_bit}).\")", "def __or__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n return bitlist(list(reversed(\n [a | b for (a, b) in zip(self.bits, other.bits)]\n )))", "def __or__(self, other):\n bits = []\n for i in range(0, len(self)):\n bits += [self.bits[i] + other.bits[i]]\n return UInt8(bits=bits)", "def __or__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseOr, self, other)", "def shift_bits_right(binary, amount):\n sign_bit = binary[0]\n return (sign_bit * amount) + binary[:-amount]", "def __and__(self, other):\n bits = []\n for i in range (0,len(self)):\n bits += [self.bits[i] * other.bits[i]]\n return UInt8(bits=bits)", "def __and__(self: bitlist, other: bitlist) -> bitlist:\n if len(self) != len(other):\n raise ValueError(\n 'arguments to logical operations must have equal lengths'\n )\n\n return bitlist(list(reversed(\n [a & b for (a, b) in zip(self.bits, other.bits)]\n )))", "def right_of(self, other):\n\n if not self.is_valid_range(other):\n raise TypeError(\n f\"Right of is not supported for {other.__class__.__name__}, provide a proper range class\"\n )\n\n return other.left_of(self)", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def __rlshift__(self, other: Union[\"TaskMixin\", Sequence[\"TaskMixin\"]]):\n self.__rshift__(other)\n return self", "def __rshift__(self, val):\n if isinstance(val, numbers.Number):\n new = self.copy()\n new._abscissa_vals += val\n new._abscissa.support = new._abscissa.support >> val\n return new\n else:\n raise TypeError(\"unsupported operand type(s) for >>: {} and {}\".format(str(type(self)), str(type(val))))", "def shift(x,y):\n n1 = b2d(x)\n n2 = b2d(y)\n a = n1 << n2\n res = d2b(a,2*len(x))\n return res", "def XOR(self,other):\n raise OpNotAllowedError(\"Cannot do operation on Bit instance\")", "def __rrshift__(self, other: Union[\"TaskMixin\", Sequence[\"TaskMixin\"]]):\n self.__lshift__(other)\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bitwise not of `self`. Returns IntegerValue Inverted bits of `self`.
def __invert__(self) -> IntegerValue: try: node = ops.BitwiseNot(self) except (IbisTypeError, NotImplementedError): return NotImplemented else: return node.to_expr()
[ "def __invert__(self):\n newInt = self\n bits = []\n for i in xrange(0, len(newInt.bits)):\n bits.append(~newInt.bits[i])\n return UInt8(bits=bits)", "def __invert__(self: bitlist) -> bitlist:\n return bitlist(list(reversed([1-b for b in self.bits])))", "def negate(self):\n return Formula(\"not\", self)", "def invert(self):\n inverse = self.copy()\n inverse.pixels = ~self.pixels\n return inverse", "def __neg__(self) -> \"SbVec2i32\":\n return _coin.SbVec2i32___neg__(self)", "def __neg__(self) -> \"SbVec4ui32\":\n return _coin.SbVec4ui32___neg__(self)", "def __neg__(self) -> \"SbVec4i32\":\n return _coin.SbVec4i32___neg__(self)", "def __neg__(self) -> NumericValue:\n return self.negate()", "def __invert__(self) -> Permissions:\n return Permissions.from_int(~self.to_int())", "def __neg__(self) -> \"SbVec3i32\":\n return _coin.SbVec3i32___neg__(self)", "def inverted_plus_erosion(self):\n\n if isinstance(self.struct_shape, int) is False:\n raise TypeError('structure shape must be an integer')\n shape = np.ones(len(self.image.shape)).astype(int) * self.struct_shape\n erosion = grey_erosion(self.image, size=shape)\n inverse = np.amax(erosion) - erosion\n max_val = np.amax(inverse)\n inverse = inverse / max_val\n inverse *= 100\n return inverse", "def negation(X:cpuByte) -> cpuByte:\r\n returnable:cpuByte=cpuByte()\r\n for position in range(cpuByte._size):\r\n returnable._state[position] = not(X._state[position])\r\n return returnable", "def invert(self) -> 'BitSequence':\n self._seq = bytearray([x ^ 1 for x in self._seq])\n return self", "def __neg__(self):\n result = Scalar._create_raw()\n lib.crypto_core_ed25519_scalar_negate(result._ptr, self._ptr)\n return result", "def bit_underflow_internal(self):\n return self._bit_underflow_internal", "def __xor__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseXor, self, other)", "def bitwise_not(binary):\n return ''.join('1' if bit == '0' else '0' for bit in binary)", "def instruction_NEG(self, inst):\n\t\tsrc1 = self.getOperandOneWord(inst)\n\t\tself.setDestinationWord(inst, ~src1)", "def bitwise_not(expr: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]:\n\n return UnaryExpression._create_bitwise_not(expr)" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aggregate the column using the bitwise and operator.
def bit_and(self, where: ir.BooleanValue | None = None) -> IntegerScalar: return ops.BitAnd(self, where).to_expr()
[ "def bitwise_and_(self, e):\n return self.__lazy_operate(operator.and_, e)", "def __and__(self, other: IntegerValue) -> IntegerValue:\n return _binop(ops.BitwiseAnd, self, other)", "def bitwise_and(src1, src2, dst=..., mask=...) -> dst:\n ...", "def filter_expr(self):\n return lambda df: reduce(and_, [(b.filter_expr()(df)) for b in self.bins])", "def bitwise_and(*binaries):\n def bit_and(bit1, bit2):\n return '1' if int(bit1) & int(bit2) else '0'\n return bitwise_operation(bit_and, binaries)", "def __and__(expr):", "def addBinColumn(df):\n binaries = []\n columns = df.columns\n dff = df.copy()\n for col in dff.columns:\n dff = dff.rename(columns={col: str(col)})\n for _, row in dff.iterrows():\n binary = '0b'\n for col in dff.columns:\n binary = binary + str(int(row[col]))\n binaries.append(int(binary, 2))\n df[cn.VALUE] = binaries", "def instruction_AND(self, inst):\n\t\tsrc1 = self.getOperandOneWord(inst)\n\t\tsrc2 = self.getOperandTwoWord(inst)\n\t\tself.setDestinationWord(inst, src1 & src2)", "def logical_and(x1: ArrayOrScalar, x2: ArrayOrScalar) -> Union[Array, bool]:\n # https://github.com/python/mypy/issues/3186\n import pytato.utils as utils\n return utils.broadcast_binary_op(x1, x2,\n lambda x, y: prim.LogicalAnd((x, y)),\n lambda x, y: np.bool8) # type: ignore", "def opcode_set_register_bitwise_and(self, opcode: bytes) -> None:\n # Get the necessary information from the opcode\n first_register = self.get_lower_nibble(opcode[0])\n second_register = self.get_upper_nibble(opcode[1])\n first_register_value = self.registers[first_register]\n second_register_value = self.registers[second_register]\n result = first_register_value & second_register_value\n\n # Perform the instruction\n self.registers[first_register] = result\n logger.debug(f\"Execute Opcode {opcode.hex()}: Set the value of register {first_register} to the bitwise and of itself and the value of register {second_register} ({first_register_value} & {second_register_value} = {result}).\")", "def _to_binary_mask(self, array):\n # check where the transparency is not zero\n return (array[..., -1] > 0).astype(self.raster_dtype) * self.raster_value", "def bench_ak_bitwise_binops(benchmark, op):\r\n cfg = ak.get_config()\r\n N = pytest.prob_size * cfg[\"numLocales\"]\r\n\r\n a1 = ak.randint(0, 2**32, N, dtype=ak.uint64, seed=pytest.seed)\r\n a2 = ak.randint(0, 2**32, N, dtype=ak.uint64, seed=pytest.seed)\r\n a = ak.bigint_from_uint_arrays([a1, a2], max_bits=pytest.max_bits)\r\n b1 = ak.randint(0, 2**32, N, dtype=ak.uint64, seed=pytest.seed)\r\n b2 = ak.randint(0, 2**32, N, dtype=ak.uint64, seed=pytest.seed)\r\n b = ak.bigint_from_uint_arrays([b1, b2], max_bits=pytest.max_bits)\r\n\r\n # bytes per bigint array (N * 16) since it's made of 2 uint64 arrays\r\n # if max_bits in [0, 64] then they're essentially 1 uint64 array\r\n nbytes = N * 8 if pytest.max_bits != -1 and pytest.max_bits <= 64 else N * 8 * 2\r\n\r\n if op == \"and\":\r\n benchmark.pedantic(_perform_and_binop, args=[a, b], rounds=pytest.trials)\r\n elif op == \"or\":\r\n benchmark.pedantic(_perform_or_binop, args=[a, b], rounds=pytest.trials)\r\n elif op == \"shift\":\r\n benchmark.pedantic(_perform_shift_binop, args=[a], rounds=pytest.trials)\r\n\r\n benchmark.extra_info[\"description\"] = \"Measures the performance of bigint bitwise binops\"\r\n benchmark.extra_info[\"problem_size\"] = pytest.prob_size\r\n benchmark.extra_info[\"transfer_rate\"] = \"{:.4f} GiB/sec\".format(\r\n (nbytes / benchmark.stats[\"mean\"]) / 2**30\r\n )\r\n benchmark.extra_info[\"max_bit\"] = pytest.max_bits # useful when looking at bigint\r", "def test_and() -> None:\n v8 = TestValue(\"A\", IntType.u(8))\n v16 = TestValue(\"B\", IntType.u(16))\n litval = 0x1234\n lit = IntLiteral(litval)\n assert AndOperator(v8, v8).mask == 0xFF\n assert AndOperator(v16, v16).mask == 0xFFFF\n assert AndOperator(lit, lit).mask == litval\n assert AndOperator(v8, v16).mask == 0xFF\n assert AndOperator(v8, lit).mask == litval & 0xFF\n assert AndOperator(v16, lit).mask == litval\n assert AndOperator(v8, v16, lit).mask == litval & 0xFF", "def AND(X:cpuByte,Y:cpuByte) -> cpuByte:\r\n returnable:cpuByte=cpuByte()\r\n for position in range(cpuByte._size):\r\n returnable._state[position] = X._state[position] & Y._state[position]\r\n return returnable", "def col_sum(self):\n\t\treturn(self.sum(axis=1))", "def addBroadcastBits( iAdr, bitCount ):\n # set the broadcast values\n for idx in range( 32-bitCount ):\n iAdr = iAdr | (1 << idx)\n return iAdr", "def __and__(self, other: Selector) -> Selector:\n return self.__class__(lambda col: self.predicate(col) and other.predicate(col))", "def all_(expr: _ColumnExpressionArgument[_T]) -> CollectionAggregate[bool]:\n return CollectionAggregate._create_all(expr)", "def add_operator(self, df: dd.DataFrame, attribute: Record, operator: str, *args):\n _check_attribute(attribute)\n added_operator = self._operator_function[operator](df, attribute.name, *args)\n logger.debug(f\"adding operator {attribute} {operator} {args}\")\n if self.mask is None:\n self.mask = added_operator\n else:\n self.mask = self.mask & added_operator\n logger.debug(f\"{self.mask}\")\n return self" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads meta information from meta file.
def read_meta_from_file(): try: with open(meta_file_name, "r") as meta_file: return json.load(meta_file) except OSError: sys.exit("Could not open/read meta file: meta.json.")
[ "def meta_load_socrata(self):\n import json\n\n meta = self.filesystem.download('meta')\n\n with open(meta) as f:\n d = json.load(f)\n\n md = self.metadata\n md.about.title = d['name']\n md.about.summary = d['description']\n\n md.write_to_dir()", "def get_meta_info(self):\n try:\n info_file = open('metadata.txt', 'r')\n except FileNotFoundError:\n print(\"metadata.txt not found\")\n else:\n table_started = False\n table_name = \"\"\n for ro in info_file:\n if ro.strip() == '<begin_table>':\n table_started = True\n continue\n if ro.strip() == '<end_table>':\n continue\n if table_started:\n table_started = False\n table_name = ro.strip()\n self.tableInfo[table_name] = []\n continue\n # append the column names into the table dict\n self.tableInfo[table_name].append(ro.strip())", "def _load_meta(self):\n\n resourceBase = self.resource.split(\"/\")[0]\n url = \"{base_url}/{resource}/meta\".format(base_url=self.base_url,\n resource=resourceBase)\n\n response = self.get_request(url, verify=self.cert_verify)\n\n if response.status_code == 302:\n raise Exception(\"Received redirect (HTTP 302). Try to switch between http/https protocol\")\n elif response.status_code != 200:\n self._warn(\"Failed to fetch meta information\")\n else:\n try:\n self.metadata = response.json()[\"meta\"][\"fields\"]\n except (ValueError, KeyError, TypeError):\n self._warn(\"Meta information is incorrect\")", "def _readMetadata(self):\r\n if self._mdFile is not None and os.path.exists(self._mdFile):\r\n with open(self._mdFile, 'r') as fp:\r\n return json.load(fp)\r\n return {}", "def readMetadata(fname):\n if isinstance(fname, (tuple, list)):\n fname = fname[0]\n with h5.File(str(fname), \"r\") as inf:\n try:\n metaGrp = inf[\"meta\"]\n lattice = yaml.safe_load(loadString(metaGrp[\"lattice\"]))\n params = yaml.safe_load(loadString(metaGrp[\"params\"]))\n makeActionSrc = loadString(metaGrp[\"action\"])\n versions = {name: loadString(val) for name, val in metaGrp[\"version\"].items()}\n except KeyError as exc:\n getLogger(__name__).error(\"Cannot read metadata from file %s: %s\",\n str(fname), str(exc))\n raise\n return lattice, params, makeActionSrc, versions", "def _read_metadata(self, path='/data/info'):\n base_dir = os.getcwd() + path\n\n # Return if we cannot file the metadata file\n if not os.path.exists(base_dir):\n return\n\n # Read metadata from the file\n with open(f'{base_dir}/metadata', 'r') as f:\n # Process metadata\n raw_data = f.read().strip('\\n')\n metadata = json.loads(raw_data)\n\n # Add data back to the blockchain\n self._bits = metadata['bits']\n self._subsidy = metadata['subsidy']\n self._height = metadata['height']\n self._count = metadata['count']\n self._index = metadata['index']\n self._root_address = metadata['root_address']", "def parse_dist_meta():\n pats = {re_meta: _add_default, re_doc: _add_doc}\n here = os.path.abspath(os.path.dirname(__file__))\n with open(os.path.join(here, NAME, '__about__.py')) as meta_fh:\n distmeta = {}\n for line in meta_fh:\n if line.strip() == '# -eof meta-':\n break\n for pattern, handler in pats.items():\n m = pattern.match(line.strip())\n if m:\n distmeta.update(handler(m))\n return distmeta", "def metadata_load(self):\n path = self.metadata_path // \"metadata.json\"\n if (not path.exists()):\n WARNING(\"no metadata to load; using defaults\")\n self.metadata_init()\n return\n self.metadata = json_from_file(path, \"metadata\")", "def _readMetaInfo(self, validate=None):\n if validate is None:\n validate = self._validate\n data = self._getPlist(METAINFO_FILENAME)\n if validate and not isinstance(data, dict):\n raise UFOLibError(\"metainfo.plist is not properly formatted.\")\n try:\n formatVersionMajor = data[\"formatVersion\"]\n except KeyError:\n raise UFOLibError(\n f\"Missing required formatVersion in '{METAINFO_FILENAME}' on {self.fs}\"\n )\n formatVersionMinor = data.setdefault(\"formatVersionMinor\", 0)\n\n try:\n formatVersion = UFOFormatVersion((formatVersionMajor, formatVersionMinor))\n except ValueError as e:\n unsupportedMsg = (\n f\"Unsupported UFO format ({formatVersionMajor}.{formatVersionMinor}) \"\n f\"in '{METAINFO_FILENAME}' on {self.fs}\"\n )\n if validate:\n from fontTools.ufoLib.errors import UnsupportedUFOFormat\n\n raise UnsupportedUFOFormat(unsupportedMsg) from e\n\n formatVersion = UFOFormatVersion.default()\n logger.warning(\n \"%s. Assuming the latest supported version (%s). \"\n \"Some data may be skipped or parsed incorrectly\",\n unsupportedMsg,\n formatVersion,\n )\n data[\"formatVersionTuple\"] = formatVersion\n return data", "def _parse_meta(self, meta):\n if isinstance(meta, astropy.io.fits.header.Header):\n meta = MetaDict(sunpy.io.header.FileHeader(meta))\n if isinstance(meta, sunpy.timeseries.TimeSeriesMetaData):\n new_meta = MetaDict()\n for m in meta.metas:\n new_meta.update(m)\n meta = new_meta\n return meta", "def read_artdata_file(self, video_id):\n meta_file = os.path.join(self.metadata_path, str(video_id)+'.art')\n if xbmcvfs.exists(meta_file):\n f = xbmcvfs.File(meta_file, 'rb')\n content = f.read()\n f.close()\n meta_data = pickle.loads(content)\n return meta_data\n return", "def readMetadata(data, key):\n if 'metadata' not in data:\n return None\n m = data['metadata']\n if key not in m:\n return None\n return m[key]", "def loadMeta(self):\r\n config = ConfigParser()\r\n config.read(\"data/server.meta\")\r\n specs = ConfigParser()\r\n specs.read(\"data/spectators.meta\")\r\n # Read in the worlds\r\n if config.has_section(\"worlds\"):\r\n for name in config.options(\"worlds\"):\r\n self.worlds[name] = None\r\n if name is \"main\":\r\n self.main_loaded = True\r\n else:\r\n self.worlds[\"main\"] = None\r\n if not self.main_loaded:\r\n self.worlds[\"main\"] = None\r\n # Read in the directors\r\n if config.has_section(\"directors\"):\r\n for name in config.options(\"directors\"):\r\n self.directors.add(name)\r\n # Read in the admins\r\n if config.has_section(\"admins\"):\r\n for name in config.options(\"admins\"):\r\n self.admins.add(name)\r\n # Read in the mods\r\n if config.has_section(\"mods\"):\r\n for name in config.options(\"mods\"):\r\n self.mods.add(name)\r\n # Read in the advanced builders\r\n if config.has_section(\"advbuilders\"):\r\n for name in config.options(\"advbuilders\"):\r\n self.advbuilders.add(name)\r\n if config.has_section(\"silenced\"):\r\n for name in config.options(\"silenced\"):\r\n self.silenced.add(name)\r\n # Read in the spectators\r\n if specs.has_section(\"spectators\"):\r\n for name in specs.options(\"spectators\"):\r\n self.spectators.add(name)\r\n # Read in the bans\r\n if config.has_section(\"banned\"):\r\n for name in config.options(\"banned\"):\r\n self.banned[name] = config.get(\"banned\", name)\r\n # Read in the ipbans\r\n if config.has_section(\"ipbanned\"):\r\n for ip in config.options(\"ipbanned\"):\r\n self.ipbanned[ip] = config.get(\"ipbanned\", ip)", "def test_v2_setting_metas_read(self):\n pass", "async def read_metadata(fobj):\n data = await check_read(fobj, meta_struct.size)\n meta = ldm_meta(*meta_struct.unpack(data))\n logger.debug('LDM metadata: %s', meta)\n prod_ident = await read_byte_string(fobj)\n logger.debug('Got prod_id: %s', prod_ident)\n prod_origin = await read_byte_string(fobj)\n logger.debug('Got origin: %s', prod_origin)\n return prod_ident, meta.prod_len", "def read_file_with_metadata(filename):\n with open(filename, 'r') as f:\n data = f.readlines()\n\n state = 'STARTING'\n mdata = {}\n rval = \"\"\n for line in data:\n if state == 'STARTING' and line.startswith('---'):\n state = 'METADATA'\n elif state == 'STARTING':\n state = 'CONTENT'\n rval = line\n elif state == 'METADATA' and line.startswith('---'):\n state = 'CONTENT'\n elif state == 'METADATA':\n (key, value) = re.split(\":\\s*\", line, 1)\n mdata[key] = value\n elif state == 'CONTENT':\n rval += line\n return(mdata, rval)", "def readExistingMetaData(self: object) -> dict[str, list[str]]:\n\t\twith exiv.Image(f\"{self.rootPath}/{self.fileName}\") as f:\n\t\t\tdata = f.read_xmp()\n\t\treturn data", "def getMetaData(self, filePath): #$NON-NLS-1$\r", "def readMetaInfo(self, validate=None):\n data = self._readMetaInfo(validate=validate)\n self._formatVersion = data[\"formatVersionTuple\"]" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }