id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3241103 | #coding:utf-8
"""The News Insert Implementation."""
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
def insert_news(date, title, html, trhtml, text, trtext):
client = MongoClient(connectTimeoutMS=2000, serverSelectionTimeoutMS=2000)
try:
# The ismaster command is cheap a... | StarcoderdataPython |
3298994 | from .TaroColor import TaroColor
| StarcoderdataPython |
1750627 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
from oauthlib.common import Request
from oauthlib.oauth1 import (
SIGNATURE_HMAC_SHA1, SIGNATURE_HMAC_SHA256, SIGNATURE_PLAINTEXT,
SIGNATURE_RSA, SIGNATURE_TYPE_BODY, SIGNATURE_TYPE_QUERY,
)
from oauthlib.oauth1.rfc5849 import Client
from tests.unittest import TestCas... | StarcoderdataPython |
1641563 | """
This file must not depend on any other CuPy modules.
"""
import os
import os.path
import shutil
_cuda_path = None
_nvcc_path = None
def get_cuda_path():
# Returns the CUDA installation path or None if not found.
global _cuda_path
if _cuda_path is None:
_cuda_path = _get_cuda_path()
retu... | StarcoderdataPython |
3372923 | <reponame>rlberry-py/rlberry<gh_stars>10-100
from rlberry.seeding.seeding import safe_reseed
import gym
import numpy as np
import pytest
from rlberry.seeding import Seeder
from rlberry.envs import gym_make
from copy import deepcopy
gym_envs = [
'Acrobot-v1',
'CartPole-v1',
'MountainCar-v0',
]
def get_en... | StarcoderdataPython |
1703511 | import flask_wtf
import wtforms
import wtforms.fields.core as wtforms_core
import wtforms.fields.simple as wtforms_simple
class LoginForm(flask_wtf.FlaskForm):
"""Class representing the login form for the application
Parameters
----------
FlaskForm : WTForms
Flask wtf class that is extended ... | StarcoderdataPython |
1731974 | import coc
import discord
from config import *
async def claim(client_discord,
connectionBDD,
args,
message):
"""claim:
Args:
client_discord ([discord.Client]): [un client pour l'API discord]
connectionBDD ([database_outils.appelsBDD]): [un conn... | StarcoderdataPython |
305 | from turtle import Turtle
SPEED = 10
class Ball(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.color("white")
self.shape("circle")
self.move_speed = 0.1
self.y_bounce = 1
self.x_bounce = 1
def move(self):
new_x = self.xcor() ... | StarcoderdataPython |
3305821 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 4 15:23:46 2018
@author: Jared
"""
from collections import Counter
import pymongo
import pandas as pd
from ast import literal_eval
from ml.elements import *
#import machineLearner as ml #get rid of if doing oqmd database
#from qmpy import * #use... | StarcoderdataPython |
1622760 | import json
import os
import pytz
def _bool_convert(value):
truthy = {"t", "true", "on", "y", "yes", "1", 1, 1.0, True}
falsy = {"f", "false", "off", "n", "no", "0", 0, 0.0, False}
if isinstance(value, str):
value = value.lower()
if value in truthy:
return True
if value in falsy:
... | StarcoderdataPython |
78114 | <filename>hms/migrations/0001_initial.py
# Generated by Django 3.2.4 on 2021-06-08 17:04
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(... | StarcoderdataPython |
1624524 | <gh_stars>1-10
from django import forms
from django.utils.html import strip_tags
from .forms import HTMLField
from .widgets import HTMLFieldWidget
def _process_checkbox(field_json):
field = forms.MultipleChoiceField()
field.widget = forms.CheckboxSelectMultiple()
return field
def _process_date(field_jso... | StarcoderdataPython |
84058 | # --coding:utf-8--
#
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License,
# attached with Common Clause Condition 1.0, found in the LICENSES directory.
import time
import pytest
from tests.common.nebula_test_suite import NebulaTestSuite, T_NULL
class TestI... | StarcoderdataPython |
180252 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 17:50:06 2020
@author: <NAME>
"""
def CLEARLAYOUT(layout):
for i in reversed(range(layout.count())):
layoutItem = layout.itemAt(i)
if layoutItem.widget() is not None:
widgetToRemove = layoutItem.widget()
widgetTo... | StarcoderdataPython |
3311682 | <gh_stars>10-100
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BS... | StarcoderdataPython |
153935 | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2013, <NAME> <<EMAIL>
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANS... | StarcoderdataPython |
1647300 | #
# Copyright 2015 ClusterHQ
#
# 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, s... | StarcoderdataPython |
1617483 | #!/usr/bin/env python
import sys
import os
import json
import re
import urllib
import urllib2
# Basic Dynamic DNS update client. Written around the no-ip.com API.
# Supports determining your public IP by querying an external web service, or by
# using an IP address from a local interface
#
# Reads in config from a JS... | StarcoderdataPython |
3302518 | <gh_stars>1-10
# Copyright (c) 2016-2021 InSeven Limited
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | StarcoderdataPython |
91802 | import RPi.GPIO as GPIO
from picamera import PiCamera
class DiceCam(object):
"""Dice Cam! Flash the LEDs, take a pic!"""
def __init__(self, *led_pins):
super(DiceCam, self).__init__()
self.led_pins = list(led_pins)
self.camera = PiCamera()
self.camera.stop_preview()
self.camera.resolution = ... | StarcoderdataPython |
3294773 | <filename>src/IVR-Comprehend2DynamoDB/read_transcripts.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 02 2020
@author: <NAME> (Amazon Web Services)
@email: <EMAIL>
"""
import json
import boto3
# Get S3 client
s3 = boto3.client("s3")
def read_transcripts(src_bucket, guid):
"""Get the transcripts ... | StarcoderdataPython |
3331011 | <<<<<<< HEAD
<<<<<<< refs/remotes/origin/master
=======
>>>>>>> 6b69621ca7b67c04c4370529ed374ff23ee4c464
#lista znajomych bez piewszej osoby od 01 pozycji listy, lista zaczyna się od pozycji 0
friends = ["Monika", "Piotrek", "Tomek", "Tomek.P", "Justyna", "Rafał", "Witek", "Agnieszka", "Sabina"]
#Dodawanie do listy po... | StarcoderdataPython |
1634809 | <gh_stars>1-10
from configparser import ConfigParser
parser = ConfigParser()
parser.read('multisection.ini')
for candidate in ['wiki', 'bug_tracker', 'dvcs']:
print('{:<12}: {}'.format(
candidate, parser.has_section(candidate))) | StarcoderdataPython |
75178 | <filename>pytsp/core/__init__.py<gh_stars>1-10
from pytsp.core.annealing import (AnnealingMixin, CompressedAnnealing,
SimulatedAnnealing)
from pytsp.core.genetic import GeneticAlgorithm
from pytsp.core.util import Model, cached, jarvis
from pytsp.core.tsp import TravellingSalesman, Travelli... | StarcoderdataPython |
1739869 | for i in range(9):
for j in range(20000):
if(j<19999 or i!=8):
print(i,end=" ")
else:
print(i)
print("7")
| StarcoderdataPython |
1748165 | <reponame>bpbpublications/Programming-Techniques-using-Python
class Uppercase_decorator:
def __init__(self, myfunc):
self.myfunc = myfunc
def __call__(self):
mystr1 = self.myfunc()
return mystr1.upper()
# adding class decorator to the function mygreet
@Uppercase_decorator
d... | StarcoderdataPython |
199133 | <filename>synapse/rest/client/v2_alpha/room_keys.py
# -*- coding: utf-8 -*-
# Copyright 2017, 2018 New Vector Ltd
#
# 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... | StarcoderdataPython |
3381654 |
import poplib
from email.parser import Parser
email = '<EMAIL>'
password = '<PASSWORD>'
pop3_server = 'pop.163.com'
server = poplib.POP3(pop3_server)
print(server.getwelcome().decode('utf8'))
server.user(email)
server.pass_(password)
print('Message: %s. Size: %s' % (server.stat()))
resp, mails, octets = server... | StarcoderdataPython |
1701681 | # fix imports for appengine environments
import fix_imports
(fix_imports)
from tg import AppConfig
from tg import redirect
from google.appengine.api import users
from main import MainController
# def controller_wrapper(next_caller):
# def call(*args, **kw):
# user = users.get_current_user()
# if ... | StarcoderdataPython |
4830904 | <reponame>sangaman/raiden<gh_stars>0
from pathlib import Path
import pytest
from raiden.storage.versions import filter_db_names, latest_db_file
def test_latest_db_file():
assert latest_db_file([Path("v10_log.db"), Path("v9_log.db")]) == Path("v10_log.db")
assert latest_db_file([Path("v9_log.db"), Path("v10_... | StarcoderdataPython |
53758 | <gh_stars>0
#-*- coding:utf-8 -*-
##############################################
# GARUDA CLIENT SDK
# Reference: Garuda Base Protocol Version 1.1
# Last Updated: 07-Aug-2015
##############################################
import sys
import time
import json
import socket
import threading
# Configuration for Garuda Co... | StarcoderdataPython |
4821375 | import csv
import sys
with open(sys.argv[1]) as csvfile:
header_line = csvfile.readline()
split_header = header_line.split(',')
print(len(split_header))
first_line = csvfile.readline()
split_first_line = first_line.split(',')
print(len(split_first_line))
| StarcoderdataPython |
1737070 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Void Copyright NO ONE
#
# Void License
#
# The code belongs to no one. Do whatever you want.
# Forget about boring open source license.
#
# AEAD cipher for shadowsocks
#
from __future__ import absolute_import, division, print_function, \
with_statement
from ctypes... | StarcoderdataPython |
16637 | <gh_stars>1-10
# Copyright (c) The InferLO authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 - see LICENSE.
import warnings
import numpy as np
from sklearn.utils.extmath import randomized_svd
from .bucket_elimination import BucketElimination
from .factor import Factor, default_fac... | StarcoderdataPython |
3247197 | <reponame>dfm/sup
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
__all__ = ["manager"]
from flask.ext.script import Manager
from sup import create_app
from sup.manage import (
CreateTablesCommand, DropTablesCommand,
CreateUserCommand,
SendSupCommand,
)
manager = Man... | StarcoderdataPython |
1692357 | # -*- coding: utf-8 -*-
import json
import scrapy
from robot.items import ProxyItem, ProxyItemLoader
from robot.processors import RemoveTags
from scrapy_redis.spiders import RedisSpider
class ProxySpider(RedisSpider):
name = 'proxy'
allowed_domains = ['raw.githubusercontent.com']
start_urls = ['https:/... | StarcoderdataPython |
3303158 | <filename>metadata_driver_elasticsearch/utils.py<gh_stars>0
import logging
from datetime import datetime
import metadata_driver_elasticsearch.indexes as index
logger = logging.getLogger(__name__)
AND = 'must'
OR = 'should'
GT = 'gte'
LT = 'lte'
BOOL = 'bool'
RANGE = 'range'
MATCH = 'match'
def query_parser(query):... | StarcoderdataPython |
3348771 | <reponame>PredaaA/JackCogs
# Copyright 2018-2020 <NAME> (https://github.com/jack1142)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# U... | StarcoderdataPython |
102752 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.conf.urls.i18n import i18n_patterns
admin.au... | StarcoderdataPython |
67390 | <gh_stars>1000+
#!/usr/bin/env python
#===----------------------------------------------------------------------===##
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
... | StarcoderdataPython |
1604506 | <reponame>faezs/plotly.py
import _plotly_utils.basevalidators
class FlatshadingValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name='flatshading', parent_name='mesh3d', **kwargs
):
super(FlatshadingValidator, self).__init__(
plotly_name=plotly_... | StarcoderdataPython |
1764094 | #!/usr/bin/env python
if __name__ == '__main__' and __package__ is None:
print "?"
| StarcoderdataPython |
1674165 | <reponame>SweydAbdul/estudos-python
import os
import os.path
for a in os.listdir('.'):
if os.path.isdir(a):
print(f'{a}/')
elif os.path.isfile(a):
print(f'{a}') | StarcoderdataPython |
23469 | from functools import lru_cache
from itertools import product
from pathlib import Path
from typing import Optional, List, Tuple
from pydantic import validate_arguments
import pyhmmer
import requests as r
from yarl import URL
from sadie.typing import Species, Chain, Source
class G3:
"""API Wrapper with OpenAPI f... | StarcoderdataPython |
3244967 | <filename>Source/Qt5/modules/node.py<gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
def main():
#Load modules
try:
import imp
import sys
except ImportError:
print("Error: Faild to import modules.")
print("Error: Exiting application")
sys.exit(1)
#Test if modules availible
testMods = ['sys', 'r... | StarcoderdataPython |
25122 | <filename>src/server_dgram/server.py
import logging
import socket
import numpy
import time
from cPickle import loads
from scipy import linalg
from matplotlib import pyplot
from multiprocessing import Array
from src.logic import helpers
from src.logic.parallel_process import ProcessParallel
from scipy import *
from nump... | StarcoderdataPython |
3332858 | '''tzinfo timezone information for Australia/Lord_Howe.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Lord_Howe(DstTzInfo):
'''Australia/Lord_Howe timezone definition. See datetime.tzinfo for details'''
zone = 'Australi... | StarcoderdataPython |
4837028 | <reponame>c0dehard/lazy-junk-organizer
"""
-*- coding: utf-8 -*-
========================
Python Lazy Junk Files Organizer
========================
========================
"""
import os
from pathlib import Path
DIRECTORIES = {
"HTML": [".html5", ".html", ".htm", ".xhtml"],
"MARKUP": [".md"],
"IMAGES": ["... | StarcoderdataPython |
30608 | import os
def get_token():
return os.environ['VACCINEBOT_TOKEN'] | StarcoderdataPython |
1749822 | <filename>examples/topology-optimization/truss2.py
from matplotlib import pyplot as plt
from compas.numerical import topop_numpy
nelx = 100
nely = 200
plt.figure(figsize=(12, 8))
plt.axis([0, nelx, 0, nely])
plt.ion()
def callback(x):
plt.imshow(1 - x, cmap='gray', origin='lower')
plt.pause(0.001)
loads = {... | StarcoderdataPython |
1638778 | <filename>lib/python/treadmill/templates/ipset_host_restore.py<gh_stars>0
"""IPSet host restore template."""
T = """
create {{any_container}} list:set size 8
create {{infra_services}} hash:ip,port family inet hashsize 1024 maxelem 65536
create {{nonprod_containers}} hash:ip family inet hashsize 1024 maxelem 65536
crea... | StarcoderdataPython |
109116 | <reponame>ArcIX/vsdscrapy<filename>securityscrape/securityscrape/items.py<gh_stars>0
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
class SecurityItem(Item):
# define the fields for your item here like:... | StarcoderdataPython |
3210194 | # ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... | StarcoderdataPython |
3283126 | <filename>DataStructuresandAlgorithmsInPython/com/kranthi/Algorithms/challenges/easy/maxMoneyWithdraw.py
"""
Maximum money that can be withdrawn in two steps
Last Updated : 10 May, 2019
There are two cash lockers, one has X number of coins and the other has Y number of coins, you can withdraw money at max two times, wh... | StarcoderdataPython |
28406 | #! /usr/bin/env python
from math import factorial
import numpy as np
# test passed
def generate_poly(max_exponent,max_diff,symbol):
f=np.zeros((max_diff+1, max_exponent+1), dtype=float)
for k in range(max_diff+1):
for i in range(max_exponent+1):
if (i - k) >= 0:
f[k,i] = factorial(i)*symbol**(i-k)/facto... | StarcoderdataPython |
190243 | #----------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#------------------------------------------------------------------... | StarcoderdataPython |
1623495 | """Linear Predictive Coding analysis and resynthesis for audio."""
import numpy as np
import scipy.signal
def lpcfit(x, p=12, h=128, w=None, overlaps=True):
"""Perform LPC analysis of short-time windows of a waveform.
Args:
x: 1D np.array containing input audio waveform.
p: int, order of LP models to fit... | StarcoderdataPython |
73969 | <reponame>ParikhKadam/zenml
# Copyright (c) ZenML GmbH 2021. 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
#
#... | StarcoderdataPython |
1697947 | import ConfigParser
import logging
import warnings
# to avoid the generation of .pyc files
import sys
sys.dont_write_bytecode = True
# necessary import to ignore any ExtdepricationWarning warnings for external
# libraries
from flask.exthook import ExtDeprecationWarning
warnings.simplefilter('ignore', ExtDeprecation... | StarcoderdataPython |
3275079 | from abc import abstractmethod
from .autoencoder import Autoencoder
from .default_values import *
from .data_utils import DataCooker
from .layers import ConstantDispersionLayer
from keras.optimizers import *
from keras.models import model_from_json
import numpy as np
import json
import os
class Corrector():
@abstr... | StarcoderdataPython |
3227241 | <filename>models.py
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
class Attn(nn.Module):
def __init__(self, method, hidden_size):
super(Attn, self).__init__()
self.use_cuda = torch.cuda.is_available()
self.method... | StarcoderdataPython |
3350407 | <reponame>anirudhmungre/sneaky-lessons<gh_stars>1-10
# Incorporate the random library
import random
# Print Title
print("Let's Play Rock Paper Scissors!")
# Specify the three options
options = ["r", "p", "s"]
# Computer Selection
computer_choice = random.choice(options)
# User Selection
user_choice = input("Make yo... | StarcoderdataPython |
1682168 | <filename>celery_task_plugins/redis_chain_store/task.py<gh_stars>0
import threading
from contextlib import contextmanager
import redis
from celery.task import Task
from kombu import serialization
def CeleryChainPlugin(
redis_host,
redis_port=6379,
redis_db=1,
base_exc_class=Exception,
read_kwarg=... | StarcoderdataPython |
1781148 | <filename>megaverse_rl/runs/single_agent.py
from sample_factory.runner.run_description import RunDescription
from megaverse_rl.runs.megaverse_base_experiments import EXPERIMENT_1AGENT
RUN_DESCRIPTION = RunDescription('megaverse_arxiv', experiments=[EXPERIMENT_1AGENT])
| StarcoderdataPython |
3208460 | <reponame>itsnamgyu/reid-research
import collections
import warnings
import torch
from reid_evaluation.metric import evaluate, compute_distances
from utils import MetricTracker, SharedStorage
class ActiveMetric:
"""Metric class that actively interacts with MetricTracker and SharedStorage to track metrics,
d... | StarcoderdataPython |
1659864 | <gh_stars>0
import sqlite3
# Connect to the database
conn = sqlite3.connect('data.sqlite')
cur = conn.cursor()
# Retrieve the most recent date from the Dates table
def recent_date(cr):
cr.execute('SELECT MAX(date) FROM Dates')
date = cr.fetchone()[0]
return date
# Display information about each restaura... | StarcoderdataPython |
72047 | # -*- coding: utf-8 -*-
"""
Tests for the Keystone states
"""
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.helpers import destructiveTest
from tests.support.mixins i... | StarcoderdataPython |
3387218 | <reponame>DiegoAV95/python_curso_-domingos<filename>Modulo1/Src/hola_argumento.py
import sys
# preguntando el nombre de la persona
nombre = input('Introduzca su nombre: ')
# imprimiendo nombre de la persona
print('hola, {} !'.format(nombre))
# print('hola, ' + nombre + '!') | StarcoderdataPython |
24818 | <gh_stars>0
from __future__ import absolute_import, division, print_function
from trakt.mapper.core.base import Mapper
import logging
log = logging.getLogger(__name__)
class SyncMapper(Mapper):
@classmethod
def process(cls, client, store, items, media=None, flat=False, **kwargs):
if flat:
... | StarcoderdataPython |
4825596 | <filename>gravedigger/gravedigger.py<gh_stars>1-10
"""
This module kills and removes containers that satisfy the following conditions:
* not matched by any pattern listed in whitelist.txt
* created more than 24h ago
Also, a logfile called gravedigger.log is created in the current directory
"""
import logging
import re
... | StarcoderdataPython |
1771245 | <filename>backend/videos/views.py
from logging import Formatter, StreamHandler, getLogger
from time import sleep, time
from flask import Blueprint, Response, current_app
from image_process.factory import create_image_processes
from .factory import create_camera
logger = getLogger(__name__)
handler = StreamHandler()... | StarcoderdataPython |
3218025 | import torch
import torchvision.models as models
import torch
import torch.nn.functional as F
from sklearn.metrics import confusion_matrix
from tqdm import tqdm
import numpy as np
from . import vae, deepinfomax
import time
__version__ = "0.7.0"
from .model import EfficientNet, VALID_MODELS
from .utils import (
Gl... | StarcoderdataPython |
3362345 | <filename>leasing/tests/test_utils.py
from datetime import date
from leasing.utils import calculate_increase_with_360_day_calendar, days360
def test_days360_year():
date1 = date(year=2020, month=1, day=1)
date2 = date(year=2021, month=1, day=1)
days = days360(date1, date2, True)
assert days == 360
... | StarcoderdataPython |
1680884 | <reponame>BrenoCipolli/login_with_interface
from PySimpleGUI import PySimpleGUI as sg
import time
tema = sg.theme('Reddit')
def sucesso():
tema = sg.theme('Reddit')
layout = [
[sg.Text('Success!',font='Roboto',size=(20,30))]
]
janela1 = sg.Window('Successful',layout,size=(100,50))
while Tru... | StarcoderdataPython |
1633489 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-11 20:51
from __future__ import unicode_literals
from django.db import migrations, models
import estate.core.models.fields
class Migration(migrations.Migration):
dependencies = [
('terraform', '0003_auto_20170707_1414'),
]
operatio... | StarcoderdataPython |
3239395 | # -*- coding: utf-8 -*-
import application
if __name__ == '__main__':
app = application.Application()
app.run()
| StarcoderdataPython |
1649184 | from collections import defaultdict
result = 0
orbits = defaultdict(lambda: [])
numorbits = {"COM": 0}
with open("input.txt", "r") as input:
for line in input:
line = line.strip().split(")")
orbits[line[0]].append(line[1])
processing = ["COM"]
while len(processing) > 0:
c = processing.pop()
... | StarcoderdataPython |
84897 | #$Id$#
from books.model.BankRule import BankRule
from books.model.Criteria import Criteria
from books.service.ZohoBooks import ZohoBooks
zoho_books = ZohoBooks("{auth_token}", "{organization_id}")
bank_rules_api = zoho_books.get_bank_rules_api()
accounts_api = zoho_books.get_bank_accounts_api()
account_id = account... | StarcoderdataPython |
1664385 | <reponame>thecoblack/CompilerGym
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for //compiler_gym/util:truncate."""
from compiler_gym.util.truncate import truncate, truncate_l... | StarcoderdataPython |
115583 | #!/usr/bin/env python
# NOTE: this script is based on logeion_load.py to do a basic import of russian
from lattices.models import LatticeNode, LemmaNode
def create_lemma_node(lemma, lattice_node, context):
lemma_node, created = LemmaNode.objects.get_or_create(
context=context,
lemma=lemma,
... | StarcoderdataPython |
3315530 | """
namecom: data_models.py
Defines data models for the api.
<NAME> [https://github.com/CtheSky]
License: MIT
"""
class DataModel(object):
"""
This is base class for data models.
It provides following utilities:
1. class method `from_dict` to construct model from a dict
2. instance method `... | StarcoderdataPython |
1711660 | # -*- coding: utf-8 -*-
#
# cafeWorker.py
#
# Defines Kakao cafe's worker interface.
from abc import ABCMeta, abstractmethod
class CafeWorker(metaclass=ABCMeta):
@abstractmethod
def Print(self) -> None:
raise NotImplementedError('Method Print not implemented')
| StarcoderdataPython |
1605438 | <reponame>DerouineauNicolas/dpx_to_ffv1<filename>dpx2ffv1/test.py<gh_stars>0
from unittest import TestCase
from dpx2ffv1.dpx2ffv1 import dpx2ffv1
class TestJoke(TestCase):
def test_main_function(self):
out = dpx2ffv1('./test/', 'out.mkv', 24)
assert(out == 0)
if __name__ == '__main__':
unittes... | StarcoderdataPython |
35934 | TORRENTS_PER_PAGE = 25
| StarcoderdataPython |
3363236 | <filename>section6_turtle-tree.py
from turtle import *
# 再帰的に木を描く
def tree(n):
if n<=1: # 引数が1以下なら
forward(5) #5歩すすむ
else: # 引数は1より大きいとき
forward(5*(1.1**n)) # 引数の値に応じて前進(幹)
# 今の位置と向きを記録
xx = pos()
h = heading()
# 左へ 30 度回転
left(30)
# 大きさ n-2 で木を描く... | StarcoderdataPython |
1718531 | #!/usr/bin/env python3
import sys, pybench
pythons = [
(1, '/usr/bin/python3'),
(0, '/usr/bin/python2')
]
stmts = [
# Use function calls: map wins
(0, 0, "[ord(x) for x in 'spam' * 2500]"),
(0, 0, "res=[]\nfor x in 'spam' * 2500: res.append(ord(x))"),
(0, 0, "$... | StarcoderdataPython |
1697860 | <gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.examples.tutorials.mnist import input_data
import tabular_logger as tlogger
import tensorflow as tf
import numpy as np
import argparse
import time
import sys
import os
def normal... | StarcoderdataPython |
1701704 | from django.contrib import admin
from article.models import Article
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title','date_time')
admin.site.register(Article,ArticleAdmin)
# Register your models here.
| StarcoderdataPython |
53766 | <gh_stars>0
'''
olympics.py
A command line interface for querying the olympics database.
Written by <NAME> for cs257
'''
import psycopg2
import argparse
from config import user, password, database
def connect_to_database():
try:
connection = psycopg2.connect(database = database, user = user, password = pa... | StarcoderdataPython |
58751 | <reponame>ber2/pybcn-meetup-pbt<filename>festa_major.py
import datetime as dt
def first_sunday_of_august(year: int) -> dt.date:
weekday_of_august_first = dt.date(year, 8, 1).isocalendar()[2]
missing_days = 7 - weekday_of_august_first
return dt.date(year, 8, 1 + missing_days)
def next_festa_major(date: d... | StarcoderdataPython |
3317255 | <filename>sudokubot/solver.py<gh_stars>1-10
from utils import search , display, grid_values, row_units
import sys
def solve(grid, format='string'):
if len(grid) != 81:
print 'ERROR: Sudoku length is not proper'
sys.exit()
values = search(grid_values(grid))
if '' in values.values():
... | StarcoderdataPython |
98577 | <filename>modelutils/pytorch/rename_weights.py
import argparse
import os
import torch
def rename_weights(input_filepath, output_filepath, rename_lists):
if os.path.exists(output_filepath):
raise RuntimeError(f"{output_filepath} already exists.")
state_dict = torch.load(input_filepath)
for rename ... | StarcoderdataPython |
1680146 | import asyncio
from traceback import format_exc
from typing import List
from teletype.io import erase_lines, style_format, style_print
from stonky.const import SYSTEM
from stonky.settings import Settings
from stonky.stock_store import StockStore
def format_table(rows: List[List[str]], colours: List[str]):
colum... | StarcoderdataPython |
63572 | # -*- coding: utf-8 -*- voir https://docs.python.org/2/tutorial/interpreter.html#source-code-encoding
def interface(jeu):
"""Retourne les éléments de l'interface pour le menu "Game Over", défini également les boutons dans la variable jeu.
Paramètre:
- dict jeu: Dictionnaire contenant les valeurs asso... | StarcoderdataPython |
96606 | <gh_stars>0
'''
Copyright 2014 The MITRE Corporation.
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 a... | StarcoderdataPython |
1718347 | # 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
# distributed under t... | StarcoderdataPython |
83388 | """Defines the factory for creating monitors"""
from __future__ import unicode_literals
import logging
logger = logging.getLogger(__name__)
_SCANNERS = {}
def add_scanner_type(scanner_class):
"""Registers a scanner class so it can be used for Scale Scans
:param scanner_class: The class definition for a sc... | StarcoderdataPython |
1696294 | import puzzleinput
import math
def rotate(x2, y2, degrees):
angle = math.radians(degrees)
cos = math.cos(angle)
sin = math.sin(angle)
x3 = cos * x2 - sin * y2
y3 = sin * x2 + cos * y2
return round(x3), round(y3)
x = 10
y = -1
traveled_x = 0
traveled_y = 0
for line in puzzleinput.lines:
a... | StarcoderdataPython |
4821235 | from sqlalchemy import Column, Integer, ForeignKey
from . import Base
class UserFeed(Base):
__tablename__ = 'user_feeds'
user_id = Column('user_id', ForeignKey('users.db_id'), primary_key=True)
feed_id = Column('feed_id', ForeignKey('feeds.db_id'), primary_key=True)
def __repr__(self):
return f"<UserFeed(use... | StarcoderdataPython |
1707770 | """
jobs.py
Defines routes that are used to interact with worker instantiation and
execution given input samples.
"""
import rq
import redis
from flask import jsonify, request, current_app, g
from rq import Queue
from boa.routes import web
from boa.worker import BoaWorker
def get_redis_connection():
""... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.