id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1694763
import logging import sonrai.platform.aws.arn def run(ctx): iam_client = ctx.get_client().get('iam') # Get role name resource_arn = sonrai.platform.aws.arn.parse(ctx.resource_id) role_name = resource_arn \ .assert_service("iam") \ .assert_type("role") \ .name # https://d...
StarcoderdataPython
1640920
import os import sys import json import logging from github import Github from typing import Any, Dict, List, Mapping, Optional import reconcile.openshift_base as ob from reconcile.utils import helm from reconcile import queries from reconcile.status import ExitCodes from reconcile.utils.oc import OCDeprecated, OC_M...
StarcoderdataPython
1679454
<gh_stars>1-10 """Collection on GDB commands useful for low-level debugging, aimed at bringing debug.exe flavor into GDB command line interface. """ import sys import gdb if sys.version_info < (3,0,0): gdb.write("Warning: Janitor expects Python version >= 3.0.0\n"); gdb_version = gdb.VERSION.split('.') if int(gd...
StarcoderdataPython
1743346
#41) Pandigital prime #We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. #What is the largest n-digit pandigital prime that exists? #%% Solution def is_pandigital(x): return sorted(str(x)) == list('1...
StarcoderdataPython
89283
<filename>pyugrid/test/test_save_as_netcdf.py #!/usr/bin/env python """ tests for saving a UGrid in netcdf format designed to be run with pytest """ from __future__ import (absolute_import, division, print_function) import numpy as np import netCDF4 from pyugrid.ugrid import UGrid, UVar from pyugrid.test_examples ...
StarcoderdataPython
1720444
<gh_stars>1-10 import pygame from pygame import mixer from moviepy.editor import * def play_music(music_name): mixer.init() mixer.music.load(music_name) mixer.music.play() def set_volume_start(vol): mixer.music.set_volume(vol) def set_volume(vol): curr_vol = mixer.music.get_volume() # prin...
StarcoderdataPython
1601038
<gh_stars>0 import numpy as np from typing import List, Tuple def vectorize_1_hot(word: str, vocabulary: List[str]) -> np.array: return np.fromiter((w == word for w in vocabulary), dtype=int) def training_matrix(word_pairs: List[Tuple[str, str]], vocabulary: List[str]) -> Tuple[np.array, np.array]: in_word...
StarcoderdataPython
3274041
<reponame>yifeiren/vnpy-1.8 # encoding: UTF-8 import multiprocessing from time import sleep from datetime import datetime, time from vnpy.event import EventEngine2 from vnpy.trader.vtEvent import EVENT_LOG, EVENT_ERROR from vnpy.trader.vtEngine import MainEngine, LogEngine #from vnpy.trader.gateway import ctpGateway ...
StarcoderdataPython
3394286
# -*- coding: utf-8 -*- """minor2.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1actLRdpDfBgRyQ0yYrgH7LWB-CoU3O3w """ import numpy as np import pandas as pd from matplotlib import pyplot as plt import cv2 import os from PIL import Image from ke...
StarcoderdataPython
55312
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Bernoulli from src.models.nns import Decoder class ConvDecoder(nn.Module): def __init__(self, z_dim): super().__init__() self.z_dim = z_dim self.decoder = Decoder( 128, ...
StarcoderdataPython
3307709
<reponame>jkavan/highlite<filename>highlite.py #!/usr/bin/env python import sys import getopt import re from termcolor import colored # # You can freely customize the colors and/or styles if you like (though # the changes may be overwritten by the upgrade process). # # Available colors: # fore back # ---- ...
StarcoderdataPython
3219233
<filename>media.py import webbrowser class Movie(): """ This class provides a way to store movie related information""" VALID_RATINGS = ["G","PG","PG-13","R"] # Class variables are capitalized def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): # Self is object being created, can be n...
StarcoderdataPython
3292240
#!/usr/bin/env python2.7 # twitterwin.py by <NAME> http://raspi.tv/?p=5281 import tweepy import random # Consumer keys and access tokens, used for OAuth consumer_key = 'copy your consumer key here' consumer_secret = 'copy your consumer secret here' access_token = 'copy your access token here' access_token_secret = 'co...
StarcoderdataPython
1770922
#!/usr/bin/env python """ Module to launch and control running jobs. Contains job_controller, job, and inherited classes. A job_controller can create and manage multiple jobs. The worker or user-side code can issue and manage jobs using the launch, poll and kill functions. Job attributes are queried to determine stat...
StarcoderdataPython
3363538
<gh_stars>10-100 ''' Description: Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. empty() -- Return whether the stack is empty. Example: MyStack stack = new MyStack(); stack.push(1); st...
StarcoderdataPython
21877
<filename>DominantSparseEigenAD/tests/demos/2ndderivative.py<gh_stars>10-100 """ A small toy example demonstrating how the process of computing 1st derivative can be added to the original computation graph to produce an enlarged graph whose back-propagation yields the 2nd derivative. """ import torch x = torch.ran...
StarcoderdataPython
71852
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2014 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Google Factory Tool. This tool is intended to be used on factory assembly lines. It provides all of t...
StarcoderdataPython
3328508
from .base import * from .request import * from .response import *
StarcoderdataPython
3356118
#!/usr/bin/env mayapy # # Copyright 2022 Animal Logic # # 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 ...
StarcoderdataPython
90509
from collections import defaultdict from nertoolkit.geneontology.GeneOntology import GeneOntology from synonymes.Synonym import Synonym from synonymes.SynonymUtils import handleCommonExcludeWords from utils.idutils import dataDir, loadExludeWords, printToFile, speciesName2TaxID celloObo = GeneOntology(dataDir + "miRE...
StarcoderdataPython
1733244
<reponame>gammasky/cta-dc """ Make an HDU and observation index tables for the CTA 1DC dataset. Format is described here: http://gamma-astro-data-formats.readthedocs.io/en/latest/data_storage/index.html """ from collections import OrderedDict import logging from glob import glob from pathlib import Path import subproc...
StarcoderdataPython
1603918
from tkinter import * from tkinter.messagebox import * def label(parent, text_label, x=0, y=0): label_tables = Label(parent,text=text_label).grid(row=x, column=y) def text(parent, text, x=0, y=0, height=2, width=30): text_to_display = Text(parent,height=height, width=width) text_to_display.insert(...
StarcoderdataPython
4806177
<gh_stars>0 # Copyright (c) 2020 <NAME> <jan.vrany (a) fit.cvut.cz> # # 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, co...
StarcoderdataPython
165471
<reponame>WebCampZg/conference-web # Generated by Django 2.1.7 on 2019-03-02 14:05 from django.db import migrations def populate_applicants(apps, schema_editor): Talk = apps.get_model("talks", "Talk") for talk in Talk.objects.all(): talk.applicants.add(talk.application.applicant) if talk.co_p...
StarcoderdataPython
3312955
<filename>test/unit/api/response/response_type/test_question_answering_phase_response.py import unittest from unittest.mock import patch, call from src.api.response.response_tag import ResponseTag from src.api.response.response_type.question_answering_phase_response import QuestionAnsweringPhaseResponse class TestQu...
StarcoderdataPython
3382307
<filename>freeAgents.py<gh_stars>0 import time import dataLoader from itertools import combinations positions = dataLoader.loadData("CrowdsourcingResults.csv") dataLoader.printPositions(positions) print "" print "" bold = lambda val: ("*" + str(val) + "*") def getHighestKey(positions, pos, key, usedPlayers=[]): be...
StarcoderdataPython
135544
import os from uuid import getnode as get_mac APP_PATH = os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir)) LIB_PATH = os.path.join(APP_PATH, "robot") DATA_PATH = os.path.join(APP_PATH, "static") TEMP_PATH = os.path.join(APP_PATH, "temp") OUTFILES_PATH = os.path.jo...
StarcoderdataPython
26114
import threading import traceback import logging import requests from json.decoder import JSONDecodeError from ping3 import ping logging.basicConfig(level=logging.INFO) GATEWAY_IP = "192.168.100.1" STATIC_IP_MIN = 200 STATIC_IP_MAX = 254 lastDot = GATEWAY_IP.rfind(".") ipAddressBase = GATEWAY_IP[0:lastDot+1] threadL...
StarcoderdataPython
61055
<gh_stars>1-10 #!/usr/bin/env python import time def level3(): while True: level3="level3" time.sleep(1) def level2(): level3() def level1(): level2() if __name__ == '__main__': level1()
StarcoderdataPython
4806926
""" File: WfSchemaMap.py A data class containing schema definitions for WF Database. __author__ = "<NAME>" __email__ = "<EMAIL>" __version__ = "V0.01" __Date__ = "April 21, 2010" """ class WfSchemaMap(object): _schemaMap = { "DEPOSITION": { "ATTRIBUTES": { ...
StarcoderdataPython
49096
from ..api import _v1 from pathlib import Path from app.error import Error import pandas as pd from app.components._data import dataframeHandler import numpy as np from sklearn.impute import KNNImputer from sklearn import preprocessing # ** ALL CONTENT COMENTED BETWEEN ASTERISCS MUST BE EDITED ** # ** Set the plugin ...
StarcoderdataPython
3359431
<reponame>aisk/ironpython3 # Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. # # Copyright (c) <NAME>. # import os import unittest import zlib from iptest import...
StarcoderdataPython
3219939
from pcfg import PCFG from collections import deque import time def dfs(G : PCFG): ''' A generator that enumerates all programs using a DFS. ''' # We need to reverse the rules: new_rules = {} for S in G.rules: new_rules[S] = {} sorted_derivation_list = sorted( G....
StarcoderdataPython
4828744
from __future__ import absolute_import # Django verions 1.6 and worse don't have the "apps" package so we have to mock # it up when its not available try: from django.apps import AppConfig, apps is_installed = apps.is_installed except ImportError: class AppConfig: pass def is_installed(dotted_...
StarcoderdataPython
3309207
<reponame>baklanovp/pystella import numpy as np import unittest from scipy.optimize import curve_fit import pylab as plt import pystella.rf.rad_func as rf import pystella.rf.spectrum as spectrum __author__ = 'bakl' class TestSpectrumFitting(unittest.TestCase): def setUp(self): nf = 100 start, e...
StarcoderdataPython
1637799
<reponame>Dodo33/alchemist-lib<filename>alchemist_lib/populate/bittrexpopulate.py from .populate import PopulateBaseClass from ..datafeed import BittrexDataFeed from ..database.asset import Asset from ..database.instrument import Instrument from ..database.exchange import Exchange from .. import utils class Bittr...
StarcoderdataPython
1754050
<filename>main.py import os import sys from PySide2 import QtWidgets, QtCore, QtGui class Window(QtWidgets.QWidget): def __init__(self): super().__init__() # 隐藏任务栏|去掉边框|顶层显示 self.setWindowFlags(QtCore.Qt.Tool | QtCore.Qt.X11BypassWindowManagerHint | Qt...
StarcoderdataPython
1772940
<gh_stars>1-10 """Functions to write output.""" # Copyright 2020-2022 Blue Brain Project / EPFL # 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...
StarcoderdataPython
1699463
<filename>flow/target.py # coding: utf-8 import json from .base import Base from log import Log from setting import RecordsStatus, MAX_SWIPE_DOWN_COUNT from exception import ValidationError logger = Log.logger(__file__) class TARGETModel(Base): def __init__(self, driver): super().__init__(driver) ...
StarcoderdataPython
3362173
<reponame>nxtlo/Tsujigiri # -*- cofing: utf-8 -*- # MIT License # # Copyright (c) 2021 - Present nxtlo # # 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...
StarcoderdataPython
3340256
<reponame>BitMask-Technologies/route-lift-api<filename>routelift_api/message_templates/routers.py from message_templates.views import (create_message_settings, create_message_template, delete_message_settings, delete_message_template, get_all_mes...
StarcoderdataPython
1726759
<filename>Cracking_the_Coding_Interview/20_1_custom_add.py #!/usr/bin/env python """ Write a function that adds two numbers -- but no arithmetic operators can be used. """ def sum_add(first, second): """Kind of cheating to use Python's sum function.""" return sum([first, second]) def binary_add(first, secon...
StarcoderdataPython
4831189
import pytest import mock import numpy as np import awkward as awk from zinv.utils.AwkwardOps import ( get_nth_object, get_nth_sorted_object_indices, get_attr_for_min_ref, jagged_prod, ) @pytest.mark.parametrize("array,id,size,out", ([ awk.JaggedArray.fromiter([[0, 1, 2], [3, 4], [5, 6, 7, 8]]), ...
StarcoderdataPython
1713988
import glob import json import itertools import numpy as np import tifffile import zarr from numcodecs import Blosc import os import tqdm """ Default chunk size is (64, 64, 64) """ class ZarrStack: def __init__(self, src, dest, compressor=None): """ :param src: glob for tiffs or a zarr store ...
StarcoderdataPython
86499
#!/usr/bin/env python # Copyright [2010] [Anso Labs, LLC] # # 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 requi...
StarcoderdataPython
1672580
<reponame>artemrys/poetry from typing import Dict from typing import List import pytest from poetry.core.packages.package import Package from poetry.factory import Factory from poetry.utils.extras import get_extra_package_names _PACKAGE_FOO = Package("foo", "0.1.0") _PACKAGE_SPAM = Package("spam", "0.2.0") _PACKAG...
StarcoderdataPython
1657333
from django.apps import AppConfig class TodoApiConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'todo_api'
StarcoderdataPython
4810487
#!/usr/bin/env python import sys, os, cmd class CLI(cmd.Cmd): def __init__(self, fh): #super(CLI, self).__init__() cmd.Cmd.__init__(self) self.fh = fh self.prompt = '> ' def do_send(self, *args): line = ' '.join(args) fh.write(line + '\n') fh.flush() print("Sent [{}]".format(line)) def help_send(...
StarcoderdataPython
88382
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest def raise_error(*args, **kwds): print args, kwds raise ValueError('Invalid value:' + str(args) + str(kwds)) class ExceptionTest(unittest.TestCase): def testTrapLocally(self): try: raise_error('a', b='c') except Value...
StarcoderdataPython
3213152
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 31 16:46:12 2020 @author: skyjones """ import os import re import shutil import sys import pandas as pd from glob import glob import nibabel as nib import numpy as np import matplotlib.pyplot as plt from scipy import stats from sklearn.ensemble im...
StarcoderdataPython
3239867
<reponame>huykingsofm/FileTransmitter<filename>src/sft/qsft/server.py<gh_stars>1-10 import os from hks_pylib.logger import Display from hks_pylib.logger.standard import StdUsers from hks_pylib.cryptography.ciphers.hkscipher import HKSCipher from hks_pylib.cryptography.ciphers.symmetrics import NoCipher from hks_pylib....
StarcoderdataPython
1795469
<gh_stars>0 # ***************************************************************************** # Copyright (c) 2019, Intel Corporation All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistribu...
StarcoderdataPython
3278571
<gh_stars>10-100 import gym import os import numpy as np from gym.wrappers import Monitor from gym import Wrapper from gym.envs.classic_control import AcrobotEnv, PendulumEnv class PickleableEnv(Wrapper): def __init__(self, env, env_name='acrobot', **kwargs): super(PickleableEnv, self).__init__(env) ...
StarcoderdataPython
3280544
<filename>code/branch_and_bound/time_opti.py<gh_stars>0 ########################################################################### # In main directory # Usage: '$ python code/branch_and_bound/time_opti.py' # # Check '$ python code/branch_and_bound/time_opti.py -h' for help #############################################...
StarcoderdataPython
3268946
<filename>src/error.py class Error(Exception): """Base class for exceptions in this module.""" pass class NoReader(Error): """Exception raised when no readers are plug to the computer. Attributes: message -- explanation of the error """ def __init__(self, message): self.messa...
StarcoderdataPython
3317613
#!/usr/bin/python -Wall # ================================================================ # <NAME> # <EMAIL> # 2008-02-05 # ================================================================ from __future__ import division # 1/2 = 0.5, not 0. import sackmat_m from math import * # -------------------------------------...
StarcoderdataPython
3314062
<reponame>GBrachetta/guillermo from django.contrib import admin from .models import Event # Register your models here. class EventAdmin(admin.ModelAdmin): """ Fields available in the admin, ordered by date """ list_display = ( "name", "venue", "programme", "date", ...
StarcoderdataPython
3326969
from __future__ import unicode_literals import multiprocessing, time from gensim.models import Word2Vec from gensim.models import Word2Vec as WV_model from gensim.models.word2vec import LineSentence from gensim import utils class MyCorpus(object): """An interator that yields sentences (lists of str).""" def...
StarcoderdataPython
3313246
<filename>freefall-archiver/freefall.py #!/usr/bin/env python3 # pylint: disable=C0111 import re from pathlib import Path from urllib.parse import urljoin from urllib.request import urlopen IMG_PER_PAGE = 10 CSS_VISIBLE = "visible" CSS_HIDDEN = "hidden" HTML_INDEX_ENTRY = """<a href="p%05d/index.html">%s - %s</a>"""...
StarcoderdataPython
3315624
# 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 # d...
StarcoderdataPython
3205010
print('olá mundo') name = input('Qual é o seu nome ') print('Seja bem vindo ', name)
StarcoderdataPython
2778
<filename>jp_doodle/quantity_forest.py from jp_doodle import doodle_files qf_js = doodle_files.vendor_path("js/quantity_forest.js") from jp_doodle import dual_canvas import jp_proxy_widget import os from subprocess import check_output import pprint if bytes != str: unicode = str def directory_usage(directory, eps...
StarcoderdataPython
3357439
import csv from pymongo import MongoClient import datetime client = MongoClient('mongodb://localhost:27017/') db = client['accounts'] collection = db['transactions'] transactions = db.transactions with open('trx.csv', 'r') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='"') for row i...
StarcoderdataPython
3203498
# Exercise 3.14 # Author: <NAME> from math import sqrt, exp, pi def gauss(x, m=0, s=1): gaussian = 1 / (sqrt(2 * pi) * s) * exp(-0.5 * ((x - m) / s) ** 2) return gaussian print '%8s' % 'x', for x in range(-5, 6): print '%9d' % x, print "\nGaussian", for x in range(-5, 6): print '%.7f' % gauss(x),
StarcoderdataPython
71376
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime # Create your models here. class Clarification(models.Model): cid = models.IntegerField() asker = models.TextField() question = models.TextField() reply = models.TextField() time = models.DateTimeField(default=datet...
StarcoderdataPython
38061
<gh_stars>0 # -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from unittest.mock import patch from datetime import datetime, date from dateutil.relativedelta import relativedelta from odoo import fields from odoo.tests.common import SavepointCase, new_test_user from od...
StarcoderdataPython
1761032
<gh_stars>1-10 from injector import inject from .default_execution_initializer import DefaultExecutionInitializer from .execution_initializer import ExecutionInitializer from .....dependency import IScoped from .....dependency.provider import ServiceProvider class ExecutionInitializerFactory(IScoped): @inject ...
StarcoderdataPython
4836025
<filename>Encryption/main.py from Utils import mtk from random import randint import math def getKey(): key = '0' x = 0 while '0' in str(key) or len(str(key)) < 7: a = mtk.getRandPrime() b = mtk.getRandPrime() c = mtk.getRandPrime() key = mtk.getRandPrime(0,a*b*c) # ...
StarcoderdataPython
3324792
<gh_stars>1-10 # %% import time #%% start1 = time.time() !python3 practice.py end1 = time.time() # %% start2 = time.time() !python3 practice_m.py end2 = time.time() # %% print(f'single-core execution time {end1 - start1}') print(f'multi-core execution time {end2 - start2}') # %%
StarcoderdataPython
1700796
<reponame>rgharris/libcloud<filename>docs/examples/compute/profitbricks/create_lan.py import os from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.PROFIT_BRICKS) # Get ProfitBricks credentials from environment variables pb_username = os.environ.get...
StarcoderdataPython
1624494
<gh_stars>0 import pandas as pd import numpy as np import matplotlib.pyplot as plt from types import SimpleNamespace class Perceptron: def __init__(self, algorithm="batch"): self._coef = [] self._n_feats = 0 self.algorithm = algorithm def fit(self, X, Y, theta, eta=None): sel...
StarcoderdataPython
110197
import time from googlesearch import search import urllib.request #one of my more major projects that I've worked on #url = "https://paintwithbob.com" #testing url opener with paintwithbob #f = urllib.request.urlopen(url) #test = f.read() #if ("Paint".encode("utf-8") in test): # print (test) searchterm = input("S...
StarcoderdataPython
97319
<reponame>torcolvin/rbtools """Unit tests for rbtools.utils.aliases.""" from __future__ import unicode_literals from rbtools.utils.aliases import replace_arguments from rbtools.utils.testbase import RBTestBase class AliasTests(RBTestBase): """Tests for rbtools.utils.aliases.""" def test_replace_arguments_b...
StarcoderdataPython
3210591
<reponame>minikdo/travelarchive2 # Generated by Django 2.1.4 on 2019-01-09 13:23 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('travels', '0011_auto_20190109_1422'), ] operations = [ migrations.AlterFie...
StarcoderdataPython
1779223
#!/usr/bin/python2.7 import os, sys, shutil, platform, time, json import install SUFFIX = ".so" COMPILER = "gcc" INCLUDE = [ ] LINK = [ "aria" ] DEFINE = [ ] CFLAGS = [ "-Wall", "-Wextra", "-c", "-fPIC", "-fno-strict-aliasing" "--std=c99", "-pedantic", "-O3" ] LFLAGS = [ "-shared", "-fPIC" ] EXTRA = [ ] if platfo...
StarcoderdataPython
1638486
# Import modules and libraries import torch from torch.utils.data import DataLoader import csv import pickle import numpy as np import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt import glob from skimage.io import imread import time import argparse from DeepSTORM3D.data_utils import generate_batc...
StarcoderdataPython
31200
<gh_stars>0 from django.db import models from django.utils import timezone from django.core.validators import MinLengthValidator from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) # Nickname is display name nickname = models.CharField( ...
StarcoderdataPython
172374
from rest_framework.exceptions import status, APIException class ConflictError(APIException): """ Base class for REST framework exceptions. Subclasses should provide `.status_code` and `.default_detail` properties. """ status_code = status.HTTP_409_CONFLICT default_detail = u'A database conflic...
StarcoderdataPython
1687578
<filename>icekit_events/management/commands/create_event_occurrences.py from django.core.management.base import NoArgsCommand from ...models import EventBase class Command(NoArgsCommand): help = 'Create missing repeat event occurrences' def handle_noargs(self, *args, **options): verbosity = int(opti...
StarcoderdataPython
3251576
#!/usr/bin/python3 from collections import namedtuple variable = 42 Point = namedtuple('Point', ['long', 'lat']) point = Point(long=3, lat=4) def function(number): return number ** 2 print(f'{variable}') print(f'Longitude: {point.long}, Latitude: {point.lat}') print(f'{function(variable)}')
StarcoderdataPython
3385460
<reponame>rpm1995/LeetCode class Solution: def canJump(self, nums: List[int]) -> bool: can_reach = [False for _ in range(len(nums))] can_reach[-1] = True cur_max = len(nums) - 1 for current in range(len(nums) - 2, -1, -1): if nums[current] + current >= len(nums) or num...
StarcoderdataPython
3289854
<reponame>Acidburn0zzz/dfvfs<filename>dfvfs/lib/fvde.py # -*- coding: utf-8 -*- """Helper function for FileVault Drive Encryption (FVDE) support.""" from __future__ import unicode_literals def FVDEVolumeOpen(fvde_volume, path_spec, file_object, key_chain): """Opens the FVDE volume using the path specification. ...
StarcoderdataPython
3261480
# terrascript/provider/hashicorp/consul.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:14:36 UTC) import terrascript class consul(terrascript.Provider): """terraform-provider-consul""" __description__ = "terraform-provider-consul" __namespace__ = "hashicorp" __name__ = "consul" ...
StarcoderdataPython
3349970
import os class Wordlist: words = [] def __init__(self, path, words=[]): if os.path.exists(path) and os.path.isfile(path): self.path = path else: raise FileNotFoundError(f"[!] - {path} cannot be found") if isinstance(words, list) and words: ...
StarcoderdataPython
3231946
<reponame>sUeharaE4/mlcomp from typing import List import os import ast from glob import glob import pathspec import pkg_resources from mlcomp.db.core import Session from mlcomp.utils.logging import create_logger from mlcomp.utils.io import read_lines _mapping = { 'cv2': 'opencv-python', 'sklearn': 'scikit-le...
StarcoderdataPython
34167
<filename>hw_asr/augmentations/wave_augmentations/__init__.py from hw_asr.augmentations.wave_augmentations.Gain import Gain from hw_asr.augmentations.wave_augmentations.ImpulseResponse import ImpulseResponse from hw_asr.augmentations.wave_augmentations.Noise import GaussianNoise from hw_asr.augmentations.wave_augmentat...
StarcoderdataPython
1630979
quote = """ Alright, but apart from the Sanitation, the Medicine, Education, Wine, Public Order, Irrigation, Roads, the Fresh-Water System, and Public Health, what have the Romans ever done for us? """ # Use a for loop and an if statement to print just the capitals in the quote above. for char in quote: if char.i...
StarcoderdataPython
138775
<filename>sql/tests/setup/dataloader/make_sqlite.py import os import subprocess import pandas as pd root_url = subprocess.check_output("git rev-parse --show-toplevel".split(" ")).decode("utf-8").strip() from sqlalchemy import create_engine, text from sqlalchemy import Column, Date, Integer, String from sqlalchemy.ext...
StarcoderdataPython
1736880
import logging from io import StringIO class Progress: """ IMPORTANT! Progress initialization is required to change job state into PROGRESS, so that it's execution will be shown in '/process' app handler. """ def __init__(self, total): self.stream = StringIO() self.handler = loggi...
StarcoderdataPython
1766230
from pathlib import Path import os #import dj_database_url BASE_DIR = Path(__file__).resolve(strict=True).parent.parent DEBUG = True ALLOWED_HOSTS = ['192.168.100.198','192.168.1.21','192.168.1.7','127.0.0.1','localhost'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ...
StarcoderdataPython
4819444
# -*- coding: utf-8 -*- # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2008-2020 German Aerospace Center (DLR) and others. # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www....
StarcoderdataPython
1639797
<filename>cvat/apps/tf_annotation/views.py # Copyright (C) 2018 Intel Corporation # # SPDX-License-Identifier: MIT import ast import datetime import threading import time from zipfile import ZipFile from django.http import HttpResponse, JsonResponse, HttpResponseBadRequest, QueryDict from django.core.exceptions import...
StarcoderdataPython
1640748
#!/usr/bin/python import subprocess from subprocess import PIPE def test_subprocess(): cmd = 'adb devices' #print(subprocess.call(cmd, shell=True)) #print(subprocess.check_output(["adb", "devices"])) std_out, std_err = subprocess.Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() #p...
StarcoderdataPython
133762
<gh_stars>0 #!/usr/bin/python ############################################### # This script computes char co-occurence within # alexa's top 1-million web domains. # The co-occurence counts, probability and # log(probability) and stored in a json doc. ############################################### import json import...
StarcoderdataPython
3311495
<filename>Borda_Guevara_Tissera_TP2/resolutions/knapsack.py from search import Problem import random class KnapsackState: # A KnapsackState represents the state of the knapsack in # a determinate moment in the knapsack problem # The form of the items in the knapsack is # (weight, value) def __init...
StarcoderdataPython
30694
# Generated by Django 2.2.10 on 2020-05-02 05:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('purchases', '0008_auto_20200430_1617'), ] operations = [ migrations.RenameField( model_name='itempurchase', old_name='suppl...
StarcoderdataPython
1632681
from CommonServerPython import * """ IMPORTS """ import requests import ast from datetime import datetime # disable insecure warnings requests.packages.urllib3.disable_warnings() # remove proxy if not set to true in params if not demisto.params().get("proxy"): del os.environ["HTTP_PROXY"] del os.environ["HTT...
StarcoderdataPython
146731
<gh_stars>0 import json import numpy as np class AbstractBenchmark: """ Abstract template for benchmark classes """ def __init__(self, config_path=None): """ Initialize benchmark class Parameters ------- config_path : str Path to load configuration...
StarcoderdataPython
1629335
<gh_stars>0 # Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ) # # 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/L...
StarcoderdataPython
53651
import datetime import os import uuid from os.path import join as opjoin from pathlib import Path import numpy as np import requests import yaml from celery.result import AsyncResult from django.db.models import Q from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from rest_framework import mi...
StarcoderdataPython