def draw_line(self, x0: int, y0: int, x1: int, y1: int, color: int): """ Bresenham algorithm """ dx = x1 - x0 dy = y1 - y0 if abs(dx) >= abs(dy): # x-driving axis x_start = min(x0, x1) x_end = max(x0, x1) y = y0 if x0 < x1 else y1 dy = dy if x0 < x1 else -dy eps = abs(dy) - abs(dx) for x in range(x_start, x_end + 1): self.pixel_buffer.fill_pixel(x, y, color) if eps >= 0: y += sign(dy) eps -= abs(dx) eps += abs(dy) else: # y-driving axis y_start = min(y0, y1) y_end = max(y0, y1) x = x0 if y0 < y1 else x1 dx = dx if y0 < y1 else -dx eps = abs(dx) - abs(dy) for y in range(y_start, y_end + 1): self.pixel_buffer.fill_pixel(x, y, color) if eps >= 0: x += sign(dx) eps -= abs(dy) eps += abs(dx)
def _deaccelerate(self) -> None: self.vel.x -= 0.1 * sign(self.vel.x) if abs(self.vel.x) > self._max_speed: self.vel.x -= 0.2 * sign(self.vel.x) if abs(self.vel.x) <= 0.1: self.vel.x = 0
def RRA(self): # Rotate Right then Add with Carry # ROR + ADC # 同样用到了A, 也没有IMP的情况 c = self.registers['P'][0] bit_0 = self.cur_value & 1 value = (self.cur_value >> 1) % 128 + (c << 7) self.space[self.cur_ad] = value self.registers['P'][0] = bit_0 result = self.A + value + self.registers['P'][0] signed_a = sign(self.A) signed_value = sign(value) signed_result = signed_a + signed_value + self.registers['P'][0] if result > 255: self.registers['P'][0] = 1 else: self.registers['P'][0] = 0 if signed_result < -127 or signed_result > 128: self.registers['P'][6] = 1 else: self.registers['P'][6] = 0 set_value = result % 256 self.check_z_flag(set_value) self.check_n_flag(set_value) self.A = set_value
def update(self): """ An update on the robot. Performed once per timestep. Will use robots information to set a linear speed and a turning speed """ speed = self._TARGET_SPEED x, y = self._communicator.get_position() heading = self._communicator.get_heading() try: gamma = self._path_tracker.get_turn_radius_inverse(x, y, heading) turn_speed = gamma * speed except NoPointObservableError: # Make the robot rotate til it sees points to go to current_angular_speed = self._communicator.get_angular_speed() turn_speed = utils.sign(current_angular_speed) * \ self._MAX_TURNING_SPEED speed = 0 if not self._turning_to_find_point: self._turning_to_find_point = time() else: if self._turning_to_find_point - time() > \ self._TURNING_TO_FIND_POINT_TIME: raise NoPointObservableError() if abs(turn_speed) > self._MAX_TURNING_SPEED: # Limit linear speed as max turning speed is constant turn_speed = utils.sign(turn_speed) * self._MAX_TURNING_SPEED speed = turn_speed / gamma self._communicator.post_speed(turn_speed, speed)
def derived_key(self): kDate = utils.sign(("AWS4" + self.secret_access_key).encode("utf-8"), utils.time("%Y%m%d")) kRegion = utils.sign(kDate, self.region) kService = utils.sign(kRegion, "glacier") kSigning = utils.sign(kService, "aws4_request") return kSigning
def test(diff, i): summ = 0 success = 0 for j in range(len(weights)): summ += diff[i + j + 1] * weights[j] return utils.sign(summ) == utils.sign(diff[i])
def test_write(tmp_path): binary_name = "crypt_and_hash" fat = lief.MachO.parse( get_sample( 'MachO/9edfb04c55289c6c682a25211a4b30b927a86fe50b014610d04d6055bd4ac23d_crypt_and_hash.macho' )) target = fat.take(lief.MachO.CPU_TYPES.ARM64) output = f"{tmp_path}/{binary_name}.built" target.write(output) target = lief.parse(output) process(target) valid, err = lief.MachO.check_layout(target) assert valid, err if is_apple_m1(): chmod_exe(output) sign(output) with subprocess.Popen([output], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: stdout = proc.stdout.read() assert "CAMELLIA-256-CCM*-NO-TAG" in stdout assert "AES-128-CCM*-NO-TAG" in stdout
def step(self, steps): """Step the motors in sync.""" biggest = int(max(abs(steps.r), abs(steps.t))) step_size = Steps(float(steps.r) / biggest, float(steps.t) / biggest) self.r_motor.set_direction(sign(steps.r)) self.t_motor.set_direction(sign(steps.t)) accumulation = Steps(0.0, 0.0) for i in range(biggest): accumulation += step_size while abs(accumulation.r) >= 1.0 or abs(accumulation.t) >= 1.0: this_step = Polar(0.0, 0.0) if abs(accumulation.r) >= 1.0: r_step = self.r_motor.step() this_step.r = r_step if r_step.is_boundry: accumulation.r = 0.0 else: accumulation.r = accumulation.r - sign(steps.r) if abs(accumulation.t) >= 1.0: this_step.t = self.t_motor.step() accumulation.t = accumulation.t - sign(steps.t) yield this_step
def read_packet(self, BaseAgent, packet): self.BaseAgent = BaseAgent fieldInfo = BaseAgent.get_field_info() self.cars = [] self.my_car = None self.their_cars = [] for n, car in enumerate(packet.game_cars): lcar = Car(car) if n == self.index: self.my_car = lcar else: self.their_cars.append(lcar) self.cars.append(lcar) self.my_goal = Goal(self.team, Vector3(0.0, utils.sign(self.team)*5120.0, 312.0)) self.their_goal = Goal(self.team, Vector3(0.0, utils.sign(utils.opp(self.team))*5120.0, 312.0)) self.goals = [self.my_goal, self.their_goal] self.ball = Ball(packet.game_ball) self.boosts = [] for n, boost in enumerate(packet.game_boosts): self.boosts.append(Boost(boost, n)) for n, boost in enumerate(fieldInfo.boost_pads): cboost = [boosts for boosts in self.boosts if boosts.index == n][0] cboost.update(boost)
def test_bin2lib(tmp_path): file_path = "MachO/mbedtls_selftest_arm64.bin" if is_aarch64( ) else "MachO/mbedtls_selftest_x86_64.bin" bin_path = pathlib.Path(get_sample(file_path)) original = lief.parse(bin_path.as_posix()) output = f"{tmp_path}/libtest.dylib" header: lief.MachO.Header = original.header header.file_type = lief.MachO.FILE_TYPES.DYLIB # Create LC_ID_DYLIB command original.add(lief.MachO.DylibCommand.id_dylib(output, 0, 1, 2)) # Create a new export :) ADDR = 0x10000D782 if header.cpu_type == lief.MachO.CPU_TYPES.x86_64 else 0x10004F3F4 assert original.add_exported_function(ADDR, "_lief_test_export") original.write(output) new = lief.parse(output) checked, err = lief.MachO.check_layout(new) assert checked, err if is_osx(): sign(output) print(f"Loading {output}") lib = ctypes.cdll.LoadLibrary(output) assert lib assert lib.lief_test_export
def is_rook_move_correct(self, source_x, source_y, destination_x, destination_y): # Проверим, что в пункте назначения не стоит фигура того же цвета, что и наша if not self.board.is_empty(destination_x, destination_y): if self.board.get_piece( source_x, source_y).get_color() == self.board.get_piece( destination_x, destination_y).get_color(): return False difference_x = destination_x - source_x # перемещение вдоль оси Х difference_y = destination_y - source_y # перемещение вдоль оси Y # Если движение не по одной оси, ладья не может сходить так if (difference_x * difference_y != 0) or (difference_x + difference_y == 0): return False # направление по осям factor_x = sign(difference_x) factor_y = sign(difference_y) for index in range(1, abs(difference_x)): if not self.board.is_empty(source_x + factor_x * index, source_y + factor_y * index): return False for index in range(1, abs(difference_y)): if not self.board.is_empty(source_x + factor_x * index, source_y + factor_y * index): return False return True
def backward(self, output, target): res = output - target if self.p % 2: return (sign(res) if self.p == 1 else sign(res) * res**(self.p - 1)) else: return (res if self.p == 2 else res**(self.p - 1))
def lora_unpacking_realtime_data(packet_data): logger.info('--------real data process beginning-----------') gateway_addr = str(packet_data.read(3).uint) node_addr = str(packet_data.read(13).int) tran_direct = packet_data.read(1).bool func_code = packet_data.read(3) switch = packet_data.read(1).bool temp1_sign = packet_data.read(1).bool temp2_sign = packet_data.read(1).bool temp3_sign = packet_data.read(1).bool temp1 = packet_data.read(10).uint temp2 = packet_data.read(10).uint temp3 = packet_data.read(10).uint battery_vol = packet_data.read(2).uint temprature1 = (sign(temp1_sign) * temp1) / 10.0 temprature2 = (sign(temp2_sign) * temp2) / 10.0 temprature3 = (sign(temp3_sign) * temp3) / 10.0 logger.debug('gateway_addr: %s', gateway_addr) logger.info('-------------------') logger.info('node_addr: %s', node_addr) logger.info('-------------------') logger.debug('tran_direct: %s', tran_direct) logger.debug('-------------------') logger.debug('func_code: %s', func_code) logger.debug('-------------------') logger.debug('switch: %s', switch) logger.debug('-------------------') logger.debug('temp1_sign', temp1_sign) logger.debug('-------------------') logger.debug('temp2_sign', temp2_sign) logger.debug('-------------------') logger.debug('temp3_sign', temp3_sign) logger.debug('-------------------') logger.info('temp1: %s', temp1) logger.info('temp2: %s', temp2) logger.info('temp3: %s', temp3) logger.info('-------------------') logger.info('battery_vol: %s', battery_vol) logger.info('values : %s, %s, %s, %s', temprature1, temprature2, temprature3, battery_vol) return (gateway_addr, node_addr, switch, temprature1, temprature2, temprature3, battery_vol)
def make_move_action(self, entity, pos, goal): delta = goal.position - pos if delta.x: delta = Position(sign(delta.x), 0) elif delta.y: delta = Position(0, sign(delta.y)) else: return self.registry.assign(entity, Action, ActionType.MOVE, delta=delta)
def check(self, pce0): tf = False for pce in pce0.mates: if (pce0.group == pce.group) and pce.group > 0: # already in same group pass elif pce0.angle <> pce.angle: # must be same angle to align pass else: dx0 = abs(pce.cx0 - pce0.cx0) dy0 = abs(pce.cy0 - pce0.cy0) dx = abs(pce.cx - pce0.cx) dy = abs(pce.cy - pce0.cy) if pce.angle in (1, 3): dx, dy = dy, dx if abs(dx - dx0) < self.margin: if abs(dy - dy0) < self.margin: ok = True # close enough - check if right place angle = pce.angle dind = utils.sign(pce.ind - pce0.ind) dx = utils.sign(pce.cx - pce0.cx) dy = utils.sign(pce.cy - pce0.cy) if abs(pce.ind - pce0.ind) == 1: # same row if angle == 0: if dx <> dind: ok = False elif angle == 1: if dy <> dind: ok = False elif angle == 2: if dx <> -dind: ok = False elif angle == 3: if dy <> -dind: ok = False else: # same column if angle == 0: if dy <> dind: ok = False elif angle == 1: if dx <> -dind: ok = False elif angle == 2: if dy <> -dind: ok = False elif angle == 3: if dx <> dind: ok = False if ok: tf = True if pce.group == 0: if pce0.group == 0: self.next_group += 1 pce.group = self.next_group pce0.group = self.next_group else: pce.group = pce0.group else: if pce0.group == 0: pce0.group = pce.group else: # two separate groups for pce1 in self.pieces: if pce1.group == pce0.group: pce1.group = pce.group return tf
def run(self): while running: if 'w' in keys and 'a' in keys: self.motor_left_target_speed = 70 # forward_mov_speed / 2 self.motor_right_target_speed = forward_mov_speed elif 'w' in keys and 'd' in keys: self.motor_left_target_speed = forward_mov_speed self.motor_right_target_speed = 70 # forward_mov_speed / 2 elif 'w' in keys or 'forward' in pad_keys: self.motor_left_target_speed = forward_mov_speed self.motor_right_target_speed = forward_mov_speed elif 's' in keys or 'backward' in pad_keys: self.motor_left_target_speed = -backwards_mov_speed self.motor_right_target_speed = -backwards_mov_speed elif 'd' in keys or 'right' in pad_keys: self.motor_left_target_speed = rotation_speed self.motor_right_target_speed = -rotation_speed elif 'a' in keys or 'left' in pad_keys: self.motor_left_target_speed = -rotation_speed self.motor_right_target_speed = rotation_speed else: self.motor_left_target_speed = 0 self.motor_right_target_speed = 0 dx_left = sign(int(self.motor_left_target_speed * 10) - int(self.motor_left_actual_speed * 10)) dx_right = sign(int(self.motor_right_target_speed * 10) - int(self.motor_right_actual_speed * 10)) # self.motor_left_actual_speed += dx_left * 10 # self.motor_right_actual_speed += dx_right * 10 # pas de rampe pour doggo, mais ma laisser ca ici en cas que il faudrait en avoir une self.motor_left_actual_speed = self.motor_left_target_speed self.motor_right_actual_speed = self.motor_right_target_speed if self.motor_left_actual_speed < 0: write_pwm([config.doggo_motor_left_back_channel], abs(self.motor_left_actual_speed)) write_pwm([config.doggo_motor_left_for_channel], 0) else: write_pwm([config.doggo_motor_left_for_channel], self.motor_left_actual_speed) write_pwm([config.doggo_motor_left_back_channel], 0) if self.motor_right_actual_speed < 0: write_pwm([config.doggo_motor_right_back_channel], abs(self.motor_right_actual_speed)) write_pwm([config.doggo_motor_right_for_channel], 0) else: write_pwm([config.doggo_motor_right_for_channel], self.motor_right_actual_speed) write_pwm([config.doggo_motor_right_back_channel], 0) time.sleep(1/60.0)
def catch_all(path): ip = get_ip_from_request(request) print(str(ip)) print(request.headers) print(path) if path == 'box': return API_KEY url = API_URL + path data = {} if request.get_json() is not None: data = request.get_json() params = {} for key, value in request.args.items(): params[key] = value if request.method == 'GET': signature = sign(API_KEY, API_SECRET, params) else: signature = sign(API_KEY, API_SECRET, data) headers = {} for key, value in request.headers.items(): headers[key] = value headers['Host'] = API_HOST headers['X-API-Key'] = API_KEY headers['X-API-Sign'] = signature try: mac = headers['X-Customer-Mac'] except KeyError: mac = '11:11:11:11:11:11' if STAGE == 'production': with ServiceRpcProxy('ndsctl_service', NAMEKO_CONFIG) as proxy: mac = proxy.get_client_mac(str(ip)) headers['X-Customer-Mac'] = mac esreq = requests.Request(method=request.method, url=url, data=request.data, params=params, headers=headers) print(url) resp = requests.Session().send(esreq.prepare()) resp.encoding = 'utf-8' resp_text = resp.text if STAGE == 'production': resp_text = replace_host(resp_text, 'storage.googleapis.com', 'w.zone:5001') return (resp_text, resp.status_code, resp.headers.items())
def __init__(self, vector: Vector3, duration: float = 0.1, delay: float = 0.1): super().__init__() self.vector = vector.normalize() self.pitch = abs(self.vector[0]) * -sign(self.vector[0]) self.yaw = abs(self.vector[1]) * sign(self.vector[1]) self.delay = delay if delay >= duration else duration self.duration = duration # the time the jump began self.time = -1 # keeps track of the frames the jump button has been released self.counter = 0
def check_if_circle_safe(self, endx, endy): """ This takes all the lasers and calculates if the circular path to endx and endy is unobstructed. endx and endy must be in the robots coordinate system i.e. robots position is 0, 0 with heading 0. It takes the robot width into account. """ laser_angles = self.communicator.get_laser_angles() laser_distances = self.communicator.get_laser_distances() robot_width = .45 radius0 = abs((endx**2 + endy**2) / (2 * endy)) radius1 = radius0 + robot_width / 2 radius_1 = radius0 - robot_width / 2 for i in range(min(len(laser_angles), len(laser_distances))): if laser_angles[i] > math.pi / 2 or laser_angles[i] < -math.pi / 2: continue # can only hande points in front of robot angle = math.pi / 2 - utils.sign(endy) * laser_angles[i] u0 = math.atan2(endy - utils.sign(endy) * radius0, endx) u1 = math.pi / 2 + utils.sign(endy) * u0 u2 = math.pi - u1 - angle lt = math.sqrt(radius0**2 + radius_1**2 - radius0 * radius_1 * math.cos(u1)) t = u1 * radius_1 / lt if angle > t: try: length = radius0*math.cos(angle) + \ math.sqrt((radius0*math.cos(angle))**2 + radius1**2 - radius0**2) except ValueError: return False else: try: length = radius0*math.cos(angle) + \ math.sqrt((radius0*math.cos(angle))**2 + radius_1**2 - radius0**2) except ValueError: return False if math.pi - angle > u1: length_end = radius0 * u1 / u2 if laser_distances[i] < min(length, length_end): return False else: if laser_distances[i] < length: return False return True
def execute(self): target = self.ball.location offset = (target.x / utils.FIELD_WIDTH) * math.pi x = target.x + 90 * abs(math.cos(offset)) * utils.sign(offset) y = target.y + 90 * abs(math.sin(offset)) * utils.sign(self.agent.team) # target = Vector3(x,y,target.z) self.substate = substates.pick_state(self, self.agent, self.car, target, 2400, self.hierarchy) self.expired = ( not utils.ballProject(self) > -(utils.distance2D(self.ball.location, self.car.location) / 2) or (calcShoot(self.agent).available())) return self.substate.step(1.0 / 60.0)
def optimalShift(self, goal=None, condition=None, rounds=20): if goal == None: goal = lambda d, h: signedStatisticalParity( d, self.protectedIndex, self.protectedValue, h) if condition == None: condition = self.protected low = self.minShift high = self.maxShift dataToUse = self.validationData minGoalValue = goal(dataToUse, self.conditionalShiftClassifier(low, condition)) maxGoalValue = goal(dataToUse, self.conditionalShiftClassifier(high, condition)) #print((low, minGoalValue)) #print((high, maxGoalValue)) if sign(minGoalValue) != sign(maxGoalValue): # a binary search for zero for _ in range(rounds): midpoint = (low + high) / 2 if (sign( goal(dataToUse, self.conditionalShiftClassifier( low, condition))) == sign( goal( dataToUse, self.conditionalShiftClassifier( midpoint, condition)))): low = midpoint else: high = midpoint return midpoint else: print("Warning: bisection method not applicable") bestShift = None bestVal = float('inf') step = (high - low) / rounds for newShift in numpy.arange(low, high, step): newVal = goal( dataToUse, self.conditionalShiftClassifier(newShift, condition)) print(newVal) newVal = abs(newVal) if newVal < bestVal: bestShift = newShift bestVal = newVal return bestShift
def post(method=None, extra_data=None, **kws): params = { 'access_key': settings.AKEY, 'secret_key': settings.SKEY, 'created': int(time.time()), 'method': method, } params.update(kws) signature = sign(params) params['sign'] = signature params.pop('secret_key') # 额外数据不参与签名 if extra_data: for k, v in extra_data.iteritems(): if v: params[k] = v payload = urllib.urlencode(params) r = requests.post(settings.HOST, params=payload) # 错误处理[摊手] assert r.status_code == 200 r = r.json() kws = ', '.join('%s=%s' for k, v in kws.iteritems()) assert 'code' not in r, '%s(%s) => %d %s' % (method, kws, r['code'], r['message']) utils.info('%s(%s) => %r', method, kws, r) return r
def send(self, amount, to_addr): """ Send money to the given address from this wallet. Args: amount: How much value is sent to_addr: Address where value is transferred to. """ tx = Transaction(self.key) utxo = self.blockchain.scan_unspent_transactions( self.key.publickey()) debit = sum(map(lambda x: x['value'], utxo)) change = debit - amount if change < 0: raise InsufficientFundsException() for credit in utxo: signature = sign(self.key, credit['hash']) tx.add_in(credit['hash'], signature, self.key.publickey(), credit['value']) tx.add_out(amount, to_addr) tx.add_out(change, self.key.publickey()) self.blockchain.add(tx)
def decompose(matrix): """ Раскладывает матрицу A в произведение матриц ST x D x S. Возвращает матрицы S и D. """ end = len(matrix) s = [[0.0 for _ in range(0, end)] for _ in range(0, end)] d = [0.0 for _ in range(0, end)] for i in range(0, end): # Вычисление d_i и s_ii d[i] = sign(matrix[i][i] - sum(s[j][i]**2 * d[j] for j in range(0, i))) s[i][i] = sqrt( abs(matrix[i][i] - sum(s[j][i]**2 * d[j] for j in range(0, i)))) # Вычисление s_ij for j in range(i + 1, end): s[i][j] = matrix[i][j] - sum(s[k][i] * s[k][j] * d[k] for k in range(0, i)) s[i][j] /= s[i][i] * d[i] return s, d
def steps(self, steps): """Step the motor.""" self.set_direction(sign(steps)) for i in range(int(abs(steps))): yield self.step() if not FAST: time.sleep(self.step_time)
def concatState(self, index, state_queue): state = np.zeros( shape=(self.state_height, self.state_width, self.histLen), dtype=np.uint8, ) sign = utils.sign(index) for i in range(self.histLen): pos = index - i if not utils.sign(pos) == sign: break elif self.t[pos] and not (i == 0): break else: state[:, :, i] = state_queue[pos] return state
def check_castling(self, source_x, source_y, destination_x, destination_y): if self.board.is_empty(source_x, source_y): return False if self.board.get_piece(source_x, source_y).get_type() != ChessPieceType.King: return False difference_x = destination_x - source_x difference_y = destination_y - source_y if abs(difference_x) != 2 or difference_y != 0: return False factor_x = sign(difference_x) # Проверям, что на пути от короля до ладьи ничего не стоит checking_square = [source_x + factor_x, source_y] while self.board.is_empty(*checking_square) and 0 <= checking_square[0] < BOARD_SIZE: checking_square[0] += factor_x if checking_square[0] < 0 or checking_square[0] >= BOARD_SIZE: return False if self.board.get_piece(*checking_square).get_type() != ChessPieceType.Rook: return False # Проверка, что король не под шахом и поле, пересекаемое или занимаемое им, не атаковано for i in range(3): checking_square = [source_x + factor_x * i, source_y] if self.can_be_attacked(checking_square[0], checking_square[1], self.board.get_piece(source_x, source_y).get_color()): return False # Проверяем, что данные ладья и король не делали свой ход if (source_x, source_y, destination_x, destination_y) == (4, 0, 2, 0) and self.possible_white_long_castling: return True if (source_x, source_y, destination_x, destination_y) == (4, 0, 6, 0) and self.possible_white_short_castling: return True if (source_x, source_y, destination_x, destination_y) == (4, 7, 2, 7) and self.possible_black_long_castling: return True if (source_x, source_y, destination_x, destination_y) == (4, 7, 6, 7) and self.possible_black_short_castling: return True return False
def move(self, source_x, source_y, destination_x, destination_y): if self.board.is_empty(source_x, source_y): raise ChessException('Empty source square') source_color = self.board.get_piece(source_x, source_y).get_color() if self.whose_turn() != source_color: raise ChessException("It's " + str(source_color.get_another_color()) + ' turn!') if not self.is_move_correct(source_x, source_y, destination_x, destination_y): raise ChessException("Incorrect move") # Если это рокировка, то ладью тоже нужно передвинуть #self.previous_board = copy.deepcopy(self.board) if self.check_castling(source_x, source_y, destination_x, destination_y): if destination_x < source_x: rook_x = 0 else: rook_x = BOARD_SIZE - 1 # destination_x может быть равна только 3 или 5 self.add_step_to_notation_if_castling(source_x, source_y, destination_x, destination_y) self.board.move_piece(rook_x, source_y, 3 + 2 * sign(rook_x), source_y) else: self.add_step_to_notation(source_x, source_y, destination_x, destination_y) self.board.move_piece(source_x, source_y, destination_x, destination_y) self.move_number += 1 black_mate = self.is_mate(ChessColor.Black) white_mate = self.is_mate(ChessColor.White) if black_mate or white_mate: self.result_notation_text += '#' # Если ход был сделан Ладьей или Королем, исключаем дальнейшую возможность соответствующих рокировок if (source_x, source_y) == (0, 0) or (source_x, source_y) == ( 4, 0) or (destination_x, destination_y) == (0, 0): self.possible_white_long_castling = False if (source_x, source_y) == (7, 0) or (source_x, source_y) == ( 4, 0) or (destination_x, destination_y) == (7, 0): self.possible_white_short_castling = False if (source_x, source_y) == (0, 7) or (source_x, source_y) == ( 4, 7) or (destination_x, destination_y) == (0, 7): self.possible_black_long_castling = False if (source_x, source_y) == (7, 7) or (source_x, source_y) == ( 4, 7) or (destination_x, destination_y) == (7, 7): self.possible_black_short_castling = False if self.is_check(ChessColor.Black): self.is_black_check = True elif self.is_black_check: self.is_black_check = False if self.is_check(ChessColor.White): self.is_white_check = True elif self.is_white_check: self.is_white_check = False
def __init__(self, vector: Vector3, duration: float = 0.1, delay: float = 0.1, angle: float = 0, boost: bool = False): super().__init__() self.vector = vector.normalize() self.pitch = abs(self.vector[0]) * -sign(self.vector[0]) self.yaw = abs(self.vector[1]) * sign(self.vector[1]) self.delay = delay if delay >= duration else duration self.duration = duration self.boost = boost self.angle = math.radians(angle) if boost else 0 x = math.cos(self.angle) * self.vector.x - math.sin(self.angle) * self.vector.y y = math.sin(self.angle) * self.vector.x + math.cos(self.angle) * self.vector.y self.preorientation = Vector3(x, y, 0) # the time the jump began self.time = -1 # keeps track of the frames the jump button has been released self.counter = 0
def is_bishop_move_correct(self, source_x, source_y, destination_x, destination_y): # Проверим, что в пункте назначения не стоит фигура того же цвета, что и наша if not self.board.is_empty(destination_x, destination_y): if self.board.get_piece(source_x, source_y).get_color() == self.board.get_piece(destination_x, destination_y).get_color(): return False difference_x = destination_x - source_x # перемещение вдоль оси Х difference_y = destination_y - source_y # перемещение вдоль оси Y if abs(destination_x - source_x) != abs(destination_y - source_y): return False # направление по осям factor_x = sign(difference_x) factor_y = sign(difference_y) for index in range(1, abs(difference_x)): if not self.board.is_empty(source_x + factor_x * index, source_y + factor_y * index): return False return True
def grad(self, params, x, y): w, alpha = self.inflate(params) d_prev = self.decide(0., x[0], w, alpha) d_prev_by_w = sech2(dot(w, x[0])) * x[0] r_prev_by_w = d_prev_by_w * y[0] - self.delta * sign( d_prev) * d_prev_by_w A_prev_by_w = r_prev_by_w d_prev_by_alpha = r_prev_by_alpha = A_prev_by_alpha = 0. for i in range(1, len(y)): x_t = x[i] q_t = y[i] d_t = self.decide(d_prev, x_t, w, alpha) d_i = dot(w, x_t) + alpha * d_prev d_t_by_w = sech2(d_i) * (x_t + alpha * d_prev_by_w) r_t_by_w = d_t_by_w * q_t - self.delta * sign(d_t - d_prev) * ( d_t_by_w - d_prev_by_w) A_t_by_w = A_prev_by_w + (1. / (i + 1)) * (r_t_by_w - A_prev_by_w) if i == 1: d_t_by_alpha = sech2(d_i) * d_prev else: d_t_by_alpha = sech2(d_i) * (alpha * d_prev_by_alpha + d_prev) r_t_by_alpha = d_t_by_alpha * q_t - ( self.delta * sign(d_t - d_prev) * (d_t_by_alpha - d_prev_by_alpha)) A_t_by_alpha = A_prev_by_alpha + (1. / (i + 1)) * (r_t_by_alpha - A_prev_by_alpha) d_prev = d_t d_prev_by_w = d_t_by_w r_prev_by_w = r_t_by_w A_prev_by_w = A_t_by_w d_prev_by_alpha = d_t_by_alpha r_prev_by_alpha = r_t_by_alpha A_prev_by_alpha = A_t_by_alpha return -1 * append(A_t_by_w, A_t_by_alpha) + 2 * self.lmb * params
def decorator(cls): """ 给类加上类型信息 :param cls: :return: """ cls.__serialize_name__ = cls.__name__ if len(name) == 0 else name[0] d = dict() for field_name, protocol_type in fields.items(): desc = Descriptor(field_name, protocol_type) if isinstance(protocol_type, TypeInfo) \ else Descriptor(field_name, TypeInfo(protocol_type)) d[sign(field_name.lower())] = desc setattr(cls, field_name, desc) cls.__simple_name__ = cls.__serialize_name__ cls.__serialize_fields__ = [item[1] for item in sorted(d.items(), key=lambda x:x[0])] register.reg(sign(cls.__serialize_name__), cls) return cls
def turn(self): twist = Twist() while not self.reached(): twist.angular.z = self._ang_zvel * utils.sign(utils.wrap_to_pi(self.theta_goal - self.theta)) if not self.command(twist): return False self.ok = True return True
def available(self): goal = self.agent.game_info.my_goal.location if utils.sign(self.agent.team ) * self.ball.location.y > 3000 and utils.distance2D( self.ball.location, goal) < utils.distance2D( goal, self.car.location): return True return False
def test_sign(self): self.assertEquals(utils.sign(-5.3), -1) self.assertEquals(utils.sign(-0.5), -1) self.assertEquals(utils.sign(-0.0000001), -1) self.assertEquals(utils.sign(0), 0) self.assertEquals(utils.sign(0.00000001), 1) self.assertEquals(utils.sign(0.3), 1) self.assertEquals(utils.sign(324), 1)
def sign(self): """return sign in the form {relpath: (origin layer, SHA256)} """ target = self.target_file sig = {} if target.exists() and target.isfile(): sig[self.relpath] = (self.current.url, self.kind, utils.sign(self.target_file)) return sig
def grad(self, params, x, y): w, alpha = self.inflate(params) d_prev = self.decide(0., x[0], w, alpha) d_prev_by_w = sech2(dot(w, x[0])) * x[0] r_prev_by_w = d_prev_by_w*y[0] - self.delta*sign(d_prev)*d_prev_by_w A_prev_by_w = r_prev_by_w d_prev_by_alpha = r_prev_by_alpha = A_prev_by_alpha = 0. for i in range(1, len(y)): x_t = x[i] q_t = y[i] d_t = self.decide(d_prev, x_t, w, alpha) d_i = dot(w, x_t) + alpha*d_prev d_t_by_w = sech2(d_i) * (x_t + alpha*d_prev_by_w) r_t_by_w = d_t_by_w*q_t - self.delta*sign(d_t - d_prev)*(d_t_by_w - d_prev_by_w) A_t_by_w = A_prev_by_w + (1./(i+1))*(r_t_by_w - A_prev_by_w) if i == 1: d_t_by_alpha = sech2(d_i) * d_prev else: d_t_by_alpha = sech2(d_i) * (alpha * d_prev_by_alpha + d_prev) r_t_by_alpha = d_t_by_alpha*q_t - ( self.delta*sign(d_t - d_prev)*(d_t_by_alpha - d_prev_by_alpha)) A_t_by_alpha = A_prev_by_alpha + (1./(i+1))*(r_t_by_alpha - A_prev_by_alpha) d_prev = d_t d_prev_by_w = d_t_by_w r_prev_by_w = r_t_by_w A_prev_by_w = A_t_by_w d_prev_by_alpha = d_t_by_alpha r_prev_by_alpha = r_t_by_alpha A_prev_by_alpha = A_t_by_alpha return -1 * append(A_t_by_w, A_t_by_alpha) + 2*self.lmb*params
def enum(name, **enums): """ 创建枚举类型并且注册序列化typeid :param name: :param enums: :return: """ # TODO 按照现有做法,实际在invoke时,值的类型并不是Enum子类,序列化时就有问题 enum_cls = mkenum(**enums) enum_cls.__simple_name__ = name register.reg(sign(name), enum_cls) return enum_cls
def is_rook_move_correct(self, source_x, source_y, destination_x, destination_y): # Проверим, что в пункте назначения не стоит фигура того же цвета, что и наша if not self.board.is_empty(destination_x, destination_y): if self.board.get_piece(source_x, source_y).get_color() == self.board.get_piece(destination_x, destination_y).get_color(): return False difference_x = destination_x - source_x # перемещение вдоль оси Х difference_y = destination_y - source_y # перемещение вдоль оси Y # Если движение не по одной оси, ладья не может сходить так if (difference_x * difference_y != 0) or (difference_x + difference_y == 0): return False # направление по осям factor_x = sign(difference_x) factor_y = sign(difference_y) for index in range(1, abs(difference_x)): if not self.board.is_empty(source_x + factor_x * index, source_y + factor_y * index): return False for index in range(1, abs(difference_y)): if not self.board.is_empty(source_x + factor_x * index, source_y + factor_y * index): return False return True
def sign(self): """return sign in the form {relpath: (origin layer, SHA256)} """ sigs = {} for hook in ['joined', 'changed', 'broken', 'departed']: target = self._target / "hooks" / "{}-relation-{}".format( self.relation_name, hook) rel = target.relpath(self._target.directory) sigs[rel] = (self.interface.url, "dynamic", utils.sign(target)) return sigs
def optimalShift(self, goal=None, condition=None, rounds=20): if goal == None: goal = lambda d, h: signedStatisticalParity(d, self.protectedIndex, self.protectedValue, h) if condition == None: condition = self.protected low = self.minShift high = self.maxShift dataToUse = self.validationData minGoalValue = goal(dataToUse, self.conditionalShiftClassifier(low, condition)) maxGoalValue = goal(dataToUse, self.conditionalShiftClassifier(high, condition)) print((low, minGoalValue)) print((high, minGoalValue)) if sign(minGoalValue) != sign(maxGoalValue): # a binary search for zero for _ in range(rounds): midpoint = (low + high) / 2 if (sign(goal(dataToUse, self.conditionalShiftClassifier(low, condition))) == sign(goal(dataToUse, self.conditionalShiftClassifier(midpoint, condition)))): low = midpoint else: high = midpoint return midpoint else: print("Warning: bisection method not applicable") bestShift = None bestVal = float('inf') step = (high-low)/rounds for newShift in numpy.arange(low, high, step): newVal = goal(dataToUse, self.conditionalShiftClassifier(newShift, condition)) print(newVal) newVal = abs(newVal) if newVal < bestVal: bestShift = newShift bestVal = newVal return bestShift
def move(self, source_x, source_y, destination_x, destination_y): if self.board.is_empty(source_x, source_y): raise ChessException('Empty source square') source_color = self.board.get_piece(source_x, source_y).get_color() if self.whose_turn() != source_color: raise ChessException("It's "+str(source_color.get_another_color())+' turn!') if not self.is_move_correct(source_x, source_y, destination_x, destination_y): raise ChessException("Incorrect move") # Если это рокировка, то ладью тоже нужно передвинуть #self.previous_board = copy.deepcopy(self.board) if self.check_castling(source_x, source_y, destination_x, destination_y): if destination_x < source_x: rook_x = 0 else: rook_x = BOARD_SIZE - 1 # destination_x может быть равна только 3 или 5 self.add_step_to_notation_if_castling(source_x, source_y, destination_x, destination_y) self.board.move_piece(rook_x, source_y, 3 + 2 * sign(rook_x), source_y) else: self.add_step_to_notation(source_x, source_y, destination_x, destination_y) self.board.move_piece(source_x, source_y, destination_x, destination_y) self.move_number += 1 black_mate = self.is_mate(ChessColor.Black) white_mate = self.is_mate(ChessColor.White) if black_mate or white_mate: self.result_notation_text += '#' # Если ход был сделан Ладьей или Королем, исключаем дальнейшую возможность соответствующих рокировок if (source_x, source_y) == (0, 0) or (source_x, source_y) == (4, 0) or (destination_x, destination_y) == (0, 0): self.possible_white_long_castling = False if (source_x, source_y) == (7, 0) or (source_x, source_y) == (4, 0) or (destination_x, destination_y) == (7, 0): self.possible_white_short_castling = False if (source_x, source_y) == (0, 7) or (source_x, source_y) == (4, 7) or (destination_x, destination_y) == (0, 7): self.possible_black_long_castling = False if (source_x, source_y) == (7, 7) or (source_x, source_y) == (4, 7) or (destination_x, destination_y) == (7, 7): self.possible_black_short_castling = False if self.is_check(ChessColor.Black): self.is_black_check = True elif self.is_black_check: self.is_black_check = False if self.is_check(ChessColor.White): self.is_white_check = True elif self.is_white_check: self.is_white_check = False
def rotate(desiredAngle): ''' This will drive the robot to an angle, relative to its current orientation 0 degrees will keep the robot fixed. This code was inspired by kobuki_testsuite at: https://github.com/yujinrobot/kobuki/tree/hydro-devel/kobuki_testsuite/src/kobuki_testsuite Positive angles = counter-clockwise motion ''' u = 0 tolerance = .1 zvel = .8 initialAngle = odom.curVals['theta'] # print initialAngle # print desiredAngle desiredAngle = utils.wrap_to_pi(desiredAngle + initialAngle) while not angleCloseEnough(desiredAngle): currentAngle = odom.curVals['theta'] speed = zvel * utils.sign(utils.wrap_to_pi(desiredAngle - currentAngle)) #print currentAngle publishTwist(0, speed) stopRobot() return
def retraction(self,X,U,t=1.0): Y = X + t*U Q,R = np.linalg.qr(Y) return Q * np.diag(sign(sign(np.diag(R))+0.5))
def detailedLR(data, eta=DEFAULT_ETA, rounds=DEFAULT_NUM_ROUNDS): for w in lrGenerator(data, eta, rounds): pass return w, lambda x: sigmoid(numpy.dot(w,x)), lambda x: sign(numpy.dot(w,x))
def finalHypothesis(x): return sign(sum(a * h(x) for (a, h) in zip(alpha, hypotheses)))
def logmod(x): return sign(x)*log(abs(x) + 1)
def __init__(self, asn, links, transient_flag): self.record = pickle.dumps(PathEndRecord(asn, links, transient_flag)) self.signature = utils.sign(self.record)
def weightedMajorityVote(x): return sign(sum(a * h(x) for (a, h) in zip(alpha, hypotheses[:t+1])))
def hyperplaneToHypothesis(w): return lambda x: sign(numpy.dot(w, x))
def testCoordinate(samples, j): values = [sign(x[j] - 0.5) * y for (x,y) in samples] return len([z for z in values if z > 0]) / len(values)
def test_process(self): nums = [-5, -0.5, 0, 0.5, 1, 3] for x in nums: self.assertEquals(self.node._processReturn([x], 1), utils.sign(x)) self.assertTimeIndependent([x])
def kSVMGradientDescent(data,kernel): margin = kSVMDetailedGradientDescent(data, kernel, DEFAULT_LAMBDA, DEFAULT_NUM_ROUNDS) return lambda x: sign(margin(x))
def grad(self, params, x, y): W, w, alpha = self.inflate(params) x_t = x[0] q_t = y[0] h_t = tanh(dot(W, x_t)) d_prev = self.decide(0., x_t, W, w, alpha) d_prev_by_w = sech2(dot(w, h_t)) * h_t r_prev_by_w = d_prev_by_w*y[0] - self.delta*sign(d_prev)*d_prev_by_w A_prev_by_w = r_prev_by_w h_prev_by_W = zeros((w.size, W.shape[0], W.shape[1])) for i in range(self.hidden): h_prev_by_W[i,:,:] = sech2(dot(W[i,:], x_t)) * x_t d_prev_by_W = zeros(W.shape) + sech2(dot(w, h_t)) for i in range(self.hidden): d_prev_by_W[i,:] *= w[i]*h_prev_by_W[i,i,:] r_prev_by_W = d_prev_by_W*y[0] - self.delta*sign(d_prev)*d_prev_by_W A_prev_by_W = r_prev_by_W d_prev_by_alpha = zeros(alpha.shape) r_prev_by_alpha = zeros(alpha.shape) A_prev_by_alpha = zeros(alpha.shape) for step in range(1, len(y)): x_t = x[step] q_t = y[step] h_t = tanh(dot(W, x_t) + alpha*d_prev) d_t = self.decide(d_prev, x_t, W, w, alpha) h_t_by_w = dot(outer(d_prev_by_w, alpha), diag(sech2(dot(W, x_t) + alpha*d_prev))) d_t_by_w = sech2(dot(w, h_t)) * (dot(h_t_by_w, w) + h_t) r_t_by_w = d_t_by_w*q_t - self.delta*sign(d_t - d_prev)*(d_t_by_w - d_prev_by_w) A_t_by_w = A_prev_by_w + (1./(step+1))*(r_t_by_w - A_prev_by_w) h_t_by_W = zeros((w.size, W.shape[0], W.shape[1])) for k in range(w.size): a = sech2(dot(W[k,:], x_t) + alpha[k]*d_prev) for i in range(W.shape[0]): for j in range(W.shape[1]): b = alpha[k]*d_prev_by_W[i][j] if k == i: b += x_t[j] h_t_by_W[k][i][j] = a*b d_t_by_W = zeros(W.shape) for i in range(self.hidden): for j in range(self.exlen): d_t_by_W[i][j] = sech2(dot(w, h_t)) * dot(w, h_t_by_W[:,i,j]) r_t_by_W = d_t_by_W*q_t - self.delta*sign(d_t - d_prev)*(d_t_by_W - d_prev_by_W) A_t_by_W = A_prev_by_W + (1./(step+1))*(r_t_by_W - A_prev_by_W) a = sech2(dot(W, x_t) + alpha*d_prev) b = outer(d_prev_by_alpha, alpha) + eye(alpha.size)*d_prev h_t_by_alpha = dot(b, diag(a)) d_t_by_alpha = sech2(dot(w, h_t)) * dot(h_t_by_alpha, w) r_t_by_alpha = d_t_by_alpha*q_t - self.delta*sign(d_t - d_prev)*(d_t_by_alpha - d_prev_by_alpha) A_t_by_alpha = A_prev_by_alpha + (1./(step+1))*(r_t_by_alpha - A_prev_by_alpha) d_prev = d_t d_prev_by_w = d_t_by_w r_prev_by_w = r_t_by_w A_prev_by_w = A_t_by_w d_prev_by_W = d_t_by_W r_prev_by_W = r_t_by_W A_prev_by_W = A_t_by_W d_prev_by_alpha = d_t_by_alpha r_prev_by_alpha = r_t_by_alpha A_prev_by_alpha = A_t_by_alpha return -1 * concatenate((A_t_by_W.reshape((A_t_by_W.size,)), A_t_by_w, A_t_by_alpha)) + 2*self.lmb*params
def send(iface, team_id, cmd, data, stream, dh_key=1): encoded_data = int.from_bytes(data, byteorder='big') * dh_key pkg = RadioTap() / Dot11(type=2) / LLC() / Env(team_id=team_id, stream=stream, cmd=cmd, decoded=31337, data=str(encoded_data), sign=str(sign(encoded_data, private_key))) for i in range(10): time.sleep(randint(10, 200) / 1000) sendp(pkg, iface=iface, verbose=0)