content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from __future__ import print_function __author__ = "Gianluca Santoni" __copyright__ = "Copyright 20150-2019" __credits__ = ["Gianluca Santoni, Alexander Popov"] __license__ = "" __version__ = "1.0" __maintainer__ = "Gianluca Santoni" __email__ = "gianluca.santoni@esrf.fr" __status__ = "Beta" from scipy.cluster import hierarchy import scipy import matplotlib.pyplot as plt import os import numpy as np import subprocess import collections import operator import stat import json import random if __name__== '__main__': main()
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 834, 9800, 834, 796, 366, 38, 666, 75, 43120, 10844, 14651, 1, 198, 834, 22163, 4766, 834, 796, 366, 15269, 580, 1120, 12, 23344, 1, 198, 834, 66, 20696, 834, 796, 14631, 38, 666, ...
2.58296
223
#!/usr/bin/env python # Author: Nick Zwart # Date: 2015oct31 from __future__ import print_function import os import sys import stat import errno import shutil import optparse import traceback import subprocess wrappaconda_name_string = 'Wr[App]-A-Conda' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 6434, 25, 8047, 1168, 24657, 198, 2, 7536, 25, 1853, 38441, 3132, 220, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 11748...
2.883495
103
import requests
[ 11748, 7007, 628 ]
5.666667
3
from scripts.test import shared from . import utils
[ 6738, 14750, 13, 9288, 1330, 4888, 198, 6738, 764, 1330, 3384, 4487, 628 ]
4.076923
13
from PyQt5.QtWidgets import QTreeWidget from PyQt5.Qt import pyqtSignal from PyQt5.QtWidgets import QTreeWidgetItem from PyQt5.Qt import Qt
[ 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 27660, 38300, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 1330, 12972, 39568, 11712, 282, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 27660, 3...
2.413793
58
import os import sys LOCALPATH = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, LOCALPATH + '/../../../../') from app.api.v2.db import Db def format_sale(sale): """Formats the results to a dictionary""" sale = { "id": sale[0], "books": sale[1], "total": sale[2], "created_by": sale[3], "attendant_name": sale[5], "created_at": str(sale[4]) } return sale
[ 11748, 28686, 198, 11748, 25064, 198, 198, 29701, 1847, 34219, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 4008, 198, 17597, 13, 6978, 13, 28463, 7, 15, 11, 37347, 1847, 34219, 134...
2.162562
203
from bleSuite import bleConnectionManager, bleServiceManager from bluepy.btle import Scanner from ubirch.linux.bleServiceManager import BLEServiceManager
[ 6738, 7245, 5606, 578, 1330, 7245, 32048, 13511, 11, 7245, 16177, 13511, 198, 6738, 4171, 9078, 13, 65, 7100, 1330, 20937, 1008, 198, 198, 6738, 20967, 343, 354, 13, 23289, 13, 903, 16177, 13511, 1330, 9878, 1546, 712, 501, 13511, 628 ]
3.804878
41
# Copyright (c) 2015-2020 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from cgtsclient.common import base from cgtsclient import exc CREATION_ATTRIBUTES = ['software_version', 'compatible_version', 'required_patches'] IMPORT_ATTRIBUTES = ['path_to_iso', 'path_to_sig', 'active']
[ 2, 15069, 357, 66, 8, 1853, 12, 42334, 3086, 5866, 11998, 11, 3457, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 2, 628, 198, 6738, 269, 70, 912, 16366, 13, 11321, 1330, 2779, 198, ...
2.488722
133
# Copyright 2021 Sony Semiconductors Israel, Inc. All rights reserved. # # 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 numpy as np import tensorflow as tf from model_compression_toolkit.tpc_models.default_tp_model import get_op_quantization_configs from model_compression_toolkit.tpc_models.keras_tp_models.keras_default import generate_keras_default_tpc from tests.common_tests.helpers.generate_test_tp_model import generate_mixed_precision_test_tp_model from tests.keras_tests.feature_networks_tests.base_keras_feature_test import BaseKerasFeatureNetworkTest import model_compression_toolkit as mct from model_compression_toolkit.common.mixed_precision.kpi import KPI from model_compression_toolkit.common.mixed_precision.mixed_precision_quantization_config import \ MixedPrecisionQuantizationConfig from model_compression_toolkit.common.user_info import UserInformation from tests.common_tests.base_feature_test import BaseFeatureNetworkTest from tests.common_tests.helpers.tensors_compare import cosine_similarity keras = tf.keras layers = keras.layers tp = mct.target_platform
[ 2, 15069, 33448, 10184, 311, 5314, 12920, 669, 2692, 11, 3457, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, ...
3.543158
475
""":run """ import curses import datetime import json import logging import os import re import shlex import shutil import time import uuid from math import floor from queue import Queue from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union from ..action_base import ActionBase from ..action_defs import RunStdoutReturn from ..app_public import AppPublic from ..configuration_subsystem import ApplicationConfiguration from ..runner import CommandAsync from ..steps import Step from ..ui_framework import CursesLine from ..ui_framework import CursesLinePart from ..ui_framework import CursesLines from ..ui_framework import Interaction from ..ui_framework import dict_to_form from ..ui_framework import form_to_dict from ..ui_framework import nonblocking_notification from ..ui_framework import warning_notification from ..utils.functions import abs_user_path from ..utils.functions import human_time from ..utils.functions import remove_ansi from ..utils.functions import round_half_up from ..utils.serialize import json_dump from . import _actions as actions from . import run_action RESULT_TO_COLOR = [ ("(?i)^failed$", 9), ("(?i)^ok$", 10), ("(?i)^ignored$", 13), ("(?i)^skipped$", 14), ("(?i)^in_progress$", 8), ] get_color = lambda word: next( # noqa: E731 (x[1] for x in RESULT_TO_COLOR if re.match(x[0], word)), 0, ) def color_menu(_colno: int, colname: str, entry: Dict[str, Any]) -> Tuple[int, int]: # pylint: disable=too-many-branches """Find matching color for word :param colname: A word to match """ colval = entry[colname] color = 0 decoration = 0 if "__play_name" in entry: if not colval: color = 8 elif colname in ["__task_count", "__play_name", "__progress"]: failures = entry["__failed"] + entry["__unreachable"] if failures: color = 9 elif entry["__ok"]: color = 10 else: color = 8 elif colname == "__changed": color = 11 else: color = get_color(colname[2:]) if colname == "__progress" and entry["__progress"].strip().lower() == "complete": decoration = curses.A_BOLD elif "task" in entry: if entry["__result"].lower() == "__in_progress": color = get_color(entry["__result"]) elif colname in ["__result", "__host", "__number", "__task", "__task_action"]: color = get_color(entry["__result"]) elif colname == "__changed": if colval is True: color = 11 else: color = get_color(entry["__result"]) elif colname == "__duration": color = 12 return color, decoration def content_heading(obj: Any, screen_w: int) -> Union[CursesLines, None]: """create a heading for some piece of content showing :param obj: The content going to be shown :param screen_w: The current screen width :return: The heading """ if isinstance(obj, dict) and "task" in obj: detail = f"PLAY [{obj['play']}:{obj['__number']}] " stars = "*" * (screen_w - len(detail)) line_1 = CursesLine( (CursesLinePart(column=0, string=detail + stars, color=0, decoration=0),), ) detail = f"TASK [{obj['task']}] " stars = "*" * (screen_w - len(detail)) line_2 = CursesLine( (CursesLinePart(column=0, string=detail + stars, color=0, decoration=0),), ) if obj["__changed"] is True: color = 11 res = "CHANGED" else: color = next((x[1] for x in RESULT_TO_COLOR if re.match(x[0], obj["__result"])), 0) res = obj["__result"] if "res" in obj and "msg" in obj["res"]: msg = str(obj["res"]["msg"]).replace("\n", " ").replace("\r", "") else: msg = "" string = f"{res}: [{obj['__host']}] {msg}" string = string + (" " * (screen_w - len(string) + 1)) line_3 = CursesLine( (CursesLinePart(column=0, string=string, color=color, decoration=curses.A_UNDERLINE),), ) return CursesLines((line_1, line_2, line_3)) return None def filter_content_keys(obj: Dict[Any, Any]) -> Dict[Any, Any]: """when showing content, filter out some keys""" return {k: v for k, v in obj.items() if not (k.startswith("_") or k.endswith("uuid"))} PLAY_COLUMNS = [ "__play_name", "__ok", "__changed", "__unreachable", "__failed", "__skipped", "__ignored", "__in_progress", "__task_count", "__progress", ] TASK_LIST_COLUMNS = [ "__result", "__host", "__number", "__changed", "__task", "__task_action", "__duration", ]
[ 15931, 1298, 5143, 198, 37811, 198, 11748, 43878, 198, 11748, 4818, 8079, 198, 11748, 33918, 198, 11748, 18931, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 427, 2588, 198, 11748, 4423, 346, 198, 11748, 640, 198, 11748, 334, 27112, 198...
2.35906
2,086
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @file : __init__.py.py @Time : 2020/11/12 13:37 @Author: Tao.Xu @Email : tao.xu2008@outlook.com """ """ phoronix-test-suite: Main for Performance Test =================== https://github.com/phoronix-test-suite/phoronix-test-suite The Phoronix Test Suite is the most comprehensive testing and benchmarking platform available for Linux, Solaris, macOS, Windows, and BSD operating systems. """ if __name__ == '__main__': pass
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 41002, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 7753, 220, 1058, 11593, 15003, 834, 13, 9078, 13, 9078, 198, 31, 7575, 220, 1058, 12131, 14, 1157, 14, 1065, 15...
2.681564
179
# Copyright 2018 Google LLC # # 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. """This script is used to synthesize generated parts of this library.""" from pathlib import Path from typing import List, Optional import synthtool as s from synthtool import gcp from synthtool.languages import python common = gcp.CommonTemplates() def get_staging_dirs( # This is a customized version of the s.get_staging_dirs() function # from synthtool to # cater for copying 3 different folders from # googleapis-gen: # spanner, spanner/admin/instance and spanner/admin/database. # Source: # https://github.com/googleapis/synthtool/blob/master/synthtool/transforms.py#L280 default_version: Optional[str] = None, sub_directory: Optional[str] = None, ) -> List[Path]: """Returns the list of directories, one per version, copied from https://github.com/googleapis/googleapis-gen. Will return in lexical sorting order with the exception of the default_version which will be last (if specified). Args: default_version (str): the default version of the API. The directory for this version will be the last item in the returned list if specified. sub_directory (str): if a `sub_directory` is provided, only the directories within the specified `sub_directory` will be returned. Returns: the empty list if no file were copied. """ staging = Path("owl-bot-staging") if sub_directory: staging /= sub_directory if staging.is_dir(): # Collect the subdirectories of the staging directory. versions = [v.name for v in staging.iterdir() if v.is_dir()] # Reorder the versions so the default version always comes last. versions = [v for v in versions if v != default_version] versions.sort() if default_version is not None: versions += [default_version] dirs = [staging / v for v in versions] for dir in dirs: s._tracked_paths.add(dir) return dirs else: return [] spanner_default_version = "v1" spanner_admin_instance_default_version = "v1" spanner_admin_database_default_version = "v1" for library in get_staging_dirs(spanner_default_version, "spanner"): # Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 s.replace( library / f"google/cloud/spanner_{library.name}/types/transaction.py", r""". Attributes:""", r""".\n Attributes:""", ) # Work around gapic generator bug https://github.com/googleapis/gapic-generator-python/issues/902 s.replace( library / f"google/cloud/spanner_{library.name}/types/transaction.py", r""". Attributes:""", r""".\n Attributes:""", ) # Remove headings from docstring. Requested change upstream in cl/377290854 due to https://google.aip.dev/192#formatting. s.replace( library / f"google/cloud/spanner_{library.name}/types/transaction.py", """\n ==.*?==\n""", ":", ) # Remove headings from docstring. Requested change upstream in cl/377290854 due to https://google.aip.dev/192#formatting. s.replace( library / f"google/cloud/spanner_{library.name}/types/transaction.py", """\n --.*?--\n""", ":", ) s.move( library, excludes=[ "google/cloud/spanner/**", "*.*", "docs/index.rst", "google/cloud/spanner_v1/__init__.py", ], ) for library in get_staging_dirs( spanner_admin_instance_default_version, "spanner_admin_instance" ): s.move( library, excludes=["google/cloud/spanner_admin_instance/**", "*.*", "docs/index.rst"], ) for library in get_staging_dirs( spanner_admin_database_default_version, "spanner_admin_database" ): s.move( library, excludes=["google/cloud/spanner_admin_database/**", "*.*", "docs/index.rst"], ) s.remove_staging_dirs() # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- templated_files = common.py_library( microgenerator=True, samples=True, cov_level=99, split_system_tests=True, ) s.move(templated_files, excludes=[ ".coveragerc", ".github/workflows", # exclude gh actions as credentials are needed for tests ] ) # Ensure CI runs on a new instance each time s.replace( ".kokoro/build.sh", "# Remove old nox", """\ # Set up creating a new instance for each system test run export GOOGLE_CLOUD_TESTS_CREATE_SPANNER_INSTANCE=true # Remove old nox""", ) # Update samples folder in CONTRIBUTING.rst s.replace("CONTRIBUTING.rst", "samples/snippets", "samples/samples") # ---------------------------------------------------------------------------- # Samples templates # ---------------------------------------------------------------------------- python.py_samples() # ---------------------------------------------------------------------------- # Customize noxfile.py # ---------------------------------------------------------------------------- open_telemetry_test = """ # XXX Work around Kokoro image's older pip, which borks the OT install. session.run("pip", "install", "--upgrade", "pip") session.install("-e", ".[tracing]", "-c", constraints_path) # XXX: Dump installed versions to debug OT issue session.run("pip", "list") # Run py.test against the unit tests with OpenTelemetry. session.run( "py.test", "--quiet", "--cov=google.cloud.spanner", "--cov=google.cloud", "--cov=tests.unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", "--cov-fail-under=0", os.path.join("tests", "unit"), *session.posargs, ) """ place_before( "noxfile.py", "@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)", open_telemetry_test, escape="()", ) skip_tests_if_env_var_not_set = """# Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", "") and not os.environ.get( "SPANNER_EMULATOR_HOST", "" ): session.skip( "Credentials or emulator host must be set via environment variable" ) """ place_before( "noxfile.py", "# Install pyopenssl for mTLS testing.", skip_tests_if_env_var_not_set, escape="()", ) s.replace( "noxfile.py", """f"--junitxml=unit_{session.python}_sponge_log.xml", "--cov=google", "--cov=tests/unit",""", """\"--cov=google.cloud.spanner", "--cov=google.cloud", "--cov=tests.unit",""", ) s.replace( "noxfile.py", r"""session.install\("-e", "."\)""", """session.install("-e", ".[tracing]")""", ) s.replace( "noxfile.py", r"""# Install all test dependencies, then install this package into the # virtualenv's dist-packages. session.install\("mock", "pytest", "google-cloud-testutils", "-c", constraints_path\) session.install\("-e", ".", "-c", constraints_path\)""", """# Install all test dependencies, then install this package into the # virtualenv's dist-packages. session.install("mock", "pytest", "google-cloud-testutils", "-c", constraints_path) session.install("-e", ".[tracing]", "-c", constraints_path)""", ) s.shell.run(["nox", "-s", "blacken"], hide_output=False)
[ 2, 15069, 2864, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330...
2.675541
3,005
from random import randint def k_means(data, K): """ k-Means clustering TODO: Assumes values from 0-255 :param data: NxD array of numbers :param K: The number of clusters :return: Tuple of cluster means (KxD array) and cluster assignments (Nx1 with values from 1 to K) """ N = len(data) D = len(data[0]) means = [None]*K for i in range(0,K): means[i] = [randint(0, 255), randint(0, 255), randint(0, 255)] assignments = [None]*N changed = True while(changed): old_means = means # Find closest centroid for n in range(0, N): "max distance in RGB" min = 442.0 index = -1 for k in range(0,K): temp = __distance(data[n], means[k], D) if temp <= min: min = temp index = k assignments[n] = index # Calculate the new centers for k in range(0,K): # Aus assignments die Indizes mit Eintrag k finden indices = [i for i,x in enumerate(assignments) if x == k] # ... und dann anhand derer in Data die Werte schauen temp_data = [x for i,x in enumerate(data) if i in indices] # ... und mitteln means[k] = __mean(temp_data, D) # Check if something changed changed = False for k in range(0,K): if old_means[k] != means[k]: changed = True break return (means, assignments)
[ 6738, 4738, 1330, 43720, 600, 198, 198, 4299, 479, 62, 1326, 504, 7, 7890, 11, 509, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 479, 12, 5308, 504, 32966, 1586, 628, 220, 220, 220, 16926, 46, 25, 2195, 8139, 3815, 422, 65...
2.039578
758
""" Support for interacting with ModelCenter via the AnalysisServer protocol. Client-mode access to an AnalysisServer is provided by the 'client', 'factory', and 'proxy' modules. Server-mode access by ModelCenter is provided by the 'server' and 'wrapper' modules. An extension to the protocol allows 'eggs' to pe 'published': the egg is sent to the server and made part of the server's set of supported components. """ from __future__ import absolute_import from .client import Client from .factory import ASFactory from .server import Server, start_server, stop_server, DEFAULT_PORT from .stream import Stream from .units import have_translation, get_translation, set_translation from .publish import publish_class, publish_object, publish_egg
[ 37811, 198, 15514, 329, 24986, 351, 9104, 23656, 2884, 262, 14691, 10697, 8435, 13, 198, 11792, 12, 14171, 1895, 284, 281, 14691, 10697, 318, 2810, 416, 262, 705, 16366, 3256, 705, 69, 9548, 3256, 198, 392, 705, 36436, 6, 13103, 13, 2...
3.9375
192
import os import numpy as np import tensorflow as tf import cv2 import time import sys import pickle import ROLO_utils as util '''----------------------------------------main-----------------------------------------------------''' if __name__=='__main__': main(sys.argv)
[ 11748, 28686, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 269, 85, 17, 198, 11748, 640, 198, 11748, 25064, 198, 11748, 2298, 293, 198, 11748, 371, 3535, 46, 62, 26791, 355, 7736, 198, 198, ...
3.72973
74
import itertools import re import shlex def cmdify(self): """Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are doubled, so they are all escaped properly. * Backslashes elsewhere are left as-is; cmd will interpret them literally. The result is then quoted into a pair of double quotes to be grouped. An argument is intentionally not quoted if it does not contain foul characters. This is done to be compatible with Windows built-in commands that don't work well with quotes, e.g. everything with `echo`, and DOS-style (forward slash) switches. Foul characters include: * Whitespaces. * Carets (^). (pypa/pipenv#3307) * Parentheses in the command. (pypa/pipenv#3168) Carets introduce a difficult situation since they are essentially "lossy" when parsed. Consider this in cmd.exe:: > echo "foo^bar" "foo^bar" > echo foo^^bar foo^bar The two commands produce different results, but are both parsed by the shell as `foo^bar`, and there's essentially no sensible way to tell what was actually passed in. This implementation assumes the quoted variation (the first) since it is easier to implement, and arguably the more common case. The intended use of this function is to pre-process an argument list before passing it into ``subprocess.Popen(..., shell=True)``. See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence """ return " ".join( itertools.chain( [_quote_if_contains(self.command, r"[\s^()]")], (_quote_if_contains(arg, r"[\s^]") for arg in self.args), ) )
[ 11748, 340, 861, 10141, 198, 11748, 302, 198, 11748, 427, 2588, 628, 628, 198, 220, 220, 220, 825, 23991, 1958, 7, 944, 2599, 198, 220, 220, 220, 220, 220, 220, 220, 37227, 4834, 8189, 656, 257, 23991, 12, 18558, 18187, 4731, 13, 62...
2.602516
795
from .framework import Client, Resource from . import constants as const client = Client( base_url='https://login.microsoftonline.com', base_headers={ 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0', 'Content-Type': 'application/x-www-form-urlencoded', } )
[ 6738, 764, 30604, 1330, 20985, 11, 20857, 198, 198, 6738, 764, 1330, 38491, 355, 1500, 198, 198, 16366, 796, 20985, 7, 198, 220, 220, 220, 2779, 62, 6371, 11639, 5450, 1378, 38235, 13, 40485, 25119, 13, 785, 3256, 198, 220, 220, 220, ...
2.480916
131
import logging import re from warn.cache import Cache as BaseCache from .urls import urls logger = logging.getLogger(__name__)
[ 11748, 18931, 198, 11748, 302, 198, 198, 6738, 9828, 13, 23870, 1330, 34088, 355, 7308, 30562, 198, 198, 6738, 764, 6371, 82, 1330, 2956, 7278, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 628 ]
3.195122
41
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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 textwrap import json import sys import os from cement.core import controller from ebcli import __version__ from ebcli.core.ebglobals import Constants from ebcli.lib import elasticbeanstalk, utils from ebcli.core import io, fileoperations from ebcli.objects.exceptions import ( NoEnvironmentForBranchError, PlatformWorkspaceNotSupportedError, ApplicationWorkspaceNotSupportedError, EBCLIException, NotInitializedError ) from ebcli.resources.strings import strings, flag_text from ebcli.objects import region from ebcli.operations import commonops
[ 2, 15069, 1946, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 11074, 921, 198, 2, 743, 407, 779, 428, 2393, ...
3.662379
311
import unittest import speak if __name__ == "__main__": unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 2740, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 555, 715, 395, 13, 12417, 3419, 198 ]
2.566667
30
#!/usr/local/bin/python import sys temperatures=[10,-20,-289,100] for temp in temperatures: file = open('temperatures.txt','a+') if temp > -273.15: temp_output = c2f(temp) file.write(str(temp_output)) file.write("\n") file.close()
[ 2, 48443, 14629, 14, 12001, 14, 8800, 14, 29412, 198, 11748, 25064, 198, 198, 11498, 525, 6691, 41888, 940, 12095, 1238, 12095, 27693, 11, 3064, 60, 628, 198, 1640, 20218, 287, 10101, 25, 198, 220, 220, 220, 2393, 796, 1280, 10786, 11...
2.174603
126
#!/usr/bin/env python3 # METADATA OF THIS TAL_SERVICE: problem="eggs" service="confirm_min_throws" args_list = [ ('min',int), ('n_eggs',int), ('n_floors',int), ('lang',str), ('ISATTY',bool), ] from sys import stderr, exit, argv from random import randrange from math import inf as IMPOSSIBLE from multilanguage import Env, Lang, TALcolors ENV =Env(problem, service, args_list) TAc =TALcolors(ENV) LANG=Lang(ENV, TAc, lambda fstring: eval(f"f'{fstring}'")) TAc.print(LANG.opening_msg, "green") # START CODING YOUR SERVICE: # INITIALIZATON: allocation, base cases, sentinels table = [ [0] + [IMPOSSIBLE] * ENV['n_floors'] ] for u in range(ENV['n_eggs']): table.append([0] + [None] * ENV['n_floors']) # INDUCTTVE STEP: the min-max recursion with nature playing against for u in range(1,1+ENV['n_eggs']): for f in range(1,1+ENV['n_floors']): table[u][f] = IMPOSSIBLE for first_launch_floor in range(1,1+f): table[u][f] = min(table[u][f],1+max(table[u][f-first_launch_floor],table[u-1][first_launch_floor-1])) if table[ENV['n_eggs']][ENV['n_floors']] < ENV['min']: print(f"No! When you are given {ENV['n_eggs']} eggs and the floors are {ENV['n_floors']} then there exists a policy that guarantees you to find out the truth in strictly less than {ENV['min']} launches, whatever will happen (worst case).") #English: print("No! When you are given {ENV['n_eggs']} eggs and the floors are {ENV['n_floors']} then there exists a policy that guarantees you to find out the truth in strictly less than {ENV['min']} launches, whatever will happen (worst case).") if table[ENV['n_eggs']][ENV['n_floors']] > ENV['min']: print(f"No! When you are given {ENV['n_eggs']} eggs and the floors are {ENV['n_floors']} then no policy guarantees you to find out the truth within {ENV['min']} launches in every possible scenario (aka, whathever the truth is).") #English: if table[ENV['n_eggs']][ENV['n_floors']] == ENV['min']: print(f"Yes! Indeed, {ENV['min']} is the smallest possible natural B such that, when you are given {ENV['n_eggs']} eggs and the floors are {ENV['n_floors']}, still there exists a policy that guarantees you to find out the truth within B launches in every possible scenario.") #English: exit(0)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 31243, 2885, 13563, 3963, 12680, 309, 1847, 62, 35009, 27389, 25, 198, 45573, 2625, 33856, 82, 1, 198, 15271, 2625, 10414, 2533, 62, 1084, 62, 400, 8516, 1, 198, 22046, 6...
2.608447
876
errorFound = False
[ 18224, 21077, 796, 10352, 628, 628 ]
3.666667
6
#$ header variable x :: int #$ acc parallel private(idx) #$ omp parallel private(idx)
[ 29953, 13639, 7885, 2124, 7904, 493, 198, 29953, 697, 10730, 2839, 7, 312, 87, 8, 198, 29953, 267, 3149, 10730, 2839, 7, 312, 87, 8, 198 ]
3.307692
26
from django.contrib import admin from .models import Doctor, ConsultationTime, Medicine, Allergy, Child, Parent admin.site.site_header = "Allisto - We Do Good" admin.site.register(ConsultationTime)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 6738, 764, 27530, 1330, 9356, 11, 21651, 341, 7575, 11, 11558, 11, 1439, 26079, 11, 5932, 11, 16774, 198, 198, 28482, 13, 15654, 13, 15654, 62, 25677, 796, 366, 3237, 396, 78, ...
3.234375
64
from backend.entity.entity import DefinedFuntion from backend.ir.dumper import Dumper from backend.ir.stmt import Assign from backend.ir.stmt import Return from backend.ir.expr import Bin from backend.ir.expr import Call from backend.entity.scope import * # This class were used to import IR from json text
[ 198, 6738, 30203, 13, 26858, 13, 26858, 1330, 2896, 1389, 37, 2797, 295, 198, 6738, 30203, 13, 343, 13, 67, 15829, 1330, 360, 15829, 198, 6738, 30203, 13, 343, 13, 301, 16762, 1330, 2195, 570, 198, 6738, 30203, 13, 343, 13, 301, 167...
3.586207
87
import numpy as np from pyquil.gate_matrices import X, Y, Z, H from forest.benchmarking.operator_tools.superoperator_transformations import * # Test philosophy: # Using the by hand calculations found in the docs we check conversion # between one qubit channels with one Kraus operator (Hadamard) and two # Kraus operators (the amplitude damping channel). Additionally we check # a few two qubit channel conversions to get additional confidence. HADChi = 0.5 * np.asarray([[0, 0, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 1, 0, 1]]) HADPauli = 1.0 * np.asarray([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0], [0, 1, 0, 0]]) HADSuper = 0.5 * np.asarray([[1, 1, 1, 1], [1, -1, 1, -1], [1, 1, -1, -1], [1, -1, -1, 1]]) HADChoi = 0.5 * np.asarray([[1, 1, 1, -1], [1, 1, 1, -1], [1, 1, 1, -1], [-1, -1, -1, 1]]) # Single Qubit Pauli Channel # Pauli twirled Amplitude damping channel # I \otimes Z channel or gate (two qubits) two_qubit_paulis = n_qubit_pauli_basis(2) IZKraus = two_qubit_paulis.ops_by_label['IZ'] IZSuper = np.diag([1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1]) # one and zero state as a density matrix ONE_STATE = np.asarray([[0, 0], [0, 1]]) ZERO_STATE = np.asarray([[1, 0], [0, 0]]) # Amplitude damping Kraus operators with p = 0.1 AdKrausOps = amplitude_damping_kraus(.1) # Use Kraus operators to find output of channel i.e. # rho_out = A_0 rho A_0^\dag + A_1 rho A_1^\dag. rho_out = np.matmul(np.matmul(AdKrausOps[0], ONE_STATE), AdKrausOps[0].transpose().conj()) + \ np.matmul(np.matmul(AdKrausOps[1], ONE_STATE), AdKrausOps[1].transpose().conj())
[ 11748, 299, 32152, 355, 45941, 198, 6738, 12972, 421, 346, 13, 10494, 62, 6759, 45977, 1330, 1395, 11, 575, 11, 1168, 11, 367, 198, 6738, 8222, 13, 26968, 4102, 278, 13, 46616, 62, 31391, 13, 16668, 46616, 62, 35636, 602, 1330, 1635, ...
1.860399
1,053
import OIL.color import OIL.label import OIL.parser import OIL.tools import OIL.errors
[ 11748, 440, 4146, 13, 8043, 198, 11748, 440, 4146, 13, 18242, 198, 11748, 440, 4146, 13, 48610, 198, 11748, 440, 4146, 13, 31391, 198, 11748, 440, 4146, 13, 48277 ]
2.965517
29
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import sys import spack.cmd import spack.cmd.common.arguments as arguments import spack.environment as ev import spack.store import spack.user_environment as uenv import spack.util.environment description = "add package to the user environment" section = "user environment" level = "short" def setup_parser(subparser): """Parser is only constructed so that this prints a nice help message with -h. """ arguments.add_common_arguments( subparser, ['recurse_dependencies', 'installed_specs']) shells = subparser.add_mutually_exclusive_group() shells.add_argument( '--sh', action='store_const', dest='shell', const='sh', help="print sh commands to load the package") shells.add_argument( '--csh', action='store_const', dest='shell', const='csh', help="print csh commands to load the package") shells.add_argument( '--fish', action='store_const', dest='shell', const='fish', help="print fish commands to load the package") subparser.add_argument( '--first', action='store_true', default=False, dest='load_first', help="load the first match if multiple packages match the spec" ) subparser.add_argument( '--only', default='package,dependencies', dest='things_to_load', choices=['package', 'dependencies'], help="""select whether to load the package and its dependencies the default is to load the package and all dependencies alternatively one can decide to load only the package or only the dependencies""" )
[ 2, 15069, 2211, 12, 1238, 2481, 13914, 45036, 3549, 2351, 4765, 11, 11419, 290, 584, 198, 2, 1338, 441, 4935, 34152, 13, 4091, 262, 1353, 12, 5715, 27975, 38162, 9947, 2393, 329, 3307, 13, 198, 2, 198, 2, 30628, 55, 12, 34156, 12, ...
2.924959
613
import numpy as np import imageio from PoissonTemperature import FiniteDifferenceMatrixConstruction if __name__ == '__main__': folder = './data/pie/' mask = imageio.imread(folder+'mask.png')[:, :, 0].astype(np.float32) background = imageio.imread(folder+'mona.png')[:, :, :3]/255 foreground = imageio.imread(folder+'gine.png')[:, :, :3]/255 mask[mask > 0] = np.nan ind2sub_fn = folder+'ind2sub.npy' sub2ind_fn = folder+'sub2ind.npy' ind_sub_conversion(mask, ind2sub_fn, sub2ind_fn) FDMC = FiniteDifferenceMatrixConstruction(ind2sub_fn, sub2ind_fn) result = pie(FDMC, background, foreground) imageio.imwrite(folder+'result.png', result)
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2939, 952, 198, 6738, 7695, 30927, 42492, 1330, 4463, 578, 28813, 1945, 46912, 36687, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 9483, 796, 705...
2.467626
278
from distutils.version import LooseVersion import requests import os import shutil import threading import webbrowser from zipfile import ZipFile from pathlib import Path import traceback import tempfile # import concurrent.futures from flask import Flask, url_for, make_response from flask.json import dumps from flask_restx import Api from mindsdb.__about__ import __version__ as mindsdb_version from mindsdb.interfaces.datastore.datastore import DataStore from mindsdb.interfaces.model.model_interface import ModelInterface from mindsdb.interfaces.database.integrations import IntegrationController from mindsdb.utilities.ps import is_pid_listen_port, wait_func_is_true from mindsdb.utilities.telemetry import inject_telemetry_to_static from mindsdb.utilities.config import Config from mindsdb.utilities.log import get_log from mindsdb.interfaces.storage.db import session from mindsdb.utilities.json_encoder import CustomJSONEncoder def update_static(): ''' Update Scout files basing on compatible-config.json content. Files will be downloaded and updated if new version of GUI > current. Current GUI version stored in static/version.txt. ''' config = Config() log = get_log('http') static_path = Path(config['paths']['static']) last_gui_version_lv = get_last_compatible_gui_version() current_gui_version_lv = get_current_gui_version() if last_gui_version_lv is False: return False if current_gui_version_lv is not None: if current_gui_version_lv >= last_gui_version_lv: return True log.info(f'New version of GUI available ({last_gui_version_lv.vstring}). Downloading...') temp_dir = tempfile.mkdtemp(prefix='mindsdb_gui_files_') success = download_gui(temp_dir, last_gui_version_lv.vstring) if success is False: shutil.rmtree(temp_dir) return False temp_dir_for_rm = tempfile.mkdtemp(prefix='mindsdb_gui_files_') shutil.rmtree(temp_dir_for_rm) shutil.copytree(str(static_path), temp_dir_for_rm) shutil.rmtree(str(static_path)) shutil.copytree(temp_dir, str(static_path)) shutil.rmtree(temp_dir_for_rm) log.info(f'GUI version updated to {last_gui_version_lv.vstring}') return True def _open_webbrowser(url: str, pid: int, port: int, init_static_thread, static_folder): """Open webbrowser with url when http service is started. If some error then do nothing. """ init_static_thread.join() inject_telemetry_to_static(static_folder) logger = get_log('http') try: is_http_active = wait_func_is_true(func=is_pid_listen_port, timeout=10, pid=pid, port=port) if is_http_active: webbrowser.open(url) except Exception as e: logger.error(f'Failed to open {url} in webbrowser with exception {e}') logger.error(traceback.format_exc()) session.close()
[ 6738, 1233, 26791, 13, 9641, 1330, 6706, 577, 14815, 198, 11748, 7007, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 11748, 4704, 278, 198, 11748, 3992, 40259, 198, 6738, 19974, 7753, 1330, 38636, 8979, 198, 6738, 3108, 8019, 1330, 10644...
2.72905
1,074
# Copyright Contributors to the Pyro-Cov project. # SPDX-License-Identifier: Apache-2.0 import functools import io import logging import math import re import sys import torch import torch.multiprocessing as mp from Bio import AlignIO from Bio.Phylo.NewickIO import Parser from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from .phylo import Phylogeny logger = logging.getLogger(__name__) FILE_FORMATS = { "nex": "nexus", "nexus": "nexus", "fasta": "fasta", "xml": "beast", } def count_nexus_trees(filename): """ Counts the number of trees in a nexus file. """ return sum(read_nexus_trees(filename, format="count")) def stack_nexus_trees(filename, *, max_num_trees=math.inf, processes=0): """ Loads a batch of trees from a nexus file. """ trees = read_nexus_trees( filename, format="torch", max_num_trees=max_num_trees, processes=processes ) return Phylogeny.stack(trees) def read_newick_tree(filename): """ Parse a single newick tree and convert to a ``Phylogeny``. """ with open(filename) as f: line = f.read().strip() tree = next(Parser.from_string(line).parse()) return Phylogeny.from_bio_phylo(tree) def read_alignment( filename, format=None, *, max_taxa=math.inf, max_characters=math.inf ): """ Reads a single alignment file to a torch tensor of probabilites. :param str filename: Name of input file. :param str format: Optional input format, e.g. "nexus" or "fasta". :param int max_taxa: Optional number of taxa for truncation. :param int max_characters: Optional number of characters for truncation. :rtype: torch.Tensor :returns: A float tensor of shape ``(num_sequences, num_characters, num_bases)`` that is normalized along its rightmost dimension. Note that ``num_bases`` is 5 = 4 + 1, where the final base denots a gap or indel. """ # Load a Bio.Align.MultipleSeqAlignment object. logger.info(f"Loading data from {filename}") if format is None: suffix = filename.split(".")[-1].lower() format = FILE_FORMATS.get(suffix) if format is None: raise ValueError("Please specify a file format, e.g. 'nexus' or 'fasta'") elif format == "nexus": alignment = _read_alignment_nexus(filename) elif format == "beast": alignment = _read_alignment_beast(filename) else: alignment = AlignIO.read(filename, format) # Convert to a single torch.Tensor. num_taxa = min(len(alignment), max_taxa) if num_taxa < len(alignment): alignment = alignment[:num_taxa] num_characters = min(len(alignment[0]), max_characters) if num_characters < len(alignment[0]): alignment = alignment[:, :num_characters] logger.info(f"parsing {num_taxa} taxa x {num_characters} characters") codebook = _get_codebook() probs = torch.full((num_taxa, num_characters, 5), 1 / 5) for i in range(num_taxa): seq = alignment[i].seq if not VALID_CODES.issuperset(seq): raise ValueError(f"Invalid characters: {set(seq) - VALID_CODES}") # Replace gaps at ends with missing. beg, end = 0, probs.size(1) if seq[0] in "-.N": seq, old = seq.lstrip(seq[0]), seq beg += len(old) - len(seq) if seq[-1] in "-.N": seq, old = seq.rstrip(seq[-1]), seq end -= len(old) - len(seq) probs[i, beg:end] = codebook[list(map(ord, seq))] assert torch.isfinite(probs).all() return probs # See https://www.bioinformatics.org/sms/iupac.html NUCLEOTIDE_CODES = { # [ A, C, G, T, gap] "?": [1 / 5, 1 / 5, 1 / 5, 1 / 5, 1 / 5], # missing "n": [1 / 5, 1 / 5, 1 / 5, 1 / 5, 1 / 5], # missing "A": [1 / 1, 0.0, 0.0, 0.0, 0.0], # adenine "C": [0.0, 1 / 1, 0.0, 0.0, 0.0], # cytosine "G": [0.0, 0.0, 1 / 1, 0.0, 0.0], # guanine "T": [0.0, 0.0, 0.0, 1 / 1, 0.0], # thymine "U": [0.0, 0.0, 0.0, 1 / 1, 0.0], # uracil "R": [1 / 2, 0.0, 1 / 2, 0.0, 0.0], "Y": [0.0, 1 / 2, 0.0, 1 / 2, 0.0], "S": [0.0, 1 / 2, 1 / 2, 0.0, 0.0], "W": [1 / 2, 0.0, 0.0, 1 / 2, 0.0], "K": [0.0, 0.0, 1 / 2, 1 / 2, 0.0], "M": [1 / 2, 1 / 2, 0.0, 0.0, 0.0], "B": [0.0, 1 / 3, 1 / 3, 1 / 3, 0.0], "D": [1 / 3, 0.0, 1 / 3, 1 / 3, 0.0], "H": [1 / 3, 1 / 3, 0.0, 1 / 3, 0.0], "V": [1 / 3, 1 / 3, 1 / 3, 0.0, 0.0], "N": [1 / 4, 1 / 4, 1 / 4, 1 / 4, 0.0], "-": [0.0, 0.0, 0.0, 0.0, 1 / 1], # gap ".": [0.0, 0.0, 0.0, 0.0, 1 / 1], # gap } VALID_CODES = set(NUCLEOTIDE_CODES) AMBIGUOUS_CODES = { frozenset("AG"): "R", frozenset("CT"): "Y", frozenset("CG"): "S", frozenset("AT"): "W", frozenset("GT"): "K", frozenset("AC"): "M", frozenset("CGT"): "B", frozenset("AGT"): "D", frozenset("ACT"): "H", frozenset("ACG"): "V", frozenset("ACGT"): "N", } assert len(AMBIGUOUS_CODES) == 6 + 4 + 1
[ 2, 15069, 25767, 669, 284, 262, 44954, 12, 34, 709, 1628, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 11748, 1257, 310, 10141, 198, 11748, 33245, 198, 11748, 18931, 198, 11748, 10688, 198,...
2.137457
2,328
import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 29127, 62, 19849, 1330, 44800, 8081, 2234, 198 ]
3.56
25
# https://www.codingame.com/training/easy/bank-robbers from heapq import * solution()
[ 2, 3740, 1378, 2503, 13, 66, 7656, 480, 13, 785, 14, 34409, 14, 38171, 14, 17796, 12, 22609, 1213, 628, 198, 6738, 24575, 80, 1330, 1635, 628, 198, 198, 82, 2122, 3419, 198 ]
2.757576
33
""" {{ }} {% %} {% |, Book.id | add: 1 <= 2 id+12 |: %} 2 {% if book.name|length > 4 %} |name.length {{ book.pub_date|date:'Ymj' }} """ """ CSRF () CSRF """ """ session session """
[ 37811, 198, 220, 220, 220, 220, 198, 220, 220, 220, 22935, 220, 34949, 628, 220, 220, 220, 1391, 4, 220, 4064, 92, 628, 220, 220, 220, 1391, 4, 220, 930, 11, 4897, 13, 312, 930, 751, 25, 352, 19841, 362, 4686, 10, 1065, 198, 220...
1.713333
150
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Sky maps.""" from .base import * from .geom import * from .hpx import * from .hpxnd import * from .hpxsparse import * from .hpxmap import * from .wcs import * from .wcsnd import * from .wcsmap import * from .sparse import *
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 37811, 22308, 8739, 526, 15931, 198, 6738, 764, 8692, 1330, 1635, 198, 6738, 764, 469, 296, 1330, 1635, 198, 6738, 764, 71, 841...
2.91
100
import warnings from typing import Dict, Tuple from lhotse import CutSet from lhotse.dataset.sampling.base import CutSampler def find_pessimistic_batches( sampler: CutSampler, batch_tuple_index: int = 0 ) -> Tuple[Dict[str, CutSet], Dict[str, float]]: """ Function for finding 'pessimistic' batches, i.e. batches that have the highest potential to blow up the GPU memory during training. We will fully iterate the sampler and record the most risky batches under several criteria: - single longest cut - single longest supervision - largest batch cuts duration - largest batch supervisions duration - max num cuts - max num supervisions .. note: It is up to the users to convert the sampled CutSets into actual batches and test them by running forward and backward passes with their model. Example of how this function can be used with a PyTorch model and a :class:`~lhotse.dataset.K2SpeechRecognitionDataset`:: sampler = SingleCutSampler(cuts, max_duration=300) dataset = K2SpeechRecognitionDataset() batches, scores = find_pessimistic_batches(sampler) for reason, cuts in batches.items(): try: batch = dset[cuts] outputs = model(batch) loss = loss_fn(outputs) loss.backward() except: print(f"Exception caught when evaluating pessimistic batch for: {reason}={scores[reason]}") raise :param sampler: An instance of a Lhotse :class:`.CutSampler`. :param batch_tuple_index: Applicable to samplers that return tuples of :class:`~lhotse.cut.CutSet`. Indicates which position in the tuple we should look up for the CutSet. :return: A tuple of dicts: the first with batches (as CutSets) and the other with criteria values, i.e.: ``({"<criterion>": <CutSet>, ...}, {"<criterion>": <value>, ...})`` """ criteria = { "single_longest_cut": lambda cuts: max(c.duration for c in cuts), "single_longest_supervision": lambda cuts: max( sum(s.duration for s in c.supervisions) for c in cuts ), "largest_batch_cuts_duration": lambda cuts: sum(c.duration for c in cuts), "largest_batch_supervisions_duration": lambda cuts: sum( s.duration for c in cuts for s in c.supervisions ), "max_num_cuts": len, "max_num_supervisions": lambda cuts: sum( 1 for c in cuts for _ in c.supervisions ), } try: sampler = iter(sampler) first_batch = next(sampler) if isinstance(first_batch, tuple): first_batch = first_batch[batch_tuple_index] except StopIteration: warnings.warn("Empty sampler encountered in find_pessimistic_batches()") return {}, {} top_batches = {k: first_batch for k in criteria} top_values = {k: fn(first_batch) for k, fn in criteria.items()} for batch in sampler: if isinstance(batch, tuple): batch = batch[batch_tuple_index] for crit, fn in criteria.items(): val = fn(batch) if val > top_values[crit]: top_values[crit] = val top_batches[crit] = batch return top_batches, top_values
[ 11748, 14601, 198, 6738, 19720, 1330, 360, 713, 11, 309, 29291, 198, 198, 6738, 300, 8940, 325, 1330, 9712, 7248, 198, 6738, 300, 8940, 325, 13, 19608, 292, 316, 13, 37687, 11347, 13, 8692, 1330, 9712, 16305, 20053, 628, 198, 4299, 10...
2.47937
1,333
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-03 08:41 from __future__ import unicode_literals from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 319, 2177, 12, 3312, 12, 3070, 8487, 25, 3901, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738...
2.8
55
#!/usr/bin/env python import ComparisonStatistics import cdutil import os,sys # Reference ref = os.path.join(cdutil.__path__[0],'..','..','..','..','sample_data','tas_dnm-95a.xml') Ref=cdutil.VariableConditioner(ref) Ref.var='tas' Ref.id='reference' # Test tst = os.path.join(cdutil.__path__[0],'..','..','..','..','sample_data','tas_ccsr-95a.xml') Tst=cdutil.VariableConditioner(tst) Tst.var='tas' Tst.id='test' # Final Grid FG=cdutil.WeightedGridMaker() FG.longitude.n=36 FG.longitude.first=0. FG.longitude.delta=10. FG.latitude.n=18 FG.latitude.first=-85. FG.latitude.delta=10. # Now the compall thing c=ComparisonStatistics.ComparisonStatistics(Tst,Ref,weightedGridMaker=FG) c.fracmin=.5 c.minyr=3 icall=19 # Let's force the indices to be the same c.variableConditioner1.cdmsKeywords['time']=('1979','1982','co') c.variableConditioner2.cdmsKeywords['time']=slice(0,36) print "Before computing:" print c.variableConditioner1 #print 'C printing:\n',c ## (test,tfr),(ref,reffrc)=c() (test,tfr),(ref,reffrc) = c.compute() print "Test:",test # Retrieve the rank for th etime_domain 19 (monthly space time) rank=c.rank(time_domain=19) print 'Result for Rank:',rank c.write('tmp.nc',comments='A simple example')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 34420, 48346, 198, 11748, 22927, 22602, 198, 11748, 28686, 11, 17597, 198, 198, 2, 20984, 198, 5420, 796, 28686, 13, 6978, 13, 22179, 7, 10210, 22602, 13, 834, 6978, 834, 5...
2.521739
483
import math import numpy as np from mathipy.math import calculus
[ 11748, 10688, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 10688, 541, 88, 13, 11018, 1330, 41443 ]
3.764706
17
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This module contains the necessary functions to load a text-corpus from NLTK, contract all possible sentences, applying POS-tags to the contracted sentences and compare that with the original text. The information about which contraction+pos-tag pair gets expanded to which full form will be saved in a dictionary for use in expander.py """ __author__ = "Yannick Couzini" # standard library imports import pprint import yaml # third-party library imports import nltk # local library imports import utils # increase the allowed ram size that the models can use # nltk.internals.config_java(options='-xmx2G') def _find_sub_list(sublist, full_list): """ Args: - sublist is a list of words that are supposed to be found in the full list. - full list is a list of words that is supposed to be searched in. Returns: - List of tuples with the form (first_index_of_occurence, last_index_of_occurence) This function finds all occurences of sublist in the full_list. """ # this is the output list results = [] sublist_len = len(sublist) # loop over all ind if the word in full_list[ind] matches the first # word of the sublist for ind in (i for i, word in enumerate(full_list) if word == sublist[0]): # check that the complete sublist is matched if full_list[ind:ind+sublist_len] == sublist: # then append this to the results results.append((ind, ind+sublist_len-1)) return results def _invert_contractions_dict(): """ This is just a short function to return the inverted dictionary of the contraction dictionary. """ with open("contractions.yaml", "r") as stream: # load the dictionary containing all the contractions contractions = yaml.load(stream) # invert the dictionary for quicker finding of contractions expansions = dict() for key, value in contractions.items(): if len(value) == 1: continue for expansion in value: if expansion in expansions: print("WARNING: As an contraction to {}, {} is replaced with" " {}.".format(expansion, expansions[expansion], key)) expansions[expansion] = key return expansions def write_dictionary(pos_model, sent_lst, add_tags=0, use_ner=False, ner_args=None): """ Args: - pos_model is an instance of StanfordPOSTagger - sent-lst a list of sentences which themselves are lists of the single words. - add_tags is the amount of pos tags used after the relevant contraction, this can be used to further disambiguate but (of course) spreads out the data. - use_ner is boolean to decide whether to use named-entity-recognition for a potential increase in accuracy but with the obvious costs of performance. - ner_args is a list with an object of StanfordNERTagger and the tag to be used. This only needs to be supplied if use_ner is true. Returns: - None, but writes a disambiguations.yaml file with disambiguations for the ambiguous contractions in contractions.yaml. Raises: ValueError if use_ner is True but no ner_model is supplied. Using the provided list of sentences, contract them and pos-tag them. Using the pos-tags it is then possible to classify which (contraction, pos-tag) combinations get expanded to which ambiguous long form. """ # pylint: disable=too-many-locals if use_ner and (ner_args is None): raise ValueError("The use_ner flag is True but no NER" " model has been supplied!") expansions = _invert_contractions_dict() output_dict = dict() ambiguity_counter = 0 for tuple_rslt in _contract_sentences(expansions, sent_lst, use_ner=use_ner, ner_args=ner_args): # pos tag the sentence if use_ner: # first replace the NER tag with "it" pos_sent = [word.replace(ner_args[1], "it") for word in tuple_rslt[2]] # tag the sentence pos_sent = pos_model.tag(pos_sent) # and replace it with the tag again pos_sent = [(tuple_rslt[2][i], word_pos[1]) for i, word_pos in enumerate(pos_sent)] else: pos_sent = pos_model.tag(tuple_rslt[2]) # extract the pos tags on the contracted part contr_word_pos = pos_sent[tuple_rslt[0]:(tuple_rslt[0] + len(tuple_rslt[1]))] if add_tags == 0: contr_pos = tuple(contr_word_pos) else: add_pos_list = pos_sent[len(tuple_rslt[1]):(len(tuple_rslt[1]) + add_tags)] add_pos = [pos_word[1] for pos_word in add_pos_list] contr_pos = tuple(contr_word_pos + add_pos) # write a dictionary entry connecting the (words, pos) of the # contraction to the expanded part word = ' '.join(tuple_rslt[1]) if contr_pos not in output_dict: output_dict[contr_pos] = dict() output_dict[contr_pos][word] = 1 # keep track of the progress print("\n\n ---- \n\n") pprint.pprint(output_dict) print("Ambiguity counter is {}.".format(ambiguity_counter)) print("\n\n ---- \n\n") elif word in output_dict[contr_pos].keys(): # check whether the entry is already there output_dict[contr_pos][word] += 1 continue else: # if the combination of pos tags with words already occured # once then a list has to be made. Ideally this case doesn't # occur ambiguity_counter += 1 output_dict[contr_pos][word] = 1 print("\n\n ---- \n\n") print("AMBIGUITY ADDED!") pprint.pprint(output_dict) print("Ambiguity counter is {}.".format(ambiguity_counter)) print("\n\n ---- \n\n") with open("disambiguations.yaml", "w") as stream: yaml.dump(output_dict, stream) if __name__ == '__main__': # if you call this function directly just build the disambiguation # dictionary. # load a corpus that has the form of list of sentences which is # split up into a list of words SENT_LST = nltk.corpus.brown.sents() SENT_LST += nltk.corpus.gutenberg.sents() SENT_LST += nltk.corpus.reuters.sents() SENT_LST += nltk.corpus.inaugural.sents() POS_MODEL = utils.load_stanford('pos') NER_MODEL = utils.load_stanford('ner') write_dictionary(POS_MODEL, SENT_LST, add_tags=1, use_ner=False, ner_args=[NER_MODEL, "<NE>"])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 1212, 8265, 4909, 262, 3306, 5499, 284, 3440, 220, 257, 2420, 12, 10215, 79, 385, 422, 198, 45, 2773...
2.20206
3,301
# pylint: disable = C0111 from setuptools import find_packages, setup setup(name="paperai", # version="1.5.0", # author="NeuML", # description="AI-powered literature discovery and review engine for medical/scientific papers", # long_description=DESCRIPTION, # long_description_content_type="text/markdown", # url="https://github.com/neuml/paperai", # project_urls={ # "Documentation": "https://github.com/neuml/paperai", # "Issue Tracker": "https://github.com/neuml/paperai/issues", # "Source Code": "https://github.com/neuml/paperai", # }, # C:\Users\sxm\Desktop\paperai # project_urls={ # "Documentation": "C:\\Users\\sxm\\Desktop\\paperai", # "Source Code": "C:\\Users\\sxm\\Desktop\\paperai", #}, license="Apache 2.0: C:\\Users\\sxm\\Desktop\\paperai\\LICENSE", packages=find_packages(where="C:\\Users\\sxm\\Desktop\\paperai\\src\\python"), package_dir={"": "src\\python"}, keywords="search embedding machine-learning nlp covid-19 medical scientific papers", python_requires=">=3.6", entry_points={ "console_scripts": [ "paperai = paperai.shell:main", ], }, install_requires=[ "html2text>=2020.1.16", # "mdv>=1.7.4", "networkx>=2.4", "PyYAML>=5.3", "regex>=2020.5.14", "txtai>=1.4.0", "txtmarker>=1.0.0" ], classifiers=[ "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Software Development", "Topic :: Text Processing :: Indexing", "Topic :: Utilities" ])
[ 2, 279, 2645, 600, 25, 15560, 796, 327, 486, 1157, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 628, 198, 40406, 7, 3672, 2625, 20189, 1872, 1600, 198, 220, 220, 220, 220, 220, 1303, 2196, 2625, 16, 13, 20, 13, 1...
2.210341
851
from io import BytesIO from typing import List, Dict from PIL import Image from hit_analysis.commons.config import Config from hit_analysis.commons.consts import IMAGE, CROP_X, CROP_Y, CROP_SIZE, FRAME_DECODED, CLASSIFIED, CLASS_ARTIFACT, ORIG_IMAGE def do_reconstruct(detections: List[dict], config: Config) -> None: """ Reconstruction the fill by black cropped frame in CREDO Detector app v2. The detection[x]['frame_decoded'] will be replaced by new value, old value will be stored in detection[x]['frame_decoded_orig']. No any changes when count of detections is less or equal 1 :param detections: should be sorted by detection_id :param config: config object """ if len(detections) <= 1: return sp = [str(detections[0].get('device_id')), str(detections[0].get('timestamp'))] image = Image.new('RGBA', (detections[0].get('width'), detections[0].get('height')), (0, 0, 0)) edge = 'no_edge' for d in detections: if d.get('edge'): edge = 'edge' for d in reversed(detections): append_to_frame(image, d) config.store_png(['recostruct', edge, *sp, 'orig'], d.get('id'), d.get(IMAGE)) for d in detections: replace_from_frame(image, d) config.store_png(['recostruct', edge, *sp], d.get('id'), d.get(IMAGE)) if config.out_dir: image.save('%s/recostruct/%s/%s/frame.png' % (config.out_dir, edge, "/".join(sp))) def check_all_artifacts(detections: List[dict]) -> bool: """ Check if all detections is just classified as artifacts :param detections: list of detections to check :return: True - all detections is artifacts """ for d in detections: if d.get(CLASSIFIED) != CLASS_ARTIFACT: return False return True def filter_unclassified(by_timestamp: Dict[int, List[dict]]) -> List[int]: """ Filter detections with one or more unclassified as artifact. :param by_timestamp: detections grouped by timestamp :return: list of filtered timestamp keys """ ret = [] for timestamp, detections in by_timestamp.items(): if not check_all_artifacts(detections): ret.append(timestamp) return ret
[ 6738, 33245, 1330, 2750, 4879, 9399, 198, 6738, 19720, 1330, 7343, 11, 360, 713, 198, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 6738, 2277, 62, 20930, 13, 9503, 684, 13, 11250, 1330, 17056, 198, 6738, 2277, 62, 20930, 13, 9503, 684,...
2.614387
848
# Copyright 2022 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """ test graph fallback control flow if in if scenario""" import pytest import numpy as np from mindspore import Tensor, ms_function, context context.set_context(mode=context.GRAPH_MODE)
[ 2, 15069, 33160, 43208, 21852, 1766, 1539, 12052, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198...
4.114286
210
# -*- coding: utf-8 -*- from scipy.fftpack import fft, fftshift, ifft from scipy.fftpack import fftfreq from scipy.signal import find_peaks from scipy import signal import numpy as np import matplotlib.pyplot as plt import pickle import warnings import sys from scipy.signal.filter_design import maxflat warnings.filterwarnings("ignore") MAPEMax = 1e4 MAPEStdMax = 1e4 FigCount = 0 TLowBoundBase = 0.4 TLowBound = TLowBoundBase TRound = 6 SetTLowBound = False GrpFigCount = 0 # # wfr 20210107 # wfr 20210130 N , N # PctRange , PctRange N # wfr 20210126 , , # T MAPE(Mean Absolute Percentage Error) # arraySample # arrayTimeStamp # T # , , # wfr 20210108 # wfr 20210116 # wfr 20201230
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 629, 541, 88, 13, 487, 83, 8002, 1330, 277, 701, 11, 277, 701, 30846, 11, 611, 701, 198, 6738, 629, 541, 88, 13, 487, 83, 8002, 1330, 277, 701, 19503, 80, 19...
2.407407
297
import numpy as np import numpy.testing as npt import slippy import slippy.core as core """ If you add a material you need to add the properties that it will be tested with to the material_parameters dict, the key should be the name of the class (what ever it is declared as after the class key word). The value should be a tuple of dicts: The first dict in the tuple will be unpacked to instantiate the class, The second will be used with the displacement from loads method The third will be used with the loads from displacement method to ensure that the methods are inverses of each other If there is a limit the applicability of the displacements from loads method (such as for a perfectly plastic material the _max_load key word should be set in the second dict. For more complex behaviour please also implement your own tests """ material_parameters = { 'Elastic': ({'name': 'steel_5', 'properties': {'E': 200e9, 'v': 0.3}}, {'grid_spacing': 0.01, 'simple': True}, {'grid_spacing': 0.01, 'simple': True, 'tol': 1e-9}), 'Rigid': ({}, {}, {}) } exceptions = [core.Rigid]
[ 11748, 299, 32152, 355, 45941, 198, 11748, 299, 32152, 13, 33407, 355, 299, 457, 198, 11748, 1017, 41214, 198, 11748, 1017, 41214, 13, 7295, 355, 4755, 198, 198, 37811, 198, 1532, 345, 751, 257, 2587, 345, 761, 284, 751, 262, 6608, 32...
3.242775
346
#!/usr/bin/env python """Restore files with ending BACKUP_ENDING to original files.""" # The copyright in this software is being made available under the BSD License, # included below. This software may be subject to other third party and contributor # rights, including patent rights, and no such rights are granted under this license. # # Copyright (c) 2016, Dash Industry Forum. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation and/or # other materials provided with the distribution. # * Neither the name of Dash Industry Forum nor the names of its # contributors may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os import sys from backup_handler import BACKUP_ENDING def main(): "Command-line function." from optparse import OptionParser parser = OptionParser() #pylint: disable=unused-variable (options, args) = parser.parse_args() if len(args) < 1: parser.error("Wrong number of arguments") sys.exit(1) for file_name in args: if file_name.endswith(BACKUP_ENDING): old_name = file_name[:-len(BACKUP_ENDING)] print("moving %s to %s" % (file_name, old_name)) if os.path.exists(old_name): os.unlink(old_name) os.rename(file_name, old_name) continue if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 19452, 382, 3696, 351, 7464, 28767, 8577, 62, 10619, 2751, 284, 2656, 3696, 526, 15931, 198, 198, 2, 383, 6634, 287, 428, 3788, 318, 852, 925, 1695, 739, 262, 347, 10305, 13789,...
3.127404
832
# Copyright 2020-2021 OpenDR European Project # # 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 pyglet import numpy as np import sklearn.preprocessing
[ 2, 15069, 12131, 12, 1238, 2481, 4946, 7707, 3427, 4935, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, ...
3.813953
172
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-01-30 10:40 from __future__ import unicode_literals import bluebottle.utils.fields from decimal import Decimal from django.db import migrations, models import django.db.models.deletion import djmoney.models.fields
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 13, 23, 319, 13130, 12, 486, 12, 1270, 838, 25, 1821, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 1...
3.01087
92
# import os # os.environ.setdefault('PICKLE_STORAGE_SETTINGS', 'pickle_storage.tests.settings')
[ 2, 1330, 28686, 198, 2, 28686, 13, 268, 2268, 13, 2617, 12286, 10786, 47, 11860, 2538, 62, 2257, 1581, 11879, 62, 28480, 51, 20754, 3256, 705, 27729, 293, 62, 35350, 13, 41989, 13, 33692, 11537 ]
2.714286
35
import argparse import json import os
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 28686, 628, 628, 628, 628 ]
3.461538
13
from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from sumy.parsers.html import HtmlParser from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer #from sumy.summarizers.lsa import LsaSummarizer as Summarizer from sumy.summarizers.lex_rank import LexRankSummarizer as Summarizer from sumy.nlp.stemmers import Stemmer from sumy.utils import get_stop_words # t = TextSummarizer() # t.summarize_from_file("obama_short.txt") # pdf = pdfgeneration() # pdf.generate_pdf_summarizer("summarizer_output2.txt")
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 3601, 62, 8818, 11, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 2160, 88, 13, 79, 945, 364, 13, 6494, 1330, 367, 20369, 46677, 198, 6738, ...
2.995025
201
"""Unit test package for super_json_normalize."""
[ 37811, 26453, 1332, 5301, 329, 2208, 62, 17752, 62, 11265, 1096, 526, 15931, 198 ]
3.571429
14
# An example of a turbulent BEC in a harmonic trap. The groundstate is found # and then some vortices randomly printed about with a phase printing. Some # evolution in imaginary time is then performed to smooth things out before # evolving the BEC in time. # Run with 'mpirun -n <N CPUs> python run_example.py' from __future__ import division, print_function import sys # sys.path.insert(0, '../..') # The location of the modules we need to import import numpy as np from parPDE import Simulator2D, LAPLACIAN from parPDE.BEC2D import BEC2D def get_number_and_trap(rhomax, R): """Gives the 2D normalisation constant and trap frequency required for the specified maximum density and radius of a single-component condensate in the Thomas-Fermi approximation""" N = pi * rhomax * R**2 / 2 omega = np.sqrt(2 * g * rhomax / (m * R**2)) return N, omega # Constants: pi = np.pi hbar = 1.054571726e-34 # Reduced Planck's constant a_0 = 5.29177209e-11 # Bohr radius u = 1.660539e-27 # unified atomic mass unit m = 86.909180*u # 87Rb atomic mass a = 98.98*a_0 # 87Rb |2,2> scattering length g = 4*pi*hbar**2*a/m # 87Rb self interaction constant rhomax = 2.5e14 * 1e6 # Desired peak condensate density R = 7.5e-6 # Desired condensate radius mu = g * rhomax # Approximate chemical potential for desired max density # (assuming all population is in in mF=+1 or mF=-1) N_2D, omega = get_number_and_trap(rhomax, R) # 2D normalisation constant and trap frequency # required for specified radius and peak density # Space: nx_global = ny_global = 256 x_max_global = y_max_global = 10e-6 simulator = Simulator2D(-x_max_global, x_max_global, -y_max_global, y_max_global, nx_global, ny_global, periodic_x=True, periodic_y=True, operator_order=6) bec2d = BEC2D(simulator, natural_units=False, use_ffts=True) x = simulator.x y = simulator.y dx = simulator.dx dy = simulator.dy r2 = x**2.0 + y**2.0 r = np.sqrt(r2) # A Harmonic trap: V = 0.5 * m * omega**2 * R**2.0 * (r/R)**2 dispersion_timescale = dx**2 * m / (pi * hbar) chemical_potential_timescale = 2*pi*hbar/mu potential_timescale = 2*pi*hbar/V.max() K = -hbar**2/(2*m)*LAPLACIAN def H(t, psi): """The Hamiltonian for single-component wavefunction psi. Returns the kinetic term as an OperatorSum instance, and the local terms separately.""" H_local_lin = V H_local_nonlin = g * abs(psi)**2 return K, H_local_lin, H_local_nonlin if __name__ == '__main__': # The initial Thomas-Fermi guess: psi = rhomax * (1 - (x**2 + y**2) / R**2) psi[psi < 0] = 0 psi = np.sqrt(psi) # Find the groundstate: psi = bec2d.find_groundstate(H, mu, psi, relaxation_parameter=1.7, convergence=1e-13, output_interval=100, output_directory='groundstate', convergence_check_interval=10) # psi is real so far, convert it to complex: psi = np.array(psi, dtype=complex) # Print some vortices, seeding the pseudorandom number generator so that # MPI processes all agree on where the vortices are: np.random.seed(42) for i in range(30): sign = np.sign(np.random.normal()) x_vortex = np.random.normal(0, scale=R) y_vortex = np.random.normal(0, scale=R) psi[:] *= np.exp(sign * 1j*np.arctan2(x - y_vortex, y - x_vortex)) # Smooth it a bit in imaginary time: psi = bec2d.evolve(dt=dispersion_timescale/2, t_final=chemical_potential_timescale, H=H, psi=psi, mu=mu, method='rk4', imaginary_time=True, output_interval=100, output_directory='smoothing') # And evolve it in time for 10ms: psi = bec2d.evolve(dt=dispersion_timescale/2, t_final=10e-3, H=H, psi=psi, mu=mu, method='rk4', imaginary_time=False, output_interval=100, output_directory='evolution')
[ 2, 1052, 1672, 286, 257, 42291, 347, 2943, 287, 257, 49239, 12840, 13, 383, 2323, 5219, 318, 1043, 198, 2, 290, 788, 617, 410, 419, 1063, 15456, 10398, 546, 351, 257, 7108, 13570, 13, 2773, 198, 2, 6954, 287, 26726, 640, 318, 788, ...
2.191467
1,922
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 28 09:33:53 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, InitialCondition from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe import numpy as np helps = { 'show' : 'show the results figure', } from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/fluid_mesh.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field_1 = Field.from_args(name='3_velocity', dtype=nm.float64, shape=3, region=omega, approx_order=1) field_2 = Field.from_args(name='pressure', dtype=nm.float64, shape=1, region=omega, approx_order=1) region_0 = domain.create_region(name='Walls1', select='vertices in (y < -0.049)', kind='facet') region_1 = domain.create_region(name='Walls2', select='vertices in (y > 0.049)', kind='facet') region_2 = domain.create_region(name='Inlet', select='vertices in (x < -0.499)', kind='facet') region_3 = domain.create_region(name='Outlet', select='vertices in (x > -0.499)', kind='facet') ebc_1 = EssentialBC(name='Walls1', region=region_0, dofs={'u.[0,1,2]' : 0.0}) ebc_2 = EssentialBC(name='Walls2', region=region_1, dofs={'u.[0,1,2]' : 0.0}) ebc_3 = EssentialBC(name='Inlet', region=region_2, dofs={'u.0' : 1.0, 'u.[1,2]' : 0.0}) ebc_4 = EssentialBC(name='Outlet', region=region_3, dofs={'p':0.0, 'u.[1,2]' : 0.0}) viscosity = Material(name='viscosity', value=1.25e-3) variable_1 = FieldVariable('u', 'unknown', field_1) variable_2 = FieldVariable(name='v', kind='test', field=field_1, primary_var_name='u') variable_3 = FieldVariable(name='p', kind='unknown', field=field_2) variable_4 = FieldVariable(name='q', kind='test', field=field_2, primary_var_name='p') integral_1 = Integral('i1', order=2) integral_2 = Integral('i2', order=3) t1 = Term.new(name='dw_div_grad(viscosity.value, v, u)', integral=integral_2, region=omega, viscosity=viscosity, v=variable_2, u=variable_1) t2 = Term.new(name='dw_convect(v, u)', integral=integral_2, region=omega, v=variable_2, u=variable_1) t3 = Term.new(name='dw_stokes(v, p)', integral=integral_1, region=omega, v=variable_2, p=variable_3) t4 = Term.new(name='dw_stokes(u, q)', integral=integral_1, region=omega, u=variable_1, q=variable_4) eq1 = Equation('balance', t1+t2-t3) eq2 = Equation('incompressibility', t4) eqs = Equations([eq1,eq2]) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({'i_max' : 20, 'eps_a' : 1e-8, 'eps_r' : 1.0, 'macheps' : 1e-16, 'lin_red' : 1e-2, 'ls_red' : 0.1, 'ls_red_warp' : 0.001, 'ls_on' : 0.99999, 'ls_min' : 1e-5, 'check' : 0, 'delta' : 1e-6}, lin_solver=ls, status=nls_status) pb = Problem('Navier-Stokes', equations=eqs) pb.set_bcs(ebcs=Conditions([ebc_1, ebc_2, ebc_3])) pb.set_solver(nls) status = IndexedStruct() state = pb.solve(status=status, save_results=True) out = state.create_output_dict() pb.save_state('Navier_Stokes.vtk', out=out) view = Viewer('Navier_Stokes.vtk') view(rel_scaling=2, is_scalar_bar=True, is_wireframe=True)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 2892, 4280, 2579, 7769, 25, 2091, 25, 4310, 12131, 198, 198, 31, 9800, 25, 34590, 724, 82...
2.370236
1,653
# -*- coding: utf-8 -*- from __future__ import unicode_literals import frappe import json from frappe.utils import now, cint from functools import partial from toolz import compose _get_subsections = compose( partial(map, lambda x: x.get("test_event") or x.get("particulars")), partial(filter, lambda x: cint(x.is_subsection) == 1), )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 11748, 5306, 27768, 198, 11748, 33918, 198, 6738, 5306, 27768, 13, 26791, 1330, 783, 11, 269, 600, 198, ...
2.830645
124
#!/usr/bin/env python3 from scripts.workflow import get_app_name, is_name_valid from scripts.workflow import get_args, is_args_valid from scripts.workflow import create_dir, create_app, create_templates_folder, create_static_folder, create_dockerfile from scripts.manual import print_manual from scripts.messages import empty_name, success_msg, failure_msg import sys app_name = get_app_name() args = get_args() args.remove(app_name) # validate name of app!! if (is_name_valid(app_name)): # validate all arguments first!! if(is_args_valid(args)): # Create folder named app_name create_dir(app_name) # Arguments debugger_mode = False import_css_js = False use_docker = False if '-d' in args or '--debugger' in args: debugger_mode = True print("- Debugger mode on") print(" |__ added debug=True") else: print("- Debugger mode off") if '-cj' in args or '--css-js' in args: import_css_js = True create_static_folder(app_name) print("- Css and Js mode on") print(" |__ import static/stylesheet/style.css") print(" |__ import static/js/app.css") else: print("- Css and Js mode off") if '-dc' in args or '--docker-container' in args: use_docker = True print("- Docker mode on") print(' |__ cd %s' % app_name) print(' |__ \"docker-compose up -d\" to start app') else: print("- Docker mode off") # create templates folder to hold index.html create_templates_folder(app_name, import_css_js) # create app.py in root directory(app_name) create_app(app_name, debugger_mode) # move application to docker container; if (use_docker): # generate Dockerfile create_dockerfile(app_name) success_msg(app_name) else: print('Unknown argument detected! Please check the help section\n') print_manual() failure_msg(app_name) else: if (app_name == '-h' or app_name == '--help'): print_manual() else: print('Please choose another app name') failure_msg(app_name)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 6738, 14750, 13, 1818, 11125, 1330, 651, 62, 1324, 62, 3672, 11, 318, 62, 3672, 62, 12102, 198, 6738, 14750, 13, 1818, 11125, 1330, 651, 62, 22046, 11, 220, 318, 62, 22046, 62, ...
2.26713
1,007
import os from pathlib import Path from jinja2 import Template import parser from utils import write_to_file from utils import mkdir_p parser.init() # parse and assign to vars spec = parser.spec def _concat(slice: str) -> str: """helper to concatenate each template slice.""" return "{}\n".format(slice) def slices_filename_content_hash() -> dict: """create a dict of filename: content for slices""" docker_slices = {} path = Path.cwd().joinpath( os.path.join(os.path.dirname(os.path.realpath(__file__)), "slices") ) for file in path.iterdir(): docker_slices[file.name] = file.read_text() return docker_slices def concat_slices(component: str = "tensorflow", flavor: str = "mkl") -> str: """concatenate templates based on the what user want""" docker_slices = slices_filename_content_hash() names = ["os.dockerfile"] dockerfile = "" if component == "tensorflow" and flavor == "mkl": names.append("tensorflow.dockerfile") names.append("horovod.dockerfile") if component == "pytorch" and flavor == "mkl": names.append("pytorch.dockerfile") names.append("horovod.dockerfile") for name in names: dockerfile += _concat(docker_slices[name]) return "".join(dockerfile) def generate_dockerfile(os: str, framework: str, file_name: str = "Dockerfile"): """generate and write to dir dockerfiles per `os` and `framework`""" dlrs = spec["stack"]["dlrs"] os_version = dlrs[os]["version"] pkgs = dlrs[os]["os_pkgs"] tf_version = dlrs[os]["tensorflow"]["mkl"]["version"] hvd_version = dlrs[os]["horovod"]["version"] torch_version = dlrs[os]["pytorch"]["mkl"]["version"] pkg_installer = "apt-get install -y" if os == "ubuntu" else "swupd bundle-add" kwargs = { "os": "{}:{}".format(os, os_version), "pkg_install": "{} {}".format(pkg_installer, " ".join(pkgs)), "tf_version": tf_version, "hvd_version": hvd_version, "torch_version": torch_version, } dockerfile_template = concat_slices(framework) dockerfile = insert_template_values(dockerfile_template, kwargs) write_to_file(file_name, dockerfile) def generate_all_dockerfiles(generate: bool = True, build: bool = False) -> None: """generate all dockerfiles for all frameworks and OSes""" if generate: base_dir = "./dockerfiles" for framework in ["pytorch", "tensorflow"]: for _os in ["ubuntu", "clearlinux"]: save_to_dir = mkdir_p(os.path.join(base_dir, _os, framework)) save_to_file = os.path.join(save_to_dir, "Dockerfile") generate_dockerfile(_os, framework, save_to_file) if build: # TOOD(unrahul) build the dockerfiles pass
[ 11748, 28686, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 474, 259, 6592, 17, 1330, 37350, 198, 198, 11748, 30751, 198, 6738, 3384, 4487, 1330, 3551, 62, 1462, 62, 7753, 198, 6738, 3384, 4487, 1330, 33480, 15908, 62, 79, 198, ...
2.430435
1,150
# -*- coding:utf-8 -*- # /usr/bin/env python """ Author: Albert King date: 2019/10/20 10:58 contact: jindaxiang@163.com desc: """ # headers SHORT_HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36' } # url FX_SPOT_URL = "http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/rfx-sp-quot.json" FX_SWAP_URL = "http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/rfx-sw-quot.json" FX_PAIR_URL = "http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/cpair-quot.json" # payload SPOT_PAYLOAD = { "t": {} }
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 13838, 25, 9966, 2677, 198, 4475, 25, 13130, 14, 940, 14, 1238, 838, 25, 3365, 198, 32057, 25, 474, 521, 897,...
2.128028
289
import os from datetime import datetime import pytest from entropylab import ExperimentResources, SqlAlchemyDB, PyNode, Graph
[ 11748, 28686, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 920, 1773, 2645, 397, 1330, 29544, 33236, 11, 311, 13976, 2348, 26599, 11012, 11, 9485, 19667, 11, 29681, 628 ]
3.583333
36
from .file_core import FileEngine from src.utils.utils import * from .version import __version__
[ 6738, 764, 7753, 62, 7295, 1330, 9220, 13798, 198, 6738, 12351, 13, 26791, 13, 26791, 1330, 1635, 198, 6738, 764, 9641, 1330, 11593, 9641, 834, 198 ]
3.730769
26
# # def add(x, y): # """ # Add Number Together # """ # return x+y # # # def subtract(x, y): # """ # Subtract x from y # """ # return x-y
[ 2, 198, 2, 825, 751, 7, 87, 11, 331, 2599, 198, 2, 220, 220, 220, 220, 37227, 198, 2, 220, 220, 220, 220, 3060, 7913, 17083, 198, 2, 220, 220, 220, 220, 37227, 198, 2, 220, 220, 220, 220, 1441, 2124, 10, 88, 198, 2, 198, 2, ...
1.817204
93
from open_anafi.models import Indicator, IndicatorParameter, IndicatorLibelle from open_anafi.serializers import IndicatorSerializer from .frame_tools import FrameTools from open_anafi.lib import parsing_tools from open_anafi.lib.ply.parsing_classes import Indic import re from django.db import transaction from django.core.exceptions import ObjectDoesNotExist
[ 6738, 1280, 62, 272, 19910, 13, 27530, 1330, 1423, 26407, 11, 1423, 26407, 36301, 11, 1423, 26407, 25835, 13485, 198, 6738, 1280, 62, 272, 19910, 13, 46911, 11341, 1330, 1423, 26407, 32634, 7509, 198, 6738, 764, 14535, 62, 31391, 1330, ...
3.60396
101
import os,sys,math,random from phycas import * from MCMCManager import LikelihoodCore from phycas.utilities.PhycasCommand import * from phycas.readnexus import NexusReader from phycas.utilities.CommonFunctions import CommonFunctions
[ 11748, 28686, 11, 17597, 11, 11018, 11, 25120, 198, 6738, 872, 88, 34004, 1330, 1635, 198, 6738, 13122, 9655, 13511, 1330, 4525, 11935, 14055, 198, 6738, 872, 88, 34004, 13, 315, 2410, 13, 2725, 88, 34004, 21575, 1330, 1635, 198, 6738, ...
3.477612
67
from app import db import datetime from flask_mongoengine.wtf import model_form TodoForm = model_form(Todo)
[ 6738, 598, 1330, 20613, 198, 11748, 4818, 8079, 198, 6738, 42903, 62, 76, 25162, 18392, 13, 86, 27110, 1330, 2746, 62, 687, 628, 198, 51, 24313, 8479, 796, 2746, 62, 687, 7, 51, 24313, 8, 198 ]
3.055556
36
dia = int(input('Dia = ')) mes = str(input('Ms = ')) ano = int(input('Ano = ')) print('Voc nasceu no dia {} de {} de {}. Correto?' .format(dia, mes, ano))
[ 67, 544, 796, 493, 7, 15414, 10786, 35, 544, 796, 705, 4008, 198, 6880, 796, 965, 7, 15414, 10786, 10128, 796, 705, 4008, 198, 5733, 796, 493, 7, 15414, 10786, 2025, 78, 796, 705, 4008, 198, 4798, 10786, 53, 420, 25221, 344, 84, 6...
2.279412
68
############################################################################## # Copyright (c) 2009-2021, Hajime Nakagami<nakagami@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Python DB-API 2.0 module for Firebird. ############################################################################## from firebirdsql.consts import * # noqa from firebirdsql.utils import * # noqa from firebirdsql.fbcore import Connection
[ 29113, 29113, 7804, 4242, 2235, 198, 2, 15069, 357, 66, 8, 3717, 12, 1238, 2481, 11, 29399, 524, 22255, 363, 6277, 27, 77, 461, 363, 6277, 31, 14816, 13, 785, 29, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 2297, 396, 3890, 2...
3.650862
464
from discord.ext import commands from typing import Union from types import ModuleType from .context import Context
[ 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 19720, 1330, 4479, 198, 6738, 3858, 1330, 19937, 6030, 198, 198, 6738, 764, 22866, 1330, 30532, 628 ]
4.72
25
import logging from credstuffer.db.connector import DBConnector from credstuffer.exceptions import DBCreatorError
[ 11748, 18931, 198, 6738, 2600, 301, 13712, 13, 9945, 13, 8443, 273, 1330, 360, 2749, 261, 1606, 273, 198, 6738, 2600, 301, 13712, 13, 1069, 11755, 1330, 360, 2749, 630, 273, 12331, 628, 628, 628, 198 ]
3.333333
36
from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING if TYPE_CHECKING: from poetry.core.poetry import Poetry
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 41876, 62, 50084, 2751, 628, 198, 361, 41876, 62, 50084, 2751, 25, 198, 220, 220, 220, 422, 19518, 13, 7295, 13, 7501, 11973, 1330, ...
3.568182
44
"""users.country Revision ID: 429d596c43a7 Revises: 77e0c0edaa04 Create Date: 2020-10-23 21:26:55.598146 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '429d596c43a7' down_revision = '77e0c0edaa04' branch_labels = None depends_on = None
[ 37811, 18417, 13, 19315, 198, 198, 18009, 1166, 4522, 25, 42313, 67, 45734, 66, 3559, 64, 22, 198, 18009, 2696, 25, 8541, 68, 15, 66, 15, 276, 7252, 3023, 198, 16447, 7536, 25, 12131, 12, 940, 12, 1954, 2310, 25, 2075, 25, 2816, 1...
2.471074
121
""" Module for processing mentions of the bot via the Twitter API. """ from ConnectFourGame import * from databasehelpers import * from helpers import * from minimax import * def process_mentions(): """ Scan through recent mentions and send them to be processed. """ api = get_twitter_api() first = True since_id = get_read_since() newest_tweet_id = None for tweet in limit_handled(tweepy.Cursor(api.mentions_timeline).items()): if int(tweet.id_str) <= int(since_id): # if tweet has already been processed... if first is True: # & we haven't seen any other tweets yet: log("No new mentions to process.") else: # we have processed other tweets, thus: log("Processed mentions from " + str(since_id) + " to " + str(newest_tweet_id) + ".") set_read_since(newest_tweet_id) return if first is True: # Collect ID of first tweet processed. newest_tweet_id = tweet.id_str first = False if tweet.in_reply_to_status_id is None: # Check if mention starts a game thread. result_newgame = try_newgame(tweet) if result_newgame is not None: record_outgoing_tweet(result_newgame) else: # Check if mention is a valid play on an existing game thread. doc = get_active_game(str(tweet.in_reply_to_status_id)) if doc is not None: result_game = try_playturn(tweet, doc) if result_game is not None: record_outgoing_tweet(result_game) remove_active_game(str(tweet.in_reply_to_status_id)) def try_newgame(tweet): """ Process a single attempted new game. :param tweet: The tweet to be processed as new game. :type tweet: Tweepy.Status, dict :return: The resulting new game, or None if no new game made. :rtype: None, ConnectFourGame """ if tweet.in_reply_to_status_id is None: # not reply to another tweet if tweet.text.split(" ")[1] == "new": # second word is 'new' user1 = tweet.user.screen_name # TWO PLAYER GAME if len(tweet.entities[u'user_mentions']) > 1: user2 = tweet.entities[u'user_mentions'][1][u'screen_name'] newgame = ConnectFourGame.new_game(get_next_game_id(), user1, user2, int(tweet.id_str)) log("Created two player game: " + newgame.game_to_string()) return newgame # ONE PLAYER GAME if tweet.text.split(" ")[2] == "singleplayer": user2 = " mimimax_ai_alpha" newgame = ConnectFourGame.new_game(get_next_game_id(), user1, user2, int(tweet.id_str)) newgame.play_turn(int(tweet.id_str), minimax(newgame, 3)) log("Created one player game: " + newgame.game_to_string()) return newgame def try_playturn(tweet, doc): """ Process a single tweet as an attempted move on an open game. :param tweet: The tweet to be processed as an attempted move on an open game. :type tweet: Tweepy.Status, dict :param doc: The database item storing the game onto which the turn is played. :type doc: dict :return: The resulting game after the move is played, or None if move not played. :rtype: ConnectFourGame, None """ game = ConnectFourGame.game_from_string(doc["game"]) active_user = game.user2 if game.user1_is_playing == 1: active_user = game.user1 move_index = 2 if game.user1 == game.user2 or game.user2 == " mimimax_ai_alpha": move_index = 1 tweet_text = tweet.text.split(" ") if len(tweet_text) >= move_index + 1: column_played = tweet_text[move_index] if any(column_played == s for s in ["1", "2", "3", "4", "5", "6", "7"]): if (tweet.user.screen_name == active_user) & game.can_play(int(column_played)): # PLAY TURN game.play_turn(int(tweet.id_str), int(column_played)) log(active_user + " played a " + column_played + " resulting in game: " + game.game_to_string()) if game.user2 == ' mimimax_ai_alpha': ai_move = minimax(game, 3) game.play_turn(int(tweet.id_str), ai_move) log("mimimax_ai_v1 played a " + str(ai_move) + " resulting in game: " + game.game_to_string()) return game if __name__ == '__main__': process_mentions()
[ 37811, 19937, 329, 7587, 15802, 286, 262, 10214, 2884, 262, 3009, 7824, 13, 198, 37811, 198, 6738, 8113, 15137, 8777, 1330, 1635, 198, 6738, 6831, 16794, 364, 1330, 1635, 198, 6738, 49385, 1330, 1635, 198, 6738, 10356, 897, 1330, 1635, ...
2.268634
1,999
import pandas as pd
[ 11748, 19798, 292, 355, 279, 67, 628 ]
3
7
from .command import Command, ApiCommand
[ 6738, 764, 21812, 1330, 9455, 11, 5949, 72, 21575, 198 ]
4.1
10
from unittest import TestCase, main from single_package.single import Single if __name__ == "__main__": main()
[ 6738, 555, 715, 395, 1330, 6208, 20448, 11, 1388, 198, 6738, 2060, 62, 26495, 13, 29762, 1330, 14206, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
3.105263
38
import responses from tests.util import random_str from tests.util import mock_http_response from binance.spot import Spot as Client from binance.lib.utils import encoded_string from binance.error import ParameterRequiredError mock_item = {"key_1": "value_1", "key_2": "value_2"} key = random_str() secret = random_str() params = { "email": "alice@test.com", "coin": "BNB", "network": "BNB", "recvWindow": 1000, } def test_sub_account_deposit_address_without_email(): """Tests the API endpoint to get deposit address without email""" params = {"email": "", "coin": "BNB", "network": "BNB", "recvWindow": 1000} client = Client(key, secret) client.sub_account_deposit_address.when.called_with(**params).should.throw( ParameterRequiredError ) def test_sub_account_deposit_address_without_coin(): """Tests the API endpoint to get deposit address without coin""" params = { "email": "alice@test.com", "coin": "", "network": "BNB", "recvWindow": 1000, } client = Client(key, secret) client.sub_account_deposit_address.when.called_with(**params).should.throw( ParameterRequiredError )
[ 11748, 9109, 198, 198, 6738, 5254, 13, 22602, 1330, 4738, 62, 2536, 198, 6738, 5254, 13, 22602, 1330, 15290, 62, 4023, 62, 26209, 198, 6738, 9874, 590, 13, 20485, 1330, 15899, 355, 20985, 198, 6738, 9874, 590, 13, 8019, 13, 26791, 133...
2.698198
444
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import copy import traceback from telemetry import value as value_module from telemetry.results import page_run from telemetry.results import progress_reporter as progress_reporter_module from telemetry.value import failure from telemetry.value import skip def DidRunPage(self, page, discard_run=False): # pylint: disable=W0613 """ Args: page: The current page under test. discard_run: Whether to discard the entire run and all of its associated results. """ assert self._current_page_run, 'Did not call WillRunPage.' self._progress_reporter.DidRunPage(self) if not discard_run: self._all_page_runs.append(self._current_page_run) self._current_page_run = None def WillAttemptPageRun(self, attempt_count, max_attempts): """To be called when a single attempt on a page run is starting. This is called between WillRunPage and DidRunPage and can be called multiple times, one for each attempt. Args: attempt_count: The current attempt number, start at 1 (attempt_count == 1 for the first attempt, 2 for second attempt, and so on). max_attempts: Maximum number of page run attempts before failing. """ self._progress_reporter.WillAttemptPageRun( self, attempt_count, max_attempts) # Clear any values from previous attempts for this page run. self._current_page_run.ClearValues()
[ 2, 15069, 1946, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 11748...
3.103113
514
from tensorflow.keras.models import Model import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np import cv2 import numpy as np import pandas as pd from tensorflow.keras.models import load_model import tensorflow as tf import os #--------------------------------------------------------------------------------- # get data #--------------------------------------------------------------------------------- #------------------------------------------------------------------------------------ # find last conv layer #----------------------------------------------------------------------------------- #---------------------------------------------------------------------------------- # calculate gradient class actiavtion map #---------------------------------------------------------------------------------- def compute_heatmap(model, saved_model, image, pred_index, last_conv_layer): """ construct our gradient model by supplying (1) the inputs to our pre-trained model, (2) the output of the (presumably) final 4D layer in the network, and (3) the output of the softmax activations from the model """ gradModel = Model( inputs=[model.inputs], outputs=[model.get_layer(last_conv_layer).output, model.output] ) # record operations for automatic differentiation with tf.GradientTape() as tape: """ cast the image tensor to a float-32 data type, pass the image through the gradient model, and grab the loss associated with the specific class index """ print(pred_index) inputs = tf.cast(image, tf.float32) print(image.shape) last_conv_layer_output, preds = gradModel(inputs) print(preds) print(preds.shape) # class_channel = preds[:, pred_index] class_channel = preds # use automatic differentiation to compute the gradients grads = tape.gradient(class_channel, last_conv_layer_output) """ This is a vector where each entry is the mean intensity of the gradient over a specific feature map channel """ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) """ We multiply each channel in the feature map array by "how important this channel is" with regard to the top predicted class then sum all the channels to obtain the heatmap class activation """ last_conv_layer_output = last_conv_layer_output[0] heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis] heatmap = tf.squeeze(heatmap) # For visualization purpose, we will also normalize the heatmap between 0 & 1 heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap) heatmap = heatmap.numpy() return heatmap #------------------------------------------------------------------------------------ # save gradcam heat map #----------------------------------------------------------------------------------- # jet_heatmap0.save(os.path.join(save_dir, fn2)) # jet_heatmap.save(os.path.join(save_dir, fn3)) # img0.save(os.path.join(save_dir, fn4)) if __name__ == '__main__': train_img_dir = '/media/bhkann/HN_RES1/HN_CONTRAST/train_img_dir' val_save_dir = '/mnt/aertslab/USERS/Zezhong/constrast_detection/val' test_save_dir = '/mnt/aertslab/USERS/Zezhong/constrast_detection/test' exval_save_dir = '/mnt/aertslab/USERS/Zezhong/constrast_detection/exval' val_gradcam_dir = '/mnt/aertslab/USERS/Zezhong/constrast_detection/val/gradcam' test_gradcam_dir = '/mnt/aertslab/USERS/Zezhong/constrast_detection/test/gradcam' exval_gradcam_dir = '/mnt/aertslab/USERS/Zezhong/constrast_detection/test/gradcam' pro_data_dir = '/home/bhkann/zezhong/git_repo/IV-Contrast-CNN-Project/pro_data' model_dir = '/mnt/aertslab/USERS/Zezhong/contrast_detection/model' input_channel = 3 re_size = (192, 192) i = 72 crop = True alpha = 0.9 saved_model = 'ResNet_2021_07_18_06_28_40' show_network = False conv_n = 'conv5' run_type = 'val' #--------------------------------------------------------- # run main function #-------------------------------------------------------- if run_type == 'val': save_dir = val_save_dir elif run_type == 'test': save_dir = test_save_dir ## load model and find conv layers model = load_model(os.path.join(model_dir, saved_model)) # model.summary() list_i = [100, 105, 110, 115, 120, 125] for i in list_i: image, label, pred_index, y_pred, ID = data( input_channel=input_channel, i=i, val_save_dir=val_save_dir, test_save_dir=test_save_dir ) conv_list = ['conv2', 'conv3', 'conv4', 'conv5'] conv_list = ['conv4'] for conv_n in conv_list: if conv_n == 'conv2': last_conv_layer = 'conv2_block3_1_conv' elif conv_n == 'conv3': last_conv_layer = 'conv3_block4_1_conv' elif conv_n == 'conv4': last_conv_layer = 'conv4_block6_1_conv' elif conv_n == 'conv5': last_conv_layer = 'conv5_block3_out' heatmap = compute_heatmap( model=model, saved_model=saved_model, image=image, pred_index=pred_index, last_conv_layer=last_conv_layer ) save_gradcam( image=image, heatmap=heatmap, val_gradcam_dir=val_gradcam_dir, test_gradcam_dir=test_gradcam_dir, alpha=alpha, i=i ) print('label:', label) print('ID:', ID) print('y_pred:', y_pred) print('prediction:', pred_index) print('conv layer:', conv_n) # if last_conv_layer is None: # last_conv_layer = find_target_layer( # model=model, # saved_model=saved_model # ) # print(last_conv_layer) # # if show_network == True: # for idx in range(len(model.layers)): # print(model.get_layer(index = idx).name) # # compute the guided gradients # castConvOutputs = tf.cast(convOutputs > 0, "float32") # castGrads = tf.cast(grads > 0, "float32") # guidedGrads = castConvOutputs * castGrads * grads # # the convolution and guided gradients have a batch dimension # # (which we don't need) so let's grab the volume itself and # # discard the batch # convOutputs = convOutputs[0] # guidedGrads = guidedGrads[0] # # # compute the average of the gradient values, and using them # # as weights, compute the ponderation of the filters with # # respect to the weights # weights = tf.reduce_mean(guidedGrads, axis=(0, 1)) # cam = tf.reduce_sum(tf.multiply(weights, convOutputs), axis=-1) # # # grab the spatial dimensions of the input image and resize # # the output class activation map to match the input image # # dimensions ## (w, h) = (image.shape[2], image.shape[1]) ## heatmap = cv2.resize(cam.numpy(), (w, h)) # heatmap = cv2.resize(heatmap.numpy(), (64, 64)) # # normalize the heatmap such that all values lie in the range ## # [0, 1], scale the resulting values to the range [0, 255], ## # and then convert to an unsigned 8-bit integer # numer = heatmap - np.min(heatmap) # eps = 1e-8 # denom = (heatmap.max() - heatmap.min()) + eps # heatmap = numer / denom # heatmap = (heatmap * 255).astype("uint8") # colormap=cv2.COLORMAP_VIRIDIS # heatmap = cv2.applyColorMap(heatmap, colormap) # print('heatmap shape:', heatmap.shape) ## img = image[:, :, :, 0] ## print('img shape:', img.shape) # img = image.reshape((64, 64, 3)) # print(img.shape) # output = cv2.addWeighted(img, 0.5, heatmap, 0.5, 0) # # # return heatmap, output
[ 6738, 11192, 273, 11125, 13, 6122, 292, 13, 27530, 1330, 9104, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 11125, 1330, 41927, 292, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 2603, 29...
2.467822
3,232
# coding:utf-8 """ start rob task good luck! > python start.py """ import datetime import time from sys import version_info import threadpool import ticket_config as config from config.stations import check_station_exists from train.login import Login from train.order import Order from train.ticket import Ticket from util.app_util import current_date, validate_date_str, current_hour, current_timestamp, datetime_str_timestamp, \ validate_time_str from util.logger import Logger log = Logger('INFO') if __name__ == '__main__': if version_info.major != 3 or version_info.minor != 6: log.error("Python3.6") # Checking config information if not validate_date_str(config.DATE): log.error('') exit(0) today = datetime.datetime.strptime(current_date(), '%Y-%m-%d') depart_day = datetime.datetime.strptime(config.DATE, '%Y-%m-%d') difference = (depart_day - today).days if difference > 29 or difference < 0: log.error('12306') exit(0) if not check_station_exists(config.FROM_STATION) or not check_station_exists(config.TO_STATION): log.error('') exit(0) if config.SELL_TIME != '': if not validate_time_str(config.SELL_TIME): log.error('') exit(0) login = Login() while True: hour = current_hour() if hour > 22 or hour < 6: time.sleep(1.5) continue else: login.login() order = Order(None) if not order.search_unfinished_order(): break count = 0 # Sell time if config.SELL_TIME != '': start_time = datetime_str_timestamp(config.DATE + ' ' + config.SELL_TIME) log.info('Waiting for sell ticket...') while True: current_time = current_timestamp() + 2505600 if start_time - current_time < 0: break log.info('Starting...') while True: ticket_list = Ticket.search_stack(from_station=config.FROM_STATION, to_station=config.TO_STATION, train_date=config.DATE) # Filter unable ticket ticket_list = list(filter(lambda x: x.sell_time == '', ticket_list)) if len(ticket_list) < 1: log.info('') continue count += 1 if config.SEAT_TYPE: ticket_list = [i for i in ticket_list if i.train_no in config.TRAINS_NO] Ticket.show_tickets(ticket_list) seat_level_all = [([0] * len(config.TRAINS_NO)) for i in range(len(config.SEAT_TYPE))] for j, ticket in enumerate(ticket_list): ticket_seat = ticket.get_seat_level(config.SEAT_TYPE) for i, seat in enumerate(ticket_seat): seat_level_all[i][j] = seat # Choose a ticket that you can order usable_ticket = {} for i in seat_level_all: for j in i: train_no = j['train_no'] usable = j['usable'] seat_type = j['type'] if usable == '--' or usable == 'no' or usable == '*': usable = 0 elif usable == 'yes': usable = 21 usable = int(usable) if usable > 0: usable_ticket = {'train_no': train_no, 'type': seat_type, 'seat_count': usable} break else: continue break if usable_ticket: order_ticket = None for ticket in ticket_list: if ticket.train_no == usable_ticket['train_no']: order_ticket = ticket break order_ticket.seat_type = usable_ticket['type'] order_ticket.seat_count = usable_ticket['seat_count'] order = Order(order_ticket) order.submit() log.info(order) log.info('...') order.order_callback() break else: log.warning(': {}'.format(count)) time.sleep(1) break
[ 2, 19617, 25, 40477, 12, 23, 198, 198, 37811, 198, 9688, 3857, 4876, 922, 8458, 0, 198, 198, 29, 21015, 923, 13, 9078, 198, 37811, 198, 198, 11748, 4818, 8079, 198, 11748, 640, 198, 6738, 25064, 1330, 2196, 62, 10951, 198, 198, 1174...
1.788447
2,666
import subprocess import sys import os import setup_util from os.path import expanduser
[ 198, 11748, 850, 14681, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 9058, 62, 22602, 198, 6738, 28686, 13, 6978, 1330, 4292, 7220, 198 ]
3.708333
24
import os, stat
[ 11748, 28686, 11, 1185, 198 ]
3.2
5
from django.db import models from django.utils.translation import ugettext_lazy as _, ugettext
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 13, 41519, 1330, 334, 1136, 5239, 62, 75, 12582, 355, 4808, 11, 334, 1136, 5239, 628, 628, 628, 628 ]
3.1875
32
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Common utility functions Created on Sun May 27 16:37:42 2018 @author: chen """ import math import cv2 import os from imutils import paths import numpy as np import scipy.ndimage def rotate_cooridinate(cooridinate_og,rotate_angle,rotate_center): """ calculate the coordinates after rotation """ rotate_angle = rotate_angle*(math.pi/180) rotated_x = (cooridinate_og[0]-rotate_center[0])*math.cos(rotate_angle)\ -(cooridinate_og[1]-rotate_center[1])*math.sin(rotate_angle)+rotate_center[0] rotated_y = (cooridinate_og[0]-rotate_center[0])*math.sin(rotate_angle)\ +(cooridinate_og[1]-rotate_center[1])*math.cos(rotate_angle)+rotate_center[1] rotated_coordinate = np.array([rotated_x,rotated_y]) rotated_coordinate = np.round(rotated_coordinate).astype(np.int) return rotated_coordinate def mkdir(path): """ create new folder automatically """ folder = os.path.exists(path) if not folder: os.makedirs(path) def load_data(path): """ load data from specified folder """ print("[INFO] loading images...") imgs = [] # grab the image paths and randomly shuffle them imagePaths = sorted(list(paths.list_images(path))) for imagePath in imagePaths: # load the image, pre-process it, and store it in the data list image = cv2.imread(imagePath,cv2.IMREAD_GRAYSCALE) imgs.append(image) return imgs def normfun(x,sigma): """ function of normal distribution """ mu = 45 pdf = np.exp(-((x - mu)**2)/(2*sigma**2)) / (sigma * np.sqrt(2*np.pi)) return pdf def calc_box(box,x_gap,y_gap,rotate_angle,center): """ calculate the size of the required surrounding environment for doorway segmentation box: four corners' coordinates of doorway x_gap: remained space in the vertical way y_gap: remained space in the horizontal way """ door_box = np.array([box[0][::-1]+[y_gap,x_gap],box[1][::-1]+[y_gap,-x_gap], box[2][::-1]-[y_gap,x_gap],box[3][::-1]-[y_gap,-x_gap]]) rotated_box = [] for coordinate in door_box: box_coordinate = rotate_cooridinate(coordinate,rotate_angle,center) rotated_box.append(box_coordinate) rotated_box = np.array(rotated_box) box = [np.min(rotated_box[:,0]),np.min(rotated_box[:,1]),np.max(rotated_box[:,0]),np.max(rotated_box[:,1])] return box def calc_IoU(candidateBound, groundTruthBounds): """ calculate the intersection over union """ cx1 = candidateBound[0] cy1 = candidateBound[1] cx2 = candidateBound[2] cy2 = candidateBound[3] gx1 = groundTruthBounds[:,0] gy1 = groundTruthBounds[:,1] gx2 = groundTruthBounds[:,2] gy2 = groundTruthBounds[:,3] carea = (cx2 - cx1) * (cy2 - cy1) garea = (gx2 - gx1) * (gy2 - gy1) x1 = np.maximum(cx1, gx1) y1 = np.maximum(cy1, gy1) x2 = np.minimum(cx2, gx2) y2 = np.minimum(cy2, gy2) w = np.maximum(0, x2 - x1) h = np.maximum(0, y2 - y1) area = w * h ious = area / (carea + garea - area) return ious def overlapp(candidateBound, groundTruthBounds): """ calculate the proportion of prediction to groundtruth """ cx1 = candidateBound[0] cy1 = candidateBound[1] cx2 = candidateBound[2] cy2 = candidateBound[3] gx1 = groundTruthBounds[:,0] gy1 = groundTruthBounds[:,1] gx2 = groundTruthBounds[:,2] gy2 = groundTruthBounds[:,3] garea = (gx2 - gx1) * (gy2 - gy1) x1 = np.maximum(cx1, gx1) y1 = np.maximum(cy1, gy1) x2 = np.minimum(cx2, gx2) y2 = np.minimum(cy2, gy2) w = np.maximum(0, x2 - x1) h = np.maximum(0, y2 - y1) area = w * h reious = area / garea return reious def calc_corner(door_center,door_size,door_depth,side): """ calculate the corners' coordinates from the centroid, size and depth of doorway door_corners_inside is a list of coordinates of corners close to the corridor door_corners_outside is a list of coordinates of corners close to the room """ door_corners_inside = [door_center-np.array([np.int(door_size/2),0]), door_center+np.array([door_size-np.int(door_size/2),0])] door_corners_outside = [x-np.array([0,np.power(-1,side)*door_depth[side]]) for x in door_corners_inside] door_corners_outside = np.array(door_corners_outside) return door_corners_inside,door_corners_outside def draw_door(mask,complete_map,door,door_depth,side): """ label the doorway on the mask and add some error inside the doorway region """ door_size = abs(door[1,0]-door[0,0]) door_area_inside = door+np.array([0,np.power(-1,side)*door_depth[side]]) # label the doorway on the mask cv2.rectangle(mask,tuple(door[0][::-1]),tuple(door_area_inside[1][::-1]),255,-1) # add a small point to emulate the error in the doorway region if door_size>20: if np.random.randint(4)==0: if side ==0: pt_center = [np.random.randint(door[0,0]+4,door[1,0]-3),np.random.randint(door[0,1],door_area_inside[0,1])] else: pt_center = [np.random.randint(door[0,0]+3,door[1,0]-2),np.random.randint(door_area_inside[0,1],door[0,1])] cv2.circle(complete_map,tuple(pt_center[::-1]),np.random.choice([1,2,3]),0,-1) return door_size def room_division(room_space,num_room): """ assign the lengths of rooms according to the length of corridor and number of rooms room_space: coordinates of corridor's side num_room: the number of rooms on one side rooms: a list of the coordinates belonging to different rooms rooms_corners: a list of only the top and bottom cooridnates of different rooms """ rooms = [] rooms_corners=[] a = num_room thickness = np.random.randint(2,5) length = room_space.shape[0]-(num_room-1)*thickness start_point = 0 for i in range(num_room-1): room_size = np.random.randint(length/(a+0.7),length/(a-0.7)) room = room_space[start_point:start_point+room_size,:] rooms.append(room) start_point +=room_size+thickness room = room_space[start_point:,:] rooms.append(room) rooms = [room.astype(np.int) for room in rooms] for x in rooms: rooms_corner = np.concatenate((x[0,:][np.newaxis,:],x[-1,:][np.newaxis,:]),axis = 0) rooms_corners.append(rooms_corner) return rooms,rooms_corners def calc_gradient(gmap): """ calculate the gradient of image to find the contour """ kernel = np.array([[1,1,1],[1,-8,1],[1,1,1]]) img = gmap.astype(np.int16) gradient = scipy.ndimage.correlate(img,kernel,mode = 'constant',cval =127) return gradient
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 17227, 10361, 5499, 220, 198, 198, 41972, 319, 3825, 1737, 2681, 1467, 25, 2718, 25, 3682, 2864, 198, ...
2.257729
3,073
import os import sys from subprocess import CalledProcessError from working_with_github.utils import run
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 850, 14681, 1330, 34099, 18709, 12331, 198, 198, 6738, 1762, 62, 4480, 62, 12567, 13, 26791, 1330, 1057, 628, 628, 198 ]
3.928571
28
import logging import time import re import serial from threading import Thread, Event from respeaker import Microphone from respeaker import BingSpeechAPI from respeaker import PixelRing,pixel_ring BING_KEY = '95e4fe8b3a324389be4595bd1813121c' ser = serial.Serial('/dev/ttyS1',115200,timeout=0) data=[0xAA,0x01,0x64,0x55] data1=[0xAA,0x01,0x00,0x55] data2=[0xAA,0x01,0x00,0x55,0xAA,0x00,0x00,0x55] data3=[0xAA,0x01,0x64,0x55,0xAA,0x00,0x64,0x55] lefthand = [0xAA,0x00,0x32,0x55] righthand = [0xAA,0x01,0x32,0x55] nodhead = [0xAA,0x02,0x32,0x55] shakehead = [0xAA,0x03,0x32,0x55] wakeup = [0xAA,0x02,0x64,0x55,0xAA,0x03,0x64,0x55] origin = [lefthand,righthand,nodhead,shakehead] if __name__ == '__main__': main()
[ 11748, 18931, 198, 11748, 640, 198, 11748, 302, 198, 11748, 11389, 198, 6738, 4704, 278, 1330, 14122, 11, 8558, 198, 198, 6738, 581, 431, 3110, 1330, 4527, 4862, 198, 198, 6738, 581, 431, 3110, 1330, 21631, 5248, 3055, 17614, 198, 6738,...
1.915567
379
#!/usr/bin/env python # encoding: utf-8 ''' @author: caroline @license: (C) Copyright 2019-2022, Node Supply Chain Manager Corporation Limited. @contact: caroline.fang.cc@gmail.com @software: pycharm @file: account_voteCredit.py @time: 2020/1/8 11:23 @desc: ''' from apis.API import request_Api def voteCredit(api_name, params): ''' curl -H "Content-Type: application/json" -X post --data '{"jsonrpc":"2.0","method":"account_voteCredit","params":["0x300fc5a14e578be28c64627c0e7e321771c58cd4","0x0ad472fd967eb77fb6e36ec40901790065155d5e","0xf4240","0x110","0x30000"],"id":1}' http://127.0.0.1:15645 :param api_name: :param params:fromto gas :return:hash ''' try: result = request_Api(api_name, params) print("api{}".format(result)) except Exception as e: print("api:{}".format(e)) if __name__ == '__main__': api_name = "account_voteCredit" params = ["0xaD3dC2D8aedef155eabA42Ab72C1FE480699336c", "0xef32f718642426fba949b42e3aff6c56fe08b23c", "0xf4240", "0x110", "0x30000"] voteCredit(api_name, params)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 7061, 6, 198, 31, 9800, 25, 1097, 14453, 198, 31, 43085, 25, 357, 34, 8, 15069, 13130, 12, 1238, 1828, 11, 19081, 22663, 21853, 9142, 10501, 15...
2.328798
441
import numpy as np from matplotlib import pyplot as plt # np.random.seed(3) shape = (100, 2) x = (np.random.random((shape[0], shape[1])) * 100).astype(int) x = np.c_[np.ones((shape[0], 1)), x] w = np.array([-5, -2, 2]) w = w.reshape(-1, 1) y = np.dot(x, w) pos_index = np.where(y > 10)[0] neg_index = np.where(y < 10)[0] plt.scatter(x[:, 1][pos_index], x[:, 2][pos_index], marker="P") plt.scatter(x[:, 1][neg_index], x[:, 2][neg_index], marker=0) plt.show() best_w = pla(x, y,100) print(best_w)
[ 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 628, 198, 198, 2, 220, 628, 198, 37659, 13, 25120, 13, 28826, 7, 18, 8, 198, 43358, 796, 357, 3064, 11, 362, 8, 198, 87, 796, 357, 3765...
2.0875
240
from ..utils import _make_pseudo_id from .base import BaseModel, cleanup_list, SourceMixin from .bill import Bill from .popolo import pseudo_organization from .schemas.vote_event import schema from pupa.exceptions import ScrapeValueError import re
[ 6738, 11485, 26791, 1330, 4808, 15883, 62, 7752, 12003, 62, 312, 198, 6738, 764, 8692, 1330, 7308, 17633, 11, 27425, 62, 4868, 11, 8090, 35608, 259, 198, 6738, 764, 35546, 1330, 3941, 198, 6738, 764, 12924, 14057, 1330, 24543, 62, 9971,...
3.521127
71
#################### # ES-DOC CIM Questionnaire # Copyright (c) 2017 ES-DOC. All rights reserved. # # University of Colorado, Boulder # http://cires.colorado.edu/ # # This project is distributed according to the terms of the MIT license [http://www.opensource.org/licenses/MIT]. #################### from django.db import models from django.conf import settings import os from Q.questionnaire import APP_LABEL, q_logger from Q.questionnaire.q_fields import QVersionField from Q.questionnaire.q_utils import EnumeratedType, EnumeratedTypeList from Q.questionnaire.q_constants import * ################### # local constants # ################### PUBLICATION_UPLOAD_DIR = "publications" PUBLICATION_UPLOAD_PATH = os.path.join(APP_LABEL, PUBLICATION_UPLOAD_DIR) QPublicationFormats = EnumeratedTypeList([ QPublicactionFormat("CIM2_XML", "CIM2 XML"), ]) #################### # the actual class # ####################
[ 14468, 4242, 198, 2, 220, 220, 13380, 12, 38715, 327, 3955, 18233, 24042, 198, 2, 220, 220, 15069, 357, 66, 8, 2177, 13380, 12, 38715, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 220, 220, 2059, 286, 7492, 11, 27437, 198, 2, 220, ...
3.25784
287
# -*- coding: utf-8 -*- import os import shutil from django.conf import settings from django.core.management import call_command from django.test import TestCase from six import StringIO try: from unittest.mock import patch except ImportError: from mock import patch
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 4423, 346, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 1330, 869, 62, 21812, 198, 6738, ...
3.195402
87
import pandas as pd import numpy as np from cvxopt import matrix from cvxopt import solvers import math main()
[ 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 269, 85, 87, 8738, 1330, 17593, 198, 6738, 269, 85, 87, 8738, 1330, 1540, 690, 198, 11748, 10688, 628, 198, 12417, 3419 ]
3
38
Anything = AnythingType()
[ 198, 40028, 796, 21035, 6030, 3419, 198 ]
3.857143
7
import os, IP2Location, sys, ipaddress # database = IP2Location.IP2Location(os.path.join("data", "IPV6-COUNTRY.BIN"), "SHARED_MEMORY") database = IP2Location.IP2Location(os.path.join("data", "IPV6-COUNTRY.BIN")) try: ip = sys.argv[1] if ip == '' : print ('You cannot enter an empty IP address.') sys.exit(1) else: try: ipaddress.ip_address(ip) except ValueError: print ('Invalid IP address') sys.exit(1) rec = database.get_all(ip) print (rec) except IndexError: print ("Please enter an IP address to continue.") database.close()
[ 11748, 28686, 11, 6101, 17, 14749, 11, 25064, 11, 20966, 21975, 198, 198, 2, 6831, 796, 6101, 17, 14749, 13, 4061, 17, 14749, 7, 418, 13, 6978, 13, 22179, 7203, 7890, 1600, 366, 4061, 53, 21, 12, 34, 19385, 40405, 13, 33, 1268, 12...
2.268116
276
import ADT_of_person as AP import datetime as dm #ADT Staff() # Staff(self, str name, str sex, tuple birthday, tuple entey_date, int salary, str position) # name(self) # sex(self) # en_year(self) # salary(self) # set_salary(self, new_salary) # position(self) # set_position(self, new_position) # birthday(self) # detail(self)
[ 11748, 5984, 51, 62, 1659, 62, 6259, 355, 3486, 201, 198, 11748, 4818, 8079, 355, 288, 76, 201, 198, 201, 198, 2, 2885, 51, 9983, 3419, 201, 198, 2, 220, 220, 9983, 7, 944, 11, 965, 1438, 11, 965, 1714, 11, 46545, 10955, 11, 465...
2.329032
155
""" Test signal handlers for completion. """ from datetime import datetime from unittest.mock import patch import ddt import pytest from completion import handlers from completion.models import BlockCompletion from completion.test_utils import CompletionSetUpMixin from django.test import TestCase from pytz import utc from xblock.completable import XBlockCompletionMode from xblock.core import XBlock from lms.djangoapps.grades.api import signals as grades_signals from openedx.core.djangolib.testing.utils import skip_unless_lms
[ 37811, 198, 14402, 6737, 32847, 329, 11939, 13, 198, 37811, 198, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 11748, 288, 28664, 198, 11748, 12972, 9288, 198, 6738, 11939, 1330, ...
3.610738
149
from typing import Tuple import pygame import numpy as np from .wall import Wall
[ 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 12972, 6057, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 764, 11930, 1330, 5007, 628 ]
3.5
24
light_up(light_1, light_2, light_3) Sets the brightness of the individual lights on the Color Sensor. This causes the Color Sensor to change modes, which can affect your program in unexpected ways. For example, the Color Sensor can't read colors when it's in light up mode. Parameters light_1 The desired brightness of light 1. Type : integer (a positive or negative whole number, including 0) Values : 0 to 100% ("0" is off, and "100" is full brightness.) Default : 100% light_2 The desired brightness of light 2. Type : integer (a positive or negative whole number, including 0) Values : 0 to 100% ("0" is off, and "100" is full brightness.) Default : 100% light_3 The desired brightness of light 3. Type : integer (a positive or negative whole number, including 0) Values : 0 to 100% ("0" is off, and "100" is full brightness.) Default : 100% Errors TypeError light_1, light_2, or light_3 is not an integer. RuntimeError The sensor has been disconnected from the Port. Example light_up(light_1, light_2, light_3) Sets the brightness of the individual lights on the Color Sensor. This causes the Color Sensor to change modes, which can affect your program in unexpected ways. For example, the Color Sensor can't read colors when it's in light up mode. Parameters light_1 The desired brightness of light 1. Type : integer (a positive or negative whole number, including 0) Values : 0 to 100% ("0" is off, and "100" is full brightness.) Default : 100% light_2 The desired brightness of light 2. Type : integer (a positive or negative whole number, including 0) Values : 0 to 100% ("0" is off, and "100" is full brightness.) Default : 100% light_3 The desired brightness of light 3. Type : integer (a positive or negative whole number, including 0) Values : 0 to 100% ("0" is off, and "100" is full brightness.) Default : 100% Errors TypeError light_1, light_2, or light_3 is not an integer. RuntimeError The sensor has been disconnected from the Port. Example
[ 2971, 62, 929, 7, 2971, 62, 16, 11, 1657, 62, 17, 11, 1657, 62, 18, 8, 198, 50, 1039, 262, 22204, 286, 262, 1981, 7588, 319, 262, 5315, 35367, 13, 198, 1212, 5640, 262, 5315, 35367, 284, 1487, 12881, 11, 543, 460, 2689, 534, 143...
3.418118
574
''' Script by: Gabriele Bendetti date: 25/06/2021 Utilities functions. This file is used to have a more organized main script. It contains: + Random plane orientation generator that can be used to practice plane attitude interpretation + Random fold generator + Plotter + Data converter from pandas dataframe to dict following the format used in plane_plot ''' import numpy as np import matplotlib.pyplot as plt import mplstereonet import obspy.imaging.beachball as bb import mplstereonet as mpl # Convert CSV in dictionary with valid format such as {nset:{dd:[..],d:[..]},..}
[ 7061, 6, 198, 198, 7391, 416, 25, 12300, 5034, 293, 26874, 24851, 198, 198, 4475, 25, 1679, 14, 3312, 14, 1238, 2481, 198, 198, 18274, 2410, 5499, 13, 770, 2393, 318, 973, 284, 423, 257, 517, 8389, 1388, 4226, 13, 632, 4909, 25, 1...
3.342541
181
import tensorflow as tf import os from bayes_filter import logging from bayes_filter.filters import FreeTransitionVariationalBayes from bayes_filter.feeds import DatapackFeed, IndexFeed from bayes_filter.misc import make_example_datapack, maybe_create_posterior_solsets, get_screen_directions from bayes_filter.datapack import DataPack, _load_array_file import numpy as np if __name__ == '__main__': output_folder = os.path.join(os.path.abspath('test_filter_vi_P126+65'), 'run15') os.makedirs(output_folder, exist_ok=True) # datapack = make_example_datapack(5, 10, 2, name=os.path.join(output_folder, 'test_data.h5'), gain_noise=0.3, # index_n=1, obs_type='DTEC', clobber=True, # kernel_hyperparams={'variance': 3.5 ** 2, 'lengthscales': 15., 'a': 250., # 'b': 100., 'timescale': 50.}) datapack = DataPack('/net/lofar1/data1/albert/imaging/data/P126+65_compact_raw/P126+65_full_compact_raw.h5') datapack.current_solset = 'sol000' actual_antenna_labels, _ = datapack.antennas antenna_labels, antennas = _load_array_file(DataPack.lofar_array) antennas = np.stack([antennas[list(antenna_labels).index(a.astype(antenna_labels.dtype)),:] for a in actual_antenna_labels],axis=0) datapack.set_antennas(antenna_labels, antennas) patch_names, _ = datapack.directions _, screen_directions = datapack.get_directions(patch_names) screen_directions = get_screen_directions('/home/albert/ftp/image.pybdsm.srl.fits', max_N=None) maybe_create_posterior_solsets(datapack, 'sol000', posterior_name='posterior', screen_directions=screen_directions) # config = tf.ConfigProto(allow_soft_placement = True) sess = tf.Session(graph=tf.Graph())#,config=config) # from tensorflow.python import debug as tf_debug # sess = tf_debug.LocalCLIDebugWrapperSession(sess) with sess: with tf.device('/device:CPU:0'): logging.info("Setting up the index and datapack feeds.") datapack_feed = DatapackFeed(datapack, selection={'ant': list(range(1,7,2)) + list(range(45, 62, 1)),'dir':None, 'pol':slice(0,1,1), 'time':slice(0,None,1)}, solset='sol000', postieror_name='posterior', index_n=1) logging.info("Setting up the filter.") free_transition = FreeTransitionVariationalBayes(datapack_feed=datapack_feed, output_folder=output_folder) free_transition.init_filter() filter_op = free_transition.filter( parallel_iterations=10, kernel_params={'resolution': 4, 'fed_kernel': 'M52', 'obs_type': 'DTEC'}, num_parallel_filters=10, solver_params=dict(iters=200, learning_rate=0.1, gamma=0.3, stop_patience=6), num_mcmc_param_samples_learn=50, num_mcmc_param_samples_infer=100, minibatch_size=None, y_sigma=0.1) logging.info("Initializing the filter") sess.run(free_transition.initializer) # print(sess.run([free_transition.full_block_size, free_transition.datapack_feed.time_feed.slice_size, free_transition.datapack_feed.index_feed.step])) logging.info("Running the filter") sess.run(filter_op)
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 28686, 198, 6738, 15489, 274, 62, 24455, 1330, 18931, 198, 6738, 15489, 274, 62, 24455, 13, 10379, 1010, 1330, 3232, 8291, 653, 23907, 864, 15262, 274, 198, 6738, 15489, 274, 62, 24455, ...
2.037628
1,754
import argparse import json import matplotlib.pyplot as plt import numpy as np import pickle import time import torch from torch import optim from typing import Tuple, List, Dict import dataset from model import BiLSTM_CRF import utils if __name__ == '__main__': main()
[ 11748, 1822, 29572, 198, 11748, 33918, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2298, 293, 198, 11748, 640, 198, 11748, 28034, 198, 6738, 28034, 1330, 6436, 198, 6738, ...
3.133333
90