signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def __init__(self, max_size=<NUM_LIT> * <NUM_LIT>): | self.max_size = max_size<EOL>self.queue = Queue()<EOL>self.received_bytes = self.queue.put_nowait<EOL>self.synchronizing = False<EOL>self.residual = b'<STR_LIT>'<EOL> | max_size - an anti-DoS measure. If, after processing an incoming message, buffered
data would exceed max_size bytes, that buffered data is dropped entirely and the
framer waits for a newline character to re-synchronize the stream.
Set to zero to not limit the buffer size. | f5364:c1:m0 |
def __init__(self,<EOL>jvm_started=False,<EOL>parse_datetime=False,<EOL>minimum_heap_size='<STR_LIT>',<EOL>maximum_heap_size='<STR_LIT>'): | self.parse_datetime = parse_datetime<EOL>self._is_loaded = False<EOL>self._lock = threading.Lock()<EOL>if not jvm_started:<EOL><INDENT>self._classpath = self._create_classpath()<EOL>self._start_jvm(minimum_heap_size, maximum_heap_size)<EOL><DEDENT>try:<EOL><INDENT>if threading.activeCount() > <NUM_LIT:1>:<EOL><INDENT>i... | Initializes Duckling. | f5372:c0:m0 |
def load(self, languages=[]): | duckling_load = self.clojure.var("<STR_LIT>", "<STR_LIT>")<EOL>clojure_hashmap = self.clojure.var("<STR_LIT>", "<STR_LIT>")<EOL>clojure_list = self.clojure.var("<STR_LIT>", "<STR_LIT:list>")<EOL>if languages:<EOL><INDENT>iso_languages = [Language.convert_to_iso(lang) for lang in languages]<EOL>duckling_load.invoke(<EOL... | Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"]) | f5372:c0:m3 |
def parse(self, input_str, language=Language.ENGLISH, dim_filter=None, reference_time='<STR_LIT>'): | if self._is_loaded is False:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>')<EOL><DEDENT>if threading.activeCount() > <NUM_LIT:1>:<EOL><INDENT>if not jpype.isThreadAttachedToJVM():<EOL><INDENT>jpype.attachThreadToJVM()<EOL><DEDENT><DEDENT>language = Language.convert_to_duckling_language_id(language)<EOL>duckling_parse... | Parses datetime information out of string input.
It invokes the Duckling.parse() function in Clojure.
A language can be specified, default is English.
Args:
input_str: The input as string that has to be parsed.
language: Optional parameter to specify language,
... | f5372:c0:m4 |
@classmethod<EOL><INDENT>def is_supported(cls, lang):<DEDENT> | return lang in cls.SUPPORTED_LANGUAGES<EOL> | Check if a language is supported by the current duckling version. | f5374:c0:m0 |
@classmethod<EOL><INDENT>def convert_to_duckling_language_id(cls, lang):<DEDENT> | if lang is not None and cls.is_supported(lang):<EOL><INDENT>return lang<EOL><DEDENT>elif lang is not None and cls.is_supported(lang + "<STR_LIT>"): <EOL><INDENT>return lang + "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>lang, "<STR_LIT:U+002CU+0020>".join(cls.SUPPORTED_LANGUAGES)... | Ensure a language identifier has the correct duckling format and is supported. | f5374:c0:m1 |
def parse(self, input_str, reference_time='<STR_LIT>'): | return self._parse(input_str, reference_time=reference_time)<EOL> | Parses input with Duckling for all dims.
Args:
input_str: An input string, e.g. 'You owe me twenty bucks, please
call me today'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling outpu... | f5375:c0:m10 |
def parse_time(self, input_str, reference_time='<STR_LIT>'): | return self._parse(input_str, dim=Dim.TIME,<EOL>reference_time=reference_time)<EOL> | Parses input with Duckling for occurences of times.
Args:
input_str: An input string, e.g. 'Let's meet at 11:45am'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
... | f5375:c0:m11 |
def parse_timezone(self, input_str): | return self._parse(input_str, dim=Dim.TIMEZONE)<EOL> | Parses input with Duckling for occurences of timezones.
Args:
input_str: An input string, e.g. 'My timezone is pdt'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"timezone"... | f5375:c0:m12 |
def parse_temperature(self, input_str): | return self._parse(input_str, dim=Dim.TEMPERATURE)<EOL> | Parses input with Duckling for occurences of temperatures.
Args:
input_str: An input string, e.g. 'Let's change the temperature from
thirty two celsius to 65 degrees'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:... | f5375:c0:m13 |
def parse_number(self, input_str): | return self._parse(input_str, dim=Dim.NUMBER)<EOL> | Parses input with Duckling for occurences of numbers.
Args:
input_str: An input string, e.g. 'I'm 25 years old'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"number",
... | f5375:c0:m14 |
def parse_ordinal(self, input_str): | return self._parse(input_str, dim=Dim.ORDINAL)<EOL> | Parses input with Duckling for occurences of ordinals.
Args:
input_str: An input string, e.g. 'I'm first, you're 2nd'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"ordinal... | f5375:c0:m15 |
def parse_distance(self, input_str): | return self._parse(input_str, dim=Dim.DISTANCE)<EOL> | Parses input with Duckling for occurences of distances.
Args:
input_str: An input string, e.g. 'I commute 5 miles everyday'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"d... | f5375:c0:m16 |
def parse_volume(self, input_str): | return self._parse(input_str, dim=Dim.VOLUME)<EOL> | Parses input with Duckling for occurences of volumes.
Args:
input_str: An input string, e.g. '1 gallon is 3785ml'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"volume",
... | f5375:c0:m17 |
def parse_money(self, input_str): | return self._parse(input_str, dim=Dim.AMOUNTOFMONEY)<EOL> | Parses input with Duckling for occurences of moneys.
Args:
input_str: An input string, e.g. 'You owe me 10 dollars'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"amount-of... | f5375:c0:m18 |
def parse_duration(self, input_str): | return self._parse(input_str, dim=Dim.DURATION)<EOL> | Parses input with Duckling for occurences of durations.
Args:
input_str: An input string, e.g. 'I ran for 2 hours today'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"dura... | f5375:c0:m19 |
def parse_email(self, input_str): | return self._parse(input_str, dim=Dim.EMAIL)<EOL> | Parses input with Duckling for occurences of emails.
Args:
input_str: An input string, e.g. 'Shoot me an email at
[email protected]'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
... | f5375:c0:m20 |
def parse_url(self, input_str): | return self._parse(input_str, dim=Dim.URL)<EOL> | Parses input with Duckling for occurences of urls.
Args:
input_str: An input string, e.g. 'http://frank-blechschmidt.com is
under construction, but you can check my github
github.com/FraBle'.
Returns:
A preprocessed list of results (dicts) from D... | f5375:c0:m21 |
def parse_phone_number(self, input_str): | return self._parse(input_str, dim=Dim.PHONENUMBER)<EOL> | Parses input with Duckling for occurences of phone numbers.
Args:
input_str: An input string, e.g. '424-242-4242 is obviously a fake
number'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
... | f5375:c0:m22 |
def parse_leven_product(self, input_str): | return self._parse(input_str, dim=Dim.LEVENPRODUCT)<EOL> | Parses input with Duckling for occurences of products.
Args:
input_str: An input string, e.g. '5 cups of sugar'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim": "leven-produc... | f5375:c0:m23 |
def parse_leven_unit(self, input_str): | return self._parse(input_str, dim=Dim.LEVENUNIT)<EOL> | Parses input with Duckling for occurences of leven units.
Args:
input_str: An input string, e.g. 'two pounds of meat'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim": "leven-... | f5375:c0:m24 |
def parse_quantity(self, input_str): | return self._parse(input_str, dim=Dim.QUANTITY)<EOL> | Parses input with Duckling for occurences of quantities.
Args:
input_str: An input string, e.g. '5 cups of sugar'.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim": "quantity",... | f5375:c0:m25 |
def parse_cycle(self, input_str): | return self._parse(input_str, dim=Dim.CYCLE)<EOL> | Parses input with Duckling for occurences of cycles.
Args:
input_str: An input string, e.g. 'coming week'.
Returns:
A preprocessed list of results (dicts) from Duckling output. | f5375:c0:m26 |
def parse_unit(self, input_str): | return self._parse(input_str, dim=Dim.UNIT)<EOL> | Parses input with Duckling for occurences of units.
Args:
input_str: An input string, e.g. '6 degrees outside'.
Returns:
A preprocessed list of results (dicts) from Duckling output. | f5375:c0:m27 |
def parse_unit_of_duration(self, input_str): | return self._parse(input_str, dim=Dim.UNITOFDURATION)<EOL> | Parses input with Duckling for occurences of units of duration.
Args:
input_str: An input string, e.g. '1 second'.
Returns:
A preprocessed list of results (dicts) from Duckling output. | f5375:c0:m28 |
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,<EOL>retry_log_level=logging.INFO,<EOL>retry_log_message="<STR_LIT>"<EOL>"<STR_LIT>",<EOL>max_failures=None, interval=<NUM_LIT:0>,<EOL>max_failure_log_level=logging.ERROR,<EOL>max_failure_log_message="<STR_LIT>"): | exc_classes = tuple(exc_classes)<EOL>@wraps(f)<EOL>def deco(*args, **kwargs):<EOL><INDENT>failures = <NUM_LIT:0><EOL>while True:<EOL><INDENT>try:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT>except exc_classes as e:<EOL><INDENT>if logger is not None:<EOL><INDENT>logger.log(retry_log_level,<EOL>retry_log_message.fo... | Decorator to automatically reexecute a function if the connection is
broken for any reason. | f5378:m0 |
def _new_connection(self): | raise NotImplementedError<EOL> | Estabilish a new connection (to be implemented in subclasses). | f5378:c0:m1 |
def _keepalive(self, c): | raise NotImplementedError()<EOL> | Implement actual application-level keepalive (to be
reimplemented in subclasses).
:raise: socket.error if the connection has been closed or is broken. | f5378:c0:m2 |
@contextmanager<EOL><INDENT>def get(self):<DEDENT> | self.lock.acquire()<EOL>try:<EOL><INDENT>c = self.conn.popleft()<EOL>yield c<EOL><DEDENT>except self.exc_classes:<EOL><INDENT>gevent.spawn_later(<NUM_LIT:1>, self._addOne)<EOL>raise<EOL><DEDENT>except:<EOL><INDENT>self.conn.append(c)<EOL>self.lock.release()<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>self.conn.append(c)<EO... | Get a connection from the pool, to make and receive traffic.
If the connection fails for any reason (socket.error), it is dropped
and a new one is scheduled. Please use @retry as a way to automatically
retry whatever operation you were performing. | f5378:c0:m5 |
def timeparse(sval): | match = re.match(r'<STR_LIT>' + TIMEFORMAT + r'<STR_LIT>', sval, re.I)<EOL>if not match or not match.group(<NUM_LIT:0>).strip():<EOL><INDENT>return<EOL><DEDENT>mdict = match.groupdict()<EOL>return sum(<EOL>MULTIPLIERS[k] * cast(v) for (k, v) in mdict.items() if v is not None)<EOL> | Parse a time expression, returning it as a number of seconds. If
possible, the return value will be an `int`; if this is not
possible, the return will be a `float`. Returns `None` if a time
expression cannot be parsed from the given string.
Arguments:
- `sval`: the string value to parse
>>> ti... | f5380:m1 |
def out_path_of(self, in_path): | raise Exception("<STR_LIT>")<EOL> | given the input path of a file, return the ouput path | f5383:c0:m1 |
def compile_file(self, path): | raise Exception("<STR_LIT>")<EOL> | given the path of a file, compile it and return the result | f5383:c0:m2 |
@capture_exception<EOL><INDENT>@zip_with_output(skip_args=[<NUM_LIT:0>])<EOL>def compile_and_process(self, in_path):<DEDENT> | out_path = self.path_mapping[in_path]<EOL>if not self.embed:<EOL><INDENT>pdebug("<STR_LIT>" % (<EOL>self.compiler_name,<EOL>self.name,<EOL>os.path.relpath(in_path),<EOL>os.path.relpath(out_path)),<EOL>groups=["<STR_LIT>"],<EOL>autobreak=True)<EOL><DEDENT>else:<EOL><INDENT>pdebug("<STR_LIT>" % (<EOL>self.compiler_name,<... | compile a file, save it to the ouput file if the inline flag true | f5383:c0:m3 |
def collect_output(self): | if self.embed:<EOL><INDENT>if self.concat:<EOL><INDENT>concat_scripts = [self.compiled_scripts[path]<EOL>for path in self.build_order]<EOL>return [self.embed_template_string % '<STR_LIT:\n>'.join(concat_scripts)]<EOL><DEDENT>else:<EOL><INDENT>return [self.embed_template_string %<EOL>self.compiled_scripts[path]<EOL>for ... | helper function to gather the results of `compile_and_process` on
all target files | f5383:c0:m4 |
def build(self): | if not self.embed:<EOL><INDENT>mkdir_recursive(self.output_directory)<EOL><DEDENT>self.build_order = remove_dups(<EOL>reduce(lambda a, b: a + glob.glob(b),<EOL>self.build_targets,<EOL>[]))<EOL>self.build_order_output = [self.out_path_of(t)<EOL>for (t) in self.build_order]<EOL>self.path_mapping = dict(zip(<EOL>self.buil... | build the scripts and return a string | f5383:c0:m5 |
def update_build(self, updated_files): | for f in updated_files:<EOL><INDENT>self.compiled_scripts[f] = self.compile_and_process(f)<EOL><DEDENT>return self.collect_output()<EOL> | updates a build based on updated files
TODO implement this pls | f5383:c0:m6 |
def print_helptext(): | pout("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % sys.argv[<NUM_LIT:0>])<EOL> | print helptext for command-line interface | f5387:m0 |
def main(): | options = None<EOL>try:<EOL><INDENT>options, args = getopt.gnu_getopt(<EOL>sys.argv[<NUM_LIT:1>:],<EOL>"<STR_LIT>",<EOL>["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"])<EOL><DEDENT>except getopt.GetoptError as e:<EOL><INDENT>print(e)<EOL>print_helptext()<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>should_watch = False<EOL>q... | parse command line opts and run a skeleton file
when called from the command line, ligament looks in the current
working directory for a file called `skeleton.py`. Tasks specified from
the command line are then executed in order, and if the -w flag was
specified, ligament then watches ... | f5387:m1 |
def partition(pred, iterable): | trues = []<EOL>falses = []<EOL>for item in iterable:<EOL><INDENT>if pred(item):<EOL><INDENT>trues.append(item)<EOL><DEDENT>else:<EOL><INDENT>falses.append(item)<EOL><DEDENT><DEDENT>return trues, falses<EOL> | split the results of an iterable based on a predicate | f5388:m0 |
def zip_with_output(skip_args=[]): | def decorator(fn):<EOL><INDENT>def wrapped(*args, **vargs):<EOL><INDENT>g = [arg for i, arg in enumerate(args) if i not in skip_args]<EOL>if len(g) == <NUM_LIT:1>:<EOL><INDENT>return(g[<NUM_LIT:0>], fn(*args, **vargs))<EOL><DEDENT>else:<EOL><INDENT>return (g, fn(*args, **vargs))<EOL><DEDENT><DEDENT>return wrapped<EOL><... | decorater that zips the input of a function with its output
only zips positional arguments.
skip_args : list
a list of indexes of arguments to exclude from the skip
@zip_with_output(skip_args=[0])
def foo(bar, baz):
return baz
will decorate... | f5388:m1 |
def capture_exception(fn): | def wrapped(*args):<EOL><INDENT>try:<EOL><INDENT>return fn(*args)<EOL><DEDENT>except Exception as e:<EOL><INDENT>return e<EOL><DEDENT><DEDENT>return wrapped<EOL> | decorator that catches and returns an exception from wrapped function | f5388:m2 |
def compose(*funcs): | return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)<EOL> | compose a list of functions | f5388:m3 |
def build_lst(a, b): | if type(a) is list:<EOL><INDENT>return a + [b]<EOL><DEDENT>elif a:<EOL><INDENT>return [a, b]<EOL><DEDENT>else:<EOL><INDENT>return b<EOL><DEDENT> | function to be folded over a list (with initial value `None`)
produces one of:
1. `None`
2. A single value
3. A list of all values | f5388:m4 |
def map_over_glob(fn, path, pattern): | return [fn(x) for x in glob.glob(os.path.join(path, pattern))]<EOL> | map a function over a glob pattern, relative to a directory | f5388:m6 |
def mkdir_recursive(dirname): | parent = os.path.dirname(dirname)<EOL>if parent != "<STR_LIT>":<EOL><INDENT>if not os.path.exists(parent):<EOL><INDENT>mkdir_recursive(parent)<EOL><DEDENT>if not os.path.exists(dirname):<EOL><INDENT>os.mkdir(dirname)<EOL><DEDENT><DEDENT>elif not os.path.exists(dirname):<EOL><INDENT>os.mkdir(dirname)<EOL><DEDENT> | makes all the directories along a given path, if they do not exist | f5388:m7 |
def indent_text(*strs, **kwargs): | <EOL>indent = kwargs["<STR_LIT>"] if "<STR_LIT>" in kwargs else"<STR_LIT>"<EOL>autobreak = kwargs.get("<STR_LIT>", False)<EOL>char_limit = kwargs.get("<STR_LIT>", <NUM_LIT>)<EOL>split_char = kwargs.get("<STR_LIT>", "<STR_LIT:U+0020>")<EOL>strs = list(strs)<EOL>if autobreak:<EOL><INDENT>for index, s in enumerate(strs):<... | indents text according to an operater string and a global indentation
level. returns a tuple of all passed args, indented according to the
operator string
indent: [defaults to +0]
The operator string, of the form
++n : increments the global indentation level by n and in... | f5388:m11 |
def perror(*args, **kwargs): | if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT:error>"])):<EOL><INDENT>global colorama_init<EOL>if not colorama_init:<EOL><INDENT>colorama_init = True<EOL>colorama.init()<EOL><DEDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write(colorama.Fore.RED)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr... | print formatted output to stderr with indentation control | f5388:m12 |
def pwarning(*args, **kwargs): | if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT>"])):<EOL><INDENT>global colorama_init<EOL>if not colorama_init:<EOL><INDENT>colorama_init = True<EOL>colorama.init()<EOL><DEDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write(colorama.Fore.YELLOW)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr.wr... | print formatted output to stderr with indentation control | f5388:m13 |
def pdebug(*args, **kwargs): | if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT>"])):<EOL><INDENT>global colorama_init<EOL>if not colorama_init:<EOL><INDENT>colorama_init = True<EOL>colorama.init()<EOL><DEDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write(colorama.Fore.CYAN)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr.writ... | print formatted output to stdout with indentation control | f5388:m14 |
def pout(*args, **kwargs): | if should_msg(kwargs.get("<STR_LIT>", ["<STR_LIT>"])):<EOL><INDENT>args = indent_text(*args, **kwargs)<EOL>sys.stderr.write("<STR_LIT>".join(args))<EOL>sys.stderr.write("<STR_LIT:\n>")<EOL><DEDENT> | print to stdout, maintaining indent level | f5388:m15 |
def urlretrieve(url, dest, write_mode="<STR_LIT:w>"): | response = urllib2.urlopen(url)<EOL>mkdir_recursive(os.path.dirname(dest))<EOL>with open(dest, write_mode) as f:<EOL><INDENT>f.write(response.read())<EOL>f.close()<EOL><DEDENT> | save a file to disk from a given url | f5388:m16 |
def remove_dups(seq): | seen = set()<EOL>seen_add = seen.add<EOL>return [x for x in seq if not (x in seen or seen_add(x))]<EOL> | remove duplicates from a sequence, preserving order | f5388:m17 |
def run_skeleton(skeleton_path, tasks, watch=True): | build_context = load_context_from_skeleton(skeleton_path);<EOL>for task in tasks:<EOL><INDENT>build_context.build_task(task)<EOL><DEDENT>if watch:<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>observer = Observer()<EOL>buildcontexteventhandler = BuildContextFsEventHandler(build_context)<EOL>built_tasks = ((taskname, t... | loads and executes tasks from a given skeleton file
skeleton_path:
path to the skeleton file
tasks:
a list of string identifiers of tasks to be executed
watch:
boolean flag of if the skeleton should be watched for changes and
automatically updat... | f5389:m1 |
def register_with_context(self, myname, context): | if self.context is not None:<EOL><INDENT>raise Exception("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>context.register_task(myname, self)<EOL>self._name = myname<EOL>self.context = context<EOL>for key in self.data_dependencies:<EOL><INDENT>if type(self.data_dependencies[key]) is DeferredDependency:<EOL><INDENT>self.data_de... | registers this build target (exclusively) with a given context | f5390:c0:m3 |
def resolve_dependencies(self): | return dict(<EOL>[((key, self.data_dependencies[key])<EOL>if type(self.data_dependencies[key]) != DeferredDependency<EOL>else (key, self.data_dependencies[key].resolve()))<EOL>for key in self.data_dependencies])<EOL> | evaluate each of the data dependencies of this build target,
returns the resulting dict | f5390:c0:m4 |
def resolve_and_build(self): | pdebug("<STR_LIT>" % self.name,<EOL>groups=["<STR_LIT>"])<EOL>indent_text(indent="<STR_LIT>")<EOL>toret = self.build(**self.resolve_dependencies())<EOL>indent_text(indent="<STR_LIT>")<EOL>return toret<EOL> | resolves the dependencies of this build target and builds it | f5390:c0:m5 |
def build(self): | raise Exception("<STR_LIT>" % type(self))<EOL>pass<EOL> | (abstract) perform some task and return the result.
Also assigns the value f self.file_watch_targets | f5390:c0:m6 |
def update_build(self, changedfiles): | raise Exception("<STR_LIT>" % type(self))<EOL>pass<EOL> | (abstract) updates the task given a list of changed files | f5390:c0:m7 |
def register_dependency(self, data_src, data_sink): | pdebug("<STR_LIT>" % (data_src, data_sink))<EOL>if (data_src not in self._gettask(data_sink).depends_on):<EOL><INDENT>self._gettask(data_sink).depends_on.append(data_src)<EOL><DEDENT>if (data_sink not in self._gettask(data_src).provides_for):<EOL><INDENT>self._gettask(data_src).provides_for.append(data_sink)<EOL><DEDEN... | registers a dependency of data_src -> data_sink
by placing appropriate entries in provides_for and depends_on | f5391:c1:m2 |
def build_task(self, name): | try:<EOL><INDENT>self._gettask(name).value = (<EOL>self._gettask(name).task.resolve_and_build())<EOL><DEDENT>except TaskExecutionException as e:<EOL><INDENT>perror(e.header, indent="<STR_LIT>")<EOL>perror(e.message, indent="<STR_LIT>")<EOL>self._gettask(name).value = e.payload<EOL><DEDENT>except Exception as e:<EOL><IN... | Builds a task by name, resolving any dependencies on the way | f5391:c1:m3 |
def is_build_needed(self, data_sink, data_src): | return (self._gettask(data_src).last_build_time == <NUM_LIT:0> or<EOL>self._gettask(data_src).last_build_time <<EOL>self._gettask(data_sink).last_build_time)<EOL> | returns true if data_src needs to be rebuilt, given that data_sink
has had a rebuild requested. | f5391:c1:m4 |
def verify_valid_dependencies(self): | unobserved_dependencies = set(self.tasks.keys())<EOL>target_queue = []<EOL>while len(unobserved_dependencies) > <NUM_LIT:0>:<EOL><INDENT>target_queue = [unobserved_dependencies.pop()]<EOL>while target_queue is not []:<EOL><INDENT>target_queue += unobserved_dependencies<EOL><DEDENT><DEDENT> | Checks if the assigned dependencies are valid
valid dependency graphs are:
- noncyclic (i.e. no `A -> B -> ... -> A`)
- Contain no undefined dependencies
(dependencies referencing undefined tasks) | f5391:c1:m5 |
def deep_dependendants(self, target): | direct_dependents = self._gettask(target).provides_for<EOL>return (direct_dependents +<EOL>reduce(<EOL>lambda a, b: a + b,<EOL>[self.deep_dependendants(x) for x in direct_dependents],<EOL>[]))<EOL> | Recursively finds the dependents of a given build target.
Assumes the dependency graph is noncyclic | f5391:c1:m6 |
def resolve_dependency_graph(self, target): | targets = self.deep_dependendants(target)<EOL>return sorted(targets,<EOL>cmp=lambda a, b:<EOL><NUM_LIT:1> if b in self.deep_dependendants(a) else<EOL>-<NUM_LIT:1> if a in self.deep_dependendants(b) else<EOL><NUM_LIT:0>)<EOL> | resolves the build order for interdependent build targets
Assumes no cyclic dependencies | f5391:c1:m7 |
def resolve(self): | values = {}<EOL>for target_name in self.target_names:<EOL><INDENT>if self.context.is_build_needed(self.parent, target_name):<EOL><INDENT>self.context.build_task(target_name)<EOL><DEDENT>if len(self.keyword_chain) == <NUM_LIT:0>:<EOL><INDENT>values[target_name] = self.context.tasks[target_name].value<EOL><DEDENT>else:<E... | Builds all targets of this dependency and returns the result
of self.function on the resulting values | f5391:c2:m1 |
def __init__(self, header, *args, **vargs): | self.header = header<EOL>"""<STR_LIT>"""<EOL>if "<STR_LIT>" in vargs:<EOL><INDENT>self.payload = vargs["<STR_LIT>"]<EOL>del vargs["<STR_LIT>"]<EOL><DEDENT>else:<EOL><INDENT>self.payload = Nones<EOL>"""<STR_LIT>"""<EOL><DEDENT>Exception.__init__(self, *args, **vargs)<EOL> | header : str
a short description of the error message
(kwarg) payload : (any)
A value to return in place of a normal return value | f5393:c0:m0 |
def bind_sockets(port, address=None, family=socket.AF_UNSPEC,<EOL>backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False): | if reuse_port and not hasattr(socket, '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>sockets = []<EOL>if not address:<EOL><INDENT>address = None<EOL><DEDENT>if not socket.has_ipv6 and family == socket.AF_UNSPEC:<EOL><INDENT>family = socket.AF_INET<EOL><DEDENT>if flags is None:<EOL><INDENT>flags = s... | Creates listening sockets bound to the given port and address.
Returns a list of socket objects (multiple sockets are returned if
the given address maps to multiple IP addresses, which is most common
for mixed IPv4 and IPv6 use).
Address may be either an IP address or hostname. If it's a hostname,
... | f5394:m4 |
def bind_unix_socket(file_, mode=<NUM_LIT>, backlog=_DEFAULT_BACKLOG): | sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)<EOL>sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, <NUM_LIT:1>)<EOL>sock.setblocking(<NUM_LIT:0>)<EOL>try:<EOL><INDENT>st = os.stat(file_)<EOL><DEDENT>except OSError as err:<EOL><INDENT>if err.errno != errno.ENOENT:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>... | Creates a listening unix socket.
If a socket with the given name already exists, it will be deleted.
If any other file with that name exists, an exception will be
raised.
Returns a socket object (not a list of socket objects like
`bind_sockets`) | f5394:m5 |
def circles_pil(width, height, color): | image = Image.new("<STR_LIT>", (width, height), color=None)<EOL>draw = ImageDraw.Draw(image)<EOL>draw.ellipse((<NUM_LIT:0>, <NUM_LIT:0>, width - <NUM_LIT:1>, height - <NUM_LIT:1>), fill=color)<EOL>image.save('<STR_LIT>')<EOL> | Implementation of circle border with PIL. | f5403:m0 |
def circles_pycairo(width, height, color): | cairo_color = color / rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.new_path()<EOL>ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)<EOL>ctx.arc(width / <NUM_LIT:2>, height / <NUM_LIT:... | Implementation of circle border with PyCairo. | f5403:m1 |
def circles(width=<NUM_LIT:12>, height=<NUM_LIT:12>, color=rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)): | circles_pycairo(width, height, color)<EOL> | Draws a repeatable circle border pattern. | f5403:m2 |
def vertical_strip(width=<NUM_LIT:10>, height=<NUM_LIT:100>, color=rgb(<NUM_LIT:100>, <NUM_LIT:100>, <NUM_LIT:100>),<EOL>subtlety=<NUM_LIT:0.1>): | cairo_color = color / rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.scale(width / <NUM_LIT:1.0>, height / <NUM_LIT:1.0>)<EOL>pat = cairo.LinearGradient(<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1... | Draws a subtle vertical gradient strip. | f5404:m0 |
def vertical_white(width=<NUM_LIT:10>, height=<NUM_LIT:100>, subtlety=<NUM_LIT:0.1>): | start = <NUM_LIT:0.5> - subtlety<EOL>end = <NUM_LIT:0.5> + subtlety<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.scale(width/<NUM_LIT:1.0>, height/<NUM_LIT:1.0>)<EOL>pat = cairo.LinearGradient(<NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:0.0>, <NUM_LIT:1.0>)<EO... | Draws a subtle vertical gradient strip: white with varying alpha. | f5404:m1 |
def draw_img_button(width=<NUM_LIT:200>, height=<NUM_LIT:50>, text='<STR_LIT>', color=rgb(<NUM_LIT:200>,<NUM_LIT:100>,<NUM_LIT:50>)): | surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>ctx.rectangle(<NUM_LIT:0>, <NUM_LIT:0>, width - <NUM_LIT:1>, height - <NUM_LIT:1>)<EOL>ctx.set_source_rgb(color.red/<NUM_LIT>, color.green/<NUM_LIT>, color.blue/<NUM_LIT>)<EOL>ctx.fill()<EOL>ctx.set_source_rgb(<NUM_LIT... | Draws a simple image button. | f5405:m0 |
def draw_css_button(width=<NUM_LIT:200>, height=<NUM_LIT:50>, text='<STR_LIT>', color=rgb(<NUM_LIT:200>,<NUM_LIT:100>,<NUM_LIT:50>)): | <EOL>from scss import Scss<EOL>css_class = '<STR_LIT>'<EOL>html = '<STR_LIT>'.format(css_class, text)<EOL>css = Scss()<EOL>scss_str = "<STR_LIT>".format(css_class)<EOL>css.compile(scss_str)<EOL> | Draws a simple CSS button. | f5405:m1 |
def draw_circle(ctx, x, y, radius, cairo_color): | ctx.new_path()<EOL>ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)<EOL>ctx.arc(x, y, radius, <NUM_LIT:0>, <NUM_LIT:2> * pi)<EOL>ctx.fill()<EOL> | Draw a circle.
:param radius: radius in pixels
:param cairo_color: normalized rgb color | f5406:m0 |
def draw_cloud(width=<NUM_LIT>, height=<NUM_LIT>, color=rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)): | cairo_color = color / rgb(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)<EOL>surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)<EOL>ctx = cairo.Context(surface)<EOL>draw_circle(ctx, width / <NUM_LIT:3>, height / <NUM_LIT:2>, height / <NUM_LIT:3>, cairo_color)<EOL>draw_circle(ctx, <NUM_LIT:2> * width / <NUM_... | Draw a cloud with the given width, height, and color. | f5406:m1 |
def verify_gate_bqm(self, bqm, nodes, get_gate_output, ground_energy=<NUM_LIT:0>, min_gap=<NUM_LIT:2>): | for a, b, c in product([-<NUM_LIT:1>, <NUM_LIT:1>], repeat=<NUM_LIT:3>):<EOL><INDENT>spin_state = {nodes[<NUM_LIT:0>]: a, nodes[<NUM_LIT:1>]: b, nodes[<NUM_LIT:2>]: c}<EOL>energy = bqm.energy(spin_state)<EOL>if c == get_gate_output(a, b):<EOL><INDENT>self.assertEqual(ground_energy, energy, "<STR_LIT>".format(spin_state... | Check that all equally valid gate inputs are at ground and that invalid values meet
threshold (min_gap) requirement. | f5410:c0:m0 |
def get_item(dictionary, tuple_key, default_value): | u, v = tuple_key<EOL>tuple1 = dictionary.get((u, v), None)<EOL>tuple2 = dictionary.get((v, u), None)<EOL>return tuple1 or tuple2 or default_value<EOL> | Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two-element tuple as keys
tuple_key: Unordered tuple of two elements
default_value: Value that is returned when ... | f5411:m0 |
def _get_lp_matrix(spin_states, nodes, edges, offset_weight, gap_weight): | if len(spin_states) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>n_states = len(spin_states)<EOL>m_linear = len(nodes)<EOL>m_quadratic = len(edges)<EOL>matrix = np.empty((n_states, m_linear + m_quadratic + <NUM_LIT:2>)) <EOL>if spin_states.ndim == <NUM_LIT:1>:<EOL><INDENT>spin_states = np.expand_dims(spin_stat... | Creates an linear programming matrix based on the spin states, graph, and scalars provided.
LP matrix:
[spin_states, corresponding states of edges, offset_weight, gap_weight]
Args:
spin_states: Numpy array of spin states
nodes: Iterable
edges: Iterable of tuples
offset_w... | f5411:m1 |
def generate_bqm(graph, table, decision_variables,<EOL>linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=<NUM_LIT:2>): | <EOL>if len(graph) != len(decision_variables):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not linear_energy_ranges:<EOL><INDENT>linear_energy_ranges = {}<EOL><DEDENT>if not quadratic_energy_ranges:<EOL><INDENT>quadratic_energy_ranges = {}<EOL><DEDENT>nodes = decision_variables<EOL>edges = graph.edges<EOL>... | Args:
graph: A networkx.Graph
table: An iterable of valid spin configurations. Each configuration is a tuple of
variable assignments ordered by `decision`.
decision_variables: An ordered iterable of the variables in the binary quadratic model.
linear_energy_ranges: Dictionary of the form {v: (mi... | f5411:m2 |
@pm.penaltymodel_factory(<NUM_LIT:50>)<EOL>def get_penalty_model(specification): | <EOL>feasible_configurations = specification.feasible_configurations<EOL>if specification.vartype is dimod.BINARY:<EOL><INDENT>feasible_configurations = {tuple(<NUM_LIT:2> * v - <NUM_LIT:1> for v in config): en<EOL>for config, en in iteritems(feasible_configurations)}<EOL><DEDENT>ising_quadratic_ranges = specification.... | Factory function for penaltymodel-lp.
Args:
specification (penaltymodel.Specification): The specification
for the desired penalty model.
Returns:
:class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.
Raises:
:class:`penaltymodel.ImpossiblePena... | f5413:m0 |
def check_bqm_table(self, bqm, gap, table, decision): | response = dimod.ExactSolver().sample(bqm)<EOL>highest_feasible_energy = max(table.values()) if isinstance(table, dict) else <NUM_LIT:0><EOL>seen_gap = float('<STR_LIT>')<EOL>seen_table = set()<EOL>for sample, energy in response.data(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>self.assertAlmostEqual(bqm.energy(sample), en... | check that the bqm has ground states matching table | f5417:c0:m0 |
def check_bqm_graph(self, bqm, graph): | self.assertEqual(len(bqm.linear), len(graph.nodes))<EOL>self.assertEqual(len(bqm.quadratic), len(graph.edges))<EOL>for v in bqm.linear:<EOL><INDENT>self.assertIn(v, graph)<EOL><DEDENT>for u, v in bqm.quadratic:<EOL><INDENT>self.assertIn(u, graph.adj[v])<EOL><DEDENT> | bqm and graph have the same structure | f5417:c0:m1 |
def check_generated_ising_model(self, feasible_configurations, decision_variables,<EOL>linear, quadratic, ground_energy, infeasible_gap): | if not feasible_configurations:<EOL><INDENT>return<EOL><DEDENT>from dimod import ExactSolver<EOL>response = ExactSolver().sample_ising(linear, quadratic)<EOL>sample, ground = next(iter(response.data(['<STR_LIT>', '<STR_LIT>'])))<EOL>gap = float('<STR_LIT>')<EOL>self.assertIn(tuple(sample[v] for v in decision_variables)... | Check that the given Ising model has the correct energy levels | f5418:c0:m4 |
def generate_bqm(graph, table, decision,<EOL>linear_energy_ranges=None, quadratic_energy_ranges=None, min_classical_gap=<NUM_LIT:2>,<EOL>precision=<NUM_LIT:7>, max_decision=<NUM_LIT:8>, max_variables=<NUM_LIT:10>,<EOL>return_auxiliary=False): | <EOL>if not isinstance(graph, nx.Graph):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not set().union(*table).issubset({-<NUM_LIT:1>, <NUM_LIT:1>}):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not isinstance(decision, list):<EOL><INDENT>decision = list(decision) <EOL><DEDENT>if not all(v in gra... | Get a binary quadratic model with specific ground states.
Args:
graph (:obj:`~networkx.Graph`):
Defines the structure of the generated binary quadratic model.
table (iterable):
Iterable of valid configurations (of spin-values). Each configuration is a tuple of
v... | f5419:m0 |
@pm.penaltymodel_factory(-<NUM_LIT>)<EOL>def get_penalty_model(specification): | <EOL>feasible_configurations = specification.feasible_configurations<EOL>if specification.vartype is dimod.BINARY:<EOL><INDENT>feasible_configurations = {tuple(<NUM_LIT:2> * v - <NUM_LIT:1> for v in config): en<EOL>for config, en in iteritems(feasible_configurations)}<EOL><DEDENT>ising_quadratic_ranges = specification.... | Factory function for penaltymodel-mip.
Args:
specification (penaltymodel.Specification): The specification
for the desired penalty model.
Returns:
:class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.
Raises:
:class:`penaltymodel.ImpossiblePen... | f5421:m0 |
def cache_connect(database=None): | if database is None:<EOL><INDENT>database = cache_file()<EOL><DEDENT>if os.path.isfile(database):<EOL><INDENT>conn = sqlite3.connect(database)<EOL><DEDENT>else:<EOL><INDENT>conn = sqlite3.connect(database)<EOL>conn.executescript(schema)<EOL><DEDENT>with conn as cur:<EOL><INDENT>cur.execute("<STR_LIT>")<EOL><DEDENT>conn... | Returns a connection object to a sqlite database.
Args:
database (str, optional): The path to the database the user wishes
to connect to. If not specified, a default is chosen using
:func:`.cache_file`. If the special database name ':memory:'
is given, then a temporary d... | f5426:m0 |
def insert_graph(cur, nodelist, edgelist, encoded_data=None): | if encoded_data is None:<EOL><INDENT>encoded_data = {}<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(nodelist)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(edgelist)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>e... | Insert a graph into the cache.
A graph is stored by number of nodes, number of edges and a
json-encoded list of edges.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
nodelist (list): The nodes in the grap... | f5426:m1 |
def iter_graph(cur): | select = """<STR_LIT>"""<EOL>for num_nodes, num_edges, edges in cur.execute(select):<EOL><INDENT>yield list(range(num_nodes)), json.loads(edges)<EOL><DEDENT> | Iterate over all graphs in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
tuple: A 2-tuple containing:
list: The nodelist for a graph in the cache.
list: the edgel... | f5426:m2 |
def insert_feasible_configurations(cur, feasible_configurations, encoded_data=None): | if encoded_data is None:<EOL><INDENT>encoded_data = {}<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(next(iter(feasible_configurations)))<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = len(feasible_configurations)<EOL><DEDENT>if '<ST... | Insert a group of feasible configurations into the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
feasible_configurations (dict[tuple[int]): The set of feasible
configurations. Each key should b... | f5426:m3 |
def _serialize_config(config): | out = <NUM_LIT:0><EOL>for bit in config:<EOL><INDENT>out = (out << <NUM_LIT:1>) | (bit > <NUM_LIT:0>)<EOL><DEDENT>return out<EOL> | Turns a config into an integer treating each of the variables as spins.
Examples:
>>> _serialize_config((0, 0, 1))
1
>>> _serialize_config((1, 1))
3
>>> _serialize_config((1, 0, 0))
4 | f5426:m4 |
def iter_feasible_configurations(cur): | select ="""<STR_LIT>"""<EOL>for num_variables, feasible_configurations, energies in cur.execute(select):<EOL><INDENT>configs = json.loads(feasible_configurations)<EOL>energies = json.loads(energies)<EOL>yield {_decode_config(config, num_variables): energy<EOL>for config, energy in zip(configs, energies)}<EOL><DEDENT> | Iterate over all of the sets of feasible configurations in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
dict[tuple(int): number]: The feasible_configurations. | f5426:m5 |
def _decode_config(c, num_variables): | def bits(c):<EOL><INDENT>n = <NUM_LIT:1> << (num_variables - <NUM_LIT:1>)<EOL>for __ in range(num_variables):<EOL><INDENT>yield <NUM_LIT:1> if c & n else -<NUM_LIT:1><EOL>n >>= <NUM_LIT:1><EOL><DEDENT><DEDENT>return tuple(bits(c))<EOL> | inverse of _serialize_config, always converts to spin. | f5426:m6 |
def insert_ising_model(cur, nodelist, edgelist, linear, quadratic, offset, encoded_data=None): | if encoded_data is None:<EOL><INDENT>encoded_data = {}<EOL><DEDENT>insert_graph(cur, nodelist, edgelist, encoded_data=encoded_data)<EOL>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encoded_data['<STR_LIT>'] = _serialize_linear_biases(linear, nodelist)<EOL><DEDENT>if '<STR_LIT>' not in encoded_data:<EOL><INDENT>encod... | Insert an Ising model into the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
nodelist (list): The nodes in the graph.
edgelist (list): The edges in the graph.
linear (dict): The linear bias... | f5426:m7 |
def _serialize_linear_biases(linear, nodelist): | linear_bytes = struct.pack('<STR_LIT:<>' + '<STR_LIT:d>' * len(linear), *[linear[i] for i in nodelist])<EOL>return base64.b64encode(linear_bytes).decode('<STR_LIT:utf-8>')<EOL> | Serializes the linear biases.
Args:
linear: a interable object where linear[v] is the bias
associated with v.
nodelist (list): an ordered iterable containing the nodes.
Returns:
str: base 64 encoded string of little endian 8 byte floats,
one for each of the bias... | f5426:m8 |
def _serialize_quadratic_biases(quadratic, edgelist): | <EOL>quadratic_list = [quadratic[(u, v)] if (u, v) in quadratic else quadratic[(v, u)]<EOL>for u, v in edgelist]<EOL>quadratic_bytes = struct.pack('<STR_LIT:<>' + '<STR_LIT:d>' * len(quadratic), *quadratic_list)<EOL>return base64.b64encode(quadratic_bytes).decode('<STR_LIT:utf-8>')<EOL> | Serializes the quadratic biases.
Args:
quadratic (dict): a dict of the form {edge1: bias1, ...} where
each edge is of the form (node1, node2).
edgelist (list): a list of the form [(node1, node2), ...].
Returns:
str: base 64 encoded string of little endian 8 byte floats,
... | f5426:m9 |
def iter_ising_model(cur): | select ="""<STR_LIT>"""<EOL>for linear_biases, quadratic_biases, num_nodes, edges, offset in cur.execute(select):<EOL><INDENT>nodelist = list(range(num_nodes))<EOL>edgelist = json.loads(edges)<EOL>yield (nodelist, edgelist,<EOL>_decode_linear_biases(linear_biases, nodelist),<EOL>_decode_quadratic_biases(quadratic_biase... | Iterate over all of the Ising models in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
tuple: A 5-tuple consisting of:
list: The nodelist for a graph in the cache.
... | f5426:m10 |
def _decode_linear_biases(linear_string, nodelist): | linear_bytes = base64.b64decode(linear_string)<EOL>return dict(zip(nodelist, struct.unpack('<STR_LIT:<>' + '<STR_LIT:d>' * (len(linear_bytes) // <NUM_LIT:8>), linear_bytes)))<EOL> | Inverse of _serialize_linear_biases.
Args:
linear_string (str): base 64 encoded string of little endian
8 byte floats, one for each of the nodes in nodelist.
nodelist (list): list of the form [node1, node2, ...].
Returns:
dict: linear biases in a dict.
Examples:
... | f5426:m11 |
def _decode_quadratic_biases(quadratic_string, edgelist): | quadratic_bytes = base64.b64decode(quadratic_string)<EOL>return {tuple(edge): bias for edge, bias in zip(edgelist,<EOL>struct.unpack('<STR_LIT:<>' + '<STR_LIT:d>' * (len(quadratic_bytes) // <NUM_LIT:8>), quadratic_bytes))}<EOL> | Inverse of _serialize_quadratic_biases
Args:
quadratic_string (str) : base 64 encoded string of little
endian 8 byte floats, one for each of the edges.
edgelist (list): a list of edges of the form [(node1, node2), ...].
Returns:
dict: J. A dict of the form {edge1: bias1, ..... | f5426:m12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.