id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3372980
# Generated by Django 3.0.3 on 2020-05-05 08:44 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('stats', '0003_auto_20200...
StarcoderdataPython
3286791
from io import StringIO from snakefmt import DEFAULT_LINE_LENGTH from snakefmt.formatter import Formatter from snakefmt.parser.parser import Snakefile def setup_formatter(snake: str, line_length: int = DEFAULT_LINE_LENGTH): stream = StringIO(snake) smk = Snakefile(stream) return Formatter(smk, line_lengt...
StarcoderdataPython
3341988
# Generated by Django 3.1.2 on 2020-11-21 16:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('discourse', '0031_topic_image_of_topic'), ] operations = [ migrations.AddField( model_name='topic', name='image_url'...
StarcoderdataPython
190584
from .sorting_algorithms import * class Policy: context = None def __init__(self, context): self.context = context def configure(self): if len(self.context.numbers) > 10: print('More than 10 numbers, choosing merge sort!') self.context.sorting_algorithm = MergeSor...
StarcoderdataPython
1706930
""" Create db table """ import os import psycopg2 QUERIES = ( """ CREATE TABLE IF NOT EXISTS users( user_id SERIAL PRIMARY KEY NOT NULL, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(100) NOT NULL ...
StarcoderdataPython
1757761
import pyabc import tempfile import pytest import os import numpy as np # create and run some model def model(p): return {'ss0': p['p0'] + 0.1 * np.random.uniform(), 'ss1': p['p1'] + 0.1 * np.random.uniform()} p_true = {'p0': 3, 'p1': 4} observation = {'ss0': p_true['p0'], 'ss1': p_true['p1']} lim...
StarcoderdataPython
1677273
<gh_stars>1-10 from web3 import Web3, HTTPProvider infura_api = "" def verify(address, assigned_content, txn_addr): w3 = Web3(HTTPProvider(infura_api)) func_header = 'leaveMsg(string)' txn_receipt = w3.eth.getTransactionReceipt(txn_addr) if txn_receipt['to'] != address: return False if txn...
StarcoderdataPython
4829137
import sentry_sdk from framework.util.settings import get_setting sentry_sdk.init(get_setting("SENTRY_DSN"), traces_sample_rate=1.0) def application(environ, start_response): if environ["PATH_INFO"] == "/e/": division = 1 / 0 status = "200 OK" headers = { "Content-type": "text/html", ...
StarcoderdataPython
3285426
### Not working!!! ### Alternative trianing of Faster R-CNN, # which means we are going to train RPN first, then detector, then RPN, then detector... import sys from pathlib import Path import pickle import random from copy import copy import numpy as np import pandas as pd import tensorflow as tf from tensorflow.im...
StarcoderdataPython
4834604
import uuid from ast import literal_eval from django_filters.rest_framework import DjangoFilterBackend from django.http import HttpResponse from django.db.models import Q from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin from rest_framework.viewsets import GenericV...
StarcoderdataPython
3293811
def beachfront_cell(map, i, j): '''Returns the amount of beachfront for the cell at `map[i][j]`. The map is a grid of 1s and 0s where 1 means land and 0 means water. Beachfront is defined as any point where water borders land to the top, bottom, left, or right. Only land cells have beachfront (otherwis...
StarcoderdataPython
156651
import os from pathlib import Path import subprocess import paramiko from paramiko.rsakey import RSAKey from .box_config import BoxConfig class SSH: """Manage SSH connections""" ip: str user: str client: paramiko.SSHClient def __init__(self, user: str, ip: str, cfg: BoxConfig) -> None: se...
StarcoderdataPython
118155
from django.db import models from users.models import User class Event(models.Model): title = models.CharField(verbose_name="事件名", max_length=64) time = models.DateField(verbose_name="事件执行日期") finished = models.BooleanField(verbose_name="是否完成", default=False) creator = models.ForeignKey(User, on_dele...
StarcoderdataPython
3391039
import json import os.path import posixpath import platform import sys from subprocess import Popen, PIPE, STDOUT if __name__ == '__main__': print "Running " + str(__file__) + "..." #Run the XFoil simulation ------------------------------------------------------------------------------------------ print ...
StarcoderdataPython
1769295
<filename>mymongolib/mysql.py import signal import sys import logging from pymysqlreplication import BinLogStreamReader from pymysqlreplication.row_event import ( DeleteRowsEvent, UpdateRowsEvent, WriteRowsEvent, ) def mysql_stream(conf, mongo, queue_out): logger = logging.getLogger(__name__) # ...
StarcoderdataPython
1745495
# -*- coding:utf-8 -*- from unittest import TestCase from simstring.measure.dice import DiceMeasure class TestCosine(TestCase): measure = DiceMeasure() def test_min_feature_size(self): self.assertEqual(self.measure.min_feature_size(5, 1.0), 5) self.assertEqual(self.measure.min_feature_size(5,...
StarcoderdataPython
4800091
<filename>setup.py from setuptools import setup, find_packages from os import path from io import open here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup(name='veriservice',...
StarcoderdataPython
3201092
<reponame>hsivan/automon import autograd.numpy as np from autograd import hessian from scipy.optimize import minimize import matplotlib.pyplot as plt from matplotlib import rcParams, rcParamsDefault from scipy.optimize import brentq from autograd import grad from experiments.visualization.visualization_utils import get...
StarcoderdataPython
1675151
import tfm__unit_interval import tfm__2D_rows_sum_to_one__log import tfm__2D_rows_sum_to_one__stickbreak # Make a few functions easily available logistic_sigmoid = tfm__unit_interval.logistic_sigmoid inv_logistic_sigmoid = tfm__unit_interval.inv_logistic_sigmoid from log_logistic_sigmoid import log_logistic_sigmoid
StarcoderdataPython
4801894
<reponame>neugeeug/terraform-aws-ecr-scanner import os, boto3, json import urllib.request, urllib.parse from urllib.error import HTTPError import logging from botocore.exceptions import ClientError client = boto3.client('ecr') logger = logging.getLogger() def get_all_image_data(repository): """ Gets a list ...
StarcoderdataPython
63354
""" Created on 19/06/2020 @author: <NAME> """ from Data_manager.Dataset import Dataset from Data_manager.IncrementalSparseMatrix import IncrementalSparseMatrix_FilterIDs from pandas.api.types import is_string_dtype import pandas as pd def _add_keys_to_mapper(key_to_value_mapper, new_key_list): for new_key in n...
StarcoderdataPython
3215836
# Copyright 2017 The TensorFlow 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/LICENSE-2.0 # # Unless required by applica...
StarcoderdataPython
59206
# import the necessary packages from imutils.video import VideoStream from imutils import face_utils import argparse import imutils import time import dlib import cv2 import tensorflow as tf from tensorflow.keras.models import load_model import numpy as np from matplotlib import pyplot as plt import os ...
StarcoderdataPython
3342482
<filename>decoder/xor/xor/xor.py # Copyright 2014-2015 PUNCH Cyber Analytics Group # # 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...
StarcoderdataPython
1741183
# Twowaits Twowaits Problem # Python code to find second largest # element from a dictionary using sorted() method # creating a new Dictionary example_dict ={"a":13, "b":3, "c":6, "d":11} # now directly print the second largest # value in the dictionary print(list(sorted(example_dict.values()))[-2])
StarcoderdataPython
1782204
<filename>tests/test_adaptivecard.py from unittest import TestCase from adaptivecards.adaptivecard import AdaptiveCard class TestAdaptiveCard(TestCase): def test_generate_card(self): apt = AdaptiveCard() obj = apt.render() expected = { 'type': 'AdaptiveCard', 'versi...
StarcoderdataPython
3389298
<filename>app/views.py """The albumjet flask app viewss """ from flask import jsonify, render_template, request from . import app, db from .models import UserAlbum, UserLamina from .functions import toBoolean @app.route('/') def index(): """index view """ useralbum = UserAlbum.query.get(1) retu...
StarcoderdataPython
3321434
<gh_stars>1-10 class LaftelPyException(Exception): pass class HTTPException(LaftelPyException): pass
StarcoderdataPython
1622629
<gh_stars>1-10 # Importar as bibliotecas necessárias import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import seaborn as sns from sklearn.linear_model import LinearRegression # Leitu...
StarcoderdataPython
3200558
<filename>sentinel/rest/http.py import asyncio import weakref import aiohttp import sys import json import traceback import logging from urllib.parse import quote as _uriquote from ..errors import HTTPException, Forbidden, NotFound, ServerError, SentinelError log = logging.getLogger(__name__) class Route: BASE ...
StarcoderdataPython
1672803
<filename>pallindrome.py n=int(input("Enter number:")) temp=n rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 if(temp==rev): print("The number is a palindrome!") else: print("The number isn't a palindrome!")
StarcoderdataPython
1684852
import requests # For calculating the lat and long of places from geopy.geocoders import Nominatim geolocator = Nominatim() source = geolocator.geocode("tambaram") print(source.longitude, source.latitude) dest = geolocator.geocode("nungambakkam") print (dest.longitude , dest.latitude ) source_coordinates = str(sourc...
StarcoderdataPython
24049
string_input = "amazing" vowels = "aeiou" answer = [char for char in string_input if char not in vowels] print(answer)
StarcoderdataPython
3200495
<filename>Scripts/Utils/board.py def check_args(r, c, d, i, player): if r > 2 or r < 0: raise ValueError('Unknown row: ' + str(r)) if c > 2 or c < 0: raise ValueError('Unknown column: ' + str(c)) if d > 1 or d < 0: raise ValueError('Unknown diag: ' + str(d)) if i > 8 or i < 0: ...
StarcoderdataPython
44492
<filename>digit-dataset/k-means.py import numpy as np from sklearn.cluster import KMeans num_classes = 10 dirr = "./" cat = np.load(dirr+"features_cat.npz") rev = np.load(dirr+"features_rev.npz") mstn = np.load(dirr+"features_mstn.npz") cat_pred = KMeans(n_clusters=num_classes, n_jobs=-1).fit_predict(np.concatenate([...
StarcoderdataPython
82293
import socket import sys from thread import start_new_thread from InstagramAPI import InstagramAPI import subprocess import flickrapi import requests import MySQLdb import urllib2 def getIDbyUsername(uname): target_link="http://instagram.com/"+uname+"/" response=urllib2.urlopen(target_link) pa...
StarcoderdataPython
1724833
<filename>binp/service.py from asyncio import Task, get_event_loop, sleep, CancelledError from dataclasses import dataclass from enum import Enum from logging import getLogger from typing import Callable, Awaitable, Optional, Dict, List from pydantic import BaseModel from binp.events import Emitter class Status(str...
StarcoderdataPython
1747433
import unittest from app.models import Comment,User,Pitch from app import db class CommentModelTest(unittest.TestCase): def setUp(self): self.user_postgres = User(username = 'kayleen',password = 'password', email = '<EMAIL>') self.new_comment = Comment(comment='nice work',user = self.user...
StarcoderdataPython
15766
from unittest import TestCase, mock from modelgen import ModelGenerator, Base from os import getcwd, path class TestModelgen(TestCase): @classmethod def setUpClass(self): self.yaml = {'tables': {'userinfo':{'columns': [{'name': 'firstname', 'type': 'varchar'}, ...
StarcoderdataPython
3293530
''' The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the po...
StarcoderdataPython
72562
import copy from proxy import Proxy class ProxyList(list): """ A proxy wrapper for a normal Python list. A lot of functionality is being reproduced from Proxy. Inheriting Proxy would simplify things a lot but I get type errors when I try to do so. It is not exactly clear what a partial copy entail...
StarcoderdataPython
3322783
from rest_framework.test import APITestCase from main.models import FavoriteThing, Category class BaseViewTest(APITestCase): @staticmethod def create_category(category_name=''): category = Category.objects.create(category_name=category_name) return category @staticmethod def creat...
StarcoderdataPython
3215465
<gh_stars>1-10 from setuptools import setup if __name__ == '__main__': setup(name='lakehouse', author='Elementl', license='Apache-2.0', install_requires=['dagster'])
StarcoderdataPython
122137
from unittest import TestCase, mock from unittest.mock import MagicMock import numpy as np from source.constants import Constants from source.preprocessing.epoch import Epoch from source.preprocessing.heart_rate.heart_rate_collection import HeartRateCollection from source.preprocessing.heart_rate.heart_rate_feature_ser...
StarcoderdataPython
12404
<gh_stars>1-10 #!/usr/bin/env python # # Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any of the # following licenses(2): Mozilla Public License, V1.1, GNU General # Public License, V2.0, GNU ...
StarcoderdataPython
1624308
import collections import logging import pickle from typing import Any, Dict, Hashable, Iterable, Iterator, Mapping, Optional, Sequence, Union import warnings import numpy as np from smqtk_dataprovider import from_uri from smqtk_descriptors import DescriptorElement from smqtk_classifier.interfaces.classify_descripto...
StarcoderdataPython
3280504
<filename>scripts/usage-report.py # Emails you a per-collector per-source usage report # # python usage-report.py <accessId> <accessKey> <orgId> <fromTime> <toTime> <timezone> <timeslice> <email> # # TODO per-source # TODO log hook # TODO delete jobs? from email.mime.text import MIMEText import json from smtplib impor...
StarcoderdataPython
143532
<reponame>JosephVSN/cmus-scrobbler<gh_stars>0 """Config script for cmus_scrobbler.""" import os import json import lastfm CONFIG_DIR = os.path.join(os.path.expanduser("~"), ".config", "cmus-scrobbler") CONFIG_JSON = os.path.join(CONFIG_DIR, "cmus_scrobbler_config.json") def _setup_config() -> bool: """Creates th...
StarcoderdataPython
43184
<filename>python_demo_v2/lxml_test.py import requests from lxml import etree def get_one_page(url): try: headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', 'cookie': 'prov=75cc3cab-0ed5-5...
StarcoderdataPython
110649
<reponame>chrigl/docker-library<gh_stars>0 """Define interfaces for your add-on. """ from plone.theme.interfaces import IDefaultPloneLayer from zope.interface import Interface class IGeoFileLayer(IDefaultPloneLayer): """Marker interface that defines a Zope 3 browser layer. """ class IGisFile(Interface): "...
StarcoderdataPython
17117
<gh_stars>0 import sys from __init__ import Bot MESSAGE_USAGE = "Usage is python %s [name] [token]" if __name__ == "__main__": if len(sys.argv) == 3: Bot(sys.argv[1], sys.argv[2]) else: print(MESSAGE_USAGE.format(sys.argv[0]))
StarcoderdataPython
4819668
# TODO: FIX INDENTATION TO REMOVE THIS ERROR # PEP8-COMPLIANT MEANS 4 SPACES/TAB import logging import re import aiohttp import discord from bs4 import BeautifulSoup from discord.ext import commands from asyncTest import saveDict user_agent = """\ Mozilla/5.0 (Windows; U; Windows NT 10.0; rv:10.0) Gecko/2010010...
StarcoderdataPython
3384979
<reponame>BobBriksz/front-end """Initialize flask app""" from .app import create_app app=create_app()
StarcoderdataPython
3236220
# -*- coding: utf-8 -*- # Copyright 2018 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. """Unit tests for chromite.lib.repo and helpers for testing that module.""" from __future__ import print_function import os impo...
StarcoderdataPython
3399001
# Implements a list of unique numbers from cs50 import get_int # Memory for numbers numbers = [] # Prompt for numbers (until EOF) while True: # Prompt for number number = get_int("number: ") # Check for EOF if not number: break # Check whether number is already in list if number no...
StarcoderdataPython
196445
#!/usr/bin/env python import os import re import sys import warnings from setuptools import setup, find_packages from setuptools import Command MAJOR = 0 MINOR = 10 MICRO = 0 ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) QUALIFIER = 'rc2' DISTNAME = 'xarray' LICENSE = 'Apache' AUTHOR = 'xarray Dev...
StarcoderdataPython
4826776
""" System tests. <NAME> <<EMAIL>> pytest tmpdir docs: http://doc.pytest.org/en/latest/tmpdir.html#the-tmpdir-fixture """ import copy import shutil import re from pathlib import Path import textwrap import click.testing from mailmerge.__main__ import main from . import utils def test_no_options(tmpdir): """Veri...
StarcoderdataPython
145267
<gh_stars>0 # # Class for quick plotting of variables from models # import numpy as np import pybamm import warnings from collections import defaultdict def ax_min(data): "Calculate appropriate minimum axis value for plotting" data_min = np.nanmin(data) if data_min <= 0: return 1.04 * data_min ...
StarcoderdataPython
1761015
__source__ = 'https://leetcode.com/problems/hand-of-straights/' # Time: O(N * (N/W)) # Space: O(N) # # Description: Leetcode # 846. Hand of Straights # # Alice has a hand of cards, given as an array of integers. # # Now she wants to rearrange the cards into groups so that each group is size W, # and consists of W cons...
StarcoderdataPython
54516
<reponame>hnarasimhan/constrained-classification import numpy as np from time import time from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import LogisticRegressionCV from models.constrained import COCOClassifier, FRACOClassifier from models.unconstrained import FrankWolfeClassifier, BisectionCl...
StarcoderdataPython
3299639
import copy import os from typing import Optional, Text, List, Dict, Union, Tuple, Any, TYPE_CHECKING from rasa.shared.exceptions import FileNotFoundException import rasa.shared.utils.io import rasa.shared.utils.cli from rasa.core.constants import ( DEFAULT_NLU_FALLBACK_THRESHOLD, DEFAULT_CORE_FALLBACK_THRESHO...
StarcoderdataPython
1762723
<gh_stars>1-10 #!usr/bin/env python3 # # Copyright 2017 Petuum, 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 ...
StarcoderdataPython
3302826
# Copyright 2016-2020 The <NAME> at the California Institute of # Technology (Caltech), with support from the Paul Allen Family Foundation, # Google, & National Institutes of Health (NIH) under Grant U24CA224309-01. # All rights reserved. # # Licensed under a modified Apache License, Version 2.0 (the "License"); # you ...
StarcoderdataPython
3294920
from django.db import models from django.template.defaultfilters import slugify from django.conf import settings from datetime import datetime class Category(models.Model): id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100, unique=True, verbose_name='What is the category ...
StarcoderdataPython
3213276
class BoolNode: def __init__(self,token): self.token = token self.position = token.position def __repr__(self): return f'{self.token}' class NumberNode: def __init__(self,token): self.token = token self.position = token.position def __repr__(self): retu...
StarcoderdataPython
1653319
from __future__ import unicode_literals from django.apps import AppConfig class SignalControlConfig(AppConfig): name = 'signalcontrol' verbose_name = 'Signal Control'
StarcoderdataPython
3229755
<gh_stars>0 #!/usr/bin/env python3 # author: d.koch # coding: utf-8 # naming: pep-0008 # typing: pep-0484 # docstring: pep-0257 # indentation: tabulation (4 spc) """ enamlx-api.py API list in copy/paste friendly format """ # How to use this file # This file is *not* runnable # This file is *not* an exhaustive docum...
StarcoderdataPython
3239423
<gh_stars>0 from keras.models import Sequential from keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout, ZeroPadding2D def create_mnist_model(xshape): model = Sequential() model.add(ZeroPadding2D(padding=((2, 2), (2, 2)), input_shape=xshape)) model.add(Conv2D(10, 5, activation='relu')) ...
StarcoderdataPython
78060
{ 'variables': { 'target_arch%': 'ia32', 'naclversion': '0.4.5' }, 'targets': [ { 'target_name': 'sodium', 'sources': [ 'sodium.cc', ], "dependencies": [ "<(module_root_dir)/dep...
StarcoderdataPython
160295
from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, render from django.utils.decorators import method_decorator from django.conf.urls import url from ..core.app import ShopKitApp class OrderApp(ShopKitApp): app_name = 'order' namespace = 'order' Orde...
StarcoderdataPython
141081
DATABASE_NAME = 'telepebble' DATABASE_ALIAS = 'default'
StarcoderdataPython
54778
<filename>extreme_feedback_tts/build_status_enum.py<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- from enum import Enum class BuildStatus( Enum ): Success = 1 Failed = 2 Running = 3 Unavailable = 4 @classmethod def has_value( cls, value ): return any( BuildSt...
StarcoderdataPython
1668743
# coding=utf-8 from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut from OTLMOW.OTLModel.Classes.Verlichtingstoestel import Verlichtingstoestel from OTLMOW.OTLModel.Datatypes.KwantWrdInMeter import KwantWrdInMeter # Generated with OTLClassCreator. To modify: extend, do not edit class VerlichtingstoestelT...
StarcoderdataPython
1663984
<gh_stars>1000+ __author__ = "<NAME>" import numpy as np from theano import config from theano import function from theano import tensor as T from pylearn2.sandbox.lisa_rl.bandit.environment import Environment from pylearn2.utils import sharedX from pylearn2.utils.rng import make_np_rng, make_theano_rng class Gaus...
StarcoderdataPython
3275638
<reponame>SLieng/vim_snippets from snp.src.ᗰ͈ import ᗰ͈
StarcoderdataPython
3238551
<filename>reporting/models.py from django.db import models from django.urls import reverse class Product(models.Model): """ Model representing a vendors product """ asin = models.CharField('ASIN',max_length=50, help_text="ASIN for the product", primary_key=True) product_name = models.CharField('Pro...
StarcoderdataPython
76676
<filename>weather/services/sun.py import datetime import time from typing import Dict import aiohttp def _utc_to_local(date: str) -> datetime.datetime: """Converts utl to local datetime.""" now_timestamp = time.time() return datetime.datetime.strptime(date, "%I:%M:%S %p") + ( datetime.datetime.fro...
StarcoderdataPython
1656833
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from metascrape import utils import mock import unittest class UtilsTestCase(unittest.TestCase): def test_extract_headers(self): mock_response = mock.Mock() mock_response.headers = { "Accept-Ranges": "none", "Connection": "...
StarcoderdataPython
17636
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup setup(name='starsearch', version='0.3', description='Package to dig into the ESO archives', author='<NAME>', author_email='<EMAIL>', license='MIT', url='https://github.com/jdavidrcamacho/starsearch', p...
StarcoderdataPython
77544
# make sure configure registrations are executed from . import deserialize_content # noqa from . import deserialize_value # noqa from . import serialize_content # noqa from . import serialize_schema # noqa from . import serialize_schema_field # noqa from . import serialize_value # noqa
StarcoderdataPython
30730
<reponame>gexahedron/pytti from pytti.LossAug import MSELoss, LatentLoss import sys, os, gc import argparse import os import cv2 import glob import math, copy import numpy as np import torch from torch import nn from torch.nn import functional as F from PIL import Image import imageio import matplotlib.pyp...
StarcoderdataPython
3276081
""" This is the PyTurbSim python advanced programming interface (API). This module provides a fully-customizable high-level object-oriented interface to the PyTurbSim program. The four components of this API are: 1) The :class:`tsrun <pyts.main.tsrun>` class, which is the controller/run object for PyTurbSim simulatio...
StarcoderdataPython
1794099
<reponame>sundarsrst/pytablewriter<filename>pytablewriter/error.py # encoding: utf-8 """ .. codeauthor:: <NAME> <<EMAIL>> """ from __future__ import absolute_import class NotSupportedError(Exception): pass class EmptyTableNameError(Exception): """ Exception raised when a table writer class of the |tab...
StarcoderdataPython
1750598
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <<EMAIL>> ...
StarcoderdataPython
1732673
<reponame>voussoir/voussoirk import math import re import sys from voussoirkit import pipeable def hms_to_seconds(hms) -> float: ''' Convert hh:mm:ss string to an integer or float of seconds. ''' parts = hms.split(':') seconds = 0 if len(parts) > 3: raise ValueError(f'{hms} doesn\'t ma...
StarcoderdataPython
1676224
import tensorflow as tf from tensorflow_probability import edward2 as ed N = 10000 car_door = ed.Categorical(probs=tf.constant([1. / 3., 1. / 3., 1. / 3.]), sample_shape = N, name = 'car_door') picked_door = ed.Categorical(probs=tf.constant([1. / 3., 1. / 3., 1. / 3.]), sample_shape = N, name = 'picked_door') prefe...
StarcoderdataPython
163873
<filename>test/common/test_group_by.py<gh_stars>1-10 from inspect import isgenerator from stograde.common.group_by import group_by def test_group_by(): assert isgenerator(group_by([1, 2, 3], lambda s: s % 2 == 0)) assert dict(group_by(['1', '2', '3'], lambda s: s.isdigit())) == {True: ['1', '2', '3']} ass...
StarcoderdataPython
199095
from CyberSource import * import os import json from importlib.machinery import SourceFileLoader config_file = os.path.join(os.getcwd(), "data", "Configuration.py") configuration = SourceFileLoader("module.name", config_file).load_module() # To delete None values in Input Request Json body def del_none(d): for ke...
StarcoderdataPython
188552
<reponame>bnels/manimtda<gh_stars>0 from setuptools import * LONG_DESC = """ An extension of `manim` for topological data analysis """ setup(name='manimtda', version='0.0.0', description='Topological Data Analysis in `manim`', long_description=LONG_DESC, author='<NAME> & <NAME>', url='ht...
StarcoderdataPython
3266566
from django.db import models class Report(models.Model): name = models.CharField(max_length = 50, null = True) phone = models.CharField(max_length = 20, null = True) lat = models.DecimalField(max_digits = 9, decimal_places = 6, null = True) lng = models.DecimalField(max_digits = 9, decimal_places = 6, null = True...
StarcoderdataPython
1718349
<filename>1/solve.py with open('input') as fh: print('Part 1:', sum(int(x) // 3 - 2 for x in fh.readlines())) import itertools as it with open('input') as fh: print('Part 2:', sum( sum(it.takewhile((0).__lt__, it.accumulate(it.repeat(None), lambda a, b: a // 3 - 2, initial=in...
StarcoderdataPython
3253160
<gh_stars>0 import asyncio import bilibiliCilent class Rafflehandler: instance = None def __new__(cls, *args, **kw): if not cls.instance: cls.instance = super(Rafflehandler, cls).__new__(cls, *args, **kw) cls.instance.list_activity = [] cls.instance.list_TV = [] ...
StarcoderdataPython
99884
fig, ax = create_map_background() # Contour 1 - Temperature, dotted cs2 = ax.contour(lon, lat, tmpk_850.to('degC'), range(-50, 50, 2), colors='grey', linestyles='dotted', transform=dataproj) plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=10, fmt='%i', rightside_up=True, use_clabelte...
StarcoderdataPython
32975
from django.utils import timezone from django.utils.translation import ugettext from mediane.algorithms.enumeration import get_name_from from mediane.algorithms.lri.BioConsert import BioConsert from mediane.algorithms.lri.ExactAlgorithm import ExactAlgorithm from mediane.algorithms.misc.borda_count import BordaCount f...
StarcoderdataPython
3341706
<filename>backend/scout_service/ScoutRepository.py import IQRRepository as rep from qrookDB.data import QRTable from datetime import datetime import json from abc import abstractmethod users = QRTable() class IScoutRepository(): @abstractmethod def register_event(self, user_id, time, event: str, data: dict): ...
StarcoderdataPython
59485
<filename>django/api/tests/ftp.py from ftplib import FTP from io import StringIO import re import sys # Connect to local ftp server ftp = FTP(host='localhost', user='user',passwd='<PASSWORD>') ###################### Download ########################### # Store output for later old_stdout = sys.stdout # Redirect out...
StarcoderdataPython
1795557
import cv2 import numpy as np src = np.array( [[164, 215], [128, 8], [480, 72]] ) dst = np.array( [(175, 237), (146, 44), (486, 99)] ).reshape(-1,2) m = cv2.estimateAffine2D(dst,src) print(m) # m = cv2.estimateRigidTransform(_prev_pts, _curr_pts, fullAffine=False) tr = np.array([[ 1.03016009, 3.173...
StarcoderdataPython
1697556
# -*- coding: utf-8 -*- #Completa Si import sip # switch on QVariant in Python3 sip.setapi('QVariant', 2) sip.setapi('QString', 1) from PyQt4.QtCore import QtCore, QString, QVariant from PyQt4.QtGui import QtGui from PyQt4.Qt import Qt from pineboolib.fllegacy.FLFormDB import FLFormDB from pineboolib.fllegacy.FLSq...
StarcoderdataPython
185315
<reponame>Kpaubert/onlineweb4 # Generated by Django 3.0.6 on 2020-05-25 12:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("events", "0027_auto_20200420_1143"), ] operations = [ migrations.AlterModelOptions( name="attendanceevent"...
StarcoderdataPython
3392848
<filename>ExerciciosPYTHON/PythonCeV/038.py print('='*8,'Comparando Numeros','='*8) n1 = int(input('Digite um numero inteiro qualquer: ')) n2 = int(input('Digite outro numero inteiro qualquer: ')) if n1 > n2 : print('O primeiro valor e o {}MAIOR{}.'.format('\033[36m','\033[m')) elif n2 > n1 : print('O segundo ...
StarcoderdataPython