code
stringlengths
281
23.7M
class Solution(object): def readBinaryWatch(self, num): def transfer_reading(clock): hour = int(''.join(clock[:4]), 2) minute = int(''.join(clock[4:]), 2) if (hour > 11): return None if (minute > 59): return None return '{}:{:02d}'.format(hour, minute) def gen_cases(num, start=0, clock=None): if (num < 0): return if ((start >= 10) and (num > 0)): return elif ((start >= 10) and (num == 0)): (yield clock) return if (clock is None): clock = (['0'] * 10) clock = list(clock) for gc in gen_cases(num, (start + 1), clock): (yield gc) if (start < 10): clock[start] = '1' for gc in gen_cases((num - 1), (start + 1), clock): (yield gc) ret = [] for clock in gen_cases(num): reading = transfer_reading(clock) if (reading is None): continue ret.append(reading) return ret
class ModuleListTests(unittest.TestCase): class ModuleBase(): pass def setUp(self): self.status_handler = MagicMock() self.ml = util.ModuleList(self.status_handler, ClassFinder(self.ModuleBase)) def test_append_simple(self): module = self.ModuleBase() module.registered = MagicMock() self.ml.append(module) module.registered.assert_called_with(self.status_handler) def _create_module_class(self, name, bases=None): if (not bases): bases = (self.ModuleBase,) return type(name, bases, {'registered': MagicMock(), '__init__': MagicMock(return_value=None)}) def test_append_class_instanciation(self): module_class = self._create_module_class('module_class') self.ml.append(module_class) module_class.__init__.assert_called_with() module_class.registered.assert_called_with(self.status_handler) def test_append_module(self): pymod = types.ModuleType('test_mod') pymod.some_class = self._create_module_class('some_class') pymod.some_class.__module__ = 'test_mod' self.ml.append(pymod) pymod.some_class.__init__.assert_called_with() pymod.some_class.registered.assert_called_with(self.status_handler) def test_append_module2(self): pymod = types.ModuleType('test_mod') pymod.some_class = self._create_module_class('some_class') pymod.some_class.__module__ = 'other_module' with self.assertRaises(ConfigInvalidModuleError): self.ml.append(pymod) assert (not pymod.some_class.__init__.called) assert (not pymod.some_class.registered.called) def test_ambigious_classdef(self): pymod = types.ModuleType('test_mod') pymod.some_class = self._create_module_class('some_class') pymod.some_class.__module__ = 'test_mod' pymod.some_other_class = self._create_module_class('some_other_class') pymod.some_other_class.__module__ = 'test_mod' with self.assertRaises(ConfigAmbigiousClassesError): self.ml.append(pymod) def test_invalid_module(self): pymod = types.ModuleType('test_mod') with self.assertRaises(ConfigInvalidModuleError): self.ml.append(pymod) def test_append_class_inheritance(self): in_between = self._create_module_class('in_between') cls = self._create_module_class('cls', (in_between,)) self.ml.append(cls) cls.__init__.assert_called_with() cls.registered.assert_called_with(self.status_handler)
def test_etm_chat_copy(db, slave): chat = convert_chat(db, chat=slave.chat_with_alias) copied = chat.copy() attributes = ('module_id', 'module_name', 'channel_emoji', 'uid', 'name', 'alias', 'notification', 'vendor_specific', 'full_name', 'long_name', 'chat_title') for i in attributes: assert (getattr(chat, i) == getattr(copied, i)) assert (chat.db is copied.db)
('cuda.batched_dense_vec_jagged_2d_mul.func_decl') def jagged_to_dense_gen_function_decl(func_attrs) -> str: matrices = func_attrs['inputs'][1] func_name = func_attrs['name'] backend_spec = CUDASpec() return FUNC_DECL_TEMPLATE.render(prefix=backend_spec.prefix, index_type=backend_spec.index_type, func_name=func_name, offsets=gen_offsets_str(matrices._attrs['shape'][0], has_type=True, const_ref=True, name='offsets'))
def int3c2e3d_sph_110(ax, da, A, bx, db, B, cx, dc, C): result = numpy.zeros((3, 3, 1), dtype=float) x0 = (ax + bx) x1 = (x0 ** (- 1.0)) x2 = (cx + x0) x3 = (x2 ** (- 1.0)) x4 = ((- x1) * ((ax * A[0]) + (bx * B[0]))) x5 = (x4 + C[0]) x6 = (- x5) x7 = ((- x1) * ((ax * A[1]) + (bx * B[1]))) x8 = (x7 + C[1]) x9 = (- x8) x10 = ((- x1) * ((ax * A[2]) + (bx * B[2]))) x11 = (x10 + C[2]) x12 = (- x11) x13 = (cx * x3) x14 = ((x0 * x13) * (((x12 ** 2) + (x6 ** 2)) + (x9 ** 2))) x15 = boys(1, x14) x16 = (x15 * x3) x17 = (cx ** (- 1.0)) x18 = (x17 * boys(0, x14)) x19 = (x1 * (x16 - x18)) x20 = (x4 + A[0]) x21 = (- x20) x22 = ((x16 * x6) - (x18 * x21)) x23 = (2.0 * x22) x24 = (A[0] - B[0]) x25 = (x3 * boys(2, x14)) x26 = (x15 * x17) x27 = (x13 * x5) x28 = (A[1] - B[1]) x29 = (A[2] - B[2]) x30 = ((((((17. * da) * db) * dc) * x1) * (x2 ** (- 0.5))) * numpy.exp(((((- ax) * bx) * x1) * (((x24 ** 2) + (x28 ** 2)) + (x29 ** 2))))) x31 = (x7 + A[1]) x32 = (- x31) x33 = ((x16 * x9) - (x18 * x32)) x34 = ((x25 * x9) - (x26 * x32)) x35 = (((- x20) * x33) + (x27 * x34)) x36 = (2.0 * x30) x37 = (x10 + A[2]) x38 = (- x37) x39 = ((x12 * x16) - (x18 * x38)) x40 = ((x12 * x25) - (x26 * x38)) x41 = (((- x20) * x39) + (x27 * x40)) x42 = (2.0 * x33) x43 = (x13 * x8) x44 = (((- x31) * x39) + (x40 * x43)) x45 = (2.0 * x39) result[(0, 0, 0)] = numpy.sum(((- x30) * (((x19 - (x20 * x23)) + (x23 * x24)) - ((2.0 * x27) * ((x21 * x26) - (x25 * x6)))))) result[(0, 1, 0)] = numpy.sum(((- x36) * ((x22 * x28) + x35))) result[(0, 2, 0)] = numpy.sum(((- x36) * ((x22 * x29) + x41))) result[(1, 0, 0)] = numpy.sum(((- x36) * ((x24 * x33) + x35))) result[(1, 1, 0)] = numpy.sum((x30 * ((((- x19) - (x28 * x42)) + (x31 * x42)) - ((2.0 * x34) * x43)))) result[(1, 2, 0)] = numpy.sum(((- x36) * ((x29 * x33) + x44))) result[(2, 0, 0)] = numpy.sum(((- x36) * ((x24 * x39) + x41))) result[(2, 1, 0)] = numpy.sum(((- x36) * ((x28 * x39) + x44))) result[(2, 2, 0)] = numpy.sum((x30 * (((((((- 2.0) * x11) * x13) * x40) - x19) - (x29 * x45)) + (x37 * x45)))) return result
class ShardedFile(): def __init__(self, pattern: str) -> None: comps = ShardedFileComponents(pattern) if comps.is_at_star_pattern(): comps.shard_total = self._find_unambiguous_shard_total(comps, pattern) elif (not comps.is_at_n_pattern()): raise ValueError('Pattern should use or * for shard specification.') self._set_shard_file_names(comps) self._shard_file_names.sort() def get_filenames(self) -> List[str]: return self._shard_file_names def _set_shard_file_names(self, pcomps: ShardedFileComponents) -> None: self._shard_file_names = [] for i in range(pcomps.shard_total): filename = pcomps.get_shard_filename(i) if (not os.path.isfile(filename)): raise ValueError('Shard {} does not exist.'.format(filename)) self._shard_file_names.append(filename) def _find_unambiguous_shard_total(self, pcomps: ShardedFileComponents, pattern: str) -> int: dir = pcomps.directory if (not os.path.isdir(dir)): raise ValueError('Not a directory {}'.format(dir)) pattern = ((pcomps.stem + '?????-of-?????') + pcomps.extension) seen_shard_count = (- 1) for file in os.listdir(dir): if fnmatch.fnmatch(file, pattern): try: comps = ShardedFileComponents(file) except ValueError: continue if (seen_shard_count == (- 1)): seen_shard_count = comps.shard_total elif (seen_shard_count != comps.shard_total): [a, b] = sorted([seen_shard_count, comps.shard_total]) raise ValueError('* matches ambiguous shard sets: {} and {}'.format(a, b)) if (seen_shard_count == (- 1)): raise ValueError('Pattern matches no sharded file set: {}'.format(pattern)) return seen_shard_count
def _benchmark(count, inputs_repeats, warmup, inputs, outputs, module, test_name): for i in range(warmup): module.run_with_tensors(inputs[(i % inputs_repeats)], outputs, sync=False) torch.cuda.synchronize() start_event = torch.cuda.Event(enable_timing=True) end_event = torch.cuda.Event(enable_timing=True) start_event.record() for i in range(count): module.run_with_tensors(inputs[(i % inputs_repeats)], outputs, sync=False) end_event.record() torch.cuda.synchronize() _LOGGER.warning(f'{test_name} benchmark, duration: {(start_event.elapsed_time(end_event) / count)}ms')
def find_pickles(path: str, extension: str) -> Iterator[str]: for (directory, _, filenames) in os.walk(path): for filename in filenames: if filename.endswith(extension): file_path = os.path.join(directory, filename) file_path = file_path[(len(path) + 1):] (yield file_path)
class Identity(IdentityBase): phone_number: Optional[PhoneNumber] = None email: Optional[EmailStr] = None ga_client_id: Optional[str] = None ljt_readerID: Optional[str] = None fides_user_device_id: Optional[str] = None class Config(): extra = Extra.forbid ('fides_user_device_id') def validate_fides_user_device_id(cls, v: Optional[str]) -> Optional[str]: if (not v): return v uuid.UUID(v, version=4) return v
class Argument(): def __init__(self, name): assert (name != 'format') self.name = name self.availability = None self._type = None self._normalize = {} self.format = None self.aliases = None def normalize(self): return self._normalize def normalize(self, value): self.format = value.pop('format', None) self.aliases = value.pop('aliases', None) self._normalize = value def cmltype(self): if (self._type is None): if self.availability: if (self._normalize.get('values') is None): self._normalize['values'] = self.availability self._type = infer_type(**self.normalize) return self._type def add_alias_transformers(self, pipeline): if self.aliases: pipeline.append(AliasTransformer(self, self.cmltype, self.aliases)) def add_type_transformers(self, pipeline): pipeline.append(TypeTransformer(self, self.cmltype)) def add_format_transformers(self, pipeline): if (self.format is not None): pipeline.append(FormatTransformer(self, self.format, self.cmltype)) def __repr__(self) -> str: return f'Argument({self.name})'
class ElephantRobot(object): def __init__(self, host, port, debug=False): self.debug = debug setup_logging(self.debug) self.log = logging.getLogger(__name__) self.BUFFSIZE = 2048 self.ADDR = (host, port) self.tcp_client = socket(AF_INET, SOCK_STREAM) def start_client(self): try: self.tcp_client.connect(self.ADDR) return '' except Exception as e: return e def stop_client(self): self.tcp_client.close() def send_command(self, command): with mutex: self.tcp_client.send(command.encode()) recv_data = self.tcp_client.recv(self.BUFFSIZE).decode() res_str = str(recv_data) print(('recv = ' + res_str)) res_arr = res_str.split(':') if (len(res_arr) == 2): return res_arr[1] else: return '' def string_to_coords(self, data): data = data.replace('[', '') data = data.replace(']', '') data_arr = data.split(',') if (len(data_arr) == 6): try: coords_1 = float(data_arr[0]) coords_2 = float(data_arr[1]) coords_3 = float(data_arr[2]) coords_4 = float(data_arr[3]) coords_5 = float(data_arr[4]) coords_6 = float(data_arr[5]) coords = [coords_1, coords_2, coords_3, coords_4, coords_5, coords_6] return coords except: return self.invalid_coords() return self.invalid_coords() def string_to_double(self, data): try: val = float(data) return val except: return (- 9999.99) def string_to_int(self, data): try: val = int(data) return val except: return (- 9999) def invalid_coords(self): coords = [(- 1), (- 2), (- 3), (- 4), (- 1), (- 1)] return coords def get_angles(self): command = 'get_angles()\n' res = self.send_command(command) return self.string_to_coords(res) def get_coords(self): command = 'get_coords()\n' res = self.send_command(command) return self.string_to_coords(res) def get_speed(self): command = 'get_speed()\n' res = self.send_command(command) return self.string_to_double(res) def power_on(self): command = 'power_on()\n' res = self.send_command(command) return True def power_off(self): command = 'power_off()\n' res = self.send_command(command) return True def start_robot(self): command = 'start_robot()\n' res = self.send_command(command) return True def check_running(self): command = 'check_running()\n' res = self.send_command(command) return (res == '1') def state_check(self): command = 'state_check()\n' res = self.send_command(command) return (res == '1') def upload_file(self, local_filename, remote_filename): with open(local_filename, 'rb') as f: content = f.read().encode() content_base64 = base64.b64encode(content).decode() content_sha256 = hashlib.sha256(content).hexdigest() command = 'upload_file({},{},{})'.format(content_base64, remote_filename, content_sha256) res = self.send_command(command) return res def program_open(self, file_path): command = (('program_open(' + file_path) + ')\n') res = self.send_command(command) return self.string_to_int(res) def program_run(self, start_line): command = (('program_run(' + str(start_line)) + ')\n') res = self.send_command(command) return self.string_to_int(res) def read_next_error(self): command = 'read_next_error()\n' res = self.send_command(command) return res def write_coords(self, coords, speed): command = 'set_coords(' for item in coords: command += (str(item) + ',') command += (str(speed) + ')\n') self.send_command(command) def write_coord(self, axis, value, speed): coords = self.get_coords() if (coords != self.invalid_coords()): coords[axis] = value self.write_coords(coords, speed) def write_angles(self, angles, speed): command = 'set_angles(' for item in angles: command += (str(item) + ',') command += (str(speed) + ')\n') self.send_command(command) def write_angle(self, joint, value, speed): angles = self.get_angles() if (angles != self.invalid_coords()): angles[joint] = value self.write_angles(angles, speed) def set_speed(self, percentage): command = (('set_speed(' + str(percentage)) + ')\n') self.send_command(command) def set_carte_torque_limit(self, axis_str, value): command = (((('set_torque_limit(' + axis_str) + ',') + str(value)) + ')\n') self.send_command(command) def set_upside_down(self, up_down): up = '1' if up_down: up = '0' command = (('set_upside_down(' + up) + ')\n') self.send_command(command) def set_payload(self, payload): command = (('set_speed(' + str(payload)) + ')\n') self.send_command(command) def state_on(self): command = 'state_on()\n' self.send_command(command) def state_off(self): command = 'state_off()\n' self.send_command(command) def task_stop(self): command = 'task_stop()\n' self.send_command(command) def jog_angle(self, joint_str, direction, speed): command = (((((('jog_angle(' + joint_str) + ',') + str(direction)) + ',') + str(speed)) + ')\n') self.send_command(command) def jog_coord(self, axis_str, direction, speed): command = (((((('jog_coord(' + axis_str) + ',') + str(direction)) + ',') + str(speed)) + ')\n') self.send_command(command) def get_digital_in(self, pin_number): command = (('get_digital_in(' + str(pin_number)) + ')\n') self.send_command(command) def get_digital_out(self, pin_number): command = (('get_digital_out(' + str(pin_number)) + ')\n') print(command) self.send_command(command) def get_joint_current(self, joint_number): command = (('get_joint_current(' + str(joint_number)) + ')\n') print(command) self.send_command(command) def set_digital_out(self, pin_number, pin_signal): command = (((('set_digital_out(' + str(pin_number)) + ',') + str(pin_signal)) + ')\n') self.send_command(command) def set_analog_out(self, pin_number, pin_signal): command = (((('set_analog_out(' + str(pin_number)) + ',') + str(pin_signal)) + ')\n') self.send_command(command) def send_feed_override(self, override): command = (('set_feed_rate(' + str(override)) + ')\n') res = self.send_command(command) return self.string_to_int(res) def get_acceleration(self): command = 'get_acceleration()\n' res = self.send_command(command) return self.string_to_int(res) def set_acceleration(self, acceleration): command = (('set_acceleration(' + str(acceleration)) + ')\n') self.send_command(command) def command_wait_done(self): command = 'wait_command_done()\n' self.send_command(command) def wait(self, seconds): command = (('wait(' + str(seconds)) + ')\n') self.send_command(command) def assign_variable(self, var_name, var_value): command = (((('assign_variable("' + str(var_name)) + '",') + str(var_value)) + ')\n') self.send_command(command) def get_variable(self, var_name): command = (('get_variable("' + str(var_name)) + '")\n') return self.send_command(command) def jog_relative(self, joint_id, angle, speed): command = 'SendJogIncrement("{}","{}","{}")\n'.format(joint_id, angle, speed) return self.send_command(command)
def create_metadata_from_template(apk): if os.path.exists('template.yml'): with open('template.yml') as f: metatxt = f.read() if (('name' in apk) and (apk['name'] != '')): metatxt = re.sub('^(((Auto)?Name|Summary):)[ \'"\\.]*$', ('\\1 ' + apk['name']), metatxt, flags=(re.IGNORECASE | re.MULTILINE)) else: logging.warning(_('{appid} does not have a name! Using application ID instead.').format(appid=apk['packageName'])) metatxt = re.sub('^(((Auto)?Name|Summary):).*$', ('\\1 ' + apk['packageName']), metatxt, flags=(re.IGNORECASE | re.MULTILINE)) str_fields = [x for x in metadata.yaml_app_fields if (metadata.fieldtype(x) == metadata.TYPE_STRING)] metatxt = re.sub((('^(' + '|'.join(str_fields)) + '):\\s*$'), "\\1: ''", metatxt, flags=re.MULTILINE) with open(os.path.join('metadata', (apk['packageName'] + '.yml')), 'w') as f: f.write(metatxt) else: app = dict() app['Categories'] = [os.path.basename(os.getcwd())] app['AuthorName'] = '' app['Summary'] = '' app['WebSite'] = '' app['IssueTracker'] = '' app['SourceCode'] = '' app['CurrentVersionCode'] = if (('name' in apk) and (apk['name'] != '')): app['Name'] = apk['name'] else: logging.warning(_('{appid} does not have a name! Using application ID instead.').format(appid=apk['packageName'])) app['Name'] = apk['packageName'] with open(os.path.join('metadata', (apk['packageName'] + '.yml')), 'w') as f: yaml.dump(app, f, default_flow_style=False) logging.info(_('Generated skeleton metadata for {appid}').format(appid=apk['packageName']))
class OptionSeriesSunburstSonificationTracksMappingLowpassFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class OptionSeriesPieSonificationContexttracksMappingGapbetweennotes(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
def test_Kc_prime_count(L): BEGIN = 255 END = (BEGIN + 30) with open('bf3/L{}-{}-{}.txt'.format(L, BEGIN, END), mode='w') as fp: for i in count(BEGIN): Kc_HEX = hex(i)[2:] if ((len(Kc_HEX) % 2) == 1): Kc_HEX = ('0' + Kc_HEX) Kc = bytearray.fromhex(Kc_HEX) while (len(Kc) < KEYS_LEN): Kc = ('\x00' + Kc) assert (len(Kc) == KEYS_LEN) (Kc_prime, red) = Kc_to_Kc_prime(Kc, L, red=True) fp.write('i : {}\n'.format(i)) fp.write('Kc : {}\n'.format(bytearray_to_hexstring(Kc))) fp.write('red: {}\n'.format(bytearray_to_hexstring(red))) fp.write("Kc': {}\n".format(bytearray_to_hexstring(Kc_prime))) fp.write('\n') log.info('i : {}'.format(i)) log.info('Kc : {}'.format(bytearray_to_hexstring(Kc))) log.info('red: {}'.format(bytearray_to_hexstring(red))) log.info("Kc': {}".format(bytearray_to_hexstring(Kc_prime))) log.info('') if (i >= END): break
def _read_config(config_name: str, argument: Optional[str], env_var: str, default_val: str) -> str: if argument: logger.info(f'Read {config_name} from program arguments...') return argument env_val = os.getenv(env_var) if env_val: logger.info(f'Read {config_name} from environment variables...') return env_val logger.info(f'Read {config_name} from default value...') return default_val
class Cubo(Entity): def __init__(self): super().__init__() self.model = 'cube' self.texture = 'brick' self.shader = lit_with_shadows_shader def update(self): self.rotation_z += (time.dt * 20) self.x += ((held_keys['right arrow'] * time.dt) * 5) self.x -= ((held_keys['left arrow'] * time.dt) * 5)
def flt_imgurl_wrapper(ori): _quota_check def flt_imgurl(r, suc, fail, ori=ori): if re.match('Invalid page', r.text): return fail((ERR_IMAGE_RESAMPLED, r._real_url, r.url)) while True: _ = re.findall('src="([^"]+keystamp[^"]+)"', r.text) if (not _): _ = re.findall('src="([^"]+)"\\s+style="', r.text) if (not _): break picurl = util.htmlescape(_[0]) _ = re.findall('</a></div><div>(.*?) ::.+::.+</di', r.text) if (not _): break filename = _[0] if ('image.php' in filename): _ = re.findall('n=(.+)', picurl) if _: filename = _[0] _ = re.findall('.+\\.([a-zA-Z]+)', filename) if (not _): break fmt = _[0] _ = re.findall('.+/(\\d+)-(\\d*)', r._real_url) if (not _): break index = _[0] fullurl = re.findall('class="mr".+<a href="(.+)"\\s*>Download original', r.text) fullsize = re.findall('Download\\soriginal\\s[0-9]+\\sx\\s[0-9]+\\s(.*)\\ssource', r.text) if fullurl: fullurl = util.htmlescape(fullurl[0]) else: fullurl = picurl _ = re.findall("return nl\\('([a-zA-Z\\d\\-]+)'\\)", r.text) if (not _): break js_nl = _[0] reload_url = ('%s%snl=%s' % (r._real_url, ('&' if ('?' in r._real_url) else '?'), js_nl)) if ori: return suc((fullurl, reload_url, filename)) else: return suc((picurl, reload_url, filename)) return fail((ERR_SCAN_REGEX_FAILED, r._real_url, r.url)) return flt_imgurl
def listen() -> None: TEMP_FRAME_FORMAT_DROPDOWN.select(update_temp_frame_format, inputs=TEMP_FRAME_FORMAT_DROPDOWN) TEMP_FRAME_QUALITY_SLIDER.change(update_temp_frame_quality, inputs=TEMP_FRAME_QUALITY_SLIDER) target_video = get_ui_component('target_video') if target_video: for method in ['upload', 'change', 'clear']: getattr(target_video, method)(remote_update, outputs=[TEMP_FRAME_FORMAT_DROPDOWN, TEMP_FRAME_QUALITY_SLIDER])
class IPv4ProtoUDP(MatchTest): def runTest(self): match = ofp.match([ofp.oxm.eth_type(2048), ofp.oxm.ip_proto(17)]) matching = {'udp': simple_udp_packet()} nonmatching = {'tcp': simple_tcp_packet(), 'icmp': simple_icmp_packet()} self.verify_match(match, matching, nonmatching)
def create_headerecho_mapping(namespace): headerecho_mapping = f''' --- apiVersion: getambassador.io/v3alpha1 kind: Mapping metadata: name: headerecho-mapping namespace: {namespace} spec: hostname: "*" prefix: /headerecho/ rewrite: / service: headerecho ''' apply_kube_artifacts(namespace=namespace, artifacts=headerecho_mapping)
def main(args=None): args = parse_arguments().parse_args(args) space = {'pit': hp.uniform('pit', 0, 100), 'oet': hp.uniform('oet', 0, 5), 'peakWidth': hp.choice('peakWidth', list(range(1, 10))), 'windowSize': hp.choice('windowSize', list(range(4, 15))), 'pp': hp.uniform('pp', 1e-07, 0.15), 'p': hp.uniform('p', 1e-07, 0.1), 'maxLoopDistance': hp.choice('maxLoopDistance', list(range(1000000, 3000000, 100000))), 'matrixFile': args.matrix, 'proteinFile': args.proteinFile, 'maximumNumberOfLoops': args.maximumNumberOfLoops, 'resolution': args.resolution, 'threads': args.threads, 'chrPrefixLoops': args.chrPrefixLoops} trials = Trials() best = fmin(objective, space, algo=tpe.suggest, max_evals=args.runs, trials=trials) with open(args.outputFileName, 'w') as file: file.write('# Created by HiCExplorer hicHyperoptDetectLoops {}\n\n'.format(__version__)) file.write('{}'.format(space_eval(space, best)))
class Emu(BaseFunctions): def __init__(self, args): self.name = 'emu' self.args = args self.commands = {cmd.name: cmd for cmd in EMU_COMMANDS} self.parse() def parse(self): cmd = self.next_arg() if (cmd is None): self.print_commands(error_msg='You must specify a command for emu. Some options are:', ascii_art=True) return if (cmd not in self.commands): self.print_commands(error_msg='Unknown command! Try one of these:') return self.commands[cmd].main(self.args, cmd)
def extractZhaojianguiTumblrCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
class UrbanSharing(BikeShareSystem): def __init__(self, tag, meta): super(UrbanSharing, self).__init__(tag, meta) def update(self, scraper=None): if (scraper is None): scraper = PyBikesScraper() feed_url = FEED_URL.format(tag=self.tag) stations_data = json.loads(scraper.request(feed_url)) stations = [] for station_data in stations_data['data']['dockGroups']: station = UrbanSharingStation(station_data) stations.append(station) self.stations = stations
def assert_dens_mats(dens_dict, json_fn): wf = Wavefunction.from_orca_json(json_fn) (Pa_ref, Pb_ref) = wf.P P = (Pa_ref + Pb_ref) Pr = (Pa_ref - Pb_ref) np.testing.assert_allclose(P, dens_dict['scfp'], atol=1e-14) if wf.unrestricted: np.testing.assert_allclose(Pr, dens_dict['scfr'], atol=1e-14) return wf
def address_check_update(message, old_address): bot.send_chat_action(message.chat.id, 'typing') connection = get_connection() with connection.cursor() as cursor: if (message.text in airdrop_wallets): msg = bot.reply_to(message, config.texts['airdrop_walletused'], parse_mode='Markdown') bot.register_next_step_handler(msg, address_check_update, old_address) elif ((message.content_type == 'text') and re.match('^(?=.{42}$).*', message.text)): sql = 'UPDATE users SET address = %s, address_change_status = address_change_status + 1 WHERE user_id = %s' cursor.execute(sql, (message.text, message.chat.id)) bot.reply_to(message, config.texts['airdrop_wallet_update'], parse_mode='Markdown') airdrop_wallets.append(message.text) try: bot.send_message(config.log_channel, ' *#Address_Updated:*\n User: [{1}](tg://user?id={2}) (#id{2})\n Old Address: `{3}`\n New Address: `{4}`\n Time: `{5} UTC`'.format(len(airdrop_wallets), bot.get_chat(message.chat.id).first_name, message.chat.id, old_address, message.text, strftime('%Y-%m-%d %H:%M:%S', gmtime())), parse_mode='Markdown', disable_web_page_preview=True) except: pass else: msg = bot.reply_to(message, ' Invalid address. Try again:', parse_mode='Markdown', reply_markup=cancel_button()) bot.register_next_step_handler(msg, address_check_update, old_address)
_os(*metadata.platforms) def main(): msxsl = 'C:\\Users\\Public\\msxsl.exe' user32 = 'C:\\Windows\\System32\\user32.dll' dll = 'C:\\Users\\Public\\scrobj.dll' ps1 = 'C:\\Users\\Public\\Invoke-ImageLoad.ps1' rcedit = 'C:\\Users\\Public\\rcedit.exe' common.copy_file(EXE_FILE, msxsl) common.copy_file(user32, dll) common.copy_file(PS1_FILE, ps1) common.copy_file(RENAMER, rcedit) common.log('Modifying the OriginalFileName attribute') common.execute([rcedit, msxsl, '--set-version-string', 'OriginalFilename', 'msxsl.exe']) common.log('Loading scrobj.dll into fake msxsl') common.execute([msxsl, '-c', f'Import-Module {ps1}; Invoke-ImageLoad {dll}'], timeout=10) common.remove_files(msxsl, dll, ps1, rcedit)
def wikidata(n: int): import os import json path = os.path.join(os.path.expanduser('~'), '.cache', 'lmql', 'datasets', 'wikidata.json') if (not os.path.exists(path)): os.makedirs(os.path.join(os.path.expanduser('~'), '.cache', 'lmql', 'datasets'), exist_ok=True) url = ' subprocess.run(['curl', url], stdout=open(path, 'w'), check=True) assert os.path.exists(path) with open(path, 'r') as f: data = json.load(f) s = data['examples'][n] target = s['target'] return DirectPredictionSample(s['input'], target)
class OptionPlotoptionsColumnSonificationTracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsColumnSonificationTracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsColumnSonificationTracksMappingHighpassFrequency) def resonance(self) -> 'OptionPlotoptionsColumnSonificationTracksMappingHighpassResonance': return self._config_sub_data('resonance', OptionPlotoptionsColumnSonificationTracksMappingHighpassResonance)
def wait_for_pending_datafeeds_and_jobs(client: Elasticsearch, timeout=30): end_time = (time.time() + timeout) while (time.time() < end_time): resp = client.ml.get_datafeeds(datafeed_id='*', allow_no_match=True) if (resp['count'] == 0): break for datafeed in resp['datafeeds']: client.options(ignore_status=404).ml.delete_datafeed(datafeed_id=datafeed['datafeed_id']) end_time = (time.time() + timeout) while (time.time() < end_time): resp = client.ml.get_jobs(job_id='*', allow_no_match=True) if (resp['count'] == 0): break for job in resp['jobs']: client.options(ignore_status=404).ml.close_job(job_id=job['job_id']) client.options(ignore_status=404).ml.delete_job(job_id=job['job_id']) end_time = (time.time() + timeout) while (time.time() < end_time): resp = client.ml.get_data_frame_analytics(id='*') if (resp['count'] == 0): break for job in resp['data_frame_analytics']: client.options(ignore_status=404).ml.stop_data_frame_analytics(id=job['id']) client.options(ignore_status=404).ml.delete_data_frame_analytics(id=job['id'])
def get_rocket_chat_token_virtual_room(user: User, event: Optional[Event]=None, videoStream: Optional[VideoStream]=None): settings = get_settings() if (not (api_url := settings['rocket_chat_url'])): raise RocketChatException('Rocket Chat Integration is not enabled', RocketChatException.CODES.DISABLED) rocket_chat = RocketChat(api_url) return rocket_chat.get_token_virtual_room(user, event, videoStream=videoStream)
.integration_test .parametrize('config_str, expected, extra_files', [('GEN_KW KW_NAME template.txt kw.txt prior.txt INIT_FILES:custom_param%d', 'MY_KEYWORD 1.31\nMY_SECOND_KEYWORD 1.01', [('custom_param0', 'MY_SECOND_KEYWORD 1.01\nMY_KEYWORD 1.31')])]) def test_that_order_of_input_in_user_input_is_abritrary_for_gen_kw_init_files(tmpdir, config_str, expected, extra_files, storage): with tmpdir.as_cwd(): config = dedent('\n JOBNAME my_name%d\n NUM_REALIZATIONS 1\n ') config += config_str with open('config.ert', mode='w', encoding='utf-8') as fh: fh.writelines(config) with open('template.txt', mode='w', encoding='utf-8') as fh: fh.writelines('MY_KEYWORD <MY_KEYWORD>\nMY_SECOND_KEYWORD <MY_SECOND_KEYWORD>') with open('prior.txt', mode='w', encoding='utf-8') as fh: fh.writelines('MY_KEYWORD NORMAL 0 1\nMY_SECOND_KEYWORD NORMAL 0 1') for (fname, contents) in extra_files: write_file(fname, contents) create_runpath(storage, 'config.ert') assert (Path('simulations/realization-0/iter-0/kw.txt').read_text('utf-8') == expected)
class OptionSeriesLollipopSonificationDefaultinstrumentoptionsMappingVolume(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class op(bpy.types.Operator): bl_idname = 'uv.textools_select_islands_overlap' bl_label = 'Select outline' bl_description = 'Select all overlapping UV islands but one' bl_options = {'REGISTER', 'UNDO'} def poll(cls, context): if (bpy.context.area.ui_type != 'UV'): return False if (not bpy.context.active_object): return False if (bpy.context.active_object.type != 'MESH'): return False if (bpy.context.active_object.mode != 'EDIT'): return False if (not bpy.context.object.data.uv_layers): return False if bpy.context.scene.tool_settings.use_uv_select_sync: return False return True def execute(self, context): bpy.ops.uv.select_overlap() utilities_uv.multi_object_loop(deselect, self, context) bpy.ops.uv.select_linked() return {'FINISHED'}
def get_last_untagged(decks, limit) -> List[IndexNote]: deckQ = _deck_query(decks) if deckQ: res = mw.col.db.all(("select distinct notes.id, flds, tags, did, mid from notes left join cards on notes.id = cards.nid where did in %s and (tags is null or tags = '') order by notes.id desc limit %s" % (deckQ, limit))) else: res = mw.col.db.all(("select distinct notes.id, flds, tags, did, mid from notes left join cards on notes.id = cards.nid where tags is null or tags = '' order by notes.id desc limit %s" % limit)) return to_notes(res)
class OptionPlotoptionsGaugeSonificationTracksMappingLowpass(Options): def frequency(self) -> 'OptionPlotoptionsGaugeSonificationTracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsGaugeSonificationTracksMappingLowpassFrequency) def resonance(self) -> 'OptionPlotoptionsGaugeSonificationTracksMappingLowpassResonance': return self._config_sub_data('resonance', OptionPlotoptionsGaugeSonificationTracksMappingLowpassResonance)
class Solution(): def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: if (beginWord not in wordList): wordList.append(beginWord) if (endWord not in wordList): return [] endIndex = wordList.index(endWord) beginIndex = wordList.index(beginWord) graph = convert(wordList) parents = bfs(graph, beginIndex) pathList = [] currPath = [endWord] findPaths(pathList, currPath, endIndex, parents, wordList) return pathList
def extractSincereDreamwidthOrg(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=postfix) return False
class OptionPlotoptionsPyramidSonificationDefaultspeechoptionsMappingPitch(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get('undefined') def mapTo(self, text: str): self._config(text, js_type=False) def max(self): return self._config_get('undefined') def max(self, text: str): self._config(text, js_type=False) def min(self): return self._config_get('undefined') def min(self, text: str): self._config(text, js_type=False) def within(self): return self._config_get('undefined') def within(self, text: str): self._config(text, js_type=False)
def resolve_pkg(pkg, grpc_url): if pkg.startswith('pkg://'): url = pkg.replace('pkg://', '') splits = url.split(os.path.sep, 1) if (len(splits) == 2): packages = nm.nmd().file.get_packages(grpc_url) for (path, pkgname) in packages.items(): if (pkgname == splits[0]): return os.path.join(path, splits[1]) raise Exception(('invalid package url to split: %s' % pkg))
def _parse_section(raw): (section, sep, args) = raw.partition(':') if (not sep): args = () elif ((not args) or (not args.strip())): args = [args] else: args = args.split(',') args = [(int(a) if a.isdigit() else a) for a in args] try: (_, _, *kwnames) = SECTIONS[section] except KeyError: raise ValueError(f'unsupported section {section!r}') if (len(args) > len(kwnames)): raise ValueError(f'got extra args {args!r}') kwargs = dict(zip(kwnames, args)) spec = (kwargs,) return (section, spec)
class Window(QMainWindow): def __init__(self): super().__init__() base = QWidget() layout = QVBoxLayout() font = QFont() font.setPixelSize(90) base.setFont(font) self.label = QLabel('Deixa um Like!') self.label.setAlignment(Qt.AlignCenter) botao = QPushButton('Botao!') botao.clicked.connect(self.muda_label) layout.addWidget(self.label) layout.addWidget(botao) base.setLayout(layout) self.setCentralWidget(base) menu = self.menuBar() arquivo_menu = menu.addMenu('Arquivo') action = QAction('Print!') action.triggered.connect(callback2) arquivo_menu.addAction(action) def muda_label(self): self.label.setText('Clicado!!!!')
class UFO3ReadLayersTestCase(unittest.TestCase): def setUp(self): self.tempDir = tempfile.mktemp() os.mkdir(self.tempDir) self.ufoPath = os.path.join(self.tempDir, 'test.ufo') def tearDown(self): shutil.rmtree(self.tempDir) def makeUFO(self, metaInfo=None, layerContents=None): self.clearUFO() if (not os.path.exists(self.ufoPath)): os.mkdir(self.ufoPath) if (metaInfo is None): metaInfo = dict(creator='test', formatVersion=3) path = os.path.join(self.ufoPath, 'metainfo.plist') with open(path, 'wb') as f: plistlib.dump(metaInfo, f) if (layerContents is None): layerContents = [('public.default', 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 2')] if layerContents: path = os.path.join(self.ufoPath, 'layercontents.plist') with open(path, 'wb') as f: plistlib.dump(layerContents, f) else: layerContents = [('', 'glyphs')] for (name, directory) in layerContents: glyphsPath = os.path.join(self.ufoPath, directory) os.mkdir(glyphsPath) contents = dict(a='a.glif') path = os.path.join(glyphsPath, 'contents.plist') with open(path, 'wb') as f: plistlib.dump(contents, f) path = os.path.join(glyphsPath, 'a.glif') with open(path, 'w') as f: f.write(' ') def clearUFO(self): if os.path.exists(self.ufoPath): shutil.rmtree(self.ufoPath) def testValidRead(self): self.makeUFO(metaInfo=dict(creator='test', formatVersion=1), layerContents=dict()) reader = UFOReader(self.ufoPath, validate=True) reader.getGlyphSet() self.makeUFO(metaInfo=dict(creator='test', formatVersion=2), layerContents=dict()) reader = UFOReader(self.ufoPath, validate=True) reader.getGlyphSet() self.makeUFO() reader = UFOReader(self.ufoPath, validate=True) reader.getGlyphSet() def testMissingLayerContents(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testInvalidLayerContentsFormat(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) with open(path, 'w') as f: f.write('test') reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = {'public.default': 'glyphs', 'layer 1': 'glyphs.layer 1', 'layer 2': 'glyphs.layer 2'} with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testInvalidLayerContentsNameFormat(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [(1, 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 2')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testInvalidLayerContentsDirectoryFormat(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('public.foregound', 'glyphs'), ('layer 1', 1), ('layer 2', 'glyphs.layer 2')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testLayerContentsHasMissingDirectory(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('public.foregound', 'glyphs'), ('layer 1', 'glyphs.doesnotexist'), ('layer 2', 'glyphs.layer 2')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testMissingDefaultLayer(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 2')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testDuplicateLayerName(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('public.foregound', 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 1', 'glyphs.layer 2')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testDuplicateLayerDirectory(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('public.foregound', 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 1')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) self.assertRaises(UFOLibError, reader.getGlyphSet) def testDefaultLayerNoName(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('public.foregound', 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 2')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) reader.getGlyphSet() def testDefaultLayerName(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('custom name', 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 2')] expected = layerContents[0][0] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) result = reader.getDefaultLayerName() self.assertEqual(expected, result) self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('custom name', 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 2')] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) reader.getGlyphSet(expected) def testLayerOrder(self): self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('public.foregound', 'glyphs'), ('layer 1', 'glyphs.layer 1'), ('layer 2', 'glyphs.layer 2')] expected = [name for (name, directory) in layerContents] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) result = reader.getLayerNames() self.assertEqual(expected, result) self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('layer 1', 'glyphs.layer 1'), ('public.foregound', 'glyphs'), ('layer 2', 'glyphs.layer 2')] expected = [name for (name, directory) in layerContents] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) result = reader.getLayerNames() self.assertEqual(expected, result) self.makeUFO() path = os.path.join(self.ufoPath, 'layercontents.plist') os.remove(path) layerContents = [('layer 2', 'glyphs.layer 2'), ('layer 1', 'glyphs.layer 1'), ('public.foregound', 'glyphs')] expected = [name for (name, directory) in layerContents] with open(path, 'wb') as f: plistlib.dump(layerContents, f) reader = UFOReader(self.ufoPath, validate=True) result = reader.getLayerNames() self.assertEqual(expected, result)
class RnanModel(PreTrainedModel): config_class = RnanConfig def __init__(self, args, conv=default_conv): super(RnanModel, self).__init__(args) n_resgroup = args.n_resgroups n_feats = args.n_feats kernel_size = 3 scale = args.scale act = nn.ReLU(True) rgb_mean = args.rgb_mean rgb_std = args.rgb_std self.sub_mean = MeanShift(args.rgb_range, rgb_mean, rgb_std) modules_head = [conv(args.n_colors, n_feats, kernel_size)] modules_body_nl_low = [_NLResGroup(conv, n_feats, kernel_size, act=act, res_scale=args.res_scale)] modules_body = [_ResGroup(conv, n_feats, kernel_size, act=act, res_scale=args.res_scale) for _ in range((n_resgroup - 2))] modules_body_nl_high = [_NLResGroup(conv, n_feats, kernel_size, act=act, res_scale=args.res_scale)] modules_body.append(conv(n_feats, n_feats, kernel_size)) modules_tail = [Upsampler(conv, scale, n_feats, act=False), conv(n_feats, args.n_colors, kernel_size)] self.add_mean = MeanShift(args.rgb_range, rgb_mean, rgb_std, 1) self.head = nn.Sequential(*modules_head) self.body_nl_low = nn.Sequential(*modules_body_nl_low) self.body = nn.Sequential(*modules_body) self.body_nl_high = nn.Sequential(*modules_body_nl_high) self.tail = nn.Sequential(*modules_tail) def forward(self, x): if self.training: x = self.sub_mean(x) feats_shallow = self.head(x) res = self.body_nl_low(feats_shallow) res = self.body(res) res = self.body_nl_high(res) res += feats_shallow res_main = self.tail(res) res_main = self.add_mean(res_main) return res_main else: print('eval') def load_state_dict(self, state_dict, strict=False): own_state = self.state_dict() for (name, param) in state_dict.items(): if (name in own_state): if isinstance(param, nn.Parameter): param = param.data try: own_state[name].copy_(param) except Exception: if (name.find('tail') >= 0): print('Replace pre-trained upsampler to new one...') else: raise RuntimeError('While copying the parameter named {}, whose dimensions in the model are {} and whose dimensions in the checkpoint are {}.'.format(name, own_state[name].size(), param.size())) elif strict: if (name.find('tail') == (- 1)): raise KeyError('unexpected key "{}" in state_dict'.format(name)) if strict: missing = (set(own_state.keys()) - set(state_dict.keys())) if (len(missing) > 0): raise KeyError('missing keys in state_dict: "{}"'.format(missing))
def test_grouping(): class _EventInterface(ABC): _stats_grouping('group') _step_stats(sum) def event1(self, group, attr1): pass agg = LogStatsAggregator(LogStatsLevel.STEP) for v in [1, 3]: agg.add_event(EventRecord(_EventInterface, _EventInterface.event1, dict(group=0, attr1=v))) agg.add_event(EventRecord(_EventInterface, _EventInterface.event1, dict(group=1, attr1=(v * 2)))) stats = agg.reduce() assert (len(stats) == 2) value1 = stats[(_EventInterface.event1, None, (0,))] value2 = stats[(_EventInterface.event1, None, (1,))] assert (value1 == 4) assert (value2 == 8)
class OptionPlotoptionsTreegraphStatesHoverMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): self._config(num, js_type=False) def fillColor(self): return self._config_get(None) def fillColor(self, text: str): self._config(text, js_type=False) def height(self): return self._config_get(None) def height(self, num: float): self._config(num, js_type=False) def lineColor(self): return self._config_get('#ffffff') def lineColor(self, text: str): self._config(text, js_type=False) def lineWidth(self): return self._config_get(0) def lineWidth(self, num: float): self._config(num, js_type=False) def radius(self): return self._config_get(4) def radius(self, num: float): self._config(num, js_type=False) def width(self): return self._config_get(None) def width(self, num: float): self._config(num, js_type=False)
class FastChatLLMModelAdapterWrapper(LLMModelAdapter): def __init__(self, adapter: 'BaseModelAdapter') -> None: self._adapter = adapter def new_adapter(self, **kwargs) -> 'LLMModelAdapter': return FastChatLLMModelAdapterWrapper(self._adapter) def use_fast_tokenizer(self) -> bool: return self._adapter.use_fast_tokenizer def load(self, model_path: str, from_pretrained_kwargs: dict): return self._adapter.load_model(model_path, from_pretrained_kwargs) def get_generate_stream_function(self, model: 'TorchNNModule', model_path: str): if _IS_BENCHMARK: from dbgpt.util.benchmarks.llm.fastchat_benchmarks_inference import generate_stream return generate_stream else: from fastchat.model.model_adapter import get_generate_stream_function return get_generate_stream_function(model, model_path) def get_default_conv_template(self, model_name: str, model_path: str) -> Optional[ConversationAdapter]: conv_template = self._adapter.get_default_conv_template(model_path) return (FschatConversationAdapter(conv_template) if conv_template else None) def __str__(self) -> str: return '{}({}.{})'.format(self.__class__.__name__, self._adapter.__class__.__module__, self._adapter.__class__.__name__)
class Messages(list): def __init__(self, msg=None, level=constants.SUCCESS): if msg: self.add_message(level, msg) def add_message(self, lvl, msg): self.append(Message(lvl, msg)) def debug(self, msg): self.add_message(constants.DEBUG, msg) def info(self, msg): self.add_message(constants.INFO, msg) def success(self, msg): self.add_message(constants.SUCCESS, msg) def warning(self, msg): self.add_message(constants.WARNING, msg) def error(self, msg): self.add_message(constants.ERROR, msg)
.parametrize('uri', ('meh://block/byhash/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080?score=11', 'eth://meh/byhash/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080?score=11', 'eth://block/meh/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080?score=11', 'eth://block/byhash/meh?score=78', 'eth://block/meh/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080?score=11', 'eth://block/meh/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080?score=meh', 'eth://block/byhash/0x113f05289c685eb5b87d433c3e09ec2bfa51d6472cc37108d03b0113b11e3080')) def test_throws_validation_error(uri): with pytest.raises(ValidationError): parse_checkpoint_uri(uri, MAINNET_NETWORK_ID)
def extractZefelinaWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('his canary', 'his canary', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
.django_db def test_treasury_account_component_filter_appropriate_characters(client, monkeypatch, elasticsearch_award_index, subaward_with_tas): _setup_es(client, monkeypatch, elasticsearch_award_index) resp = query_by_treasury_account_components(client, [{'a': 'R'}], None) assert (resp.status_code == status.HTTP_200_OK), 'Failed to return 422 Response'
class Migration(migrations.Migration): dependencies = [('core', '0028_auto__0237')] operations = [migrations.RenameField(model_name='bookingnote', old_name='reservation', new_name='booking'), migrations.AlterField(model_name='bookingnote', name='booking', field=models.ForeignKey(related_name='booking_note', null=False, to='core.Booking')), migrations.AlterField(model_name='booking', name='bill', field=models.OneToOneField(related_name='booking', null=True, to='core.BookingBill')), migrations.AlterField(model_name='booking', name='location', field=models.ForeignKey(related_name='bookings', to='core.Location', null=True)), migrations.AlterField(model_name='booking', name='user', field=models.ForeignKey(related_name='bookings', to=settings.AUTH_USER_MODEL))]
class ZISApi(Api): def __init__(self, config): super(ZISApi, self).__init__(config, endpoint=EndpointFactory('zis'), object_type='') self.registry = ZISRegistryApi(config, endpoint=self.endpoint.registry, object_type='integration') def __call__(self, *args, **kwargs): raise ZenpyException('You cannot call this endpoint directly!')
class _hashable_function_wrapper(): def __init__(self, wrapped, identifier): self.__nutils_hash__ = nutils_hash(('hashable_function', identifier)) functools.update_wrapper(self, wrapped) def __call__(*args, **kwargs): return args[0].__wrapped__(*args[1:], **kwargs) def __get__(self, instance, owner): return self def __hash__(self): return hash(self.__nutils_hash__) def __eq__(self, other): return ((type(self) is type(other)) and (self.__nutils_hash__ == other.__nutils_hash__))
def pull(manifests_dir: str, url: str, headers: Dict[(str, str)], all_resources_file: Optional[str]) -> None: existing_keys = pull_existing_resources(manifests_dir=manifests_dir, url=url, headers=headers) if all_resources_file: pull_missing_resources(manifest_path=all_resources_file, url=url, headers=headers, existing_keys=existing_keys) echo_green('Pull complete.')
class Command(BaseCommand): help = __doc__ def add_arguments(self, parser): parser.add_argument('--measure_ids', nargs='+') def handle(self, *args, measure_ids, **kwargs): base_path = os.path.join(settings.APPS_ROOT, 'bq_public_tables') client = Client('public') with open(os.path.join(base_path, '_measure_template.sql')) as f: measure_template_sql = f.read() if measure_ids: measures = Measure.objects.filter(id__in=measure_ids) else: measures = Measure.objects.all() for measure in measures: table_name = ('measure_' + measure.id) print(table_name) table = client.get_table(table_name) numerator_sql = '\n SELECT\n CAST(month AS DATE) AS month,\n practice AS practice_id,\n {numerator_columns}\n FROM {numerator_from}\n WHERE {numerator_where}\n GROUP BY month, practice_id\n '.format(numerator_columns=measure.numerator_columns, numerator_from=measure.numerator_from, numerator_where=measure.numerator_where) denominator_sql = '\n SELECT\n CAST(month AS DATE) AS month,\n practice AS practice_id,\n {denominator_columns}\n FROM {denominator_from}\n WHERE {denominator_where}\n GROUP BY month, practice_id\n '.format(denominator_columns=measure.denominator_columns, denominator_from=measure.denominator_from, denominator_where=measure.denominator_where) sql = partially_format(measure_template_sql, numerator_sql=numerator_sql, denominator_sql=denominator_sql) table.insert_rows_from_query(sql)
class _Validators(): def check_string(cls, label, value, non_empty=False): if (value is None): return None if (not isinstance(value, str)): if non_empty: raise ValueError('{0} must be a non-empty string.'.format(label)) raise ValueError('{0} must be a string.'.format(label)) if (non_empty and (not value)): raise ValueError('{0} must be a non-empty string.'.format(label)) return value def check_number(cls, label, value): if (value is None): return None if (not isinstance(value, numbers.Number)): raise ValueError('{0} must be a number.'.format(label)) return value def check_string_dict(cls, label, value): if ((value is None) or (value == {})): return None if (not isinstance(value, dict)): raise ValueError('{0} must be a dictionary.'.format(label)) non_str = [k for k in value if (not isinstance(k, str))] if non_str: raise ValueError('{0} must not contain non-string keys.'.format(label)) non_str = [v for v in value.values() if (not isinstance(v, str))] if non_str: raise ValueError('{0} must not contain non-string values.'.format(label)) return value def check_string_list(cls, label, value): if ((value is None) or (value == [])): return None if (not isinstance(value, list)): raise ValueError('{0} must be a list of strings.'.format(label)) non_str = [k for k in value if (not isinstance(k, str))] if non_str: raise ValueError('{0} must not contain non-string values.'.format(label)) return value def check_number_list(cls, label, value): if ((value is None) or (value == [])): return None if (not isinstance(value, list)): raise ValueError('{0} must be a list of numbers.'.format(label)) non_number = [k for k in value if (not isinstance(k, numbers.Number))] if non_number: raise ValueError('{0} must not contain non-number values.'.format(label)) return value def check_analytics_label(cls, label, value): value = _Validators.check_string(label, value) if ((value is not None) and (not re.match('^[a-zA-Z0-9-_.~%]{1,50}$', value))): raise ValueError('Malformed {}.'.format(label)) return value def check_datetime(cls, label, value): if (value is None): return None if (not isinstance(value, datetime.datetime)): raise ValueError('{0} must be a datetime.'.format(label)) return value
.parametrize('between, r_update', [(9, False), (21, False)]) def test_mb_growingnt(between, r_update): geoms = MullerBrownPot().get_minima() geoms = (geoms[1], geoms[0]) (geom0, geom1) = geoms gnt_kwargs = {'between': between, 'rms_thresh': 0.08, 'final_geom': geom1, 'r_update_thresh': 0.9, 'r_update': True} gnt = GrowingNT(geom0, **gnt_kwargs) opt_kwargs = {'max_cycles': 100} opt = PreconLBFGS(gnt, **opt_kwargs) opt.run() assert opt.is_converged assert (gnt.images[(- 1)].energy == pytest.approx((- 146.)))
def prepare_fake_quant_model(cfg, model, is_qat, example_input=None): if cfg.QUANTIZATION.EAGER_MODE: if hasattr(model, 'prepare_for_quant'): model = model.prepare_for_quant(cfg) else: logger.info('Using default implementation for prepare_for_quant (eager mode)') model = default_prepare_for_quant(cfg, model) if is_qat: torch.ao.quantization.prepare_qat(model, inplace=True) else: torch.ao.quantization.prepare(model, inplace=True) else: if (not is_qat): model = fuse_utils.swap_modules(model) if hasattr(model, 'custom_prepare_fx'): ret = model.custom_prepare_fx(cfg, is_qat, example_input) if (not (isinstance(ret, tuple) and (len(ret) == 2))): raise ValueError('`custom_prepare_fx` requires return model and convert_callback') (model, convert_fx_callback) = ret else: logger.info('Using default implementation for custom_prepare_fx (FX graph mode)') (model, convert_fx_callback) = default_custom_prepare_fx(cfg, model, is_qat, example_input) if hasattr(model, _CONVERT_FX_CALLBACK_ATTRIBUTE): raise AttributeError(f'{_CONVERT_FX_CALLBACK_ATTRIBUTE} is already set in model: {model}') setattr(model, _CONVERT_FX_CALLBACK_ATTRIBUTE, convert_fx_callback) return model
def run_flirt_to_T1w(native_func_3D, settings, cost_function='corratio', degrees_of_freedom='12'): logger.info('Running FLIRT transform to T1w with costfunction {} and dof {}'.format(cost_function, degrees_of_freedom)) func2T1w_mat = os.path.join(settings.results_dir, 'native', 'mat_EPI_to_T1.mat') run(['mkdir', '-p', os.path.join(settings.results_dir, 'native')]) run(['flirt', '-in', native_func_3D, '-ref', os.path.join(settings.vol_reg['src_dir'], settings.vol_reg['T1wBrain']), '-omat', func2T1w_mat, '-o', os.path.join(tmpdir, 'epi_in_T1w.nii.gz'), '-dof', str(degrees_of_freedom), '-cost', cost_function, '-searchcost', cost_function, '-searchrx', '-180', '180', '-searchry', '-180', '180', '-searchrz', '-180', '180']) return func2T1w_mat
class TestDeviceStateUtil(): def test_next_event_time_update(self) -> None: training_schedule = TrainingSchedule(creation_time=0, start_time=12, end_time=16) device_state = DeviceState(training_schedule) assertEqual(device_state.next_event_time(), training_schedule.start_time) device_state.training_started() assertEqual(device_state.next_event_time(), training_schedule.end_time) device_state.training_ended() assertEqual(device_state.next_event_time(), training_schedule.end_time) def test_device_next_event_time_comparison(self) -> None: training_schedule1 = TrainingSchedule(creation_time=0, start_time=12, end_time=16) device_state_1 = DeviceState(training_schedule1) training_schedule2 = TrainingSchedule(creation_time=0, start_time=12.1, end_time=16.1) device_state_2 = DeviceState(training_schedule2) assertLess(device_state_1, device_state_2) device_state_1.training_started() assertGreater(device_state_1, device_state_2) device_state_2.training_started() assertLess(device_state_1, device_state_2) device_state_1.training_ended() assertLess(device_state_1, device_state_2) device_state_2.training_ended() assertLess(device_state_1, device_state_2) def test_device_next_event_time_comparison_equality(self) -> None: training_schedule1 = TrainingSchedule(creation_time=0, start_time=12, end_time=16) device_state_1 = DeviceState(training_schedule1) training_schedule2 = TrainingSchedule(creation_time=0, start_time=16, end_time=20) device_state_2 = DeviceState(training_schedule2) assertLess(device_state_1, device_state_2) device_state_1.training_started() assertLess(device_state_1, device_state_2) assertGreater(device_state_2, device_state_1) device_state_2.training_started() assertLess(device_state_1, device_state_2) device_state_1.training_ended() assertLess(device_state_1, device_state_2) device_state_2.training_ended() assertLess(device_state_1, device_state_2)
def test_inverse_transform_raises_non_fitted_error(): df1 = pd.DataFrame({'words': ['dog', 'dog', 'cat', 'cat', 'cat', 'bird']}) enc = OrdinalEncoder(encoding_method='arbitrary') with pytest.raises(NotFittedError): enc.inverse_transform(df1) df1.loc[(len(df1) - 1)] = nan with pytest.raises(ValueError): enc.fit(df1) with pytest.raises(NotFittedError): enc.inverse_transform(df1)
class HostCRDClientCertCrossNamespace(AmbassadorTest): target: ServiceType def init(self): self.target = HTTP() def manifests(self) -> str: return ((namespace_manifest('alt-namespace') + self.format((((((('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Host\nmetadata:\n name: {self.path.k8s}\n labels:\n kat-ambassador-id: {self.ambassador_id}\nspec:\n ambassador_id: [ {self.ambassador_id} ]\n hostname: ambassador.example.com\n acmeProvider:\n authority: none\n tlsSecret:\n name: {self.path.k8s}.server\n tls:\n # ca_secret supports cross-namespace references, so test it\n ca_secret: {self.path.k8s}.ca.alt-namespace\n cert_required: true\n---\napiVersion: v1\nkind: Secret\nmetadata:\n name: {self.path.k8s}.ca\n namespace: alt-namespace\n labels:\n kat-ambassador-id: {self.ambassador_id}\ntype: kubernetes.io/tls\ndata:\n tls.crt: ' + TLSCerts['master.datawire.io'].k8s_crt) + '\n tls.key: ""\n---\napiVersion: v1\nkind: Secret\nmetadata:\n name: {self.path.k8s}.server\n labels:\n kat-ambassador-id: {self.ambassador_id}\ntype: kubernetes.io/tls\ndata:\n tls.crt: ') + TLSCerts['ambassador.example.com'].k8s_crt) + '\n tls.key: ') + TLSCerts['ambassador.example.com'].k8s_key) + '\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nmetadata:\n name: {self.path.k8s}\n labels:\n kat-ambassador-id: {self.ambassador_id}\nspec:\n ambassador_id: [ {self.ambassador_id} ]\n hostname: "*"\n prefix: /\n service: {self.target.path.fqdn}\n'))) + super().manifests()) def scheme(self) -> str: return ' def queries(self): base = {'url': self.url(''), 'ca_cert': TLSCerts['master.datawire.io'].pubcert, 'headers': {'Host': 'ambassador.example.com'}, 'sni': True} (yield Query(**base, client_crt=TLSCerts['presto.example.com'].pubcert, client_key=TLSCerts['presto.example.com'].privkey)) (yield Query(**base, maxTLSv='v1.2', error='tls: handshake failure')) (yield Query(**base, minTLSv='v1.3', error=(['tls: certificate required'] + (['write: connection reset by peer', 'write: broken pipe'] if bug_clientcert_reset else [])))) (yield Query(**base, client_crt=TLSCerts['localhost'].pubcert, client_key=TLSCerts['localhost'].privkey, maxTLSv='v1.2', error='tls: handshake failure')) def requirements(self): for r in super().requirements(): query = r[1] query.headers = {'Host': 'ambassador.example.com'} query.sni = True query.ca_cert = TLSCerts['master.datawire.io'].pubcert query.client_cert = TLSCerts['presto.example.com'].pubcert query.client_key = TLSCerts['presto.example.com'].privkey (yield (r[0], query))
def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): (lookupMib, cbFun, cbCtx) = cbCtx if cbFun: varBinds = VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBinds, lookupMib) return cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx) (addrName, paramsName) = LCD.configure(snmpEngine, authData, transportTarget, contextData.contextName) varBinds = VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds) return cmdgen.GetCommandGenerator().sendVarBinds(snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, varBinds, __cbFun, (options.get('lookupMib', True), options.get('cbFun'), options.get('cbCtx')))
class CanadianPostalCode(Regex): format = _('LnL nLn') regex = re.compile('^([a-zA-Z]\\d[a-zA-Z])\\s?(\\d[a-zA-Z]\\d)$') strip = True messages = dict(invalid=_('Please enter a zip code (%(format)s)')) def _convert_to_python(self, value, state): self.assert_string(value, state) match = self.regex.search(value) if (not match): raise Invalid(self.message('invalid', state, format=self.format), value, state) return ('%s %s' % (match.group(1).upper(), match.group(2).upper()))
class RelationshipUtilTest(ForsetiTestCase): def test_get_resource_ancestors_from_full_name(self): mock_starting_resource = mock.MagicMock() mock_starting_resource.type = 'organization' mock_starting_resource.id = 'org1' resource_ancestors = relationship.find_ancestors(mock_starting_resource, 'organization/org1/') self.assertEqual(1, len(resource_ancestors)) mock_starting_resource.type = 'project' mock_starting_resource.id = 'project3' resource_ancestors = relationship.find_ancestors(mock_starting_resource, 'organization/org1/folder/folder2/project/project3/') self.assertEqual(3, len(resource_ancestors)) self.assertEqual(mock_starting_resource, resource_ancestors[0]) self.assertEqual('folder2', resource_ancestors[1].id) self.assertEqual('org1', resource_ancestors[2].id) mock_starting_resource.type = 'firewall' mock_starting_resource.id = 'firewall5' resource_ancestors = relationship.find_ancestors(mock_starting_resource, 'organization/org1/folder/folder2/folder/folder3/project/project4/firewall/firewall5/') self.assertEqual(5, len(resource_ancestors)) self.assertEqual(mock_starting_resource, resource_ancestors[0]) self.assertEqual('project4', resource_ancestors[1].id) self.assertEqual('folder3', resource_ancestors[2].id) self.assertEqual('folder2', resource_ancestors[3].id) self.assertEqual('org1', resource_ancestors[4].id)
class LiteralMap(_common.FlyteIdlEntity): def __init__(self, literals): self._literals = literals def literals(self): return self._literals def to_flyte_idl(self): return _literals_pb2.LiteralMap(literals={k: v.to_flyte_idl() for (k, v) in self.literals.items()}) def from_flyte_idl(cls, pb2_object): return cls({k: Literal.from_flyte_idl(v) for (k, v) in pb2_object.literals.items()})
def apply_gyro_dropout(module: fl.Chain, probability: float=0.5, total_subnetworks: int=32, concurrent_subnetworks: int=16, iters_per_epoch: int=32) -> None: for (linear, parent) in module.walk(fl.Linear): if (not linear.weight.requires_grad): continue assert (not (isinstance(parent, Dropout) or isinstance(parent, GyroDropout))), f'{linear} already has a dropout layer' GyroDropoutAdapter(target=linear, probability=probability, total_subnetworks=total_subnetworks, concurrent_subnetworks=concurrent_subnetworks, iters_per_epoch=iters_per_epoch).inject(parent)
def extractKaedesan721TumblrCom(item): bad_tags = ['FanArt', 'htr asks', 'Spanish translations', 'htr anime', 'my thoughts', 'Cats', 'answered', 'ask meme', 'relay convos', 'translation related post', 'nightmare fuel', 'htr manga', 'memes', 'htrweek', 'Video Games', 'Animation', 'replies', 'jazz', 'Music'] if any([(bad in item['tags']) for bad in bad_tags]): return None (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('my translations' in item['tags']): tagmap = [('Hakata Tonkotsu Ramens', 'Hakata Tonkotsu Ramens', 'translated'), ('hakata tonktosu ramens', 'Hakata Tonkotsu Ramens', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if (tagname in item['tags']): return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
class EmailNotification(SoftDeletionModel): __tablename__ = 'email_notifications' id = db.Column(db.Integer, primary_key=True) next_event = db.Column(db.Boolean, default=False) new_paper = db.Column(db.Boolean, default=False) session_accept_reject = db.Column(db.Boolean, default=False) session_schedule = db.Column(db.Boolean, default=False) after_ticket_purchase = db.Column(db.Boolean, default=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE')) event_id = db.Column(db.Integer, db.ForeignKey('events.id', ondelete='CASCADE')) event = db.relationship('Event') user = db.relationship('User', backref='email_notifications') def __str__(self): return ((('User:' + self.user_id) + ' Event: ') + self.event_id)
class OptionPlotoptionsScatter(Options): def accessibility(self) -> 'OptionPlotoptionsScatterAccessibility': return self._config_sub_data('accessibility', OptionPlotoptionsScatterAccessibility) def allowPointSelect(self): return self._config_get(False) def allowPointSelect(self, flag: bool): self._config(flag, js_type=False) def animation(self): return self._config_get(True) def animation(self, flag: bool): self._config(flag, js_type=False) def animationLimit(self): return self._config_get(None) def animationLimit(self, num: float): self._config(num, js_type=False) def boostBlending(self): return self._config_get('undefined') def boostBlending(self, value: Any): self._config(value, js_type=False) def boostThreshold(self): return self._config_get(5000) def boostThreshold(self, num: float): self._config(num, js_type=False) def className(self): return self._config_get(None) def className(self, text: str): self._config(text, js_type=False) def clip(self): return self._config_get(True) def clip(self, flag: bool): self._config(flag, js_type=False) def cluster(self) -> 'OptionPlotoptionsScatterCluster': return self._config_sub_data('cluster', OptionPlotoptionsScatterCluster) def color(self): return self._config_get(None) def color(self, text: str): self._config(text, js_type=False) def colorAxis(self): return self._config_get(0) def colorAxis(self, num: float): self._config(num, js_type=False) def colorIndex(self): return self._config_get(None) def colorIndex(self, num: float): self._config(num, js_type=False) def colorKey(self): return self._config_get('y') def colorKey(self, text: str): self._config(text, js_type=False) def connectEnds(self): return self._config_get(None) def connectEnds(self, flag: bool): self._config(flag, js_type=False) def connectNulls(self): return self._config_get(False) def connectNulls(self, flag: bool): self._config(flag, js_type=False) def crisp(self): return self._config_get(True) def crisp(self, flag: bool): self._config(flag, js_type=False) def cursor(self): return self._config_get(None) def cursor(self, text: str): self._config(text, js_type=False) def custom(self): return self._config_get(None) def custom(self, value: Any): self._config(value, js_type=False) def dashStyle(self): return self._config_get('Solid') def dashStyle(self, text: str): self._config(text, js_type=False) def dataLabels(self) -> 'OptionPlotoptionsScatterDatalabels': return self._config_sub_data('dataLabels', OptionPlotoptionsScatterDatalabels) def dataSorting(self) -> 'OptionPlotoptionsScatterDatasorting': return self._config_sub_data('dataSorting', OptionPlotoptionsScatterDatasorting) def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def dragDrop(self) -> 'OptionPlotoptionsScatterDragdrop': return self._config_sub_data('dragDrop', OptionPlotoptionsScatterDragdrop) def enableMouseTracking(self): return self._config_get(True) def enableMouseTracking(self, flag: bool): self._config(flag, js_type=False) def events(self) -> 'OptionPlotoptionsScatterEvents': return self._config_sub_data('events', OptionPlotoptionsScatterEvents) def findNearestPointBy(self): return self._config_get('xy') def findNearestPointBy(self, text: str): self._config(text, js_type=False) def getExtremesFromAll(self): return self._config_get(False) def getExtremesFromAll(self, flag: bool): self._config(flag, js_type=False) def inactiveOtherPoints(self): return self._config_get(False) def inactiveOtherPoints(self, flag: bool): self._config(flag, js_type=False) def includeInDataExport(self): return self._config_get(None) def includeInDataExport(self, flag: bool): self._config(flag, js_type=False) def jitter(self) -> 'OptionPlotoptionsScatterJitter': return self._config_sub_data('jitter', OptionPlotoptionsScatterJitter) def keys(self): return self._config_get(None) def keys(self, value: Any): self._config(value, js_type=False) def label(self) -> 'OptionPlotoptionsScatterLabel': return self._config_sub_data('label', OptionPlotoptionsScatterLabel) def legendSymbol(self): return self._config_get('rectangle') def legendSymbol(self, text: str): self._config(text, js_type=False) def linecap(self): return self._config_get(round) def linecap(self, value: Any): self._config(value, js_type=False) def lineWidth(self): return self._config_get(0) def lineWidth(self, num: float): self._config(num, js_type=False) def linkedTo(self): return self._config_get(None) def linkedTo(self, text: str): self._config(text, js_type=False) def marker(self) -> 'OptionPlotoptionsScatterMarker': return self._config_sub_data('marker', OptionPlotoptionsScatterMarker) def negativeColor(self): return self._config_get(None) def negativeColor(self, text: str): self._config(text, js_type=False) def onPoint(self) -> 'OptionPlotoptionsScatterOnpoint': return self._config_sub_data('onPoint', OptionPlotoptionsScatterOnpoint) def opacity(self): return self._config_get(1) def opacity(self, num: float): self._config(num, js_type=False) def point(self) -> 'OptionPlotoptionsScatterPoint': return self._config_sub_data('point', OptionPlotoptionsScatterPoint) def pointDescriptionFormat(self): return self._config_get(None) def pointDescriptionFormat(self, value: Any): self._config(value, js_type=False) def pointDescriptionFormatter(self): return self._config_get(None) def pointDescriptionFormatter(self, value: Any): self._config(value, js_type=False) def pointInterval(self): return self._config_get(1) def pointInterval(self, num: float): self._config(num, js_type=False) def pointIntervalUnit(self): return self._config_get(None) def pointIntervalUnit(self, value: Any): self._config(value, js_type=False) def pointStart(self): return self._config_get(0) def pointStart(self, num: float): self._config(num, js_type=False) def relativeXValue(self): return self._config_get(False) def relativeXValue(self, flag: bool): self._config(flag, js_type=False) def selected(self): return self._config_get(False) def selected(self, flag: bool): self._config(flag, js_type=False) def showCheckbox(self): return self._config_get(False) def showCheckbox(self, flag: bool): self._config(flag, js_type=False) def showInLegend(self): return self._config_get(None) def showInLegend(self, flag: bool): self._config(flag, js_type=False) def skipKeyboardNavigation(self): return self._config_get(None) def skipKeyboardNavigation(self, flag: bool): self._config(flag, js_type=False) def softThreshold(self): return self._config_get(True) def softThreshold(self, flag: bool): self._config(flag, js_type=False) def sonification(self) -> 'OptionPlotoptionsScatterSonification': return self._config_sub_data('sonification', OptionPlotoptionsScatterSonification) def stacking(self): return self._config_get(None) def stacking(self, text: str): self._config(text, js_type=False) def states(self) -> 'OptionPlotoptionsScatterStates': return self._config_sub_data('states', OptionPlotoptionsScatterStates) def step(self): return self._config_get(None) def step(self, value: Any): self._config(value, js_type=False) def stickyTracking(self): return self._config_get(False) def stickyTracking(self, flag: bool): self._config(flag, js_type=False) def threshold(self): return self._config_get(0) def threshold(self, num: float): self._config(num, js_type=False) def tooltip(self) -> 'OptionPlotoptionsScatterTooltip': return self._config_sub_data('tooltip', OptionPlotoptionsScatterTooltip) def turboThreshold(self): return self._config_get(1000) def turboThreshold(self, num: float): self._config(num, js_type=False) def visible(self): return self._config_get(True) def visible(self, flag: bool): self._config(flag, js_type=False) def zoneAxis(self): return self._config_get('y') def zoneAxis(self, text: str): self._config(text, js_type=False) def zones(self) -> 'OptionPlotoptionsScatterZones': return self._config_sub_data('zones', OptionPlotoptionsScatterZones)
_settings(ROOT_URLCONF='tests.browsable_api.no_auth_urls') class AnonymousUserTests(TestCase): def setUp(self): self.client = APIClient(enforce_csrf_checks=True) def tearDown(self): self.client.logout() def test_get_raises_typeerror_when_anonymous_user_in_queryset_filter(self): with self.assertRaises(TypeError): self.client.get('/basicviewset') def test_get_returns_ old_permissions = BasicModelWithUsersViewSet.permission_classes BasicModelWithUsersViewSet.permission_classes = [IsAuthenticated, OrganizationPermissions] response = self.client.get('/basicviewset') BasicModelWithUsersViewSet.permission_classes = old_permissions self.assertEqual(response.status_code, 403)
class RegReplaceEditRegexCommand(sublime_plugin.WindowCommand): def needs_escape(self, string, target_char, quote_count=1): skip = False count = 0 needs_escape = False for c in string: if skip: skip = False continue if (c == '\\'): skip = True elif (c == target_char): count += 1 if (count == quote_count): needs_escape = True break else: count = 0 return needs_escape def fix_escape(self, string, target_char, quote_count=1): skip = False count = 0 fixed = [] for c in string(): if skip: fixed.append(c) continue if (c == '\\'): skip = True fixed.append(c) elif (c == target_char): count += 1 if (count == quote_count): fixed.append('\\') fixed.append(c) count = 0 else: fixed.append(c) else: count = 0 fixed.append(c) return ''.join(fixed) def format_string(self, name, value): if ((value is not None) and isinstance(value, str)): string = ('%s = %s\n' % (name, self.simple_format_string(value))) else: string = ('%s = None\n' % name) return string def format_regex_string(self, name, value): if ((value is not None) and isinstance(value, str)): string = ('%s = %s\n' % (name, self.simple_format_string(value, force_raw=True))) else: string = ('%s = None\n' % name) return string def simple_format_string(self, value, force_raw=False): m = re.search('((\\n)|\\r|\\n|\\t|\\\\)', value) newlines = False raw = '' if m: if m.group(2): newlines = True raw = 'r' if (force_raw and (not raw)): raw = 'r' single = self.needs_escape(value, "'") double = self.needs_escape(value, '"') tsingle = self.needs_escape(value, "'", quote_count=3) tdouble = self.needs_escape(value, '"', quote_count=3) if ((not double) and (not newlines)): string = ('%s"%s"' % (raw, value)) elif ((not single) and (not newlines)): string = ("%s'%s'" % (raw, value)) elif (not tdouble): string = ('%s"""%s"""' % (raw, value)) elif (not tsingle): string = ("%s'''%s'''" % (raw, value)) elif (not newlines): string = ('%s"%s"' % (raw, self.fix_escape(value, '"'))) else: string = ('%s"""%s"""' % (raw, self.fix_escape(value, '"', quote_count=3))) return string def format_array(self, name, value): if ((value is not None) and isinstance(value, list)): array = ('%s = [\n%s]\n' % (name, self.parse_array(value, 1))) else: array = ('%s = None\n' % name) return array def format_bool(self, name, value): if ((value is not None) and isinstance(value, bool)): boolean = ('%s = %s\n' % (name, str(value))) else: boolean = ('%s = None\n' % name) return boolean def parse_array(self, value, indent): array = '' for v in value: if (v is None): array += ('%(indent)sNone,\n' % {'indent': (' ' * indent)}) elif isinstance(v, str): array += ('%(indent)s%(content)s,\n' % {'indent': (' ' * indent), 'content': self.simple_format_string(v)}) elif isinstance(v, (int, float)): array += ('%(indent)s%(content)s,\n' % {'indent': (' ' * indent), 'content': v.__repr__()}) elif isinstance(v, list): array += ('%(indent)s[\n%(content)s%(indent)s],\n' % {'indent': (' ' * indent), 'content': self.parse_array(v, (indent + 1))}) elif isinstance(v, dict): array += ('%(indent)s{\n%(content)s%(indent)s},\n' % {'indent': (' ' * indent), 'content': self.parse_dict(v, (indent + 1))}) return array def parse_dict(self, value, indent): dictionary = '' for (k, v) in value.items(): if (v is None): dictionary += ('%(indent)s%(name)s: None,\n' % {'name': self.simple_format_string(k), 'indent': (' ' * indent)}) elif isinstance(v, str): dictionary += ('%(indent)s%(name)s: %(content)s,\n' % {'name': self.simple_format_string(k), 'indent': (' ' * indent), 'content': self.simple_format_string(v)}) elif isinstance(v, (int, float)): dictionary += ('%(indent)s%(name)s: %(content)s,\n' % {'name': self.simple_format_string(k), 'indent': (' ' * indent), 'content': v.__repr__()}) elif isinstance(v, list): dictionary += ('%(indent)s%(name)s: [\n%(content)s%(indent)s],\n' % {'name': self.simple_format_string(k), 'indent': (' ' * indent), 'content': self.parse_array(v, (indent + 1))}) elif isinstance(v, dict): dictionary += ('%(indent)s%(name)s: {\n%(content)s%(indent)s},\n' % {'name': self.simple_format_string(k), 'indent': (' ' * indent), 'content': self.parse_dict(v, (indent + 1))}) return dictionary def format_dict(self, name, value): if ((value is not None) and isinstance(value, dict)): if len(value): dictionary = ('%(name)s = {\n%(content)s}\n' % {'name': name, 'content': self.parse_dict(value, 1)}) else: dictionary = ('%s%s = {}\n' % name) else: dictionary = ('%s = None\n' % name) return dictionary def edit_rule(self, value, new=False): if ((value >= 0) or new): if new: name = None rule = {} else: name = self.keys[value] rule = self.rules[value] text = '"""\nIf you don\'t need a setting, just leave it as None.\n' text += 'When the rule is parsed, the default will be used.\n' text += 'Each variable is evaluated separately, so you cannot substitute variables ' text += 'in other variables.\n"""\n' text += '\n# name (str): Rule name. Required.\n' text += self.format_string('name', name) text += '\n# find (str): Regular expression pattern or literal string.\n' text += '# Use (?i) for case insensitive. Use (?s) for dotall.\n' text += '# See for more info on regex flags.\n' text += '# Required unless "scope" is defined.\n' text += self.format_regex_string('find', rule.get('find')) text += "\n# replace (str - default=r'\\g<0>'): Replace pattern.\n" text += self.format_regex_string('replace', rule.get('replace')) text += '\n# literal (bool - default=False): Preform a non-regex, literal search and replace.\n' text += self.format_bool('literal', rule.get('literal')) text += '\n# literal_ignorecase (bool - default=False): Ignore case when "literal" is true.\n' text += self.format_bool('literal_ignorecase', rule.get('literal_ignorecase')) text += '\n# scope (str): Scope to search for and to apply optional regex to.\n' text += '# Required unless "find" is defined.\n' text += self.format_string('scope', rule.get('scope')) text += '\n# scope_filter ([str] - default=[]): An array of scope qualifiers for the match.\n' text += '# Only used when "scope" is not defined.\n' text += '#\n' text += '# - Any instance of scope qualifies match: scope.name\n' text += '# - Entire match of scope qualifies match: !scope.name\n' text += '# - Any instance of scope disqualifies match: -scope.name\n' text += '# - Entire match of scope disqualifies match: -!scope.name\n' text += self.format_array('scope_filter', rule.get('scope_filter')) text += '\n# greedy (bool - default=True): Apply action to all instances (find all).\n' text += '# Used when "find" is defined.\n' text += self.format_bool('greedy', rule.get('greedy')) text += '\n# greedy_scope (bool - default=True): Find all the scopes specified by "scope."\n' text += self.format_bool('greedy_scope', rule.get('greedy_scope')) text += '\n# format_replace (bool - default=False): Use format string style replace templates.\n' text += '# Works only for Regex (with and without Backrefs) and Re (with Backrefs).\n' text += '# See for more info.\n' text += self.format_bool('format_replace', rule.get('format_replace')) text += '\n# selection_inputs (bool -default=False): Use selection for inputs into find pattern.\n' text += '# Global setting "selection_only" must be disabled for this to work.\n' text += self.format_bool('selection_inputs', rule.get('selection_inputs')) text += '\n# multi_pass (bool - default=False): Perform multiple sweeps on the scope region to find\n' text += '# and replace all instances of the regex when regex cannot be formatted to find\n' text += '# all instances. Since a replace can change a scope, this can be useful.\n' text += self.format_bool('multi_pass', rule.get('multi_pass')) text += '\n# plugin (str): Define replace plugin for more advanced replace logic.\n' text += self.format_string('plugin', rule.get('plugin')) text += "\n# args (dict): Arguments for 'plugin'.\n" text += self.format_dict('args', rule.get('args')) text += '\n# \n' text += '# test: Here you can setup a test command. This is not saved and is just used for this session.\n' text += '# - replacements ([str]): A list of regex rules to sequence together.\n' text += '# - find_only (bool): Highlight current find results and prompt for action.\n' text += '# - action (str): Apply the given action (fold|unfold|mark|unmark|select).\n' text += '# This overrides the default replace action.\n' text += '# - options (dict): optional parameters for actions (see documentation for more info).\n' text += '# - key (str): Unique name for highlighted region.\n' text += '# - scope (str - default="invalid"): Scope name to use as the color.\n' text += '# - style (str - default="outline"): Highlight style (solid|underline|outline).\n' text += '# - multi_pass (bool): Repeatedly sweep with sequence to find all instances.\n' text += '# - no_selection (bool): Overrides the "selection_only" setting and forces no selections.\n' text += '# - regex_full_file_with_selections (bool): Apply regex search to full file then apply\n' text += '# action to results under selections.\n' text += textwrap.dedent((' test = {\n "replacements": [%s],\n "find_only": True,\n "action": None,\n "options": {},\n "multi_pass": False,\n "no_selection": False,\n "regex_full_file_with_selections": False\n }\n ' % (self.simple_format_string(name) if (name is not None) else ''))) replace_view = self.window.create_output_panel('reg_replace') replace_view.run_command('reg_replace_panel_insert', {'text': text}) for ext in ST_LANGUAGES: highlighter = sublime.load_settings('reg_replace.sublime-settings').get('python_highlighter', 'Python/Python') highlighter = (('Packages/' + highlighter) + ext) try: sublime.load_resource(highlighter) replace_view.set_syntax_file(highlighter) break except Exception: pass replace_view.settings().set('gutter', True) replace_view.settings().set('line_numbers', True) replace_view.settings().set('reg_replace.edit_view', True) replace_view.settings().set('bracket_highlighter.bracket_string_escape_mode', 'regex') replace_view.settings().set('regreplace.name', name) replace_view.sel().clear() replace_view.sel().add(sublime.Region(0, 0)) self.window.run_command('show_panel', {'panel': 'output.reg_replace'}) sublime.set_timeout((lambda w=self.window, v=replace_view: w.focus_view(v)), 100) def run(self, new=False): if new: self.edit_rule((- 1), new=True) else: self.keys = [] self.rules = [] rules = sublime.load_settings('reg_replace_rules.sublime-settings').get('replacements', {}) for (name, rule) in sorted(rules.items()): self.keys.append(name) self.rules.append(rule) if len(self.keys): self.window.show_quick_panel(self.keys, self.edit_rule)
class Solution(): def searchRange(self, nums: List[int], target: int) -> List[int]: def search(lo, hi): if (nums[lo] == target == nums[hi]): return [lo, hi] if (nums[lo] <= target <= nums[hi]): mid = ((lo + hi) // 2) (l, r) = (search(lo, mid), search((mid + 1), hi)) return (max(l, r) if ((- 1) in (l + r)) else [l[0], r[1]]) return [(- 1), (- 1)] if (not nums): return [(- 1), (- 1)] return search(0, (len(nums) - 1)) def searchRange2(self, nums: List[int], target: int) -> List[int]: import bisect (left, right) = (bisect.bisect_left(nums, target), bisect.bisect_right(nums, target)) if (left == right): return [(- 1), (- 1)] return [left, (right - 1)]
class SetRef(_Expr): def __init__(self, set_ref): if isinstance(set_ref, _Expr): value = set_ref.value else: value = set_ref super(SetRef, self).__init__(value) def to_fauna_json(self): return {'': self.value} def __repr__(self): return ('SetRef(%s)' % repr(self.value)) def __eq__(self, other): return (isinstance(other, SetRef) and (self.value == other.value)) def __ne__(self, other): return (not (self == other))
class OptionPlotoptionsBarSonificationContexttracksMappingNoteduration(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class ReceptiveCollectionPanel(CollectionPanel): def drag_data_received(self, widget, context, x, y, data, info, stamp): uris = data.get_uris() (tracks, playlists) = self.tree.get_drag_data(uris) tracks = [t for t in tracks if (not self.collection.loc_is_member(t.get_loc_for_io()))] self.add_tracks_func(tracks) def add_tracks_func(self, tracks): locs = [t['__loc'] for t in tracks] lib = self.collection.get_libraries()[0] for l in locs: lib.add(l)
(st.binary()) def test_sign_message_against_sign_hash_as_bytes(keyed_acct, message_bytes): msg_hash = defunct_hash_message(message_bytes) with pytest.deprecated_call(): signed_via_hash = keyed_acct.signHash(msg_hash) signable_message = encode_defunct(message_bytes) signed_via_message = keyed_acct.sign_message(signable_message) assert (signed_via_hash == signed_via_message)
def check_password_format(password, username, email): if (not (any((s.isupper() for s in password)) and any((s.islower() for s in password)))): return False if (len(password) < 8): return False if (not any([c.isdigit() for c in password])): return False if (username in password): return False if (email in password): return False return True
('bodhi.server.models.work_on_bugs_task', mock.Mock()) ('bodhi.server.models.fetch_test_cases_task', mock.Mock()) class TestUpdateMeetsTestingRequirements(BasePyTestCase): def test_autokarma_update_reaching_stable_karma(self): update = model.Update.query.first() update.autokarma = True update.status = UpdateStatus.testing update.stable_karma = 1 with mock_sends(Message): update.comment(self.db, 'testing', author='hunter2', karma=1) assert update.meets_testing_requirements def test_critpath_14_days_negative_karma(self): update = model.Update.query.first() update.critpath = True update.status = model.UpdateStatus.testing update.request = None update.date_testing = (datetime.utcnow() - timedelta(days=15)) update.stable_karma = 1 update.comment(self.db, 'testing', author='enemy', karma=(- 1)) update.comment(self.db, 'testing', author='bro', karma=1) assert (not update.meets_testing_requirements) def test_critpath_14_days_no_negative_karma(self): update = model.Update.query.first() update.critpath = True update.status = model.UpdateStatus.testing update.request = None update.date_testing = (datetime.utcnow() - timedelta(days=15)) update.stable_karma = 1 assert update.meets_testing_requirements def test_critpath_karma_2_met(self): update = model.Update.query.first() update.critpath = True update.stable_karma = 1 with mock_sends(Message, Message, Message, Message, Message): update.comment(self.db, 'testing', author='enemy', karma=(- 1)) update.comment(self.db, 'testing', author='bro', karma=1) update.comment(self.db, 'testing', author='ham', karma=1) assert update.meets_testing_requirements def test_critpath_karma_2_required(self): update = model.Update.query.first() update.critpath = True update.stable_karma = 1 assert (not update.meets_testing_requirements) def test_critpath_negative_karma(self): update = model.Update.query.first() update.critpath = True update.comment(self.db, 'testing', author='enemy', karma=(- 1)) assert (not update.meets_testing_requirements) def test_karma_2_met(self): update = model.Update.query.first() update.stable_karma = 3 update.comment(self.db, 'testing', author='enemy', karma=(- 1)) update.comment(self.db, 'testing', author='bro', karma=1) update.comment(self.db, 'testing', author='ham', karma=1) assert update.meets_testing_requirements def test_non_autokarma_update_below_stable_karma(self): update = model.Update.query.first() update.autokarma = False update.comments = [] update.status = UpdateStatus.testing update.stable_karma = 1 assert (not update.meets_testing_requirements) def test_non_autokarma_update_reaching_stable_karma(self): update = model.Update.query.first() update.autokarma = False update.status = UpdateStatus.testing update.stable_karma = 1 assert update.meets_testing_requirements def test_test_gating_faild_no_testing_requirements(self): config['test_gating.required'] = True update = model.Update.query.first() update.autokarma = False update.stable_karma = 1 update.test_gating_status = TestGatingStatus.failed update.comment(self.db, 'I found $100 after applying this update.', karma=1, author='bowlofeggs') assert (not update.meets_testing_requirements) def test_test_gating_queued_no_testing_requirements(self): config['test_gating.required'] = True update = model.Update.query.first() update.autokarma = False update.stable_karma = 1 update.test_gating_status = TestGatingStatus.queued update.comment(self.db, 'I found $100 after applying this update.', karma=1, author='bowlofeggs') assert (not update.meets_testing_requirements) def test_test_gating_running_no_testing_requirements(self): config['test_gating.required'] = True update = model.Update.query.first() update.autokarma = False update.stable_karma = 1 update.test_gating_status = TestGatingStatus.running update.comment(self.db, 'I found $100 after applying this update.', karma=1, author='bowlofeggs') assert (not update.meets_testing_requirements) def test_test_gating_missing_testing_requirements(self): config['test_gating.required'] = True update = model.Update.query.first() update.autokarma = False update.stable_karma = 1 update.test_gating_status = None update.comment(self.db, 'I found $100 after applying this update.', karma=1, author='bowlofeggs') assert update.meets_testing_requirements def test_test_gating_waiting_testing_requirements(self): config['test_gating.required'] = True update = model.Update.query.first() update.autokarma = False update.stable_karma = 1 update.test_gating_status = TestGatingStatus.waiting update.comment(self.db, 'I found $100 after applying this update.', karma=1, author='bowlofeggs') assert (not update.meets_testing_requirements) def test_test_gating_off(self): config['test_gating.required'] = False update = model.Update.query.first() update.autokarma = False update.stable_karma = 1 update.test_gating_status = TestGatingStatus.running update.comment(self.db, 'I found $100 after applying this update.', karma=1, author='bowlofeggs') assert update.meets_testing_requirements def test_time_in_testing_met(self): update = model.Update.query.first() update.status = model.UpdateStatus.testing update.request = None update.date_testing = (datetime.utcnow() - timedelta(days=8)) update.stable_karma = 10 assert update.meets_testing_requirements def test_time_in_testing_unmet(self): update = model.Update.query.first() update.status = model.UpdateStatus.testing update.request = None update.date_testing = (datetime.utcnow() - timedelta(days=6)) update.stable_karma = 10 assert (not update.meets_testing_requirements)
def test_filter_object_no_results(): config = FilterPostProcessorConfiguration(field='email_contact', value='') data = {'id': , 'email_contact': 'somebody-', 'name': 'Somebody Cool'} processor = FilterPostProcessorStrategy(configuration=config) result = processor.process(data) assert (result == [])
def component_name_convention(ecs_version: str, ecs_nested: Dict[(str, FieldNestedEntry)]) -> List[str]: version: str = ecs_version.replace('+', '-') names: List[str] = [] for (fieldset_name, fieldset) in ecs_helpers.remove_top_level_reusable_false(ecs_nested).items(): names.append('ecs_{}_{}'.format(version, fieldset_name.lower())) return names
class LocatedSlider(): def __init__(self, slider): self.slider = slider def register(cls, registry): registry.register_interaction(target_class=cls, interaction_class=KeyClick, handler=(lambda wrapper, interaction: _interaction_helpers.key_click_slider(wrapper._target.slider, interaction, wrapper.delay)))
class Solution(): def openLock(self, deadends: List[str], target: str) -> int: def find_neighbors(curr, visited, deadends): for (i, c) in enumerate(curr): ncs = [chr(((((ord(c) - ord('0')) + 11) % 10) + ord('0'))), chr(((((ord(c) - ord('0')) + 9) % 10) + ord('0')))] for nc in ncs: ncurr = ((curr[:i] + nc) + curr[(i + 1):]) if ((ncurr not in visited) and (ncurr not in deadends)): (yield ncurr) deadends = set(deadends) queue = deque() queue.append(('0000', 0)) visited = set() while queue: (curr, step) = queue.popleft() if (curr in deadends): return (- 1) if (curr == target): return step if (curr in visited): continue visited.add(curr) for ne in find_neighbors(curr, visited, deadends): queue.append((ne, (step + 1))) return (- 1)
class ProductionInfo(): children: Dict[(str, ProductionChildInfo)] def from_class(production_rule): children = {} production_name = production_rule.__name__ try: type_hints = get_type_hints(production_rule) except (NameError or TypeError) as e: raise GrammarError(f'Production class {production_name} could not be processed.') from e for (name, annotation) in type_hints.items(): try: child_info = ProductionChildInfo.from_type_hint(annotation, production_name, name) if (child_info is not None): if Production.is_production(child_info.symbol): children[name] = child_info except GrammarError as e: raise GrammarError(f'Production class {production_name} could not process child {name}.') from e return ProductionInfo(children)
class Solution(): def addToArrayForm(self, num: List[int], k: int) -> List[int]: def int_to_arr(val): ret = [] while (val > 0): (val, c) = divmod(val, 10) ret.append(c) return ret[::(- 1)] def add_arrs(arr1, arr2): ret = [] carry = 0 for (a, b) in itertools.zip_longest(reversed(arr1), reversed(arr2), fillvalue=0): (carry, c) = divmod(((a + b) + carry), 10) ret.append(c) if (carry != 0): ret.append(carry) return ret[::(- 1)] return add_arrs(num, int_to_arr(k))
class WorkflowClosure(_common.FlyteIdlEntity): def __init__(self, compiled_workflow): self._compiled_workflow = compiled_workflow def compiled_workflow(self): return self._compiled_workflow def to_flyte_idl(self): return _admin_workflow.WorkflowClosure(compiled_workflow=self.compiled_workflow.to_flyte_idl()) def from_flyte_idl(cls, p): return cls(compiled_workflow=_compiler_models.CompiledWorkflowClosure.from_flyte_idl(p.compiled_workflow))
class TestStorageUtil(): def test_get_schema_for_secrets_invalid_storage_type(self): with pytest.raises(ValueError): get_schema_for_secrets('invalid_storage_type', StorageSecretsS3(aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key')) with pytest.raises(ValueError): get_schema_for_secrets(StorageType.local, StorageSecretsS3(aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key')) with pytest.raises(ValueError) as e: get_schema_for_secrets(StorageType.s3, {'aws_access_key_id': 'aws_access_key_id', 'aws_secret_access_key': 'aws_secret_access_key', 'fake_key': 'aws_secret_access_key'}) assert ('extra fields not permitted' in str(e)) def test_get_schema_for_secrets(self): secrets = get_schema_for_secrets('s3', StorageSecretsS3(aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key')) assert (secrets.aws_access_key_id == 'aws_access_key_id') assert (secrets.aws_secret_access_key == 'aws_secret_access_key') secrets = get_schema_for_secrets(StorageType.s3, StorageSecretsS3(aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key')) assert (secrets.aws_access_key_id == 'aws_access_key_id') assert (secrets.aws_secret_access_key == 'aws_secret_access_key')
class ExtractEntityParser(BaseOutputParser): def __init__(self, is_stream_out: bool, **kwargs): super().__init__(is_stream_out=is_stream_out, **kwargs) def parse_prompt_response(self, response, max_length: int=128) -> Set[str]: lowercase = True print('clean prompt response:', response) results = [] response = response.strip() if response.startswith('KEYWORDS:'): response = response[len('KEYWORDS:'):] keywords = response.split(',') for k in keywords: rk = k if lowercase: rk = rk.lower() results.append(rk.strip()) return set(results) def parse_view_response(self, speak, data) -> str: return data
class Container(containers.DeclarativeContainer): config = providers.Configuration(default={'target': 'A', 'items': {'A': {'option1': 60, 'option2': 80}, 'B': {'option1': 10, 'option2': 20}}}) foo_factory = providers.Factory(Foo, option1=config.items[config.target].option1, option2=config.items[config.target].option2)
def get_webcam_capture() -> Optional[cv2.VideoCapture]: global WEBCAM_CAPTURE if (WEBCAM_CAPTURE is None): if (platform.system().lower() == 'windows'): webcam_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) else: webcam_capture = cv2.VideoCapture(0) if (webcam_capture and webcam_capture.isOpened()): WEBCAM_CAPTURE = webcam_capture return WEBCAM_CAPTURE
class OptionSeriesAreaSonificationTracksMappingTremoloDepth(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): self._config(text, js_type=False) def max(self): return self._config_get(None) def max(self, num: float): self._config(num, js_type=False) def min(self): return self._config_get(None) def min(self, num: float): self._config(num, js_type=False) def within(self): return self._config_get(None) def within(self, value: Any): self._config(value, js_type=False)
class GPTNeoXCausalLM(TransformerCausalLM[GPTNeoXConfig], FromHFHub[GPTNeoXConfig], Quantizable): def __init__(self, config: GPTNeoXConfig, *, device: Optional[torch.device]=None) -> None: super().__init__(config) self.decoder = GPTNeoXDecoder(config, device=device) self.output_embeddings = Linear(in_features=config.layer.feedforward.hidden_width, out_features=config.embedding.n_pieces, bias=False, device=device) def is_supported(cls: Type[Self], config: Dict[(str, Any)]) -> bool: return (config.get('model_type') == 'gpt_neox') def state_dict_from_hf(cls: Type[Self], params: Mapping[(str, Tensor)]) -> Mapping[(str, Tensor)]: return state_dict_from_hf(params, CAUSAL_LM_HF_PARAM_KEY_TRANSFORMS) def state_dict_to_hf(cls: Type[Self], params: Mapping[(str, Tensor)]) -> Mapping[(str, Tensor)]: return state_dict_to_hf(params, CAUSAL_LM_HF_PARAM_KEY_TRANSFORMS) def config_from_hf(cls, hf_config: Mapping[(str, Any)]) -> GPTNeoXConfig: return _config_from_hf(hf_config) def config_to_hf(cls, curated_config: GPTNeoXConfig) -> Mapping[(str, Any)]: return _config_to_hf(cls, curated_config) def from_hf_config(cls: Type[Self], *, hf_config: Any, device: Optional[torch.device]=None) -> Self: config = cls.config_from_hf(hf_config) return cls(config, device=device) def modules_to_not_quantize(cls) -> Set[str]: return {'output_embeddings'}
def check_device_perms(): logging.debug('Checking input devices permissions') uinput_path = Path('/dev/uinput') if (not uinput_path.exists()): return None has_perms = os.access(uinput_path, (os.R_OK | os.W_OK)) if (not has_perms): MSG_NO_INPUT_DEV_PERMS.show() return has_perms
class OptionPlotoptionsNetworkgraphDatalabelsTextpath(Options): def attributes(self): return self._config_get(None) def attributes(self, value: Any): self._config(value, js_type=False) def enabled(self): return self._config_get(False) def enabled(self, flag: bool): self._config(flag, js_type=False)
def narrow_to_non_space(view: sublime.View, region: sublime.Region, direction=(NON_SPACE_LEFT | NON_SPACE_RIGHT)) -> sublime.Region: begin = region.begin() end = region.end() if (direction & NON_SPACE_LEFT): while (begin < end): if (not view.substr(begin).isspace()): break begin += 1 if (direction & NON_SPACE_RIGHT): while (end > begin): if (not view.substr((end - 1)).isspace()): break end -= 1 return sublime.Region(begin, end)
(vrrp.VRRP_VERSION_V2) class VRRPRouterV2(VRRPRouter): _STATE_MAP = {vrrp_event.VRRP_STATE_INITIALIZE: VRRPV2StateInitialize, vrrp_event.VRRP_STATE_MASTER: VRRPV2StateMaster, vrrp_event.VRRP_STATE_BACKUP: VRRPV2StateBackup} def __init__(self, *args, **kwargs): super(VRRPRouterV2, self).__init__(*args, **kwargs) def start(self): params = self.params params.master_adver_interval = self.config.advertisement_interval self.state_change(vrrp_event.VRRP_STATE_INITIALIZE) if self.config.address_owner: self.send_advertisement() self.state_change(vrrp_event.VRRP_STATE_MASTER) self.adver_timer.start(self.config.advertisement_interval) else: self.state_change(vrrp_event.VRRP_STATE_BACKUP) self.master_down_timer.start(params.master_down_interval) super(VRRPRouterV2, self).start()
class DataSet(DataAttrs): def backgroundColor(self): return self._attrs.get('backgroundColor') def backgroundColor(self, color: str): self.set_val(color) def borderColor(self): return self._attrs.get('borderColor') def borderColor(self, color: str): self.set_val(color) def borderWidth(self): return self._attrs.get('borderWidth') def borderWidth(self, val: int): self._attrs['borderWidth'] = val def fillOpacity(self): return self._attrs.get('backgroundColor') def fillOpacity(self, val): bg_colors = self._attrs['backgroundColor'] if isinstance(bg_colors, list): op_colors = [] for c in bg_colors: color = Colors.getHexToRgb(c) op_colors.append(('rgba(%s, %s, %s, %s)' % (color[0], color[1], color[2], val))) self._attrs['backgroundColor'] = op_colors elif bg_colors.startswith('rgba'): split_colors = bg_colors.split(',') split_colors[3] = (' %s)' % val) self._attrs['backgroundColor'] = ','.join(split_colors) else: color = Colors.getHexToRgb(self._attrs['backgroundColor']) self._attrs['backgroundColor'] = ('rgba(%s, %s, %s, %s)' % (color[0], color[1], color[2], val)) def fontColor(self): return self._attrs.get('fontColor') def fontColor(self, color: str): self.set_val(color) def fontFamily(self): return self._attrs.get('fontFamily') def fontFamily(self, value: str): self.set_val(value) def set_style(self, background_color: str=None, fill_opacity: int=None, border_width: int=None, border_color: str=None): if (background_color is not None): self.backgroundColor = background_color if (fill_opacity is not None): self.fillOpacity = fill_opacity if (border_width is not None): self.borderWidth = border_width if (border_color is not None): self.borderColor = border_color return self
class QueryServicer(object): def Proposal(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Proposals(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Vote(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Votes(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Params(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Deposit(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def Deposits(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def TallyResult(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')