text
string
size
int64
token_count
int64
__author__ = 'Sergey' import shutil import os import stat def read_all_directory_path(root_folder, final_directory_list=[], folder_for_remove='.svn'): under_files_and_folders = os.listdir(root_folder) if os.path.split(root_folder)[1] == folder_for_remove: final_directory_list.append(root_folder) ...
1,656
522
"""Main package for tackle box.""" __version__ = "0.1.0-alpha.4"
65
27
from abc import ABC, abstractmethod from typing import Any, AsyncIterable, Callable, Awaitable, Optional, Union import uuid class BaseCommandExecution(ABC): @abstractmethod async def execute( self, command: str, *, stdin: Optional[bytes] = None, cwd: Optional[str] = None ) -> None: ... ...
1,374
421
from apps.flow.settings import config if config.SERVER_ENV != 'dev': from gevent import monkey monkey.patch_all() else: pass from apps.flow.views.deploy import deploy from apps.flow.views.flow import flow from library.api.tFlask import tflask def create_app(): app = tflask(config) register_blue...
563
193
from villas.controller.components.gateway import Gateway class VILLASrelayGateway(Gateway): def __init__(self, manager, args): # Some default properties props = { 'category': 'gateway', 'type': 'villas-relay', 'realm': manager.realm, 'name': args['i...
493
147
def trigger(): return """ CREATE OR REPLACE FUNCTION trg_ticket_prioridade() RETURNS TRIGGER AS $$ DECLARE prioridade_grupo smallint; prioridade_subgrupo smallint; BEGIN prioridade_grupo = COALESCE((SELECT prioridade FR...
880
254
import fiona from shapely import wkt, geometry from ..loaders import FileLoader from ..parsers.base import BaseParser from ..mappers import TupleMapper class FionaLoaderParser(FileLoader, BaseParser): """ Composite loader & parser mixin for GIS data, powered by Fiona """ layer_id = None meta = {} ...
4,315
1,288
""" File to house a requester connection """ from logging import getLogger import zmq from service_framework.utils.connection_utils import BaseConnection from service_framework.utils.msgpack_utils import msg_pack, msg_unpack from service_framework.utils.socket_utils import get_requester_socket LOG = getLogger(__name...
4,331
1,099
# from sklearn.cluster._kmeans import * import copy from typing import Union import torch import torch.nn as nn from sklearn.cluster._robustq import * from .quantizer import Quantizer __all__ = ['MiniBatchRobustqTorch', 'RobustqTorch'] class ClusterQuantizerBase(Quantizer): def __init__(self, n_feature=1, n_cl...
25,675
8,454
# CPU: 0.18 s n_rows, _ = map(int, input().split()) common_items = set(input().split()) for _ in range(n_rows - 1): common_items = common_items.intersection(set(input().split())) print(len(common_items)) print(*sorted(common_items), sep="\n")
247
92
from .blog_item import FormBlogItem from .edit_profile import FormEditProfile from .news_item import FormNewsItem from .publication import FormPublication
155
41
#!/usr/bin/python3 # -*- coding: utf-8 -*- from datetime import datetime import json import elasticsearch import argparse import logging import sys, os, time, atexit from signal import SIGTERM #needed for Daemon from httplib2 import Http #needed for put_dict class Daemon: """ A generic daemon class. ...
22,333
6,520
import time import os import spidev as SPI import SSD1306 from PIL import Image, ImageDraw, ImageFont # 调用相关库文件 from datetime import datetime PATH = os.path.dirname(__file__) RST = 19 DC = 16 bus = 0 device = 0 # 树莓派管脚配置 disp = SSD1306.SSD1306(rst=RST, dc=DC, spi=SPI.SpiDev(bus, device)) disp.begin() disp.clear() ...
2,195
900
class Solution: def shortestSuperstring(self, A: List[str]) -> str:
81
26
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: Gaivin Wang @license: Apache Licence @contact: gaivin@outlook.com @site: @software: PyCharm @file: chart.py @time: 10/10/2018 4:14 PM """ from pyecharts import Bar, Line, WordCloud import pandas as pd import random, os.p...
4,008
1,467
# -*- coding: utf-8 -*- import torch import argparse import numpy as np from model import PointCloudNet from code.utils import fp_sampling, knn_patch, helper_function import os parser = argparse.ArgumentParser() parser.add_argument('--num_points', default=1024, type=int, help='Number of points ...
2,773
1,111
''' Authors: Trond Henninen(trond.henninen@empa.ch) and Feng Wang This script is for generating normalised Gaussian simulated annular dark-field scanning transmission electron microscopy (ADF-STEM) images from input atomic coordinates. For rapidly generating a large dataset, it approximates a contrast similar to multi...
10,197
3,574
class APIException(Exception): def __init__(self, message, code=None): self.context = {} if code: self.context['errorCode'] = code super().__init__(message)
197
54
lista = [] pess = [] men = 0 mai = 0 while True: pess.append(str(input('Nome:'))) pess.append(float(input('Peso:'))) if len(lista)==0:# se nao cadastrou ninguem ainda mai = men = pess[1]#o maior é o mesmo que o menor e igual pess na posicao 1 que é o peso else: if pess[1] > mai: ...
906
368
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len = 0 l, r = 0, 0 count = dict() while r < len(s): count[s[r]] = count.get(s[r], 0) + 1 while count[s[r]] > 1: count[s[l]] = count[s[l]] - 1 l += 1 ...
399
151
import importlib from uvicorn.workers import UvicornWorker class DynamicUvicornWorker(UvicornWorker): """ This class is called `DynamicUvicornWorker` because it assigns values according to the module available Union['asyncio', 'uvloop'] It also set `lifespan` to `off` :) """ spam_spec = impo...
563
194
class DeviceInterface: # This operation is used to initialize the device instance. Accepts a dictionary that is read in from the device's yaml definition. # This device_config_yaml may contain any number of parameters/fields necessary to initialize/setup the instance for data collection. def initialize(self...
585
134
# 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 applica...
3,949
1,146
""" bridge-like integrator for amuse the bridge class provides a bridge like coupling between different gravitational integrators. In this way a system composed of multiple components can be evolved taking account of the self gravity of the whole system self consistently, while choosing the most appropiate i...
24,225
7,065
""" Handles classes and methods for an active local Game. Classes: `ActiveGame` - Represents an active LOL game `Player` - represents a player inside the game `ActivePlayer` - subclass of player, represents host `Item` - represents an item in game Methods: `check_status()` -> bool Err...
8,808
2,693
from core.himesis import Himesis import uuid class HExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans(Himesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule ExitPoint2BProcDefWhetherOrNotExitPtHasOutgoingTrans. """ # Flag this instan...
6,406
2,048
""" Show the INI config(s) used by a command tree. """ from .. import command class Show(command.Command): """ Show current INI configuration. Programs may make use of a configuration file which is usually located in your $HOME directory as .<prog>_config. The file is a standard INI style config fi...
1,553
425
import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from PIL import Image import pandas as pd from sklearn.decomposition import PCA from scipy.spatial.distance import pdist, squareform from scipy.sparse.linalg import eigs from numpy import linalg as LA from mpl_toolkits.mplot3d import Ax...
7,862
4,281
import typing from ex_dataclass import ex_dataclass, asdict, field, EXpack @ex_dataclass class User: # default_factory: 需要给一个类(可callable的对象) name: str = field(default_factory=str) # default: 给定一个默认值 age: int = field(default=0) @ex_dataclass class Team: team_name: str = field(default_factory=str)...
3,983
1,640
''' mro stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods''' print(__doc__) print('\n'+'-'*35+ 'Method Resolution Order'+'-'*35) class A(object): def dothis(self): print('From A class') class B1(A): de...
766
311
from twisted.trial import unittest from ..eventsource import EventSourceParser class FakeTransport: disconnecting = False def parse_events(s): fields = [] p = EventSourceParser(lambda name, data: fields.append((name,data))) p.makeConnection(FakeTransport()) p.dataReceived(s) return fields cla...
1,507
420
from coffea.nanoevents.methods.systematics.UpDownSystematic import UpDownSystematic __all__ = ["UpDownSystematic"]
116
37
# -*- coding: utf-8 -*- """ Microsoft-Windows-SecurityMitigationsBroker GUID : ea8cd8a5-78ff-4418-b292-aadc6a7181df """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp impor...
7,121
3,332
from pydub import AudioSegment from pydub.silence import split_on_silence def segment(filename,foldername): """ filename : str foldername: str folder to put all the chunks """ sound_file = AudioSegment.from_file(filename) sound_file = sound_file.set_channels(1) sound_file = sound_file.set_frame_rate(16000) ...
592
231
# coding: utf-8 import os size = os.path.getsize("test.txt") with open("test.txt", mode="r") as f: print(f.read(size))
126
53
# -*- coding: utf-8 -*- # !/usr/bin/python __author__ = 'ma_keling' # Version : 1.0.0 # Start Time : 2018-12-20 # Update Time : # Change Log : ## 1. ## 2. ## 3. import arcpy import CalculateLods def execute(): in_map = arcpy.GetParameter(0) arcpy.AddMessage("Input map : ...
494
215
import sys, os, re, codecs, json, glob import random from random import randint from collections import defaultdict from collections import Counter from sets import Set words=Set() def read_json_data(strJsonFile): with codecs.open(strJsonFile, 'r', encoding='utf-8') as f: try: json_data = jso...
1,099
363
# coding: utf-8 """ MBTA MBTA service API. https://www.mbta.com Source code: https://github.com/mbta/api # noqa: E501 The version of the OpenAPI document: 3.0 Contact: developer@mbta.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa:...
19,727
5,706
import aiodocker import interactive_widgets.backend.contexts.context class DockerContext(interactive_widgets.backend.contexts.context.Context): async def __aenter__(self): self.docker = aiodocker.Docker( url=self.configuration.get('url', None), ) await self.docker.__aenter__(...
499
146
import io import logging import time from typing import List, Optional from custom_components.xiaomi_cloud_map_extractor.common.map_data import MapData from custom_components.xiaomi_cloud_map_extractor.types import Colors, Drawables, ImageConfig, Sizes, Texts try: from miio import RoborockVacuum, DeviceException ...
12,524
4,154
import os; import time; cont_file_path = './cont.txt'; log_file_path = './logs/'; def can_continue(): can_cont = True; if os.path.exists(cont_file_path): with open(cont_file_path,'r') as f: line = f.readline(); if(line=='Y'): print("Cont..."); ca...
974
355
# -*- coding: utf-8 -*- """ flask_cors ~~~~ Flask-CORS is a simple extension to Flask allowing you to support cross origin resource sharing (CORS) using a simple decorator. :copyright: (c) 2014 by Cory Dolphin. :license: MIT, see LICENSE for more details. """ from .decorator import cross_origin...
418
144
from rest_framework import viewsets from .models import Vehicle from .serializers import VehicleSerializer class VehicleViewSet(viewsets.ModelViewSet): model = Vehicle serializer_class = VehicleSerializer def pre_save(self, obj): if obj.resident_id is None: obj.resident = self.requ...
554
161
from Locators.checkout_overview_locator import CheckoutOverviewLocator from Objects.product import Product from Pages.base_page_object import BasePage from Utils.utility import Utils class CheckoutOverViewPage(BasePage): def __init__(self, driver): super().__init__(driver) def get_product_overview_info(self...
1,337
481
# -*- coding: utf-8 -*- # https://github.com/Kodi-vStream/venom-xbmc-addons import xbmcaddon, xbmcgui, xbmc """System d'importation from resources.lib.comaddon import addon, dialog, VSlog, xbmcgui, xbmc """ """ from resources.lib.comaddon import addon addons = addon() en haut de page. utiliser une fonction comad...
6,336
2,212
#!/usr/bin/env python # encoding: utf-8 """ @version: v1.0 @author: xag @license: Apache Licence @contact: xinganguo@gmail.com @site: http://www.xingag.top @software: PyCharm @file: replace_source.py @time: 4/25/19 10:46 @description:替换apk的资源文件 """ from file_utils import * import os from subprocess impo...
2,457
1,091
from dataclasses import dataclass from bindings.gmd.arc_by_center_point_type import ArcByCenterPointType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class CircleByCenterPointType(ArcByCenterPointType): pass
226
77
# type: ignore[attr-defined] from solids import example_one_solid # pylint: disable=import-error from dagster import pipeline @pipeline def example_one_pipeline(): example_one_solid()
192
64
"Utility Fireworks functions borrowed from the atomate package." import logging import os import sys from typing import Optional def env_chk( val: str, fw_spec: dict, strict: Optional[bool] = True, default: Optional[str] = None, ): """ Code borrowed from the atomate package. env_chk() is ...
1,637
494
import random import torch from game import Game from agent import RLAgent from moves import Moves game=Game() agent=RLAgent() moves=Moves() num_win=0 #initialize no. of win by human num_lose=0 #initialize no. of win by ai but loss by human num_tie=0 random.seed(1000) def check_board_and_may_update_state_values():...
1,328
606
# receive_msg.py # # SPDX-FileCopyrightText: Copyright 2021 Fabbio Protopapa # # SPDX-License-Identifier: MIT # # Receive message from IOTA tangle # import iota_client import os import pprint # Config msg_meta = False env_node_address = 'HORNET_NODE_ADDRESS' # Print Message data def show_message(message, meta=Fals...
2,265
738
# -*- coding: utf-8 -*- """ Turn on and off systemd suspend inhibitor. Configuration parameters: format: display format for this module (default '[\?color=state SUSPEND [\?if=state OFF|ON]]') lock_types: specify state to inhibit, comma separated list https://www.freedesktop.org/wiki/Software/sy...
2,601
864
import numpy as np import time def create_maze(): height = input("\n Enter the number of rows: ") width = input("\n Enter the number of columns: ") if height.isdigit() and width.isdigit(): height, width = int(height), int(width) grid = np.random.randint(0, 10, (height, width)) grid[...
1,595
531
from typing import Callable from enum import Enum from io import TextIOBase import sys class TokenType(Enum): EOF = -1 DEF = -2 EXTERN = -3 IDENTIFIER = -4 NUMBER = -5 OP = -6 class Token: GENERIC_TOKEN_TYPES = [TokenType.NUMBER, TokenType.IDENTIFIER, TokenType.OP] def __init__(sel...
2,707
878
import peeweedb import astropy.units as u def get_by_basename(db, table, basename): """Get data from SQL database by basename. Returns a list of dict""" if isinstance(table, str): assert table in db.get_tables(), "Sanity Check Failed: Table queried does not exist" table = peeweedb.tabl...
1,175
389
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2021-2022 Hewlett Packard Enterprise, Inc. All rights reserved. # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''...
5,878
1,602
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' PyTorch Implementation of training DeLF feature. Solver for step 1 (finetune local descriptor) nashory, 2018.04 ''' import os, sys, time import shutil import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from utils import...
8,407
2,572
import torch import torch.nn.functional as F from torch import nn from util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_dist_avail_and_initialized) from .backbone import build_backbone from .matcher import build_mat...
13,248
4,581
import numpy as np import torchvision import os import argparse import warnings warnings.filterwarnings('ignore') from PIL import Image, ImageDraw import torch from torch.utils.data import Dataset, DataLoader from torchvision import datasets, models, transforms import torchvision.ops from retinanet.dataloader import CS...
7,110
2,252
import datetime from data_sqlalchemy.modelbase import SqlAlchemyBase import sqlalchemy as sa class Word(SqlAlchemyBase): __tablename__ = "words" # id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) id = sa.Column(sa.String, primary_key=True) created_date = sa.Column(sa.DateTime, default...
518
170
import bpy from bpy.props import * from ...preferences import get_pref def update_node(self, context): try: self.node.node_dict[self.name] = self.value # update node tree self.node.update_parms() except Exception as e: print(e) class RenderNodeSocketInterface(bpy.types.NodeSo...
9,023
2,989
from webapp.extensions import db
35
11
from keras.models import load_model import numpy as np import pandas as pd from keras.preprocessing.image import ImageDataGenerator from sklearn.cluster import KMeans from time import time # Takes a pandas dataframe containing the cluster assignment and ground truth for each data point # and returns the purity of the ...
5,823
1,789
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Components of the simulation system, namely blocks, wires and plugs. """ from abc import ABC, abstractmethod from typing import Any, Iterable, List, Optional as Opt, Tuple, Union, TYPE_CHECKING from typing_extensions import Literal from bdsim.core import np if TYPE_CH...
26,954
7,853
import os, sys import math import random sys.path.insert(0, os.path.basename(__file__) + os.sep + '..' + os.sep + '..') from server.switch import _Switch from server.node import _Node from utils import util from alg.utils.topology import Topology from .base import BasePlaceMent class RandomPlaceMent(BasePlaceMent): ...
4,509
1,373
from unittest import TestCase from fbl_handler.message_id_extractor import MessageIdExtractor class TestMessageIdExtractor(TestCase): def setUp(self): self.message_id_extractor = MessageIdExtractor() def test_extract_from_yandex_fbl(self): with open('files/yandex_fbl.txt', 'r') as file: ...
466
161
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # """Evohome RF - Opentherm processor.""" import logging import struct from typing import Any from .const import __dev_mode__ DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) # Data structure shamelessy cop...
30,169
11,009
import bokeh.io import bokeh.plotting import bokeh.layouts import bokeh.palettes import seaborn as sns import numpy as np import os import matplotlib.pyplot as plt import matplotlib def plotting_style(grid=True): """ Sets the style to the publication style """ rc = {'axes.facecolor': '#E3DCD0', ...
3,030
1,196
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ This code is a part of django.utils.six on https://github.com/django/django/blob/stable/2.2.x/django/utils/six.py removed form Django 3.0 To keep the backward compatibility between python 2 and 3 the decorator need to be used as well, during ...
992
311
#!/usr/bin/env python3 ''' start of support of theaudiodb ''' from html.parser import HTMLParser import logging import logging.config import logging.handlers import os import requests import requests.utils import nowplaying.bootstrap import nowplaying.config from nowplaying.recognition import RecognitionPlugin cla...
4,206
1,276
# -*- coding: utf-8 -*- # 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, softw...
2,237
692
import os import io import os import pandas as pd import numpy as np from google.cloud import vision from PIL import Image from google.cloud import vision from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics import mean_squared_error as MSE import pickle as pkl import time import tqdm features_...
8,328
3,209
from common.scripts.cleaning import strip def test_clean_identity(): assert strip(None) == "" assert strip("NaN") == "" row_input = "Holà chicanos" assert strip(row_input) == row_input
203
65
from main import process import os import platform import subprocess import sys import threading import webview def worker_thread(window, inputfiles, model): print('processing started ...') count = 0 for inputfile in inputfiles: count += 1 (inputfilepath, inputfilename) = os.path.split(inputfil...
2,186
682
from django.contrib.auth.models import AbstractUser # Create your models here. class ContextUser(AbstractUser): """ Just an abstract model class to represent Auth user coming as context in GRPC requests """ class Meta: abstract = True def __str__(self): return " ".format([self.fi...
347
93
import math import torch.nn as nn from .modules import QConv2d, QLinear def make_layers(cfg, batch_norm=False, wbit=4, abit=4): layers = list() in_channels = 3 for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] elif v == 'A': layers += [nn....
2,258
961
#!/usr/bin/python ''' Central Templates Ansible Module ''' # MIT License # # Copyright (c) 2020 Aruba, a Hewlett Packard Enterprise company # # 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 w...
12,732
3,500
from django.db import models from django.utils.translation import ugettext_lazy as _ from habitat.timezone import get_timezone timezone = get_timezone() class MissionDate(models.Model): date = models.CharField( verbose_name=_(timezone.DATE_VERBOSE_NAME), help_text=_(timezone.DATE_HELP_TEXT), ...
897
280
#!/usr/bin/env python from __future__ import print_function import sys import serial import time from math import sin, cos, pi import argparse import ast from comms import * from boards import * from livegraph import livegraph if __name__ == '__main__': parser = argparse.ArgumentParser(description='Drive motor m...
3,097
917
import erdos class WaypointsMessage(erdos.Message): """Message class to be used to send waypoints. Optionally can also send a target speed for each waypoint. Args: timestamp (:py:class:`erdos.timestamp.Timestamp`): The timestamp of the message. waypoints (list(:py:class:`~pyl...
1,889
532
def solution(s1, s2): ''' EXPLANATION ------------------------------------------------------------------- I approached this problem by creating two dictionaries, one for each string. These dictionaries are formatted with characters as keys, and counts as values. I then iterate over each string, ...
1,959
503
a = float(input('Введите число: ')) def koren (a): x = 3 k = 0 if (a<0): raise ValueError('Ошибка, введите число, меньшее нуля') while k != (a**0.5): k = 0.5 * (x + a/x) x = k return(k) print('Корень из числа ' + str(a) + ' равен ' + str(koren(a)))
295
136
from typing import Optional class BaseCaseMethodNotImplemented(Exception): """ Exception when a BaseCase method has not been implemented. """ pass class BaseCase: """ Base class for representing a dataset case with a mandatory question text and an optional question id and sparql query an...
2,350
597
class Node: def __init__(self, data=None, left=None, right=None): self._left = left self._data = data self._right = right @property def left(self): return self._left @left.setter def left(self, left): self._left = left @property def right(self): return self._right @right.setter def right(self, ...
2,151
769
import json import plotly import pandas as pd from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize from flask import Flask from flask import render_template, request, jsonify from plotly.graph_objs import Bar from sklearn.externals import joblib from sqlalchemy import create_engine app = ...
4,531
1,260
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __all__ = ("natural_earth",) from .natural_earth import natural_earth
119
49
#Faça um programa que pergunte ao usuario o valor do produto, #e mostre o valor final com 5% de desconto. valorProduto = float(input('Qual o valor do produto? R$ ')) desconto = (valorProduto * 5) / 100 vFinal = valorProduto - desconto print('O valor do produto é R${}'.format(valorProduto)) print('O novo valor com o d...
355
137
# # Copyright (c) 2017, UT-BATTELLE, LLC # All rights reserved. # # This software is released under the BSD license detailed # in the LICENSE file in the top level a-prime directory # ###Work in Progress: Plot meridional averages for different fields in the same plot. ###07/03/2017 import matplotlib as mpl #changing t...
9,880
3,176
import kabusapi url = "localhost" port = "18081" # 検証用, 本番用は18080 password = "hogehoge" # 初期設定・トークン取得 api = kabusapi.Context(url, port, password) # 取得トークンの表示 print(api.token) # トークンを指定した初期設定 パスワードが不要 api = kabusapi.Context(url, port, token='fugafuga') # 注文発注 (現物買い) data = { "Password": "hoge", "Symbol": ...
1,670
894
# A resizable list of integers class Vector(object): # Attributes items: [int] = None size: int = 0 # Constructor def __init__(self:"Vector"): self.items = [0] # Returns current capacity def capacity(self:"Vector") -> int: return len(self.items) # Increases capacity of...
2,766
1,068
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import Dict, Optional, Sequence from refinery.units.blockwise import Arg, BlockTransformation from refinery.lib.tools import isbuffer class map(BlockTransformation): """ Each block of the input data which occurs as a block of the index argument is re...
2,330
649
''' Arithmetic progression with 10 elements. ''' first_term = int(input('Type the first term of this A.P: ')) reason = int(input('Type the reason of this A.P: ')) last_term = first_term + (50-1)*reason # A.P formula for c in range (first_term, last_term + reason , reason): print(c, end=' ► ')
299
106
#!/usr/bin/env python import logging import sys from pathlib import Path from typing import Union, List, Dict, Any, Optional, Tuple import os import numpy as np import pandas as pd from cascade_at.core import CascadeATError from cascade_at.context.model_context import Context from cascade_at.core.log import get_logger...
11,360
3,454
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains configuration and setup utilities for the `astropy` project. This includes all functionality related to the affiliated package index. """ from __future__ import (absolute_import, division, print_function, u...
414
111
import sys from collections import defaultdict input = sys.stdin.readline mod = 998244353 def extgcd(a,b): r = [1,0,a] w = [0,1,b] while w[2] != 1: q = r[2]//w[2] r2 = w w2 = [r[0]-q*w[0],r[1]-q*w[1],r[2]-q*w[2]] r = r2 w = w2 return [w[0],w[1]] def mod_inv(a,...
1,047
476
# pylint: skip-file import json import requests url = "http://localhost:8085/v1/graphql" def fetch_evals(term, dump=True): query = ( """ query MyQuery { courses(where: { season: {season_code: {_eq: \"""" + str(term) + """\"}}, school: {...
1,363
404
from dataclasses import dataclass from . import Spec from dto.person import PersonDTO @dataclass class HasNameSpec(Spec): def passes(self, candidate: PersonDTO) -> bool: return candidate.name is not None and candidate.name != "" @dataclass class HasAgeSpec(Spec): def passes(self, candidate: PersonDT...
1,375
440
import requests HUB_LOCATION = 'http://hub.wattbike.com/ranking/getSessionRows?sessionId=' class HubClient: def __init__(self, location=None): self.location = location if location else HUB_LOCATION def _validate_session_id(self, session_id): # TODO: add regex validation of session_id ...
629
195
from django.shortcuts import get_object_or_404, render from django.http import Http404 from .models import MainMetadata from cal.models import Event from classes.models import ClassInstance from cal.models import Event from datetime import date, timedelta # Create your views here. def about(request): about = Mai...
1,436
431
import json import requests import tenacity from bs4 import BeautifulSoup from geopy.geocoders import Nominatim from urllib.parse import parse_qs from urllib.parse import urlparse @tenacity.retry(retry=tenacity.retry_if_exception_type(IOError), wait=tenacity.wait_fixed(2)) def get_grid_ref_for_postcode(nominatim, pos...
1,761
633