id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1606674
<filename>ctbBio27/check.py #!/usr/bin/python2.7 """ script for checking to see if a file exists also consider: os.path.isfile(file) """ import sys import os def check(file): """ if a file exists, return 'True,' else, 'False' """ # return os.path.isfile(file) try: open(file) return True except (OSError, IOE...
StarcoderdataPython
1710167
class CircularlyLinkedList: """ The implementation of the Circular Linked List ADT """ class _Node: """ Lightweight, nonpublic class for storing a circularly linked node """ __slots__ = 'element', 'next' def __init__(self, element, next_node=None): """ Creates a node object...
StarcoderdataPython
3286443
from django.apps import AppConfig class DiscussionForumConfig(AppConfig): name = 'Discussion_forum'
StarcoderdataPython
28243
<filename>project-vitas.py import os import sys import json import shutil import ipfsapi import base64 import datetime import maya from twisted.logger import globalLogPublisher from umbral.keys import UmbralPublicKey ### NuCypher ### from nucypher.characters.lawful import Alice, Bob, Ursula from nucyphe...
StarcoderdataPython
3267527
from cli_ui.tests import MessageRecorder from tsrc.test.helpers.cli import CLI from tsrc.test.helpers.git_server import GitServer def test_happy( tsrc_cli: CLI, git_server: GitServer, message_recorder: MessageRecorder ) -> None: """ Scenario: * Create a manifest with two repos, foo and bar * Init...
StarcoderdataPython
31426
import sys import pylab as plb import numpy as np import mountaincar class DummyAgent(): """A not so good agent for the mountain-car task. """ def __init__(self, mountain_car = None, parameter1 = 3.0): if mountain_car is None: self.mountain_car = mountaincar.MountainCar() ...
StarcoderdataPython
161491
"""Automatic differentiation of tensor expressions.""" from ._ffi.function import _init_api from ._ffi.node import NodeBase, register_node _init_api("tvm.autodiff") @register_node class DifferentiationResult(NodeBase): """Result of differentiation. Parameters ---------- result : List[Tensor] ...
StarcoderdataPython
3320812
<reponame>PatrickCmd/GraphQL-and-REST<filename>rest/blog/users/schema.py from marshmallow import Schema from webargs import fields, validate class UserSchema(Schema): id = fields.Int(dump_only=True) username = fields.String(required=True, validate=validate.Length(3)) email = fields.String(required=True, ...
StarcoderdataPython
4810948
import asyncio import collections import logging import pathlib import traceback import typing import aiohttp from .events import RoundComplete, StartRound from .state import GoblinState log = logging.getLogger(__name__) # log.setLevel(logging.DEBUG) class GoblinClient: def __init__(self, http_base="http://go...
StarcoderdataPython
1775661
# fixtures: Fixtures with cleanups for testing and convenience. # # Copyright (c) 2010, <NAME> <<EMAIL>> # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use thi...
StarcoderdataPython
3301414
#!/usr/bin/env python2.7 # Copyright (c) 2015, VMRaid Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import os import vmraid vmraid.connect(site=os.environ.get("site"))
StarcoderdataPython
4825970
"""main sim script to run sims""" import sys import platform import re import os from os import listdir import importlib import yaml from internal.weights import find_weights from internal.sim_parser import parse_json from internal.sim_parser import get_timestamp from internal.analyze import analyze from internal imp...
StarcoderdataPython
3306560
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2020 Dell Inc. or its subsidiaries. All Rights Reserved # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ############################################# # WARNING # ######################...
StarcoderdataPython
14754
# -*- coding: utf-8 -*- import os import sys import types import unittest import inspect from lxml import etree from . import XSL, XML, VERSION_LIST from .core import get_module, get_stylesheet, get_source_version, get_migration_path, list_versions from .main import parse_args from .migrate import migrate_by_styleshe...
StarcoderdataPython
1781259
# =============================================================================== # Copyright 2016 dgketchum # # 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...
StarcoderdataPython
1678428
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_functional.ipynb (unless otherwise specified). __all__ = ['zip_cycle_longest', 'lmap', 'lzip', 'lfilter', 'lrange', 'Lmap', 'Lzip', 'Lfilter', 'Lrange', 'isinstance', 'compose_star', 'add_kwargs', 'get_all_public_attr', 'pcolkw'] # Cell from .imports impor...
StarcoderdataPython
1628473
#! /usr/bin/env python3 import os import sys import numpy as np from multiprocessing import Pool from datetime import datetime import arrow data_dir = 'raw_data/' out_dir = 'clean_data/' out_dir = os.path.dirname(out_dir) + '/' if out_dir: os.makedirs(out_dir, exist_ok=True) def decode_to_bool(bytes_to_decode): ...
StarcoderdataPython
3261367
from typing import Generic, Optional, TypeVar, Union from pyspark.sql import DataFrame, Column from spark_auto_mapper.data_types.array_base import AutoMapperArrayLikeBase from spark_auto_mapper.data_types.data_type_base import AutoMapperDataTypeBase from spark_auto_mapper.type_definitions.wrapper_types import ( A...
StarcoderdataPython
3200049
<reponame>JE-Chen/je_old_repo '''OpenGL extension EXT.cull_vertex This module customises the behaviour of the OpenGL.raw.GL.EXT.cull_vertex to provide a more Python-friendly API Overview (from the spec) This extension introduces a method for culling vertexes in object space based on the value of the do...
StarcoderdataPython
4813841
<filename>home_application/views.py from django.http import JsonResponse from django.shortcuts import render # Create your views here. def home(request): """ 首页 """ return render(request, "index.html") def hello_world(request): host = request.get_host() path = request.get_full_path() re...
StarcoderdataPython
41797
<filename>tester/tester/timeout.py<gh_stars>1-10 import logging import os import time import math logger = logging.getLogger(__name__) class TimeoutManager: # we will keep 15s for mantainance in this python app, it should be very # generous and should be enough for everyone TIMEOUT = max(int(os.getenv('T...
StarcoderdataPython
1744529
<filename>src/ros-basics/move_robot.py #! /usr/bin/env python import rospy from geometry_msgs.msg import Twist rospy.init_node('move_robot_node') pub = rospy.Publisher('cmd_vel_mux/input/teleop', Twist, queue_size=1) rate = rospy.Rate(2) move = Twist() move.linear.x = 0.5 #Move the robot with a linear velocity in the...
StarcoderdataPython
186840
from siuba.sql import LazyTbl import pytest import os from sqlalchemy import create_engine, types BACKEND_CONFIG = { "postgresql": { "dialect": "postgresql", "dbname": ["SB_TEST_PGDATABASE", "postgres"], "port": ["SB_TEST_PGPORT", "5433"], "user": ["SB_TEST_PGUSE...
StarcoderdataPython
3257044
'''Environment Agent for SIR model: infects random agent at timestep 7. @author: <NAME> <<EMAIL>> ''' from ComplexNetworkSim import NetworkAgent, Sim from agent_SIR import INFECTED, SUSCEPTIBLE, RECOVERED class SIRenvironment(NetworkAgent): def __init__(self, state, initialiser): NetworkAg...
StarcoderdataPython
3215454
<filename>sagemaker_batch_transform/tensorflow_open-images_jpg/code/inference.py # 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. A copy of # the License is loc...
StarcoderdataPython
3261913
# 期权交易行动类 import numpy as np class SopAction(object): IDX_OPTION = 0 IDX_ACTION = 1 IDX_PERCENT = 2 def __init__(self, env): self.refl = 'apps.sop.SopAction' self.action = [ np.zeros((len(env.ds.key_list),)), np.zeros((3,)), np.zeros((10...
StarcoderdataPython
1653959
# Author <NAME> for Encoder training import torch import torch.nn as nn import sys import os sys.path.append("./model") sys.path.append("./loss") sys.path.append('./utils') import dataset import torch.autograd as autograd import VGANCox import argparse from torch.backends import cudnn import datetime import time impo...
StarcoderdataPython
3386594
<filename>src/models/UserModel.py # -*- coding: utf-8 -*- # src/models/UserModel.py """ ...Web Flask com autorização JWT (Jason web token authorization) ------------------------------------------------------------------------ Modelo de usuário ----------------------------------------...
StarcoderdataPython
1794942
<reponame>Miracle1991/DetectionHub # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # from ._utils import _C from DetectionHub import _C import torch # we need this for the custom ops to exist import DetectionHub._custom_ops # noqa: F401 from DetectionHub.utils import amp _nms = torch.ops.De...
StarcoderdataPython
4825394
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Copyright (c) 2019, Eurecat / UPF # 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...
StarcoderdataPython
3249480
from viscum.plugin import (Module, ModuleArgument, ModuleCapabilities) from periodicpy.irtools.lirc import LircClient import os.path _MODULE_VERSION = '0.1' _MODULE_DESCRIPTOR = 'lircd.json' def module_version(): """Get module version """ return _MODU...
StarcoderdataPython
3366995
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
StarcoderdataPython
1648583
''' Created on 09.11.2017 @author: sfs ''' import numpy as np from matplotlib import pylab from pylab import * nums = np.arange(51) probs = np.random.randint(low = 0, high = 10, size= (1, 51)) cdict = {'red': ((0.0, 0.0, 0.0), (0.5, 1.0, 0.7), (1.0, 1.0, 1.0)), 'green': ((0.0, 0.0,...
StarcoderdataPython
89441
<gh_stars>0 from enum import Enum, auto class EquipmentSlots(Enum): MAIN_HAND = auto() OFF_HAND = auto() HEAD = auto() CHEST= auto() HANDS = auto() LEGS = auto() FEET = auto() class EquipmentSlotGroups(): WEAPONS = [EquipmentSlots.MAIN_HAND] ARMOR = [EquipmentSlots.HEAD, Equipment...
StarcoderdataPython
37312
from math import floor, log n = lambda x: (x + 1) % 2 + 1 s = lambda x: floor(log(x + 1, 2)) r = lambda x: x // 2 - n(x) + 1 + n(x) * 2**(s(x) - 1) pn = lambda p: r(p) + (n(p) == 2) * (r(r(p)) - r(p)) dn = lambda p, d: (d + (n(p) == n(d) == 2) * (n(r(p)) * 2**s(d)) - (n(p) == 1)) // (3 - n(p))
StarcoderdataPython
109426
<reponame>DataManagementLab/thesis-fl_client-side_validation<filename>cliva_fl/validation/method/freivald.py import torch from cliva_fl.utils import tensors_close global global_diff def freivald(A, B, C, bias=None, rtol=1e-05, atol=1e-08, n_check=1): """ Freivalds' algorithm to check if AB = C Avoid erro...
StarcoderdataPython
1720504
from PIL import Image import torch import torch.utils.data as data class ClsDataset(data.Dataset): def __init__(self, txt_path, root, transform=None): fh = open(txt_path, 'r') lists = [] for line in fh: line = line.rstrip() words = line.split(' ') lists...
StarcoderdataPython
28915
#from utils import ordinal import re from urllib.parse import quote as uriquote import asyncio from bs4 import BeautifulSoup import collections from utils.context import MoreContext from utils.context import Location from utils.paginator import Paginator from utils.units import units ordinal = lambda n: "%d%s" % (n,"t...
StarcoderdataPython
1671141
import pytest from time import time from unittest.mock import Mock, call from quickrpc.transports import Transport, MuxTransport, RestartingTransport, TransportError class MyVal: pass class MyTransportError(Exception): pass class MyTransport(Transport): def __init__(self): Transport.__init__(self) ...
StarcoderdataPython
3308653
############################################################################## # Written by: <NAME> <<EMAIL>> # Date: 01/07/2009 # Description: tabpage.py wrapper script # Used by the tabpage-*.py tests ############################################################################## import sys impor...
StarcoderdataPython
1646631
from django.contrib import admin from .models import * # Register your models here. admin.site.register(CtasContable) admin.site.register(SumasYSaldos) admin.site.register(EmpresasClientes)
StarcoderdataPython
3385376
wallet_user_id = '6005794' wallet_char_id = '90602792' wallet_api_key = '8CBBA3EC31E54F6FB23E7FE0B77705A5B07CD36B405749E0A781E4A2F4565705' wallet_corp_id = '98055909' LAST_REFID_KEY = 'last_refid' PULL_TIME_KEY = 'pull_time' WALLET_BALANCE_KEY = 'wallet_balance' def load_refid(): refid = 0 if not db(db.persist...
StarcoderdataPython
3335803
''' pickle is GREAT for this saving specified data structure task. ''' import pickle from collections import defaultdict def load_words(filename = "words.txt"): with open(filename) as f: for word in f: yield word.rstrip() # return a generator def all_anagram(l): '''Reads a list and return a set of anagram word...
StarcoderdataPython
4838208
<gh_stars>1-10 #!/usr/bin/python ''' To reproduce the plots from the Seek paper, plot supplemental 1a requires grouping queries by query size (such as all queries with 2 genes, with 4 genes etc). This program iterates through the output files from SeekMiner and groups them by query size and creates a set of filelists ...
StarcoderdataPython
69769
<filename>crud-python/Ex09_ReadMetrics.py #!/usr/bin/env python3 from db_connection import Connection import uuid print('========================================') print('Start exercise') journey_id = uuid.UUID('230995ee-c697-11ea-b7a1-8c85907c08dd') spacecraft_name = 'Crew Dragon Endeavour,SpaceX' try: connecti...
StarcoderdataPython
195228
from os import path class File: def __init__(self, file_path): self.__path = file_path self.__name = path.basename(self.__path) self.__size = path.getsize(self.__path) self.__jpg_name = '' self.__jpg_size = 0 self.__jpg_percent = 0 def get_path(self) -> str: ...
StarcoderdataPython
4813520
from IPython.core.display import display, HTML import testpyColab.displayhtml as dhtml class Student(): def __init__(self, group=1, id='sin_id'): self.group = group self.id = id def check_info(self): msg = f'¡Bienvenido estudiante {self.id}! El grupo ingresado ha sido {self.group}...
StarcoderdataPython
1689259
<filename>retinanet/train.py from math import isfinite from statistics import mean import torch from apex import amp from apex.parallel import DistributedDataParallel from torch.optim import Adam, SGD from torch.optim.lr_scheduler import ReduceLROnPlateau from .backbones.layers import convert_fixedbn_model from .dali...
StarcoderdataPython
1757894
<gh_stars>0 def splitChars(chars): numeric = 0 strings = {0:"", 1:"", 2:"", 3:""} for letter in chars: if letter.isupper(): if letter not in strings[0]: strings[0] += letter elif letter.islower(): if letter not in strings[1]: strings[1...
StarcoderdataPython
3359059
<reponame>giantryansaul/easy_blog_django<filename>easy_blog_django/tags/views.py from django.views.generic import ListView, DetailView, CreateView from .models import Tag from ..posts.models import Post class PostsByTagNameMixIn(object): """ Returns posts related to the tag name. """ def get_context_...
StarcoderdataPython
1663487
from src.utils.cli import main main()
StarcoderdataPython
3294462
from django.core.management.base import BaseCommand from app.models import Player, PlayerRole, Spectator, Moderator, most_recent_game class Command(BaseCommand): help = 'Prints a list of all zombie emails' def handle(self, *args, **options): game = most_recent_game() spectators = Spectator.o...
StarcoderdataPython
89797
""" Proof of concept for pytest + rich integration. """ import sys import warnings from pathlib import Path from typing import Dict from typing import List from typing import Optional from typing import Sequence from typing import Tuple from typing import Union import attr import pytest from _pytest._code.code import ...
StarcoderdataPython
88440
from collections import OrderedDict import torch import torch.nn as nn from gym import spaces from rl.policies.utils import MLP, BC_Visual_Policy from rl.policies.actor_critic import Actor, Critic from util.gym import observation_size, action_size, goal_size, box_size, robot_state_size, image_size import numpy as np...
StarcoderdataPython
147680
<gh_stars>0 from typing import List from jetavator.config import ComputeServiceConfig import wysdom DatabricksLibraryConfig = wysdom.SchemaDict(wysdom.SchemaAnything()) class DatabricksConfig(ComputeServiceConfig): type: str = wysdom.UserProperty(wysdom.SchemaConst('remote_databricks')) host: str = wysdom....
StarcoderdataPython
3307289
from pyglet.window import key class InputHandler(key.KeyStateHandler): inputs = [0]*16 keys = { key.Q: 0x0, key.W: 0x1, key.E: 0x2, key.R: 0x3, key.T: 0x4, key.Y: 0x5, key.U: 0x6, key.I: 0x7, key.O: 0x8, key.P: 0x9, key.A...
StarcoderdataPython
1716259
<gh_stars>0 import os import datetime import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt from logger import Logger class Plotter(object): def __init__(self, p_tup, stat, year=None): self.log = Logger('Plotter', save_dir='logs') se...
StarcoderdataPython
3328281
<gh_stars>0 import os import logging as log from settings.base import setup_logger """If you must to debug your project import this file 'from logger import LOG' and all ready to work""" class Logger: BASE_DIR = '/opt/docker_polls_group/api/' conf = { 'version': 1, 'disable_existing_loggers': False,} ...
StarcoderdataPython
85879
<reponame>cbefus/Eynnyd from eynnyd.exceptions import InvalidCookieHeaderException from eynnyd.internal.utils.cookies.request_cookie import RequestCookie from eynnyd.internal.utils.cookies import rfc class CookieHeaderConverter: @staticmethod def from_header(header): cookies = {} for token in...
StarcoderdataPython
1649432
from astropy.table import Table, Column from astropy.coordinates import SkyCoord import numpy as np import sys import yaml def main(): ext_sources = yaml.load(open(sys.argv[1])) srcnames = sorted(ext_sources.keys()) #srcnames = ['3fgl_j1209.1-5224','fhes_j2125.8+5833e'] tables = [Table.read('s...
StarcoderdataPython
3215753
import os import re import time from dataclasses import dataclass, field from timeit import repeat from typing import Optional,Dict, Union, Any, Tuple, List import fitlog import nltk import numpy as np import datasets import torch import torch.nn as nn import torch.distributed as dist from torch.utils.data import Data...
StarcoderdataPython
3258584
"""init.py.""" # -*- coding: utf-8 -*- # @Author: AnthonyKenny98 # @Date: 2019-11-11 14:10:44 # @Last Modified by: AnthonyKenny98 # @Last Modified time: 2019-11-11 14:23:53 from .chatbot import ChatBot # noqa: F401
StarcoderdataPython
4825545
<filename>lib/python/pqos/test/test_capability.py ################################################################################ # BSD LICENSE # # Copyright(c) 2019-2021 Intel Corporation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provide...
StarcoderdataPython
1604378
""" Parses data from MAL,Anilist and themes.moe """ from .animelist import ANIMELISTSITES ,AniList, MyAnimeList from .animethemes import fetch_animethemes from .dldata import get_download_data from .parser import get_animethemes
StarcoderdataPython
1623070
<gh_stars>1-10 #------------------------------------------------------------------------------ # Copyright (c) 2020, 2022, Oracle and/or its affiliates. # # This software is dual-licensed to you under the Universal Permissive License # (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl and Apache License # 2.0 a...
StarcoderdataPython
1719844
import sure # noqa # pylint: disable=unused-import import xmltodict import moto.server as server def test_cloudfront_list(): backend = server.create_backend_app("cloudfront") test_client = backend.test_client() res = test_client.get("/2020-05-31/distribution") data = xmltodict.parse(res.data, dict_...
StarcoderdataPython
43951
# -*- coding: utf-8 -*- from django.db.utils import ProgrammingError try: from edw_fluent.signals.handlers import ( page_layout, template, entity, data_mart, term, simple_page, hot_tag ) except (AttributeError, ProgrammingError) as e: # initial migrat...
StarcoderdataPython
3215697
<reponame>vishalbelsare/PyBNesian<gh_stars>1-10 import pytest import pybnesian as pbn from pybnesian import FactorType, Factor def test_factor_type(): lg1 = pbn.LinearGaussianCPD("a", []) lg2 = pbn.LinearGaussianCPD("b", ["a"]) lg3 = pbn.LinearGaussianCPD("c", ["b", "a"]) assert lg1.type() == pbn.Line...
StarcoderdataPython
143246
<reponame>al7e/answer-retrieval # Copyright 2016 IBM 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 requir...
StarcoderdataPython
1760919
<reponame>molecules/bio # # Sanity check to verify that the alignments work # import difflib import os import random import subprocess import sys from subprocess import PIPE join = os.path.join # The path to the current file. CURR_DIR = os.path.abspath(os.path.dirname(__file__)) # The default data directory. DATA_DI...
StarcoderdataPython
1636187
import os.path checkDirs = ['words/', 'words/a01/a01-000u/'] checkFiles = ['words.txt', 'test.png', 'words/a01/a01-000u/a01-000u-00-00.png'] for f in checkDirs: if os.path.isdir(f): print('[OK]', f) else: print('[ERR]', f) for f in checkFiles: if os.path.isfile(f): print('[OK]', f) else: prin...
StarcoderdataPython
3248494
<gh_stars>10-100 from django import template from ..models import Post register = template.Library() def latest_blog_posts(context, num): """ Displays the most recent blog posts. It takes an argument, num and displays so many posts depending on the value. """ latest_blog_posts = Post.objects.all...
StarcoderdataPython
138693
#!/usr/bin/env python3 """This plugin is used to check that db_write calls are working correctly. """ from lightning import Plugin, RpcError import sqlite3 plugin = Plugin() plugin.sqlite_pre_init_cmds = [] plugin.initted = False @plugin.init() def init(configuration, options, plugin): if not plugin.get_option('...
StarcoderdataPython
166348
<reponame>christianvadillo/fakenewsdetection<filename>src/data/google_facts_web_scraping.py<gh_stars>1-10 import pandas as pd import numpy as np import trafilatura import time import random from tqdm import tqdm from pathlib import Path def get_full_text_col(df: pd.DataFrame) -> None: """ A method that will ...
StarcoderdataPython
55657
import csv class Store: __INVENTORY_FILE = "products.csv" def __init__(self, name, taxRate): self.__Inventory = self.auditInventory() self.__name = name self.__taxRate = taxRate def getName(self): return self.__name def getTaxRate(self): re...
StarcoderdataPython
1787023
#!/usr/bin/python3 import collections import sys if __name__ == "__main__": seen = set() names = collections.defaultdict(int) for line in sys.stdin: line = line[:-1] line = line.split("<")[0] line = line.split("#")[0] try: addr_str, data_str, ins_str = line.s...
StarcoderdataPython
3395009
<gh_stars>0 # Copyright (c) 2019 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 requir...
StarcoderdataPython
1624745
<gh_stars>0 ## buildMission20NC.py - Build Mission 20 Cleaned netCDF # Import statements import numpy as np import sys import datetime import logging # Import DUNEX Tools sys.path.append('..') from tools import buildBasicMissionNC from tools import cleanDUNEXMissions from tools import missionView from tools import mak...
StarcoderdataPython
3214851
<gh_stars>0 import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import interpolate import time start_time = time.time() data_matrix = np.array(pd.read_csv('SUSY.csv')) X = data_matrix[:,1:] Y = data_matrix[:,0] Y[Y==0.0] = -1.0 nrows, ncols = X.shape[0], X.shape[1] training_percent = ...
StarcoderdataPython
97634
<gh_stars>10-100 # Generated by Django 3.1.2 on 2021-01-13 17:03 from django.db import migrations SQL_STATEMENT = """ INSERT INTO product_product_companies(product_id, company_id) SELECT product_product.id AS product_id, product_product.company_id AS company_id FROM product_product WHERE product_product.compan...
StarcoderdataPython
1777035
<filename>omnia_timeseries_sdk/timeseries.py<gh_stars>1-10 """ Timeseries API """ import datetime from typing import List from .resources import DataPoint, DataPoints, TimeSeries, TimeSeriesList from ._utils import to_omnia_datetime_string class TimeSeriesAPI(object): """ Timeseries API client Parameters...
StarcoderdataPython
155325
<reponame>iljah/PyBitmessage<filename>src/tests/common.py<gh_stars>0 import os import sys import time import unittest _files = ( 'keys.dat', 'debug.log', 'messages.dat', 'knownnodes.dat', '.api_started', 'unittest.lock' ) def cleanup(home=None, files=_files): """Cleanup application files""" if not h...
StarcoderdataPython
113045
<reponame>K9Kraken/EZpanda from panda3d.core import WindowProperties, ClockObject class Window: __slots__=( 'panda_winprops', 'get_display_modes', '_aspect2D_edges', '_show_fps' ) def __init__(self): self.panda_winprops = WindowProperties() self.get_d...
StarcoderdataPython
152322
# -*- coding: utf-8 -*- # 欢迎关注微信公众号“码上”,了解更多教程信息 # website: https://www.05dt.com/ # github: https://github.com/05dt/scrapy import scrapy from ..items import BookItem class BooksSpider(scrapy.Spider): # 每一个爬虫的唯一标识 name = "books" # 定义爬虫爬取的起始点,起始点可以是多个,这里只有一个 start_urls = ['http://books.toscrape.com/']...
StarcoderdataPython
1695656
<reponame>closest-git/DeepFormer import math import torch import time import multiprocessing from .kfac_preconditioner import * class CG_KFAC(KFAC): def __init__(self, model, lr=0.1, factor_decay=0.95, damping=0.001, kl_clip=0.001...
StarcoderdataPython
3262651
from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import os import pandas as pd def printOpen(f_out, data = None): #open file, if data is given first write data then open if data: f = open(f_out, 'w') f.write(str(data)) f.close() try: os.startfile(...
StarcoderdataPython
116433
"""Tests related to the @defended decorator.""" from generics import defended defended(None)
StarcoderdataPython
1777177
import abc import collections import itertools from decimal import Decimal from core.calculators.utils import round_float from core.calculators.value import Value class OrderCalculatorMixin: class Item: def __init__(self, price, count, vat, amount=1, seller=None): self.price = price ...
StarcoderdataPython
1668439
#!/usr/bin/env python # coding: utf-8 import astropy_stark.myfake as mf import matplotlib.pylab as plt import numpy as np output_directory = 'fit_synthetic_lightcurves' ''' mf.myfake arguments are wavelengths: enter the wavelengths (-1 indicates an emission line light curve modelled with a top-hat response), snr:...
StarcoderdataPython
3288634
''' # Model admin <= https://docs.djangoproject.com/es/1.10/_modules/django/contrib/admin/options/#ModelAdmin In the after link, see you all configuration and options about model admin. Is very important understand the getters: + e.g.: get_form(self, request, obj=None,**kwards): - Th...
StarcoderdataPython
4803107
from keras.applications import VGG16 conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150, 150, 3)) conv_base.summary() conv_base.trainable = False
StarcoderdataPython
4800817
import numpy as np import pandas as pd import itertools import datetime as dt import pytest from tyme.utils import GroupedTimeSeries from tyme.group_forecasters.optimized_hyperparameters import ( RobustExponentialSmoothingGroupRegressor, ExponentialSmoothingGroupRegressor, ) @pytest.fixture() def input_df():...
StarcoderdataPython
3315156
#!/usr/bin/env python3 from espnet2.tasks.kws import KWSTask def get_parser(): parser = KWSTask.get_parser() return parser def main(cmd=None): r"""KWS training. Example: % python kws_train.py kws --print_config --optim adadelta \ > conf/train_kws.yaml % python kws_t...
StarcoderdataPython
37870
import unittest class TestHelloWorld(unittest.TestCase): # Import and validate HW1 def test_HW1(self): import HelloWorld.HW1 global R1 R1 = HelloWorld.HW1.result self.assertTrue(R1.val().isValid()) # Import and validate HW2 def test_HW2(self): import HelloWorld...
StarcoderdataPython
3353334
""" General utility definitions. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys from Bio.Data import CodonTable from Bio.Data.IUPACData import (protein_letters_1to3, protein_letters_1to3_extended) from Bio.SeqUtils import seq3 PY2 = sys.version_info[0] =...
StarcoderdataPython
4820150
<reponame>MattVUIIS/SMDA #!/usr/bin/env python from __future__ import division, print_function from PIL import Image, ImageDraw, ImageFont import os import sys glyph_dir = 'smda/lucky/glyphs/XXX/exvivo-1' try: os.makedirs(glyph_dir) except OSError: pass slices = 1 min_slice = 53 max_slice = 53 min_row = 1 max_row =...
StarcoderdataPython
3366625
from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path("cshs/", views.base_club, name="cshs"), ] urlpatterns += staticfiles_urlpatterns()
StarcoderdataPython
1660683
<reponame>yarons/readthedocs.org<gh_stars>1000+ from rest_framework.routers import APIRootView, DefaultRouter from rest_framework_extensions.routers import NestedRouterMixin class DocsAPIRootView(APIRootView): # Overridden only to add documentation for BrowsableAPIRenderer. # noqa """ Each request r...
StarcoderdataPython
3385872
<reponame>Jyrijoul/arduino-adc-tester<gh_stars>0 import serial from serial.serialutil import SerialException, SerialTimeoutException import serial.tools.list_ports from input_device import InputDeviceInterface class SerialDevice(InputDeviceInterface): timeout = 0 serial_port = "" baud_rate = 115200 ve...
StarcoderdataPython
4817610
<gh_stars>0 import yaml import six import time from google.cloud import translate_v2 as translate # from google.cloud import translate def read_file(src_file): with open(src_file) as file: return yaml.load(file, Loader=yaml.FullLoader) def write_file(dst_file, data): with open(dst_f...
StarcoderdataPython