text
string
size
int64
token_count
int64
from django.db.models import Q from hier.search import SearchResult from .models import app_name, Apart, Meter, Bill, Service, Price def search(user, query): result = SearchResult(query) lookups = Q(name__icontains=query) | Q(addr__icontains=query) items = Apart.objects.filter(user = user.id).filter(l...
1,553
544
import os import shutil import numpy as np from pyrevolve.custom_logging.logger import logger import sys class ExperimentManagement: # ids of robots in the name of all types of files are always phenotype ids, and the standard for id is 'robot_ID' def __init__(self, settings): self.settings = settings...
5,884
1,820
#$Id$ class Instrumentation: """This class is used tocreate object for instrumentation.""" def __init__(self): """Initialize parameters for Instrumentation object.""" self.query_execution_time = '' self.request_handling_time = '' self.response_write_time = '' self.page_c...
2,136
594
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from setuptools import setup with open("README.md") as f: readme = f.read() setup( name="dpr", version="...
1,079
375
# encoding: utf-8 """ @version: v1.0 @author: Richard @license: Apache Licence @contact: billions.richard@qq.com @site: @software: PyCharm @time: 2019/9/12 20:37 """ from pprint import pprint as pp from operator import itemgetter import time from collections import OrderedDict from hard.smallest_range.srcs....
2,817
1,353
from pcf.core.gcp_resource import GCPResource from pcf.core import State import logging from google.cloud import storage from google.cloud import exceptions logger = logging.getLogger(__name__) class Storage(GCPResource): """ This is the implementation of Google's storage service. """ flavor = "stor...
4,887
1,372
import numpy as np def smooth(a, WSZ): # a: NumPy 1-D array containing the data to be smoothed # WSZ: smoothing window size needs, which must be odd number, # as in the original MATLAB implementation if WSZ % 2 == 0: WSZ = WSZ - 1 out0 = np.convolve(a, np.ones(WSZ, dtype=int), 'valid') / W...
498
216
from __future__ import absolute_import import abc import os import json import glob import shutil from tensorflow.python.estimator import gc from tensorflow.python.estimator import util from tensorflow.python.estimator.canned import metric_keys from tensorflow.python.framework import errors_impl from tensorflow.pytho...
11,810
3,213
# Copyright: 2005-2012 Brian Harring <ferringb@gmail.com # Copyright: 2006 Marien Zwart <marienz@gentoo.org> # License: BSD/GPL2 """ base restriction class """ from functools import partial from snakeoil import caching, klass from snakeoil.currying import pretty_docs class base(object, metaclass=caching.WeakInstMe...
5,329
1,692
"""extend_ip_field Revision ID: 8da20383f6e1 Revises: eeb702f77d7d Create Date: 2021-01-14 10:50:56.275257 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "8da20383f6e1" down_revision = "eeb702f77d7d" branch_labels = None depends_on = None def upgrade(engine_n...
797
331
import ply.lex as lex tokens =["NUM","OPERADORES"] t_NUM = '\d+' t_OPERADORES = '[+|*|-]' t_ignore='\n\t ' def t_error(t): print("Erro") print(t) lexer = lex.lex() # 1+2 1-2 1*2 # ola mundo import sys for line in sys.stdin: lexer.input(line) for tok in lexer: print(tok)
301
148
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-07-10 20:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ucsrb', '0012_auto_20180710_1249'), ] operations = [ migrations.AddField( ...
1,657
493
from __future__ import annotations import typing from ctc import spec from . import timestamp_crud from . import metric_crud from . import analytics_spec async def async_create_payload( *, blocks: typing.Sequence[spec.BlockNumberReference] | None = None, timestamps: typing.Sequence[int] | None = None, ...
2,015
658
# Copyright 2016 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 applicab...
18,118
6,171
load("@rules_jvm_external//:defs.bzl", "artifact") # For more information see # - https://github.com/bmuschko/bazel-examples/blob/master/java/junit5-test/BUILD # - https://github.com/salesforce/bazel-maven-proxy/tree/master/tools/junit5 # - https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-starte...
1,657
538
# This module provides mocked versions of classes and functions provided # by Carla in our runtime environment. class Location(object): """ A mock class for carla.Location. """ def __init__(self, x, y, z): self.x = x self.y = y self.z = z class Rotation(object): """ A mock class...
625
205
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ee = '\033[1m' green = '\033[32m' yellow = '\033[33m' cyan = '\033[36m' line = cyan+'-' * 0x2D print(ee+line) R,G,B = [float(X) / 0xFF for X in input(f'{yellow}RGB: {green}').split()] K = 1-max(R,G,B) C,M,Y = [round(float((1-X-K)/(1-K) * 0x64),1) for X in [R,G,B]] K = r...
404
238
#!/usr/bin/env python """Builds the documentaion. First it runs gendoc to create rst files for the source code. Then it runs sphinx make. .. Warning:: This will delete the content of the output directory first! So you might loose data. You can use updatedoc.py -nod. Usage, just call:: updatedoc.py -h "...
4,720
1,425
def selection_sort(A): # O(n^2) n = len(A) for i in range(n-1): # percorre a lista min = i for j in range(i+1, n): # encontra o menor elemento da lista a partir de i + 1 if A[j] < A[min]: min = j A[i], A[min] = A[min], A[i] # insere o elemento na posicao corre...
478
223
import os from typing import List, Tuple from BridgeOptimizer.datastructure.hypermesh.LoadCollector import LoadCollector from BridgeOptimizer.datastructure.hypermesh.LoadStep import LoadStep from BridgeOptimizer.datastructure.hypermesh.Force import Force from BridgeOptimizer.datastructure.hypermesh.SPC import SPC cla...
4,618
1,503
tajniBroj = 51 broj = 2 while tajniBroj != broj: broj = int(input("Pogodite tajni broj: ")) if tajniBroj == broj: print("Pogodak!") elif tajniBroj < broj: print("Tajni broj je manji od tog broja.") else: print("Tajni broj je veci od tog broja.") print("Kraj programa")
320
132
import numpy as np from sklearn import metrics from neupy import algorithms from base import BaseTestCase class CMACTestCase(BaseTestCase): def test_cmac(self): X_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1)) X_train_before = X_train.copy() X_test = np.reshape(np.linspace(...
2,806
1,015
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com from sqlalchemy.ext.associationproxy import association_proxy from ggrc import db...
3,075
1,033
# Copyright ©2020-2021 The American University in Cairo and the Cloud V Project. # # This file is part of the DFFRAM Memory Compiler. # See https://github.com/Cloud-V/DFFRAM for further info. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
11,196
4,590
class CoinbaseResponse: bid = 0 ask = 0 product_id = None def set_bid(self, bid): self.bid = float(bid) def get_bid(self): return self.bid def set_ask(self, ask): self.ask = float(ask) def get_ask(self): return self.ask def get_product_id(self): ...
426
150
# noqa: D100 from typing import Optional import numpy as np import xarray from xclim.core.units import ( convert_units_to, declare_units, pint_multiply, rate2amount, units, units2pint, ) from xclim.core.utils import ensure_chunk_size from ._multivariate import ( daily_temperature_range, ...
19,777
6,528
# Copyright (c) 2013, VHRS and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _, msgprint from frappe.utils import (cint, cstr, date_diff, flt, getdate, money_in_words, nowdate, rounded, today) from datet...
14,714
4,283
import os DEFAULT_ROOT = './materials' datasets_dt = {} def register(name): def decorator(cls): datasets_dt[name] = cls return cls return decorator def make(name, **kwargs): if kwargs.get('root_path') is None: kwargs['root_path'] = os.path.join(DEFAULT_ROOT, name) dataset =...
369
125
from .comment import CommentParser from .protobuf import Protobuf from .proto_structures import Syntax class SyntaxParser(): @classmethod def parse_and_add(cls, proto_obj: Protobuf, line, top_comment_list): if proto_obj.syntax is not None: raise 'multiple syntax detected!' proto_...
888
264
from flask import render_template, request, Blueprint core = Blueprint('core', __name__) @core.route("/", methods=['GET', 'POST']) def home(): return render_template('home.html') @core.route("/about") def about(): return render_template('about.html') @core.route('/search', methods=['GET', 'POST']) def se...
443
140
# encoding: utf-8 import functools import os from urllib.parse import urlsplit import boto3 import botocore import pytest from botocore.exceptions import BotoCoreError, ClientError from mock import MagicMock from parameterized import parameterized from ..mirror import MirrorUploader from ..model import ( DataSour...
47,884
14,701
"""Set the build version to be 'qa', 'rc', 'release'""" import sys import os import re import logging log = logging.getLogger() log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) def get_build_type(travis_tag=None): if not travis_tag: return "qa" log.debug("getting build type for ta...
1,114
420
#!/usr/bin/python import yaml import os import ast import sys from collections import OrderedDict curr_dir = os.getcwd() work_dir = sys.argv[1] network_type = sys.argv[2] testplan_dict = {} testplan_dict["name"] = "System performance test" testplan_dict["description"] = "This test is to create as much chaincode com...
7,087
2,322
"""Collection of tests.""" import pytest import dblib.lib f0 = dblib.lib.Finding('CD spook', 'my_PC', 'The CD drive is missing.') f1 = dblib.lib.Finding('Unplugged', 'my_PC', 'The power cord is unplugged.') f2 = dblib.lib.Finding('Monitor switched off', 'my_PC', 'The monitor is switched off.') def test_add_remove(...
1,033
405
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
1,627
460
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-25 22:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import django_smalluuid.models class Migration(migrations.Migration): dependencies = [("hordak",...
6,553
1,734
from aiogram import Bot, types from aiogram.dispatcher import Dispatcher from aiogram.utils import executor TOKEN = "Token for you bot" bot = Bot(token=TOKEN) dp = Dispatcher(bot) @dp.message_handler(command=['start', 'help']) async def send_welcome(msg: types.Message): await msg.reply_to_message(f'Добро ...
646
238
from django.core.exceptions import ImproperlyConfigured from importlib import import_module try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding import force_unicode as force_text from django.utils.functional import Promise import json def import_class(path): ...
1,398
413
# timedpid.py # Source: https://github.com/DrGFreeman/PyTools # # MIT License # # Copyright (c) 2017 Julien de la Bruere-Terreault <drgfreeman@tuta.io> # # 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 th...
4,984
1,447
# # -*- coding: utf-8-*- # receives messages via zmq and executes some simple # operations. # # (c) ISC Clemenz & Weinbrecht GmbH 2018 # import json import requests import zmq import pmon class ZmqResponder(object): context = None socket = None def __init__(self): """ Constructor. ...
3,051
910
from padmini import operations as op def test_yatha(): before = ("tAs", "Tas", "Ta", "mip") after = ("tAm", "tam", "ta", "am") for i, b in enumerate(before): assert op.yatha(b, before, after) == after[i] """ def test_ti(): assert S.ti("ta", "e") == "te" assert S.ti("AtAm", "e") == "Ate"...
423
182
# coding: utf-8 #just prints the emails of members of a group to stdout, #both primary and secondary members # run as # $python extractemails_nogui.py "Tidal Disruption Events" from __future__ import print_function '__author__' == 'Federica Bianco, NYU - GitHub: fedhere' import sys import pandas as pd from argparse im...
2,186
611
from discord.ext import commands, menus import utils import random , discord, os, importlib, mystbin, typing, aioimgur, functools, tweepy import traceback, textwrap from discord.ext.menus.views import ViewMenuPages class Owner(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(brief="a c...
20,373
6,857
# This file is part of the UFO. # # This file contains definitions for functions that # are extensions of the cmath library, and correspond # either to functions that are in cmath, but inconvenient # to access from there (e.g. z.conjugate()), # or functions that are simply not defined. # # from __future__ import absol...
1,341
418
#!/usr/bin/python # # Copyright 2019 Polyaxon, Inc. # # 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 o...
2,395
706
import pytest from duckql.properties import Null @pytest.fixture(scope="module") def valid_instance() -> Null: return Null() def test_string(valid_instance: Null): assert str(valid_instance) == 'NULL' def test_obj(valid_instance: Null): assert valid_instance.obj == 'properties.Null' def test_json_p...
413
134
# -*- Mode: Python -*- # GObject-Introspection - a framework for introspecting GObject libraries # Copyright (C) 2010 Red Hat, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; eith...
6,190
1,981
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import sys import shutil import tempfile import subprocess import typing as tp from pathlib import Path from ne...
6,057
1,686
import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname='54.165.97.91',username='ec2-user',password='paramiko123',port=22) sftp_client=ssh.open_sftp() #sftp_client.get('/home/ec2-user/paramiko_download.txt','paramiko_downloaded_file.txt') #sftp_c...
568
231
# coding=utf-8 """ Internal tools for NimLime development & testing. """ from pprint import pprint import sublime try: from cProfile import Profile except ImportError: from profile import Profile from functools import wraps from pstats import Stats try: from StringIO import StringIO except ImportError: ...
1,522
439
import orjson from asynctest import TestCase, Mock, patch from freezegun import freeze_time from driftage.monitor import Monitor class TestMonitor(TestCase): def setUp(self): self.monitor = Monitor( "user_test@local", "pass_test", "identif" ) def tearDown(self): self.mon...
2,524
800
import fastarg import commands.todo as todo import commands.user as user app = fastarg.Fastarg(description="productivity app", prog="todo") @app.command() def hello_world(name: str): """hello world""" print("hello " + name) app.add_fastarg(todo.app, name="todo") app.add_fastarg(user.app, name="user") if __n...
354
128
import asyncio import uuid import pytest from aiomisc_pytest.pytest_plugin import TCPProxy import aiormq async def test_simple(amqp_channel: aiormq.Channel): await amqp_channel.basic_qos(prefetch_count=1) assert amqp_channel.number queue = asyncio.Queue() deaclare_ok = await amqp_channel.queue_dec...
7,177
2,381
__all__ = ['mediaclassification_stats']
39
12
''' Problem description: Given a string, determine whether or not the parentheses are balanced ''' def balanced_parens(str): ''' runtime: O(n) space : O(1) ''' if str is None: return True open_count = 0 for char in str: if char == '(': open_count += 1 ...
455
142
# -*- coding: utf-8 -*- """Parser for the CCleaner Registry key.""" import re from dfdatetime import time_elements as dfdatetime_time_elements from plaso.containers import events from plaso.containers import time_events from plaso.lib import definitions from plaso.parsers import winreg_parser from plaso.parsers.winr...
6,333
2,125
from abc import ABCMeta, abstractmethod from dataclasses import dataclass from typing import Any, TypeVar X = TypeVar('X') class Closeable(metaclass=ABCMeta): @abstractmethod def close(self) -> None: """ Close this to free resources and deny further use. """ raise NotImplementedError() cla...
1,296
381
import time import pytest from test import config from test.cube_utils import CubeUtils ITERATIONS_NUM = getattr(config, 'iterations_num', 1) ROUNDS_NUM = getattr(config, 'rounds_num', 10) class TestDefaultHighRes: @pytest.fixture(scope="class", autouse=True) def cube_default(self): cube_utils = Cu...
2,057
715
import pytest from mindmeld.components import Conversation def assert_reply(directives, templates, *, start_index=0, slots=None): """Asserts that the provided directives contain the specified reply Args: directives (list[dict[str, dict]]): list of directives returned by application templates ...
5,545
1,838
import os,sys import webbrowser import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.cm as cm import matplotlib.pylab as plt from matplotlib import ticker plt.rcParams['font.family'] = 'monospace' fig = plt.figure() rect = fig.add_subplot(111, aspect='equal') data0 = np.loadtxt('data0.dat', del...
1,707
761
from sarna.model.enums import Score, Language from sarna.report_generator import make_run from sarna.report_generator.locale_choice import locale_choice from sarna.report_generator.style import RenderStyle def score_to_docx(score: Score, style: RenderStyle, lang: Language): ret = make_run(getattr(style, score.nam...
455
135
# Open mode AP tests # Copyright (c) 2014, Qualcomm Atheros, Inc. # # This software may be distributed under the terms of the BSD license. # See README for more details. import logging logger = logging.getLogger() import struct import subprocess import time import os import hostapd import hwsim_utils from tshark impo...
20,000
7,501
#!/usr/bin/env python # coding: utf-8 # pylint: disable-all from __future__ import absolute_import from sklearn.preprocessing import LabelEncoder from pathlib import Path import torch from torch.autograd import Variable import torch.nn as nn import torch.optim as optim class BinModel(nn.Module): expected_target...
4,708
1,796
"""Simulate stochastic observing weather conditions. The simulated conditions include seeing, transparency and the dome-open fraction. """ from __future__ import print_function, division, absolute_import from datetime import datetime import numpy as np import astropy.time import astropy.table import astropy.units a...
9,894
2,884
# coding=utf-8 # Copyright 2015 Google 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 ap...
8,075
2,424
# -*- coding: utf-8 -*- """ @Project : RNN_Prediction @Author : Xu-Shan Zhao @Filename: stockPrediction202005201318.py @IDE : PyCharm @Time1 : 2020-05-20 13:18:46 @Time2 : 2020/5/20 13:18 @Month1 : 5月 @Month2 : 五月 """ import tushare as ts import tensorflow as tf import pandas as pd from sklearn.model_select...
2,924
1,194
#!/usr/bin/env python # -*- coding: utf-8 -*- from src import app import os import shutil from flask import Flask, render_template, session, request, flash, url_for, redirect from Forms import ContactForm, LoginForm, editForm, ReportForm, CommentForm, searchForm, AddPlaylist from flask.ext.mail import Message, Mail fro...
29,063
9,082
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 ...
19,221
6,762
""" test_pop_models.py Author: Jordan Mirocha Affiliation: UCLA Created on: Fri Jul 15 15:23:11 PDT 2016 Description: """ import ares import matplotlib.pyplot as pl PB = ares.util.ParameterBundle def test(): # Create a simple population pars_1 = PB('pop:fcoll') + PB('sed:bpass') pop_fcoll = ares.po...
1,433
655
# coding: utf-8 import time import hashlib import leancloud from leancloud._compat import to_bytes __author__ = 'asaka <lan@leancloud.rocks>' def sign_by_key(timestamp, key): return hashlib.md5(to_bytes('{0}{1}'.format(timestamp, key))).hexdigest()
258
93
""" mavsimPy - Chapter 4 assignment for Beard & McLain, PUP, 2012 - Update history: 12/27/2018 - RWB 1/17/2019 - RWB """ import sys sys.path.append('..') import numpy as np import parameters.simulation_parameters as SIM from chap2.mav_viewer import mav_viewer # from chap2.video_writer import ...
2,377
845
import os.path as osp import sys import numpy as np import mmcv from tqdm import tqdm from functools import cmp_to_key cur_dir = osp.dirname(osp.abspath(__file__)) PROJ_ROOT = osp.normpath(osp.join(cur_dir, "../../../../")) sys.path.insert(0, PROJ_ROOT) from lib.pysixd import inout, misc from lib.utils.bbox_utils impo...
6,010
3,001
from flask import abort from guniflask.context import service from ..config.jwt_config import jwt_manager @service class AccountService: accounts = { 'root': { 'authorities': ['role_admin'], 'password': '123456', } } def login(self, username: str, password: str): ...
918
253
import pandas as pd I = ["A", "B", "C", "D", "E"] oneDigit = pd.Series([1, 2, 3, 4, 5], pd.Index(I)) twoDigit = pd.Series([10, 20, 30, 40, 50], pd.Index(I)) print "addends:" print oneDigit print twoDigit print print "sum:" print oneDigit + twoDigit print I2 = ["A", "B", "C"] I3 = ["B", "C", "D", "E"] X = pd.Series(...
616
294
# # (c) 2008-2020 Matthew Shaw # import sys import os import re import logging import nelly from .scanner import Scanner from .program import Program from .types import * class Parser(object): def __init__(self, include_dirs=[]): self.include_dirs = include_dirs + [ os.path.join(nelly.root, 'grammars...
11,176
3,192
""" This module contains helper functions that provide information about how QCoDeS is installed and about what other packages are installed along with QCoDeS """ import sys from typing import Dict, List, Optional import subprocess import json import logging import requirements if sys.version_info >= (3, 8): from ...
2,363
671
from django.shortcuts import render from django.http import JsonResponse from .models import FieldCategory def fieldname_values(request): if request.method == "GET": fieldname = request.GET['fieldname'] query = request.GET.get('q') q_kwargs= dict( fieldname=fieldname, ...
1,177
342
# tests/test_provider_Mongey_kafka-connect.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:20:11 UTC) def test_provider_import(): import terrascript.provider.Mongey.kafka_connect def test_resource_import(): from terrascript.resource.Mongey.kafka_connect import kafka_connect_connector # T...
746
251
from flask import Flask, render_template, request, redirect, jsonify, g from flask import url_for, flash, make_response from flask import session as login_session from sqlalchemy import create_engine, asc from sqlalchemy.orm import sessionmaker from models import Base, Category, Item, User from oauth2client.client impo...
12,850
3,575
from .echo import echo, set_quiet from .errors import NooException, cancel from .store import STORE, FileStore, Store __all__ = ( "FileStore", "NooException", "Store", "STORE", "cancel", "echo", "set_quiet", )
239
87
# Copyright Allen Institute for Artificial Intelligence 2017 """ ai2thor.server Handles all communication with Unity through a Flask service. Messages are sent to the controller using a pair of request/response queues. """ import json import logging import sys import os import os.path try: from queue import Em...
20,472
6,283
from setuptools import setup setup(name='mydocstring', version='0.2.7', description="""A tool for extracting and converting Google-style docstrings to plain-text, markdown, and JSON.""", url='http://github.com/ooreilly/mydocstring', author="Ossian O'Reilly", license='MIT', pa...
625
190
# -*- coding: utf-8 -*- # # Copyright (c) 2020~2999 - Cologler <skyoflw@gmail.com> # ---------- # # ---------- import bson import struct from ..err import SerializeError from ..abc import * from ..core import register_format @register_format('bson', '.bson') class BsonSerializer(ISerializer): format_name = 'bson...
903
294
# -*- encoding: utf-8 -*- import json import os import shutil import tempfile from collections import OrderedDict from datetime import timedelta from pyparsing import ParseBaseException, ParseException, ParseSyntaxException import mock import pytest from pyhocon import (ConfigFactory, ConfigParser, ConfigSubstitution...
69,875
21,493
#!/usr/bin/env python # Copyright (c) 2018-2020 Intel Corporation # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ This module provides the ScenarioManager implementation. It must not be modified and is for reference only! """ from __future__ ...
7,416
2,035
# # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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...
43,104
12,398
from calendar import month_name class Tools: def __init__(self): self.output = "" def formatDate(self, date): elements = date.split("-") return f"{elements[2]}. {month_name[int(elements[1])]} {elements[0]}" def shortenText(self, string, n): #return first n sentences from strin...
1,740
539
#!/usr/bin/env python # -*- coding: utf-8 -*- #__Author__ = 烽火戏诸侯 #_PlugName_ = Shop7z /admin/lipinadd.asp越权访问 import re def assign(service, arg): if service == "shop7z": return True, arg def audit(arg): payload = 'admin/lipinadd.asp' target = arg + payload code, head,res, errcode...
583
253
"""Support for the Philips Hue lights.""" from __future__ import annotations from datetime import timedelta from functools import partial import logging import random import aiohue import async_timeout from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FL...
18,444
5,818
# Copyright (c) 2018-2021 Manfred Moitzi # License: MIT License # source: http://www.lee-mac.com/bulgeconversion.html # source: http://www.afralisp.net/archive/lisp/Bulges1.htm from typing import Any, TYPE_CHECKING, Tuple import math from ezdxf.math import Vec2 if TYPE_CHECKING: from ezdxf.eztypes import Vertex _...
4,794
1,562
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. #if __name__ == "__main__": # print "Hello World" from ProgrammingEmail import ManageAttachments import jpype import os.path asposeapispath...
666
222
from prompt_toolkit.key_binding.bindings.named_commands import (accept_line, self_insert, backward_delete_char, beginning_of_line) from prompt_toolkit.key_binding.bindings.basic import if_no_repeat from prompt_toolkit.key_binding.bindings.basic import load_basic_bindings from prompt_toolkit.key_binding.bindings.ema...
33,005
10,487
from biogeme import * from headers import * from loglikelihood import * from statistics import * from nested import * #import random cons_work= Beta('cons for work', 0,-10,10,0) cons_edu = Beta('cons for education',0,-50,10,0) cons_shopping = Beta('cons for shopping',0,-10,10,0) cons_...
10,909
5,846
# 初始化模块 from config import Config from flask import Flask from flask_sqlalchemy import SQLAlchemy # 数据库操作对象 db = SQLAlchemy() # 创建app def create_app(): # flask操作对象 app = Flask(__name__) # 通过配置文件读取并应用配置 app.config.from_object(Config) # 初始化数据库 db.init_app(app) # 员工管理子系统 from app.view i...
739
320
import json import web3 class EthereumConnection(): def __init__(self, url_node): self._url_node = url_node self._node_provider = web3.HTTPProvider(self._url_node) self._w3 = web3.Web3(self._node_provider) @property def w3(self): return self._w3 @property def url_...
1,225
399
"""STOCHASTIC ROSS plotting module. This module returns graphs for each type of analyses in st_rotor_assembly.py. """ import numpy as np from plotly import express as px from plotly import graph_objects as go from plotly import io as pio from plotly.subplots import make_subplots from ross.plotly_theme import tableau_...
60,991
17,775
import os import itertools import importlib import numpy as np import random STRATEGY_FOLDER = "exampleStrats" RESULTS_FILE = "results.txt" pointsArray = [[1,5],[0,3]] # The i-j-th element of this array is how many points you receive if you do play i, and your opponent does play j. moveLabels = ["D","C"] #...
4,227
1,548
# Copyright (c) 2014, Stanford University # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the ...
10,075
2,901
#!./venv/bin/python from lib.mbp32 import XKey from lib.utils import one_line_from_stdin xkey = XKey.from_xkey(one_line_from_stdin()) print(xkey) print("Version:", xkey.version) print("Depth:", xkey.depth) print("Parent FP:", xkey.parent_fp.hex()) print("Child number:", xkey.child_number_with_tick()) print("Chain cod...
611
239
from spherical_distortion.util import * sample_order = 9 # Input resolution to examine def ang_fov(s): print('Spherical Resolution:', s) for b in range(s): dim = tangent_image_dim(b, s) # Pixel dimension of tangent image corners = tangent_image_corners(b, s) # Corners of each tangent image ...
616
232