id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3279975
# -*- coding: utf-8 -*- import csv import os import platform import codecs import re import sys from datetime import datetime import pytest import numpy as np from pandas._libs.lib import Timestamp import pandas as pd import pandas.util.testing as tm from pandas import DataFrame, Series, Index, MultiIndex from pand...
StarcoderdataPython
1717412
""" After running 2021-nyc-parse.py, run this file to upload and/or modify the data as needed """ import json import os import requests UPLOAD_CACHE_FILENAME ='cache/uploads.json' API_KEY = os.environ['RCVIS_API_KEY'] def getUploadsData(): if not os.path.exists(UPLOAD_CACHE_FILENAME): return {} with ...
StarcoderdataPython
1767715
# Copyright 2014 <NAME> <<EMAIL>> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the...
StarcoderdataPython
1765790
# Copyright (c) 2020-2021 CRS4 # # 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, modify, merge, publish, distribut...
StarcoderdataPython
3344993
# Text formatting class C: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def _text_wrapper(start, end=C.ENDC): return '{}{{}}{}'.format(start, end).format red = _text_wra...
StarcoderdataPython
123400
<gh_stars>1-10 #!/usr/bin/env python import sys import collections import utils try: import argparse as ap import bz2 except ImportError: sys.stderr.write( "argparse not found" ) sys.exit(-1) def read_params( args ): p = ap.ArgumentParser(description='Convert txt files to libsvm\n') p.add_a...
StarcoderdataPython
64892
<reponame>KIT-CMS/CROWN<filename>code_generation/code_generation.py<gh_stars>1-10 from __future__ import annotations # needed for type annotations in > python 3.7 import logging from typing import Any, Dict, List, Set from git import Repo from code_generation.producer import SafeDict log = logging.getLogger(__name...
StarcoderdataPython
3217010
<filename>tests/players/test_player.py """ Tests for the Player class. """ from hypothesis import given from hypothesis.strategies import lists, text from matching import Player @given(name=text()) def test_init(name): """ Make an instance of Player and check their attributes are correct. """ player = Play...
StarcoderdataPython
158085
# From http://code.activestate.com/recipes/498245/ import collections import functools from itertools import ifilterfalse from heapq import nsmallest from operator import itemgetter class Counter(dict): 'Mapping where default values are zero' def __missing__(self, key): return 0 def lru_cache(maxsi...
StarcoderdataPython
1791038
from unittest import TestCase from src.nexus_api.email_alerts import EmailAlerts from dotenv import load_dotenv, find_dotenv from pathlib import Path import os # Set test options and .env file BASE_DIR = Path('..') dotenv_path = BASE_DIR / 'secrets.env' load_dotenv(find_dotenv(dotenv_path)) class TestEmailAlerts(Te...
StarcoderdataPython
55304
<reponame>alnsokolov/soc_recon import vk_api import os import cache def auth(check_saved=1): def tfa_handler(): code = input("[!] 2FA detected! Please enter code you've just received: ") return code, 0 def inner_auth(i_login=None, i_password=None, tfa=tfa_handler): session = vk_api.Vk...
StarcoderdataPython
3086
""" 启动此 spider 前需要手动启动 Chrome,cmd 命令如下: cd 进入 Chrome 可执行文件 所在的目录 执行:chrome.exe --remote-debugging-port=9222 此时在浏览器窗口地址栏访问:http://127.0.0.1:9222/json,如果页面出现 json 数据,则表明手动启动成功 启动此 spider 后,注意与命令行交互! 在 settings 当中要做的: # ROBOTSTXT_OBEY = False # 如果不关闭,parse 方法无法执行 # COOKIES_ENABLED = True # 以便 Request 值在传递时自动传递 cookies...
StarcoderdataPython
39759
<reponame>pombredanne/django-fluent-contents<gh_stars>0 # following PEP 386 __version__ = "1.0a1"
StarcoderdataPython
139151
import re emails = ''' <EMAIL> <EMAIL> <EMAIL> ''' pattern = re.compile(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+') matches = pattern.finditer(emails) for match in matches: print(match)
StarcoderdataPython
3303429
# -*- coding=utf-8 -*- " The Compiler and Judger of rlj " import os import psutil import subprocess import time from .languages import getLanguage class JudgeStatus(object): ''' Info of a judge. ''' def __init__(self, status, time_used=None, memory_used=None, returncode=None): self.s...
StarcoderdataPython
3279891
<filename>Week 4/divideandconquer-starter-files/inversions/invs.py<gh_stars>0 # Uses python3 import sys number_of_inversions = 0 def merge_sort(li): if len(li) < 2: return li m = len(li) / 2 return merge(merge_sort(li[:m]), merge_sort(li[m:])) def merge(l, r): global number_of_inversions resu...
StarcoderdataPython
1723044
<reponame>nwillemse/nctrader from __future__ import print_function from ..compat import queue from ..event import EventType from datetime import datetime class Backtest(object): """ Enscapsulates the settings and components for carrying out an event-driven backtest. """ def __init__( sel...
StarcoderdataPython
37375
''' Created on: see version log. @author: rigonz coding: utf-8 IMPORTANT: requires py3.6 (rasterio) Script that: 1) reads a series of raster files, 2) runs some checks, 3) makes charts showing the results. The input data corresponds to a region of the world (ESP) and represents the population density (pop/km2). Each...
StarcoderdataPython
39008
<gh_stars>0 #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- from subprocess import Popen, PIPE from contextlib import contextmanager @contextmanager def ScopedPopen(*args, **kwargs): proc = Popen(*args, **kwargs) try: yield proc finally: try: proc.kill() except Except...
StarcoderdataPython
3247166
<gh_stars>1-10 ''' # -*- coding: UTF-8 -*- # Interstitial Error Detector # Version 0.2, 2013-08-28 # Copyright (c) 2013 AudioVisual Preservation Solutions # All rights reserved. # Released under the Apache license, v. 2.0 # Created on Aug 6, 2014 # @author: <NAME> <<EMAIL>> ''' from PySide.QtCore import * ...
StarcoderdataPython
1791997
<gh_stars>0 #!/usr/bin/env python import plugins, os, string, shutil, sys, logging, glob from ConfigParser import ConfigParser, NoOptionError from copy import copy from ordereddict import OrderedDict plugins.addCategory("bug", "known bugs", "had known bugs") plugins.addCategory("badPredict", "internal errors", "had i...
StarcoderdataPython
3315381
from rest_framework.permissions import BasePermission from rest_framework.compat import is_authenticated class UserSiteIsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return request.user_site and is_authenticated(req...
StarcoderdataPython
3357932
# -*- coding: utf-8 -*- import os import sys import re import codecs leftBracket = 1 # { rightBracket = 2 # } blankLine = 3 # 空行 otherLine = 4 # それ以外 # 行のタイプを解析する def parseLine(line): match = re.search('^\s*{\s*$', line) if match: return leftBracket match = re.search('^\s*}\s*(;\s*)?$', line) if match...
StarcoderdataPython
1605121
import os import pdb import sys import tempfile sys.path.append("/opt/tosca") from translator.toscalib.tosca_template import ToscaTemplate from core.models import Slice,User,Site,Network,NetworkSlice,SliceRole,SlicePrivilege,Service,Image,Flavor,Node from xosresource import XOSResource class XOSSlice(XOSResource): ...
StarcoderdataPython
3305257
<reponame>n3011/deepchem<gh_stars>1-10 """ Tests for Pose Scoring """ from __future__ import division from __future__ import unicode_literals __author__ = "<NAME>" __copyright__ = "Copyright 2016, Stanford University" __license__ = "MIT" import sys import logging import unittest import tempfile import os import shuti...
StarcoderdataPython
130874
<gh_stars>0 import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme GPIO.setup(18,GPIO.OUT) GPIO.setup(23,GPIO.OUT) # Initial state for LEDs: print("Testing RF out, Press CTRL+C to exit") try: print('try') p = GPIO.PWM(18,100) p.start(0) p1 = GPIO.PWM (23,100...
StarcoderdataPython
78155
<gh_stars>0 """Definition of Data classes.""" import logging from typing import List, NamedTuple, Optional, Type, Set import email from pydantic import BaseModel, Extra from circuit_maintenance_parser.constants import EMAIL_HEADER_SUBJECT, EMAIL_HEADER_DATE logger = logging.getLogger(__name__) class DataPart(Named...
StarcoderdataPython
1716874
<reponame>wgifford/ray import logging logger = logging.getLogger(__name__) MIN_PYARROW_VERSION = (4, 0, 1) _VERSION_VALIDATED = False def _check_pyarrow_version(): global _VERSION_VALIDATED if not _VERSION_VALIDATED: import pkg_resources try: version_info = pkg_resources.require(...
StarcoderdataPython
3221988
<filename>necrobot/race/racer.py import discord from necrobot.race.racerstatus import RacerStatus from necrobot.user import userlib from necrobot.user.necrouser import NecroUser from necrobot.util import racetime from necrobot.util.necrodancer import level FIELD_UNKNOWN = int(-1) class Racer(object): def __init...
StarcoderdataPython
3241250
from .base import Question from googleform import utils class ShortTextQuestion(Question): def __init__(self, question_tree): super().__init__(question_tree) self._answer = None @staticmethod def is_this_question(tree): return utils.has_freebird_div(tree, "TextShortText") de...
StarcoderdataPython
3278696
<gh_stars>1-10 import pytest from simplejson import loads from wallet_lib.adapters import WalletAdapterBase from wallet_lib.wallet_exceptions import WalletException from bitcoinrpc.authproxy import JSONRPCException class WalletTestBase: def run_positive_case_json(self, Mock, command_run, *args): expecte...
StarcoderdataPython
3263331
import sys from operator import itemgetter from Model import Model import random import math import pandas as pd def find_initial_score(n): i = 0 sums = 0 scores = [] scoring_sum = 0 if n > 5: for k in range(2): remain = n - k sums = remain + sums else: ...
StarcoderdataPython
1638109
# python3 # Copyright 2019 DeepMind Technologies Limited # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
StarcoderdataPython
142670
#!/usr/bin/env python # # test_ldp_isis_topo1.py # Part of NetDEF Topology Tests # # Copyright (c) 2020 by <NAME> # # Permission to use, copy, modify, and/or distribute this software # for any purpose with or without fee is hereby granted, provided # that the above copyright notice and this permission notice appear # ...
StarcoderdataPython
1669596
num1 = input('Informe o 1º número inteiro ') num2 = input('Informe o 2º número inteiro ') num3 = input('Informe um número real ') op1 = int(num1) * 2 + int(num2) / 2 op2 = int(num1) * 3 + float(num3) op3 = float(num3) ** 3 print(f'Produdo do dobro do 1º com metade do 2º é {op1}') print(f'A soma do triplo do 1º com...
StarcoderdataPython
1678282
# Generated by Django 3.1.4 on 2021-02-23 13:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('function', '0014_delete_curriculum'), ] operations = [ migrations.CreateModel( name='Curriculum', fields=[ ...
StarcoderdataPython
68528
import os class RenderHTML: def __init__(self, file): self._file = file if not os.path.exists(self._file): raise FileNotFoundError(f"No such HTML file: {self._file}") with open(file, 'r') as f: self._html = f.read() def __repr__(self): return "<%s...
StarcoderdataPython
1778815
# pylint: disable-all # flake8: noqa from .base import Base from .device import Device from .group import Group from .user import User from .client import Client from .asset import Asset from .media_convert_queue import MediaConvertQueue
StarcoderdataPython
1617300
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** # Export this package's modules as members: from .cluster import * from .event_subscription import * from .get_cluster import * from .g...
StarcoderdataPython
3371286
<gh_stars>1-10 from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from poll import views urlpatterns = [ path('', views.polls), path('<int:poll_pk>/vote/', views.vote), path('<int:poll_pk>/result/', views.result), ] urlpatterns = format_suffix_patt...
StarcoderdataPython
3292286
"""empty message Revision ID: 7c86cc916b5c Revises: 52553d4d6309 Create Date: 2019-12-17 15:27:22.009335 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '52553d4d6309' branch_labels = None depends_on = None def upgrade(): # ### com...
StarcoderdataPython
43647
<reponame>pythonyhd/django_blog # -*- coding: utf-8 -*- import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps')) # SECURITY WARNING: keep the secret key used in production sec...
StarcoderdataPython
3347191
# coding: utf-8 # In[1]: #!/usr/bin/env python ################################################################ # Copyright (C) 2015 OpenEye Scientific Software, Inc. ################################################################ from __future__ import print_function import os, sys import pandas as pd ...
StarcoderdataPython
1782917
from htdfsdk.ens import ENS ns = ENS()
StarcoderdataPython
3288115
from coldtype.test import * from coldtype.midi.controllers import LaunchControlXL @test((1000, 300)) def test_system_font(r): return DATText("Hello, world!", Style("Times", 100, load_font=0, fill=0), r.offset(100, 100)) @test((1000, 300), rstate=1) def test_return_string(r, rs): ri = r.inset(30) sx, sy = ...
StarcoderdataPython
3373908
<reponame>phyz777/muonic_webapp_BUW<filename>controller/serializers.py<gh_stars>0 from rest_framework import serializers from django.contrib.auth.models import User from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' read_o...
StarcoderdataPython
97897
# Copyright (C) 2022 viraelin # License: MIT from PyQt6.QtCore import * from PyQt6.QtWidgets import * from PyQt6.QtGui import * # todo: bug when showing again if color is black/white/gray class ColorPicker(QWidget): color_changed = pyqtSignal(str) def __init__(self, parent=None, color=QColor(Qt.GlobalColor....
StarcoderdataPython
177854
from project_RL.linear_monte_carlo.monte_carlo_agent import LinearMonteCarlo from project_RL.parsing import linear_parse_observation_to_state from project_RL.play import play from gym_minigrid.wrappers import * from time import time def train(env, hyperparameters): """ Train a sarsa lambda agent in the re...
StarcoderdataPython
3364977
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # U...
StarcoderdataPython
156047
#!/usr/bin/env python import rospy import numpy as np from cv_bridge import CvBridge, CvBridgeError import cv2 from sensor_msgs.msg import Image from sensor_msgs.msg import CompressedImage # Initialize the node with rospy rospy.init_node('virtual_mirror_node') bridge = CvBridge() # Define Timer callback def callba...
StarcoderdataPython
62936
from urllib.request import urlopen from bs4 import BeautifulSoup from youtube_dl import YoutubeDL import pyexcel # Part 1 url = "https://www.apple.com/itunes/charts/songs/" html_content = urlopen(url).read().decode('utf-8') soup = BeautifulSoup(html_content,"html.parser") section = soup.find("section","section chart-g...
StarcoderdataPython
3257659
<gh_stars>1-10 from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible import uuid from django.db import models from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField USER_TYPES = ( ('Neu','Neu'), ('Athlet','Athlet'), ('Elte...
StarcoderdataPython
3263042
<reponame>knowsuchagency/composer import os from operator import methodcaller import pytest from aws_cdk import ( core as cdk, aws_lambda_python, aws_stepfunctions as sfn, aws_lambda, aws_stepfunctions_tasks as sfn_tasks, ) from aws_cdk.cx_api import CloudAssembly from app import Stacks from examp...
StarcoderdataPython
49663
<reponame>emarinizquierdo/xentinels<filename>rest_gae/rest_gae.py """ Wraps NDB models and provided REST APIs (GET/POST/PUT/DELETE) arounds them. Fully supports permissions. Some code is taken from: https://github.com/abahgat/webapp2-user-accounts """ import importlib import json import re from urlparse import urlpa...
StarcoderdataPython
3284879
import os import shutil import subprocess import sys import time import pytest import fsspec from fsspec.implementations.cached import CachingFileSystem @pytest.fixture() def m(): """ Fixture providing a memory filesystem. """ m = fsspec.filesystem("memory") m.store.clear() try: yiel...
StarcoderdataPython
139543
import torch as to import torch.nn as nn from abc import ABC, abstractmethod from typing import Sequence, Callable, Tuple import pyrado from pyrado.policies.base_recurrent import RecurrentPolicy from pyrado.policies.fnn import FNN from pyrado.policies.initialization import init_param from pyrado.policies.rnn import de...
StarcoderdataPython
23525
""" This module comes with functions to decide which poker player out of all players has the best cards. """ import itertools # full_list in [('A','A'),('B','B')...,('F','F')] def results(full_list, public_card): """ The results function takes a list of player cards and the community cards (in the middle of...
StarcoderdataPython
4822169
<reponame>jordanm/scheme from scheme.exceptions import * from scheme.field import * from scheme.interpolation import interpolate_parameters from scheme.util import string __all__ = ('Map',) class Map(Field): """A field for homogeneous mappings of key/value pairs. A map can contain any number of key/value pai...
StarcoderdataPython
1707791
import json import os _THIS_DIR = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(_THIS_DIR, "chars_to_jyutping.json"), encoding="utf8") as f: CHARS_TO_JYUTPING = json.load(f) with open(os.path.join(_THIS_DIR, "lettered.json"), encoding="utf8") as f: LETTERED = json.load(f)
StarcoderdataPython
1792202
from ceo.tools import ascupy from ceo.pyramid import Pyramid import numpy as np import cupy as cp from scipy.ndimage import center_of_mass class PyramidWFS(Pyramid): def __init__(self, N_SIDE_LENSLET, N_PX_LENSLET, modulation=0.0, N_GS=1, throughput=1.0, separation=None): Pyramid.__init__(self) sel...
StarcoderdataPython
1600514
import os from PIL import Image class Microscope(object): def __init__(self, group, init_pos_idx, left_up_point, transform=None, unit_distance=0.5): self.group = group self.pos_init = init_pos_idx if init_pos_idx < self.pos_min or init_pos_idx > self.pos_max: raise ValueError(...
StarcoderdataPython
4820356
<filename>apduboy/bitcoin.py from dataclasses import dataclass from enum import IntEnum from typing import NamedTuple, Optional from construct import ( Byte, Bytes, GreedyBytes, Int8ub, Int32ub, PascalString, Prefixed, PrefixedArray, Struct, ) from .lib.bip32 import Derivation from...
StarcoderdataPython
102238
############################################################################## # Copyright (c) 2016 <NAME> and others # <EMAIL> # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is availab...
StarcoderdataPython
166441
import locale import gettext DEBUG = True MAILSENDER="<EMAIL>" MAILRCPTTO="<EMAIL>" CURLOCALE = 'en_US' #current_locale = 'lt_LT' LANGUAGES={'ru': 'ru_RU', 'en': 'en_US', 'lt': 'lt_LT', 'ua': 'ua_UA', 'it': 'it_IT', 'lv': 'lv_LV', 'by': 'by_BY', 'pl': 'pl_PL', 'de': 'de_DE'} LANGUAGESNR={'lt': 1, 'ru'...
StarcoderdataPython
3259612
## THUCNews 原始数据集 import sys sys.path.append("./") sys.path.append("./bert_seq2seq/") import torch from tqdm import tqdm import torch.nn as nn from torch.optim import Adam import numpy as np import os import json import time import glob import bert_seq2seq from torch.utils.data import Dataset, DataLoa...
StarcoderdataPython
1693386
# Copyright (c) 2017 Intel Corporation. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. from chroma_core.services import log_register from chroma_core.models import SyslogEvent, ClientConnectEvent, ManagedHost from django.db import transaction...
StarcoderdataPython
1646874
<gh_stars>1-10 import logging def stream_logger(logger_name): logger = logging.getLogger(logger_name) logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setLevel(logging.INFO) logger.addHandler(handler) return logger
StarcoderdataPython
193775
<reponame>tifat58/lsv-c4-django-webexperiment<filename>StatisticsPreview/views.py from django.shortcuts import render, get_object_or_404, redirect from django.views.generic import View from django.http import HttpResponseRedirect from django.http import HttpResponse, JsonResponse from django.core.urlresolvers import re...
StarcoderdataPython
1760660
"""Real-time monitor of light level""" import math import os import sys import time import prometheus_client as prom import SI1132 import BME280 I2C_DEVICE_FILE = "/dev/i2c-2" def main(): verbose = len(sys.argv) > 1 si1132 = SI1132.SI1132(I2C_DEVICE_FILE) while True: light_visible_lux = si113...
StarcoderdataPython
1729688
<reponame>tecdan/Pretrained_Models_NMT import sys sys.path.append('/home/dhe/hiwi/Exercises/Pretrained_Models_NMT/') import onmt.Markdown import argparse parser = argparse.ArgumentParser(description='bert_dict.py') onmt.Markdown.add_md_help_argument(parser) parser.add_argument('-model_type', default="bert", ...
StarcoderdataPython
46850
__author__ = "songjiangshan" __copyright__ = "Copyright (C) 2021 songjiangshan \n All Rights Reserved." __license__ = "" __version__ = "1.0" DEVICE_TYPE_TAG=0 #OLD3 DEVICE_TYPE_ANCHOR=1 #OLD2 DEVICE_TYPE_ANCHORZ=2 #OLD1 def client_id_remove_group(client_id): return str(client_id_get_type(client_id)) + '-' + str(...
StarcoderdataPython
3373135
<filename>Term 2/16/3-tuple_vs_list.py a_list = [1, 2, 3, 4, 5, 6] a_tuple = (1, 2, 3, 4, 5, 6) a_list[4] = 97 print(a_list) # a_tuple[4] = 97 error b = [1] print(type(b)) c = ('1',) print(type(c))
StarcoderdataPython
1631616
#!/usr/bin/env python import sys import zipfile date_options = [ (1990, 4, 19, 11, 0, 0), (1984, 2, 5, 10, 0, 0), ] zip = zipfile.ZipFile(sys.argv[1], 'w') zip.writestr(zipfile.ZipInfo('file.txt', date_options[int(sys.argv[2])]), 'data') zip.close()
StarcoderdataPython
1685503
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from demo.polygon import Point class PointTest(unittest.TestCase): def setUp(self): self.p1 = Point(0, 0) self.p2 = Point(3, 4) def tearDown(self): pass def testSub(self): p = self.p2 - self.p1 self.a...
StarcoderdataPython
3223398
from .log import log class C_new: def __new__(cls, *args, **kwargs): log("__new__", args, kwargs) return object.__new__(cls) class C_init: def __init__(self, *args): log("__init__", args) class C_reduce: def __reduce__(self): log("__reduce__") return self.__cla...
StarcoderdataPython
1660559
<reponame>Takato0120/social_ecological_system<gh_stars>1-10 # -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-16 07:16 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0013_auto_20160202_0144'), ]...
StarcoderdataPython
4802660
import json import logging import struct import os from steam import SteamClient from steam.enums import EResult from steam.enums.emsg import EMsg from .result import EPurchaseResultDetail class SocketHandler(object): def __init__(self, ws, serv_name=None): self._ws = ws self._client = None ...
StarcoderdataPython
141168
<reponame>li-ziang/cogdl<filename>cogdl/data/dataloader.py from abc import ABCMeta import torch.utils.data from torch.utils.data.dataloader import default_collate from cogdl.data import Batch, Graph try: from typing import GenericMeta # python 3.6 except ImportError: # in 3.7, genericmeta doesn't exist but w...
StarcoderdataPython
4837144
import numpy as np import sys import argparse from maddux.predefined_environments import environments def main(): """Run CLI to get animation arguments""" parser = argparse.ArgumentParser(description="Animate a given saved path") parser.add_argument('-i', '--input', type=str, required=True, ...
StarcoderdataPython
106670
<reponame>bcsr0009/pdtf # coding: utf-8 import requests import json import paramiko import time import logging import os import difflib import pdb from coreutils.logdecorator import logwrap @logwrap def execute_command(ssh_connection_handler, cmd): ''' This method provides execute_command option on device ...
StarcoderdataPython
1700519
"""Run a DAG in memory.""" import itertools import os from typing import Any, Dict, Iterable, Mapping, Union from dagger.dag import DAG, Node, validate_parameters from dagger.input import FromNodeOutput, FromParam from dagger.runtime.local.output import load from dagger.runtime.local.task import invoke_task from dagge...
StarcoderdataPython
182277
import gym from envs.tape_env_wrapper import TapeEnvWrapper from envs.discrete_env_wrapper import DiscreteEnvWrapper from envs.blackjack_env_wrapper import BlackjackEnvWrapper from envs.guess_env_wrapper import GuessEnvWrapper from envs.continuous_state_env_wrapper import ContinuousStateEnvWrapper from envs.pendulum_en...
StarcoderdataPython
1724378
import csv import os import rdflib YAML_NAMESPACE_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'namespaces.yaml') FOAF = rdflib.Namespace('http://xmlns.com/foaf/0.1/') LODE = rdflib.Namespace('http://linkedevents.org/ontology/') IDS = rdflib.Namespace('http://data.socialhistory.org/resource/ids/')...
StarcoderdataPython
1745375
<filename>Collections-a-installer/community-general-2.4.0/plugins/modules/vexata_volume.py #!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, <NAME> (<EMAIL>) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, pr...
StarcoderdataPython
1734356
<filename>src/models/cnn_gaze.py import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from math import floor from torch.utils.tensorboard import SummaryWriter from yaml import safe_load import os from src.data.data_utils import ImbalancedDatasetSampler from src.data.data_loaders import ...
StarcoderdataPython
1717954
<reponame>Code-and-Response/ISAC-SIMO-Repo-2 from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # Image & Image Files path('image', views.images, name="images"), path('image/add', views.addImage, name="images.add"), ...
StarcoderdataPython
1684626
<filename>tasks.py # # This file is part of Gruvi. Gruvi is free software available under the # terms of the MIT license. See the file "LICENSE" that was provided # together with this source file for the licensing terms. # # Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a # complete list. from ...
StarcoderdataPython
3367926
<gh_stars>0 print('{:=^40}'.format(' Loja do Lusca ')) preco = float(input('Preço total das compras: R$')) print(''' -- Formas de Pagamento -- [ 1 ] à vista em dinheiro/cheque [ 2 ] à vista no cartão [ 3 ] 2x no cartão [ 4 ] 3x ou mais no cartão ''') op = int(input(' >> ')) if 1 <= op <= 4: if op == 4: tot...
StarcoderdataPython
3351206
# fourFn.py # # Demonstration of the pyparsing module, implementing a simple 4-function expression parser, # with support for scientific notation, and symbols for e and pi. # Extended to add exponentiation and simple built-in functions. # Extended test cases, simplified pushFirst method. # Removed unnecessary exp...
StarcoderdataPython
1759250
import sys from setuptools import setup from dnsservicecleint.settings import * assert sys.version_info >= MINIMUM_PYTHON_VERSION setup( name="dns-service-cleint", version=VERSION, description="dns-service-cleint", author="Terminal Labs", author_email="<EMAIL>", license="mit", packages=["...
StarcoderdataPython
3244514
from vcx.error import ErrorCode from vcx.common import error_message def test_error(): assert ErrorCode.InvalidJson == 1016 def test_c_error_msg(): assert error_message(0) == 'Success'
StarcoderdataPython
164706
import sublime import sublime_plugin def char_at(view, point): return view.substr(sublime.Region(point, point + 1)) def is_space(view, point): return char_at(view, point).isspace() def is_newline(view, point): return char_at(view, point) == "\n" class CommentFoldCommand(sublime_plugin.TextCommand): ...
StarcoderdataPython
3304294
# -*- coding: utf-8 -*- import os import sys import subprocess adb_path = '' def get_path(): global adb_path try: adb_path = 'adb' subprocess.Popen([adb_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return adb_path except FileNotFoundError: ...
StarcoderdataPython
3342627
<filename>aws-scripts/yolo-inference.py from argparse import Namespace import time from pathlib import Path import cv2 import torch import torch.backends.cudnn as cudnn from numpy import random import numpy as np import base64 from models.experimental import attempt_load from utils.datasets import letterbox from util...
StarcoderdataPython
37847
<filename>helper.py from itertools import repeat from random import randrange def randoms_from(values, length=None): _range = range(length) if length is not None else repeat(0) values_len = len(values) for _ in _range: yield values[randrange(0, values_len)]
StarcoderdataPython
1784706
<filename>tests/test_Task05.py from Graph import Graph from ContextFreeGrammar import ChomskyNormalForm as CNF from pyformlang.cfg import * def test_Asimov(): gr = CNF.from_file("cfg_input.txt") g = Graph() g.from_file("input4.txt") reachable = frozenset(gr.Asimov(g)) reachable_actual = frozenset(g...
StarcoderdataPython
3215792
#!/usr/bin/python3 import requests import sys import urllib.parse class StreamCamel: def __fetch(self, url): max_retry = 3 attempt = 1 while True: try: print("Fetch URL: {}".format(url)) r = requests.get(url = url, timeout=10) brea...
StarcoderdataPython
29427
import random import os import logging import pickle import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn # import faiss ################################################################################ # General-...
StarcoderdataPython
1749425
def get_set_elements(n): elements = set() for _ in range(n): element = input() elements.add(element) return elements def find_intersection_elements(first_set, second_set): return first_set.intersection(second_set) def print_result(intersection_elements): print('\n'.join(intersec...
StarcoderdataPython
149715
import os import io import glob import matplotlib.pyplot as plt import imageio from tensorboard.backend.event_processing.event_accumulator import EventAccumulator SIZE_GUIDANCE = { 'images': 20 } def plot_alignment(log_dir, save_dir): tf_event = glob.glob(os.path.join(log_dir, "events.*"))[0] event_acc...
StarcoderdataPython