id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1680758
<filename>backend/src/contaxy/operations/json_db.py from abc import ABC, abstractmethod from typing import List, Optional from contaxy.schema import JsonDocument class JsonDocumentOperations(ABC): @abstractmethod def create_json_document( self, project_id: str, collection_id: str, ...
StarcoderdataPython
1649619
<reponame>fredmorcos/attic """ Data filter module. """ __docformat__ = "restructuredtext en" ## Copyright (c) 2009 <NAME> ## ## This file is part of npy. ## ## npy 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 Found...
StarcoderdataPython
1674246
<reponame>alanamarzoev/structured-realm # coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lice...
StarcoderdataPython
3216306
""" Caching framework. This package defines set of cache backends that all conform to a simple API. In a nutshell, a cache is a set of values -- which can be any object that may be pickled -- identified by string keys. For the complete API, see the abstract BaseCache class in django.core.cache.backends.base. Client ...
StarcoderdataPython
44010
<gh_stars>0 from Utils.bt_scheme import BacktrackingVCSolver, PartialSolutionWithVisitedControl def solver(C, A, B): class PartialSolution(BacktrackingVCSolver): def __init__(self, ds, SA, SB): self.ds = ds self.n = len(ds) self.SA = SA self.SB = SB def is_solution(self): return self.n == len(C) ...
StarcoderdataPython
1794496
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python 2 - Criado por <NAME> - 12/04/2012 import sys, os from datetime import datetime pasta = 'c:' #print(os.path.isfile('caixa.txt')) def main(): dinheiro(preco()) def preco(): while 1: preco = raw_input('Preço: ') try: preco =...
StarcoderdataPython
130513
<gh_stars>1-10 n = int(input()) chars_of_each_string = [[char for char in input()] for _ in range(n)] chars = [] for characters in chars_of_each_string: chars += list(set(characters)) chars_used_in_all = [] for char in set(chars): if chars.count(char) == n: chars_used_in_all.append(char) ...
StarcoderdataPython
77802
#!/usr/bin/python3 """Analyse metadynamics trajectories from xtb.""" import argparse import numpy as np import matplotlib.pyplot as plt import MDAnalysis as mda import MDAnalysis.analysis.pca as pca from MDAnalysis.lib import distances from scipy.constants import calorie from scipy.constants import kilo from scipy.c...
StarcoderdataPython
3014
##### # # This class is part of the Programming the Internet of Things # project, and is available via the MIT License, which can be # found in the LICENSE file at the top level of this repository. # # Copyright (c) 2020 by <NAME> # import logging import unittest from programmingtheiot.cda.system.SystemMemUtilTask...
StarcoderdataPython
112238
<reponame>mk-fg/nflog-zmq-pcap-pipe #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function def main(): from contextlib import closing import os, errno, logging, metrics, shaper import argparse parser = argparse.ArgumentParser( description='Decompress traffic coming from zmq socket,...
StarcoderdataPython
3355902
"""Test Krylov methods.""" import numpy as np from numpy.testing import (TestCase, assert_array_almost_equal, assert_equal, assert_almost_equal) from scipy.linalg import solve import scipy.sparse as sparse import pyamg from pyamg.util.linalg import norm from pyamg.krylov import bicgstab, cg,...
StarcoderdataPython
1757150
<filename>epytope/test/TestEpitopePrediction.py """ Unittest for PSSM predictors """ __author__ = 'schubert' import unittest # Variants and Generator from epytope.Core import Allele from epytope.Core import Peptide # Predictions from epytope.EpitopePrediction import EpitopePredictorFactory, AExternalEpitopePredicti...
StarcoderdataPython
4827417
"""Create important distributions classes. Especially provide the logic for a hypererlang distributions with data fitting. """ import logging import multiprocessing as mp from itertools import combinations_with_replacement from typing import Any, Dict, Generator, Iterable, List, Optional, Union import matplotlib.pyp...
StarcoderdataPython
1651433
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 14 + 64 + 34 + 44 8208 = 84 + 24 + 04 + 84 9474 = 94 + 44 + 74 + 44 As 1 = 14 is not a sum it is not included. The sum of these numb...
StarcoderdataPython
3269640
# -*- coding: utf-8 -*- #Figure 4.1 x = 25 epsilon = 0.01 numGuesses = 0 low = 0.0 high = max(1.0, x) ans = (high + low)/2.0 while abs(ans**2 - x) >= epsilon: numGuesses += 1 if ans**2 < x: low = ans else: high = ans ans = (high + low)/2.0 print('numGuesses =', numGuesses) print(ans, 'i...
StarcoderdataPython
1630197
<filename>aguamenti/status.py # Import modified 'os' module with LC_LANG set so click doesn't complain from .os_utils import os, REFLOW_BATCHES, sanitize_path, \ get_stdout_from_command from collections import defaultdict import click from .reflow_utils import SAMPLES_CSV, CONFIG_JSON STATE_JSON = 'state.json...
StarcoderdataPython
1744703
<reponame>gw-vis/pcas-controller<gh_stars>0 from . import pcasphy from . import phytron_stepper_motor import sys import time import logging import logging.config import os #BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #print BASE_DIR #logging.config.fileConfig(os.path.join(BASE_DIR, 'utils', 'lo...
StarcoderdataPython
18862
<filename>plugins/modules/oci_sch_service_connector.py #!/usr/bin/python # Copyright (c) 2017, 2020 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl...
StarcoderdataPython
38419
<filename>ccdproc/tests/test_ccdproc_logging.py from astropy.extern import six from astropy.tests.helper import pytest import astropy.units as u from ..ccdproc import create_variance, Keyword @pytest.mark.parametrize('key', [ 'short', 'toolongforfits']) def test_log_...
StarcoderdataPython
1600773
# -*- coding: utf-8 -*- """ Created on Thu Sep 15 16:40:12 2016 @author: mark This file contains methods for calculating kinetics values that don't necessarily require cantera or another outside less known software package. all rates are currently only in kcal/mol (except arrhenius) """ # -*- coding: utf-8 -*- im...
StarcoderdataPython
1663743
<gh_stars>0 # # Copyright 2022 Logical Clocks AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
StarcoderdataPython
1624354
<reponame>chrisxue815/leetcode_python<filename>problems/test_0703.py import heapq import unittest from typing import List import utils # O(log(k)) time. O(k) space. Binary heap. class KthLargest: def __init__(self, k: int, nums: List[int]): k_largest = [] for num in nums[:k]: heapq....
StarcoderdataPython
3375758
<filename>tests/test_collect_newspaper_monolith.py from karelcraft.karelcraft import * def main(): move() move() turn_left() turn_left() turn_left() move() turn_left() move() pick_beeper() turn_left() turn_left() move() move() move() turn_left() turn_lef...
StarcoderdataPython
153255
<reponame>glenlivet/jiagu import jiagu jiagu.load_userdict('dict/user.dict') # load file contract_file = open("contract.txt", "r") contract_contents = contract_file.read() segs = jiagu.seg(contract_contents) ner = jiagu.ner(segs) print(segs) print(ner) content_arr = list(segs) for i in range(len(content_arr)): if...
StarcoderdataPython
3262223
<filename>apps/improc/apps.py from django.apps import AppConfig class ImprocConfig(AppConfig): name = 'improc'
StarcoderdataPython
1719072
#!/usr/bin/python # Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
StarcoderdataPython
3245871
<filename>estimate_center/util.py<gh_stars>1-10 ''' 直接在深度图回归出 input: points: world space points refpoints: reference points (it's the label) ''' import os import numpy as np import sys import struct import h5py import torch from torch.utils.data import Dataset def pixel2world(x, y, z, img_wid...
StarcoderdataPython
1795095
""" google drive """ import httplib2 from apiclient.discovery import build from oauth2client.client import OAuth2WebServerFlow, OAuth2Credentials from apiclient import errors def get_credentials(credentials_json): """ Build credentials object from json """ return OAuth2Credentials.from_json(credential...
StarcoderdataPython
1655539
#!/usr/bin/micropython from popen import popen from count_forwards import count import sys import ure date_pattern = ure.compile('exp=([0-9][0-9][0-9][0-9])-([0-1]?[0-9])-([0-9][0-9])') import time today = time.localtime()[:3] idx=count() for i in reversed(range(idx)): r = popen('uci get firewall.@redirect[%i]...
StarcoderdataPython
184088
import yaml class Config: def __init__(self, config_path): with open(config_path, "r") as stream: try: parsed_conf = yaml.safe_load(stream) self.blockchains = parsed_conf['blockchains'] except yaml.YAMLError as exc: print(exc)
StarcoderdataPython
148194
<filename>Questoes/Sequencia IJ 4.py for i in range(0,21,2): if(i==0): i=i elif(i==10 or i==20): i=int(i/10) else: i/=10 for k in range(1,4): print("I={} J={}".format(i, k+i))
StarcoderdataPython
1726934
<reponame>yamedvedya/camera_viewer # ---------------------------------------------------------------------- # Author: <EMAIL> # ---------------------------------------------------------------------- """ """ from PyQt5 import QtWidgets, QtCore from petra_camera.gui.Marker_ui import Ui_Marker # ----------------...
StarcoderdataPython
3320386
import re from abc import ABCMeta from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta from sqlalchemy.orm import scoped_session, sessionmaker class DeclarativeABCMeta(DeclarativeMeta, ABCMeta): """ Empty class to create a mixin between DeclarativeMeta...
StarcoderdataPython
118658
<filename>top/api/rest/ShopcatsListGetRequest.py ''' Created by auto_sdk on 2016.03.19 ''' from top.api.base import RestApi class ShopcatsListGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.fields = None def getapiname(self): return 'taobao.s...
StarcoderdataPython
107789
<gh_stars>0 def monkey_trouble(a_smile, b_smile): return (a_smile and b_smile) or (not a_smile and not b_smile)
StarcoderdataPython
1665210
# Value Function Iteration with IID Income # <NAME> 2017 # Translated by <NAME> Dec 2020 import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fsolve from discrete_normal import discrete_normal # PARAMETERS ## preferences risk_aver = 2 beta = 0.95 ## returns r = 0.03 R = 1+r ## income risk...
StarcoderdataPython
4800981
""" aliases so that a real error message is displayed if someone uses the old class named """ from .pageobject import Page, Element, Elements, ElementMap from .testcase import TestCase # pylint: disable=invalid-name # pylint: disable=too-few-public-methods # pylint: disable=no-member class Deprecated(object): """...
StarcoderdataPython
1646074
<reponame>koordinates/python-client<gh_stars>1-10 # -*- coding: utf-8 -*- """ koordinates.publishing ====================== The `Group Publishing API <https://help.koordinates.com/api/publisher-admin-api/publishing-api/>`_ allows for draft versions of versioned objects Documents, Layers, and Tables) to be scheduled f...
StarcoderdataPython
14278
<reponame>mrtyasar/PythonLearn #----------------------------------# ######### ARİTMETİK İŞLEÇLER ####### #----------------------------------# # + toplama # - çıkarma # * çarpma # / bölme # ** kuvvet # % modülüs/kalan bulma # // taban bölme/ tam bölme #aritmetik işleçler sayısal işlemler yapmamızı sağlar ...
StarcoderdataPython
139462
import random from .dictionary import ADJECTIVES, ANIMALS __all__ = [ 'animal_pair' ] def animal_pair(): return u'%s-%s' % ( random.choice(ADJECTIVES), random.choice(ANIMALS), )
StarcoderdataPython
1663811
<filename>BinarySearch.py class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if nums is None or target is None: return -1 nums.sort() left = 0 right = len(nums) - 1 ...
StarcoderdataPython
188157
<filename>backend/appengine/routes/categorias/new.py<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from categoria.categoria_model import Categoria, CategoriaForm from config.template_middleware import TemplateResponse from routes import categorias from tekton.gae.middleware...
StarcoderdataPython
3308412
""" This module contains features related to outputs generated by a model. The main responsibilities are data structures for holding such outputs, and code to translate outputs into readable strings. """ from typing import List, Union from xnmt.persistence import Serializable, serializable_init class OutputProcesso...
StarcoderdataPython
63217
<reponame>DEIB-GECO/virusurf_downloader<filename>data_sources/ncbi_services.py from os.path import sep, exists, abspath from typing import Optional, Tuple, List from Bio import Entrez from loguru import logger from lxml import etree from xml_helper import text_at_node from time import sleep from typing import Callable ...
StarcoderdataPython
30851
""" Created by Sayem on 14 March, 2021 All rights reserved. Copyright © 2020. """ from .celery import app as celery_app __author__ = "Sayem" __all__ = ["celery_app"]
StarcoderdataPython
3229770
#================================================================ # # File name : RL-Bitcoin-trading-bot_1.py # Author : PyLessons # Created date: 2020-12-02 # Website : https://pylessons.com/ # GitHub : https://github.com/pythonlessons/RL-Bitcoin-trading-bot # Description : Introduction to ...
StarcoderdataPython
1607241
"""Tests for the LED-Pi Raspberry Pi WS2801 LED Controller integration."""
StarcoderdataPython
36657
import os from logging.config import dictConfig from typing import Optional from flask import render_template, request, send_from_directory from flask_babel import get_locale, lazy_gettext as _ from werkzeug.utils import ImportStringError from .auth import auth_bp from .comp import comp_bp from .ext import babel, csr...
StarcoderdataPython
21186
<filename>saleor/graphql/order/bulk_mutations/draft_orders.py import graphene from ....order import OrderStatus, models from ...core.mutations import ModelBulkDeleteMutation class DraftOrderBulkDelete(ModelBulkDeleteMutation): class Arguments: ids = graphene.List( graphene.ID, req...
StarcoderdataPython
58456
<filename>backend/authentication/tests.py<gh_stars>1-10 from rest_framework.test import APIRequestFactory, APITestCase from django.urls import reverse from rest_framework import status from users.models import User class RegistrationTests(APITestCase): @classmethod def setUpTestData(cls): cls.username...
StarcoderdataPython
3298065
import unittest from conans.test.utils.tools import TestClient from conans.util.files import load import os class ConanScopeTest(unittest.TestCase): def conan_scopes_deps_test(self): client = TestClient() conanfile = ''' from conans import ConanFile class HelloConan(ConanFile): name = "Hell...
StarcoderdataPython
3281205
"""This module contains classes and functions to work with video files. It depends on FFmpeg. """ import pathlib import numpy as np from .ffmpeg import videofileinfo, iterread_videofile, count_frames, \ get_frameat, extract_audio from .frameprocessing import frameiterator from .utils import progress, walk_paths ...
StarcoderdataPython
69537
<reponame>mobile-insight/python-for-android # MobileInsight Recipe for python-for-android # Authors: <NAME>, <NAME>, # Update for py3: <NAME>, 2020.04 import glob from os.path import exists, join, isdir, split import sh from pythonforandroid.logger import info, shprint, warning from pythonforandroid.toolchain import ...
StarcoderdataPython
1749008
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For det...
StarcoderdataPython
4817972
<filename>app/message_generator.py import logging import uuid from ec2_metadata import ec2_metadata from jinja2 import select_autoescape, Environment, PackageLoader from datetime import datetime, timezone from dateutil import parser class MessageGenerator(object): def __init__(self, jisc_id, organisation_name, ...
StarcoderdataPython
3311867
<filename>tests/core/TestRequest.py # coding=utf-8 """ Testing CoAP requests """ import json import os import tempfile import unittest import pycolo as coap from pycolo.request import request from pycolo.endpoint import Endpoint from pycolo.exceptions import InvalidURL, COAPError from tests.examples.TestCoAPbin impor...
StarcoderdataPython
3377004
<filename>kannada_OCR_model.py import pandas as pd import numpy as np import matplotlib.pyplot as plt import os import cv2 import tensorflow as tf from tensorflow import keras from sklearn.utils import shuffle from keras.utils import np_utils from keras.preprocessing.image import ImageDataGenerator #Load Im...
StarcoderdataPython
3218823
<gh_stars>0 from django.db import models class Place(models.Model): name = models.CharField(max_length=128) cre_id = models.CharField(max_length=32) place_id = models.IntegerField() x = models.FloatField() y = models.FloatField() def __str__(self): return self.place class Prices(model...
StarcoderdataPython
1765945
<filename>note_seq/testing_lib.py # Copyright 2020 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
StarcoderdataPython
129151
#!/usr/bin/env python import asyncio import cytoolz from hexbytes import HexBytes import logging import math from typing import ( List, Dict, Iterable, Set, Optional ) from web3 import Web3 from web3.contract import Contract from web3.datastructures import AttributeDict from hummingbot.logger impo...
StarcoderdataPython
156876
import os from experiments.experiments import ModelSelectionExperiment from nilmlab.lab import TimeSeriesLength dirname = os.path.dirname(__file__) single_building_exp_checkpoint = os.path.join(dirname, '../results/cv1h.csv') exp = ModelSelectionExperiment(cv=5) exp.set_ts_len(TimeSeriesLength.WINDOW_1_HOUR) exp.set...
StarcoderdataPython
3291445
<filename>16 Network Analysis/16_dynamic_network_analysis_enron.py import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler, LabelEncoder from igraph import Graph, mean as ig_mean import chart_studio.plotly as py import plotly.graph_objs as go import matplotlib.pyplot as plt import ruptures...
StarcoderdataPython
3279222
from __future__ import print_function, division from typing import Union, Optional, List, Iterable, Dict, Any from collections import defaultdict from abc import ABCMeta import copy import re import string import math import logging import sys import numpy as np from sympy import (MatMul, MatAdd, Basic, MatrixExpr,...
StarcoderdataPython
17953
# Copyright (c) 2014 Simplistix Ltd # See license.txt for license details. from decimal import Decimal from testfixtures import RoundComparison as R, compare, ShouldRaise from unittest import TestCase from ..compat import PY2, PY3 class Tests(TestCase): def test_equal_yes_rhs(self): self.assertTrue(0.1...
StarcoderdataPython
1757870
<gh_stars>0 nomeVendedor = input() salarioFixo = float(input()) totalVendasNoMes = float(input()) comicao = 0.15 salarioFinal = (salarioFixo)+(totalVendasNoMes*comicao) print("TOTAL = R$ %.2f"%salarioFinal)
StarcoderdataPython
1647024
<gh_stars>10-100 import py from pypy.tool.tls import tlsobject from pypy.tool.ansi_print import ansi_log from pypy.rlib import jit from pypy.objspace.flow.model import copygraph, SpaceOperation, Constant from pypy.objspace.flow.model import Variable, Block, Link, FunctionGraph from pypy.annotation import model as annmo...
StarcoderdataPython
54397
<filename>predict_traffic.py from PIL import Image import numpy as np import os def show_masked_img(roads_tensor, cars_tensor, raw_img, img_name): # Convert to numpy roads_pred = roads_tensor.cpu().detach().numpy() cars_pred = cars_tensor.cpu().detach().numpy() # Extract roads roads_img_r = roads_p...
StarcoderdataPython
168077
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from __future__ import annotations from copy import deepcopy from typing import Optional from typing import Union from munch import Munch from torch.optim import Optimizer # noinspection PyUnresolvedReferences from torch.optim.lr_scheduler import _LRScheduler f...
StarcoderdataPython
153431
# This program adds two numbers num1 = 1.5 num2 = 6.3 # Add two numbers sum = num1 + num2
StarcoderdataPython
3304076
import pygame from random import randrange try: pygame.init() except: print('Problema ao iniciar o módulo pygame') branco = (255,255,255) preto = (0,0,0) vermelho = (255,0,0) verde = (0,255,0) azul = (0,0,255) largura = 320 altura = 280 tamanho = 10 placar = 40 recorde = 0 relogio = pygame.time.Clock() fun...
StarcoderdataPython
131339
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the ...
StarcoderdataPython
1701861
#!/usr/bin/env python from netmiko import ConnectHandler from getpass import getpass device = { "host": "cisco4.lasthop.io", "username": "pyclass", "password": getpass(), "device_type": "cisco_ios", } net_connect = ConnectHandler(**device) print(net_connect.find_prompt()) output = net_connect.send_co...
StarcoderdataPython
1754697
<reponame>AsciencioAlex/super-waddle-webscrapping from bs4 import BeautifulSoup import urllib.requests req = urllib.request.urlopen('http://www.nationaljournal.com/politics?rss=1') xml = BeautifulSoup(req, 'xml') for item in xml.findAll('link')[3:]: url = item.text news = urllib.request.urlopen(url).read() ...
StarcoderdataPython
143910
import array import pytest from pdsa.frequency.count_sketch import CountSketch def test_init(): cs = CountSketch(2, 4) assert cs.sizeof() == 32, 'Unexpected size in bytes' with pytest.raises(ValueError) as excinfo: cs = CountSketch(0, 5) assert str(excinfo.value) == 'At least one counter arr...
StarcoderdataPython
1725670
<reponame>grutts/siri from dataclasses import dataclass, field from enum import Enum from typing import List, Optional from siri.siri_model.siri_situation_identity_v1_1 import ( SituationFullRef, SituationRef, ) from siri.siri_utility.siri_types_v2_0 import ( NaturalLanguagePlaceNameStructure, NaturalLa...
StarcoderdataPython
113697
<filename>editor/attributes/player/player_attribute_finger_band_type_rgb_g.py from bidict import bidict from editor.utils.common_functions import ( get_lowest_byte_value, get_base_byte_value, ) from editor.attributes.player.player_attribute import ( PlayerAttribute, PlayerAttributeTypes, ) from edito...
StarcoderdataPython
17330
<reponame>gbene/pydip ''' Script by: <NAME> date: 25/06/2021 Utilities functions. This file is used to have a more organized main script. It contains: + Random plane orientation generator that can be used to practice plane attitude interpretation + Random fold generator + Plotter + Data converter from pandas dataf...
StarcoderdataPython
107306
<reponame>anthonybuckle/Reciprocity-Core from unittest import TestCase, main from recip import recipcli class test_Script(TestCase): def test_DeployScript(self): command = 'DeployScript' parameters = [] recipcli.handleCommand(command, parameters) def test_DeployLocalScript(self): ...
StarcoderdataPython
13613
<reponame>bluesheeptoken/PyGolf<gh_stars>1-10 import argparse import tempfile import unittest from pygolf.__main__ import get_arguments_warning, read_input_code, shorten class TestMain(unittest.TestCase): def test_reduce(self): self.assertEqual(shorten("print( 1 + 2 )"), "print(1+2)") self.assert...
StarcoderdataPython
75480
#!/usr/bin/env python # coding: utf-8 # /*########################################################################## # # Copyright (c) 2016-2018 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files ...
StarcoderdataPython
3205275
from django import forms from .models import PostModel class PostForm(forms.ModelForm): class Meta: model = PostModel fields = [ 'author', 'judul', 'body', 'category', ] labels = { 'author':'Penulis', } widgets = { 'judul': forms.TextInput( attrs = { 'class':'form-control', ...
StarcoderdataPython
1669930
<reponame>plazas/HSC-planck-sz-clusters-WL-mass-calibration def HMS2deg(ra='', dec=''): RA, DEC, rs, ds = '', '', 1, 1 if dec: D, M, S = [float(i) for i in dec.split()] if str(D)[0] == '-': ds, D = -1, abs(D) deg = D + (M/60) + (S/3600) DEC = '{0}'.format(deg*ds) if ra: H, M, S = [flo...
StarcoderdataPython
3319916
/home/runner/.cache/pip/pool/80/4c/3b/8f4091c562fdf46b1bf67e271ca89f9f1afd717358edb31564b0fd36e5
StarcoderdataPython
1726177
<gh_stars>0 class Blink(UsableAbility): def __init__(self, owner): super().__init__() self.owner = owner self.ability_attr["name"] = "Blink" self.ability_attr["lvl"] = 1 self.ability_attr["cost"] = 15 self.ability_attr["cost_type"] = "sta" self.ability_att...
StarcoderdataPython
3201635
from gcsfs.utils import ChecksumError from gcsfs.checkers import Crc32cChecker, MD5Checker, SizeChecker, crcmod from hashlib import md5 import base64 import pytest def google_response_from_data(expected_data: bytes, actual_data=None): actual_data = actual_data or expected_data checksum = md5(actual_data) ...
StarcoderdataPython
2878
__author__ = 'Xsank' import time from thinkutils_plus.eventbus.eventbus import EventBus from myevent import GreetEvent from myevent import ByeEvent from mylistener import MyListener if __name__=="__main__": eventbus=EventBus() eventbus.register(MyListener()) ge=GreetEvent('world') be=ByeEvent('world'...
StarcoderdataPython
4810492
"""Definition of the character sheet main module.""" from flask import Blueprint from flask_restful import Api from user.controllers import UserListcontroller, UserController, LoginController user_bp = Blueprint('users', __name__) user_api = Api(user_bp) user_api.add_resource(UserListcontroller, '/') user_api.add_r...
StarcoderdataPython
3285502
import numpy as np import scipy.misc as sp import matplotlib.pyplot as plt import os join = os.path.join def kitti_to_cityscapes_instaces(instance_img): kitti_semantic = instance_img // 256 kitti_instance = instance_img % 256 print(kitti_semantic.max()) print(kitti_instance.max()) instance_mask ...
StarcoderdataPython
64926
<filename>appSchool/models.py # import jwt # from datetime import datetime, timedelta # from django.conf import settings # from django.contrib.auth.models import ( # AbstractBaseUser, BaseUserManager, PermissionsMixin # ) # from django.db import models # # Create your models here. # class UserManager(BaseUserMana...
StarcoderdataPython
1631622
<filename>pyecharts/charts/basic_charts/calendar.py # coding=utf-8 from ... import options as opts from ...charts.chart import Chart from ...commons.types import Sequence, Union class Calendar(Chart): """ <<< 日历图 >>> 热力图主要通过颜色去表现数值的大小,必须要配合 visualMap 组件使用。 直角坐标系上必须要使用两个类目轴。 """ ...
StarcoderdataPython
1761223
<filename>ltlf2dfa/symbols.py<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of ltlf2dfa. # # ltlf2dfa 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 th...
StarcoderdataPython
1621775
<reponame>theworkingmen/majorpotential<filename>backend/tests.py import sys import os import unittest try: sys.path.insert(0, '../backend/Database/') from Universities.uni_api_func import * from Majors.major_api_func import * from Cities.cities_api_func import * except: sys.path.insert(0, os.path.ab...
StarcoderdataPython
3391110
import plotly.offline as po import plotly.graph_objs as go import numpy as np # plotly.offline.init_notebook_mode(connected=True) # 格子状に座標を生成 grid = np.mgrid[0:10, 0:20] grid_x = grid[0].flatten() grid_y = grid[1].flatten() grid_z = grid_x + grid_y points = np.array(list(zip(grid_x, grid_y, grid_z))) # プロットのためにxyzごと...
StarcoderdataPython
119039
<gh_stars>1-10 class Foo: def __init__(self, id): self.id = id def __str__(self): return 'Foo instance id: {}'.format(self.id) class Bar: def __init__(self, id): self.id = id def __str__(self): return 'Bar instance id: {}'.format(self.id) class Baz: def __init__(s...
StarcoderdataPython
3206822
<reponame>mvwicky/holdmypics import shlex import shutil import subprocess from typing import Any from loguru import logger CTX_SETTINGS = {"max_content_width": min(shutil.get_terminal_size().columns, 130)} def run(*args: str, no_log: bool = False, **kwargs: Any) -> subprocess.CompletedProcess: if not no_log: ...
StarcoderdataPython
1716657
import json import pandas as pd from analysis_lib.video_creator.create_video import create_video from analysis_lib.dlc_results_adapter import DlcResults def main(): args = json.loads(input()) create_video(raw_video_path=args["rawVideoPath"], tracking_h5_path=args["trackingResultsH5Path"], be...
StarcoderdataPython
172794
""" Pytorch implementation of the Autoencoder For denoising the images """ import sys import torch sys.path.append("../") device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") import matplotlib.pyplot as plt from torch import nn from dataloader import load_mnist from basic_autoencoder im...
StarcoderdataPython
4801583
<reponame>ayanasu-iot/LEDMatrix-WebApi ALLOWED_EXTENSIONS = {'png', 'jpg', 'gif'} UPLOAD_FOLDER = './uploads/' STATIC_FOLDER = './static/'
StarcoderdataPython
72383
<filename>test/connect/test_ConnectionUtils.py # -*- coding: utf-8 -*- from pip_services3_commons.config import ConfigParams from pip_services3_components.connect.ConnectionUtils import ConnectionUtils class TestConnectionUtils: def test_concat_options(self): options1 = ConfigParams.from_tuples( ...
StarcoderdataPython
1715866
import os import boto3 import json import urllib from datetime import datetime from dateutil.relativedelta import relativedelta from botocore.vendored import requests def lambda_handler(event, context): session = boto3.Session() s3_client = boto3.client("s3") dynamodb_client = session.resource("dynam...
StarcoderdataPython