id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
77479
<reponame>hajime9652/observations from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.grunfeld1 import grunfeld1 def test_grunfeld1(): """Test module grunfeld1.py by downloading grunfeld1.csv a...
StarcoderdataPython
48243
<gh_stars>0 from yuntu.core.common.utils import loadMethod,loadMethodFromFile import itertools def loadTransform(transformDict): if transformDict is not None: if "path" in transformDict: return loadMethodFromFile(transformDict["path"],transformDict["method"]) else: return lo...
StarcoderdataPython
1768200
#!/usr/bin/env python import click import pandas as pd import numpy as np from os import mkdir from os.path import basename, join from functools import partial DATA_TYPES_NUMERIC = ('int', 'float') FINAL_LIST = [ 'study_id', 'host_scientific_name', 'latitude_deg', 'longitude_deg', 'envo_biome_3', 'empo...
StarcoderdataPython
143325
import json from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator apikey = os.environ['apikey'] url = os.environ['url'] authenticator = IAMAuthenticator('apikey') language_translator = LanguageTranslatorV3( version='2018-05-01', authenticator=authenticator ...
StarcoderdataPython
3241817
import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State from dash.exceptions import PreventUpdate import numpy as np from app import app from scripts.read_data import get_language layout = dbc.Nav([ dbc.DropdownMenu( [dbc.DropdownMenuI...
StarcoderdataPython
4834280
<reponame>urig/entropy<filename>entropylab/api/tests/test_plot.py from entropylab.api.plot import CirclePlotGenerator from plotly.graph_objects import Figure def test_circle_plot_plotly(): target = CirclePlotGenerator() figure = Figure() data = [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]] target.plot_plot...
StarcoderdataPython
1686151
<gh_stars>0 import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from django.conf import settings from .models import Email class EmailServer(object): def __init__(self): self.server = smtplib.SMTP('smtp.gmail.com', 587) self.server.starttls() ...
StarcoderdataPython
3326923
<reponame>GArmane/python-fastapi-hex-todo<gh_stars>10-100 from faker.providers import BaseProvider from faker import Faker from passlib.hash import argon2 fake = Faker() class PasswordHashProvider(BaseProvider): def password_hash(self) -> str: return str(argon2.hash(fake.pystr()))
StarcoderdataPython
1782226
# robothon06 # rasterise the shape in glyph "A" # and draw boxes in a new glyph named "A.silly" from robofab.world import CurrentFont, CurrentGlyph sourceGlyph = "a" f = CurrentFont() source = f[sourceGlyph] # find out how big the shape is from the glyph.box attribute xMin, yMin, xMax, yMax = source.box # create a...
StarcoderdataPython
125866
# -*- coding: utf-8 -*- from dataclasses import dataclass from pprint import pprint from serpyco import Serializer @dataclass class Point(object): x: float y: float serializer = Serializer(Point) pprint(serializer.json_schema()) pprint(serializer.load({"x": 3.14, "y": 1.5})) try: serializer.load({"x"...
StarcoderdataPython
1711301
<reponame>the-fridge/Python_Projects<gh_stars>1-10 ''' You need to install geopy first using pip3 install geopy ''' from geopy.geocoders import Nominatim # This project gives you the location of the city you # entered along with its latitude and longitude ''' For this program to work an internet connection is required ...
StarcoderdataPython
127660
import RPi.GPIO as GPIO import time import thread redled = 17 #Red LED connected to G17 redbtn = 16 # red button connected G16 GPIO.setmode(GPIO.BCM) # function to set up the LEDs GPIO.setup(redled, GPIO.OUT, initial = GPIO.LOW) #HIGH=1 LOW=0 GPIO.setup(redbtn, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) #HIGH=1 LOW=0 ...
StarcoderdataPython
1691123
<gh_stars>1-10 import threading NUM_THREAD = 10 printed = False def print_text(): print ("printed once") threads = [] for i in range (NUM_THREAD): t = threading.Thread (target=print_text) threads.append(t) t.start() for i in range (NUM_THREAD): threads[i].join()
StarcoderdataPython
1692520
from django.db import models from django.utils import timezone # Create your models here. class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' class Data(models.Model): name = f'{str(timezone...
StarcoderdataPython
62749
<filename>app/models/__init__.py from .base import Base from .user import User from .todolist import List from .card import Card
StarcoderdataPython
110879
from typing import Any, Union from unittest.mock import Mock import pystac class MockStacIO(pystac.StacIO): """Creates a mock that records StacIO calls for testing and allows clients to replace StacIO functionality, all within a context scope. """ def __init__(self) -> None: self.mock = Mock...
StarcoderdataPython
85647
<gh_stars>0 # From https://stackoverflow.com/a/49375740/827927 # import os, sys # sys.path.append(os.path.dirname(os.path.realpath(__file__)))
StarcoderdataPython
47683
''' .. moduleauthor:: <NAME> / estani This module manages the abstraction of a user providing thus all information about him/her that might be required anywhere else. ''' import pwd import os import sys from ConfigParser import SafeConfigParser as Config from evaluation_system.misc import config, utils from evaluation...
StarcoderdataPython
135046
import random from datetime import datetime random.seed(datetime.now()) class SoS(object): def __init__(self, CSs, environment): self.CSs = CSs self.environment = environment pass def run(self, tick): logs = [] random.shuffle(self.CSs) for CS in self.CSs: ...
StarcoderdataPython
149331
# Generated by Django 3.2.8 on 2021-10-25 01:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('itinerary', '0007_auto_20211025_1153'), ] operations = [ migrations.AlterField( model_name='activity', name='cost', ...
StarcoderdataPython
3365294
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.http import Http404 from django.views.decorators.csrf import ensure_csrf_cookie from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, redirect, HttpResponse, get_object_or_404 from django.template import...
StarcoderdataPython
1732536
<reponame>ZhichengHuang/Food-Project import torch import os from collections import Counter class feature_lib: def __init__(self,cfg): self.feature_lib_path= cfg.FEATURELIB.PATH self.lib = self.load_lib() # size 2048*n self.lib_feature = self.lib['feature'] self.lib_labe...
StarcoderdataPython
60252
<reponame>daumann/chronas-application from django.conf import settings from django.conf.urls.static import static from django.conf.urls.i18n import i18n_patterns from django.conf.urls import patterns, url, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from ...
StarcoderdataPython
1635139
from challenge import hint, enc from Crypto.Cipher import AES from Crypto.Util.Padding import unpad import hashlib iv = bytes.fromhex(enc['iv']) enc = bytes.fromhex(enc['enc']) key = ... sha1 = hashlib.sha1() sha1.update(str(key).encode('ascii')) aes_key = sha1.digest()[:16] cipher = AES.new(aes_key, AES.MODE_CBC...
StarcoderdataPython
1718559
<reponame>mrcrnkovich/stupidb """Top-level package for stupidb.""" import importlib.metadata from stupidb.aggregation import Window # noqa: F401 from stupidb.api import * # noqa: F401,F403 __version__ = importlib.metadata.version(__name__) del importlib
StarcoderdataPython
83375
with open('students_log.txt', 'r', encoding='utf-8') as f: for row in f.read().splitlines(): last_name, first_name, patronymic, row_marks = row.split(maxsplit=3) patronymic = patronymic.strip(',') # marks = list(map(int, map(str.strip, row_marks.split(',')))) # ' 5' -> map str.strip(...
StarcoderdataPython
3245821
<reponame>rakati/ppci-mirror import unittest from test_asm import AsmTestCaseBase class Sse1TestCase(AsmTestCaseBase): """ Checks sse1 instructions """ march = 'x86_64' def test_movss(self): """ Test move scalar single-fp values """ self.feed('movss xmm4, xmm6') self.feed('movss ...
StarcoderdataPython
3362945
from __future__ import print_function import numpy as np import pinocchio as pin from numpy.testing import assert_almost_equal as assertApprox from sot_talos_balance.simple_zmp_estimator import SimpleZmpEstimator pin.switchToNumpyMatrix() # --- Create estimator print("--- Create estimator ---") estimator = Simple...
StarcoderdataPython
77392
""" A simple wrapper to invoke pbundler without needing to install it, making debugging easier in an IDE """ import sys from pbundler import PBCli def main(): sys.exit(PBCli().run(sys.argv)) if __name__ == '__main__': main()
StarcoderdataPython
4456
<filename>examples/django_mongoengine/bike/models.py from mongoengine import Document from mongoengine.fields import ( FloatField, StringField, ListField, URLField, ObjectIdField, ) class Shop(Document): meta = {"collection": "shop"} ID = ObjectIdField() name = StringField() addres...
StarcoderdataPython
3255833
<gh_stars>1-10 # Generated by Django 2.2.13 on 2020-11-17 16:18 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0076_deadline_types'), ] operations = [ migrations.CreateModel( nam...
StarcoderdataPython
3240097
""" A class to maintain model data about Lobes (collections of Nodes) """ import bisect from helper import centerOfMass, cartesian2Polar class Lobe: def __init__(self, uID, name): """ Lobe constructor. Args: uID: The unique ID string of this lobe name: The string name of this lobe. ""...
StarcoderdataPython
3346870
<reponame>attardi/iwpt-shared-task-2020 # -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-03-14 17:06 from typing import Union, Tuple import tensorflow as tf from edparser.common.structure import SerializableDict from edparser.common.transform_tf import Transform from edparser.common.vocab_tf import VocabTF from e...
StarcoderdataPython
3277570
# Load movies from HDFS, generate embeddings of movie titles with BERT, then save embeddings to # redis and HDFS. import subprocess from time import localtime, strftime import numpy as np import redis import tensorflow_hub as hub import tensorflow_text as text import os HDFS_PATH_MOVIE_EMBEDDINGS="...
StarcoderdataPython
3206839
<reponame>lucasdavid/edge def cost(g): """Return the cost of a given path or circuit represented by a nx.Graph object. :param g: the graph object which represents the path or circuit. :return: the float cost of transversing the path. """ return sum((d['weight'] for _, _, d in g.edges(data=True)))
StarcoderdataPython
1713471
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.EGL import _types as _cs # End users want this... from OpenGL.raw.EGL._types import * from OpenGL.raw.EGL import _errors from OpenGL.constant import Constant as _C import ctype...
StarcoderdataPython
4839566
#!/usr/bin/env python """ Advent of Code 2017: Day 12 Part 1 https://adventofcode.com/2017/day/12 """ import sys, re # Define a Node class to store tree information (parents and children), and to implement union-find class Node: def __init__(self): self.parent = self self.children = [] # Find this node's ...
StarcoderdataPython
93756
<gh_stars>0 #HN uses the https://news.ycombinator.com/front?day={yyyy}-{mm}-{dd} format for top posts of that day import requests from bs4 import BeautifulSoup as bs from datetime import date, datetime, timedelta import pandas as pd import re import html2text import numpy as np class Scrape(object): def __init_...
StarcoderdataPython
1714386
<filename>VQA/Stacked Attention/extract_features.py """ Created on Tue May 08 19:06:33 2018 author: <NAME> """ from keras.applications.vgg19 import VGG19, preprocess_input from keras.models import Model from keras.layers import Input from keras.optimizers import SGD import cv2, numpy as np import h5py import json from...
StarcoderdataPython
113549
from types import TracebackType from typing import Dict, Optional, Type, Union try: from typing import Literal except ImportError: from typing_extensions import Literal from aiohttp.client import ClientSession from warnings import warn from neispy.error import ExceptionsMapping class NeispyRequest: BASE...
StarcoderdataPython
1773561
<reponame>HtrTech/SnapMap-OSINT #!/usr/bin/env python3 # Inspired by https://github.com/HtrTech/SnapMap/ & https://github.com/HtrTech/snap-map-private-api/ # Created by <NAME> # # import requests, time, argparse, os, json from geopy.geocoders import Nominatim def parse_args(): parser = argparse.ArgumentParser(...
StarcoderdataPython
3375560
""" The experiment MAIN for Communities and Crime. * Run the file and the CC experiments will complete * See compas experiment file for more details on how to read results. """ import warnings warnings.filterwarnings('ignore') from adversarial_models import * from utils import * from get_data import * from sklear...
StarcoderdataPython
1648626
<filename>core/models.py from django.db import models class Post(models.Model): name = models.CharField(max_length=43) body = models.TextField() def __str__(self): return self.name
StarcoderdataPython
182663
<reponame>jkennedyvz/DeepFaceLive from collections import Iterable class AAxes(Iterable): __slots__ = ['axes','ndim','_inversed'] def __init__(self, axes, shape_ndim=None): """ Constructs AAxes from user argument arguments axes AAxes Int ...
StarcoderdataPython
3382897
import logging from concurrent.futures import ThreadPoolExecutor from os import listdir from os import path as osp import netifaces import defaults import errors import utils.async from system.drive_manager import DRIVE_MANAGER from API.handlers import APIHandler from tornado.concurrent import run_on_executor from tra...
StarcoderdataPython
3294204
<filename>hood/urls.py from django.conf.urls import url,include from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns=[ url('^$',views.index,name = 'index'), url(r'^profile/$',views.profile,name='profile'), url(r'^edit/profile/$',views.edit_profile,nam...
StarcoderdataPython
4839136
# Import required libraries import argparse import pathlib import dash import dash_core_components as dcc import dash_html_components as html import dash_table import pandas as pd import plotly.express as px import psycopg2 from dash.dash import no_update from dash.dependencies import Input, Output from dash.exception...
StarcoderdataPython
13227
<gh_stars>1-10 from pygame import image class ShowFaces(): def __init__(self, filePath, colour = (0, 0, 0), posX = 0, posY = 100, resourcePath = ""): self.filePath = filePath self.colour = colour self.posX = posX self.posY = posY self.resourcePath = resourcePath self.image = image.load(self.resourcePath +...
StarcoderdataPython
3344868
""" This submodule contains formatting utilities and formatters which will work only on Python 3.6+. There is no inherent reasons why it would not work on earlier version of Python, it just makes use of features that are 3.6 only – Like f-strings – to make the code more readable. Feel free to send patches that makes it...
StarcoderdataPython
1661771
from django.urls import path from . import views urlpatterns = [ path('<str:name>', views.xcl, name = "xcl") ]
StarcoderdataPython
159180
<reponame>firstprojectfor/FPF_python import sys import pygame from pygame.sprite import Group from game.alien import Alien from game.bullet import Bullet from game.settings import Settings from game.ship import Ship def check_event(setting: Settings, screen, ship: Ship, bullets: Group): """检查事件""" for event...
StarcoderdataPython
3240386
# Generated by Django 3.2.8 on 2021-10-21 15:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sentirsebien', '0001_initial'), ] operations = [ migrations.CreateModel( name='DataUNFV', fields=[ (...
StarcoderdataPython
1638110
# -*- coding: utf-8 -*- import sys import subprocess # # Exceptions. # class ShellError(Exception): pass width = lambda: int(subprocess.check_output(['tput', 'cols'])) height = lambda: int(subprocess.check_output(['tput', 'lines'])) # # Shell tables. # class Table: def __init__(self, output_format='text', ...
StarcoderdataPython
3394243
<reponame>andrewmeltzer/picframe<filename>src/picframe_blackout.py # Project Picframe # Copyright 2021, <NAME>, Inc. # # 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, incl...
StarcoderdataPython
3294014
<reponame>HiAwesome/dive-into-python3-practice<filename>c02/p053_all_thing_is_object.py import c02.p044_humansize as humansize print(humansize.approximate_size(4096, True)) print() print(humansize.approximate_size.__doc__) """ 4.0 KiB Convert a file size to human-readable form. Keyword arguments: size -- fi...
StarcoderdataPython
3330012
<reponame>m00nb0w/oghma #!/bin/python3 import sys grid = [] for grid_i in range(20): grid_t = [int(grid_temp) for grid_temp in input().strip().split(' ')] grid.append(grid_t) dy = [1, 1, 1, 0] dx = [-1, 0, 1, 1] m = len(grid) n = len(grid[0]) res = 0 for i in range(0, m): for j in range(0, n): fo...
StarcoderdataPython
1758575
<gh_stars>1-10 from pathlib import Path from ...graphs import Graph016 from ...utils import BaseGraphSystemTester from ....engine_input import ValidPrefix from ....engine import BGPSimpleAS class Test027BadDiagram(BaseGraphSystemTester): GraphInfoCls = Graph016 EngineInputCls = ValidPrefix base_dir = Pa...
StarcoderdataPython
1783494
import os, sys import math import random from .switch import _Switch from .node import _Node sys.path.insert(0, os.path.basename(__file__) + os.sep + '..') from utils import util # TODO: latent bug class _Cluster(object): def __init__(self, num_switch=0, num_node_p_switch=0, num_gpu_p_node=0, num_cpu_p_node=0, me...
StarcoderdataPython
5500
# Copyright 2009-present MongoDB, 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 agreed to in wri...
StarcoderdataPython
4814396
<gh_stars>0 from myflaskbackend import my_app import pytest import json from pathlib import Path import os # fixture function to only be invoked once per test module (the default is to invoke once per test function) @pytest.fixture(scope='module') def client(): my_app.app.config['TESTING'] = True with my_app....
StarcoderdataPython
99216
<gh_stars>0 # coding: utf-8 # In[19]: import pandas as pd dat = pd.read_csv("2015_City.csv", skiprows = 4, encoding = 'iso-8859-1') # In[20]: dat.head() # In[21]: from matplotlib import pyplot as plt plt.style.use('ggplot') # In[22]: plt.hist(dat["Total Wages"], bins = 50) plt.xlabel("Wages") plt.ylabel("L...
StarcoderdataPython
3393828
from IcrisCrawler import settings import requests from urllib.parse import urljoin fps_api = urljoin(settings.FP_SERVER_URL, '/api/proxy/') anonymity = settings.FP_SERVER_PROXY_ANONYMITY def fetch_proxy(scheme, count): """ Get proxy from fpserver by given scheme. :scheme: `str` proxy protocol :retu...
StarcoderdataPython
3230312
import os def main(): try: while True: while True: mode = input('Mode: ').lower() if 'search'.startswith(mode): mode = False break elif 'destroy'.startswith(mode): mode = True ...
StarcoderdataPython
1681424
<filename>crabageprediction/venv/Lib/site-packages/fontTools/colorLib/geometry.py<gh_stars>1-10 """Helpers for manipulating 2D points and vectors in COLR table.""" from math import copysign, cos, hypot, isclose, pi from fontTools.misc.roundTools import otRound def _vector_between(origin, target): return (target[...
StarcoderdataPython
3321352
import numpy as np class Mass: def __init__(self, model): """ Defines the ShellProperties object. Parameters ---------- model : BDF the BDF object """ self.model = model self.n = 0 self.conm1 = model.conm1 self.conm2 = mode...
StarcoderdataPython
3361828
import rospy import serial from ros_waspmote_reader.msg import wasp ### $ sudo usermod -a -G dialout $USER class co2_reader(): def __init__(self, frame_id = 'gas_sensor', serial_port = '/dev/ttyUSB0', serial_baudrate = 115200 ): self.pub = rospy.Publisher('espeleo_gas_pub', wasp, queue_siz...
StarcoderdataPython
3378204
import tkinter import tkinter.messagebox from PIL import Image, ImageTk from scripts import General, Warnings, InputConstraints, Parameters, Constants, Log from scripts.frontend import Navigation, ClientConnection from scripts.frontend.custom_widgets import CustomButtons, CustomLabels from scripts.frontend.custom_wid...
StarcoderdataPython
1685979
<filename>tb/test.py from cocotb_test import simulator from os import system, getcwd, environ import pytest from contextlib import contextmanager insts = environ.get("INSTS", "rv32ui-p-simple").split() if "SIM" not in environ: environ["SIM"] = "verilator" includes = [ "./build/ousia_0/src/verilog-arbiter_0-r...
StarcoderdataPython
3316785
from typing import List from guet.commands.command import Command from guet.commands.decorators.command_factory_decorator import CommandFactoryDecorator from guet.commands.decorators.start_required_decorator import StartRequiredDecorator from guet.settings.settings import Settings class LocalDecorator(CommandFactory...
StarcoderdataPython
1781014
<filename>codegen/snake2pascal.py import re import typing def _upper_zero_group(match: typing.Match) -> str: return match.group("let").upper() def snake2pascal(name: str) -> str: return re.sub(r"(?:_|\A)(?P<let>[a-z])", _upper_zero_group, name)
StarcoderdataPython
3252103
import pytest from django.contrib.auth.hashers import make_password from django.contrib.auth.models import Group, Permission from rest_framework.test import APIClient from trucks.models import PaymentMethod from .factories import PaymentMethodFactory, UserFactory GROUP = "Owners" MODELS = ["Truck", "Image", "Locatio...
StarcoderdataPython
4829009
from flask import Flask from flask import request import json import requests import hashlib as hasher import datetime as date node = Flask(__name__) # Define what a Snakecoin block is class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp se...
StarcoderdataPython
1790835
<filename>game03/2_1_timer.py<gh_stars>1-10 import pgzrun from random import randint from time import time TITLE = "🐍🐍 Connetti i satelliti 🐍🐍" WIDTH = 800 HEIGHT = 600 satelliti = [] linee = [] indice_prossimo_satellite = 0 # Variabili per la gestione del tempo tempo_iniziale = 0 tempo_totale = 0 tempo_finale =...
StarcoderdataPython
165770
# The MIT License (MIT) # # Copyright (c) 2014 <NAME> <<EMAIL>> # Copyright (c) 2015 <NAME> <<EMAIL>> # # 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 withou...
StarcoderdataPython
135586
import numpy as np import pandas as pd class StrategyOptimiser: def __init__(self, fitness_function, n_generations, generation_size, n_genes, gene_ranges, mutation_probability, gene_mutation_probability, n_select_best): """ Initializes a genetic algorithm with the given parameters. Par...
StarcoderdataPython
3263499
<reponame>ourresearch/journalsdb import pandas as pd import pytest from ingest.open_access import import_open_access from models.usage import OpenAccess from views import app test_data = { "issn_l": ["2291-5222"], "title": ["Tropical Parasitology"], "year": ["2010"], "num_dois": ["10"], "num_open...
StarcoderdataPython
1725705
<gh_stars>1-10 import numpy as np import numba import pyfftw from scipy import ndimage as scnd from ..proc import sobel_canny as sc from ..util import gauss_utils as gt from ..util import image_utils as iu @numba.jit def resize_rotate(original_4D, final_size, rotangle, ...
StarcoderdataPython
3372917
from typing import List from .BaseDoc import BaseDoc from random import sample class CPF(BaseDoc): def __init__(self, repeated_digits: bool = False): self.digits = list(range(10)) self.repeated_digits = repeated_digits def validate(self, doc: str = '') -> bool: doc = list(self._only_d...
StarcoderdataPython
9081
<reponame>IBCNServices/StardogStreamReasoning import threading class RWLock: """Synchronization object used in a solution of so-called second readers-writers problem. In this problem, many readers can simultaneously access a share, and a writer has an exclusive access to this share. Additionally, the following con...
StarcoderdataPython
1750181
<filename>test/fail_debugger.py<gh_stars>0 import pdb pdb.set_trace() import ipdb import pydevd pydevd.set_trace()
StarcoderdataPython
1621328
<gh_stars>0 """ DESAFIO 077: Contando Vogais em Tupla Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais. """ palavras = ('aprender', 'programar', 'linguagem', 'python', 'curso', 'gratis', 'estudar', 'pra...
StarcoderdataPython
9196
#!/usr/bin/env python3 """ Base-Client Class This is the parent-class of all client-classes and holds properties and functions they all depend on. Author: <NAME> """ import src.util.debugger as Debugger import src.util.configmaker as configmaker class BaseClient(object): """Base-Client Class""" def __init__(...
StarcoderdataPython
3253928
from django.urls import re_path from . import views urlpatterns = [ re_path(r'areas$', views.AreasView.as_view()), re_path(r'houses/index$', views.HousesIndexView.as_view()), re_path(r'houses/(?P<house_id>\d+)/images$', views.HousesImageView.as_view()), re_path(r'houses/(?P<pk>\d+)$', views.HousesInfoV...
StarcoderdataPython
3291572
<gh_stars>0 import csv import cv2 import os if not os.path.exists('./dataset'): os.makedirs('./dataset') name = input("enter your name") roll = input("enter your id") row = [name,roll,'A'] l =[] for root ,dire,filenames in os.walk('dataset'): for names in dire: l.append(int(names)) folder = str(l[-...
StarcoderdataPython
31682
<reponame>thisisshi/sdk import json import pandas def output_sanitization(path_to_excel, path_to_out_json=None): ''' Find the Success percentage of each output report ''' path = path_to_excel out_obj = [] excel_obj = [] # Output Sanitization wb = pandas.read_excel(path, engine='openpyxl') ...
StarcoderdataPython
4818460
<reponame>jihunroh/ProjectEuler-Python from ProjectEulerCommons.Base import * from calendar import monthrange Answer( quantify( [(year, month) for year in range(1901, 2000 + 1) for month in range(1, 12 + 1)], lambda year_month_pair: monthrange(year_month_pair[0], year_month_pair[1])[0] == 6 ) )...
StarcoderdataPython
4815303
import json from django.shortcuts import render from django.http import JsonResponse, HttpResponseServerError from . import models def get_games(request): games = models.Game.objects.all().order_by("-score").values() gamelist = list(games) return JsonResponse(gamelist, safe=False) def post_logs(request)...
StarcoderdataPython
3319311
<reponame>ayemos/tatami<filename>tatami/downloaders/s3_downloader.py import six import os from multiprocessing import Process from boto3 import resource, client from tatami import downloader class S3Downloader(downloader.Downloader): def __init__(self, bucket_name, root_prefix, data_directory_path='./tmp'): ...
StarcoderdataPython
1762896
import pytest from ...product.models import ProductType from ..utils import associate_attribute_values_to_instance def test_associate_attribute_to_non_product_instance(color_attribute): instance = ProductType() attribute = color_attribute value = color_attribute.values.first() with pytest.raises(Ass...
StarcoderdataPython
121195
<filename>db_handler.py<gh_stars>0 import psycopg2 def get_artist_details(artist_name): print("entered") conn = psycopg2.connect(database="songspedia", user="saumya", password="<PASSWORD>", host="127.0.0.1") cur = conn.cursor() query = '''WITH ARTISTID AS (SELECT ID FROM ...
StarcoderdataPython
3335405
<gh_stars>0 from datetime import datetime import json import requests from requests.exceptions import ReadTimeout from websocket import create_connection from websocket._exceptions import WebSocketTimeoutException from pysense.config import yamlcfg API_URL = yamlcfg.sense.api.url API_TIMEOUT = yamlcfg.sense.api.tim...
StarcoderdataPython
3322261
import os.path as osp import json import requests import time import numpy as np import io from PIL import Image import logging import torch import random logger = logging.getLogger('global') from dataset_base import BaseDataset from datasets import build_transform class ImageNetDataset(BaseDataset): """ Im...
StarcoderdataPython
1608363
import random import numpy as np import skimage.io as sio import skimage.color as sc import skimage.transform as st import torch from torchvision import transforms def get_patch(haze_tensor, A_tensor, t_tensor, latent_tensor, patch_size): assert haze_tensor.shape[1:] == A_tensor.shape[1:] assert haze_tensor....
StarcoderdataPython
174425
from typing import List, Tuple, Optional import os import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib import cm import matplotlib.colors as mplcolors from ramachandran.io import read_residue_torsion_collection_from_file def get...
StarcoderdataPython
3352023
<reponame>Thalizin06/Painel-S # Imports import discord from discord.ext import commands from discord.ext.commands import Bot from discord.ext import commands import asyncio import os import random from decouple import config import json import requests os.system('cls' if os.name == 'nt' else 'clear') RED = "\033[1;3...
StarcoderdataPython
1726449
#!/usr/bin/env python import os import boto from boto.s3.key import Key home = os.environ['HOME'] s3 = boto.connect_s3(host='localhost', port=10001, is_secure=False) b = s3.get_bucket('mocking') k_img = Key(b) k_img.key = 'Pictures/django.jpg' k_img.set_contents_from_filename('%s/Pictures/django.jpg' % home)
StarcoderdataPython
193730
import time from sqlalchemy import Column, Integer, String, ForeignKey from anarcho import db from sqlalchemy.orm import relationship, backref class Build(db.Model): __tablename__ = "builds" id = Column('build_id', Integer, primary_key=True) app_key = Column('app_key', String, ForeignKey('apps.app_key'))...
StarcoderdataPython
156249
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT from typing import Optional import github class GithubAuthentication: """ Represents a token manager for authentication via GitHub App. """ def get_token(self, namespace: str, repo: str) -> str: """ Get a...
StarcoderdataPython
3330107
<gh_stars>0 # -*- coding: utf-8 -*- """ @Project Name macro_economic @File Name: money_supply @Software: PyCharm @Time: 2018/6/9 14:19 @Author: taosheng @contact: <EMAIL> @version: 1.0 @Description:  """ import datetime import numpy as np import pandas as pd import tushare ...
StarcoderdataPython
75868
from unittest import TestCase from common import * from sc import * from sc_tests.test_utils import * class TestScSet(TestCase): def test_sc_set(self): ctx = TestScSet.MemoryCtx() addr1 = ctx.CreateNode(ScType.NodeConst) addr2 = ctx.CreateNode(ScType.Node) addr3 = ctx.CreateNode(ScType.Node) ...
StarcoderdataPython