id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
122985
import numpy as np from sklearn.model_selection import KFold from sklearn.mixture import GaussianMixture from routines import Routines import configparser config = configparser.ConfigParser() config.read('../system.ini') routines = Routines(config)
StarcoderdataPython
1792020
""" This module contains classes that implement a map->for loop transformation. """ import dace from copy import deepcopy as dcpy from dace import data, symbolic, dtypes, subsets from dace.graph import edges, nodes, nxutil from dace.transformation import pattern_matching from math import ceil import sympy import netwo...
StarcoderdataPython
12320
<reponame>zacharyt20/POCS import os import pytest import yaml from pocs.core import POCS from pocs.observatory import Observatory from pocs.utils import error @pytest.fixture def observatory(): observatory = Observatory(simulator=['all']) yield observatory def test_bad_state_machine_file(): with pytes...
StarcoderdataPython
3301197
<reponame>Lh4cKg/task_2_zhuko from django.urls import path, include from rest_framework import routers from server.apps.texts import views router = routers.DefaultRouter() router.register(r'texts', views.TextViewSet) router.register(r'sentences', views.SentenceViewSet) app_name = 'texts' urlpatterns = [ path('', ...
StarcoderdataPython
1724380
from datetime import datetime from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): """ 用户 """ GRADE_TYPE = ( (1, "大学一年级"), (2, "大学二年级"), (3, "大学三年级"), (4, "大学四年级"), ) name =...
StarcoderdataPython
109048
<reponame>alec-tschantz/action-oriented import numpy as np import matplotlib.pyplot as plt import seaborn as sns from core.config import * plt.rc("text", usetex=True) def create_heatmap(matrix, title, save_path, color_bar=True): f, (ax1, ax2) = plt.subplots(2, 1, figsize=(2.7, 4)) x_labels = [r"$s_{t-1}^{ne...
StarcoderdataPython
89740
from osziplotter.network.Headers import BeaconHeader, SampleTransmissionHeader, CommandHeader from osziplotter.network.SampleCollector import SampleCollector from osziplotter.modelcontroller.BoardEvents import BoardEvents from socket import socket, AF_INET, SOCK_DGRAM, error from errno import EAGAIN, EWOULDBLOCK from ...
StarcoderdataPython
1753034
<reponame>twetzel59/TinyShell RED = "\033[31;1m" GREEN = "\033[32;1m" CYAN = "\033[36;1m" RESET = "\033[0m"
StarcoderdataPython
1775233
<filename>badcode/bblfshutil.py import collections import itertools import typing from typing import Iterable, Tuple import bblfsh from .tree import Tree WILDCARD = '_MATCH_ANY_' class UAST(Tree[Tuple[str,str]]): def __init__(self, key: Tuple[str,str], children: Iterable['UAST']=tuple()) -> None: ...
StarcoderdataPython
178848
"""Sinking point - A discrete approximation of real numbers with explicit significance tracking. Implemented really badly in one file. TODO: in digital.py: - representation - reading in from int / mpfr / string - reading in from digital, clone and update - comparison - trivial bit manipulations like neg and...
StarcoderdataPython
1725372
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-20 10:15 from __future__ import unicode_literals from django.db import migrations def mark_all_renders_as_removed(apps, schema_editor): Render = apps.get_model("papers", "Render") Render.objects.all().update(container_is_removed=True) class Mi...
StarcoderdataPython
1655466
import sys def solve(): sys.setrecursionlimit(10**6) read = sys.stdin.readline n = int(read()) adj = [[] for _ in range(n + 1)] for _ in range(n - 1): u, v = map(int, read().split()) adj[u].append(v) adj[v].append(u) # dp[for_tree_rooted_at][w/_or_wo/_root_being_early_...
StarcoderdataPython
3251824
from dataclasses import dataclass, field from typing import List, Optional, Union from bindings.gmd.abstract_object_type import AbstractObjectType from bindings.gmd.actuate_value import ActuateValue from bindings.gmd.character_string_property_type import CharacterStringPropertyType from bindings.gmd.ci_citation_type im...
StarcoderdataPython
179530
<gh_stars>0 from django.test import TestCase import datetime from django.utils import timezone from .models import Question # Create your tests here. class QuestionMethodTests(TestCase): def test_was_published_recently_with_future_question(self): time=timezone.now()+datetime.timedelta(days=30) future_question=Que...
StarcoderdataPython
1717857
import numpy as np import tensorflow as tf from embeddings import text_embeddings from evaluation import appleveleval from models import wordpair_model from helpers import io_helper from helpers import data_shaper import random import itertools from ml import loss_functions from ml import trainer from evaluation import...
StarcoderdataPython
1714133
<reponame>Fishkudda/fobot<gh_stars>0 from pony.orm import * from datetime import datetime,timedelta import re from collections import OrderedDict db = Database() class Maps(db.Entity): id = PrimaryKey(int, auto=True) first_played = Required(datetime) last_played = Required(datetime) name = Required(s...
StarcoderdataPython
45329
<filename>rdkit/Chem/UnitTestGraphDescriptors.2.py # $Id$ # # Copyright (C) 2003-2006 Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit so...
StarcoderdataPython
1780962
<gh_stars>0 from .GetTraceFootprints import GetTraceFootprints from .GetOrbits import GetOrbits from .GetPosition import GetPosition from .PlotOrbit import PlotOrbit,PlotOrbitPlane from .GetMercuryPos import GetMercuryPos from .GetRegion import GetRegion
StarcoderdataPython
143189
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2019 The FATE 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/licens...
StarcoderdataPython
1716676
<gh_stars>0 from twilio.rest import Client TWILIO_SID = "AC22a576bf0fa38cb70e45832024b35bfc" TWILIO_AUTH_TOKEN = "<KEY>" TWILIO_VIRTUAL_NUMBER = "+19286156986" TWILIO_VERIFIED_NUMBER = "+13303226254" # This class is responsible for sending notifications with the deal flight details. class NotificationManager: de...
StarcoderdataPython
3364685
<gh_stars>0 from pynput.keyboard import Listener, Key from rlbot.agents.base_agent import SimpleControllerState def deadzone(normalized_axis): if abs(normalized_axis) < 0.1: return 0.0 return normalized_axis class HytakControllerInput(SimpleControllerState): def __init__(self): self._gas...
StarcoderdataPython
1798527
""" Test kw_only decorators """ from ..keywordonly import kw_only_func, kw_only_meth import pytest def test_kw_only_func(): # Test decorator def func(an_arg): "My docstring" return an_arg assert func(1) == 1 with pytest.raises(TypeError): func(1, 2) dec_func = kw_only_fun...
StarcoderdataPython
1610947
#!/usr/bin/env python # # Public Domain 2014-present MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a com...
StarcoderdataPython
1768080
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 10 15:51:15 2021 @author: rosariouceda-sosa """ ########################################### # Extraction of Propbank, Verbnet and mappings # It requires verbnet3.4, verbnet3.3 and verbnet3.2 in nltk_data directory, # as well as the latest ver...
StarcoderdataPython
3664
from unittest.mock import MagicMock, Mock from i3ipc.aio import Con import i3_live_tree.tree_serializer # noqa: F401 class MockConSerializer(Mock, Con): """Mock a generic i3ipc.aio.Con for serialization purposes This Mock is meant to ease testing of i3ipc.aio.Con serialization methods, which are mokey...
StarcoderdataPython
98274
import xlrd import typing import re # from termcolor import colored class Controle: def __init__(self) -> None: self.__planilha_esocial = None self.__planilha_candidata = None self.__relatorio:typing.IO = None def set_planilha_esocial(self, nome_pasta_esocial:str) -> None: ...
StarcoderdataPython
3284672
<reponame>smbapps/chinup from __future__ import absolute_import, unicode_literals from collections import OrderedDict import logging import threading from .lowlevel import batch_request from .conf import settings from .util import get_proof logger = logging.getLogger(__name__) _threadlocals = threading.local() ...
StarcoderdataPython
176669
<reponame>Grieverwzn/network-design-qap<gh_stars>1-10 import time import multiprocessing as mp import numpy as np import sys from queue import PriorityQueue from assignment import * sys.setrecursionlimit(10000) class TreeNode: # This is the node for tree serch def __init__(self, nb_unassigned_buildings, assig...
StarcoderdataPython
14241
<gh_stars>1-10 from enum import Enum class TestShopNames(Enum): AMAZON = ("AMAZON",) TARGET = ("TARGET",) WALMART = ("WALMART",) TJMAXX = ("TJMAXX",) GOOGLE = ("GOOGLE",) NEWEGG = ("NEWEGG",) HM = ("HM",) MICROCENTER = ("MICROCENTER",) FASHIONNOVA = ("FASHIONNOVA",) SIXPM = ("S...
StarcoderdataPython
4841155
from collections import Counter from scattertext.emojis.EmojiExtractor import extract_emoji from scattertext.features.FeatsFromSpacyDoc import FeatsFromSpacyDoc class FeatsFromSpacyDocOnlyEmoji(FeatsFromSpacyDoc): ''' Strips away everything but emoji tokens from spaCy ''' def get_feats(self, doc): ''' Param...
StarcoderdataPython
3235183
__author__ = "<NAME>" __copyright__ = "(C) 2021 Coalfire" __contributors__ = ["<NAME>"] __status__ = "Production" __license__ = "MIT" from ...API import API class ActuatorAPI(API): def __init__(self, host, api_key, verify_ssl, timeout, headers, user_agent, cert, debug): """ Initialize a ThreadFix...
StarcoderdataPython
1624834
<gh_stars>0 """Backend class.""" import numpy as np class Backend(): """Defaults are currently ARTS observing properties.""" def __init__(self, n_channels: int = 1536, channel_bandwidth: float = 0.1953125, # MHz fmin: float = 1219.700927734375, # MHz ...
StarcoderdataPython
4819268
#!/usr/bin/python import numpy as np import json import csv from pyspark import SparkConf, SparkContext conf = (SparkConf() .setMaster("local[*]") .setAppName("My app") .set("spark.executor.memory", "8g") .set("spark.executor.cores", "8")) sc = SparkContext(conf = conf) file1 = '/home...
StarcoderdataPython
3342377
<filename>gnes/indexer/vector/annoy.py import os from typing import List, Tuple import numpy as np from ..base import BaseVectorIndexer from ..key_only import ListKeyIndexer class AnnoyIndexer(BaseVectorIndexer): lock_work_dir = True def __init__(self, num_dim: int, data_path: str, metric: str = 'angular',...
StarcoderdataPython
194616
<reponame>quantummind/quantum # Copyright 2020 The TensorFlow Quantum 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/LICE...
StarcoderdataPython
1634410
<filename>desktop/libs/notebook/src/notebook/connectors/jdbc_vertica.py #!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file ...
StarcoderdataPython
199555
<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-03-30 09:42 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('music', '0005_file_obfuscate_filename'), ] operations = [ migra...
StarcoderdataPython
1789524
<gh_stars>0 #!/usr/bin/env python # coding: utf-8 """" Usage: python show_data.py """ # In[1]: import os import numpy as np from scipy import spatial import glob from multiprocessing import Process from tqdm import tqdm from vedo import load, show import sys # ## 一、自定义函数 # ### 1.获取模型信息 # In[2]: def get_edges(...
StarcoderdataPython
3368071
""" Copyright 2017 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distrib...
StarcoderdataPython
1648090
#!/usr/bin/env python # =============================================================================== # Copyright 2017 Geoscience Australia # # 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...
StarcoderdataPython
1703380
<filename>experiments.py import pandas as pd import numpy as np from src.util import transform_datasets from src.preprocessing import full_data, split_data from sklearn.model_selection import StratifiedKFold from src.model import cov_detector, dual_cov_detector from sklearn.mixture import GaussianMixture from sklearn.d...
StarcoderdataPython
134961
<filename>helpers/graph_algorithms.py """ <NAME> April 19, 2019 California Institute of Technology Simple algorithm to transitive reduce an (acyclic) graph """ import numpy as np def transitive_reduce(A): """ input: A is a reachability Boolean numpy array output: transitive reduced version of A """ ...
StarcoderdataPython
3385112
# Copyright 2022 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agre...
StarcoderdataPython
188598
# Parse header file to generate Python wrapper around the rszvb DLL for the Rohde&Scwarz ZVA 40 Network Anlyzer fout = open("rszvb_v2.py",'w') # First load the DLL print >>fout , """import numpy as numpy from ctypes import * # Prerequisition: installed rszvb driver 32-bit # Reference to rszvb dll rszvbDL...
StarcoderdataPython
4800484
<reponame>vlsantos-bit/Meteograma_GFS_GRIB2 # -*- coding: utf-8 -*- """Meteograma_gfs_data.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/136EV_t3AaGttb8F43aTEQt5BRAYOVR1x """ #Baixando bibliotecas !sudo apt-get install python-grib !sudo python ...
StarcoderdataPython
129793
<reponame>hieu1999210/image_compression """ from https://github.com/facebookresearch/detectron2/blob/master/detectron2/modeling/meta_arch/build.py """ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file e...
StarcoderdataPython
37672
<reponame>xiangnan-fan/proj01<gh_stars>0 #!/bin/python3 # encoding: utf-8 import tensorflow as tf tf.enable_eager_execution() class CNN(tf.keras.Model): def __init__(self): super().__init__() self.conv1 = tf.keras.layers.Conv2D( filters=32, kernel_size=[5, 5], ...
StarcoderdataPython
3256910
__version__ = '0.0.1' import mongoengine as mongo from bson import DBRef # # # https://hack.close.io/posts/mongomallard class SafeReferenceField(mongo.ReferenceField): """ Like a ReferenceField, but doesn't return non-existing references when dereferencing, i.e. no DBRefs are returned. This means that th...
StarcoderdataPython
3340935
from time import sleep import logging class DialogBox(): """Implements a dialog box with given values (or some default ones if chosen).""" value_selected = False pointer = 0 default_options = {"y":["Yes", True], 'n':["No", False], 'c':["Cancel", None]} def __init__(self, values, i, o, message="Ar...
StarcoderdataPython
4805753
# -*- coding: utf-8 -*- u""" .. _qook_tutorial: Using xrtQook for script generation ----------------------------------- - Start xrtQook: type ``python xrtQookStart.pyw`` from xrt/gui or, if you have installed xrt by running setup.py, type ``xrtQookStart.pyw`` from any location. .. note:: The scaling of G...
StarcoderdataPython
3342212
#!/usr/bin/env python """A module that maps unique strings to the same objects. This is useful when, for example, you have some complicated structures that are identified and referenced by names. """ __docformat__ = "restructuredtext" import os import warnings import inspect csPath = os.path.join("cleversheep3", "Te...
StarcoderdataPython
3238759
<reponame>justdjango/django-nft-sniper<filename>djsniper/sniper/admin.py<gh_stars>10-100 from django.contrib import admin from .models import NFTProject, NFT, NFTTrait, NFTAttribute class NFTAdmin(admin.ModelAdmin): list_display = ["nft_id", "rank", "rarity_score"] search_fields = ["nft_id__exact"] class NF...
StarcoderdataPython
1653336
<reponame>konflic/sqlite_database import sqlite3 con3 = sqlite3.connect(":memory:") con3.close() def example_db(): sql = """ CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, nickname TEXT, email TEXT, reg_date DATETIME ); ...
StarcoderdataPython
3358167
<reponame>doctsystems/obsCovidTja from django.db import models from core.models import ClaseModelo from django.contrib.gis.db import models class Persona(ClaseModelo): nombres=models.CharField(max_length=20) apellidos=models.CharField(max_length=30) carnet=models.CharField(max_length=10) celular=models.CharField(m...
StarcoderdataPython
3231585
import traceback from flask import current_app from urllib.parse import urljoin from ..lib import utils from .base import db from .setting import Setting from .user import User from .account_user import AccountUser class Account(db.Model): __tablename__ = 'account' id = db.Column(db.Integer, primary_key=True...
StarcoderdataPython
169346
<reponame>Leonardo-H/DR-PG import numpy as np class PerformanceEstimate(object): """ A helper function to compute gradient of the form E_{d_\pi} (\nabla E_{\pi}) [ A ] where the unnormalized state distribution is d_{\pi} = \sum_{t=1}^\infty \gamma^t * d_{pi,t} ...
StarcoderdataPython
1648268
from .calculate import * from .file import *
StarcoderdataPython
1618570
#!/usr/bin/python3 import random import string import os from dotenv import load_dotenv class CouponAPI: @staticmethod def get_random_string(length): """ Generate a random string (upper and lower case letters) to be used as a coupon code :param length: the length of the coupon code :r...
StarcoderdataPython
112032
<filename>oarepo_model_builder/invenio/invenio_views.py from .invenio_base import InvenioBaseClassPythonBuilder class InvenioViewsBuilder(InvenioBaseClassPythonBuilder): TYPE = 'invenio_views' class_config = 'create_blueprint_from_app' template = 'views'
StarcoderdataPython
3369461
<reponame>gujralsanyam22/pyrobot<gh_stars>1000+ # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Example for commanding robot with position control using moveit planner """ from pyrobot i...
StarcoderdataPython
33382
import numpy as np import math import fatpack import matplotlib.pyplot as plt import pandas as pd #Create a function that reutrns the Goodman correction: def Goodman_method_correction(M_a,M_m,M_max): M_u = 1.5*M_max M_ar = M_a/(1-M_m/M_u) return M_ar def Equivalent_bending_moment(M_ar,Neq,m): P = M_ar...
StarcoderdataPython
3323071
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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
3375817
<reponame>barsgroup/barsup-core # coding:utf-8 """Функционал для работы уровня WSGI.""" from datetime import datetime import json from os import path from sys import stderr, exc_info import traceback from uuid import uuid4 from simplejson.scanner import JSONDecodeError from webob import Response, exc from webob.dec ...
StarcoderdataPython
1705297
import anodos.tools import swarm.models import pflops.models import distributors.models import swarm.workers.worker class Worker(swarm.workers.worker.Worker): name = 'Центральный банк России' urls = {'base': 'http://cbr.ru', 'data': 'https://cbr.ru/currency_base/daily/'} cols = {'Цифр. код': ...
StarcoderdataPython
1720643
import os import sys import json import socket import threading _foo = None class LineTracer: def __init__(self, target): self.sourcefiles = {} self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect(("localhost", 5050)) # read in the configuration ...
StarcoderdataPython
112373
from flourish import Flourish from flourish.generators.base import SourceGenerator from flourish.source import SourceFile import pytest class TestFlourishPaths: @classmethod def setup_class(cls): with pytest.warns(None) as warnings: cls.flourish = Flourish('tests/source') def test_ho...
StarcoderdataPython
3233256
# SPDX-FileCopyrightText: 2021-present <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT def fibonacci(n: int) -> int: if n <= 1: return n else: return fibonacci(n - 2) + fibonacci(n - 1)
StarcoderdataPython
1762416
import re import six import unittest from geodata.addresses.entrances import * from geodata.addresses.floors import * from geodata.intersections.query import * from geodata.addresses.po_boxes import * from geodata.addresses.postcodes import * from geodata.addresses.staircases import * from geodata.addresses.units impo...
StarcoderdataPython
3325463
<filename>testing/train_cb.py import pdb import sys import subprocess import argparse p = argparse.ArgumentParser() p.add_argument('model_file', help="model specification", default="cb_hand2_v_shuffle_3areas") p.add_argument('-g', '--gpus', nargs='?', type=int, default=1) p.add_argument('-s', '--seed', nargs='?', type...
StarcoderdataPython
3322344
import tensorflow as tf import numpy as np import PIL as pil import scipy import skimage.measure from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Cropping2D, ZeroPadding2D, Convolution2D, Activation, AveragePooling2D, Flatten, Reshape from keras.layers import Deconvolution2D as Conv2DTranspos...
StarcoderdataPython
1774886
<filename>data/test_waypoints_show.py<gh_stars>1-10 #!/usr/bin/env python import os import csv import tf import numpy as np import matplotlib.pyplot as plt """ self.lights.len=8 lights[0] : [1172.183, 1186.299], lights[1] : [1584.065, 1156.953], lights[2] : [2126.353, 1550.636], lights[3] : [2178.291, 1819.328], lig...
StarcoderdataPython
3246739
<reponame>plilja/project-euler from common.primes import * from common.functions import * def largest_pandigital_primes(n): for i in range(n, 1, -1): for pandigital_number in sorted(_all_pandigital_numbers(i), reverse=True): if is_prime(pandigital_number): return pandigital_num...
StarcoderdataPython
4822555
# same as Consecutive 1's not allowed # just there instead of 0s 1s but output will be same # lets say n=3 # so binary strings = 2^3 = 8 # 000 not allowed # 001 not allowed # 010 # 011 # 100 not allowed # 101 # 110 # 111 # so output : 5 def countStrings(n): if n==0: return 0 # if n=0 then no string can be for...
StarcoderdataPython
157850
#!/usr/bin/env python """ AER1415 Computer Optimization - Assignment 1 Author: <NAME> Submitted: Feb 25, 2021 Email: <EMAIL> Descripton: """ from numpy import * import os from matplotlib import pyplot as plt from IPython import embed from mpl_toolkits import mplot3d from matplotlib import cm import...
StarcoderdataPython
1664639
<filename>dev/python/2018-12-08 discontinuous sweeps.py """ Ensure discontinuous sweeps (sweeps whose sweep length is less than their inter- sweep interval) are loaded properly and work with comments. I confirmed there is a problem on 2018_11_16_sh_0006.abf: print(abf) says total length of 0.10 min when it should be ...
StarcoderdataPython
84836
import pronto, six, csv from sys import * reader = csv.DictReader(open('goid.tab', 'r'), delimiter='\t') efs = {} for item in reader: go = item.get('goid') iturl = item.get('p') it = iturl[iturl.rfind('/')+1:] git = efs.get(go) if git is None: efs[go] = it else: print('=========...
StarcoderdataPython
45983
""" Present both functional and object-oriented interfaces for executing lookups in Hesiod, Project Athena's service name resolution protocol. """ from _hesiod import bind, resolve from pwd import struct_passwd from grp import struct_group class HesiodParseError(Exception): pass class Lookup(object): """ ...
StarcoderdataPython
1664159
# -*- coding: utf-8 -*- N = int(input()) MONEY = [100, 50, 20, 10, 5, 2, 1] print(N) for i in range(7): print("%d nota(s) de R$ %d,00" % (N / MONEY[i], MONEY[i])) N = N % MONEY[i]
StarcoderdataPython
1752188
from platypush.backend.sensor import SensorBackend class SensorSerialBackend(SensorBackend): """ This backend listens for new events from sensors connected through a serial interface (like Arduino) acting as a wrapper for the ``serial`` plugin. Requires: * The :mod:`platypush.plugins.serial`...
StarcoderdataPython
140693
from abc import ABCMeta, abstractmethod from tgt_grease.core import Logging, GreaseContainer from datetime import datetime import sys import os import traceback class Command(object): """Abstract class for commands in GREASE Attributes: __metaclass__ (ABCMeta): Metadata class object purpose (...
StarcoderdataPython
159219
<reponame>gabrielpetersson/rnngen import numpy as np def vec_word(word_vecs, dic, dim=2, rev=False): if rev: dic = {value: letter for letter, value in dic.items()} if dim == 1: res = dic[np.argmax(word_vecs)] return res if dim == 2: res = '' for letter in word_vecs:...
StarcoderdataPython
164241
# -*- coding: utf-8 -*- from pymongo import MongoClient import settings import datetime #连接 client=MongoClient('mongodb://127.0.0.1:27017/') db = client[settings.DBNAME] def getCollection(collection): if(collection): return db[collection] else: return None def saveWeibo(article): articleCollection = getCo...
StarcoderdataPython
3316836
# Simple Math # We're going to work with print statements to output the results to the screen. # You can separate multiple print items with a comma, as shown below: print("Four times four is ", 4 * 4) # Addition print("5 + 3 is ", 5 + 3) # Subtraction print("6 - 2 is ", 6 - 2) # Multiplication print("10 * 20 is ...
StarcoderdataPython
4804748
class Solution: def numIdenticalPairs(self, nums: List[int]) -> int: def nCr(n): import math f = math.factorial return f(n) / f(2) / f(n-2) s=set(nums) b=0 for i in s: x=nums.count(i) if x>=2: b=b+nCr(x) ...
StarcoderdataPython
3304432
from django.db import models class Task(models.Model): """ Task parent. Task will be sometimes generated to run asynchroon A worker will run these task one by one when enough resources are free """ VERY_LOW = 0 LOW = 1 NORMAL = 2 HIGH = 3 VERY_HIGH = 4 PRIORITIES = ( #...
StarcoderdataPython
1605289
<reponame>naokishibuya/simple_transformer import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor class MultiHeadAttention(nn.Module): """ Multi-head attention runs multiple attention calculations in parallel. """ def __init__(self, num_heads: int, dim_embed: int, drop_...
StarcoderdataPython
3340531
<reponame>totorigolo/genetic_snake import logging import os import signal import time from ga_snake.snake_game_executor import SnakeGameExecutor log = logging.getLogger("training") class Training(object): def __init__(self, args): self.args = args self.run_counter = 0 self.main_pid = No...
StarcoderdataPython
1656946
<filename>src/zenml/utils/secrets_manager_utils.py # Copyright (c) ZenML GmbH 2022. 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: # # https://www.apache.org/...
StarcoderdataPython
3359032
# This file is part of the MicroPython project, http://micropython.org/ # # The MIT License (MIT) # # Copyright (c) 2020-2021 <NAME> # # 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 ...
StarcoderdataPython
3344428
# -*- coding: utf-8 -*-. from . import ln_koko_sd_trip from . import koko_sd_shop_detail from . import res_config_settings
StarcoderdataPython
3285213
<reponame>mikemalinowski/carapace """ 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, distribute, ...
StarcoderdataPython
3311698
<reponame>ewiger/len from .defaults import DefaultScope class AppScope(DefaultScope): @property def kind(self): return "app"
StarcoderdataPython
13566
import pytest import ast from pytest_mock import MockerFixture from pystratis.api.node import Node from pystratis.api.node.responsemodels import * from pystratis.api import FullNodeState, FeatureInitializationState, LogRule from pystratis.core.networks import StraxMain, CirrusMain @pytest.mark.parametrize('network', ...
StarcoderdataPython
3203856
<filename>tests/test_settings.py import logging from pathlib import Path def test_get_exception(caplog, settings): with caplog.at_level(logging.INFO): assert settings.get("RANDOM_KEY") is False assert "No Value" in caplog.text def test_update_exception(caplog, settings): # set collection to ...
StarcoderdataPython
1788767
"Unit test for the game-board class" import unittest from .board import * def place_stone(board, color, x, y): board[x,y] = color class TestBoard(unittest.TestCase): def test_creation(self): width = 20 height = 40 board = Board(height, width) self.assertEqual(board.shape, (he...
StarcoderdataPython
154552
'''Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.''' from random import randint,sample from time import sleep print('-='*15) print('{:=^30}'.format('Jog...
StarcoderdataPython
136155
<filename>src/zveronics/__main__.py<gh_stars>0 import logging.config import pkg_resources import shutil from pathlib import Path import yaml from zveronics import serve_zveronics def load_cfg(): cfg_dir = Path.home() / '.config' / 'zveronics' cfg_dir.mkdir(parents=True, exist_ok=True) loggi...
StarcoderdataPython
4828657
<filename>global-ip-pool/global-ip-pool-functions.py # Modules import import requests from requests.auth import HTTPBasicAuth import time # Disable SSL warnings. Not needed in production environments with valid certificates import urllib3 urllib3.disable_warnings() # Authentication BASE_URL = 'https://<IP ADDRESS or ...
StarcoderdataPython
166951
<reponame>johnscancella/open-oni<gh_stars>0 import logging from django.core.management.base import BaseCommand from core.management.commands import configure_logging from core.solr_index import index_titles configure_logging("index_titles_logging.config", "index_titles.log") _logger = logging.getLogger(__name__...
StarcoderdataPython
1626695
<filename>sleeper_ff_bot/slack.py import requests from bot_interface import BotInterface class Slack(BotInterface): def __init__(self, webhook): self.webhook = webhook def send_message(self, message): requests.post(self.webhook, json={"text": message})
StarcoderdataPython