text
string
size
int64
token_count
int64
#!/bin/env python3 # coding: utf8 ''' My implementation of DFT Assignment 5.1: Hartree energy for H-atom GS Taught by René Wirnata in 2019/2020. Links: https://tu-freiberg.de/fakultaet2/thph/lehre/density-functional-theory https://github.com/PandaScience/teaching-resources This script uses the last assignment's ...
6,371
2,606
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt from sklearn import datasets, linear_model from difflib import SequenceMatcher import seaborn as sns from statistics import mean from ast import literal_eval from scipy import stats from sklearn.linear_model import LinearRegression from s...
18,714
7,223
import json import os import sys from collections import OrderedDict import iotbx.phil import xia2.Handlers.Streams from dials.util.options import OptionParser from jinja2 import ChoiceLoader, Environment, PackageLoader from xia2.Modules.Report import Report from xia2.XIA2Version import Version phil_scope = iotbx.phi...
4,684
1,608
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.views.generic import TemplateView from . import views # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patt...
757
237
from algorithm.InsertionLengthAlgorithm import InsertionLengthAlgorithm from algorithm.PhysicalCoverageAlgorithm import PhysicalCoverageAlgorithm from algorithm.SequenceCoverageAlgorithm import SequenceCoverageAlgorithm from algorithm.CigarAlgorithm import CigarAlgorithm from algorithm.KmersAlgorithm import KmersAlgori...
324
81
from tkinter import * from attack import * #calls letter frequency attack def attack(on, cipherTxt): plainTxt = str() attack = LetterFrequencyAttack(cipherTxt, on) for i in range(10): plainTxt = plainTxt + attack.attack() + '\n\n' answer.config(text = plainTxt) #defining main wi...
1,874
717
from random import randint import copy # Auxiliary Function for rotating the DNA in each cycle. def rotate(l,n): return l[n:] + l[:n] # History is the object responsible for accounting all the organisms. class History: def __init__(self): self.orgs = [] def addOrganism(self, org): ...
12,703
4,219
import os import datetime from pathlib import Path import pandas as pd import luigi PROCESSED_DIR = 'processed' ROLLUP_DIR = 'rollups' class PrepareDataTask(luigi.Task): def __init__(self): super().__init__() self.last_processed_id = 0 if os.path.exists('last_processed_id.txt'): ...
2,407
816
# automatically generated by the FlatBuffers compiler, do not modify # namespace: tflite import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class Metadata(object): __slots__ = ['_tab'] @classmethod def GetRootAsMetadata(cls, buf, offset): n = flatbuffers.encode.Ge...
2,463
790
"""Read the Kukur configuration.""" # SPDX-FileCopyrightText: 2021 Timeseer.AI # # SPDX-License-Identifier: Apache-2.0 import glob import toml class InvalidIncludeException(Exception): """Raised when the include configuration is invalid.""" def __init__(self, message: str): Exception.__init__(self, ...
1,124
316
import time from datetime import datetime import numpy as np from matplotlib import pyplot as plt from matplotlib.dates import epoch2num import device_factory if __name__ == '__main__': amount = 50 devices = [] for i in range(amount): device = device_factory.ecopower_4(i, i) ...
3,326
1,291
expected_output = { "location": { "R0 R1": { "auto_abort_timer": "inactive", "pkg_state": { 1: { "filename_version": "17.08.01.0.149429", "state": "U", "type": "IMG", } }, ...
329
108
# Copyright (c) 2021 PaddlePaddle Authors. 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 appli...
8,637
2,603
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ import boto3 import copy import unittest from botocore.stub import ANY from cfn_policy_validator.tests import account_config, offline_only, only_run_for_end_to_end from cfn_policy_validator.tests.boto_mocks impor...
22,871
8,848
""" Tests for the h5py.Datatype class. """ from __future__ import absolute_import from itertools import count import numpy as np import h5py from ..common import ut, TestCase class TestVlen(TestCase): """ Check that storage of vlen strings is carried out correctly. """ def assertVlenArrayEq...
6,672
2,365
#!/usr/bin/env python # -*- coding: UTF-8 -*- import re from typing import Pattern, Tuple, Iterator, Match, Union, Optional, List, Dict from conmon.conan import storage_path DECOLORIZE_REGEX = re.compile(r"[\u001b]\[\d{1,2}m", re.UNICODE) CONAN_DATA_PATH = re.compile( r"""(?x) (?P<path> ([a-z...
2,278
816
#!/usr/bin/env python import sysrepo as sr import argparse from prompt_toolkit import PromptSession from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.completion import Completer import sys import os import logging import asyncio from .base import Object, InvalidInput, BreakLoop from .onlp impo...
5,089
1,549
def selection_sort(my_list): for i in range(len(my_list)): min_index=i for j in range(i+1 , len(my_list)): if my_list[min_index]>my_list[j]: min_index= j my_list[i],my_list[min_index]= my_list[min_index] ,my_list[i] print(my_list) cus_list=[8,4,23,42,16,...
350
146
import requests from bs4 import BeautifulSoup from prettytable import PrettyTable # html = requests.get( # 'http://jwzx.cqu.pt/student/xkxfTj.php', # cookies={'PHPSESSID': 'o2r2fpddrj892dp1ntqddcp2hv'}).text # soup = BeautifulSoup(html, 'html.parser') # for tr in soup.find('table', {'id': 'AxfTjTable'}).find...
437
183
class Person: number_of_people = 0 def __init__(self, name): print("__init__ initiated") self.name = name print("calling add_person()") Person.add_person() @classmethod def num_of_people(cls): print("initiating num_of_person()") return cls.number_of_peo...
602
196
from django import template from django.conf import settings from webpack_manifest import webpack_manifest if not hasattr(settings, 'WEBPACK_MANIFEST'): raise webpack_manifest.WebpackManifestConfigError('`WEBPACK_MANIFEST` has not been defined in settings') if 'manifests' not in settings.WEBPACK_MANIFEST: rai...
1,117
356
import os import itertools as it import pandas as pd def compute_jaccard(v1, v2): v1, v2 = set(v1), set(v2) intersection = v1.intersection(v2) union = v1.union(v2) return ((len(intersection) / len(union) if len(union) != 0 else 0), len(intersection), len(union)) def get_inter_m...
2,668
1,163
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # T...
2,600
866
from collections import defaultdict from noise_robust_cobras.noise_robust.datastructures.constraint import Constraint from noise_robust_cobras.noise_robust.datastructures.constraint_index import ( ConstraintIndex, ) class Cycle: """ A class that represents a valid constraint cycle attributes:...
7,188
2,014
import unittest from main import Solution class TestSolutionMethods(unittest.TestCase): solution = Solution() def test_longestCommonPrefix(self): # leetcode test self.assertEqual(self.solution.removeDuplicates([1,1,2]), 2) # customized test self.assertEqual(self.solution.remov...
525
175
SEPARATOR: list = [':', ',', '*', ';', '#', '|', '+', '%', '>', '?', '&', '=', '!'] def word_splitter(string: str) -> list: for i in string: if i in SEPARATOR: string = string.replace(i, ' ') return string.split()
246
95
import csv from core.exceptions import InvalidFileException def load_so_item_from_file(path, db_service): with open(path) as csv_file: csv_reader = csv.reader(csv_file) error_msg = 'Missing required header: {}' for i, row in enumerate(csv_reader, 1): data = { ...
7,998
2,230
import googlemaps import secret from datetime import datetime import requests import pickle import time gmaps = googlemaps.Client(key=secret.PLACES_API_KEY) # lat = 45.411400 # lon = 11.887491 coordinates = [ (45.411400, 11.887491), # torre archimede (45.409218, 11.877915), # piazza garibaldi (45.407698...
8,342
2,836
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import log...
31,231
8,572
import grpc import helloworld_pb2 import helloworld_pb2_grpc from grpc.beta import implementations def run(): # 连接 rpc 服务器 # TSL连接方式 >>> with open('G:\\DotNet\\SevenTiny.Cloud.FaaS\\Code\\Python\\SevenTiny.Cloud.FaaS.GRpc\\ca\\client.pem', 'rb') as f: pem = f.read() creds = implementations.ssl...
885
329
#!/usr/bin/env python """ PCA done via matrix multiplication out-of-core. """ import argparse import time import h5py import hickle as hkl import numpy as np def input_parse(): description = 'Compute PCA with A.T * A computation out of core' p = argparse.ArgumentParser(description=description) p.add_ar...
2,350
899
# ----------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ----------------------------------------------------------------------------- # ...
5,680
1,635
import gamry_parser as parser class CyclicVoltammetry(parser.GamryParser): """Load a Cyclic Voltammetry experiment generated in Gamry EXPLAIN format.""" def get_v_range(self): """retrieve the programmed voltage scan ranges Args: None Returns: tuple, containin...
1,968
576
import json import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html import pandas as pd import dash_table def get_comps_data(bd, projverurl): print('Getting components ...') # path = projverurl + "/components?limit=5000" # # custom_headers = {'Acc...
11,609
3,220
''' Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. ''' reta1 = float(input('Digite o comprimento da primeira reta: ')) reta2 = float(input('Digite o comprimento da segunda reta: ')) reta3 = float(input('Digite o comprimento da terceira reta: ')) ...
656
254
# Copyright 2016 Mirantis 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...
15,790
4,821
from pathlib import Path import numpy as np import pickle import argparse import errno import sys def file_exists(path): return Path(path).is_file() def dir_exists(path): return Path(path).is_dir() def remove_extension(x): return x.split('.')[0] def print_error(type, file): print(FileNotFoundError(e...
2,271
696
#!/usr/bin/python from aos.util.trapezoid_profile import TrapezoidProfile from frc971.control_loops.python import control_loop from frc971.control_loops.python import angular_system from frc971.control_loops.python import controls import copy import numpy import sys from matplotlib import pylab import gflags import gl...
1,813
754
from torch.nn.modules import loss import torch import numpy as np def MAE(pred, true): return np.mean(np.abs(pred-true)) def MSE(pred, true): return np.mean((pred-true)**2) def RMSE(pred, true): return np.sqrt(MSE(pred, true)) def MAPE(pred, true): return np.mean(np.abs((pred - true) / true)) def ...
2,666
960
import pytest from pandas.errors import NullFrequencyError import pandas as pd from pandas import TimedeltaIndex import pandas._testing as tm class TestTimedeltaIndexShift: # ------------------------------------------------------------- # TimedeltaIndex.shift is used by __add__/__sub__ def test_tdi_sh...
2,772
1,060
# use selenium to scrape headlines from corriere.it # pip install selenium from re import L from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.co...
1,974
697
import os from subprocess import check_output, CalledProcessError from nose import tools as nt from stolos import queue_backend as qb from stolos.testing_tools import ( with_setup, validate_zero_queued_task, validate_one_queued_task, validate_n_queued_task ) def run(cmd, tasks_json_tmpfile, **kwargs): cm...
2,033
828
# 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 unde...
12,442
3,870
# -*- coding: utf-8 -*- # Copyright (c) 2018-2021, earthobservations developers. # Distributed under the MIT License. See LICENSE for more info. import pytest from wetterdienst import Wetterdienst @pytest.mark.remote @pytest.mark.parametrize( "provider,kind,kwargs", [ # German Weather Service (DWD) ...
1,665
515
#! -*- coding:utf-8 -*- # 语义相似度任务-无监督:训练集为网上pretrain数据, dev集为sts-b from bert4torch.tokenizers import Tokenizer from bert4torch.models import build_transformer_model, BaseModel from bert4torch.snippets import sequence_padding, Callback, ListDataset import torch.nn as nn import torch import torch.optim as optim from to...
5,803
2,198
from pathlib import Path from .anki_exporter import AnkiJsonExporter from ..anki.adapters.anki_deck import AnkiDeck from ..config.config_settings import ConfigSettings from ..utils import constants from ..utils.notifier import AnkiModalNotifier, Notifier from ..utils.disambiguate_uuids import disambiguate_note_model_u...
2,761
821
from functools import lru_cache from typing import Optional import requests from .patches import Patches class Item: """ Manipulation of static item data """ ITEM_URL = f"http://ddragon.leagueoflegends.com/cdn/{Patches.get_current_patch()}/data/en_US/item.json" items = requests.get(ITEM_URL).js...
1,086
340
# Copyright 2019 The TensorFlow Authors. 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 applic...
2,694
952
# @Time : 2020/10/6 # @Author : Shanlei Mu # @Email : slmu@ruc.edu.cn """ recbole.quick_start ######################## """ import logging from logging import getLogger from recbole.config import Config from recbole.data import create_dataset, data_preparation from recbole.utils import init_logger, get_model, get_t...
5,211
1,729
# Copyright (c) The InferLO authors. All rights reserved. # Licensed under the Apache License, Version 2.0 - see LICENSE. import warnings import numpy as np from sklearn.utils.extmath import randomized_svd from .bucket_elimination import BucketElimination from .factor import Factor, default_factor_name, produ...
4,947
1,545
import os import urllib from google.appengine.api import users from google.appengine.ext import ndb import jinja2 import webapp2 from sys import argv import datetime import pickle import sys sys.path.insert(0, 'libs') import BeautifulSoup from bs4 import BeautifulSoup import requests import json JINJA_ENVIRONM...
5,519
1,872
import json from django.utils.encoding import force_text from germanium.tools import assert_true, assert_not_equal from germanium.test_cases.client import ClientTestCase from germanium.decorators import login from germanium.crawler import Crawler, LinkExtractor, HtmlLinkExtractor as OriginalHtmlLinkExtractor def fl...
4,482
1,294
from django.contrib import admin from geometry.models import Shape @admin.register(Shape) class AdminShape(admin.ModelAdmin): ...
136
39
# -*- coding: utf-8 -*- # @Author : Ecohnoch(xcy) # @File : demo2_consume.py # @Function : TODO import kafka demo2_config = { 'kafka_host': 'localhost:9092', 'kafka_topic': 'demo2', 'kafka_group_id': 'demo2_group1' } def consume(): consumer = kafka.KafkaConsumer(demo2_config['kafka_topic'], ...
943
327
import json import pandas as pd from .application_scaling_model import ApplicationScalingModel from .platform_scaling_model import PlatformScalingModel from autoscalingsim.deltarepr.group_of_services_delta import GroupOfServicesDelta from autoscalingsim.deltarepr.node_group_delta import NodeGroupDelta from autoscali...
2,280
613
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
1,662
480
import sys verbose = False def set_v(v): global verbose verbose = v def print_v(s): if verbose: print(s) def write_v(s): if verbose: sys.stdout.write(s)
192
75
import grpc from google.protobuf import empty_pb2 from django_grpc_framework.services import Service from component_b.common.serializers import PersonProtoSerializer from component_b.common.models import PersonModel class PersonCommandService(Service): def get_object(self, pk): try: return P...
1,087
308
__author__ = 'kq4hy' import csv import sqlite3 def load_course_database(db_name, csv_filename): conn = sqlite3.connect(db_name) with conn: curs = conn.cursor() with open(csv_filename, 'rU') as csvfile: reader = csv.reader(csvfile) for row in reader: sql...
485
163
from .enum_field import EnumField, RegisteredEnum # noqa from .marsh_schema import attr_with_schema, derive # noqa
117
38
''' IoT Mini Project Weather Station using DHT Sensor and Raspberry Pi with ThingSpeak Platform Code Sample: Interfacing DHT22 with Raspberry Pi and sending the data to an IoT Platform (ThingSpeak Platform) ''' from time import sleep # import Adafruit_DHT # Not supported library import adafruit_dht from board import *...
1,492
503
#!/usr/bin/python # -*- coding: utf-8 -*- import time from page_objects import PageObject, PageElement from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.by import By delay_mi...
931
280
config = dict( module="HOTrialWavefunction.py" )
53
22
#!/usr/bin/python2 import sys import os import redis import time import datetime string_keys = [] hash_keys = [] list_keys = [] set_keys = [] zset_keys = [] def import_string(source, dest): print "Begin Import String Type" keys_count = len(string_keys) print "String Key Count is:", keys_count pipeSrc...
5,771
1,872
import torch import torch.nn as nn import numpy as np from enum import Enum from typing import List, Callable, Any from tqdm import tqdm from .model import Model from .dataset import Dataset from .experiment import Experiment from .callback import Callback class TrainingEvents(Enum): START = 'on_start' FINIS...
5,990
1,901
import unittest from pystac.utils import (make_relative_href, make_absolute_href, is_absolute_href) class UtilsTest(unittest.TestCase): def test_make_relative_href(self): # Test cases of (source_href, start_href, expected) test_cases = [ ('/a/b/c/d/catalog.js...
2,924
1,006
# Copyright (c) 2020 Michael Herman # Copyright (c) 2020 Vid Podpečan # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy...
1,322
443
from PyQt5.QtWidgets import QDialog, QPushButton, QVBoxLayout, QComboBox, QGroupBox, QCheckBox, QGridLayout, QMessageBox, QRadioButton from GUI.CustomWidgets.PathFileLineEdit import PathFileLineEdit from GUI.CustomWidgets.InputField import InputField class ExportPopUp(QDialog): def __init__(self, parent): ...
5,737
1,838
from __future__ import absolute_import import copy import re from typing import (Any, Callable, Dict, List, MutableMapping, MutableSequence, Optional, Tuple, Union) from functools import partial from ruamel.yaml.comments import CommentedMap, CommentedSeq from schema_salad import validate from sch...
7,993
2,438
import matplotlib.pyplot as plt from matplotlib import collections from matplotlib.lines import Line2D def autosize(fig=None, figsize=None): ## Take current figure if no figure provided if fig is None: fig = plt.gcf() if figsize is None: ## Get size of figure figsize = fig.get_s...
2,072
684
from re import S from manimlib import * import sys import os from tqdm.std import tqdm sys.path.append(os.getcwd()) from utils.imports import * class Opening(Scene): def construct(self): title = Text("基础递推递归", font='msyh') self.play(Write(title), run_time=2) self.wait() self.pla...
8,546
3,092
# POKEMING - GON'NA CATCH 'EM ALL # -- A simple hack 'n slash game in console # -- This class is handles all utility related things class Utility: # This allows to see important message of the game def pause(message): print(message) input('Press any key to continue.')
299
86
import logging import sys from typing import Union, Optional, Dict, Any, List from dataclasses import dataclass, replace from exp.ours import file_paths from exp.ours.boosting import MaskSpec from exp.ours.data.dataset import Dataset, Task from exp.ours.data.gpv_example import GPVExample from exp.ours.models.model im...
2,057
768
import django_filters from ...models import FN024 from .filter_utils import NumberInFilter, ValueInFilter class FN024SubFilter(django_filters.FilterSet): """A fitlerset that allows us to select subsets of net set objects by net set attributes.""" prd = ValueInFilter(field_name="prd") prd__not = Valu...
6,968
2,510
import numpy as np from time import time import matplotlib.pyplot as plt measure2index={"y-coordinate":0,"x-coordinate":1,"timestamp":2, "button_status":3,"tilt":4, "elevation":5,"pressure":6} index2measure=list(measure2index.keys()) task2index={"spiral":0,"l":1,"le":2 ,"les":3,"lektorka" :4,"porovnat":5,"nepopadnout...
7,148
2,634
import datetime datenasc = int(input(f'insert you date of bit ')) atualdate = str(datetime.date.today())[0:4] datestr = int(atualdate) datefinal = datestr - datenasc print(datefinal) if datefinal < 18: print(f'voce esta com {datefinal}Faltam {18-datefinal} pra você se alistar ao exercito hahahah' ) elif datefinal =...
574
212
__author__ = 'rob' import unittest import logging import evernotebookparser from xml.etree import ElementTree import re class TestNotebookParser(unittest.TestCase): def setUp(self): self.o = evernotebookparser.NotebookParser2("../Quotes.enex") def test_parsing2(self): results...
4,180
1,241
# Copyright 2019 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
6,872
2,300
#!/usr/bin/env python r"""estimate.py Use to estimate masses based on observed proxy values (and associated errors) from a pre-calibrated generative model for the mass-proxy relationship. The estimates will be returned as samples (fair draws) from the model's posterior on the mass given the proxy observation. This p...
2,083
717
str1 = "Python" str2 = "Python" print("\nMemory location of str1 =", hex(id(str1))) print("Memory location of str2 =", hex(id(str2))) print()
143
54
config = dict() config['fixed_cpu_frequency'] = "@ 3700 MHz" config['frequency'] = 3.7e9 config['maxflops_sisd'] = 2 config['maxflops_sisd_fma'] = 4 config['maxflops_simd'] = 16 config['maxflops_simd_fma'] = 32 config['roofline_beta'] = 64 # According to WikiChip (Skylake) config['figure_size'] = (20,9) config...
353
161
import cx_Oracle from oracledb import OracleJSONDatabaseConnection import json jsondb = OracleJSONDatabaseConnection() connection = jsondb.get_connection() connection.autocommit = True soda = connection.getSodaDatabase() x_collection = soda.createCollection('f1_2021_weather') all_data = list() for doc in x_collect...
562
186
from Tkinter import * import ttk import BuyBook import BookInformationPage import Message class UserPage(object): def __init__(self, root, color, font, dbConnection, userInfo): for child in root.winfo_children(): child.destroy() self.root = root self.color = color sel...
8,257
2,554
"""initial migration Revision ID: 1b57e397deea Revises: Create Date: 2021-12-20 20:57:14.696646 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1b57e397deea' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto ...
775
294
import copy import itertools import re from base64 import b64decode from app.utility.base_service import BaseService from app.utility.rule import RuleSet class BasePlanningService(BaseService): async def trim_links(self, operation, links, agent): """ Trim links in supplied list. Where 'trim' ent...
5,596
1,522
import math from pyclid.vector import * from pyclid.matrix import * from pyclid.quaternion import * #from pyclid.vector import vector #from pyclid.quaternion import quaternion #from pyclid.matrix import matrix
215
72
import os rootdir = os.path.abspath(os.path.join(__file__, "..", "..")) mldir = os.path.join(rootdir, "ml") import sys sys.path.append(mldir) import pfm import iispt_transforms import math import plotly import plotly.plotly as py import plotly.graph_objs as go # ====================================================...
2,939
1,029
import logging import sys import threading import serial import serial.tools.list_ports from crownstone_uart.Constants import UART_READ_TIMEOUT, UART_WRITE_TIMEOUT from crownstone_uart.core.UartEventBus import UartEventBus from crownstone_uart.core.uart.UartParser import UartParser from crownstone_uart.core.uart.Uart...
4,762
1,292
class Location: def __init__(self, location_id, borough, zone, lat, lng): self.location_id = location_id self.borough = borough self.zone = zone self.lat = lat self.lng = lng @property def json(self): return { "location_id": self.location_id, ...
20,753
12,084
import math from utils import * def main(): showHome() option = chooseOption() handleOption(option) main()
114
37
import os import simplejson as json def readJson(fileName): test_filename = os.path.join(os.path.dirname(__file__), fileName) with open(test_filename, mode='rb') as json_file: return json.load(json_file)
222
71
#! /usr/bin/env python # -*- coding: utf-8 -*- import daiquiri from time import time import warp10client LOG = daiquiri.getLogger(__name__) warp10_api_url = '' # Add here backend url where metrics are stored read_token = '' # Add here your metrics read token write_token = '' # Add here your metrics write token #...
1,999
888
#!/usr/bin/env python3 # # This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2020 Jim Mussared # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal ...
3,094
1,085
import scrapy import yaml class universalSpider(scrapy.Spider): name = "universal" parameters = None def __init__(self, *args, **kwargs): worker = kwargs.get("worker") if not worker: exit("You must specify worker name : -a worker=name") self.parameters = yaml.load(f...
1,081
306
import warnings import gym import matplotlib.pyplot as plt import numpy as np from skopt.acquisition import gaussian_ei from environments.groundtruthgenerator import GroundTruth warnings.simplefilter("ignore", UserWarning) from skopt.learning.gaussian_process import gpr, kernels class ContinuousBO(gym.Env): en...
11,715
3,790
import numpy as np from sklearn.metrics import pairwise_distances import matplotlib.pyplot as plt class NumpyMetrics(): def __init__(self, metric='euclidean'): self.metric = metric def rank(self, x,y, x_labels, y_labels): distances = pairwise_distances(x,y,self.metric) batch_size = x_...
5,281
1,724
# -*- coding: utf-8 -*- import logging if __name__ == '__main__': logging.basicConfig() _log = logging.getLogger(__name__) import pyxb.binding.generate import pyxb.binding.datatypes as xs import pyxb.binding.basis import pyxb.utils.domutils import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xm...
693
264
import sys ii = int(sys.argv[1]) env = sys.argv[2] # python3 print_data_structure.py 22 MD10 import glob import os import numpy as n import EmergeIterate iterate = EmergeIterate.EmergeIterate(ii, env) iterate.open_snapshots() def print_attr(h5item): for attr in h5item: print(attr, h5item[attr]) def print...
779
311
# based on https://github.com/pypa/sampleproject from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_descript...
1,999
638
import pytest import six import ujson import apache_beam as beam from apache_beam.testing.test_pipeline import TestPipeline as _TestPipeline from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to from apache_beam.coders import typecoders from apache_beam.typehints import Dict, U...
1,291
388