text
stringlengths
8
6.05M
from functools import reduce # map() - Applies the specified function to every element in the collection. def square(number: int) -> int: return number * number list1 = [1, 2, 3, 4, 5] squared_numbers = list(map(square, list1)) # [result for result in map(square, list1)] print(squared_numbers) # filter() - Filters the elements in the collection that match the predicate/condition. def is_even(number: int) -> bool: return number % 2 == 0 list2 = [1, 2, 3, 4, 5] even_numbers = list(filter(is_even, list2)) print(even_numbers) # reduce() - Reduces a collection of elements into a single value. def sum(number1: int, number2: int) -> int: return number1 + number2 list2 = [1, 2, 3, 4, 5] sum_of_values = reduce(sum, list2) print(sum_of_values)
# -*- coding: utf-8 -*- ####################################################################### # This file is for project customisation ONLY # # General DigiPal settings go to digipal/settings.py # # Particular server instance settings go to local_settings.py # ####################################################################### # Import the settings from digipal from digipal.settings import *
from os import path from zipfile import ZipFile class ZipReaderError(Exception): pass class InvalidFileName(ZipReaderError): def __init__(self, file_name): self.file_name = file_name super().__init__(f"The ZIP archive contains the invalid file name: '{file_name}'!") class FileTooLargeError(ZipReaderError): def __init__(self, file_name, file_size, file_size_limit): self.file_name = file_name self.file_size = file_size self.file_size_limit = file_size_limit super().__init__( f"The ZIP archive contains the file '{self.file_name}' with a size " f"of {self.file_size / 1_000_000} MB (only {self.file_size_limit / 1_000_000} MB allowed)!") class ZipTooLargeError(ZipReaderError): def __init__(self, decompressed_size, decompressed_size_limit): self.decompressed_size = decompressed_size self.decompressed_size_limit = decompressed_size_limit super().__init__( f"The ZIP archive has a total decompressed size of {self.decompressed_size/1_000_000} MB " f"(only {self.decompressed_size_limit / 1_000_000} MB allowed)!" ) class NoSolutionsError(ZipReaderError): def __init__(self): super().__init__("The ZIP archive does not appear to contain any solution!") class InvalidJSONError(ZipReaderError): def __init__(self, file_name, message): self.file_name = file_name super().__init__(f"The ZIP archive contains the file '{file_name}'" f" which is not a valid JSON-encoded file: {message}!") class InvalidEncodingError(ZipReaderError): def __init__(self, file_name): self.file_name = file_name super().__init__(f"File '{file_name}' in the ZIP uses an unrecognized character encoding; " f"please use UTF-8 instead.") class InvalidZipError(ZipReaderError): def __init__(self, message): super().__init__( f"The ZIP archive is corrupted and could not be decompressed: {message}!") class BadZipChecker: """ Check if zip is bad/malicious/corrupted. """ def __init__(self, file_size_limit: int, zip_size_limit: int): self.file_size_limit = file_size_limit self.zip_size_limit = zip_size_limit def _check_zip_size(self, zip_file): zip_decompressed_size = sum(zi.file_size for zi in zip_file.infolist()) if zip_decompressed_size > self.zip_size_limit: raise ZipTooLargeError(zip_decompressed_size, self.zip_size_limit) def _is_file_name_okay(self, name): return name[0] != "/" and not path.isabs(name) and ".." not in name def _check_file_names(self, f: ZipFile): for n in f.namelist(): if not self._is_file_name_okay(n): raise InvalidFileName(n) def _check_decompressed_sizes(self, f: ZipFile): for info in f.filelist: if info.file_size > self.file_size_limit: raise FileTooLargeError(info.filename, info.file_size, self.file_size_limit) def _check_crc(self, zip_file): bad_filename = zip_file.testzip() if bad_filename is not None: raise InvalidZipError(f"{bad_filename} is corrupted (CRC checksum error)!") def __call__(self, zip_file): self._check_file_names(zip_file) self._check_decompressed_sizes(zip_file) self._check_zip_size(zip_file) self._check_crc(zip_file)
#!/usr/bin/python3 # SPDX-License-Identifier: GPL-2.0-only # # Copyright (C) 2018-2019 Netronome Systems, Inc. # In case user attempts to run with Python 2. from __future__ import print_function import argparse import re import sys, os class NoHelperFound(BaseException): pass class ParsingError(BaseException): def __init__(self, line='<line not provided>', reader=None): if reader: BaseException.__init__(self, 'Error at file offset %d, parsing line: %s' % (reader.tell(), line)) else: BaseException.__init__(self, 'Error parsing line: %s' % line) class Helper(object): """ An object representing the description of an eBPF helper function. @proto: function prototype of the helper function @desc: textual description of the helper function @ret: description of the return value of the helper function """ def __init__(self, proto='', desc='', ret=''): self.proto = proto self.desc = desc self.ret = ret def proto_break_down(self): """ Break down helper function protocol into smaller chunks: return type, name, distincts arguments. """ arg_re = re.compile('((\w+ )*?(\w+|...))( (\**)(\w+))?$') res = {} proto_re = re.compile('(.+) (\**)(\w+)\(((([^,]+)(, )?){1,5})\)$') capture = proto_re.match(self.proto) res['ret_type'] = capture.group(1) res['ret_star'] = capture.group(2) res['name'] = capture.group(3) res['args'] = [] args = capture.group(4).split(', ') for a in args: capture = arg_re.match(a) res['args'].append({ 'type' : capture.group(1), 'star' : capture.group(5), 'name' : capture.group(6) }) return res class HeaderParser(object): """ An object used to parse a file in order to extract the documentation of a list of eBPF helper functions. All the helpers that can be retrieved are stored as Helper object, in the self.helpers() array. @filename: name of file to parse, usually include/uapi/linux/bpf.h in the kernel tree """ def __init__(self, filename): self.reader = open(filename, 'r') self.line = '' self.helpers = [] def parse_helper(self): proto = self.parse_proto() desc = self.parse_desc() ret = self.parse_ret() return Helper(proto=proto, desc=desc, ret=ret) def parse_proto(self): # Argument can be of shape: # - "void" # - "type name" # - "type *name" # - Same as above, with "const" and/or "struct" in front of type # - "..." (undefined number of arguments, for bpf_trace_printk()) # There is at least one term ("void"), and at most five arguments. p = re.compile(' \* ?((.+) \**\w+\((((const )?(struct )?(\w+|\.\.\.)( \**\w+)?)(, )?){1,5}\))$') capture = p.match(self.line) if not capture: raise NoHelperFound self.line = self.reader.readline() return capture.group(1) def parse_desc(self): p = re.compile(' \* ?(?:\t| {5,8})Description$') capture = p.match(self.line) if not capture: # Helper can have empty description and we might be parsing another # attribute: return but do not consume. return '' # Description can be several lines, some of them possibly empty, and it # stops when another subsection title is met. desc = '' while True: self.line = self.reader.readline() if self.line == ' *\n': desc += '\n' else: p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)') capture = p.match(self.line) if capture: desc += capture.group(1) + '\n' else: break return desc def parse_ret(self): p = re.compile(' \* ?(?:\t| {5,8})Return$') capture = p.match(self.line) if not capture: # Helper can have empty retval and we might be parsing another # attribute: return but do not consume. return '' # Return value description can be several lines, some of them possibly # empty, and it stops when another subsection title is met. ret = '' while True: self.line = self.reader.readline() if self.line == ' *\n': ret += '\n' else: p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)') capture = p.match(self.line) if capture: ret += capture.group(1) + '\n' else: break return ret def run(self): # Advance to start of helper function descriptions. offset = self.reader.read().find('* Start of BPF helper function descriptions:') if offset == -1: raise Exception('Could not find start of eBPF helper descriptions list') self.reader.seek(offset) self.reader.readline() self.reader.readline() self.line = self.reader.readline() while True: try: helper = self.parse_helper() self.helpers.append(helper) except NoHelperFound: break self.reader.close() print('Parsed description of %d helper function(s)' % len(self.helpers), file=sys.stderr) ############################################################################### class Printer(object): """ A generic class for printers. Printers should be created with an array of Helper objects, and implement a way to print them in the desired fashion. @helpers: array of Helper objects to print to standard output """ def __init__(self, helpers): self.helpers = helpers def print_header(self): pass def print_footer(self): pass def print_one(self, helper): pass def print_all(self): self.print_header() for helper in self.helpers: self.print_one(helper) self.print_footer() class PrinterRST(Printer): """ A printer for dumping collected information about helpers as a ReStructured Text page compatible with the rst2man program, which can be used to generate a manual page for the helpers. @helpers: array of Helper objects to print to standard output """ def print_header(self): header = '''\ .. Copyright (C) All BPF authors and contributors from 2014 to present. .. See git log include/uapi/linux/bpf.h in kernel tree for details. .. .. %%%LICENSE_START(VERBATIM) .. Permission is granted to make and distribute verbatim copies of this .. manual provided the copyright notice and this permission notice are .. preserved on all copies. .. .. Permission is granted to copy and distribute modified versions of this .. manual under the conditions for verbatim copying, provided that the .. entire resulting derived work is distributed under the terms of a .. permission notice identical to this one. .. .. Since the Linux kernel and libraries are constantly changing, this .. manual page may be incorrect or out-of-date. The author(s) assume no .. responsibility for errors or omissions, or for damages resulting from .. the use of the information contained herein. The author(s) may not .. have taken the same level of care in the production of this manual, .. which is licensed free of charge, as they might when working .. professionally. .. .. Formatted or processed versions of this manual, if unaccompanied by .. the source, must acknowledge the copyright and authors of this work. .. %%%LICENSE_END .. .. Please do not edit this file. It was generated from the documentation .. located in file include/uapi/linux/bpf.h of the Linux kernel sources .. (helpers description), and from scripts/bpf_helpers_doc.py in the same .. repository (header and footer). =========== BPF-HELPERS =========== ------------------------------------------------------------------------------- list of eBPF helper functions ------------------------------------------------------------------------------- :Manual section: 7 DESCRIPTION =========== The extended Berkeley Packet Filter (eBPF) subsystem consists in programs written in a pseudo-assembly language, then attached to one of the several kernel hooks and run in reaction of specific events. This framework differs from the older, "classic" BPF (or "cBPF") in several aspects, one of them being the ability to call special functions (or "helpers") from within a program. These functions are restricted to a white-list of helpers defined in the kernel. These helpers are used by eBPF programs to interact with the system, or with the context in which they work. For instance, they can be used to print debugging messages, to get the time since the system was booted, to interact with eBPF maps, or to manipulate network packets. Since there are several eBPF program types, and that they do not run in the same context, each program type can only call a subset of those helpers. Due to eBPF conventions, a helper can not have more than five arguments. Internally, eBPF programs call directly into the compiled helper functions without requiring any foreign-function interface. As a result, calling helpers introduces no overhead, thus offering excellent performance. This document is an attempt to list and document the helpers available to eBPF developers. They are sorted by chronological order (the oldest helpers in the kernel at the top). HELPERS ======= ''' print(header) def print_footer(self): footer = ''' EXAMPLES ======== Example usage for most of the eBPF helpers listed in this manual page are available within the Linux kernel sources, at the following locations: * *samples/bpf/* * *tools/testing/selftests/bpf/* LICENSE ======= eBPF programs can have an associated license, passed along with the bytecode instructions to the kernel when the programs are loaded. The format for that string is identical to the one in use for kernel modules (Dual licenses, such as "Dual BSD/GPL", may be used). Some helper functions are only accessible to programs that are compatible with the GNU Privacy License (GPL). In order to use such helpers, the eBPF program must be loaded with the correct license string passed (via **attr**) to the **bpf**\ () system call, and this generally translates into the C source code of the program containing a line similar to the following: :: char ____license[] __attribute__((section("license"), used)) = "GPL"; IMPLEMENTATION ============== This manual page is an effort to document the existing eBPF helper functions. But as of this writing, the BPF sub-system is under heavy development. New eBPF program or map types are added, along with new helper functions. Some helpers are occasionally made available for additional program types. So in spite of the efforts of the community, this page might not be up-to-date. If you want to check by yourself what helper functions exist in your kernel, or what types of programs they can support, here are some files among the kernel tree that you may be interested in: * *include/uapi/linux/bpf.h* is the main BPF header. It contains the full list of all helper functions, as well as many other BPF definitions including most of the flags, structs or constants used by the helpers. * *net/core/filter.c* contains the definition of most network-related helper functions, and the list of program types from which they can be used. * *kernel/trace/bpf_trace.c* is the equivalent for most tracing program-related helpers. * *kernel/bpf/verifier.c* contains the functions used to check that valid types of eBPF maps are used with a given helper function. * *kernel/bpf/* directory contains other files in which additional helpers are defined (for cgroups, sockmaps, etc.). Compatibility between helper functions and program types can generally be found in the files where helper functions are defined. Look for the **struct bpf_func_proto** objects and for functions returning them: these functions contain a list of helpers that a given program type can call. Note that the **default:** label of the **switch ... case** used to filter helpers can call other functions, themselves allowing access to additional helpers. The requirement for GPL license is also in those **struct bpf_func_proto**. Compatibility between helper functions and map types can be found in the **check_map_func_compatibility**\ () function in file *kernel/bpf/verifier.c*. Helper functions that invalidate the checks on **data** and **data_end** pointers for network processing are listed in function **bpf_helper_changes_pkt_data**\ () in file *net/core/filter.c*. SEE ALSO ======== **bpf**\ (2), **cgroups**\ (7), **ip**\ (8), **perf_event_open**\ (2), **sendmsg**\ (2), **socket**\ (7), **tc-bpf**\ (8)''' print(footer) def print_proto(self, helper): """ Format function protocol with bold and italics markers. This makes RST file less readable, but gives nice results in the manual page. """ proto = helper.proto_break_down() print('**%s %s%s(' % (proto['ret_type'], proto['ret_star'].replace('*', '\\*'), proto['name']), end='') comma = '' for a in proto['args']: one_arg = '{}{}'.format(comma, a['type']) if a['name']: if a['star']: one_arg += ' {}**\ '.format(a['star'].replace('*', '\\*')) else: one_arg += '** ' one_arg += '*{}*\\ **'.format(a['name']) comma = ', ' print(one_arg, end='') print(')**') def print_one(self, helper): self.print_proto(helper) if (helper.desc): print('\tDescription') # Do not strip all newline characters: formatted code at the end of # a section must be followed by a blank line. for line in re.sub('\n$', '', helper.desc, count=1).split('\n'): print('{}{}'.format('\t\t' if line else '', line)) if (helper.ret): print('\tReturn') for line in helper.ret.rstrip().split('\n'): print('{}{}'.format('\t\t' if line else '', line)) print('') class PrinterHelpers(Printer): """ A printer for dumping collected information about helpers as C header to be included from BPF program. @helpers: array of Helper objects to print to standard output """ type_fwds = [ 'struct bpf_fib_lookup', 'struct bpf_perf_event_data', 'struct bpf_perf_event_value', 'struct bpf_sock', 'struct bpf_sock_addr', 'struct bpf_sock_ops', 'struct bpf_sock_tuple', 'struct bpf_spin_lock', 'struct bpf_sysctl', 'struct bpf_tcp_sock', 'struct bpf_tunnel_key', 'struct bpf_xfrm_state', 'struct pt_regs', 'struct sk_reuseport_md', 'struct sockaddr', 'struct tcphdr', 'struct __sk_buff', 'struct sk_msg_md', 'struct xdp_md', ] known_types = { '...', 'void', 'const void', 'char', 'const char', 'int', 'long', 'unsigned long', '__be16', '__be32', '__wsum', 'struct bpf_fib_lookup', 'struct bpf_perf_event_data', 'struct bpf_perf_event_value', 'struct bpf_sock', 'struct bpf_sock_addr', 'struct bpf_sock_ops', 'struct bpf_sock_tuple', 'struct bpf_spin_lock', 'struct bpf_sysctl', 'struct bpf_tcp_sock', 'struct bpf_tunnel_key', 'struct bpf_xfrm_state', 'struct pt_regs', 'struct sk_reuseport_md', 'struct sockaddr', 'struct tcphdr', } mapped_types = { 'u8': '__u8', 'u16': '__u16', 'u32': '__u32', 'u64': '__u64', 's8': '__s8', 's16': '__s16', 's32': '__s32', 's64': '__s64', 'size_t': 'unsigned long', 'struct bpf_map': 'void', 'struct sk_buff': 'struct __sk_buff', 'const struct sk_buff': 'const struct __sk_buff', 'struct sk_msg_buff': 'struct sk_msg_md', 'struct xdp_buff': 'struct xdp_md', } def print_header(self): header = '''\ /* This is auto-generated file. See bpf_helpers_doc.py for details. */ /* Forward declarations of BPF structs */''' print(header) for fwd in self.type_fwds: print('%s;' % fwd) print('') def print_footer(self): footer = '' print(footer) def map_type(self, t): if t in self.known_types: return t if t in self.mapped_types: return self.mapped_types[t] print("Unrecognized type '%s', please add it to known types!" % t, file=sys.stderr) sys.exit(1) seen_helpers = set() def print_one(self, helper): proto = helper.proto_break_down() if proto['name'] in self.seen_helpers: return self.seen_helpers.add(proto['name']) print('/*') print(" * %s" % proto['name']) print(" *") if (helper.desc): # Do not strip all newline characters: formatted code at the end of # a section must be followed by a blank line. for line in re.sub('\n$', '', helper.desc, count=1).split('\n'): print(' *{}{}'.format(' \t' if line else '', line)) if (helper.ret): print(' *') print(' * Returns') for line in helper.ret.rstrip().split('\n'): print(' *{}{}'.format(' \t' if line else '', line)) print(' */') print('static %s %s(*%s)(' % (self.map_type(proto['ret_type']), proto['ret_star'], proto['name']), end='') comma = '' for i, a in enumerate(proto['args']): t = a['type'] n = a['name'] if proto['name'] == 'bpf_get_socket_cookie' and i == 0: t = 'void' n = 'ctx' one_arg = '{}{}'.format(comma, self.map_type(t)) if n: if a['star']: one_arg += ' {}'.format(a['star']) else: one_arg += ' ' one_arg += '{}'.format(n) comma = ', ' print(one_arg, end='') print(') = (void *) %d;' % len(self.seen_helpers)) print('') ############################################################################### # If script is launched from scripts/ from kernel tree and can access # ../include/uapi/linux/bpf.h, use it as a default name for the file to parse, # otherwise the --filename argument will be required from the command line. script = os.path.abspath(sys.argv[0]) linuxRoot = os.path.dirname(os.path.dirname(script)) bpfh = os.path.join(linuxRoot, 'include/uapi/linux/bpf.h') argParser = argparse.ArgumentParser(description=""" Parse eBPF header file and generate documentation for eBPF helper functions. The RST-formatted output produced can be turned into a manual page with the rst2man utility. """) argParser.add_argument('--header', action='store_true', help='generate C header file') if (os.path.isfile(bpfh)): argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h', default=bpfh) else: argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h') args = argParser.parse_args() # Parse file. headerParser = HeaderParser(args.filename) headerParser.run() # Print formatted output to standard output. if args.header: printer = PrinterHelpers(headerParser.helpers) else: printer = PrinterRST(headerParser.helpers) printer.print_all()
# -*- coding:utf-8 -*- """ Created on 2017-2-28 @author: Kyrie Liu @description: Global variable """ import sys class Const(object): class ConstError(TypeError): pass def __setattr__(self, key, value): if key in self.__dict__: raise self.ConstError, "Not changed the value of const.%s" % key else: self.__dict__[key] = value def __getattr__(self, key): return self.key if key in self.__dict__ else None sys.modules[__name__] = Const()
# Generated by Django 3.0.8 on 2020-11-28 10:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('facilitators', '0004_auto_20201128_1200'), ] operations = [ migrations.AlterField( model_name='facilitatorqueries', name='replay', field=models.CharField(max_length=250), ), ]
from jitcache import Cache import time cache = Cache() @cache.memoize def slow_fn(input_1, input_2, input_3=10): print("Slow Function Called") time.sleep(1) return input_1 * input_2 * input_3 print(slow_fn(10, 2))
import sys import nbformat # read notebook from stdin nb = nbformat.reads(sys.stdin.read(), as_version = 4) # prepend a comment to the source of each cell for index, cell in enumerate(nb.cells): if cell.cell_type == 'code': cell.source = cell.source.replace('#|export\n', '# this cell is exported to a script\n\n') # write notebook to stdout nbformat.write(nb, sys.stdout)
# 头条搜索内容 touTiaoSearchKey = "西农" # mongouri配置 mongoUri = "mongodb://172.17.162.189:27017" # 多久执行一次 interval_minutes = 30 # mysql配置 mysqlHost = "xxx" mysqlUser = "xxx" mysqlPasswd = "xxx" mysqlDb = "xxx" mysqlPort = 3306
import eav from django.shortcuts import render from django.http import HttpResponse from eav.models import Attribute,EnumValue,EnumGroup from shop.models import Product def add_attribute(request): yes = EnumValue.objects.create(value='yes') no = EnumValue.objects.create(value='no') unkown = EnumValue.objects.create(value='unkown') ynu = EnumGroup.objects.create(name='Yes / No / Unkown') ynu.enums.add(yes,no,unkown) Attribute.objects.create(name = 'Has Fever?',datatype=Attribute.TYPE_ENUM,enum_group=ynu) return HttpResponse("Attribute has been added")
import os import pytest from etl_toolbox.file_functions import get_file_list_from_dir @pytest.mark.parametrize("dir, recursive, include_regex, expected", [ ( os.path.join('test_data', 'test_dir'), False, None, [os.path.join('test_data', 'test_dir', '1.csv'), os.path.join('test_data', 'test_dir', '2.csv'), os.path.join('test_data', 'test_dir', '3.json')] ), ( os.path.join('test_data', 'test_dir'), True, None, [os.path.join('test_data', 'test_dir', '1.csv'), os.path.join('test_data', 'test_dir', '2.csv'), os.path.join('test_data', 'test_dir', '3.json'), os.path.join('test_data', 'test_dir', 'a', '1.csv'), os.path.join('test_data', 'test_dir', 'b', '3.csv'), os.path.join('test_data', 'test_dir', 'b', 'c', '2.txt')] ), ( os.path.join('test_data', 'test_dir'), False, r'.*\.json$', [os.path.join('test_data', 'test_dir', '3.json')] ), ( os.path.join('test_data', 'test_dir'), True, r'.*2\..*', [os.path.join('test_data', 'test_dir', '2.csv'), os.path.join('test_data', 'test_dir', 'b', 'c', '2.txt')] ) ]) def test_get_file_list_from_dir(dir, recursive, include_regex, expected): assert sorted( get_file_list_from_dir(dir, recursive=recursive, include_regex=include_regex) ) == sorted(expected)
import tkinter as tk ICON_CHARS = { "bug": "\U0001F41B", "ant": "\U0001F41C", "honeybee": "\U0001F41D", "ladybeetle": "\U0001F41E", "hand": "\U0001F590", "hazard": "\u2623", "1": "\u0031", "width": "\u21D4", "height": "\u21D5" } class CustomBoardWindow(tk.Toplevel): def __init__(self, master, _custom_data): tk.Toplevel.__init__(self, master) # self.master = master self.custom_data = _custom_data self.tmp_custom_data = {} self.resizable(width=False, height=False) self.columnconfigure(0, weight=2) self.columnconfigure(1, weight=1) self.columnconfigure(2, weight=5) self.columnconfigure(3, weight=1) self.tmp_custom_data["width"] = tk.IntVar(value=10) tk.Label(self, text=ICON_CHARS["width"] + " Width:").grid(column=0, row=0, sticky=tk.E, padx=10, pady=5) width_spinbox = tk.Spinbox(self) width_spinbox.config(increment=1, format='%2.0f', width=5, textvariable=self.tmp_custom_data["width"]) width_spinbox.grid(column=1, row=0, sticky=tk.W, padx=10, pady=5) self.tmp_custom_data["height"] = tk.IntVar(value=10) tk.Label(self, text=ICON_CHARS["height"] + " Height:").grid(column=0, row=2, sticky=tk.E, padx=10, pady=5) height_spinbox = tk.Spinbox(self) height_spinbox.config(increment=1, format='%2.0f', width=5, textvariable=self.tmp_custom_data["height"]) height_spinbox.grid(column=1, row=2, sticky=tk.W, padx=10, pady=5) self.tmp_custom_data["insect"] = tk.IntVar(value=15) tk.Label(self, text=ICON_CHARS["ant"] + " Insect intensity:").grid(column=2, row=0, sticky=tk.E, padx=10, pady=5) insect_spinbox = tk.Spinbox(self) insect_spinbox.config(from_=1, to=99, increment=1, format='%2.0f', wrap=True, width=3, textvariable=self.tmp_custom_data["insect"]) insect_spinbox.grid(column=3, row=0, sticky=tk.W, padx=10, pady=5) # game of life checkbox self.tmp_custom_data["if_gol"] = tk.BooleanVar(value=False) gol_box = tk.Checkbutton(self, text="Game of life generator", variable=self.tmp_custom_data["if_gol"]) gol_box.grid(column=2, row=2, padx=10, pady=5, columnspan=4) # seed entry self.tmp_custom_data["seed"] = tk.StringVar(value=0) seed_frame = tk.Frame(self) seed_frame.grid(column=0, row=3, padx=10, pady=5, columnspan=4) tk.Label(seed_frame, text="Seed:").pack(side=tk.LEFT) seed_entry = tk.Entry(seed_frame, textvariable=self.tmp_custom_data["seed"]) seed_entry.config(width=30) seed_entry.pack(side=tk.RIGHT, padx=5) submit = tk.Button(self, text="Start", command=self.submit) submit.grid(column=0, row=5, padx=10, pady=5, columnspan=5) def submit(self): for x in self.tmp_custom_data: self.custom_data[x] = self.tmp_custom_data[x].get() self.destroy()
import re packages_file = 'packages.txt' name_regex = 'Product Name:(.*)' vers_regex = 'Version:(.*)' pkg_name = '' pkg_vers = '' pkg_dict = {} pkg_names_dict = {'PkgInFile':'PkgOnServer'} with open(packages_file, 'r') as f: for line in f: pkg_name_match = re.search(name_regex, line) if pkg_name_match: pkg_name = pkg_name_match.group(1).strip() pkg_vers_match = re.search(vers_regex, line) if pkg_vers_match: pkg_vers = pkg_vers_match.group(1).strip() pkg_dict[pkg_name] = pkg_vers for k, v in pkg_dict.items(): if k in pkg_names_dict: print(pkg_names_dict[k], v) else: print(k, v)
import scrapy import re from scrapy.spidermiddlewares.httperror import HttpError from twisted.internet.error import DNSLookupError from twisted.internet.error import TimeoutError, TCPTimedOutError UsersConfig = { # 代理 'proxy': '', 'email': 'placeholder', # placeholder 'password': 'placeholder', # placeholder } class SubmitsSpider(scrapy.Spider): name = "submits" headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q = 0.8", "Accept-Encoding": "gzip,deflate", "Accept-Language": "en-US,en;q=0.9", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Host": "acm.hdu.edu.cn", "Referer": "http://acm.hdu.edu.cn/status.php", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36 (KHTML, likeGecko) Chrome/65.0.3325.181 Safari/537.36" } def start_requests(self): currentUrl = 'http://acm.hdu.edu.cn/status.php?first=3231790&user=&pid=&lang=&status=#status' yield scrapy.Request(url=currentUrl, headers=self.headers, meta={ 'currentUrl': currentUrl, 'proxy': UsersConfig['proxy'], 'from': { 'sign': 'else', 'data': {} } }, callback=self.parse) def parse(self, response): # currUrl = response.meta['currUrl'] # n_id = int(currUrl.split('first=')[1].split("&user=")[0]) fixed_table = response.xpath('//div[@id="fixed_table"]/table/tr') order_list = ['', 'time', 'judgeStatus', 'problemID', 'executeTime', 'executeMemory', 'codeLength', 'language', 'author'] item_dict ={} for ind in range(1, 9): temp_list = [] for each_cell in range(1, len(fixed_table)): each_line = fixed_table[each_cell] temp_list.append(each_line.xpath('.//td')[ind].xpath('.//text()').extract()) item_dict[order_list[ind]] = temp_list temp = ''.join(re.findall(r"\d", str(response.xpath('//div[@id="fixed_table"]/p/a[3]/@href').extract()))) print("**************") print(temp) if int(temp) == 1: temp = ''.join(re.findall(r"\d", str(response.xpath('//div[@id="fixed_table"]/p/a[2]/@href').extract()))) print(temp) currentPage = int(temp) - 1 item_dict['url_num'] = currentPage with open('badpage.txt', 'a') as bb: bb.write(str(currentPage)) bb.write('\n') next = currentPage - 15 else: temp = ''.join(re.findall(r"\d", str(response.xpath('//div[@id="fixed_table"]/p/a[3]/@href').extract()))) currentPage = int(temp) + 15 item_dict['url_num'] = currentPage next = currentPage - 15 next_page = 'http://acm.hdu.edu.cn/status.php?first=' + str(next) + '&user=&pid=&lang=&status=#status' print("**************") yield item_dict print(next_page) yield scrapy.Request(url = next_page,headers = self.headers, callback = self.parse)
from flask import Flask app = Flask(__name__) # TODO:主页路由 @app.route('/') def home_page(): return u'今天是11月6日' if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port=6000)
#! /usr/bin/env python import random def seqsim (A, B, D, C): file = open ( 'SeqSimulation.txt', 'w' ) #This is the file that outcomes will be written Bases = list ( 'ATGC' ) Barcodes = [] DropSeq = [] for i in range (A): Barcode = [ random.choice ( Bases ) for i in range (B) ] #random.choice makes a list of (B) items from the Bases list. Barcode = ''.join ( Barcode ) #Join takes the items of this list and generate a string via concatenating them Barcodes.append ( Barcode ) #Adding each barcode (string) to the list of Barcodes as an item. for i in range (D): #To make D UMI+mRNAs UMI = [ random.choice (Bases ) for i in range (8) ] #randomly choosing 8 bases to make an UMI UMI = ''.join ( UMI ) #Joining those 8 bases to make a string mRNA = [ random.choice (Bases) for i in range (C) ] #Choosing C random bases to make an mRNA mRNA = ''.join (mRNA) #Concatenating the bases and generating a mRNA sequence (string) Read = ( random.choice(Barcodes) + UMI + mRNA + '\n') #choosing a random barcode and concatenating it with the UMI and the mRNA generated and puting a line ending file.write ( Read ) #then writing it in the file (SeqSimulation.txt) file.close() B = int(raw_input ( 'Barcode size ' )) #These a re the parameters asked to the user. A = int(raw_input ( 'Number of barcodes ' )) C = int(raw_input ( 'Length of mRNA ' )) D = int(raw_input ( 'Number of mRNAs reads ' )) seqsim (A, B, D, C) #After parameters are given, this runs the function with given parameters. print ('Simulations are saved in SeqSimulation.txt in your directory') #Notification for the user H = raw_input ( 'Would you like the sequences to be sorted according to barcodes Y/N ? ' ) #Question to the user for continum. H = H.upper () #Capitalizing the answer letter def seqsorter ( X ): #This is the function that sort sequences into alphabetical order. f = open ( X, 'r' ) #Working on the file X file = open ( 'SortedSeq.txt', 'w' ) #And writing the outcome in the file SortedSeq.txt lines = f.readlines () #reading the lines of the file X Y = sorted ( lines ) #sorting the lines into alphabetical order for item in Y: #writing every row to the file (SortedSeq.txt) file.write ( item ) f.close() file.close() print ( 'The Sequences are sorted and saved in SortedSeq.txt in your directory' ) #Notification for the user if H == ( 'Y' ): #If the answer for the question on line 33 is Y it executes the function on SeqSimulation.txt seqsorter ( 'SeqSimulation.txt' )
import textwrap import libtcodpy as libtcod class GUIHandler: def __init__(self, player): self.gui_panels = [] #Message Panels gui_message = MessagePanel(player, 40, 41, 40, 10) gui_message.message("Welcome to Eoraldil!", libtcod.yellow) gui_message.message("Your journey begins... in a cave. A dark, and lonely cave", libtcod.grey) self.gui_panels.append(gui_message) #Inventory Panel inventory = InventoryPanel(player, 62, 0, 19, 39) self.inventory = inventory #Character Panel character = CharacterPanel(player, 62, 0, 19, 39) self.activeSide = character self.character = character #Vital Panels gui_vitals = VitalPanel(player, 0, 41, 40, 10) self.gui_panels.append(gui_vitals) def update(self): for panel in self.gui_panels: panel.update() self.activeSide.update() class MessagePanel: def __init__(self, player, posX, posY, length, height, rows=7): self.msgs = [] self.posX = posX self.posY = posY self.length = length self.height = height self.rows = rows self.player = player self.panel = libtcod.console_new(length, height) def message(self, message, color=libtcod.white): #split the message if necessary, among multiple lines new_msg_lines = textwrap.wrap(message, self.length) for line in new_msg_lines: #if the buffer is full, remove the first line to make room for the new one if len(self.msgs) == self.rows: del self.msgs[0] #add the new line as a tuple, with the text and the color self.msgs.append( (line, color) ) def update(self): panel = self.panel game_msgs = self.msgs #prepare to render the GUI panel libtcod.console_set_default_background(panel, libtcod.black) libtcod.console_clear(panel) #print the game messages, one line at a time y = 1 for (line, color) in game_msgs: libtcod.console_set_default_foreground(panel, color) libtcod.console_print_ex(panel, 0, y, libtcod.BKGND_NONE, libtcod.LEFT, line) y += 1 #blit the contents of "panel" to the root console libtcod.console_blit(panel, 0, 0, self.length, self.height, 0, self.posX, self.posY) class InventoryPanel(MessagePanel): def __init__(self, player, posX, posY, length, height, rows=39): MessagePanel.__init__(self, player, posX, posY, length, height, rows) self.refresh() def refresh(self): player = self.player self.message("==========") self.message("INVENTORY") self.message("==========") if player.mainHand == None: self.message("Main : None") else: self.message("Main : " + str(player.mainHand.name)) class CharacterPanel(MessagePanel): def __init__(self, player, posX, posY, length, height, rows=15): counter = 0 MessagePanel.__init__(self, player, posX, posY, length, height, rows) self.refresh() def refresh(self): player = self.player Class = player.curClass self.message("==========") self.message("CHARACTER") self.message("==========") self.message("Name : " + str(player.name)) self.message("Class : " + str(Class.name)) self.message("Level : " + str(Class.level)) self.message("==========") self.message("Core Stats") self.message("==========") self.message("STR : " + str(Class.strength), libtcod.light_red) self.message("CON : " + str(Class.constitution), libtcod.light_orange) self.message("DEX : " + str(Class.dexterity), libtcod.green) self.message("AGI : " + str(Class.agility), libtcod.light_green) self.message("WIS : " + str(Class.wisdom), libtcod.light_blue) self.message("INT : " + str(Class.intelligence), libtcod.light_purple) class VitalPanel: def __init__(self, player, posX, posY, length, height, rows=7): self.msgs = [] self.posX = posX self.posY = posY self.length = length self.height = height self.rows = rows self.player = player self.panel = libtcod.console_new(length, height) def render_bar(self, x, y, total_width, name, value, maximum, bar_color, back_color): panel = self.panel #render a bar (HP, experience, etc). first calculate the width of the bar bar_width = int(float(value) / maximum * total_width) #render the background first libtcod.console_set_default_background(panel, back_color) libtcod.console_rect(panel, x, y, total_width, 1, False, libtcod.BKGND_SCREEN) #now render the bar on top libtcod.console_set_default_background(panel, bar_color) if bar_width > 0: libtcod.console_rect(panel, x, y, bar_width, 1, False, libtcod.BKGND_SCREEN) #finally, some centered text with the values libtcod.console_set_default_foreground(panel, libtcod.black) libtcod.console_print_ex(panel, x + total_width / 2, y, libtcod.BKGND_NONE, libtcod.CENTER, name + ': ' + str(value) + '/' + str(maximum)) def update(self): panel = self.panel #show the player's stats player = self.player self.render_bar(1, 1, 25, 'EXP', player.curClass.exp, player.curClass.tnl, libtcod.grey, libtcod.dark_grey) self.render_bar(1, 3, 25, 'HP', player.curClass.hp, player.curClass.maxHp, libtcod.red, libtcod.darker_red) self.render_bar(1, 5, 25, 'MP', player.curClass.mp, player.curClass.maxMp, libtcod.blue, libtcod.darker_blue) self.render_bar(1, 7, 25, 'STA', player.curClass.stamina, player.curClass.maxStamina, libtcod.orange, libtcod.darker_orange) #blit the contents of "panel" to the root console libtcod.console_blit(panel, 0, 0, 81, 8, 0, self.posX, self.posY)
""" Tests for the resource manager. """ # Standard library imports. import unittest import urllib2 import StringIO # Major package imports. from pkg_resources import resource_filename # Enthought library imports. from envisage.resource.api import ResourceManager from envisage.resource.api import NoSuchResourceError from traits.api import HasTraits, Int, Str # This module's package. PKG = 'envisage.resource.tests' # mimics urllib2.urlopen for some tests. # In setUp it replaces urllib2.urlopen for some tests, # and in tearDown, the regular urlopen is put back into place. def stubout_urlopen(url): if 'bogus' in url: raise urllib2.HTTPError(url, '404', 'No such resource', '', None) elif 'localhost' in url: return StringIO.StringIO('This is a test file.\n') else: raise ValueError('Unexpected URL %r in stubout_urlopen' % url) class ResourceManagerTestCase(unittest.TestCase): """ Tests for the resource manager. """ ########################################################################### # 'TestCase' interface. ########################################################################### def setUp(self): """ Prepares the test fixture before each test method is called. """ self.stored_urlopen = urllib2.urlopen urllib2.urlopen = stubout_urlopen return def tearDown(self): """ Called immediately after each test method has been called. """ urllib2.urlopen = self.stored_urlopen return ########################################################################### # Tests. ########################################################################### def test_file_resource(self): """ file resource """ rm = ResourceManager() # Get the filename of the 'api.py' file. filename = resource_filename('envisage.resource', 'api.py') # Open a file resource. f = rm.file('file://' + filename) self.assertNotEqual(f, None) contents = f.read() f.close() # Open the api file via the file system. g = file(filename, 'rb') self.assertEqual(g.read(), contents) g.close() return def test_no_such_file_resource(self): """ no such file resource """ rm = ResourceManager() # Open a file resource. self.failUnlessRaises( NoSuchResourceError, rm.file, 'file://../bogus.py' ) return def test_package_resource(self): """ package resource """ rm = ResourceManager() # Open a package resource. f = rm.file('pkgfile://envisage.resource/api.py') self.assertNotEqual(f, None) contents = f.read() f.close() # Get the filename of the 'api.py' file. filename = resource_filename('envisage.resource', 'api.py') # Open the api file via the file system. g = file(filename, 'rb') self.assertEqual(g.read(), contents) g.close() return def test_no_such_package_resource(self): """ no such package resource """ rm = ResourceManager() # Open a package resource. self.failUnlessRaises( NoSuchResourceError, rm.file, 'pkgfile://envisage.resource/bogus.py' ) self.failUnlessRaises( NoSuchResourceError, rm.file, 'pkgfile://completely.bogus/bogus.py' ) return def test_http_resource(self): """ http resource """ # Open an HTTP document resource. rm = ResourceManager() f = rm.file('http://localhost:1234/file.dat') self.assertNotEqual(f, None) contents = f.read() f.close() self.assertEquals(contents, 'This is a test file.\n') return def test_no_such_http_resource(self): """ no such http resource """ # Open an HTTP document resource. rm = ResourceManager() self.failUnlessRaises( NoSuchResourceError, rm.file, 'http://localhost:1234/bogus.dat' ) return def test_unknown_protocol(self): """ unknown protocol """ # Open an HTTP document resource. rm = ResourceManager() self.failUnlessRaises(ValueError, rm.file, 'bogus://foo/bar/baz') return # Entry point for stand-alone testing. if __name__ == '__main__': unittest.main() #### EOF ######################################################################
from django.apps import AppConfig class TecheiConfig(AppConfig): name = 'techei'
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """ **Project Name:** MakeHuman server socket plugin **Product Home Page:** TBD **Code Home Page:** TBD **Authors:** Joel Palmius **Copyright(c):** Joel Palmius 2018 **Licensing:** MIT Abstract -------- This plugin opens a TCP socket and accepts some basic commands. It does not make much sense without a corresponding client. """ import gui3d import mh import gui import socket import json import sys mhapi = gui3d.app.mhapi isPy3 = mhapi.utility.isPy3 if isPy3: from .dirops import SocketDirOps from .meshops import SocketMeshOps from .modops import SocketModifierOps from .workerthread import WorkerThread class SocketTaskView(gui3d.TaskView): def __init__(self, category): self.human = gui3d.app.selectedHuman gui3d.TaskView.__init__(self, category, 'Socket') self.log = mhapi.utility.getLogChannel("socket") box = self.addLeftWidget(gui.GroupBox('Server')) self.aToggleButton = box.addWidget(gui.CheckBox('Accept connections')) @self.aToggleButton.mhEvent def onClicked(event): if isPy3: if self.aToggleButton.selected: self.openSocket() else: self.closeSocket() self.scriptText = self.addTopWidget(gui.DocumentEdit()) if isPy3: self.scriptText.setText('') else: self.scriptText.setText('This version of the socket plugin requires the py3 version of MH from github.') self.scriptText.setLineWrapMode(gui.DocumentEdit.NoWrap) if isPy3: self.dirops = SocketDirOps(self) self.meshops = SocketMeshOps(self) self.modops = SocketModifierOps(self) def threadMessage(self,message): self.addMessage(str(message)) def evaluateCall(self): ops = None data = self.workerthread.jsonCall conn = self.workerthread.currentConnection if self.meshops.hasOp(data.function): ops = self.meshops if self.dirops.hasOp(data.function): ops = self.dirops if self.modops.hasOp(data.function): ops = self.modops if ops: jsonCall = ops.evaluateOp(conn,data) else: jsonCall = data jsonCall.error = "Unknown command" if not jsonCall.responseIsBinary: self.addMessage("About to serialize JSON. This might take some time.") response = jsonCall.serialize() #print("About to send:\n\n" + response) response = bytes(response, encoding='utf-8') else: response = jsonCall.data print("About to send binary response with length " + str(len(response))) conn.send(response) conn.close() def addMessage(self,message,newLine = True): self.log.debug("addMessage: ", message) if newLine: message = message + "\n" self.scriptText.addText(message) def openSocket(self): self.addMessage("Starting server thread.") self.workerthread = WorkerThread() self.workerthread.signalEvaluateCall.connect(self.evaluateCall) self.workerthread.signalAddMessage.connect(self.threadMessage) self.workerthread.start() def closeSocket(self): #self.addMessage("Closing socket.") if not self.workerthread is None: self.workerthread.stopListening() self.workerthread = None category = None taskview = None def load(app): category = app.getCategory('Community') taskview = category.addTask(SocketTaskView(category)) def unload(app): if taskview: taskview.closeSocket()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 1 20:08:24 2018 @author: zhaoyu """ from GradientDecent import * def sigmoid(x): return 1./(1+np.exp(-x)) def full_connect_sigmoid(X, beta, beta0): return sigmoid(np.matmul(X, beta)+beta0) def full_connect_softmax(X, beta, beta0): return softmax(np.matmul(X, beta)+beta0) def forward(X, weight0, b0, weight1, b1): h = full_connect_sigmoid(X, weight0, b0) pr = full_connect_softmax(h, weight1, b1) return h, pr def backward(X, y, weight0, b0, weight1, b1): n_case = X.shape[0] n_class = 10 n_hidden = weight0.shape[1] [h, pr] = forward(X, weight0, b0, weight1, b1) weight1_mean = np.matmul(weight1, pr.T) pd_loss_h = np.zeros([n_case, n_hidden]) for i in range(n_case): pd_loss_h[i] = -(weight1[:, y[i]]-weight1_mean[:, i]) for i in range(n_case): pr[i][y[i]] -= 1 pd_loss_weight1 = 1/n_case * np.matmul(h.T, pr) pd_loss_b1 = 1/n_case * np.matmul(np.ones([n_case]), pr) tmp= pd_loss_h * h * (1-h) pd_loss_weight0 = 1/n_case * np.matmul(X.T, tmp) pd_loss_b0 = 1/n_case * np.matmul(np.ones([n_case]), tmp) return pd_loss_weight0, pd_loss_b0, pd_loss_weight1, pd_loss_b1 def mlp_cross_ent(y, pr): ent = 0 for i in range(y.shape[0]): ent -= np.log(pr[i][y[i]]) return ent def mlp_accuracy(y, predict_y): return np.sum(y==predict_y)/y.shape[0] def mlp_mini_batch(X, y, weight0, b0, weight1, b1, batch_size=32): n_case = X.shape[0] batch_num = int(np.ceil(n_case/batch_size)) gama_0 = 5 gama_1 = 2 for i in range(batch_num): h, pr = forward(X, weight0, b0, weight1, b1) predict_y = np.argmax(pr, axis=1) loss = 1/n_case * mlp_cross_ent(y, pr) acc = mlp_accuracy(y, predict_y) print('{0}: loss={1:.6f} acc={2:.6f}'.format(i, loss, acc)) X_batch = X[i*batch_size:min((i+1)*batch_size, n_case), :] y_batch = y[i*batch_size:min((i+1)*batch_size, n_case)] gd_weight0, gd_b0, gd_weight1, gd_b1 = backward(X_batch, y_batch, weight0, b0, weight1, b1) weight0 -= gd_weight0*gama_0 b0 -= gd_b0*gama_0 weight1 -= gd_weight1*gama_1 b1 -= gd_b1*gama_1 class MultilayerPerceptron: def __init__(self): self.n_samp = 0 self.n_feat = 0 self.n_class = 0 def fit(self, X, y, n_hiddens = []): self.n_samp, self.n_feat = X.shape self.n_class = len(set(y)) self.n_hiddens = n_hiddens self.n_layers = len(self.n_hiddens) + 1 self.init_params() def init_params(self): self.ws = [] self.bs = [] if self.n_layers == 1: nrow, ncol = self.n_feat, self.n_class tmp_w = np.random.normal(0, 1, [nrow, ncol]) tmp_b = np.random.normal(0, 1, [ncol]) self.ws.append(tmp_w) self.bs.append(tmp_b) for ilayer in range(self.n_layers): nrow, ncol = 0, 0 if ilayer == 0: nrow, ncol = self.n_feat, self.n_hiddens[ilayer] elif ilayer == self.n_layers-1: nrow, ncol = self.n_hiddens[-1], self.n_class else: nrow, ncol = self.n_hiddens[ilayer-1], self.n_hiddens[ilayer] tmp_w = np.random.normal(0, 1, [nrow, ncol]) tmp_b = np.random.normal(0, 1, [ncol]) self.ws.append(tmp_w) self.bs.append(tmp_b) def summary(self): print(self.n_feat, ' input features, ', self.n_class, ' classes', ) print(self.n_layers, ' hidden layers: ', self.n_hiddens) for each in self.ws: print(each.shape) if __name__ == '__main__': print(sigmoid(1)) train_file = './data/train.csv' X_train, y_train = read_mnist(train_file, True) model = MultilayerPerceptron() model.fit(X_train, y_train, [10]) model.summary()
# Generated by Django 3.0.5 on 2020-04-17 17:38 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Mail_Records', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('mail', models.CharField(max_length=32)), ('domain', models.TextField()), ('probed', models.TextField()), ('d_type', models.CharField(max_length=10)), ('change_to', models.TextField()), ('state', models.TextField()), ('frequency', models.IntegerField()), ], options={ 'db_table': 'Mail_Records', }, ), migrations.CreateModel( name='Session_Mail', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('mail', models.CharField(max_length=32)), ('switch', models.CharField(max_length=10)), ('domain', models.TextField()), ], options={ 'db_table': 'Session_Mail', }, ), ]
""" tests for the merged-results command """ import pscheduler import unittest class MergedResultsTest(pscheduler.ToolMergedResultsUnitTest): name = 'owping' def test_merged_results(self): #only to check here is that we get back the one item we put in #NOTE: There is code for two results but it is not used #don't really care about the format since code doesn't check it, just care that # program runs and we get out what we put in results = [{"succeeded": True, "param": 1}] self.assert_result_at_index(results, 0) if __name__ == '__main__': unittest.main()
import unittest import library NUM_CORPUS = ''' On the 5th of May every year, Mexicans celebrate Cinco de Mayo. This tradition began in 1845 (the twenty-second anniversary of the Mexican Revolution), and is the 1st example of a national independence holiday becoming popular in the Western Hemisphere. (The Fourth of July didn't see regular celebration in the US until 15-20 years later.) It is celebrated by 77.9% of the population-- trending toward 80. ''' class TestCase(unittest.TestCase): # Helper function def assert_extract(self, text, extractors, *expected): actual = [x[1].group(0) for x in library.scan(text, extractors)] self.assertEquals(str(actual), str([x for x in expected])) # First unit test; prove that if we scan NUM_CORPUS looking for mixed_ordinals, # we find "5th" and "1st". def test_mixed_ordinals(self): self.assert_extract(NUM_CORPUS, library.mixed_ordinals, '5th', '1st') # Second unit test; prove that if we look for integers, we find four of them. def test_integers(self): self.assert_extract(NUM_CORPUS, library.integers, '1845', '15', '20', '80') # Third unit test; prove that if we look for integers where there are none, we get no results. def test_no_integers(self): self.assert_extract("no integers", library.integers) # Fourth unit test; def test_dates(self): self.assert_extract("I was born on 2015-07-25.", library.dates_iso8601, '2015-07-25') # Fifth unit test; def test_wrong_date(self): self.assert_extract("is this date correct 2015-13-25.", library.dates_iso8601) # Sixth unit test; def test_human_dates(self): self.assert_extract("I was born on 25 Jan 2017.", library.dates_human, '25 Jan 2017') # failing tests def test_match_complex_dates(self): ''' dates with time stamps with minute ''' self.assert_extract("I was born on 2008-09-15T15:53.", library.complex_date_time, '2008-09-15T15:53') ''' dates with time stamp with seconds''' self.assert_extract("I was born on 2008-09-15T15:53:00.", library.complex_date_time, '2008-09-15T15:53:00') ''' dates with time stamp with milliseconds ''' self.assert_extract("I was born on 2008-09-15T15:53:00.322345.", library.complex_date_time, '2008-09-15T15:53:00.322345') ''' date time seperated with space ''' self.assert_extract("I was born on 2008-09-15 15:53:00.", library.complex_date_time, '2008-09-15 15:53:00') ''' date time seperated with T ''' self.assert_extract("I was born on 2008-09-15T15:53:00.", library.complex_date_time, '2008-09-15T15:53:00') ''' with three letter Timezone ''' self.assert_extract("I was born on 2008-09-15T15:53:00 EST.", library.complex_date_time, '2008-09-15T15:53:00 ES') ''' with one letter Timezone ''' self.assert_extract("I was born on 2008-09-15T15:53:00Z.", library.complex_date_time, '2008-09-15T15:53:00Z') ''' with Time offset ''' self.assert_extract("I was born on 2008-09-15T15:53:00 -0800.", library.complex_date_time, '2008-09-15T15:53:00 -0800') ''' with time stamp with milliseconds and Time offset and space''' self.assert_extract("I was born on 2008-09-15 15:53:00.345623 -0800.", library.complex_date_time, '2008-09-15 15:53:00.345623 -0800') ''' with time stamp with seconds and three letter Timezone and T''' self.assert_extract("I was born on 2008-09-15T15:53:00 EST.", library.complex_date_time, '2008-09-15T15:53:00 EST') def test_match_grouped_numbers(self): self.assert_extract("pay me 123,456,789.", library.grouped_number, '123,456,789') self.assert_extract("pay me 12,34,56,789.", library.grouped_number, '12,34,56,789') if __name__ == '__main__': unittest.main()
import random vidas = 5 CLEAN = "\033[H\033[J" arquivo = open('Lista_de_Palavras.txt', 'r', encoding='utf-8') if arquivo.mode == 'r': linhas_do_arquivo = arquivo.readlines() for linha in linhas_do_arquivo: palavra = linhas_do_arquivo[random.randrange(len(linhas_do_arquivo))] palavra = palavra.upper() arquivo.close() obscure = "_ " obscureword = [] for letra in range(len(palavra)-1): obscureword.append(obscure) while vidas > 0: for space in obscureword: print(space, end='') print('') letra = input("Digite a letra: ") letra = letra.upper() for i in range(len(palavra)): if palavra[i] == letra: obscureword[i] = letra for space in obscureword: print(space, end='') print('') letraspalavra = palavra.count(letra) print(CLEAN) if letraspalavra == 0: print('Você errou a letra e perdeu uma vida') vidas = (vidas - 1) print("A palavra contém a letra '" + letra + "'", letraspalavra, 'vez(es).') if vidas > 0: print("Você ainda tem", vidas, "vidas") else: print('Você perdeu! :(') print('A palavra era', palavra) if obscureword == list(palavra[:-1]): print('Você venceu!') break
from openspending.test.helpers import *
import pandas as pd import numpy as np # v = pd.read_csv('data/u_vacancies_parts.csv') # v['ind'] = v['id_vacancy_part'] # vr = pd.DataFrame() # vr['vacancy_id'] = v.id # vr['id'] = pd.Series(range(1, vr.vacancy_id.count() + 1), index=vr.index) # vr['text'] = v.text # tv = pd.read_csv('data/d_vacancies_parts_types.csv') # vr['type_id'] = v.type.apply(lambda x: np.array(tv[tv.name == x].id)[0]) # t = pd.DataFrame() # t['id'] = vr.id # t['vacancy_id'] = vr.vacancy_id # t['text'] = vr.text # t['type_id'] = vr.type_id # vr['ind'] = v.ind # t.to_csv('data/t_vacancies_parts.csv', index=False) # vr.to_csv('data/u_vacancies_parts_t.csv', index=False) from app import db from models import MatchPart v = pd.read_csv('data/u_vacancies_parts_t.csv') p = pd.read_csv('data/u_standards_parts_t.csv') s = pd.DataFrame() co = pd.read_csv('data/sim.csv') co = co[co.id_profstandard_part.notna()] co.id_profstandard_part = co.id_profstandard_part.astype('int') def getProfstandard_id(x): temp = np.array(p[p.ind == x].id) if len(temp) > 0: return temp[0] else: return None s['profstandard_part_id'] = co.id_profstandard_part.apply(getProfstandard_id) s = s[s.profstandard_part_id.notna()] s['vacancy_part_id'] = co.id_vacancy_part.apply(lambda x: np.array(v[v.ind == x].id)[0]) s['similarity'] = co.sc s['enriched_text'] = co.prof_text t = pd.DataFrame() t['vacancy_part_id'] = s.vacancy_part_id t['profstandard_part_id'] = s.profstandard_part_id t['similarity'] = s.similarity t['enriched_text'] = s.enriched_text t.to_csv('data/t_match_parts.csv', index=False) match_parts = pd.read_csv('data/t_match_parts.csv') for index, part in match_parts.iterrows(): value = MatchPart(vacancy_part_id=part['vacancy_part_id'], profstandard_part_id=part['profstandard_part_id'], similarity=part['similarity'], enriched_text=part['enriched_text']) db.session.add(value) db.session.commit()
from onegov.election_day.forms.upload.election_compound \ import UploadElectionCompoundForm from onegov.election_day.forms.upload.election import UploadMajorzElectionForm from onegov.election_day.forms.upload.election import UploadProporzElectionForm from onegov.election_day.forms.upload.party_results import \ UploadPartyResultsForm from onegov.election_day.forms.upload.rest import UploadRestForm from onegov.election_day.forms.upload.vote import UploadVoteForm from onegov.election_day.forms.upload.wabsti_majorz import \ UploadWabstiMajorzElectionForm from onegov.election_day.forms.upload.wabsti_proporz import \ UploadWabstiProporzElectionForm from onegov.election_day.forms.upload.wabsti_vote import UploadWabstiVoteForm __all__ = [ 'UploadElectionCompoundForm', 'UploadMajorzElectionForm', 'UploadPartyResultsForm', 'UploadProporzElectionForm', 'UploadRestForm', 'UploadVoteForm', 'UploadWabstiMajorzElectionForm', 'UploadWabstiProporzElectionForm', 'UploadWabstiVoteForm', ]
"""Generate page for context""" import os, re from datetime import datetime as dt from collections import Counter def create_page_name(dir_curr_crawl): return "{0}.md".format(os.path.basename(dir_curr_crawl)) def textify_grouped_notes(grouped_notes): def textify_created(created): return "**{0}**".format(created.strftime("%Y-%m-%d-%H:%M")) full_text = "## Notes\n\n" for title, notes in grouped_notes.items(): # Sort the list first text = ["\n\n".join([textify_created(note[1]), note[0]]) for note in notes] text = "\n\n".join(text) full_text += "### {0}\n\n{1}\n\n".format(title, text) return full_text def group_notes(grouped_notes, new_note): for k,v in new_note.items(): # TODO: Support case insensitive titles notes = grouped_notes.get(k, []) grouped_notes[k] = notes + v return grouped_notes def when_note_created(name_note): return dt.strptime(name_note.replace(".md", ""), "_%Y-%m-%d-%H%M") def get_title_level(line): """Determines whether line is a title and returns the level otherwise zero""" if line: m = re.match("^[#]+$", line.split(" ")[0]) if m: return len(m.group(0)) return 0 def adjust_title_level(line, new_level): ls = line.split(" ") ls[0] = "#"*new_level return " ".join(ls) def find_title_levels_distribution(text_split): """Return Counter object that has title level (e.g. ## is 2) to frequency""" title_levels = [ get_title_level(line) for line in text_split ] return Counter(filter(lambda tl: tl != 0, title_levels)) def get_title_level_biggest(title_levels): """Return the biggest title level given a Counter object of the distribution""" stl = sorted(list(title_levels)) return stl[0] if stl else 0 def identify_code_blocks(text_split): result = [i for i in range(0, len(text_split)) if "```" in text_split[i]] return list(zip(result[0::2], result[1::2])) def strip_chunks(text_split, ranges_to_remove): """ranges_to_remove is list of pairs the pairs is the range to remove from text_split inclusive""" result = [] pointer = 0 for s,e in ranges_to_remove: result += text_split[pointer:s] # Need to add one in order to not include endpoints pointer = e+1 if pointer != len(text_split): result += text_split[pointer:] return result def is_in_block(ranges_for_blocks, line_num): """True if line_num falls into one of the blocks otherwise False""" for s,e in ranges_for_blocks: if line_num < s: return False elif s <= line_num and line_num <= e: return True return False def parse_note(note_text, created): # Split by \n and group sequential text by header "##" note_text_split = note_text.split("\n") ranges_code_block = identify_code_blocks(note_text_split) note_no_blocks = strip_chunks(note_text_split, ranges_code_block) title_levels = find_title_levels_distribution(note_no_blocks) biggest_level = get_title_level_biggest(title_levels) store = {} last_group = None for i in range(0, len(note_text_split)): line = note_text_split[i] if not is_in_block(ranges_code_block, i): # Skip trying to do the title processing when in a code block title_level = get_title_level(line) if title_level == biggest_level: last_group = line.replace("#"*biggest_level, "").strip() continue elif title_level > 0: # Note groups start at 3 - yes hardcoded line = adjust_title_level(line, 3 + (title_level - biggest_level)) if not last_group: last_group = "Dot dot dot" lines = store.get(last_group, []) lines.append(line) store[last_group] = lines # Join the lines by \n # The filter is there to strip out entries (specifically for "NOSPECIFIC" # case that has a single line that is actually empty # NOTE: Stripping white spaces for each note entry to force entries to be # consistent in form # MAYBE CHANGE STRUCTURE FOR MORE CONTRON OVER TITLE? DICTATE HOW TITLE IS # SHOWN? result = { k: [("\n".join(v).strip(), created)] for k,v in store.items() if not(len(v) == 0 or (len(v) == 1 and len(v[0]) == 0))} return result def create_page(step, order_latest_first=True): dir_curr, dir_names, file_names = step with open(os.path.join(dir_curr, "_index.md"), "r+") as f: main = f.read() dir_notes = os.path.join(dir_curr, "_notes") grouped_notes = {} reversed_maybe = lambda n: reversed(n) if order_latest_first else n for name_note in reversed_maybe(sorted(os.listdir(dir_notes))): path_note = os.path.join(dir_notes, name_note) with open(path_note, "r+") as f: created = when_note_created(name_note) new_note = parse_note(f.read(), created) grouped_notes = group_notes(grouped_notes, new_note) return "\n".join([main, textify_grouped_notes(grouped_notes)])
import Config.Config as config def delete(): cur = config.conn.cursor() cmd = """ DROP TABLE public."DzdRules", public."MatchingRules", public."AggregateTests", public."CollectionsData", public."PhenotypeData", public."MainTable", public."MainTableAll", public."MainTableNulls", public."OrganismResistance"; """ try: cur.execute(cmd) config.conn.commit() except Exception as err: print(err) config.conn.rollback() def delete_all_tables(mode): if mode == 1: delete()
from django.urls import path from . import views urlpatterns = [ path('', views.index_view, name='index'), path('signup', views.signup_view, name='signup'), path('places', views.places_view, name='places'), path('signin', views.signin_view, name='signin'), path('logout', views.logout_view, name='logout'), path('about', views.about_view, name='about'), path('contact', views.contact_view, name='contact'), path('profile', views.profile_view, name='profile'), path('feeds', views.feeds_view, name='feeds'), path('newGroup', views.groups_view, name='group') ]
""" Computations on the (n+1)-dimensional Minkowski space. """ import numpy as np from geomstats.manifold import Manifold from geomstats.riemannian_metric import RiemannianMetric import geomstats.vectorization as vectorization class MinkowskiSpace(Manifold): """The Minkowski Space.""" def __init__(self, dimension): self.dimension = dimension self.metric = MinkowskiMetric(dimension) def belongs(self, point): """ Check if point belongs to the Minkowski space. """ point = vectorization.expand_dims(point, to_ndim=2) _, point_dim = point.shape return point_dim == self.dimension def random_uniform(self, n_samples=1): """ Sample a vector uniformly in the Minkowski space, with coordinates each between -1. and 1. """ point = np.random.rand(n_samples, self.dimension) * 2 - 1 return point class MinkowskiMetric(RiemannianMetric): """ Class for the pseudo-Riemannian Minkowski metric. The metric is flat: inner product independent of the reference point. The metric has signature (-1, n) on the (n+1)-D vector space. """ def __init__(self, dimension): super(MinkowskiMetric, self).__init__( dimension=dimension, signature=(dimension - 1, 1, 0)) def inner_product_matrix(self, base_point=None): """ Minkowski inner product matrix. Note: the matrix is independent on the base_point. """ inner_prod_mat = np.eye(self.dimension) inner_prod_mat[0, 0] = -1 return inner_prod_mat def exp_basis(self, tangent_vec, base_point): """ The Riemannian exponential is the addition in the Minkowski space. """ return base_point + tangent_vec def log_basis(self, point, base_point): """ The Riemannian logarithm is the subtraction in the Minkowski space. """ return point - base_point def mean(self, points, weights=None): """ Weighted mean of the points. """ return np.average(points, axis=0, weights=weights)
''' Tweets DB schema Json object example: { "_id": ObjectId("56c8c1357e48b67d194d80c7"), "company": "Amazon", "count": 1000, "date": ISODate("2016-02-20T19:12:00Z") } ''' # These belongs to models. you should create a seperate folder for models. # schema folder is just for any .sql file class tcount(): def __init__(self, company=None, count=None, score=None, date=None): self.company = company self.count = count self.score = score self.date = date def __repr__(self): return '<text %r %r %r %r>' % (self.company, self.count, self.score, self.date)
import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import callbacks from pages.header import navbar from pages.layout_dashboard import layout_dashboard from pages.layout_acceuil import layout_acceuil from app import app,server #layout rendu par l'application app.layout = html.Div([ dcc.Location(id='url', refresh=True), navbar, html.Div(id='page-content') ]) #callback pour mettre à jour les pages @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if pathname=='/acceuil' or pathname=='/': return layout_acceuil elif pathname=='/dashboard': return layout_dashboard if __name__ == '__main__': app.run_server(debug=True)
from django.db import models from django.contrib.auth.models import User # Create your models here. ''' class User(models.Model): summoner = models.CharField(max_length=16)#summoner Name class Logger(User): user = models.ForeignKey(User) username = models.CharField(max_length=16) password = models.CharField(max_length=30) class Matches(models.Model): user = models.ForeignKey(User) ''' class UserProfile(models.Model): # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User) #username = models.CharField(max_length=30,blank=True) #password = models.CharField(max_length=30,blank=True) # Override the __unicode__() method to return out something meaningful! def __unicode__(self): return self.user.username
import sys import argparse from math import sin, cos, pi, exp from .utils.misc import bisection, newton, secant, false_position def get_args(): parser = argparse.ArgumentParser() parser.add_argument('mode', type=int, choices=[1, 2, 3]) parser.add_argument('--a', type=float) parser.add_argument('--b', type=float) parser.add_argument('--tol', type=float, default=0.00001) parser.add_argument('--n', type=int, default=200, help='max iteration num') parser.add_argument('--p0', type=float) parser.add_argument('--p1', type=float) return parser.parse_args() def main(): args = get_args() if args.mode == 1: f = lambda x: 2 - 3 * x - sin(x) a = args.a b = args.b tol = args.tol n = args.n root, iternum, error = bisection(f, a, b, tol, n) print("使用二分法求解:") print('方程的根为%f,需要的迭代次数为%d,误差为%f' % (root, iternum, error)) if args.mode == 2: f = lambda x: 1/2 + 1/4*x**2 - x*sin(x) - 1/2*cos(2*x) seq_p0 = [pi/2, 5*pi, 10*pi] print("使用牛顿法求解:") for index, p0 in enumerate(seq_p0): root, iternum, error = newton(f, p0, args.tol, args.n) print('当初始值为%f时,求得的根为%f,迭代次数为%d,误差为%f' % (p0, root, iternum, error)) if args.mode == 3: f = lambda x: 5 * x - exp(x) a = args.a b = args.b p0 = args.p0 p1 = args.p1 tol = args.tol n = args.n # using bisection method root, iternum, error = bisection(f, a, b, tol, n) print('使用二分法求解,根为%.4f,迭代次数为%d,误差为%f' % (root, iternum, error)) # using newton's method root, iternum, error = newton(f, p0, tol, n) print('使用牛顿法求解,根为%.4f,迭代次数为%d,误差为%f' % (root, iternum, error)) # using secant method root, iternum, error = secant(f, p0, p1, tol, n) print('使用割线法求解,根为%.4f,迭代次数为%d,误差为%f' % (root, iternum, error)) # using false position method root, iternum, error = false_position(f, p0, p1, tol, n) print('使用错位法求解,根为%.4f,迭代次数为%d,误差为%f' % (root, iternum, error)) if __name__ == '__main__': print(sys.argv) main()
from .layers import GraphConv, GraphMaxPool, GraphAveragePool __version__ = '0.14.0'
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn from torch.autograd import Variable class Head(nn.Module): def __init__(self, args): super(Head, self).__init__() # logging self.logger = args.logger # params self.visualize = args.visualize if self.visualize: self.vis = args.vis self.refs = args.refs self.win_head = None self.use_cuda = args.use_cuda self.dtype = args.dtype # params self.num_heads = args.num_heads self.batch_size = args.batch_size self.hidden_dim = args.hidden_dim self.mem_hei = args.mem_hei self.mem_wid = args.mem_wid self.num_allowed_shifts = args.num_allowed_shifts def _reset_states(self): self.wl_prev_vb = Variable(self.wl_prev_ts).type( self.dtype ) # batch_size x num_heads x mem_hei def _reset(self): # NOTE: should be called at each child's __init__ # self._init_weights() self.type(self.dtype) # put on gpu if possible # TODO: see how this one is reset # reset internal states self.wl_prev_ts = ( torch.eye(1, self.mem_hei) .unsqueeze(0) .expand(self.batch_size, self.num_heads, self.mem_hei) ) self._reset_states() def _visual(self): raise NotImplementedError("not implemented in base calss") def _access(self, memory_vb): # NOTE: called at the end of forward, to use the weight to read/write from/to memory raise NotImplementedError("not implemented in base calss")
# !/usr/bin/python # coding=utf-8 # # @Author: LiXiaoYu # @Time: 2014-06-06 # @Info: 循环队列 import Log from Config import Config class CircularQueue(): #配置对象 __config = "" #假设队列最大长度 __maxsize = 1000000 #队列数据结构 __sq = {"data":[],"front":0,"rear":0} #i __i=0 #初始化 def __init__(self): self.__config = Config() #入队列 def handler_8001(self, p): sql = p.get("sql","") self.__i = self.__i + 1 sql = sql % self.__i print(sql) q=self.__sq print("rear = %d" % q['rear']) try: if ((q['rear']+1)%self.__maxsize == q['front']): return [0,{"msg":"error"}] q['data'].append(sql) q['rear']=(q['rear']+1)%self.__maxsize except: Log.error() return [0,{"msg":"error"}] return [8001,{"msg":"success"}] #出队列 def handler_8002(self, p): q=self.__sq try: if q['front'] == q['rear']: return [0,{"msg":"error"}] e = q['data'][q['front']] q['front']=(q['front']+1)%self.__maxsize except: Log.error() return [0,{"msg":"error"}] return [8002,e] #队列长度 def handler_8003(self, p): q=self.__sq try: temp = (q['rear']-q['front']+self.__maxsize)%self.__maxsize except: Log.error() return [0,{"msg":"error"}] return [8003,temp] if __name__ == "__main__": cq = CircularQueue() #入队列,向队列里添加10条sql for i in range(10): cq.handler_8001({"sql":"select "+str(i)+" from table"}) #获取队列长度 print(cq.handler_8003()) #出队列,从队列里取出10条sql for i in range(10): print(cq.handler_8002()) #获取队列长度 print(cq.handler_8003())
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-04-20 06:30 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('authentication', '0021_previouspassword'), ] operations = [ migrations.RemoveField( model_name='previouspassword', name='time', ), migrations.AlterUniqueTogether( name='previouspassword', unique_together=set([('user', 'password')]), ), ]
from flask import Flask, render_template, session, request, redirect, url_for import random app= Flask(__name__) f = open('Emergency_Response_Incidents.csv','r') s = f.read() f.close() def happenings(): l = s.split("\n") Incidents = [] for i in l: q = i.split(",") Incidents.append(q[0]) return Incidents def place(): l = s.split("\n") Places = [] for i in l: q = i.split(",") Places.append(q[len(q) - 1]) return Places @app.route("/",methods=["GET","POST"]) @app.route("/home",methods=["GET","POST"]) def home(): return render_template("home.html") @app.route("/marquee") def ranIn(): l = happenings() i = random.randint(0,len(l) - 1) t = str(l[i]) l = place() t = t + ": " + str(l[i]) return t @app.route("/contentload") def contlod(): return s if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0',port=8000)
# https://www.hackerrank.com/challenges/symmetric-difference/problem m = int(input()) setM = set(list(map(int, input().split(" ")))) n = int(input()) setN = set(list(map(int, input().split(" ")))) intersec = setM.intersection(setN) uni = setM.union(setN) result = sorted(list(uni.difference(intersec))) [print(i) for i in result]
from ffl import app, db, models, espn, draft, mcts from flask import render_template, session, flash, redirect, url_for, request @app.route('/team/<team_code>') def showPlayersByTeam(team_code): teams = models.NflTeam.query.order_by(models.NflTeam.name).all() positions = models.Position.query.order_by(models.Position.order).all() team = next(t for t in teams if t.espn_code == team_code) players = models.NflPlayer.query.\ filter(models.NflPlayer.team == team).\ order_by(models.NflPlayer.projected_points.desc()) players = [( pos.name, url_for('showPlayersByPosition', pos_code=pos.espn_code), [p for p in players if pos in p.positions] ) for pos in positions] return render_template('show_players.html', players=players, teams=teams, positions=positions, breadcrumbs=['Teams', team.name]) @app.route('/position/<pos_code>') def showPlayersByPosition(pos_code): teams = models.NflTeam.query.order_by(models.NflTeam.name).all() positions = models.Position.query.order_by(models.Position.order).all() position = next(p for p in positions if p.espn_code == pos_code) players = models.NflPlayer.query.\ filter(models.NflPlayer.positions.contains(position)).\ order_by(models.NflPlayer.projected_points.desc()) players = [( t.name, url_for('showPlayersByTeam', team_code=t.espn_code), [p for p in players if p.team is t] ) for t in teams] return render_template('show_players.html', players=players, teams=teams, positions=positions, breadcrumbs=['Positions', position.name]) @app.route('/') def index(): teams = models.NflTeam.query.order_by(models.NflTeam.name).all() positions = models.Position.query.order_by(models.Position.order).all() return render_template('index.html', teams=teams, positions=positions) @app.route('/email', methods=["POST"]) def addEmail(): e = models.UserEmail(email=request.form['email']) db.session.add(e) db.session.commit() flash('Your email address ' + request.form['email'] + ' was successfully added to our mailing list.') return redirect(url_for('index')) @app.route('/draft') def showDraft(): NONE_STRING = "--" ITERMAX = int(app.config['ITERMAX']) nflteams = models.NflTeam.query.order_by(models.NflTeam.name).all() positions = models.Position.query.order_by(models.Position.order).all() if not 'draftToken' in session: token, teams, order = espn.initDraft() session['draftToken'] = token session['draftTeams'] = teams session['draftOrder'] = order token = session['draftToken'] teams = session['draftTeams'] order = session['draftOrder'] def teamId2idx(id): return next(idx for idx, team in enumerate(teams) if team['teamId'] == id) picks, index = espn.getDraft(token) fa = draft.getFreeAgents() latestPick = next(p.name for p in fa if p.espn_id == picks[-1]['playerId']) \ if picks else NONE_STRING nextTeam = teams[teamId2idx(order[index])]["teamAbbrev"] \ if index < len(order) else NONE_STRING rosters = [[] for _ in teams] turns = [teamId2idx(id) for id in order[index:]] state = draft.GameState(rosters, turns, fa) for pick in picks: player = next(p for p in fa if p.espn_id == pick['playerId']) state.PickFreeAgent(teamId2idx(pick['teamId']), player) if request.args.get('analyze'): _, nodes = mcts.UCT(state, ITERMAX) rankings = [(n.move, "[S/V: " + "{:.2f}".format(n.score / n.visits) + " | V: " + str(n.visits) + "]") for n in nodes] else: rankings = [(m, None) for m in state.GetMoves()] return render_template('draft.html', latestPick=latestPick, nextTeam=nextTeam, freeagents=fa, rankings=rankings, teams=nflteams, positions=positions)
#! python3.6 import os import sys from functools import partial import logging.handlers import atexit from pathlib import Path # for schedule from textwrap import dedent # schedule from time import sleep # schedule import appdirs import click import schedule import arrow from screenshotto.__init__ import (APPNAME, VERSION_STRING, CONFIG_PATH, CONFIG_DIR) from screenshotto.log import logger_setup, handle_exception from screenshotto.clickaliases import ClickAliasedGroup log_dir = appdirs.user_log_dir(APPNAME, False) log = logger_setup(log_dir, __file__) uncaught_exception_handler = partial(handle_exception, log) sys.excepthook = uncaught_exception_handler log.debug(VERSION_STRING) from screenshotto.util import save_screenshot, attach_console from screenshotto import config SCHEDFP = Path(CONFIG_DIR) / "schedule.txt" def set_debug(debug=True): log.debug(f"set_debug({debug})") for loghandler in log.handlers: if isinstance(loghandler, logging.handlers.MemoryHandler): conhandler = loghandler.target if debug: # set flushlevel so debugs are handled when we flush in a sec loghandler.flushLevel = logging.DEBUG else: conhandler.setLevel(logging.INFO) # 'send' all log messages that have been queued until this point log.debug("Flushing log.") loghandler.flush() # we don't need to queue/buffer messages anymore # so change capacity to 1 - effectively flushing on every message # we could remove memhandler and add conhandler here BUT then # conhandler wouldn't be last, and strip ansi formatter doesn't work loghandler.capacity = 1 def keep_open(): input("\nPress enter to close...") def echo(*args, **kwargs): try: click.echo(*args, **kwargs) except AttributeError: pass CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS, cls=ClickAliasedGroup, invoke_without_command=True) @click.option("--show-window", "-sw", is_flag=True, help="Force show console window and keep it open.") @click.option("--debug", is_flag=True, help="Show debug messages") @click.option("--version", "-v", is_flag=True, help="Print version number") @click.pass_context def cli(ctx, show_window, debug, version): """ Capture a screenshot of the entire screen (all monitors) and save it. \n There is no prompt. The entire operation is unattended, though you will see basic log messages. \n Files are named and saved according to options in the config file which is generated automatically on first run and can be found in the user config directory. """ if show_window: log.debug("Force show window mode") atexit.register(keep_open) if os.path.basename(sys.executable) == "pythonw.exe": log.debug("Currently running with pythonw.exe. " "Attaching new python console.") attach_console(APPNAME) if debug: log.debug("Debug mode") set_debug(debug) # important to set this either way so log is flushed! if version: echo(VERSION_STRING) elif not ctx.invoked_subcommand: log.debug("No subcommand. Showing help.") print(ctx.get_help()) @cli.command(name="screenshot", aliases=["capture", "save", "ss"], help="Capture and save a screenshot without user interaction") def screenshot(): imgfp = save_screenshot() echo(f"\nScreenshot saved to:\n\t{imgfp}") @cli.command(name="config", help="Open config file") def open_config_for_edit(): # default config is generated automatically when config.py is imported #os.startfile(CONFIG_PATH, "edit") click.edit(filename=CONFIG_PATH) @cli.command(name="log", help="Open log file") def view_log(): os.startfile(log.logfp) @cli.group(name="schedule", help="Run screenshot command on a schedule", cls=ClickAliasedGroup) def schedule_group(): log.debug("schedule_group()") def write_default_schedule(): log.debug(f"Writing default schedule to {SCHEDFP}") s = dedent(""" # Uncomment one or more of the example lines below, or add your own here: ## https://schedule.readthedocs.io/en/stable/ #schedule.every().second.do(job) #schedule.every(10).seconds.do(job) #schedule.every(30).to(60).seconds.do(job) #schedule.every().minute.do(job) #schedule.every(10).minutes.do(job) #schedule.every(5).to(10).minutes.do(job) #schedule.every().hour.do(job) #schedule.every(6).hours.do(job) #schedule.every(6).to(12).hours.do(job) #schedule.every().day.do(job) #schedule.every().day.at("06:30").do(job) #schedule.every(2).days.do(job) #schedule.every(2).days.at("15:00").do(job) #schedule.every().week.do(job) #schedule.every(2).weeks.do(job) #schedule.every().monday.do(job) #schedule.every().tuesday.do(job) #schedule.every().wednesday.do(job) #schedule.every().thursday.do(job) #schedule.every().friday.do(job) #schedule.every().saturday.do(job) #schedule.every().sunday.at("23:59").do(job) """).strip() with open(SCHEDFP, "w") as f: f.write(s) @schedule_group.command(name="edit", help="Open schedule file for editing") def schedule_edit(): log.debug("schedule_edit()") if not os.path.isfile(SCHEDFP): write_default_schedule() #os.startfile(SCHEDFP, "edit") click.edit(filename=SCHEDFP) @schedule_group.command(name="run", aliases=["start"], help="Start processing schedule.") @click.pass_context def schedule_run(ctx): log.debug("schedule_run()") if not os.path.isfile(SCHEDFP): echo("You don't have a schedule set up!\n") ctx.invoke(schedule_edit) template = dedent(""" def job(): termw, _ = click.get_terminal_size() print("\\r" + " ".ljust(termw), end="") click.get_current_context().invoke(screenshot) print() {usercode} termw, _ = click.get_terminal_size() while True: nextrun = schedule.next_run() if not nextrun: log.debug("Schedule has no jobs defined") cmdpath = ctx.command_path.split() cmdpath[-1] = "edit" cmdpath = " ".join(cmdpath) echo("Schedule has no jobs defined! " "Maybe try '" + cmdpath + "'") break nextrun = arrow.get(schedule.next_run(), "local") timestr = nextrun.humanize() timestr = timestr.replace("just now", "imminently") if timestr == "in seconds": secs = (nextrun - arrow.now()).total_seconds() timestr = "in " + str(int(secs)) + " seconds" print(("\\r" + "Next screenshot will be captured " + timestr + "...").ljust(termw), end="") schedule.run_pending() sleep(1) """) with open(SCHEDFP, "r") as f: code = template.format(usercode=f.read()) #print(code) exec(code) if __name__ == "__main__": cli()
""" Convert an Excel spreadsheet to a tab-delimited text file. Prints output to standard output. """ import sys import datetime try: import xlrd except ImportError: print >> sys.stderr, 'Please see http://pypi.python.org/pypi/xlrd' sys.exit(1) def create_parser(): from optparse import OptionParser parser = OptionParser( 'usage: python %s filename.xls output.tsv [options]' % __file__) parser.add_option( '--worksheet', '-w', dest='worksheet', type='string', default=None, help='The name of the worksheet to open') return parser def get_rows(xls_fname, sheet_name=None): """ Get the table rows from an Excel spreadsheet. xls_fname The filename of the spreadsheet. sheet_name The worsheet to open. If None, opens the first worksheet. Returns a list of table rows. Each table row is a list of columns. Each column is a string. """ book = xlrd.open_workbook(xls_fname, formatting_info=True) # # TODO: proper handling of exceptions and error conditions. Use asserts # for now to see exactly what can break. # assert book assert book.nsheets, 'No worksheets in file' if sheet_name: sheet = book.sheet_by_name(sheet_name) assert book.sheet_loaded(sheet_name), 'Failed to load sheet' else: sheet = book.sheet_by_index(0) assert book.sheet_loaded(0), 'Failed to load sheet' rows = [] for i in range(sheet.nrows): col = [] for j in range(sheet.ncols): cell = sheet.cell(i,j) # # TODO: all numbers are represented in floats. # Is it required to determine what the number was displayed as in # Excel? e.g. 4 vs 4.0 # format_key = book.xf_list[cell.xf_index].format_key _format = book.format_map[format_key] if _format.type == xlrd.FDT: date_tuple = xlrd.xldate_as_tuple(cell.value, book.datemode) date = datetime.datetime(*date_tuple) # # TODO: convert _format.format_str into something datetime # will understand # val = str(date) else: # # Get rid of unnecessary floating point numbers. # if type(cell.value) == float and cell.value == int(cell.value): val = str(int(cell.value)) else: val = str(cell.value) # # TODO: can this actually happen? # assert val.find('\t') == -1, 'Found Tab in cell value' col.append(val) rows.append(col) return rows def main(): parser = create_parser() (options, args) = parser.parse_args() if len(args) != 2: parser.error('incorrect number of arguments') rows = get_rows(args[0], options.worksheet) try: fout = open(args[1], 'w') fout.write('\n'.join(map(lambda x: '\t'.join(x), rows))) fout.close() print 'OK' except IOError, ioe: print >> sys.stderr, 'unable to write to file: %s' % args[1] if __name__ == '__main__': main()
import unittest from resources import pda from resources import json_reader class TestPDASimulator(unittest.TestCase): def test_string_acceptance(self): """ Tests if a string is accepted or rejected by a DPA """ file_dir = './files/' test1 = pda.PDA(json_reader.read_file(file_dir + 'pda_1_edit.json')) self.assertTrue(test1.check_string("")) self.assertTrue(test1.check_string("0")) self.assertFalse(test1.check_string("1")) self.assertTrue(test1.check_string("00")) self.assertFalse(test1.check_string("11")) self.assertTrue(test1.check_string("0011")) self.assertFalse(test1.check_string("1110001")) self.assertFalse(test1.check_string("1111111")) self.assertTrue(test1.check_string("0000000")) test2 = pda.PDA(json_reader.read_file(file_dir + 'pda_7_2_2.json')) self.assertTrue(test2.check_string("")) self.assertFalse(test2.check_string("a")) self.assertTrue(test2.check_string("abba")) self.assertTrue(test2.check_string("abab")) self.assertTrue(test2.check_string("baba")) test3 = pda.PDA(json_reader.read_file(file_dir + 'pda_7_1_2.json')) self.assertTrue(test3.check_string("")) self.assertTrue(test3.check_string("a")) self.assertTrue(test3.check_string("ab")) self.assertTrue(test3.check_string("aaaaaaaaaa")) self.assertTrue(test3.check_string("aaaaaaabbbbbbb")) self.assertFalse(test3.check_string("aaaaaaabbbbbb")) self.assertFalse(test3.check_string("abba")) self.assertFalse(test3.check_string("abab")) self.assertFalse(test3.check_string("baba")) def test_string_in_alphabet(self): """ Tests if a string contains only characters defined in the alphabet """ file_dir = './files/' print() print("Testing if string contains characters defined in the alphabet.") test1 = pda.PDA(json_reader.read_file(file_dir + 'pda_1_edit.json')) self.assertTrue(test1.check_if_in_alphabet("")) self.assertTrue(test1.check_if_in_alphabet("0")) self.assertTrue(test1.check_if_in_alphabet("1")) self.assertTrue(test1.check_if_in_alphabet("00")) self.assertTrue(test1.check_if_in_alphabet("11")) self.assertFalse(test1.check_if_in_alphabet("a")) self.assertFalse(test1.check_if_in_alphabet("b")) self.assertFalse(test1.check_if_in_alphabet("a0011")) self.assertFalse(test1.check_if_in_alphabet("0011a")) if __name__ == '__main__': unittest.main()
x = int(input("Digite um número: ")) lista = [] contador = 0 while contador < x: if contador % 2 != 0: lista.append(contador) contador += 1 print("Os números ímpares são: ", lista)
# File Module FILE_MOD_ADDWORD = "module_addword" FILE_MOD_CHECKFILE = "module_checkfile" FILE_MOD_FIND = "module_find" #Folder FOLDER_WORD = "word/"
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('investigator', '0011_auto_20170706_0053'), ] operations = [ migrations.RenameField( model_name='investigator', old_name='active', new_name='is_active', ), migrations.AddField( model_name='investigator', name='created_at', field=models.DateTimeField(default=datetime.datetime(2017, 8, 13, 13, 29, 40, 778109, tzinfo=utc), auto_now_add=True), preserve_default=False, ), migrations.AddField( model_name='investigator', name='updated_at', field=models.DateTimeField(default=datetime.datetime(2017, 8, 13, 13, 29, 42, 223151, tzinfo=utc), auto_now=True), preserve_default=False, ), migrations.AlterField( model_name='investigatorrates', name='default_in_area_payment_for_children', field=models.FloatField(default='15.00'), ), migrations.AlterField( model_name='investigatorrates', name='default_in_area_payment_for_each_additional_adult_signature', field=models.FloatField(default='30.00'), ), migrations.AlterField( model_name='investigatorrates', name='default_in_area_payment_for_one_signature', field=models.FloatField(default='80.00'), ), migrations.AlterField( model_name='investigatorrates', name='default_in_area_payment_when_signature_not_obtained', field=models.FloatField(default='60.00'), ), migrations.AlterField( model_name='investigatorrates', name='default_out_of_area_payment_for_children', field=models.FloatField(default='15.00'), ), migrations.AlterField( model_name='investigatorrates', name='default_out_of_area_payment_for_each_additional_adult_signature', field=models.FloatField(default='30.00'), ), migrations.AlterField( model_name='investigatorrates', name='default_out_of_area_payment_for_one_signature', field=models.FloatField(default='80.00'), ), migrations.AlterField( model_name='investigatorrates', name='default_out_of_area_payment_when_signature_not_obtained', field=models.FloatField(default='60.00'), ), migrations.AlterField( model_name='investigatorrates', name='maximum_in_area_payment_for_any_number_of_signatures', field=models.FloatField(default='180.00'), ), migrations.AlterField( model_name='investigatorrates', name='maximum_out_of_area_payment_for_any_number_of_signatures', field=models.FloatField(default='180.00'), ), migrations.AlterField( model_name='investigatorrates', name='mileage_compensation_rate', field=models.FloatField(default='.5'), ), migrations.AlterField( model_name='investigatorrates', name='mileage_threshold', field=models.FloatField(default='75.0'), ), ]
import sys import os import json import utils import activity def main(): if (len(sys.argv) <3): print("") print("") print('usage: python scanReplay.py <game_dir> <command>') print("") print('...where command can be :') print(' show_activity # show what happens at each DP') sys.exit() replay_json_path = sys.argv[1] command = sys.argv[2] if os.path.exists(replay_json_path): if not utils.verify_path_is_replay_json(replay_json_path): print("replay json file not valid.") sys.exit() if command == "show_activity": show_activity(replay_json_path) else: print("") print("ERROR - subcommand "+ command + " not recognized.") else: print("given file does not exist:", replay_json_path) def show_activity(replay_json_path): print("extracting game activity from replay json file") fname = os.path.basename(replay_json_path) parts = fname.split(".") replay_name = parts[0] print("") print("replay name : " + replay_name) activity.show_activity_via_replay_json(replay_json_path) if __name__ == '__main__': main()
# coding:utf-8 from selenium import webdriver from xlutils3.copy import copy # 将xlrd.Book转为xlwt.workbook,在原有的excel基础上进行修改,添加等。 import xlwt # 写入excel(新建) import xlrd # 读取excel import os import time import cx_Oracle import unittest from openpyxl import Workbook import sys sys.path.append('F:\\PyTesting\\AutoTest\\public') from Login_c import login from GetVerifyCode import get_code from Data_Comp import test_read_excel from Get_DB_Data import export from ConfigParser import ReadConfigFile sys.path.append('F:\\PyTesting\\AutoTest\\test\\action') from base_action import BaseAction class Test_warn(unittest.TestCase): ''' 报警警告报表查询测试''' @classmethod def setUpClass(cls): print("开始测试") cls.driver = webdriver.Chrome() cls.driver.maximize_window() read = ReadConfigFile("TestUrl") item_list = read.get_config_value() url = item_list[0][1] cls.driver.get(url) time.sleep(5) @classmethod def tearDownClass(cls): print("结束测试") cls.driver.quit() # def setUp(self): # # print("开始单个测试用例") # # self.dr = webdriver.Chrome() # # self.dr.maximize_window() # # self.dr.get('http://192.168.10.110:8080/WebGis/login') # # time.sleep(5) # # def tearDown(self): # print("结束单个测试用例") def test_1login(cls): '''用户登录''' driver = cls.driver CodeText = get_code(driver) login(driver, 'baoyong123', 'asdf1234', CodeText) # 正确用户名和密码 time.sleep(3) def test_2skip(cls): '''跳转到报表查询界面''' driver = cls.driver test = BaseAction(driver) test.Click("id", "gps_toolbar_leftbutton_div_w") test.Click("id", "gps_main_menu_report_s_p") time.sleep(2) # 等待元素加载 test.Click("id", "id201286") time.sleep(2) report_name = test.Get_text("xpath", "//*[@id='rnavigation']/li[2]/span[2]") try: cls.assertEqual(report_name, '报警类型统计') print("页面跳转成功!") except AssertionError as e: print("跳转失败,找不到报表标题:", report_name) raise def test_3switch_page(cls): '''分页跳转,获取分页中的所有数据''' driver = cls.driver pages = driver.find_element_by_xpath( "//*[@id='_T201286']/td/div/div[3]/div/div/table/tbody/tr").find_elements_by_tag_name("td") t = len(pages) # print(t) if t - 7 <= 9: for i in range(t - 7): driver.find_element_by_xpath( "//*[@id='_T201286']/td/div/div[3]/div/div/table/tbody/tr/td[3]/div/table/tbody/tr/td[" + str( i + 1) + "]/div").click() time.sleep(3) driver.find_element_by_xpath( "//*[@id='_T201286']/td/div/div[3]/div/div/table/tbody/tr/td[3]/div/table/tbody/tr/td[" + str( i + 1) + "]/div") cls.load_Table(i) print("获取报表第" + str(i + 1) + "页数据成功!") def load_Table(cls, page): '''获取报表页面数据''' # 创建工作簿 driver = cls.driver wbk = xlwt.Workbook(encoding='utf-8', style_compression=0) # 创建工作表 sheet = wbk.add_sheet('Web_data', cell_overwrite_ok=True) excel = r"F:\PyTesting\AutoTest\log\excel\Warn_TARG.xls" table_rows = driver.find_element_by_xpath( "//*[@id='_T201286']/td/div/div[1]/table").find_elements_by_tag_name('tr') row = 20 for i, tr in enumerate(table_rows): # enumerate()是python的内置函数.enumerate多用于在for循环中得到计数 if i == 0 and page == 0: table_cols1 = tr.find_elements_by_tag_name('th') for j, tc in enumerate(table_cols1): sheet.write(i, j, tc.text) wbk.save(excel) else: table_cols2 = tr.find_elements_by_tag_name('td') for j, tc in enumerate(table_cols2): # 老的工作簿,打开excel oldWb = xlrd.open_workbook(excel, formatting_info=True) # 新的工作簿,复制老的工作簿 newWb = copy(oldWb) # 新的工作表 newWs = newWb.get_sheet(0) newWs.write(i + page * row, j, tc.text) os.remove(excel) newWb.save(excel) def test_4get_dbdata(cls): '''获取数据库中的数据''' sql = "select h.v_targ_id,h.v_targ_name,t.n_warn_type,t.d_warn_date from GPS_TARG h,WARN_HISTORY t where h.v_targ_id= t.v_targ_id and t.d_warn_date between " \ "to_date('2018-08-08 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date('2018-08-08 23:59:59','yyyy-mm-dd hh24:mi:ss')" scrpath = "F:\\PyTesting\\AutoTest\\log\\excel\\" # 指定的保存目录 export(sql, scrpath + r'WARN_TARG_DB.xlsx') print("获取数据库数据成功!") def test_5get_dbdata(cls): '''报警警告报表数据查询验证''' excel = "F:\\PyTesting\\AutoTest\\log\\excel\\Warn_TARG.xls" excel1 = "F:\\PyTesting\\AutoTest\\log\\excel\\WARN_TARG_DB.xlsx" test_read_excel(excel, excel1, "Warn_Result.xlsx") def test_6login_out(cls): '''退出登录''' driver = cls.driver driver.find_element_by_id("gps_main_quit_span_w").click() time.sleep(2) driver.find_element_by_xpath("//body//div//div//div//button/span[./text()='确定']").click() print("退出成功!") if __name__ == '__main__': unittest.main()
a = int(input("Enter the value of a: ")) # 5 b = int(input("Enter the value of b: ")) # 6 a = a + b # a = 11, b = 6 b = a - b # b = 5 a = a - b # a = 6 print("After Swaping") print("Value of a =", a) print("Value of b =", b)
def tostring(c): c.__str__ = lambda c: "%s(%s)" % ( c.__class__.__name__, ", ".join(str(v) for v in c.__dict__.values()) ) return c
a=input() i=0 b=[] for y in range(len(a)): if a[i].lower()=='a' or a[i].lower()=='e' or a[i].lower()=='i' or a[i].lower()=='o' or a[i].lower()=='u': b.append(a[i]) else: i=i+1 if (len(b))>0: print("yes") else: print("no")
from tokenizers import BertWordPieceTokenizer import urllib from transformers import AutoTokenizer import os def download_vocab_files_for_tokenizer(tokenizer, model_type, output_path): vocab_files_map = tokenizer.pretrained_vocab_files_map vocab_files = {} for resource in vocab_files_map.keys(): download_location = vocab_files_map[resource][model_type] f_path = os.path.join(output_path, os.path.basename(download_location)) urllib.request.urlretrieve(download_location, f_path) vocab_files[resource] = f_path return vocab_files model_type = 'bert-base-uncased' output_path = './my_local_vocab_files/' tokenizer = AutoTokenizer.from_pretrained(model_type) vocab_files = download_vocab_files_for_tokenizer(tokenizer, model_type, output_path) fast_tokenizer = BertWordPieceTokenizer(vocab_files.get('vocab_file'), vocab_files.get('merges_file'))
import cv2 import numpy as np from darkflow.net.build import TFNet from shapely.geometry import box, Polygon from data_collection.img_process import grab_screen from object_detection.direction import Direct # set YOLO options options = { 'model': 'cfg/yolo.cfg', 'load': 'bin/yolov2.weights', 'threshold': 0.3, 'gpu': 0.5 } tfnet = TFNet(options) # capture = cv2.VideoCapture('gta2.mp4') t = (0, 0, 0) colors = [tuple(255 * np.random.rand(3)) for i in range(5)] colors2 = [tuple(t) for j in range(15)] def light_recog(frame, direct, traffic_lights): traffic_light = traffic_lights[0] # find out which traffic light to follow, if there are several if len(traffic_lights) > 1: # if we need to go to the right if direct == Direct.RIGHT or direct == Direct.SLIGHTLY_RIGHT: for tl in traffic_lights: if tl['topleft']['x'] > traffic_light['topleft']['x']: traffic_light = tl # straight or left else: for tl in traffic_lights: if tl['topleft']['x'] < traffic_light['topleft']['x']: traffic_light = tl # coordinates of the traffic light top_left = (traffic_light['topleft']['x'], traffic_light['topleft']['y']) bottom_right = (traffic_light['bottomright']['x'], traffic_light['bottomright']['y']) # crop the frame to the traffic light roi = frame[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]] hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) color_detected = '' mid_x = (bottom_right[0] + top_left[0]) / 2 mid_y = (top_left[1] + bottom_right[1]) / 2 # measure the width of the detected object by asking how many pixels-wide the object is. apx_distance = round((1 - ((bottom_right[0] / 800) - (top_left[0] / 800))) ** 18, 1) frame = cv2.putText(frame, '{}'.format(apx_distance), (int(mid_x), int(mid_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) # possible color ranges for traffic lights red_lower = np.array([136, 87, 111], dtype=np.uint8) red_upper = np.array([180, 255, 255], dtype=np.uint8) yellow_lower = np.array([22, 60, 200], dtype=np.uint8) yellow_upper = np.array([60, 255, 255], dtype=np.uint8) green_lower = np.array([50, 100, 100], dtype=np.uint8) green_upper = np.array([70, 255, 255], dtype=np.uint8) # find what color the traffic light is showing red = cv2.inRange(hsv, red_lower, red_upper) yellow = cv2.inRange(hsv, yellow_lower, yellow_upper) green = cv2.inRange(hsv, green_lower, green_upper) kernel = np.ones((5, 5), np.uint8) red = cv2.dilate(red, kernel) res = cv2.bitwise_and(roi, roi, mask=red) green = cv2.dilate(green, kernel) res2 = cv2.bitwise_and(roi, roi, mask=green) (_, contours, hierarchy) = cv2.findContours(red, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in enumerate(contours): color_detected = "Red" (_, contours, hierarchy) = cv2.findContours(yellow, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in enumerate(contours): color_detected = "Yellow" (_, contours, hierarchy) = cv2.findContours(green, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in enumerate(contours): color_detected = "Green" if (0 <= top_left[1] and bottom_right[1] <= 437) and (244 <= top_left[0] and bottom_right[0] <= 630): frame = cv2.putText(frame, color_detected, bottom_right, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) frame = cv2.putText(frame, "detected", bottom_right, cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2) return frame, color_detected, apx_distance def distance_warning(frame, top_left, bottom_right): mid_x = (bottom_right[0] + top_left[0]) / 2 mid_y = (top_left[1] + bottom_right[1]) / 2 apx_distance = round((1 - ((bottom_right[0] / 800) - (top_left[0] / 800))) ** 4, 1) frame = cv2.putText(frame, '{}'.format(apx_distance), (int(mid_x), int(mid_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) # myRoi_array= np.array([[(0, 490), (309, 269), (490, 270), (800,473)]]) # process_img = region_of_interest(frame, myRoi_array) # cv2.imshow("precess_img", process_img) roi = Polygon([(15, 472), (330, 321), (470, 321), (796, 495)]) car = box(top_left[0], top_left[1], bottom_right[0], bottom_right[1]) if roi.intersects(car): cv2.putText(frame[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]], 'WARNING!', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) return frame, apx_distance def person_warning(frame, top_left, bottom_right): mid_x = (bottom_right[0] + top_left[0]) / 2 mid_y = (top_left[1] + bottom_right[1]) / 2 apx_distance = round((1 - ((bottom_right[0] / 800) - (top_left[0] / 800))) ** 15, 1) frame = cv2.putText(frame, '{}'.format(apx_distance), (int(mid_x), int(mid_y)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) br_array = np.array([[(bottom_right[0], bottom_right[1]), (bottom_right[0], bottom_right[1]), (bottom_right[0], bottom_right[1]), (bottom_right[0], bottom_right[1])]], dtype=np.int32) a1 = br_array[0, 0, 0] # tr[0 b2 = br_array[0, 0, 1] # tr[1 c3 = br_array[0, 1, 0] # tl[0 d4 = br_array[0, 1, 1] # tl[1 e5 = br_array[0, 2, 0] # bl[0 f6 = br_array[0, 2, 1] # bl[1 g7 = br_array[0, 3, 0] # br[0 h8 = br_array[0, 3, 1] # br[1 if apx_distance >= 0.6: if a1 <= 629 and b2 >= 360 and c3 >= 179 and d4 >= 37 and e5 >= 0 and f6 <= 503 and g7 <= 800 and h8 <= 500: cv2.putText(frame, 'WARNING!', bottom_right, cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) if apx_distance < 0.6: if a1 <= 559 and b2 >= 307 and c3 >= 295 and d4 >= 302 and e5 >= 12 and f6 <= 482 and g7 <= 800 and h8 <= 457: cv2.putText(frame, 'WARNING!', bottom_right, cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) return frame def yolo_detection(screen, direct): # find objects on a frame by using YOLO results = tfnet.return_predict(screen[:-130, :, :]) # create a list of detected traffic lights (might be several on a frame) traffic_lights = [] for color, color2, result in zip(colors, colors2, results): top_left = (result['topleft']['x'], result['topleft']['y']) bottom_right = (result['bottomright']['x'], result['bottomright']['y']) label = result['label'] confidence = result['confidence'] text = '{}: {:.0f}%'.format(label, confidence * 100) if label == 'traffic light' and confidence > 0.3: if 220 <= result['topleft']['x'] <= 750: traffic_lights.append(result) color = color2 screen = cv2.rectangle(screen, top_left, bottom_right, color, 6) screen = cv2.putText(screen, text, top_left, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) if label == 'car' or label == 'bus' or label == 'truck' or label == 'train': screen = distance_warning(screen, top_left, bottom_right) screen = cv2.rectangle(screen, top_left, bottom_right, color, 6) screen = cv2.putText(screen, text, top_left, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) if label == 'person': screen = person_warning(screen, top_left, bottom_right) screen = cv2.rectangle(screen, top_left, bottom_right, color, 6) screen = cv2.putText(screen, text, top_left, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) if traffic_lights: screen = light_recog(screen, direct, traffic_lights) return screen def main(): while True: screen = grab_screen() screen = yolo_detection(screen, 0) cv2.imshow("Frame", screen) key = cv2.waitKey(1) & 0xFF if key == ord("q"): cv2.destroyAllWindows() break if __name__ == '__main__': main()
from rest_framework import viewsets from kratos.apps.app import models, serializers from rest_framework.response import Response from rest_framework import status class AppViewSet(viewsets.GenericViewSet): ''' 应用信息 ''' serializer_class = serializers.AppSerializer queryset = models.App.objects.all() def list(self, request): ''' 应用列表 ''' records = self.paginator.paginate_queryset(self.get_queryset(), self.request, view=self) serializer = self.get_serializer(records, many=True) return self.paginator.get_paginated_response(serializer.data) def retrieve(self, request, pk=None): ''' 应用详情 ''' serializer = self.get_serializer(self.get_object()) return Response(serializer.data) def create(self, request): ''' 新增应用 ''' serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def partial_update(self, request, pk=None): ''' 应用信息更新 ''' serializer = self.get_serializer(self.get_object(), data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def destroy(self, request, pk=None): ''' 删除一条应用记录 ''' self.get_object().delete() return Response(status=status.HTTP_204_NO_CONTENT)
pessoas = list() dados = list() totpessoas = totleve = 0 visual = '*-' *30 while True: dados.append(str(input('Digite o nome de pessoa:'))) totpessoas += 1 dados.append(int(input('Digite o peso da pessoa:'))) resp = (str(input('Deseja continuar? [S/N]'))) pessoas.append(dados[:]) dados.clear() if resp in 'Nn': break print(visual) for p in pessoas: if p[1] >= 80: print(f'{p[0]} está acima do peso!') else: print(f'{p[0]} está abaixo do peso!') totleve += 1 print(f'Foram cadastradas {totpessoas} pessoas na lista, sendo {totleve} abaixo dos 80Kg') print(visual)
#!/usr/bin/env python # Copyright Reliance Jio Infocomm, Ltd. # Author: Soren Hansen <Soren.Hansen@ril.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import argparse import errno import sys import socket import time import urllib3 import urlparse import os import netifaces import re import json import yaml import consulate from urllib3.exceptions import HTTPError class DeploymentOrchestrator(object): UPDATE_AVAILABLE = 0 UP_TO_DATE = 1 NO_CLUE = 2 NO_CLUE_BUT_WERE_JUST_GETTING_STARTED = 3 def __init__(self, host='127.0.0.1', port=8500): self.host = host self.port = port self._consul = None self._kv = None @property def consul(self): if not self._consul: self._consul = session = consulate.Consulate(self.host, self.port) return self._consul def trigger_update(self, new_version): self.consul.kv.set('/current_version', new_version) # add k/v for nodes,roles, or globally for either configuration state # or upgarde versions. This is intended to allow for different override levels # to control whether or not puppet runs or versions updates def manage_config(self, action_type, scope, key, data=None, name=None, action="set"): if not any(action_type in s for s in ['config_state', 'config_version']): print "Invalid action type: %s" % action_type return False if not any(scope in s for s in ['global', 'role', 'host']): print "Invalid scope type: %s" % scope return False if name is None and scope != 'global': print 'name must be passed if scope is not global' return False else: if scope == 'global': name_url = '/' + key else: name_url = '/' + name + '/' + key if action == 'set': self.consul.kv.set("/%s/%s%s" % (action_type, scope, name_url), data) elif action == 'delete': self.consul.kv.__delitem__("/%s/%s%s" % (action_type, scope, name_url)) return data ## # get the value for a host based on a lookup order in a k/v store # Allows for multiple properties(example - enable_update, enable_puppet) # at various levels ## def lookup_ordered_data(self, keytype, hostname, data=None): order = self.get_lookup_hash_from_hostname(hostname) ret_dict = {} for x in order: if data is None: url = "/%s/%s%s/" % (keytype, x[0], x[1]) result = self.consul.kv.find(url) else: # pass in data to save the amount of calls you have # to make to the k/v store. Expects that the data has # been retrieved via consul.kv.find("/%s/" % data_type) # and been reformated via: self.reformat_data url = "%s/%s%s" % (keytype, x[0], x[1]) result = data.get(url) # print url if result is not None: # print result for k in result.keys(): ret_dict[k.rsplit('/',1)[-1]] = result[k] return ret_dict def get_host_match(self, name): return re.search('([a-z]+)(\d+)(-.*)?', name) def get_lookup_hash_from_hostname(self, name): m = self.get_host_match(name) if m is None: print "Unexpected hostname format %s" % name return {} return [['global', ''], ['role', '/'+m.group(1)], ['host', '/'+name] ] def local_health(self, hostname=socket.gethostname(), verbose=False): results = self.consul.health.node(hostname) failing = [x for x in results if (x['Status'] == 'critical' or (x['Status'] == 'warning' and (x['Name'] == 'puppet' or x['Name'] == 'validation'))) ] if verbose: for x in failing: print '%s: %s' % (x['Name'], x['Output']) return failing def pending_update(self): local_version = self.local_version() try: if (self.current_version() == local_version): return self.UP_TO_DATE elif (self.current_version() == None): return self.NO_CLUE_BUT_WERE_JUST_GETTING_STARTED else: return self.UPDATE_AVAILABLE except: if local_version: return self.NO_CLUE else: return self.NO_CLUE_BUT_WERE_JUST_GETTING_STARTED def current_version(self): cur_ver = self.consul.kv.get('/current_version') if cur_ver == None: return None else: return str(cur_ver).strip() def ping(self): try: return bool(self.consul.agent.members()) except (IOError, HTTPError): return False def update_own_status(self, hostname, status_type, status_result): status_dir = '/status/%s' % status_type if status_type == 'puppet': if int(status_result) in (4, 6, 1): self.consul.agent.check.ttl_warn('puppet') elif int(status_result) == -1: self.consul.agent.check.ttl_warn('puppet') else: self.consul.agent.check.ttl_pass('puppet') elif status_type == 'puppet_service': if int(status_result) in (4, 6, 1): self.consul.agent.check.ttl_fail('service:puppet') elif int(status_result) == -1: self.consul.agent.check.ttl_fail('service:puppet') else: self.consul.agent.check.ttl_pass('service:puppet') elif status_type == 'validation': if int(status_result) == 0: self.consul.agent.check.ttl_pass('validation') else: self.consul.agent.check.ttl_warn('validation') elif status_type == 'validation_service': if int(status_result) == 0: self.consul.agent.check.ttl_pass('service:validation') else: self.consul.agent.check.ttl_fail('service:validation') else: raise Exception('Invalid status_type:%s' % status_type) # this is not removing outdated versions? def update_own_info(self, hostname, version=None): version = version or self.local_version() if not version: return version_dir = '/running_version/%s' % version self.consul.kv.set('%s/%s' % (version_dir, hostname), str(time.time())) versions = self.running_versions() versions.discard(version) # check if other versions are registered for the same host for v in versions: if hostname in self.hosts_at_version(v): self.consul.kv.__delitem__('%s/%s/%s' % ('running_version', v, hostname)) # this call may not scale # if pulls down all host version records as # a single hash def running_versions(self): try: res = self.consul.kv.find('/running_version') return set([x.split('/')[1] for x in res]) except (KeyError, IndexError): return set() # this call may not scale # if pulls down all host version records as # a single hash def hosts_at_version(self, version): version_dir = '/running_version/%s' % (version,) try: res = self.consul.kv.find(version_dir) except KeyError: return [] result_set = set() for x in res: if x.split('/')[-2] == version: host = x.split('/')[-1] if host: result_set.add(host) return result_set def get_failures(self, hosts=False, show_warnings=False): failures = self.consul.health.state('critical') warnings = self.consul.health.state('warning') # validation and puppet failures are being treated as warnings in consul # that when they fail during bootstrapping, it does not cause services # to be deregistered by consul. This code ensures that those "warnings" # are treated as failures in this context puppet_failures = [w for w in warnings if w['Name'] == 'puppet'] validation_failures = [w for w in warnings if w['Name'] == 'validation'] failures = failures + puppet_failures + validation_failures if hosts: if len(failures) != 0: print "Failures:" for x in failures: print " Node: %s, Check: %s" % (x['Node'], x['Name']) other_warnings = [w for w in warnings if w['Name'] != 'validation' and w['Name'] != 'puppet'] if show_warnings: if hosts: if len(other_warnings) != 0: print "Warnings:" for x in other_warnings: print " Node: %s, Check: %s" % (x['Node'], x['Name']) failures = failures + other_warnings return len(failures) == 0 def verify_hosts(self, version, hosts): return set(hosts).issubset(self.hosts_at_version(version)) def check_single_version(self, version, verbose=False): running_versions = self.running_versions() unwanted_versions = filter(lambda x: x != version, running_versions) wanted_version_found = version in running_versions if verbose: print 'Wanted version found:', wanted_version_found print 'Unwanted versions found:', ', '.join(unwanted_versions) return wanted_version_found and not unwanted_versions def local_version(self, new_value=None): mode = new_value is None and 'r' or 'w' try: with open('/etc/current_version', mode) as fp: if new_value is None: return fp.read().strip() else: fp.write(new_value) return new_value except IOError, e: if e.errno == errno.ENOENT: return '' raise def debug_timeout(self, version): self.get_failures(True) if self.hosts_at_version(version): print "Registered hosts in consul with key name Running_Versions are:" for reg_host in self.hosts_at_version(version): print " %s" % reg_host else: print "No Hosts registered!" def check_puppet(self, hostname): check_paused_ret_code = self.check_puppet_paused(hostname) if check_paused_ret_code == 0: return self.check_pending(hostname) else: return check_paused_ret_code # check if a host is in the pending state for orchestration def check_pending(self, host): result = None keytype = "config_state/enable_puppet" order = self.get_lookup_hash_from_hostname(host) for x in order: url = "%s/%s%s" % (keytype, x[0], x[1]) response = self.consul.kv._adapter.get(self.consul.kv._build_uri([url])) if response.status_code == 200: consul_result = response.body elif response.status_code == 404: continue else: print "Unexpected code: %s for consul: %s" % (response.status_code, response.body) # if something unexpected happens, do not upgrade consul_result = {'Value': False} result = consul_result['Value'] if result == 'False' or result == False: return 9 else: return 0 # check to see if a node is explicitly pasued # this will override upgrade keys def check_puppet_paused(self, hostname): data_type="config_state" result = self.lookup_ordered_data(data_type, hostname) try: ret = str(result['enable_puppet']) if 'rue' in ret: return 0 else: return 9 except KeyError: # If its not set, default is true return 0 ## # These two functions are wrapper around manage_config for some general # use cases. Leaving manage_config untouched to be used as raw consul editor ## def enable_puppet(self, value, scope, name, action): return self.manage_config('config_state', scope, 'enable_puppet', value, name, action) def set_config(self, key, value, scope, name, config_type="config_state", action="set"): return self.manage_config(config_type, scope, key, value, name, action) # get a list of all hosts at all versions def hosts_at_versions(self): return {ver: self.hosts_at_version(ver) for ver in self.running_versions()} def main(argv=sys.argv[1:]): parser = argparse.ArgumentParser(description='Utility for ' 'orchestrating updates') parser.add_argument('--host', type=str, default='127.0.0.1', help="local consul agent") parser.add_argument('--port', type=int, default=8500, help="consul port") subparsers = parser.add_subparsers(dest='subcmd') trigger_parser = subparsers.add_parser('trigger_update', help='Trigger an update') trigger_parser.add_argument('version', type=str, help='Version to deploy') config_parser = subparsers.add_parser('manage_config', help='Update configuration action state for a fleet' ) config_parser.add_argument('config_type', type=str, help='Type of configuration to manage (config_version, config_state)') config_parser.add_argument('scope', type=str, help='Scope to which update effects (global, role, host)') config_parser.add_argument('key', type=str, help='Key to set data for') config_parser.add_argument('data', type=str, help='Data to set for specified key') config_parser.add_argument('--name', '-n', type=str, default=None, help='Name to apply updates to (host name, or role name, invalid for global)') config_parser.add_argument('--action', '-a', type=str, default="set", help='set or delete') host_data_parser = subparsers.add_parser('host_data', help='get the current value of data for a host' ) host_data_parser.add_argument('data_type', type=str, help='Type of host data to lookup') host_data_parser.add_argument('--hostname', '-n', type=str, default=socket.gethostname(), help='hostname to lookup data for') check_puppet_parser = subparsers.add_parser('check_puppet', help='Check if puppet is enabled') check_puppet_parser.add_argument('--hostname', '-n', type=str, default=socket.gethostname(), help='hostname to lookup data for') enable_puppet_parser = subparsers.add_parser('enable_puppet', help='Enable/Disable puppet') enable_puppet_parser.add_argument('value', type=str, help='True/False') enable_puppet_parser.add_argument('scope', type=str, help='scope - host / role / global') enable_puppet_parser.add_argument('--action', '-a', type=str, default="set", help='set / delete') enable_puppet_parser.add_argument('--name', '-n', type=str, help='role / hostname to set data for') set_config_parser = subparsers.add_parser('set_config', help='set/update/delete a config') set_config_parser.add_argument('key', type=str, help='Key to set data for') set_config_parser.add_argument('value', type=str, help='Data to set for key') set_config_parser.add_argument('scope', type=str, help='scope - host / role / global') set_config_parser.add_argument('--action', '-a', type=str, default="set", help='set / delete') set_config_parser.add_argument('--name', '-n', type=str, help='role / hostname to set data for') set_config_parser.add_argument('--config_type', '-c', type=str, default="state", help='config_state / config_version') current_version_parser = subparsers.add_parser('current_version', help='Get available version') ping_parser = subparsers.add_parser('ping', help='Ping consul') pending_update = subparsers.add_parser('pending_update', help='Check for pending update') local_health_parser = subparsers.add_parser('local_health', help='Check health of local system') local_health_parser.add_argument('--verbose', '-v', action='store_true', help='Be verbose') local_version_parser = subparsers.add_parser('local_version', help='Get or set local version') local_version_parser.add_argument('version', nargs='?', help="If given, set this as the local version") update_own_status_parser = subparsers.add_parser('update_own_status', help="Update info related to the current status of a host") update_own_status_parser.add_argument('--hostname', type=str, default=socket.gethostname(), help="This system's hostname") update_own_status_parser.add_argument('status_type', type=str, help="Type of status to update") update_own_status_parser.add_argument('status_result', type=int, help="Command exit code used to derive status") list_failures_parser = subparsers.add_parser('get_failures', help="Return a list of every failed host. Returns the number of hosts in a failed state") list_failures_parser.add_argument('--hosts', action='store_true', help="list out all hosts in each state and not just the number in each state") list_failures_parser.add_argument('--show_warnings', action='store_true', help="Whether to count warnings as failures") update_own_info_parser = subparsers.add_parser('update_own_info', help="Update host's own info") update_own_info_parser.add_argument('--hostname', type=str, default=socket.gethostname(), help="This system's hostname") update_own_info_parser.add_argument('--version', type=str, help="Override version to report into consul") running_versions_parser = subparsers.add_parser('running_versions', help="List currently running versions") hosts_at_version_parser = subparsers.add_parser('hosts_at_version', help="List hosts at specified version") hosts_at_version_parser.add_argument('version', type=str, help="Version to retrieve list of hosts for") verify_hosts_parser = subparsers.add_parser('verify_hosts', help="Verify that list of hosts are all available") verify_hosts_parser.add_argument('version', help="Version to look for") check_single_version_parser = subparsers.add_parser('check_single_version', help="Check if the given version is the only one currently running") check_single_version_parser.add_argument('version', help='The version to check for') debug_timeout_parser = subparsers.add_parser('debug_timeout', help="Provides debug information when script gets timed out") debug_timeout_parser.add_argument('version', help="Version to look for") check_single_version_parser.add_argument('--verbose', '-v', action='store_true', help='Be verbose') args = parser.parse_args(argv) do = DeploymentOrchestrator(args.host, args.port) if args.subcmd == 'trigger_update': do.trigger_update(args.version) elif args.subcmd == 'manage_config': print do.manage_config(args.config_type, args.scope, args.key, args.data, args.name, args.action) elif args.subcmd == 'host_data': print do.lookup_ordered_data(args.data_type, args.hostname) elif args.subcmd == 'check_puppet': sys.exit(do.check_puppet(args.hostname)) elif args.subcmd == 'enable_puppet': print do.enable_puppet(args.value, args.scope, args.name, args.action) elif args.subcmd == 'set_config': print do.set_config(args.key, args.value, args.scope, args.name, args.config_type, args.action) elif args.subcmd == 'current_version': print do.current_version() elif args.subcmd == 'check_single_version': sys.exit(not do.check_single_version(args.version, args.verbose)) elif args.subcmd == 'update_own_status': do.update_own_status(args.hostname, args.status_type, args.status_result) elif args.subcmd == 'update_own_info': do.update_own_info(args.hostname, version=args.version) elif args.subcmd == 'ping': did_it_work = do.ping() if did_it_work: print 'Connection succesful' return 0 else: print 'Connection failed' return 1 elif args.subcmd == 'local_version': print do.local_version(args.version) elif args.subcmd == 'running_versions': print '\n'.join(do.running_versions()) elif args.subcmd == 'hosts_at_version': print '\n'.join(do.hosts_at_version(args.version)) elif args.subcmd == 'verify_hosts': buffer = sys.stdin.read().strip() hosts = buffer.split('\n') return not do.verify_hosts(args.version, hosts) elif args.subcmd == 'get_failures': return not do.get_failures(args.hosts, args.show_warnings) elif args.subcmd == 'local_health': failures = do.local_health(socket.gethostname(), args.verbose) return len(failures) elif args.subcmd == 'pending_update': pending_update = do.pending_update() msg = {do.UPDATE_AVAILABLE: "Yes, there is an update pending", do.UP_TO_DATE: "No updates pending", do.NO_CLUE: "Could not get current_version", do.NO_CLUE_BUT_WERE_JUST_GETTING_STARTED: "Could not get current_version, but there's also no local version set" }[pending_update] print msg return pending_update elif args.subcmd == 'debug_timeout': return not do.debug_timeout(args.version) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
""" 2. Инкапсулировать оба параметра (название и цену) товара родительского класса. Убедиться, что при сохранении текущей логики работы программы будет сгенерирована ошибка выполнения. """ class ItemDiscount: def __init__(self, name, price): self.__name = name self.__price = price class ItemDiscountReport(ItemDiscount): def get_parent_data(self): return f'Товар {self.__name}, цена {self.__price}' # Будет ошибка # return f'Товар {self._ItemDiscount__name}, цена {self._ItemDiscount__price}' item = ItemDiscountReport('Диван', 11000) print(item.get_parent_data()) # AttributeError: 'ItemDiscountReport' object has no attribute '_ItemDiscountReport__name'
# Implementation of directed graphs# class CS161Vertex: def __init__(self, v): self.inNeighbors = [] self.outNeighbors = [] self.value = v # useful for DFS/BFS self.inTime = None self.outTime = None self.status = "unvisited" def hasOutNeighbor(self,v): if v in self.outNeighbors: return True return False def hasInNeighbor(self,v): if v in self.inNeighbors: return True return False def hasNeighbor(self,v): if v in self.inNeighbors or v in self.outNeighbors: return True return False def getOutNeighbors(self): return self.outNeighbors def getInNeighbors(self): return self.inNeighbors def addOutNeighbor(self,v): self.outNeighbors.append(v) def addInNeighbor(self,v): self.inNeighbors.append(v) def __str__(self): return str(self.value) # This is a directed graph class for use in CS161. # It can also be used as an undirected graph by adding edges in both directions. class CS161Graph: def __init__(self): self.vertices = [] def addVertex(self,n): self.vertices.append(n) # add a directed edge from CS161Node u to CS161Node v def addDiEdge(self,u,v): u.addOutNeighbor(v) v.addInNeighbor(u) # add edges in both directions between u and v def addBiEdge(self,u,v): self.addDiEdge(u,v) self.addDiEdge(v,u) # reverse the edge between u and v. Multiple edges are not supported. def reverseEdge(self,u,v): if u.hasOutNeighbor(v) and v.hasInNeighbor(u): if v.hasOutNeighbor(u) and u.hasInNeighbor(v): return self.addDiEdge(v,u) u.outNeighbors.remove(v) v.inNeighbors.remove(u) # get a list of all the directed edges # directed edges are a list of two vertices def getDirEdges(self): ret = [] for v in self.vertices: ret += [ [v, u] for u in v.outNeighbors ] return ret def __str__(self): ret = "CS161Graph with:\n" ret += "\t Vertices:\n\t" for v in self.vertices: ret += str(v) + "," ret += "\n" ret += "\t Edges:\n\t" for a,b in self.getDirEdges(): ret += "(" + str(a) + "," + str(b) + ") " ret += "\n" return ret stanford = CS161Vertex("Stanford") wiki = CS161Vertex("Wikipedia") nytimes = CS161Vertex("NYTimes") cal = CS161Vertex("Berkeley") puppies = CS161Vertex("Puppies") google = CS161Vertex("Google") G = CS161Graph() V = [ stanford, wiki, nytimes, cal, puppies, google ] for v in V: G.addVertex(v) E = [ (stanford, wiki), (stanford, puppies), (wiki, stanford), (wiki, nytimes), (nytimes, stanford), (cal, stanford), (cal, puppies), (wiki,puppies), (nytimes, puppies), (puppies, google), (google, puppies) ] for x, y in E: G.addDiEdge(x,y) print(G) # Now let's implement our SCC algorithm. def DFS_helper(w, currentTime, ordering, verbose): if verbose: print("Time", currentTime, ":\t entering", w) w.inTime = currentTime currentTime += 1 w.status = "inprogress" for v in w.getOutNeighbors(): if v.status == "unvisited": currentTime = DFS_helper(v, currentTime, ordering, verbose) currentTime += 1 w.outTime = currentTime w.status = "done" ordering.insert(0, w) if verbose: print("Time", currentTime, ":\t leaving", w) return currentTime # This is a version of DFS which outputs vertices in the order that DFS leaves them. def SCC(G, verbose=False): ordering = [] for v in G.vertices: v.status = "unvisited" v.inTime = None v.outTime = None currentTime = 0 for w in G.vertices: if w.status == "unvisited": currentTime = DFS_helper( w, currentTime, ordering, verbose ) currentTime += 1 #now reverse all edges E = G.getDirEdges() for x, y in E: G.reverseEdge(x, y) # and do it (second DFS) again, but this tim in the order "ordering" SCCs = [] for v in ordering: v.status = "unvisited" v.inTime = None v.outTime = None currentTime = 0 for w in ordering: visited = [] if w.status == "unvisited": currentTime = DFS_helper(w, currentTime, visited, verbose) SCCs.append(visited[:]) return SCCs SCCs = SCC(G, False) for X in SCCs: print ([str(x) for x in X])
# Generated by Django 2.0.2 on 2018-03-24 13:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tafaha', '0007_answer_picture'), ] operations = [ migrations.RemoveField( model_name='answer', name='text', ), migrations.AddField( model_name='test', name='height', field=models.IntegerField(default=400), ), migrations.AddField( model_name='test', name='width', field=models.IntegerField(default=800), ), migrations.AddField( model_name='test', name='x', field=models.IntegerField(default=100), ), migrations.AddField( model_name='test', name='y', field=models.IntegerField(default=100), ), ]
# Programa que imprime a quinta parte de um numero num = float(input('Entre com um numero: ')) quinta_parte = num / 5 print(f'A quinta parte de {num} é: {quinta_parte}')
""" Representation of the agenda summary given to attendees of a meeting """ from pathlib import Path from typing import ( Optional, Union, ) import docx # type: ignore from docx.oxml import OxmlElement # type: ignore from docx.oxml.ns import qn # type: ignore import docx.table # type: ignore from .meeting import Agenda, AgendaItem, AgendaHeading from .locator import FileLocator class AgendaListing: def __init__( self, meeting: Agenda, template: Union[str, Path], locator: Optional[FileLocator] = None, ) -> None: self.meeting = meeting self.template = template self.locator = locator or Path self.star = "🟊 " self.star_font = "Symbola" self.agenda_heading_style = "AgendaHeading" self.agenda_item_style = "AgendaItem" self.agenda_heading_bg_color = "DDDDDD" self.document: docx.Document = None @staticmethod def _set_cell_bg_color( cell: docx.table._Cell, # pylint: disable=protected-access color: str, ) -> docx.table._Cell: # pylint: disable=protected-access """ set background shading for Header Rows """ tc = cell._tc # pylint: disable=protected-access props = tc.get_or_add_tcPr() shading = OxmlElement("w:shd") shading.set(qn("w:fill"), color) props.append(shading) return cell def load_template(self) -> None: resolved_filename = self.locator(self.template) self.document = docx.Document(resolved_filename) def find_table(self) -> docx.table.Table: return self.document.tables[0] def _fill_header( self, item: AgendaHeading, row: docx.table._Row, # pylint: disable=protected-access ) -> None: cells = row.cells # merge the cells together merged_cell = cells[1].merge(cells[2]) merged_cell = merged_cell.merge(cells[3]) # add title merged_cell.text = item.title # add styling merged_cell.paragraphs[0].style = self.agenda_heading_style cells[0].paragraphs[0].style = self.agenda_heading_style self._set_cell_bg_color(merged_cell, self.agenda_heading_bg_color) self._set_cell_bg_color(cells[0], self.agenda_heading_bg_color) def _fill_item( self, item: AgendaItem, row: docx.table._Row # pylint: disable=protected-access ) -> None: cells = row.cells # add details if item.starred: cells[1].text = "" p = cells[1].paragraphs[0] r = p.add_run(self.star) r.font.name = "Symbola" p.add_run(item.title) else: cells[1].text = item.title if item.action: cells[2].text = item.action if item.who: cells[3].text = item.who # add styling for c in cells: c.paragraphs[0].style = self.agenda_item_style def fill_table(self, table: docx.table.Table) -> None: for item in self.meeting.items: itemnum = str(item.num) print(" Adding %s" % itemnum) if isinstance(item, AgendaHeading): row = table.add_row() row.cells[0].text = itemnum self._fill_header(item, row) elif isinstance(item, AgendaItem): row = table.add_row() row.cells[0].text = itemnum self._fill_item(item, row) def build(self) -> None: self.load_template() table = self.find_table() self.fill_table(table) def save(self, filename: Union[str, Path]) -> None: resolved_filename = self.locator(filename) self.document.save(resolved_filename)
import pytest from pytest_dl import dataset @pytest.fixture(scope="module") def data(): yield dataset.MyMNIST()
#!/usr/bin/python ## -*- coding: utf-8 -*- # import json #import db_conf import cgi import sys import sqlite3 # Open database (will be created if not exists) conn = sqlite3.connect('sqlite/hemap_core3.db') conn.text_factory = str c = conn.cursor() qform = cgi.FieldStorage() inparam = qform.getvalue('inparameter') #inparam = "GSM1226121, GSM1254268, GSM1254280" #inparam = 'AML' incol = qform.getvalue('column') #incol = 'lineage_tumor_cat' #incol = 'gsm' #param:value #advancedparameter: #advancedcolumn:lineage_tumor_cat #advancedop: AND andor = qform.getvalue('advancedop') adv_incol = "" if (qform.getvalue('advancedcolumn') != None): adv_incol = qform.getvalue('advancedcolumn') adv_inparam = "" if (qform.getvalue('advancedparameter') != None): adv_inparam = qform.getvalue('advancedparameter') outcols = qform.getvalue('outc') #outcols = "gsm, gse, main_cat, lineage_tumor_cat, subtype_cat, spec_cat,cytogenetics, clinical, submaps, sample_source, sample_isolation ,alterations,tumor_type,tumor_purity,patient,gender, race, age, phenotype, survival_status, survival_time, ef_pf_status, ef_survival, gsp, invivo_treatment, invivo_treatment_time, cultured, exvivo_treatment, exvivo_treatment_time" #gsm, gse, main_cat, lineage_tumor_cat, subtype_cat, spec_cat,cytogenetics, clinical, submaps, patient, sample_source, sample_isolation, notes" """ gsm text, gse text, main_cat text, lineage_tumor_cat text, subtype_cat text, spec_cat text, cytogenetics text, clinical text, submaps text, patient text, sample_source text, sample_isolation text, notes text f = open("hema/AnnotationTable.txt", "r") """ wildc = "%" if (incol == "cluster"): wildc = "" select = "select " + outcols + " from hema_annotationf where " + incol + " like '" + wildc + inparam + wildc + "' order by gsm asc" if (adv_inparam != "" and adv_incol != ""): select = "select " + outcols + " from hema_annotationf where " + incol + " like '" + wildc + inparam + wildc + "'" + andor + adv_incol + " like '" + wildc + adv_inparam + wildc + "' order by gsm asc" #print select if (incol == "gsms"): ingsm = "" for p in inparam.split(" "): p = p.replace(" ", "") ingsm = ingsm + "'" + p + "'," ingsm = ingsm[:-1] select = "select " + outcols + " from hema_annotationf where gsm in (" + ingsm + ") or altgse in (" + ingsm + ") order by gsm asc" #during population, altgsm and altgse were swapped, for now we will swap the search to save data repopulation if (incol == "gsm"): select = "select " + outcols + " from hema_annotationf where gsm = '" + inparam + "' or altgse like '%" + inparam + "%' order by gsm asc" if (incol == "gse"): select = "select " + outcols + " from hema_annotationf where gse like '%" + inparam + "%' or altgsm like '%" + inparam + "%' order by gsm asc" logf = open("./_sql.log", "a") c.execute(select) logf.write("\n" + select + "\n") logf.close() rows = c.fetchall() print "Content-type: text/html;charset=utf-8\r\n" pa = {} pa['aaData'] = [] for row in rows: pi = [] for r in range(len(row)): col = str(row[r]) col = unicode(col, errors='ignore') if (col == None): col = "" #col = col.replace("'", "") if (r == 0): #"<a href=javascript:updateExperiment('" + str(row[r]) + "')>edit</a>") pi.append("<a href='javascript:highlightGSM(\"" + col + "\")'>" + col + "</a>") #pi.append(col) else: pi.append(col) pa['aaData'].append(pi) c.close() print json.dumps(pa)
from collections import Counter def popular_words(text: str, words: list) -> dict: c = dict(Counter(text.split())) c = {k.lower(): v for k, v in c.items()} o = {} for i in words: if i in c.keys(): o[i] = c.get(i) else: o[i] = 0 return o if __name__ == '__main__': # These "asserts" are used for self-checking and not for an auto-testing print(popular_words(''' When I was One I had just begun When I was Two I was nearly new ''', ['i', 'was', 'three', 'near']), { 'i': 4, 'was': 3, 'three': 0, 'near': 0 })
import time # time.time() # def prime_check_v1(x): # check = 1 # if x == 2 and x == 3: # check = 1 # elif x == 1: # check = 0 # else: # for i in range(2, x - 1):# think carefully on this line # # Explain a little bit more here........ # check *= x % i# Do we need this line? # if check == 0: # answer = 0 # else: # answer = 1 # return answer # 0.031998634338378906 # def prime_check_v2(x): # check = 1 #Tempted to make check answer to save one if statement but would result in fully running for loop in some cases # x = int(x) # if x < 2: #0,1 not primes and negative numbers not included in what our program was supposed to do # answer = 0 # elif x == 2 and x == 3: #2 and 3 need exceptions in our program # answer = 1 # elif x % 2 == 0: #Even numbers not prime so unnecessary to use for loop and waste processing power # answer = 0 # else: # for i in range(2, x - 1): # check *= x % i # if check == 0: # answer = 0 # else: # answer = 1 # return answer def prime_check_v3(x): answer = None check = 1 x = int(x) if x < 2: #0,1 not primes and negative numbers not included in what our program was supposed to do return 0 elif x == 2 and x == 3: #2 and 3 need exceptions in our program return 1 else: for i in range(2, int(x ** 0.5)): check *= x % i if check == 0: return 0 return 1 print(prime_check_v3(79)) # def primechecklist(): # x=1 # primes = [] # while 104743 not in primes: # if prime_check_v3(x)==1: # primes.append(x) # x += 1 # return len(primes) # print(len(primes)) # primechecklist() # Run v1 and see run time # tStart = time.time() # for i in range(1000): # prime_check_v1(97) # tEnd = time.time() # print('Run time v1 = ',tEnd - tStart) # # tStart = time.time() # for i in range(1000): # prime_check_v2(97) # tEnd = time.time() # print('Run time v2 = ',tEnd - tStart) # # tStart = time.time() # for i in range(1000): # prime_check_v3(97) # tEnd = time.time() # print('Run time v3 = ',tEnd - tStart)
import logging from typing import Dict from sonosco.serialization import serializable from ..abstract_callback import AbstractCallback, ModelTrainer LOGGER = logging.getLogger(__name__) @serializable class DisableSoftWindowAttention(AbstractCallback): """ Disable soft window pretraining after the stecified disable epoch. Args: disable_epoch: epoch after which soft-window pretraining should be disabled """ disable_epoch: int = 3 def __call__(self, epoch: int, step: int, performance_measures: Dict, context: ModelTrainer, validation: bool = False) -> None: """ Disable soft window if epoch greater than disable epoch. Args: epoch: epoch step step: step inside of the epoch performance_measures: performance measures dictionary context: model trainer validation: should validation dataloader be used for comparison """ if epoch > self.disable_epoch: context.model.decoder.soft_window_enabled = False
import time from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary('/Applications/Firefox.app/Contents/MacOS/firefox-bin') from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox(firefox_binary=binary) # driver.find_element_by_id("lst-ib").send_keys("hello") browser = webdriver.Firefox() browser.get('https://www.instagram.com/accounts/login/') username = browser.find_element_by_id('f198f9965a18b7a') driver.find_element_by_name("username").click() username.send_keys("lilmethboner") password = browser.find_element_by_name('password') password.send_keys(Qu3st10n) password.send_keys(Keys.RETURN) # hit return after you enter search text time.sleep(10) # sleep for 5 seconds so you can see the results browser.quit() # time.sleep(10) driver.quit()
from abc import ABC, abstractmethod class AbstractBird(ABC): def __init__(self, name): self.name = name super().__init__() @abstractmethod def can_fly(self): pass class Penguin1 (AbstractBird): def __init__(self): super().__init__("Penguin") class Penguin2 (AbstractBird): def __init__(self): super().__init__("Penguin") def can_fly(self): return False try: penguin = Penguin1() except: print("TypeError: Can't instantiate abstract class Penguin1 with abstract methods can_fly") penguin = Penguin2() print(penguin.can_fly())
from django.contrib import admin from .models import * class BranchInline (admin.StackedInline): model = Branch extra = 0 class ContactInline (admin.StackedInline): model = Contact extra = 0 class CoursesAdmin (admin.ModelAdmin): inlines = [BranchInline, ContactInline] admin.site.register(Category) admin.site.register(Course, CoursesAdmin)
from django.contrib import admin from . import models admin.site.register(models.StudentDay) admin.site.register(models.TeacherDay) admin.site.register(models.WorkerDay) admin.site.register(models.StudentAttendance) admin.site.register(models.TeacherAttendance) admin.site.register(models.WorkerAttendance)
# Generated by Django 2.2.5 on 2020-05-20 17:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('listings', '0013_auto_20200520_0612'), ] operations = [ migrations.AlterField( model_name='comment', name='reply_id', field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='replies', to='listings.Comment'), ), ]
import os import unittest from pathlib import Path from click.testing import CliRunner from prettydata import main class TestMain(unittest.TestCase): """Test class for testing the main module Arguments: unittest {[type]} -- [description] """ @classmethod def setUpClass(cls): print("*" * 80 + "\nStart to test [main] module\n" + "*" * 80) def setUp(self): self.runner = CliRunner() def test_main_no_command(self): """Testing for the main function with no argument """ result = self.runner.invoke(main.cmd, []) assert result.exit_code == 0 assert "First layer sub-command group" in result.output def test_main_non_defined_command(self): """Testing for the main function with non-defined command at first layer """ result = self.runner.invoke(main.cmd, ["nondefined"]) assert result.exit_code == 2 assert "No such command" in result.output def test_main_analyze_command(self): """Testing for the main function with analyze comman """ p = Path(os.getcwd() + "/tests/resources/for_analyze.csv") result = self.runner.invoke(main.analyze, [str(p)]) assert result.exit_code == 0 assert type(eval(result.output)) == dict
''' Source: https://codegolf.stackexchange.com/questions/41523/sudoku-compression ''' import itertools def print_sudoku(m): for k in m: print((" ".join(str(i) for i in k))) def potential_squares(u1, u2, u3, l1, l2, l3): """ returns generator of possible squares given lists of digits above and below u1 u2 u3 | | | l1 -- a b c l2 -- d e f l3 -- g h i if no items exist the empty list must be given """ for a, b, c, d, e, f, g, h, i in itertools.permutations(list(range(1, 10))): if ( a not in u1 and a not in l1 and b not in u2 and b not in l1 and c not in u3 and c not in l1 and d not in u1 and d not in l2 and e not in u2 and e not in l2 and f not in u3 and f not in l2 and g not in u1 and g not in l3 and h not in u2 and h not in l3 and i not in u3 and i not in l3 ): yield (a, b, c, d, e, f, g, h, i) def board_to_squares(board): """ finds 9 squares in a 9x9 board in this order: 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 4 4 4 5 5 5 6 6 6 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9 7 7 7 8 8 8 9 9 9 7 7 7 8 8 8 9 9 9 returns tuple for each square as follows: a b c d e f --> (a,b,c,d,e,f,g,h,i) g h i """ labels = [ [3 * i + 1] * 3 + [3 * i + 2] * 3 + [3 * i + 3] * 3 for i in [0, 0, 0, 1, 1, 1, 2, 2, 2] ] labelled_board = list(zip(sum(board, []), sum(labels, []))) return [tuple(a for a, b in labelled_board if b == sq) for sq in range(1, 10)] def squares_to_board(squares): """ inverse of above """ board = [ [i / 3 * 27 + i % 3 * 3 + j / 3 * 9 + j % 3 for j in range(9)] for i in range(9) ] flattened = sum([list(square) for square in squares], []) for i in range(9): for j in range(9): board[i][j] = flattened[board[i][j]] return board def sum_rows(*squares): """ takes tuples for squares and returns lists corresponding to the rows: l1 -- a b c j k l l2 -- d e f m n o ... l3 -- g h i p q r """ l1 = [] l2 = [] l3 = [] if len(squares): for a, b, c, d, e, f, g, h, i in squares: l1 += [a, b, c] l2 += [d, e, f] l3 += [g, h, i] return l1, l2, l3 return [], [], [] def sum_cols(*squares): """ takes tuples for squares and returns lists corresponding to the cols: u1 u2 u3 | | | a b c d e f g h i j k l m n o p q r ... """ u1 = [] u2 = [] u3 = [] if len(squares): for a, b, c, d, e, f, g, h, i in squares: u1 += [a, d, g] u2 += [b, e, h] u3 += [c, f, i] return u1, u2, u3 return [], [], [] def base95(A): if type(A) is int or type(A) is int: s = "" while A > 0: s += chr(32 + A % 95) A /= 95 return s if type(A) is str: return sum((ord(c) - 32) * (95 ** i) for i, c in enumerate(A)) """ dependencies: every square as labeled 1 2 3 4 5 6 7 8 9 is dependent on those above and to the left in a dictionary, it is: square: ([above],[left]) """ dependencies = { 1: ([], []), 2: ([], [1]), 3: ([], [1, 2]), 4: ([1], []), 5: ([2], [4]), 6: ([3], [4, 5]), 7: ([1, 4], []), 8: ([2, 5], [7]), 9: ([3, 6], [7, 8]), } """ max possible options for a given element 9 8 7 ? ? ? 3 2 1 6 5 4 (12096) 3 2 1 3 2 1 ? ? ? 3 2 1 ? ? ? ? ? ? 2 2 1 (12096) (420) 2 1 1 (limits for squares 2,4 determined experimentally) ? ? ? ? ? ? 1 1 1 (limit for square 5 is a pessimistic guess, might be wrong) 3 3 3 2 2 1 1 1 1 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 """ possibilities = [362880, 12096, 216, 12096, 420, 8, 216, 8, 1] def factorize_sudoku(board): squares = board_to_squares(board) factors = [] for label in range(1, 10): above, left = dependencies[label] u1, u2, u3 = sum_cols(*[sq for i, sq in enumerate(squares) if i + 1 in above]) l1, l2, l3 = sum_rows(*[sq for i, sq in enumerate(squares) if i + 1 in left]) for i, k in enumerate(potential_squares(u1, u2, u3, l1, l2, l3)): if k == squares[label - 1]: factors.append(i) continue return factors def unfactorize_sudoku(factors): squares = [] for label in range(1, 10): factor = factors[label - 1] above, left = dependencies[label] u1, u2, u3 = sum_cols(*[sq for i, sq in enumerate(squares) if i + 1 in above]) l1, l2, l3 = sum_rows(*[sq for i, sq in enumerate(squares) if i + 1 in left]) for i, k in enumerate(potential_squares(u1, u2, u3, l1, l2, l3)): if i == factor: squares.append(k) continue return squares def test_on_inputs(inputs): strings = [] for sudoku in inputs: board = [[int(x) for x in line.split()] for line in sudoku.strip().split("\n")] print_sudoku(board) factors = factorize_sudoku(board) i = 0 for item, modulus in zip(factors, possibilities): i *= modulus i += item print("integral representation:", i) print("bits of entropy:", i.bit_length()) print("") def get_compression_metrics(sudoku): """' input is a sudoku in represent_sudoku form """ # TODO: add compression ratio board = [[int(x) for x in line.split()] for line in sudoku.strip().split("\n")] factors = factorize_sudoku(board) i = 0 for item, modulus in zip(factors, possibilities): i *= modulus i += item entropy = i.bit_length() return entropy if __name__ == "__main__": # inputs = """ # 6 4 9 1 2 3 5 8 7 # 8 1 3 5 9 7 4 6 2 # 2 7 5 6 8 4 1 9 3 # 1 3 2 8 7 5 6 4 9 # 5 9 8 2 4 6 3 7 1 # 7 6 4 9 3 1 2 5 8 # 9 5 1 3 6 8 7 2 4 # 4 2 6 7 1 9 8 3 5 # 3 8 7 4 5 2 9 1 6 # 7 9 4 5 8 2 1 3 6 # 2 6 8 9 3 1 7 4 5 # 3 1 5 4 7 6 9 8 2 # 6 8 9 7 1 5 3 2 4 # 4 3 2 8 6 9 5 7 1 # 1 5 7 2 4 3 8 6 9 # 8 2 1 6 5 7 4 9 3 # 9 4 3 1 2 8 6 5 7 # 5 7 6 3 9 4 2 1 8 # """.strip().split('\n\n') test_on_inputs(inputs) sudoku = """ 7 9 4 5 8 2 1 3 6 2 6 8 9 3 1 7 4 5 3 1 5 4 7 6 9 8 2 6 8 9 7 1 5 3 2 4 4 3 2 8 6 9 5 7 1 1 5 7 2 4 3 8 6 9 8 2 1 6 5 7 4 9 3 9 4 3 1 2 8 6 5 7 5 7 6 3 9 4 2 1 8 """ print(get_compression_metrics(sudoku))
import urllib2 from urllib2 import urlopen import re from bs4 import BeautifulSoup from urlparse import urljoin import csv import httplib import sys,getopt class walk: starturl= 'http://www.globalscape.com/' visited = [] checked = [] errors = [] redirects = [] errorfile='errors.csv' visitedfile='visited.csv' def start(self,starturl): self.starturl=starturl self.perform(self.starturl,'/') print self.errors def perform(self, pageurl,parent): links = self.extractLinks(pageurl,urljoin(self.starturl,parent)) if links: for link in links: # if the link is on this same site and we haven't visisted it yet, then drill into iti if link.startswith(self.starturl): if not self.haveVisited(link): print "visiting " + link + " from " + pageurl self.perform(link,pageurl) def checkForErrors(self,url,parent): err = None try: if not self.haveVisited(url) and not url in self.redirects: req = urllib2.Request(url,headers={"User-Agent":"Magic Browser"}) page = urlopen(req) # handle redirect if urljoin(self.starturl,page.url) != url: self.redirects.append(url) req = urllib2.Request(url,headers={"User-Agent":"Magic Browser"}) err = ('Redirect Detected from: ', url, page.url) page = urlopen(req) url = urljoin(self.starturl,page.url) if not self.haveVisited(url): self.visited.append(url) #print 'loaded ' + url with open(self.visitedfile,'a+') as f: writer = csv.writer(f,delimiter=',') writer.writerow((parent,url)) return page else: return None except urllib2.HTTPError, e: err = ('HTTPError = ' + str(e.code),parent,url) except urllib2.URLError, e: err = ('URLError = ' + str(e.reason),parent,url) except httplib.HTTPException, e: err = ('HTTPError (no code)', parent, url) except Exception: err = ('Unknown error', parent, url) self.printToError(err) def printToError(self,err): print err with open(self.errorfile, 'a+') as f: writer = csv.writer(f,delimiter=',') writer.writerow(err) def haveVisited(self,url): if url in self.visited: return True else: return False def extractLinks(self,page,parent): #print 'before everything' links = [] try: #print 'before check 4 errors' p = self.checkForErrors(urljoin(self.starturl,page),parent) if p: #print ' checkforerrors done ' content = BeautifulSoup(p) for link in content.find_all('a'): linkhref = link.get('href') if linkhref: #print ' considering ' + str(linkhref) links.append(urljoin(self.starturl,linkhref)) return links else: return None except Exception ,e: print 'error on ' + page + " " + str(e) def main(argv): starturl = '' try: opts, args = getopt.getopt(argv,"hs:",["starturl="]) except getopt.GetoptError: print 'walk.py -s <starturl>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'walk.py -s <starturl>' sys.exit() elif opt in ("-s", "--starturl"): starturl = arg x = walk() x.start(starturl) if __name__ == '__main__': main(sys.argv[1:])
import os import numpy as np from dm_control.suite import common from dm_control.utils import io as resources import xmltodict _SUITE_DIR = os.path.dirname(os.path.dirname(__file__)) _FILENAMES = [ "./common/materials.xml", "./common/skybox.xml", "./common/visual.xml", ] def get_model_and_assets_from_setting_kwargs(model_fname, setting_kwargs=None): """"Returns a tuple containing the model XML string and a dict of assets.""" assets = {filename: resources.GetResource(os.path.join(_SUITE_DIR, filename)) for filename in _FILENAMES} if setting_kwargs is None: return common.read_model(model_fname), assets # Convert XML to dicts model = xmltodict.parse(common.read_model(model_fname)) materials = xmltodict.parse(assets['./common/materials.xml']) skybox = xmltodict.parse(assets['./common/skybox.xml']) # Edit grid floor if 'grid_rgb1' in setting_kwargs: assert isinstance(setting_kwargs['grid_rgb1'], (list, tuple, np.ndarray)) assert materials['mujoco']['asset']['texture']['@name'] == 'grid' materials['mujoco']['asset']['texture']['@rgb1'] = \ f'{setting_kwargs["grid_rgb1"][0]} {setting_kwargs["grid_rgb1"][1]} {setting_kwargs["grid_rgb1"][2]}' if 'grid_rgb2' in setting_kwargs: assert isinstance(setting_kwargs['grid_rgb2'], (list, tuple, np.ndarray)) assert materials['mujoco']['asset']['texture']['@name'] == 'grid' materials['mujoco']['asset']['texture']['@rgb2'] = \ f'{setting_kwargs["grid_rgb2"][0]} {setting_kwargs["grid_rgb2"][1]} {setting_kwargs["grid_rgb2"][2]}' if 'grid_markrgb' in setting_kwargs: assert isinstance(setting_kwargs['grid_markrgb'], (list, tuple, np.ndarray)) assert materials['mujoco']['asset']['texture']['@name'] == 'grid' materials['mujoco']['asset']['texture']['@markrgb'] = \ f'{setting_kwargs["grid_markrgb"][0]} {setting_kwargs["grid_markrgb"][1]} {setting_kwargs["grid_markrgb"][2]}' if 'grid_texrepeat' in setting_kwargs: assert isinstance(setting_kwargs['grid_texrepeat'], (list, tuple, np.ndarray)) assert materials['mujoco']['asset']['texture']['@name'] == 'grid' materials['mujoco']['asset']['material'][0]['@texrepeat'] = \ f'{setting_kwargs["grid_texrepeat"][0]} {setting_kwargs["grid_texrepeat"][1]}' # Edit self if 'self_rgb' in setting_kwargs: assert isinstance(setting_kwargs['self_rgb'], (list, tuple, np.ndarray)) assert materials['mujoco']['asset']['material'][1]['@name'] == 'self' materials['mujoco']['asset']['material'][1]['@rgba'] = \ f'{setting_kwargs["self_rgb"][0]} {setting_kwargs["self_rgb"][1]} {setting_kwargs["self_rgb"][2]} 1' # Edit skybox if 'skybox_rgb' in setting_kwargs: assert isinstance(setting_kwargs['skybox_rgb'], (list, tuple, np.ndarray)) assert skybox['mujoco']['asset']['texture']['@name'] == 'skybox' skybox['mujoco']['asset']['texture']['@rgb1'] = \ f'{setting_kwargs["skybox_rgb"][0]} {setting_kwargs["skybox_rgb"][1]} {setting_kwargs["skybox_rgb"][2]}' if 'skybox_rgb2' in setting_kwargs: assert isinstance(setting_kwargs['skybox_rgb2'], (list, tuple, np.ndarray)) assert skybox['mujoco']['asset']['texture']['@name'] == 'skybox' skybox['mujoco']['asset']['texture']['@rgb2'] = \ f'{setting_kwargs["skybox_rgb2"][0]} {setting_kwargs["skybox_rgb2"][1]} {setting_kwargs["skybox_rgb2"][2]}' if 'skybox_markrgb' in setting_kwargs: assert isinstance(setting_kwargs['skybox_markrgb'], (list, tuple, np.ndarray)) assert skybox['mujoco']['asset']['texture']['@name'] == 'skybox' skybox['mujoco']['asset']['texture']['@markrgb'] = \ f'{setting_kwargs["skybox_markrgb"][0]} {setting_kwargs["skybox_markrgb"][1]} {setting_kwargs["skybox_markrgb"][2]}' # Convert back to XML model_xml = xmltodict.unparse(model) assets['./common/materials.xml'] = xmltodict.unparse(materials) assets['./common/skybox.xml'] = xmltodict.unparse(skybox) return model_xml, assets
# coding: utf-8 class SearchError(Exception): pass
import spotipy import os import requests import json import pandas as pd from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail from flask import Flask, request, redirect, g, render_template from spotipy.oauth2 import SpotifyClientCredentials from dotenv import load_dotenv from urllib.parse import quote # test data playlist_group_name = "New Playlist" uris = ["spotify:track:0LtOwyZoSNZKJWHqjzADpW", "spotify:track:57RA3JGafJm5zRtKJiKPIm", "spotify:track:5RRWirYSE08FPKD6Mx4v0V", "spotify:track:4djIFfof5TpbSGRZUpsTXq"] load_dotenv() app = Flask(__name__) CLIENT_ID = os.getenv("CLIENT_ID", default="abc123") CLIENT_SECRET = os.getenv("CLIENT_SECRET", default="abc456") # Spotify URLS SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize" SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token" SPOTIFY_API_BASE_URL = "https://api.spotify.com" API_VERSION = "v1" SPOTIFY_API_URL = f"{SPOTIFY_API_BASE_URL}/{API_VERSION}" # Server-side Parameters CLIENT_SIDE_URL = "http://127.0.0.1" PORT = 8080 REDIRECT_URI = "http://127.0.0.1:8080/callback/q" SCOPE = "user-follow-read" STATE = "" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() auth_query_parameters = { "response_type": "code", "redirect_uri": REDIRECT_URI, "scope": SCOPE, "client_id": CLIENT_ID } @app.route("/") def index(): # Auth Step 1: Authorization url_args = "&".join(["{}={}".format(key, quote(val)) for key, val in auth_query_parameters.items()]) auth_url = f'{SPOTIFY_AUTH_URL}/?{url_args}' return redirect(auth_url) @app.route("/callback/q") def callback(): # Auth Step 4: Requests refresh and access tokens auth_token = request.args['code'] code_payload = { "grant_type": "authorization_code", "code": str(auth_token), "redirect_uri": REDIRECT_URI, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, } post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload) # Auth Step 5: Tokens are Returned to Application response_data = json.loads(post_request.text) access_token = response_data["access_token"] refresh_token = response_data["refresh_token"] token_type = response_data["token_type"] expires_in = response_data["expires_in"] # Auth Step 6: Use the access token to access Spotify API authorization_header = {"Authorization": "Bearer {}".format(access_token)} # Get profile data user_profile_api_endpoint = f"{SPOTIFY_API_URL}/me" profile_response = requests.get( user_profile_api_endpoint, headers=authorization_header) profile_data = json.loads(profile_response.text) # get followed users friends = ["stellapug1127", "justlivwithit", "sfrost5772"] count = len(friends) user_followers = f"{SPOTIFY_API_URL}/me/following/contains?type=user&ids=" for x in friends: if friends.index(x) == count - 1: user_followers = user_followers + x else: user_followers = user_followers + f"{x}%2C" follower_response = requests.get(user_followers, headers=authorization_header) user_data = json.loads(follower_response.text) return str(user_data) if __name__ == "__main__": app.run(debug=True, port=PORT)
import numpy as np from math import sin, cos def rotation_x(a): R = [[1, 0, 0], [0, cos(a), -1 * sin(a)], [0, sin(a), cos(a)]] return np.mat(R) def rotation_y(a): R = [[cos(a), 0, -1 * sin(a)], [0, 1, 0], [sin(a), 0, cos(a)]] return np.mat(R) def rotation_z(a): R = [[cos(a), sin(a), 0], [-1 * sin(a), cos(a), 0], [0, 0, 1]] return np.mat(R) def rotation_xyz(a): pass
from ED6ScenarioHelper import * def main(): # 蔡斯 CreateScenaFile( FileName = 'T3116 ._SN', MapName = 'Zeiss', Location = 'T3116.x', MapIndex = 1, MapDefaultBGM = "ed60013", Flags = 0, EntryFunctionIndex = 0xFFFF, Reserved = 0, IncludedScenario = [ '', '', '', '', '', '', '', '' ], ) BuildStringList( '@FileName', # 8 '拉赛尔博士', # 9 '提妲', # 10 '玛多克工房长', # 11 '加鲁诺', # 12 '普罗梅笛', # 13 '安东尼', # 14 '导力器', # 15 ) DeclEntryPoint( Unknown_00 = 0, Unknown_04 = 0, Unknown_08 = 6000, Unknown_0C = 4, Unknown_0E = 0, Unknown_10 = 0, Unknown_14 = 9500, Unknown_18 = -10000, Unknown_1C = 0, Unknown_20 = 0, Unknown_24 = 0, Unknown_28 = 2800, Unknown_2C = 262, Unknown_30 = 45, Unknown_32 = 0, Unknown_34 = 360, Unknown_36 = 0, Unknown_38 = 0, Unknown_3A = 0, InitScenaIndex = 0, InitFunctionIndex = 0, EntryScenaIndex = 0, EntryFunctionIndex = 1, ) AddCharChip( 'ED6_DT07/CH02020 ._CH', # 00 'ED6_DT07/CH00060 ._CH', # 01 'ED6_DT07/CH02620 ._CH', # 02 'ED6_DT07/CH01190 ._CH', # 03 'ED6_DT07/CH01100 ._CH', # 04 'ED6_DT07/CH01700 ._CH', # 05 'ED6_DT06/CH20021 ._CH', # 06 ) AddCharChipPat( 'ED6_DT07/CH02020P._CP', # 00 'ED6_DT07/CH00060P._CP', # 01 'ED6_DT07/CH02620P._CP', # 02 'ED6_DT07/CH01190P._CP', # 03 'ED6_DT07/CH01100P._CP', # 04 'ED6_DT07/CH01700P._CP', # 05 'ED6_DT06/CH20021P._CP', # 06 ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 0, ChipIndex = 0x0, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 8, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 1, ChipIndex = 0x1, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 9, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 2, ChipIndex = 0x2, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 7, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 3, ChipIndex = 0x3, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 6, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 4, ChipIndex = 0x4, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 5, ) DeclNpc( X = 0, Z = 0, Y = 0, Direction = 180, Unknown2 = 0, Unknown3 = 5, ChipIndex = 0x5, NpcIndex = 0x181, InitFunctionIndex = 0, InitScenaIndex = 2, TalkFunctionIndex = 0, TalkScenaIndex = 4, ) DeclNpc( X = 20, Z = 700, Y = 39430, Direction = 0, Unknown2 = 0, Unknown3 = 917510, ChipIndex = 0x6, NpcIndex = 0x1E6, InitFunctionIndex = -1, InitScenaIndex = -1, TalkFunctionIndex = -1, TalkScenaIndex = -1, ) ScpFunction( "Function_0_1C2", # 00, 0 "Function_1_3E3", # 01, 1 "Function_2_497", # 02, 2 "Function_3_4AD", # 03, 3 "Function_4_4D1", # 04, 4 "Function_5_4F1", # 05, 5 "Function_6_633", # 06, 6 "Function_7_188E", # 07, 7 "Function_8_1974", # 08, 8 "Function_9_1A47", # 09, 9 "Function_10_1B10", # 0A, 10 "Function_11_2E1E", # 0B, 11 "Function_12_41CA", # 0C, 12 "Function_13_4218", # 0D, 13 "Function_14_4243", # 0E, 14 "Function_15_426E", # 0F, 15 "Function_16_42AD", # 10, 16 "Function_17_4BD0", # 11, 17 ) def Function_0_1C2(): pass label("Function_0_1C2") Switch( (scpexpr(EXPR_PUSH_VALUE_INDEX, 0x0), scpexpr(EXPR_END)), (100, "loc_1CE"), (SWITCH_DEFAULT, "loc_210"), ) label("loc_1CE") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 1)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_1E1") OP_A2(0x513) Event(0, 10) label("loc_1E1") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 1)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 0)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_1FA") SetMapFlags(0x10000000) Event(0, 11) label("loc_1FA") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 5)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_20D") OP_A2(0x531) Event(0, 16) label("loc_20D") Jump("loc_210") label("loc_210") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_230") ClearChrFlags(0xB, 0x80) SetChrPos(0xB, -4500, 0, 6620, 99) Jump("loc_3E2") label("loc_230") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_250") ClearChrFlags(0xB, 0x80) SetChrPos(0xB, -4500, 0, 6620, 99) Jump("loc_3E2") label("loc_250") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_270") ClearChrFlags(0xB, 0x80) SetChrPos(0xB, -4500, 0, 6620, 99) Jump("loc_3E2") label("loc_270") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAA, 0)), scpexpr(EXPR_END)), "loc_2A6") ClearChrFlags(0xB, 0x80) SetChrPos(0xB, -4500, 0, 6620, 99) ClearChrFlags(0xC, 0x80) SetChrPos(0xC, -90, 0, 9830, 355) Jump("loc_3E2") label("loc_2A6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 6)), scpexpr(EXPR_END)), "loc_2CD") ClearChrFlags(0xD, 0x80) SetChrPos(0xD, 670, 0, 8480, 6) OP_43(0xD, 0x0, 0x0, 0x3) Jump("loc_3E2") label("loc_2CD") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 0)), scpexpr(EXPR_END)), "loc_2D7") Jump("loc_3E2") label("loc_2D7") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_332") SetChrPos(0xE, 40, 800, 11550, 0) ClearChrFlags(0xE, 0x80) ClearChrFlags(0x8, 0x80) OP_43(0x8, 0x0, 0x0, 0x2) SetChrPos(0x8, 140, 0, 12690, 175) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_32F") ClearChrFlags(0xA, 0x80) SetChrPos(0xA, -130, 0, 10450, 0) label("loc_32F") Jump("loc_3E2") label("loc_332") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 3)), scpexpr(EXPR_END)), "loc_37E") ClearChrFlags(0x8, 0x80) ClearChrFlags(0x9, 0x80) SetChrPos(0x9, -100, 0, 12700, 180) SetChrPos(0x8, -2310, 0, 14200, 0) SetChrPos(0xE, 40, 800, 11550, 0) ClearChrFlags(0xE, 0x80) Jump("loc_3E2") label("loc_37E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 1)), scpexpr(EXPR_END)), "loc_3A5") ClearChrFlags(0x8, 0x80) OP_43(0x8, 0x0, 0x0, 0x2) SetChrPos(0x8, 140, 0, 12690, 175) Jump("loc_3E2") label("loc_3A5") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA1, 6)), scpexpr(EXPR_END)), "loc_3C5") ClearChrFlags(0xB, 0x80) SetChrPos(0xB, -4500, 0, 6620, 99) Jump("loc_3E2") label("loc_3C5") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_3E2") ClearChrFlags(0xB, 0x80) SetChrPos(0xB, -4500, 0, 6620, 99) label("loc_3E2") Return() # Function_0_1C2 end def Function_1_3E3(): pass label("Function_1_3E3") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA7, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_3FB") OP_4F(0x1, (scpexpr(EXPR_PUSH_LONG, 0x54), scpexpr(EXPR_STUB), scpexpr(EXPR_END))) Jump("loc_428") label("loc_3FB") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 6)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_413") OP_4F(0x1, (scpexpr(EXPR_PUSH_LONG, 0x52), scpexpr(EXPR_STUB), scpexpr(EXPR_END))) Jump("loc_428") label("loc_413") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 4)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_428") OP_4F(0x1, (scpexpr(EXPR_PUSH_LONG, 0x51), scpexpr(EXPR_STUB), scpexpr(EXPR_END))) label("loc_428") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA5, 4)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 6)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_48A") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_48A") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA9, 2)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_48A") LoadEffect(0x1, "map\\\\mpfog.eff") PlayEffect(0x1, 0x1, 0xFF, 0, 0, 0, 0, 0, 0, 1000, 1000, 1000, 0xFF, 0, 0, 0, 0) label("loc_48A") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_496") OP_72(0x0, 0x4) label("loc_496") Return() # Function_1_3E3 end def Function_2_497(): pass label("Function_2_497") Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_4AC") OP_99(0xFE, 0x0, 0x7, 0x5DC) Jump("Function_2_497") label("loc_4AC") Return() # Function_2_497 end def Function_3_4AD(): pass label("Function_3_4AD") Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_4D0") OP_8D(0xFE, -1710, 9770, 3200, 6310, 3000) Jump("Function_3_4AD") label("loc_4D0") Return() # Function_3_4AD end def Function_4_4D1(): pass label("Function_4_4D1") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA6, 6)), scpexpr(EXPR_END)), "loc_4ED") OP_22(0x192, 0x0, 0x64) ChrTalk( 0xFE, "喵~……\x02", ) CloseMessageWindow() label("loc_4ED") TalkEnd(0xFE) Return() # Function_4_4D1 end def Function_5_4F1(): pass label("Function_5_4F1") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAA, 0)), scpexpr(EXPR_END)), "loc_62F") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_END)), "loc_59D") ChrTalk( 0xFE, ( "拉赛尔博士\x01", "好像已经回去了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "我本来还想请他\x01", "给我们多提一些建议的,\x01", "这次还是算了吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "只能以后有机会再说了。\x02", ) CloseMessageWindow() Jump("loc_62F") label("loc_59D") OP_A2(0x1) ChrTalk( 0xFE, ( "哦?\x01", "拉赛尔博士好像已经回去了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这次这么早就\x01", "结束了研究工作……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "哎呀~\x01", "真的是难得一见呢。\x02", ) ) CloseMessageWindow() label("loc_62F") TalkEnd(0xFE) Return() # Function_5_4F1 end def Function_6_633(): pass label("Function_6_633") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xC0, 1)), scpexpr(EXPR_END)), "loc_7B6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_6BD") ChrTalk( 0xFE, ( "说起来,\x01", "拉赛尔博士到底去了哪里呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "我倒是希望他能够\x01", "好好地收拾一下试验用具。\x02", ) ) CloseMessageWindow() Jump("loc_7B3") label("loc_6BD") OP_A2(0x0) ChrTalk( 0xFE, ( "现在我正在重新\x01", "对导力枪进行设计……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不过还是有些不舍得\x01", "对已经成熟的设计\x01", "做大幅度的改动啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "呼……这下子\x01", "说不定会比从图纸开始\x01", "重新设计还要麻烦。\x02", ) ) CloseMessageWindow() label("loc_7B3") Jump("loc_188A") label("loc_7B6") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 5)), scpexpr(EXPR_END)), "loc_8C2") ChrTalk( 0xFE, ( "现在处于研究阶段的导力枪的\x01", "平衡性出了一些问题。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不过,如果能够做得更加易用,\x01", "说不定会成为十分畅销的商品。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "到底是注重性能,\x01", "还是注重易用性呢……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这个抉择太难了,\x01", "还是先考虑二者兼顾吧。\x02", ) ) CloseMessageWindow() Jump("loc_188A") label("loc_8C2") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAB, 1)), scpexpr(EXPR_END)), "loc_B49") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_A01") ChrTalk( 0xFE, ( "为了下一次的研究,\x01", "我已经开始整理相关资料了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这次应该会以易用性\x01", "作为追求的目标吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "其实老实说,\x01", "到底应该注重哪一方面的设计\x01", "连我自己也不是很清楚……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "正因如此,对我们技术人员来说,\x01", "这一难题才有挑战的价值。\x02", ) ) CloseMessageWindow() Jump("loc_B46") label("loc_A01") OP_A2(0x0) ChrTalk( 0xFE, "哟,早上好。\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "从昨天开始,\x01", "我就在整理关于下一次研究主题的资料了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "这次应该会以易用性\x01", "作为追求的目标吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "其实老实说,\x01", "到底应该注重哪一方面的设计\x01", "连我自己也不是很清楚……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "正因如此,对我们技术人员来说,\x01", "这一难题才有挑战的价值。\x02", ) ) CloseMessageWindow() label("loc_B46") Jump("loc_188A") label("loc_B49") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xAA, 0)), scpexpr(EXPR_END)), "loc_E6E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_CAF") ChrTalk( 0xFE, ( "今天,有位客人在维修柜台\x01", "打听易用的照相机,\x01", "我就向其介绍了相关的商品。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不过,易用这一特性\x01", "用数字是表现不出来的。\x01", "结果我还是没有办法说清楚。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "虽然武器店的老板\x01", "叮嘱我说要基于\x01", "能让更多人使用这一点来考虑……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不过我还是不能理解\x01", "他这句话的含义。\x02", ) ) CloseMessageWindow() Jump("loc_E6B") label("loc_CAF") OP_A2(0x0) ChrTalk( 0xFE, "……唉,真难办啊。\x02", ) CloseMessageWindow() ChrTalk( 0xFE, ( "今天,我在维修柜台\x01", "向一位客人介绍了相关的商品……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "可是我不管怎么介绍商品的高性能,\x01", "也不能使客人满意。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "好像那位客人想要的是\x01", "使用起来非常方便的照相机……\x01", "不过易用性用数字是表现不出来的。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "虽然武器店的老板\x01", "叮嘱我说要基于\x01", "能让更多人使用这一点来考虑……\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "不过我还是不能理解\x01", "他这句话的含义。\x02", ) ) CloseMessageWindow() label("loc_E6B") Jump("loc_188A") label("loc_E6E") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA1, 6)), scpexpr(EXPR_END)), "loc_1404") Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x22, 0x0, 0x10)"), scpexpr(EXPR_END)), "loc_1310") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xB0, 5)), scpexpr(EXPR_END)), "loc_F8D") ChrTalk( 0xFE, ( "导力枪的研究\x01", "我觉得还算是比较顺利吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "一些细节部分\x01", "看来还需要些时间来完善,\x01", "但是不管怎么说大体已经成形了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "照这个势头研发的话,\x01", "会比我预计的更早出现在商店货架上哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "而且发售的时候\x01", "商品也会包装得更可爱一点。\x02", ) ) CloseMessageWindow() Jump("loc_130D") label("loc_F8D") OP_A2(0x585) Jc((scpexpr(EXPR_PUSH_VALUE_INDEX, 0xA), scpexpr(EXPR_PUSH_LONG, 0x6), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_FD2") ChrTalk( 0xFE, ( "啊,提妲。\x01", "哎,还有这几位……\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x101, 400) ChrTalk( 0xFE, "哎呀,你们是……?\x02", ) CloseMessageWindow() Jump("loc_FE6") label("loc_FD2") ChrTalk( 0xFE, "哎呀,你们就是……\x02", ) CloseMessageWindow() label("loc_FE6") ChrTalk( 0x101, "#501F嗯?怎么了?\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F说起来……\x02\x03", "我们好像\x01", "在卢安见过面吧。\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x102, 400) ChrTalk( 0xFE, ( "啊,果然是你们呀。\x01", "那时候真是给你们添麻烦了。\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x101, 400) ChrTalk( 0xFE, ( "来,要不要看看\x01", "我做的导力枪的试验品啊?\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#001F啊,我也想起来了。\x01", "你就是那时候的学者。\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#560F对了,\x01", "加鲁诺先生,您好像说过。\x02\x03", "在去卢安的途中\x01", "把导力枪试制品丢掉了。\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x107, 400) ChrTalk( 0xFE, ( "哎呀~\x01", "那一次可真是被逼到绝路了呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, "真的是得救了。\x02", ) CloseMessageWindow() ChrTalk( 0x101, ( "#000F在那之后\x01", "你的研究进行得如何了?\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x101, 400) ChrTalk( 0xFE, ( "嗯,\x01", "我觉得还算是比较顺利吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "一些细节部分\x01", "看来还需要些时间来完善,\x01", "但是不管怎么说大体已经成形了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "照这个势头研发的话,\x01", "会比我预计的更早出现在商店货架上哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "而且发售的时候\x01", "商品也会包装得更可爱一点。\x02", ) ) CloseMessageWindow() label("loc_130D") Jump("loc_1401") label("loc_1310") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_1371") ChrTalk( 0xFE, ( "唉,\x01", "现在可不是发呆的时候。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "要赶快把改良方案\x01", "确定下来才行。\x02", ) ) CloseMessageWindow() Jump("loc_1401") label("loc_1371") OP_A2(0x0) ChrTalk( 0xFE, ( "呼~……\x01", "露依赛重新把试制品做了出来,\x01", "真是帮大忙了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "如果没有样品的话,\x01", "研究就没办法进行了。\x02", ) ) CloseMessageWindow() label("loc_1401") Jump("loc_188A") label("loc_1404") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA0, 2)), scpexpr(EXPR_END)), "loc_188A") Jc((scpexpr(EXPR_EXEC_OP, "OP_29(0x22, 0x0, 0x10)"), scpexpr(EXPR_END)), "loc_1799") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xB0, 5)), scpexpr(EXPR_END)), "loc_1523") ChrTalk( 0xFE, ( "导力枪的研究\x01", "我觉得还算是比较顺利吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "一些细节部分\x01", "看来还需要些时间来完善,\x01", "但是不管怎么说大体已经成形了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "照这个势头研发的话,\x01", "会比我预计的更早出现在商店货架上哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "而且发售的时候\x01", "商品也会包装得更可爱一点。\x02", ) ) CloseMessageWindow() Jump("loc_1796") label("loc_1523") OP_A2(0x585) ChrTalk( 0xFE, "哎呀,你们是……\x02", ) CloseMessageWindow() ChrTalk( 0x101, "#501F嗯?怎么了?\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F说起来……\x02\x03", "我们好像\x01", "在卢安见过面吧。\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x102, 400) ChrTalk( 0xFE, ( "啊,我记起来了。\x01", "那时候真是给你们添麻烦了。\x02", ) ) CloseMessageWindow() TurnDirection(0xFE, 0x101, 400) ChrTalk( 0xFE, ( "来,要不要看看我做的\x01", "导力枪的试验品啊?\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#001F啊,我也想起来了。\x01", "你就是那时候的学者。\x02\x03", "#000F在那之后\x01", "你的研究进行得如何了?\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "嗯,\x01", "我觉得还算是比较顺利吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "一些细节部分\x01", "看来还需要些时间来完善,\x01", "但是不管怎么说大体已经成形了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "照这个势头研发的话,\x01", "会比我预计的更早出现在商店货架上哦。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "而且发售的时候\x01", "商品也会包装得更可爱一点。\x02", ) ) CloseMessageWindow() label("loc_1796") Jump("loc_188A") label("loc_1799") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_END)), "loc_17FA") ChrTalk( 0xFE, ( "唉,\x01", "现在可不是发呆的时候。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "要赶快把改良方案\x01", "确定下来才行。\x02", ) ) CloseMessageWindow() Jump("loc_188A") label("loc_17FA") OP_A2(0x0) ChrTalk( 0xFE, ( "呼~……\x01", "露依赛重新把试制品做了出来,\x01", "真是帮大忙了。\x02", ) ) CloseMessageWindow() ChrTalk( 0xFE, ( "如果没有样品的话,\x01", "研究就没办法进行了。\x02", ) ) CloseMessageWindow() label("loc_188A") TalkEnd(0xFE) Return() # Function_6_633 end def Function_7_188E(): pass label("Function_7_188E") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_1970") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_1902") ChrTalk( 0xA, ( "#800F提妲就拜托你们照顾了。\x01", " \x02\x03", "提妲,\x01", "去的时候要当心哦。\x02", ) ) CloseMessageWindow() Jump("loc_1970") label("loc_1902") ChrTalk( 0xA, ( "#800F咦,怎么了?\x02\x03", "去亚尔摩村的话,\x01", "要从西南方的门口出城啊。\x02", ) ) CloseMessageWindow() label("loc_1970") TalkEnd(0xFE) Return() # Function_7_188E end def Function_8_1974(): pass label("Function_8_1974") TalkBegin(0xFE) Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA3, 2)), scpexpr(EXPR_END)), "loc_19E3") ChrTalk( 0x8, ( "#100F抱歉,亚尔摩村水泵修理的工作\x01", "就麻烦你们了。\x02\x03", "只要把提妲送到那里,\x01", "后面的工作交给她就行了。\x02\x03", "那么,就拜托你们了。\x02", ) ) CloseMessageWindow() Jump("loc_1A43") label("loc_19E3") Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 3)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 1)), scpexpr(EXPR_OR), scpexpr(EXPR_END)), "loc_1A43") ChrTalk( 0x8, ( "#100F嗯?在干什么呢?\x02\x03", "还不快点去把\x01", "内燃引擎设备和汽油拿到这里来。\x02", ) ) CloseMessageWindow() label("loc_1A43") TalkEnd(0xFE) Return() # Function_8_1974 end def Function_9_1A47(): pass label("Function_9_1A47") TalkBegin(0xFE) ChrTalk( 0x9, ( "#060F内燃引擎设备和汽油的保管地方,\x01", "去五楼的演算室问问就知道了。\x02", ) ) CloseMessageWindow() Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0xA2, 6)), scpexpr(EXPR_END)), "loc_1ACA") ChrTalk( 0x101, ( "#000F嗯,保管地点已经知道了,\x01", "我们马上去拿过来。\x02", ) ) CloseMessageWindow() Jump("loc_1B0C") label("loc_1ACA") ChrTalk( 0x101, ( "#505F五楼的演算室吗。\x02\x03", "#000F那我们先去看看吧。\x02", ) ) CloseMessageWindow() label("loc_1B0C") TalkEnd(0xFE) Return() # Function_9_1A47 end def Function_10_1B10(): pass label("Function_10_1B10") ClearMapFlags(0x1) EventBegin(0x0) OP_6D(-770, 0, 1240, 0) RemoveParty(0x6, 0xFF) ClearChrFlags(0x9, 0x80) ClearChrFlags(0x8, 0x80) OP_4A(0x9, 255) OP_4A(0x8, 255) SetChrPos(0x8, -100, 0, 12700, 180) SetChrPos(0x9, -1030, 0, 1690, 0) SetChrPos(0x101, -600, 0, 510, 0) SetChrPos(0x102, -1950, 0, 750, 0) SetChrPos(0xE, 40, 800, 11550, 0) ClearChrFlags(0xE, 0x80) FadeToBright(2000, 0) OP_0D() ChrTalk( 0x8, "唉!又失败了吗!\x02", ) CloseMessageWindow() def lambda_1BC5(): OP_6D(1050, 0, 11840, 3000) ExitThread() QueueWorkItem(0x101, 2, lambda_1BC5) def lambda_1BDD(): OP_8E(0xFE, 0x55A, 0x0, 0x26D4, 0xBB8, 0x0) ExitThread() QueueWorkItem(0x9, 1, lambda_1BDD) Sleep(300) def lambda_1BFD(): OP_8E(0xFE, 0xFFFFFCE0, 0x0, 0x2710, 0xBB8, 0x0) ExitThread() QueueWorkItem(0x102, 1, lambda_1BFD) Sleep(200) def lambda_1C1D(): OP_8E(0xFE, 0x82, 0x0, 0x263E, 0xBB8, 0x0) ExitThread() QueueWorkItem(0x101, 1, lambda_1C1D) WaitChrThread(0x9, 0x1) TurnDirection(0x9, 0x8, 0) ChrTalk( 0x9, ( "#560F爷爷。\x01", "我们来帮忙了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#103F哦哦,提妲。\x02\x03", "哦……\x01", "你们也都来了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#506F嘿嘿~\x01", "我们也很在意嘛。\x02\x03", "#006F对了,现在到底在干什么呢?\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#104F如你们所见,\x01", "我正在尝试用工作机器把\x01", "『黑色导力器』的外壳切开……\x02\x03", "看来也并不顺利啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, "#014F怎么回事?\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#102F百闻不如一见,你们亲眼看看吧。\x02\x03", "……按下按钮。\x02", ) ) CloseMessageWindow() OP_22(0x9C, 0x0, 0x64) Sleep(400) OP_22(0xE0, 0x0, 0x64) OP_71(0x1, 0x20) OP_71(0x2, 0x20) OP_70(0x1, 0x3) OP_70(0x2, 0x3) Sleep(1000) OP_62(0x101, 0x0, 2000, 0x28, 0x2B, 0x64, 0x3) ChrTalk( 0x101, "#004F哇……这是什么!?\x02", ) CloseMessageWindow() ChrTalk( 0x9, ( "#062F工作用的圆盘锯。\x02\x03", "由特殊合金制成的,\x01", "能切断绝大多数种类的材料……\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#501F哦,用这个的话……\x02", ) CloseMessageWindow() OP_72(0x1, 0x20) OP_72(0x2, 0x20) OP_6F(0x1, 3) OP_6F(0x2, 3) OP_70(0x1, 0x25) OP_70(0x2, 0x25) OP_73(0x1) OP_71(0x1, 0x20) OP_71(0x2, 0x20) OP_6F(0x1, 34) OP_6F(0x2, 34) OP_70(0x1, 0x25) OP_70(0x2, 0x25) OP_22(0xC7, 0x0, 0x64) LoadEffect(0x0, "map\\\\mp007_00.eff") PlayEffect(0x0, 0x0, 0xE, 0, 300, 0, 0, 0, 0, 300, 300, 300, 0xFF, 0, 0, 0, 0) Sleep(1000) OP_72(0x1, 0x20) OP_72(0x2, 0x20) OP_23(0xE0) OP_23(0xC7) OP_22(0x9A, 0x0, 0x64) OP_7C(0x0, 0x64, 0xBB8, 0x64) OP_73(0x1) Sleep(500) OP_82(0x0, 0x2) Sleep(500) ChrTalk( 0x101, "#004F停、停下来了……\x02", ) CloseMessageWindow() ChrTalk( 0x9, "#561F果然……\x02", ) CloseMessageWindow() ChrTalk( 0x102, "#012F虽然规模较小,不过是和昨天一样的现象。\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#102F看来,这个黑色的东西能让\x01", "打算对其进行干涉的导力器的机能\x01", "完全停止下来。\x02\x03", "不仅仅是熄灭照明设备,\x01", "其他的导力器也会被停止下来。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#002F是、是这样啊……\x02", ) CloseMessageWindow() ChrTalk( 0x9, ( "#064F但是,爷爷。\x02\x03", "为什么没有像昨天那样\x01", "影响到其他的范围呢?\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#101F嗯,你发现得好。\x02\x03", "这个停止现象\x01", "似乎会在周围运作的导力器中\x01", "产生连锁反应而扩大。\x02\x03", "#100F有效范围大概为5亚矩。\x02\x03", "反过来说,\x01", "如果范围内没有运作中的导力器,\x01", "此现象就不能再继续扩大了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#014F原来如此……\x01", "还有这样的定律啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#104F但是,就算知道了这一点,\x01", "关键的机器不能运转,\x01", "还是无法调查导力器的内部呀……\x02\x03", "这才是真正的麻烦所在呀。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#006F不能想办法\x01", "用人力切开这个东西吗?\x02\x03", "比如说靠气势或毅力之类的。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#018F你还真敢说啊,艾丝蒂尔。\x02\x03", "用特殊合金制的小刀划过\x01", "不是也没有伤痕吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#505F啊,也是……\x02\x03", "#006F嗯~那么用火呢?\x02\x03", "放进熔铁炉里熔掉怎么样。\x02", ) ) CloseMessageWindow() ChrTalk( 0x9, ( "#065F那、那种做法,\x01", "内部的零件也会坏掉的呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#007F果然不行吗……\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#103F…………………………\x02\x03", "不,也许行得通。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#004F哎哎!?\x02", ) CloseMessageWindow() ChrTalk( 0x102, "#014F用高温熔化的方法吗?\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#102F不,不是的。\x02\x03", "问题在于导力——\x01", "我们太依赖靠导力来运作的机器了。\x02\x03", "用导力以外的能量\x01", "来运作工作机器就行了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#505F用导力以外的能量\x01", "来运作……?\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, "#010F有这样的方法吗?\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#104F所谓的『内燃引擎』……\x02\x03", "是利用火燃烧\x01", "所产生的能量来运作的装置。\x02\x03", "这项发明的历史比导力器更为悠久,\x01", "但效率也比导力引擎要低。\x02\x03", "#100F不过,简单地使工作机器运作,\x01", "这种程度还是可以做得到的。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#004F还有那样的东西啊……\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#019F原来如此,\x01", "这就是用『火』吗。\x02", ) ) CloseMessageWindow() ChrTalk( 0x9, ( "#064F但是,爷爷。\x02\x03", "内燃引擎这个设备,\x01", "我看都没看过呢……\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#100F记得在中央工房某个地方\x01", "保存有研究用的设备。\x02\x03", "#103F对了,\x01", "还必须找到燃料。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#000F燃料……是油吗?\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#100F那还远远不够,\x01", "必须要用『汽油』那样燃烧力更强的东西。\x02\x03", "以前这东西曾经作为溶剂使用过,\x01", "说不定还有剩余下来的。\x02\x03", "唔……\x01", "好像行得通。\x02\x03", "#101F就这样定了!\x01", "赶快开始改造工作机器吧!\x02", ) ) CloseMessageWindow() ChrTalk( 0x9, "#560F啊,我也来帮忙。\x02", ) CloseMessageWindow() ChrTalk( 0x101, ( "#006F那个那个,\x01", "有我们能帮上忙的地方吗?\x02\x03", "虽然做不到\x01", "像提妲那样专业的工作……\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#100F这样的话,\x01", "你们就去把那个内燃引擎和汽油取来吧。\x02\x03", "可能有点重,但以游击士的能力,\x01", "我想你们应该能找到办法运过来的。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#006FOK,交给我们吧!\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F内燃引擎和汽油对吧。\x02\x03", "是放在哪里的呢?\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#103F嗯?\x02\x03", "…………………………\x02\x03", "…………哎呀…………\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#014F博士您该不会是\x01", "忘了放在哪里了吧……?\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, "#104F嗯,忘了。\x02", ) CloseMessageWindow() ChrTalk( 0x101, "#509F还回答得这么轻描淡写~\x02", ) CloseMessageWindow() TurnDirection(0x9, 0x101, 400) ChrTalk( 0x9, ( "#560F#2P那、那个,艾丝蒂尔姐姐。\x02\x03", "去演算室的话,\x01", "我想应该能查到放在哪儿。\x02", ) ) CloseMessageWindow() TurnDirection(0x102, 0x9, 400) TurnDirection(0x101, 0x9, 400) ChrTalk( 0x101, "#505F演算室?\x02", ) CloseMessageWindow() ChrTalk( 0x9, ( "#060F#2P五楼有个房间里\x01", "放着一台导力演算器。\x02\x03", "有关中央工房的资料\x01", "全部都记录在那机器里面,\x01", "我想应该也有各种设备的保管场所吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#014F好厉害。\x01", "竟然有这样的东西……\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, "#101F就是这样,拜托你们了。\x02", ) CloseMessageWindow() ChrTalk( 0x101, "#007F真是的……\x02", ) CloseMessageWindow() TurnDirection(0x101, 0x102, 400) ChrTalk( 0x101, ( "#006F算了,\x01", "总之先到五楼的演算室去吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, "#010F嗯,走吧。\x02", ) CloseMessageWindow() OP_28(0x3F, 0x1, 0x80) OP_28(0x3F, 0x1, 0x100) FadeToDark(1000, 0, -1) OP_0D() SetChrPos(0x101, -410, 0, 8910, 180) SetChrPos(0x102, -410, 0, 8910, 180) SetChrPos(0x9, -100, 0, 12700, 180) SetChrPos(0x8, -2310, 0, 14200, 0) OP_4B(0x8, 255) OP_43(0x9, 0x0, 0x0, 0x2) OP_6F(0x1, 0) OP_6F(0x2, 0) OP_69(0x101, 0x0) Sleep(500) FadeToBright(1000, 0) EventEnd(0x0) Return() # Function_10_1B10 end def Function_11_2E1E(): pass label("Function_11_2E1E") AddParty(0x6, 0xFF) EventBegin(0x0) OP_6D(600, 0, 11100, 0) ClearChrFlags(0x8, 0x80) OP_4A(0x8, 255) OP_4A(0xA, 255) SetChrFlags(0x9, 0x80) SetChrPos(0x8, 400, 0, 10200, 270) SetChrPos(0x107, -630, 0, 10390, 90) SetChrPos(0x101, 640, 0, 800, 0) SetChrPos(0x102, -430, 0, 800, 0) FadeToBright(1000, 0) OP_0D() ChrTalk( 0x101, "#1P呼,我们回来了~\x02", ) CloseMessageWindow() def lambda_2EAD(): OP_8C(0xFE, 180, 400) ExitThread() QueueWorkItem(0x107, 1, lambda_2EAD) def lambda_2EBB(): OP_8C(0xFE, 180, 400) ExitThread() QueueWorkItem(0x8, 1, lambda_2EBB) def lambda_2EC9(): OP_8E(0xFE, 0x280, 0x0, 0x230A, 0xBB8, 0x0) ExitThread() QueueWorkItem(0x101, 1, lambda_2EC9) Sleep(500) OP_8E(0x102, 0xFFFFFE52, 0x0, 0x2224, 0xBB8, 0x0) ChrTalk( 0x102, ( "#010F博士,\x01", "需要的东西都带来了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, "#103F#5P哦哦,回来啦。\x02", ) CloseMessageWindow() ChrTalk( 0x107, "#560F#1P辛苦你们了~\x02", ) CloseMessageWindow() FadeToDark(300, 0, 100) SetMessageWindowPos(-1, -1, -1, -1) SetChrName("") OP_22(0x11, 0x0, 0x64) AnonymousTalk( ( scpstr(SCPSTR_CODE_COLOR, 0x0), "交出了\x07\x02", "内燃引擎设备\x07\x00", "。\x02", ) ) CloseMessageWindow() OP_56(0x0) SetMessageWindowPos(72, 320, 56, 3) SetMessageWindowPos(-1, -1, -1, -1) SetChrName("") OP_22(0x11, 0x0, 0x64) AnonymousTalk( ( scpstr(SCPSTR_CODE_COLOR, 0x0), "交出了\x07\x02", "汽油罐\x07\x00", "。\x02", ) ) CloseMessageWindow() OP_56(0x0) SetMessageWindowPos(72, 320, 56, 3) FadeToBright(300, 0) OP_3F(0x367, 1) OP_3F(0x368, 1) ChrTalk( 0x101, ( "#007F呼~\x01", "的确是有点重啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#101F#5P哦哦,真是辛苦啦。\x02\x03", "#100F哈哈,告诉你们,\x01", "工作机器也刚好改造完毕了。\x02\x03", "之后只要装上内燃引擎,\x01", "再灌入汽油就好了。\x02", ) ) CloseMessageWindow() TurnDirection(0x8, 0x107, 400) ChrTalk( 0x8, ( "#100F#5P提妲,\x01", "我们快点完成它吧。\x02", ) ) CloseMessageWindow() TurnDirection(0x107, 0x8, 400) ChrTalk( 0x107, "#061F#1P好~\x02", ) CloseMessageWindow() FadeToDark(1000, 0, -1) OP_0D() Sleep(500) OP_6D(-1390, 0, 11640, 0) SetChrPos(0x101, -2690, 0, 9810, 0) SetChrPos(0x102, -1580, 0, 9760, 0) SetChrPos(0x107, -3220, 0, 11360, 90) SetChrPos(0x8, -2350, 0, 13080, 180) OP_72(0x0, 0x4) FadeToBright(1500, 0) OP_0D() ChrTalk( 0x8, "#101F好了,完成啦。\x02", ) CloseMessageWindow() ChrTalk( 0x101, ( "#501F呜哇~\x01", "这东西真特别啊。\x02\x03", "这就是利用内燃引擎的引擎吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#060F嗯,是的。\x02\x03", "引擎里面燃烧着汽油,\x01", "所释放的能量就能使工作机器运作了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F这样一来,即使不依靠导力,\x01", "也能运行工作机器了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#104F没错。\x01", "那么赶快打开开关吧。\x02", ) ) CloseMessageWindow() OP_43(0x8, 0x1, 0x0, 0xC) OP_43(0x102, 0x1, 0x0, 0xD) OP_43(0x101, 0x1, 0x0, 0xE) OP_43(0x107, 0x1, 0x0, 0xF) OP_6D(1050, 0, 11840, 2000) WaitChrThread(0x107, 0x1) ChrTalk( 0x8, "#102F……按下按钮。\x02", ) CloseMessageWindow() OP_22(0x9C, 0x0, 0x64) Sleep(400) OP_22(0x9F, 0x1, 0x64) def lambda_3374(): label("loc_3374") OP_7C(0x0, 0xA, 0xBB8, 0x64) OP_48() Jump("loc_3374") QueueWorkItem2(0x101, 3, lambda_3374) OP_71(0x1, 0x20) OP_71(0x2, 0x20) OP_70(0x1, 0x3) OP_70(0x2, 0x3) Sleep(500) OP_8C(0x8, 180, 400) Sleep(500) ChrTalk( 0x101, "#004F哇,动了……\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F和导力引擎相比,\x01", "噪音和振动都要大很多啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#102F嗯,这是它的缺点之一。\x02\x03", "但和预想的一样,\x01", "应该不用担心会发生昨天的事情。\x02\x03", "那么,就这样开始解体吧。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#002F……(吞口水)\x02", ) CloseMessageWindow() ChrTalk( 0x107, "#560F……(紧张紧张)\x02", ) CloseMessageWindow() OP_72(0x1, 0x20) OP_72(0x2, 0x20) OP_6F(0x1, 3) OP_6F(0x2, 3) OP_70(0x1, 0x2D) OP_70(0x2, 0x2D) OP_73(0x1) OP_71(0x1, 0x20) OP_71(0x2, 0x20) OP_6F(0x1, 42) OP_6F(0x2, 42) OP_70(0x1, 0x2D) OP_70(0x2, 0x2D) OP_22(0xC7, 0x1, 0x64) LoadEffect(0x0, "map\\\\mp010_00.eff") PlayEffect(0x0, 0x0, 0xFF, -100, 1200, 11450, 0, 0, 0, 1000, 1000, 1000, 0xFF, 0, 0, 0, 0) ChrTalk( 0x101, "#004F哇哇……!\x02", ) CloseMessageWindow() ChrTalk( 0x102, "#012F好厉害的火花……\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#102F好,先停一下。\x02\x03", "首先要确认一下\x01", "这东西外壳的削损程度。\x02", ) ) CloseMessageWindow() OP_72(0x1, 0x20) OP_72(0x2, 0x20) OP_82(0x0, 0x2) OP_23(0xC7) OP_44(0x101, 0x3) OP_22(0x9A, 0x0, 0x64) OP_23(0x9F) OP_7C(0x0, 0x64, 0xBB8, 0x64) OP_6F(0x1, 362) OP_6F(0x2, 362) OP_70(0x1, 0x16D) OP_70(0x2, 0x16D) OP_73(0x1) Sleep(1000) FadeToDark(300, 0, 100) AnonymousTalk( ( scpstr(SCPSTR_CODE_COLOR, 0x5), "艾丝蒂尔他们往黑色导力器外壳的表面上看去。\x02", ) ) CloseMessageWindow() AnonymousTalk( ( scpstr(SCPSTR_CODE_COLOR, 0x5), "外壳上只是留下了小小的伤口。\x02", ) ) CloseMessageWindow() OP_56(0x0) FadeToBright(300, 0) ChrTalk( 0x101, "#505F只、只削了这么一点?\x02", ) CloseMessageWindow() ChrTalk( 0x107, ( "#065F真不敢相信……\x01", "这可是特殊合金制的圆盘锯呢。\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, "#012F真是极为坚硬的材质啊……\x02", ) CloseMessageWindow() ChrTalk( 0x8, ( "#101F其实只要保持耐心继续下去,\x01", "应该能完全切开的。\x02\x03", "哈哈……\x01", "只可惜圆盘锯有必要多换几个了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#006F这么说……\x01", "从现在开始就是耐力的考验了吧。\x02", ) ) CloseMessageWindow() ClearChrFlags(0xA, 0x80) SetChrPos(0xA, -800, 0, 800, 0) ChrTalk( 0xA, "#1P博士,你有空吗?\x02", ) CloseMessageWindow() def lambda_38B6(): TurnDirection(0xFE, 0xA, 400) ExitThread() QueueWorkItem(0x107, 1, lambda_38B6) def lambda_38C4(): TurnDirection(0xFE, 0xA, 400) ExitThread() QueueWorkItem(0x8, 1, lambda_38C4) def lambda_38D2(): TurnDirection(0xFE, 0xA, 400) ExitThread() QueueWorkItem(0x101, 1, lambda_38D2) def lambda_38E0(): TurnDirection(0xFE, 0xA, 400) ExitThread() QueueWorkItem(0x102, 1, lambda_38E0) OP_8E(0xA, 0xFFFFFF6A, 0x0, 0x1F40, 0xBB8, 0x0) ChrTalk( 0xA, ( "#801F哦哦……\x01", "已经顺利改造完毕了啊。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#104F当然了,\x01", "你以为我是谁呀。\x02\x03", "#100F怎么了,\x01", "又有什么麻烦吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0xA, ( "#800F刚才亚尔摩旅馆\x01", "给博士发了一条的联络过来。\x02\x03", "他们说旅馆那个抽取温泉的导力泵\x01", "好像出了故障。\x02\x03", "这样下去的话就不能营业了,\x01", "所以想请博士马上过去修理一下……\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#102F啊~怎么搞的!?\x02\x03", "哎呀呀!\x01", "如此忙的时候还来麻烦的事……\x02", ) ) CloseMessageWindow() ChrTalk( 0xA, ( "#805F这样的话……\x01", "要不要我派其他技师代替你去呢?\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#100F不……\x01", "那是40多年前的破铜烂铁了。\x02\x03", "只熟悉最新型机械的年轻人\x01", "是没办法应付那东西的。\x02\x03", "#104F唔,真是伤脑筋。\x02", ) ) CloseMessageWindow() OP_62(0x107, 0x0, 1700, 0x18, 0x1B, 0xFA, 0x0) Sleep(1200) OP_63(0x107) TurnDirection(0x107, 0x8, 400) ChrTalk( 0x107, ( "#560F那个,爷爷……\x02\x03", "我有个建议……\x01", "这次让我替您去修理好吗?\x02", ) ) CloseMessageWindow() def lambda_3C63(): TurnDirection(0xFE, 0x107, 400) ExitThread() QueueWorkItem(0x101, 1, lambda_3C63) def lambda_3C71(): TurnDirection(0xFE, 0x107, 400) ExitThread() QueueWorkItem(0x102, 1, lambda_3C71) TurnDirection(0x8, 0x107, 400) ChrTalk( 0x8, "#103F什么?\x02", ) CloseMessageWindow() ChrTalk( 0xA, "#802F提妲?\x02", ) CloseMessageWindow() ChrTalk( 0x107, ( "#060F以前您带我去的时候,\x01", "我也帮忙维修过那东西哦。\x02\x03", "所以我想没问题的。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#100F唔……的确。\x01", "技术方面交给你应该没问题……\x02\x03", "不过我担心别的。\x02", ) ) CloseMessageWindow() ChrTalk( 0xA, ( "#803F是啊,\x01", "街道上有那么多魔兽出没……\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#063F可是可是……\x01", "毛婆婆有麻烦,我不能置之不理啊。\x02", ) ) CloseMessageWindow() def lambda_3DD8(): TurnDirection(0xFE, 0x101, 400) ExitThread() QueueWorkItem(0x102, 1, lambda_3DD8) TurnDirection(0x101, 0x102, 400) OP_62(0x101, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0) OP_62(0x102, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0) Sleep(1200) OP_63(0x101) OP_63(0x102) def lambda_3E1C(): TurnDirection(0xFE, 0x107, 400) ExitThread() QueueWorkItem(0x102, 1, lambda_3E1C) TurnDirection(0x101, 0x107, 400) ChrTalk( 0x101, ( "#006F#2P……那样的话,\x01", "交给我们两个不就行了?\x02", ) ) CloseMessageWindow() TurnDirection(0x107, 0x101, 400) ChrTalk( 0x107, "#064F咦……\x02", ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F#2P艾丝蒂尔说的没错。\x01", "确保道路安全也是游击士的义务。\x02\x03", "这次就让我们两个做护卫吧。\x01", "我们一定会将提妲安全护送到那里的。\x02", ) ) CloseMessageWindow() ChrTalk( 0xA, ( "#801F哦哦,你们一起去的话,\x01", "那就没什么好担心的了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, ( "#100F唔……\x01", "难得你们费心,那就拜托了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#065F那个那个……\x01", "这样麻烦你们可以吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#006F#2P哎呀~小孩子就不要担心太多啦。\x02", ) CloseMessageWindow() ChrTalk( 0x102, "#019F#2P一起去的话起码多个照应。\x02", ) CloseMessageWindow() ChrTalk( 0x107, ( "#067F谢、谢谢你们。\x01", "艾丝蒂尔姐姐、约修亚哥哥。\x02", ) ) CloseMessageWindow() TurnDirection(0x107, 0x8, 400) Sleep(200) TurnDirection(0x107, 0xA, 400) Sleep(500) ChrTalk( 0x107, ( "#560F爷爷,工房长叔叔。\x02\x03", "那我们走了。\x02", ) ) CloseMessageWindow() ChrTalk( 0x8, "#101F哦哦,拜托你了。\x02", ) CloseMessageWindow() ChrTalk( 0xA, "#801F路上要小心点哦。\x02", ) CloseMessageWindow() FadeToDark(1000, 0, -1) OP_0D() OP_6D(-100, 0, 6770, 0) SetChrPos(0x101, -100, 0, 6770, 180) SetChrPos(0x102, -100, 0, 6770, 180) SetChrPos(0x107, -100, 0, 6770, 180) SetChrPos(0x8, 0, 0, 12740, 180) SetChrPos(0xA, -130, 0, 10450, 0) OP_4B(0x8, 255) OP_4B(0xA, 255) OP_6F(0x1, 0) OP_6F(0x2, 0) Sleep(500) FadeToBright(1000, 0) ClearMapFlags(0x10000000) OP_A2(0x51A) OP_28(0x3F, 0x4, 0x10) OP_28(0x3F, 0x4, 0x20) OP_28(0x40, 0x4, 0x2) OP_28(0x40, 0x4, 0x4) EventEnd(0x0) Return() # Function_11_2E1E end def Function_12_41CA(): pass label("Function_12_41CA") SetChrFlags(0xFE, 0x4) OP_8E(0xFE, 0xFFFFF876, 0x0, 0x348A, 0x7D0, 0x0) OP_8E(0xFE, 0xFFFFFEF2, 0x0, 0x3674, 0x7D0, 0x0) OP_8E(0xFE, 0xFFFFFF9C, 0x0, 0x319C, 0x7D0, 0x0) ClearChrFlags(0xFE, 0x4) OP_8C(0xFE, 90, 400) Return() # Function_12_41CA end def Function_13_4218(): pass label("Function_13_4218") Sleep(400) SetChrFlags(0xFE, 0x4) OP_8E(0xFE, 0x474, 0x0, 0x2774, 0x7D0, 0x0) ClearChrFlags(0xFE, 0x4) OP_8C(0xFE, 315, 400) Return() # Function_13_4218 end def Function_14_4243(): pass label("Function_14_4243") Sleep(800) SetChrFlags(0xFE, 0x4) OP_8E(0xFE, 0x78, 0x0, 0x26DE, 0x7D0, 0x0) ClearChrFlags(0xFE, 0x4) OP_8C(0xFE, 0, 400) Return() # Function_14_4243 end def Function_15_426E(): pass label("Function_15_426E") Sleep(1200) SetChrFlags(0xFE, 0x4) OP_8E(0xFE, 0xFFFFF448, 0x0, 0x268E, 0x7D0, 0x0) OP_8E(0xFE, 0xFFFFFD1C, 0x0, 0x27E2, 0x7D0, 0x0) ClearChrFlags(0xFE, 0x4) OP_8C(0xFE, 0, 400) Return() # Function_15_426E end def Function_16_42AD(): pass label("Function_16_42AD") EventBegin(0x0) OP_6D(-180, 0, 2620, 0) SetMapFlags(0x40000000) AddParty(0x5, 0xFF) OP_31(0x5, 0x0, 0x1A) OP_B5(0x5, 0x0) OP_B5(0x5, 0x1) OP_B5(0x5, 0x2) OP_B5(0x5, 0x3) OP_41(0x5, 0x9B) OP_41(0x5, 0xF5) OP_41(0x5, 0x113) OP_41(0x5, 0x25F, 0x0) OP_41(0x5, 0x259, 0x1) OP_41(0x5, 0x262, 0x2) OP_35(0x5, 0xC8) OP_35(0x5, 0xC9) OP_35(0x5, 0xCA) OP_36(0x5, 0xFF) OP_36(0x5, 0x100) SetChrFlags(0x106, 0x80) SetChrPos(0x107, -850, 0, 2040, 0) SetChrPos(0x101, -1590, 0, 900, 0) SetChrPos(0x102, -260, 0, 1060, 0) OP_22(0x9F, 0x1, 0x64) def lambda_434F(): label("loc_434F") OP_7C(0x0, 0xA, 0xBB8, 0x64) OP_48() Jump("loc_434F") QueueWorkItem2(0x101, 3, lambda_434F) OP_71(0x1, 0x20) OP_71(0x2, 0x20) OP_6F(0x1, 42) OP_6F(0x2, 42) OP_70(0x1, 0x2D) OP_70(0x2, 0x2D) FadeToBright(2000, 0) OP_0D() ChrTalk( 0x107, ( "#062F爷爷,不好了啦!\x02\x03", "#064F……啊……………\x02", ) ) CloseMessageWindow() OP_6D(1770, 0, 12830, 2000) def lambda_43DC(): OP_8E(0xFE, 0x140, 0x0, 0x259E, 0x1388, 0x0) ExitThread() QueueWorkItem(0x107, 1, lambda_43DC) def lambda_43F7(): OP_8E(0xFE, 0xFFFFFCAE, 0x0, 0x21F2, 0xFA0, 0x0) ExitThread() QueueWorkItem(0x101, 1, lambda_43F7) def lambda_4412(): OP_8E(0xFE, 0x3B6, 0x0, 0x2170, 0xFA0, 0x0) ExitThread() QueueWorkItem(0x102, 1, lambda_4412) WaitChrThread(0x101, 0x1) ChrTalk( 0x101, ( "#004F奇怪了……\x02\x03", "既然博士不在的话,\x01", "为什么工作机器自己会在动?\x02", ) ) CloseMessageWindow() ChrTalk( 0x107, ( "#065F是、是啊……\x01", "总之先把工作机器停下来……\x02", ) ) CloseMessageWindow() def lambda_4499(): label("loc_4499") TurnDirection(0xFE, 0x107, 400) OP_48() Jump("loc_4499") QueueWorkItem2(0x101, 1, lambda_4499) def lambda_44AA(): label("loc_44AA") TurnDirection(0xFE, 0x107, 400) OP_48() Jump("loc_44AA") QueueWorkItem2(0x102, 1, lambda_44AA) SetChrFlags(0x107, 0x4) OP_8E(0x107, 0x97E, 0x0, 0x271A, 0xFA0, 0x0) OP_8E(0x107, 0xA3C, 0x0, 0x326E, 0xFA0, 0x0) OP_8E(0x107, 0x50, 0x0, 0x350C, 0xFA0, 0x0) OP_8E(0x107, 0x8C, 0x0, 0x3200, 0xFA0, 0x0) OP_8C(0x107, 90, 400) Sleep(500) OP_72(0x1, 0x20) OP_72(0x2, 0x20) OP_23(0x9F) OP_44(0x101, 0x3) OP_22(0x9A, 0x0, 0x64) OP_7C(0x0, 0x64, 0xBB8, 0x64) OP_6F(0x1, 362) OP_6F(0x2, 362) OP_70(0x1, 0x16D) OP_70(0x2, 0x16D) OP_73(0x1) Sleep(1500) ChrTalk( 0x107, ( "#561F呼……\x02\x03", "#063F爷爷他……\x01", "现在到底在哪儿呢?\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#013F不止是博士……\x01", "『黑色导力器』也不见了。\x02\x03", "难道说这是……\x02", ) ) CloseMessageWindow() SetChrPos(0x106, -790, 0, 2500, 0) ClearChrFlags(0x106, 0x80) ChrTalk( 0x106, "#1P哼,你们在这里啊。\x02", ) CloseMessageWindow() OP_62(0x101, 0x0, 2000, 0x2, 0x7, 0x50, 0x1) OP_22(0x27, 0x0, 0x64) OP_62(0x102, 0x0, 2000, 0x2, 0x7, 0x50, 0x1) OP_22(0x27, 0x0, 0x64) Sleep(1000) def lambda_465D(): TurnDirection(0xFE, 0x106, 400) ExitThread() QueueWorkItem(0x107, 1, lambda_465D) def lambda_466B(): TurnDirection(0xFE, 0x106, 400) ExitThread() QueueWorkItem(0x101, 1, lambda_466B) def lambda_4679(): TurnDirection(0xFE, 0x106, 400) ExitThread() QueueWorkItem(0x102, 1, lambda_4679) OP_6D(990, 0, 7840, 1000) ChrTalk( 0x101, "#004F阿、阿加特!?\x02", ) CloseMessageWindow() ChrTalk( 0x102, "#014F您怎么会在这里……\x02", ) CloseMessageWindow() def lambda_46CD(): label("loc_46CD") TurnDirection(0xFE, 0x106, 400) OP_48() Jump("loc_46CD") QueueWorkItem2(0x101, 1, lambda_46CD) def lambda_46DE(): label("loc_46DE") TurnDirection(0xFE, 0x106, 400) OP_48() Jump("loc_46DE") QueueWorkItem2(0x102, 1, lambda_46DE) OP_8E(0x106, 0xFFFFFF2E, 0x0, 0x1B1C, 0xBB8, 0x0) OP_43(0x107, 0x2, 0x0, 0x11) ChrTalk( 0x106, ( "#552F哼,这句话是我问你们才对。\x02\x03", "我听到这里发生骚乱就赶了过来,\x01", "不过没想到又被你们两个抢先一步。\x02\x03", "真是不知天高地厚的小鬼,\x01", "明明本事就不多,还到处乱出风头。\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, ( "#509F你、你这个刀子嘴~……\x01", "没见一段时间还是那么惹人厌啊。\x02", ) ) CloseMessageWindow() WaitChrThread(0x107, 0x2) TurnDirection(0x107, 0x106, 400) ChrTalk( 0x107, ( "#064F那个……\x01", "艾丝蒂尔姐姐你们认识他吗?\x02", ) ) CloseMessageWindow() ChrTalk( 0x102, ( "#010F他叫阿加特。\x01", "是我们在游击士协会的前辈。\x02", ) ) CloseMessageWindow() OP_62(0x106, 0x0, 2000, 0x2, 0x7, 0x50, 0x1) OP_22(0x27, 0x0, 0x64) Sleep(1000) TurnDirection(0x106, 0x107, 400) ChrTalk( 0x106, ( "#052F喂,我问你们两个……\x02\x03", "#057F既然全体人员已经疏散了,\x01", "为什么还会有小鬼在这种地方?\x02", ) ) CloseMessageWindow() OP_8E(0x106, 0x55A, 0x0, 0x1D38, 0xBB8, 0x0) FadeToDark(300, 0, 100) AnonymousTalk( ( scpstr(SCPSTR_CODE_COLOR, 0x5), "阿加特紧紧盯着提妲。\x02", ) ) CloseMessageWindow() OP_56(0x0) FadeToBright(300, 0) OP_62(0x107, 0x0, 1700, 0x28, 0x2B, 0x64, 0x3) ChrTalk( 0x107, "#065F……呜……\x02", ) OP_9E(0x107, 0xF, 0x0, 0x3E8, 0xBB8) CloseMessageWindow() OP_44(0x101, 0xFF) OP_8E(0x101, 0x186, 0x0, 0x1DF6, 0xBB8, 0x0) TurnDirection(0x101, 0x106, 0) ChrTalk( 0x101, ( "#009F等、等一下,\x01", "你怎么吓唬人家女孩子啊!?\x02", ) ) CloseMessageWindow() ChrTalk( 0x106, ( "#057F…………………………\x02\x03", "#552F嘁……\x02\x03", "虽然想说的话堆积如山,\x01", "但还是以后再说吧。\x02", ) ) CloseMessageWindow() TurnDirection(0x106, 0x101, 400) ChrTalk( 0x106, "#050F话说回来,这到底是怎么回事?\x02", ) CloseMessageWindow() ChrTalk( 0x102, "#012F嗯,其实……\x02", ) CloseMessageWindow() FadeToDark(300, 0, 100) AnonymousTalk( ( scpstr(SCPSTR_CODE_COLOR, 0x5), "艾丝蒂尔他们向阿加特说明了拉赛尔博士不见的事情。\x02", ) ) CloseMessageWindow() OP_56(0x0) FadeToBright(300, 0) ChrTalk( 0x106, ( "#053F唔,发烟筒吗……\x01", "我有很不好的预感。\x02\x03", "#054F时间紧迫……\x01", "赶快把博士找出来吧!\x02", ) ) CloseMessageWindow() ChrTalk( 0x101, "#005F知道了!\x02", ) CloseMessageWindow() ChrTalk( 0x102, "#012F明白。\x02", ) CloseMessageWindow() ChrTalk( 0x107, "#063F……爷爷……\x02", ) CloseMessageWindow() OP_44(0x101, 0xFF) OP_44(0x102, 0xFF) OP_28(0x41, 0x1, 0x4) EventEnd(0x0) Return() # Function_16_42AD end def Function_17_4BD0(): pass label("Function_17_4BD0") OP_8E(0x107, 0x50, 0x0, 0x350C, 0xBB8, 0x0) OP_8E(0x107, 0x33E, 0x0, 0x3692, 0xBB8, 0x0) OP_8E(0x107, 0xA3C, 0x0, 0x326E, 0xBB8, 0x0) OP_8E(0x107, 0x8D4, 0x0, 0x1E14, 0xBB8, 0x0) TurnDirection(0x107, 0x101, 400) Return() # Function_17_4BD0 end SaveToFile() Try(main)
print 'helloword-test'
from collective.cart.core.error import InfiniteLoopError from collective.cart.core.interfaces import IRandomDigits from collective.cart.core.interfaces import IRegularExpression from collective.cart.core.interfaces import ISelectRange from random import choice from string import digits from zope.interface import implements import re class SelectRange(object): implements(ISelectRange) def __call__(self, number): if number is not None and number > 0: return range(1, number + 1) class RandomDigits(object): implements(IRandomDigits) def random_number(self, number): return "".join(choice(digits) for d in xrange(number)) def loop(self, number, ids): digits = self.random_number(number) if digits not in ids: return digits def __call__(self, number, ids): if ids is None: return self.random_number(number) if len(ids) == 10 ** number: raise InfiniteLoopError(number) digits = self.random_number(number) while digits in ids: digits = self.random_number(number) else: return digits class RegularExpression(object): implements(IRegularExpression) def email(self, string): check = re.compile( r"[a-zA-Z0-9._%-]+@([a-zA-Z0-9-]+\.)*[a-zA-Z]{2,4}" ).match if check(string): return True else: return False def integer(self, string): check = re.compile( r"^[0-9]+$" ).match if check(string): return True else: return False def float(self, string): if ',' in string: string = string.replace(',', '.') try: float(string) return True except ValueError: return False
import random def random_item(iterable): number = random.randint(0,len(iterable)-1) print(iterable[number]) random_item("treehouse")
from conans.model import Generator """ PC FILE EXAMPLE: prefix=/usr exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: my-project Description: Some brief but informative description Version: 1.2.3 Libs: -L${libdir} -lmy-project-1 -linkerflag Cflags: -I${includedir}/my-project-1 Requires: glib-2.0 >= 2.40 gio-2.0 >= 2.42 nice >= 0.1.6 Requires.private: gthread-2.0 >= 2.40 """ def concat_if_not_empty(groups): return " ".join([param for group in groups for param in group if param and param.strip()]) def single_pc_file_contents(name, cpp_info): lines = ['prefix=%s' % cpp_info.rootpath.replace("\\", "/")] libdir_vars = [] for i, libdir in enumerate(cpp_info.libdirs): varname = "libdir" if i == 0 else "libdir%d" % (i + 2) lines.append("%s=${prefix}/%s" % (varname, libdir)) libdir_vars.append(varname) include_dir_vars = [] for i, includedir in enumerate(cpp_info.includedirs): varname = "includedir" if i == 0 else "includedir%d" % (i + 2) lines.append("%s=${prefix}/%s" % (varname, includedir)) include_dir_vars.append(varname) lines.append("") lines.append("Name: %s" % name) description = cpp_info.description or "Conan package: %s" % name lines.append("Description: %s" % description) lines.append("Version: %s" % cpp_info.version) libdirs_flags = ["-L${%s}" % name for name in libdir_vars] libnames_flags = ["-l%s " % name for name in cpp_info.libs] shared_flags = cpp_info.sharedlinkflags + cpp_info.exelinkflags lines.append("Libs: %s" % concat_if_not_empty([libdirs_flags, libnames_flags, shared_flags])) include_dirs_flags = ["-I${%s}" % name for name in include_dir_vars] lines.append("Cflags: %s" % concat_if_not_empty( [include_dirs_flags, cpp_info.cppflags, cpp_info.cflags, ["-D%s" % d for d in cpp_info.defines]])) if cpp_info.public_deps: public_deps = " ".join(cpp_info.public_deps) lines.append("Requires: %s" % public_deps) return "\n".join(lines) + "\n" class PkgConfigGenerator(Generator): @property def filename(self): pass @property def content(self): ret = {} for depname, cpp_info in self.deps_build_info.dependencies: ret["%s.pc" % depname] = single_pc_file_contents(depname, cpp_info) return ret
from keras.models import Sequential from keras.layers import Dense model= Sequential() model.add(Dense(12, input_dim=8, kernel_initializer = 'random_uniform'))
# coding: utf-8 import math import random import copy import pygame from constantes import * class Carte: altitude_min_nour_abondante = 0. proba_modif_point_altitude_fixe = 0. valeur_modif_point_altitude_fixe = 0 proba_modif_vitesse_point_altitude_fixe = 0. def __init__(self, largeur_carte: int, hauteur_carte: int): self.largeur_carte = largeur_carte self.hauteur_carte = hauteur_carte self.grille_altitude = [] self.liste_altitudes_positives = [] self.liste_altitudes_abondantes = [] self.liste_altitudes_negatives = [] self.liste_altitudes_fixes = [] self.liste_valeurs_altitudes_fixes = [] self.liste_coefs_energie_depensee_i = [] self.largeur_ecran = 0 self.hauteur_ecran = 0 self.i_carte_camera = 0. self.j_carte_camera = 0. self.i_deplacement_camera = 0 self.j_deplacement_camera = 0 self.echelle_min = 0 self.echelle_max = 0 self.echelle = 0 self.coef_zoom = 0. self.marge_bord_deplacement = 0 self.vitesse_deplacement = 0 self.ecran = None self.ecran_miniature = None self.liste_cases_affichage = [] self.new_affichage = True self.coef_affichage_energie_depensee = 0 def init_grille(self, nb_update_carte_init, altitude_max, altitude_min, altitude_globale_init, altitude_bord, nb_altitudes_fixes_positives, nb_altitudes_fixes_negatives, coef_energie_depensee_gauche, coef_energie_depensee_droite, proba_altitudes_negaties_vers_centre, tk_var_stop, tk_var_avancement): coef_dir = (coef_energie_depensee_droite - coef_energie_depensee_gauche) / self.largeur_carte self.liste_coefs_energie_depensee_i = [coef_energie_depensee_gauche + i * coef_dir for i in range(self.largeur_carte)] self.grille_altitude = [[altitude_bord if (i == 0 or j == 0 or i == self.largeur_carte - 1 or j == self.hauteur_carte - 1) else altitude_globale_init for i in range(self.largeur_carte)] for j in range(self.hauteur_carte)] self.liste_altitudes_fixes = [(random.randint(MARGE_BORD_ALTITUDE_FIXE, self.largeur_carte - MARGE_BORD_ALTITUDE_FIXE - 1), random.randint(MARGE_BORD_ALTITUDE_FIXE, self.hauteur_carte - MARGE_BORD_ALTITUDE_FIXE - 1)) for _ in range(nb_altitudes_fixes_negatives + nb_altitudes_fixes_positives)] for i in range(nb_altitudes_fixes_negatives): if random.random() < proba_altitudes_negaties_vers_centre: self.liste_altitudes_fixes[i] = int(proba_altitudes_negaties_vers_centre * self.largeur_carte / 2 + (1 - proba_altitudes_negaties_vers_centre) * self.liste_altitudes_fixes[i][0]), self.liste_altitudes_fixes[i][1] self.liste_valeurs_altitudes_fixes = ([(random.randint(0, self.valeur_modif_point_altitude_fixe * 2) - self.valeur_modif_point_altitude_fixe, random.randint(0, self.valeur_modif_point_altitude_fixe * 2) - self.valeur_modif_point_altitude_fixe, altitude_min) for _ in range(nb_altitudes_fixes_negatives)] + [(random.randint(0, self.valeur_modif_point_altitude_fixe * 2) - self.valeur_modif_point_altitude_fixe, random.randint(0, self.valeur_modif_point_altitude_fixe * 2) - self.valeur_modif_point_altitude_fixe, altitude_max) for _ in range(nb_altitudes_fixes_positives)]) for n, (i, j) in enumerate(self.liste_altitudes_fixes): self.grille_altitude[j][i] = self.liste_valeurs_altitudes_fixes[n][2] for n in range(nb_update_carte_init): if tk_var_stop.get(): break self.update_grille() tk_var_avancement.set(round(n / nb_update_carte_init, 2)) def init_pygame(self, confs: dict): self.largeur_ecran = confs[LARGEUR_ECRAN] self.hauteur_ecran = confs[HAUTEUR_ECRAN] self.echelle_min = max(math.ceil(self.largeur_ecran / self.largeur_carte), math.ceil(self.hauteur_ecran / self.hauteur_carte)) self.echelle_max = confs[ECHELLE_MAX] self.echelle = self.echelle_min self.coef_zoom = confs[COEF_ZOOM] self.marge_bord_deplacement = confs[CARTE_MARGE_BORD_DEPLACEMENT] self.vitesse_deplacement = confs[CARTE_VITESSE_DEPLACEMENT] self.coef_affichage_energie_depensee = confs[COEF_AFFICHAGE_ENERGIE_DEPENSEE] self.ecran = pygame.Surface((self.largeur_ecran, self.hauteur_ecran)) self.ecran_miniature = pygame.Surface((self.largeur_carte, self.hauteur_carte)) self.liste_cases_affichage = [] self.new_affichage = True self.i_carte_camera = 0. self.j_carte_camera = 0. self.i_deplacement_camera = 0 self.j_deplacement_camera = 0 def gere_clic(self, x_souris: int, y_souris: int): if 0 <= x_souris - X_MINIATURE_SUR_ECRAN <= self.largeur_carte and \ 0 <= y_souris - Y_MINIATURE_SUR_ECRAN <= self.hauteur_carte: self.set_i_carte_camera(x_souris - MARGE_BORD_ALTITUDE_FIXE - self.largeur_ecran / self.echelle / 2) self.set_j_carte_camera(y_souris - MARGE_BORD_ALTITUDE_FIXE - self.hauteur_ecran / self.echelle / 2) def gere_zoom(self, sens: bool, x_souris: int, y_souris: int): old_echelle = self.echelle i_souris, j_souris = self.xy_ecran_to_ij_carte(x_souris, y_souris) if sens: self.echelle = min(self.echelle + max(int(self.echelle * self.coef_zoom), 1), self.echelle_max) else: self.echelle = max(self.echelle - max(int(self.echelle * self.coef_zoom), 1), self.echelle_min) if old_echelle != self.echelle: self.new_affichage = True coef = old_echelle / self.echelle self.set_i_carte_camera(i_souris + coef * (self.i_carte_camera - i_souris)) self.set_j_carte_camera(j_souris + coef * (self.j_carte_camera - j_souris)) def update_deplacement_camera(self, x_souris: int, y_souris: int): self.i_deplacement_camera = 0 dx = self.marge_bord_deplacement - x_souris if dx > 0: self.i_deplacement_camera = - dx / self.marge_bord_deplacement * self.vitesse_deplacement / self.echelle else: dx = self.marge_bord_deplacement - self.largeur_ecran + x_souris if dx > 0: self.i_deplacement_camera = dx / self.marge_bord_deplacement * self.vitesse_deplacement / self.echelle self.j_deplacement_camera = 0 dy = self.marge_bord_deplacement - y_souris if dy > 0: self.j_deplacement_camera = - dy / self.marge_bord_deplacement * self.vitesse_deplacement / self.echelle else: dy = self.marge_bord_deplacement - self.hauteur_ecran + y_souris if dy > 0: self.j_deplacement_camera = dy / self.marge_bord_deplacement * self.vitesse_deplacement / self.echelle def set_i_carte_camera(self, i_carte_camera: float): # if i_carte_camera == self.i_carte_camera: # return False old_i = self.i_carte_camera self.i_carte_camera = round(max(min(i_carte_camera, self.largeur_carte - self.largeur_ecran / self.echelle), 0), PRECISION_POSITION_CAMERA_CARTE) if old_i == self.i_carte_camera: return False self.new_affichage = True return True def set_j_carte_camera(self, j_carte_camera: float): # if j_carte_camera == self.j_carte_camera: # return False old_j = self.j_carte_camera self.j_carte_camera = round(max(min(j_carte_camera, self.hauteur_carte - self.hauteur_ecran / self.echelle), 0), PRECISION_POSITION_CAMERA_CARTE) if old_j == self.j_carte_camera: return False self.new_affichage = True return True def update_position_camera(self): if not self.i_deplacement_camera == 0: if not self.set_i_carte_camera(self.i_carte_camera + self.i_deplacement_camera): self.i_deplacement_camera = 0 if not self.j_deplacement_camera == 0: if not self.set_j_carte_camera(self.j_carte_camera + self.j_deplacement_camera): self.j_deplacement_camera = 0 def update_grille(self): self.liste_altitudes_positives = [] self.liste_altitudes_negatives = [] self.liste_altitudes_abondantes = [] for n, (i, j) in enumerate(self.liste_altitudes_fixes): if random.random() < self.proba_modif_point_altitude_fixe: old_i, old_j = i, j vx, vy, a = self.liste_valeurs_altitudes_fixes[n] if random.random() < self.proba_modif_point_altitude_fixe: i += vx if random.random() < self.proba_modif_point_altitude_fixe: j += vy if random.random() < self.proba_modif_vitesse_point_altitude_fixe: vx = random.randint(0, self.valeur_modif_point_altitude_fixe * 2) - \ self.valeur_modif_point_altitude_fixe if random.random() < self.proba_modif_vitesse_point_altitude_fixe: vy = random.randint(0, self.valeur_modif_point_altitude_fixe * 2) - \ self.valeur_modif_point_altitude_fixe if (old_i, old_j) == (i, j): self.liste_valeurs_altitudes_fixes[n] = vx, vy, a self.grille_altitude[j][i] = a else: if MARGE_BORD_ALTITUDE_FIXE <= i < self.largeur_carte - MARGE_BORD_ALTITUDE_FIXE and \ MARGE_BORD_ALTITUDE_FIXE <= j < self.hauteur_carte - MARGE_BORD_ALTITUDE_FIXE: self.liste_altitudes_fixes[n] = i, j self.liste_valeurs_altitudes_fixes[n] = vx, vy, a self.grille_altitude[j][i] = a copie_grille = copy.deepcopy(self.grille_altitude) for j, ligne in enumerate(copie_grille): if 0 < j < self.hauteur_carte - 1: for i, altitude in enumerate(ligne): if 0 < i < self.largeur_carte - 1 and (i, j) not in self.liste_altitudes_fixes: s = 0 for i2 in [i - 1, i, i + 1]: for j2 in [j - 1, j, j + 1]: if i2 == i and j2 == j: s += altitude else: s += copie_grille[j2][i2] self.grille_altitude[j][i] = round(s / 9, PRECISION_ALTITUDE_CARTE) if altitude > 0: self.liste_altitudes_positives.append((i, j)) if altitude > self.altitude_min_nour_abondante: self.liste_altitudes_abondantes.append((i, j)) else: self.liste_altitudes_negatives.append((i, j)) self.new_affichage = True def update_ecran(self): self.update_position_camera() if self.new_affichage: self.new_affichage = False self.liste_cases_affichage = [] i_min_camera_miniature = int(self.i_carte_camera) i_max_camera_miniature = i_min_camera_miniature + self.largeur_ecran // self.echelle j_min_camera_miniature = int(self.j_carte_camera) j_max_camera_miniature = j_min_camera_miniature + self.hauteur_ecran // self.echelle for j, ligne in enumerate(self.grille_altitude): for i, altitude in enumerate(ligne): x, y = self.ij_carte_to_xy_ecran(i, j) c = COULEUR_ALTITUDE(altitude, self.altitude_min_nour_abondante, self.liste_coefs_energie_depensee_i[i], self.coef_affichage_energie_depensee) if - self.echelle < x < self.largeur_ecran and - self.echelle < y < self.hauteur_ecran: self.ecran.fill(c, (x, y, self.echelle, self.echelle)) self.liste_cases_affichage.append((i, j)) if i_min_camera_miniature < i < i_max_camera_miniature and \ j_min_camera_miniature < j < j_max_camera_miniature: self.ecran_miniature.set_at((i, j), c) else: self.ecran_miniature.set_at((i, j), (c[0] // COEF_COULEUR_MINIATURE_HORS_CAMERA, c[1] // COEF_COULEUR_MINIATURE_HORS_CAMERA, c[2] // COEF_COULEUR_MINIATURE_HORS_CAMERA)) pygame.draw.rect(self.ecran_miniature, COULEUR_CADRE_CAMERA_MINIATURE, (i_min_camera_miniature, j_min_camera_miniature, i_max_camera_miniature - i_min_camera_miniature, j_max_camera_miniature - j_min_camera_miniature), 1) def ecran_miniature_stats(self, coef_temperature): ecran_miniature = pygame.Surface((self.largeur_carte, self.hauteur_carte)) for j, ligne in enumerate(self.grille_altitude): for i, altitude in enumerate(ligne): c = COULEUR_ALTITUDE(altitude, self.altitude_min_nour_abondante, self.liste_coefs_energie_depensee_i[i], coef_temperature) ecran_miniature.set_at((i, j), c) return ecran_miniature def xy_ecran_to_ij_carte(self, x: int, y: int): return self.i_carte_camera + x / self.echelle, self.j_carte_camera + y / self.echelle def ij_carte_to_xy_ecran(self, i: float, j: float): return int((i - self.i_carte_camera) * self.echelle), int((j - self.j_carte_camera) * self.echelle) def ij_altitude_positive(self, i: float, j: float): return (int(i), int(j)) in self.liste_altitudes_positives def affiche_miniature(self, chemin_image, taille, coef_temperature): image = pygame.image.load(chemin_image) if taille == 1: ecran_miniature = self.ecran_miniature_stats(coef_temperature) else: ecran_miniature = pygame.transform.rotozoom(self.ecran_miniature_stats(coef_temperature), 0, taille) image.blit(ecran_miniature, (X_MINIATURE_SUR_ECRAN, image.get_height() - Y_MINIATURE_SUR_ECRAN - ecran_miniature.get_height())) pygame.image.save(image, chemin_image) class CarteContent: def __init__(self, largeur_carte: int, hauteur_carte: int): self._grille_content = [[[] for _ in range(largeur_carte)] for _ in range(hauteur_carte)] def add_grille_content(self, thing, i: float, j: float): self._grille_content[int(j)][int(i)].append(thing) def add_grille_content_int(self, thing, i: int, j: int): self._grille_content[j][i].append(thing) def remove_grille_content(self, thing, i: float, j: float): self._grille_content[int(j)][int(i)].remove(thing) def remove_grille_content_int(self, thing, i: int, j: int): self._grille_content[j][i].remove(thing) def get_grille_content_ij(self, i: int, j: int): return self._grille_content[j][i] def pop_grille_content_ij(self, i: int, j: int): content = self._grille_content[j][i] self._grille_content[j][i] = [] return content def get_grille_content_dist_max_around_ij(self, i: float, j: float): i, j = int(i), int(j) liste_things = [] for dist_max, list_indiv in LISTE_CASES_AUTOUR_INDIVIDU: for di, dj in list_indiv: liste_things.append((dist_max, self.get_grille_content_ij(i + di, j + dj))) return liste_things
''' Regex with Python is easy Steps required: - import standard module `re` - write your regex pattern and compile it - call the one of methods - findall, match, search, sub etc. ''' import re number_input_text = "the numbers are: 12 34 56 and 78, others numbers are: 33 78 and 0." number_regex_pattern = r"(\d+)" r = re.compile(number_regex_pattern) # findall occurences/matches for pattern matched_numbers = r.findall(number_input_text) print("Input text:", repr(number_input_text)) print("Matched numbers:", matched_numbers) # replace all the matches/occurences with some string masked_numbers = r.sub('XX', number_input_text) print("Numbers masked:", masked_numbers) ''' search() - searches for the first pattern match - returns the MATCH object, not a string - on matched object either run, group() or groups() ''' search_numbers = r.search(number_input_text) print("Match object:", search_numbers) print("match.group():", search_numbers.group()) print("match.groups():", search_numbers.groups())
# Generated by Django 2.2.5 on 2020-04-25 16:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('listings', '0007_mobilephone_is_wkp'), ] operations = [ migrations.CreateModel( name='Brand', fields=[ ('name', models.CharField(max_length=100, primary_key=True, serialize=False)), ], ), migrations.AddField( model_name='mobilephone', name='brand', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='listings.Brand'), ), ]
import maya.cmds as cmds import os from functools import partial import Utils.Utils_File as fileUtils class Parts_UI: def __init__(self): """ Create a dictionary to store UI elements """ self.UIElements = {} """ Check to see if the UI exists """ self.windowName = "Window" if cmds.window(self.windowName, exists=True): cmds.deleteUI(self.windowName) """ Define UI elements width and height """ self.windowWidth = 240 self.windowHeight = 200 buttonWidth = 100 buttonHeight = 30 """ Define a window""" self.UIElements["window"] = cmds.window(self.windowName, width=self.windowWidth, height=self.windowHeight, title="Window", sizeable=True) self.UIElements["guiFlowLayout1"] = cmds.flowLayout(v=False, width=220, height=self.windowHeight, bgc=[0.2, 0.2, 0.2]) """ Use a flow layout for the UI """ self.UIElements["guiFlowLayout2"] = cmds.flowLayout(v=True, width=110, height=self.windowHeight, bgc=[0.4, 0.4, 0.4]) cmds.setParent(self.UIElements["guiFlowLayout1"]) self.UIElements["guiFlowLayout3"] = cmds.flowLayout(v=True, width=110, height=self.windowHeight, bgc=[0.4, 0.4, 0.4]) cmds.setParent(self.UIElements["guiFlowLayout1"]) arttools = os.environ["GTOOLS"] lytWtPath = arttools + "/RG_Parts/Parts_Maya/Widgets/Layout/" """ for widget in self.returnWidgets(lytWtPath): print widget mod = __import__("Widgets.Layout."+widget, {}, {}, [widget]) reload(mod) title = mod.TITLE description = mod.DESCRIPTION classname = mod.CLASS_NAME cmds.separator(p=self.UIElements["guiFlowLayout2"]) self.UIElements["module_button_"+widget] = cmds.button(label=title, width=buttonWidth, height=buttonHeight, p=self.UIElements["guiFlowLayout2"], command=partial(self.installWidget, widget)) """ rigWtPath = arttools + "/RG_Parts/Parts_Maya/Widgets/Rigging/" for widget in self.returnWidgets(rigWtPath): print widget mod = __import__("Widgets.Rigging."+widget, {}, {}, [widget]) reload(mod) title = mod.TITLE description = mod.DESCRIPTION classname = mod.CLASS_NAME cmds.separator(p=self.UIElements["guiFlowLayout3"]) self.UIElements["module_button_"+widget] = cmds.button(label=title, width=buttonWidth, height=buttonHeight, p=self.UIElements["guiFlowLayout3"], command=partial(self.installWidget, widget)) """ Show the window""" cmds.showWindow(self.windowName) def installWidget(self, widget, *args): print "Install" mod = __import__("Widgets.Rigging."+widget, {}, {}, [widget]) reload(mod) widgetClass = getattr(mod, mod.CLASS_NAME) widgetInstance = widgetClass() print widgetClass widgetInstance.install() def returnWidgets(self, path, *args): # search the relative directory for all available modules # Return a list of all module names (excluding the ".py" extension) allPyFiles = fileUtils.findAllFiles(path, ".py") returnModules = [] for file in allPyFiles: if file != "__init__": returnModules.append(file) return returnModules
from game_engine.constants import STATUS_ACTIVE, STATUS_FOLDED class Player: def __init__(self, stack): self._stack = stack self._bet = 0 self._status = STATUS_ACTIVE def get_player_obj(self): return { "stack": self._stack, "bet": self._bet, "status": self._status } def give_hand(self, hand): self._hand = hand self._status = STATUS_ACTIVE def set_seat(self, seat): self._seat = seat def get_seat(self): return self._seat # Bet function will be used for betting, raising and calling # because they work the same way. def bet(self, amount): if amount > self._stack: # Returns False if the amount is invalid(more then stack) return False self._stack -= amount self._bet += amount # Returns True if the bet is valid return True def fold(self): self._status = STATUS_FOLDED def reset_bet(self): self._bet = 0 def pay_blind(self, blind_val): if blind_val > self._stack: self._bet += self._stack self._stack = 0 else: self._stack = self._stack - blind_val self._bet += blind_val # The state of the player is an object that is used to # pass to other players to determine possible actions def get_state(self): return { "status": self._status, "stack": self._stack, "bet": self._bet }
#!/usr/bin/python import socket from struct import pack, unpack PROTOCOL_VERSION = 0x200 TYPE_BOOL = 0 TYPE_NUMBER = 1 TYPE_STRING = 2 TYPE_BOOL_ARRAY = 16 TYPE_NUMBER_ARRAY = 17 TYPE_STRING_ARRAY = 18 MSG_NOOP = 0 MSG_HELLO = 1 MSG_UNSUPPORTED = 2 MSG_HELLO_COMPLETE = 3 MSG_ASSIGN = 16 MSG_UPDATE = 17 class NetworkTablesClient(object): def __init__(self, server, port=1735, debug=False): self.server = server self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((server, port)) self.sock.settimeout(1) self.tables = {} self.debug = debug self.sendHello() def __iter__(self): return iter([[x[0], x[2]] for x in self.tables.values()]) def send(self, data): self.sock.send(data) def sendHello(self): if self.debug: print "Sending Hello" self.send(pack(">bH", 1, PROTOCOL_VERSION)) def _recv(self, count): buf = "" for i in range(0, count): buf += self.sock.recv(1) return buf def readType(self, entry_type): if entry_type == TYPE_BOOL: value = self._readBool() elif entry_type == TYPE_NUMBER: value = self._readNumber() elif entry_type == TYPE_STRING: value = self._readString() elif entry_type == TYPE_BOOL_ARRAY: value = self._readBoolArray() elif entry_type == TYPE_NUMBER_ARRAY: value = self._readNumberArray() elif entry_type == TYPE_STRING_ARRAY: value = self._readStringArray() else: value = None return value def process(self): first_byte = ord(self._recv(1)) if self.debug: print "First byte: %d" % first_byte if first_byte == MSG_NOOP: pass elif first_byte == MSG_HELLO: version = unpack(">H", self._recv(2))[0] if self.debug: print "Hello from client: version %d. Why is client receiving Hello?" % version elif first_byte == MSG_UNSUPPORTED: version = unpack(">H", self._recv(2))[0] if self.debug: print "Unsupported version, supports %d" % version elif first_byte == MSG_HELLO_COMPLETE: if self.debug: print "Hello complete." elif first_byte == MSG_ASSIGN: bytes_to_read = unpack(">H", self._recv(2))[0] data = self._recv(bytes_to_read) entry_type, entry_id, seq_num = unpack(">BHH", self._recv(5)) value = self.readType(entry_type) self.tables[entry_id] = [data, entry_type, value] elif first_byte == MSG_UPDATE: entry_id, seq_num = unpack(">HH", self._recv(4)) if self.debug: print "Update (%d)" % entry_id name, entry_type = self.tables[entry_id][:2] value = self.readType(entry_type) self.tables[entry_id] = [name, entry_type, value] else: if self.debug: print "Unknown value %d" % first_byte def _readBool(self): return unpack(">?", self._recv(1))[0] def _readNumber(self): return unpack(">d", self._recv(8))[0] def _readString(self): length = unpack(">H", self._recv(2))[0] return self._recv(length) def _readBoolArray(self): length = unpack(">B", self._recv(1))[0] data = [] for i in range(0, length): data.append(self._readBool()) return data def _readNumberArray(self): length = unpack(">B", self._recv(1))[0] data = [] for i in range(0, length): data.append(self._readNumber()) return data def _readStringArray(self): length = unpack(">B", self._recv(1))[0] data = [] for i in range(0, length): data.append(self._readString()) return data if __name__ == "__main__": import sys nt = NetworkTablesClient(sys.argv[1]) old = {} while 1: nt.process() new = dict(nt) for i in new: if i not in old or old[i] != new[i]: print "------" print i, new[i] old[i] = new[i]
# Scope of variables coeff = 1.0 def apply(params): data = [] for elem in params: data.append(coeff * elem) return data def apply2(params): coeff = 0.8 data = [] for elem in params: data.append(coeff * elem) return data def apply3(params): global coeff data = [] for elem in params: data.append(coeff * elem) return data def apply4(params): coeff = 0.8 def change(p): #coeff = 0.6 nonlocal coeff #global coeff data = [] for elem in p: data.append(coeff * elem) return data return change(params) # ------------------------------------ res = apply4([100, 200, 300, 400]) print('RESULT: ', res)
from django import forms from django.contrib.auth.models import User from .models import * from .views import * from django.forms import ModelForm class clientesForm(ModelForm): class Meta: model = Cliente fields = '__all__' class empresaForm(ModelForm): class Meta: model = Empresa fields = ['NombreEmpresa', 'Razon_Social', 'Email', 'RFC', 'Domicilio', 'Colonia', 'CP', 'Ciudad', 'Estado'] class sucursalForm(ModelForm): class Meta: model = Sucursal exclude = ['Empresa']
#!/usr/bin/env python # coding=utf-8 # 配置数据库信息,mongo只用来存储题目 MONGO_URI = 'mongodb://localhost:27017/' MONGO_DATABASE = 'makinami' # 支持OJ列表 OJS = [ 'poj', ]
""" Virtual Tic-Tac-Toe Board """ from __future__ import annotations from dataclasses import dataclass, field from typing import Optional, List, Tuple __all__ = ['TTTBoard', 'EMPTY', 'PLAYERX', 'PLAYERO', 'DRAW', 'STRMAP', 'switch_player'] # Constants EMPTY = 0 PLAYERX = 1 PLAYERO = 2 DRAW = 3 # Map player constants to letters for printing STRMAP = {PLAYERX: 'X', PLAYERO: 'O', EMPTY: ' '} @dataclass class TTTBoard: """A class representing TTT board. """ # === Private Attributes === # _dim: # The dimension of the board. # _custom_board: # A 2D list representing a pre-made game board to be loaded. # _board: # A 2D list representing the current game board. _dim: int _custom_board: Optional[list] = None _board: list = field(init=False) def __post_init__(self) -> None: """Initialize any variables that requires other var to be initialized. """ if self._custom_board is None: # Create empty board self._board = [[EMPTY for _ in range(self._dim)] for _ in range(self._dim)] else: # Copy board grid self._board = [ [self._custom_board[row][col] for col in range(self._dim)] for row in range(self._dim) ] def __str__(self) -> str: """Human readable representation of the board. """ rep = "" for row in range(self._dim): for col in range(self._dim): rep += STRMAP[self._board[row][col]] if col == self._dim - 1: rep += "\n" else: rep += " | " if row != self._dim - 1: rep += "-" * (4 * self._dim - 3) rep += "\n" return rep def get_dim(self) -> int: """Return the dimension of the board """ return self._dim def get_square(self, row: int, col: int) -> int: """Returns one of the three constants EMPTY, PLAYERX, or PLAYERO that correspond to the contents of the board at position (row, col). """ return self._board[row][col] def get_empty_squares(self) -> List[Tuple[int, int]]: """Return a list of (row, col) tuples for all empty squares """ empty = [] for row in range(self._dim): for col in range(self._dim): if self._board[row][col] == EMPTY: empty.append((row, col)) return empty def move(self, row: int, col: int, player: int) -> None: """Place player on the board at position (row, col). Player should be either the constant PLAYERX or PLAYERO. Does nothing if board square is not empty. """ if self._board[row][col] == EMPTY: self._board[row][col] = player def check_win(self) -> Optional[int]: """Returns a constant associated with the state of the game If PLAYERX wins, returns PLAYERX. If PLAYERO wins, returns PLAYERO. If game is drawn, returns DRAW. If game is in progress, returns None. """ board = self._board dim = self._dim lines = [] # rows lines.extend(board) # columns cols = [[board[row][col] for row in range(dim)] for col in range(dim)] lines.extend(cols) # diagonals diag1 = [board[idx][idx] for idx in range(dim)] diag2 = [board[idx][dim - idx - 1] for idx in range(dim)] lines.append(diag1) lines.append(diag2) # check all lines for line in lines: if len(set(line)) == 1 and line[0] != EMPTY: return line[0] # no winner, check for draw if len(self.get_empty_squares()) == 0: return DRAW # game is still in progress return None def clone(self) -> TTTBoard: """Return a copy of the board """ return TTTBoard(self._dim, self._board) def switch_player(player: int) -> int: """Convenience function to switch players. Returns other player. """ if player == PLAYERX: return PLAYERO else: return PLAYERX
class Solution: def buildTree(self, preorder, inorder): if not preorder or not inorder: return None root = TreeNode(preorder[0]) idx = inorder.index(preorder[0]) preorder.remove(preorder[0]) root.left = self.buildTree(preorder, inorder[:idx]) root.right = self.buildTree(preorder, inorder[idx+1:]) return root
import csv from flask_hello_world_app import db, STDcodes f = open("Std.csv") csv_f = csv.reader(f) db.create_all() i = 0 for row in csv_f: STDcode = STDcodes(stdcode=int(row[0]), city= row[1], state=row[2]) db.session.add(STDcode) db.session.commit() print(i) i += 1 f.close()
from time import sleep from datetime import date #INTRODUÇÃO DE CABEÇALHO sleep(1) print('\n') print('-=' *31 ) data_atual = date.today() data_em_texto = data_atual.strftime('%d/%m/%Y') print('PROTÓTIPO SIMPLIFICADO DE CONSULTA JURÍDICA, RIO, {}.'.format(data_em_texto)) print('-=' *31 ) #INTRODUÇÃO DIDÁTICA sleep(2) print('\n') print('============ TERMINAL INTERATIVO ============') sleep(1) print('\n====== CONSTITUIÇÃO FEDERAL - ARTIGO 5º ======') sleep(2) print('\n<<< ATENÇÃO >>> \n\nO CONTEÚDO AQUI DISPOSTO RESUME E \nEXPLICA DIDATICAMENTE O TEXTO ORIGINAL.\n') sleep(1) print('-=' * 22) print('\nAvaliação e revisão retirada de "Direito \nconstitucional descomplicado":') sleep(1) print('16 ed. rev., atual. e ampl. Rio de Janeiro: \nForense; São Paulo: Método, 2017.') sleep(1) print('\n\npor PAULO, V.; ALEXANDRINO, M.') sleep(1) print('-=' * 22) sleep(2) #MENU DE CONSULTA print('\n<<<< Referente a disposição dos artigos e incisos, escolha o conteúdo. >>>>\n') sleep(3) print('''Leia sobre:\n [ 0 ] DEFINIÇÃO DO ARTIGO 5º [ 1 ] INCISO I [ 2 ] INCISO II [ 3 ] INCISO III [ 4 ] INCISO IV [ 5 ] INCISO V [ 6 ] INCISO VI [ 7 ] INCISO VII [ 8 ] INCISO VIII [ 9 ] FAZER UMA AVALIAÇÃO DESTA APLICAÇÃO ''') sleep(1) menu = int(input('>>> SUA ESCOLHA: ')) print('-=' * 22) sleep(1) #RETORNANDO CONSULTA if menu == 0: print(''' Todos são iguais perante a lei, sem distinção de qualquer natureza, garantindo-se aos brasileiros e aos estrangeiros residentes no País a inviolabilidade do direito à vida, à liberdade, à igualdade, à segurança e à propriedade, nos termos seguintes: A despeito da literalidade do artigo, que indica serem os direitos fundamentais destinados apenas aos brasileiros e aos estrangeiros residentes no país, Paulo e Alexandrino (2017) indicam que o entendimento majoritário é o de que estrangeiros não residentes também fazem jus aos direitos em questão. O caput enumera cinco direitos fundamentais como ponto de partida. A doutrina entende que desses direitos decorrem os que seguem, constantes dos incisos do artigo. Sobre o direito à vida e à igualdade vale fazer algumas observações. VIDA Antes de mais nada, cabe ressaltar que o direito à vida não é absoluto. Muitas questões de concurso levam o candidato a afirmar o contrário a respeito desse direito fundamental. A própria CF prevê, porém, a possibilidade de que o Estado tire a vida de um indivíduo por ter praticado crime militar em caso de guerra declarada em outro inciso do Art. 5º. Veja: XLVII - não haverá penas: A de morte, salvo em caso de guerra declarada, nos termos do art. 84, XIX; A morte, nesse caso, deverá ser levada a cabo por fuzilamento. Pelo princípio da vedação ao retrocesso, impede-se que sejam criadas novas hipóteses de pena de morte no país. Isso se reflete nas obrigações com as quais o Brasil se comprometeu por meio de tratados também. Não se esqueça dessa exceção! Ainda sobre o direito à vida, alguns detalhes muito cobrados em provas: O direito à vida compreende a existência intrauterina e extrauterina. As hipóteses de aborto são apenas aquelas sobre as quais o legislador expressamente se manifestou. O feto anencéfalo é considerado biologicamente vivo, mas juridicamente morto, segundo o STF, por ser inviável. Dessa forma, é possível interromper a gravidez também nessa hipótese. Para saber mais a respeito, pesquise o teor da decisão prolatada nos autos da ADPF 54; Há uma dupla acepção do direito à vida que deve ser considerada: o direito de permanecer vivo importa tanto quanto o direito de ter uma vida digna. O Estado deve envidar esforços para garantir a todos uma existência pautada na dignidade da pessoa humana, que a maioria da doutrina considera como o valor central do ordenamento jurídico brasileiro e está prevista no Art. 1º, III, CF. IGUALDADE É necessário entender a igualdade também sob um viés duplo. A igualdade formal diz respeito à equiparação de todas as pessoas no que diz respeito aos direitos e garantias. A igualdade material diz respeito a entender que certos grupos de pessoas, por motivos históricos, sociais e econômicos não têm acesso aos direitos da mesma forma que as demais. O legislador não pode ignorar essas disparidades enraizadas na sociedade brasileira, devendo prever, sempre de maneira razoável, condições diferentes a fim de nivelar minimamente as condições de vida dessas minorias em relação às gozadas pelas demais pessoas. O direito à igualdade deve pautar a conduta do legislador, que não pode criar hipóteses que tragam tratamento diverso a quem está em igualdade de condições - a chamada igualdade na lei. Também deve ser objetivo do aplicador do direito concretizar o direito em questão, privilegiando a interpretação das normas de forma a não criar situação anti-isonômica no caso concreto. Nesse último caso, estamos diante da obrigação de observar a igualdade perante a lei. Sobre o tema, é importante levar em conta os precedentes do STF que consideram constitucionais as cotas raciais em concursos públicos e vestibulares (ADC 41 e RE 597.285); o programa que concede bolsas para cursos de graduação em universidades privadas, visando à diminuição da desigualdade social no país (ADI 3.330) e critérios de diferença de idade para fins de inscrição em concurso público (Súmula 683). ''') elif menu == 1: print(''' INCISO I - Homens e mulheres são iguais em direitos e obrigações, nos termos desta Constituição; A igualdade é um dos pilares do ordenamento jurídico brasileiro. Como visto acima, a igualdade deve ser alcançada a partir da conjugação das duas acepções - a formal e a material. Dessa forma, a ressalva inscrita no inciso "nos termos desta Constituição" faz referência a direitos e deveres previstos de forma diferente para cada qual dos diversos grupos que compõem a sociedade brasileira. Cite-se como exemplo o tratamento distinto previsto no próprio texto constitucional, a respeito da necessidade de incentivar a integração da mulher ao mercado de trabalho, como disposto no Art. 7º, XX. ''') elif menu == 2: print(''' INCISO II - Ninguém será obrigado a fazer ou deixar de fazer alguma coisa senão em virtude de lei; Aqui faz-se menção ao princípio da legalidade. Segundo esse princípio, é dado ao particular fazer tudo o que não estiver expressamente proibido pela lei. A doutrina afirma, portanto, que o particular pode agir para além da lei (praeter legem) e segundo a lei (secundum legem). Ao Estado, porém, não é possível agir de maneira diferente da que o legislador impõe, devendo pautar sua conduta segundo a lei. O respeito à lei imposto ao Estado deve ser entendido como o respeito ao ordenamento jurídico como um todo. No âmbito do Direito Administrativo, conclui-se que o alargamento decorrente desse entendimento restringe bastante a atuação da Administração. Decorrem do princípio da legalidade outros dois: o princípio da anterioridade e o princípio da reserva legal. O primeiro dos referidos corolários define que as condutas sociais devem ser pautadas por leis previamente existentes no ordenamento jurídico. É estudado com mais profundidade no âmbito do Direito Penal. Existem diversas exceções a esse princípio, notadamente as que dizem respeito à retroatividade da lei penal mais benéfica para o réu, prevista no inciso do Art. 5º, XL, CF. A Lindb, entre outras normas, trata de aspectos relativos à aplicação das leis no tempo. O princípio da reserva legal impõe que algumas matérias só podem ser regulamentadas por meio de lei formal, excluindo-se qualquer outra espécie de norma. O processo legislativo compreende regras específicas, que devem ser observadas para que a lei que dele resulte produza regularmente seus efeitos. A lei que não segue o rito deve ser considerada formalmente inconstitucional, vício também conhecido como inconstitucionalidade nomodinâmica. Essas regras, que variam de acordo com a espécie de norma editada, foram estabelecidas com o objetivo de garantir que as normas resultantes desse processo de fato reflitam a vontade da população, externada pelos parlamentares eleitos pelo povo. Algumas matérias são consideradas importantes demais para prescindirem desse procedimento, motivo pelo qual se sujeitam à reserva legal. A doutrina diferencia a reserva legal qualificada da simples. Na primeira hipótese, exige-se que se defina previamente o conteúdo da lei e a finalidade específica do ato. O segundo caso diz respeito à mera obrigatoriedade de que a norma regulamentadora seja lei formal, sem que se estabeleça seu conteúdo ou sua finalidade. ''') elif menu == 3: print(''' INCISO III - Ninguém será submetido a tortura nem a tratamento desumano ou degradante; A literalidade do inciso já passa a ideia completa do dispositivo. Não seria possível que o Estado Brasileiro deixasse de se comprometer com o combate a tais práticas, o que faz criminalizando tais condutas e atuando para impedir que elas ocorram. ''') elif menu == 4: print(''' INCISO IV - É livre a manifestação do pensamento, sendo vedado o anonimato; Aqui o constituinte consagrou o direito à liberdade de expressão. Lembre-se bem da parte final do inciso, que demonstra que as opiniões expressas sem identificação do emissor da mensagem não estão compreendidas entre as manifestações protegidas pelo direito em questão. A vedação ao anonimato aparece em muitas questões de Direito Constitucional. O Supremo, ao julgar o HC 82.424, tornou evidente que a liberdade de expressão não abrange o discurso de ódio, postulando que o direito fundamental à livre manifestação do pensamento não pode ser meio para a prática de crimes previstos no ordenamento. Sobre o tema, é importante destacar ainda que a liberdade de expressão não exime o emissor da mensagem de indenizar quem quer que tenha sido lesado com o que foi dito. A busca pela reparação deverá ser feita de acordo com o que dispõe a lei. ''') elif menu == 5: print(''' INCISO V - É assegurado o direito de resposta, proporcional ao agravo, além da indenização por dano material, moral ou à imagem; O direito de resposta previsto nesse inciso exige que se verifique no caso concreto que a ofensa foi repelida pelo ofendido pelo mesmo meio de comunicação, tamanho ou duração, sendo necessário que seja dado o mesmo destaque que teve a ofensa. A compensação por dano material, moral ou à imagem foi trazida pelo constituinte de forma independente do direito de resposta. Não há motivo para dúvida: se a questão mencionar uma suposta necessidade de exercer o direito de resposta para buscar indenização por uma ofensa, ou, em sentido diverso, indicar que quem exerce o direito de resposta fica impossibilitado de buscar reparação pelo dano sofrido por outras vias, é sinal de que a banca do seu concurso está subvertendo a disposição do inciso V. Essa dica é para nunca mais errar! ''') elif menu == 6: print(''' INCISO VI - É inviolável a liberdade de consciência e de crença, sendo assegurado o livre exercício dos cultos religiosos e garantida, na forma da lei, a proteção aos locais de culto e a suas liturgias. ''') elif menu == 7: print(''' INCISO VII - É assegurada, nos termos da lei, a prestação de assistência religiosa nas entidades civis e militares de internação coletiva; ''') elif menu == 8: print(''' INCISO VIII - Ninguém será privado de direitos por motivo de crença religiosa ou de convicção filosófica ou política, salvo se as invocar para eximir-se de obrigação legal a todos imposta e recusar-se a cumprir prestação alternativa, fixada em lei; Sobre a liberdade de crença, o constituinte considerou muito importante explicitar a forma como deve ser garantido o exercício de tal prerrogativa fundamental. A importância dada à liberdade religiosa é tamanha que é o fundamento para a imunidade tributária concedida aos templos de qualquer culto, presente no Art. 150, VI, "b" da CF. Art. 150. Sem prejuízo de outras garantias asseguradas ao contribuinte, é vedado à União, aos Estados, ao Distrito Federal e aos Municípios: Instituir impostos sobre: Templos de qualquer culto; A prestação de assistência religiosa a que faz referência o inciso VII é de caráter privado. Não confunda o compromisso do Estado de garantir o acesso à assistência religiosa com a assunção de uma responsabilidade por parte do Estado de oferecê-la por meio da atuação de seus órgãos e agentes. Considere a disposição constitucional a seguir e perceba que uma interpretação nesse sentido não seria compatível com o que a Carta da República estabelece. Art. 19. É vedado à União, aos Estados, ao Distrito Federal e aos Municípios: Estabelecer cultos religiosos ou igrejas, subvencioná-los, embaraçar-lhes o funcionamento ou manter com eles ou seus representantes relações de dependência ou aliança, ressalvada, na forma da lei, a colaboração de interesse público; O inciso VIII trata da escusa de consciência. Assim, ninguém deve ser submetido a cumprir uma obrigação legal que vá de encontro as suas convicções religiosas, morais ou filosóficas. Porém, se a lei previr uma obrigação alternativa a ser exigida nesses casos, deixar de cumpri-la poderá acarretar privação de direitos. Perceba que se trata de norma de eficácia contida: enquanto o legislador não regular a hipótese, prevendo as mencionadas obrigações alternativas, não poderá restringir qualquer direito de quem se declarar impossibilitado de cumprir com obrigação imposta a todos. ''') elif menu == 9: sleep(2) av = int(input('Digite uma nota de 0 a 10 para esta aplicação: ')) sleep(1) comment = str(input('Deixe seu comentário ou tecle ENTER para continuar: ')) sleep(1) print('Obrigado por utilizar nosso protótipo, sua avaliação {} foi computada com sucesso.\nMuito obrigado!'.format(av)) else: print('Opção inválida')