id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
3312115
<reponame>gumerov-amir/Pyttcl from threading import Thread from wx import CallAfter from .msg_dlg import MessageDialog from lib.TeamTalk5 import Channel, User # from lib import Tolk class EventThread(Thread): def __init__(self, pyttcl): Thread.__init__(self ) self.pyttcl = py...
StarcoderdataPython
4874028
import templated_email from django.conf import settings def get_context(): return { 'footer_text': settings.EMAIL_FOOTER_TEXT } def send_templated_mail( template_name, from_email, recipient_list, context, *args, **kwargs): context.update(get_context()) return templated_emai...
StarcoderdataPython
3231487
# BOJ 1799 import copy import sys si = sys.stdin.readline dy = [-1, 1, -1, 1] dx = [-1, 1, 1, -1] def backtrack(idx, maps): if idx == len(s_point): return for i in range(len(s_point)): y, x = s_point[i] cp = copy.deepcopy(maps) if not cp[y][x]: cp[y][x] = True ...
StarcoderdataPython
4801573
<reponame>Adel-Charef/scripts import os def recurse_dir(root): root = os.path.abspath(root) for item in os.listdir(root): item_full_path = os.path.join(root, item) if os.path.isdir(item_full_path): recurse_dir(item_full_path) else: print("%s - %s" % (item_full_pa...
StarcoderdataPython
5191076
<reponame>Tdev95/JWM<gh_stars>0 class JWMException(Exception): pass class DeserializationException(JWMException): pass class VerificationFailure(Exception): """ Verification of a Macaroon was attempted but failed for an unknown reason """ class CriticalClaimException(VerificationFailure): ...
StarcoderdataPython
8036738
<reponame>CornellDataScience/CoalescenceML<filename>src/coalescenceml/utils/json_utils.py import json from pathlib import Path from typing import Any, Dict from coalescenceml.io import fileio, utils def write_json(file_path: str, contents: Dict[str, Any]) -> None: """Write contents as JSON to file_path. Arg...
StarcoderdataPython
3531168
<reponame>ansabgillani/binarysearchcomproblems class Solution: def solve(self,rect0,rect1): return ((rect0[1]<=rect1[3]<=rect0[3] or rect0[1]<=rect1[1]<=rect0[3]) and not(rect1[2] <= rect0[0] or rect1[0] >= rect0[2])) or ((rect0[0]<=rect1[0]<=rect0[2] or rect0[0]<=rect1[2]<=rect0[2]) and not(rect1[3] <= rec...
StarcoderdataPython
140744
<reponame>EliasOPrado/tour-project from django.contrib import admin from .models import Order, OrderLineItem # Register your models here. """ TubularInline subclass defines the template used to render the Order in the admin interface. StackInline is other one. """ class OrderLineAdminInline(admin.TabularInline): m...
StarcoderdataPython
221760
<filename>backend/ringi/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='ringi.index'), path('create', views.create, name='ringi.create'), path('show/<int:id>', views.show, name='ringi.show'), path('edit/<int:id>', views.edit, name='ringi.edit'), ...
StarcoderdataPython
1673953
from .TS3Bot import Bot from .guild_service import GuildService __all__ = ['GuildService', 'Bot']
StarcoderdataPython
5197975
<gh_stars>0 #1) print([x+8 for x in range(3,7)]) #2) print([c for c in "programa"]) #3) print([[z,k] for z in range(3) for k in range(3,5)]) #4) print([s.upper() for s in "hoy es viernes"]) #5) print([len(z) for z in "hoy es viernes 24".split()]) ########################################## #Ej1) print("\nEjercicio ...
StarcoderdataPython
1613939
<reponame>ShubhamPandey28/sunpy """ Common solar physics coordinate systems. This submodule implements various solar physics coordinate frames for use with the `astropy.coordinates` module. """ import numpy as np import astropy.units as u from astropy.coordinates import Attribute, ConvertError from astropy.coordinate...
StarcoderdataPython
6555645
<filename>web_controller.py from flask import Flask, render_template, request import redis_phones app = Flask(__name__) @app.route('/index') def index(): return render_template('index.html') self.con. @app.route('/set', methods=['POST',]) def set(): return render_template( 'set.html', n...
StarcoderdataPython
3498119
<gh_stars>0 from math import sqrt from sklearn.metrics import mean_squared_error class ImagesMeanSquareError: @staticmethod def get_mean_square_error(image1data, image2data): return sqrt(mean_squared_error(image1data, image2data))
StarcoderdataPython
4828997
<reponame>rohe/otest """ Assertion test module ~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by <NAME>. :license: APACHE 2.0, see LICENSE for more details. """ from future.backports.urllib.parse import parse_qs import json import inspect import traceback import sys from otest.events import EV_PROTOCOL_R...
StarcoderdataPython
3408131
import requests from bs4 import BeautifulSoup import time class Linktree: def __init__(self, config, permutations_list): # 1000 ms self.delay = config['plateform']['linktree']['rate_limit'] / 1000 # https://linktr.ee/{username} self.format = config['plateform']['linktree']['format'...
StarcoderdataPython
251133
<reponame>baajur/benchm-ml<filename>4-DL/3-keras.py from __future__ import print_function from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD from keras.utils import np_utils from keras import backend as K import numpy as np import time import pandas as pd from sklearn ...
StarcoderdataPython
342953
# -*- coding: utf-8 -*- """ Module for evaluating detection performance. .. automodule:: pydriver.evaluation.evaluation """ from __future__ import absolute_import, division from .evaluation import Evaluator, EvaluatorPoint
StarcoderdataPython
8111112
<filename>src/sentry/utils/colors.py from __future__ import absolute_import import hashlib import colorsys def get_hashed_color(string, l=0.5, s=0.5): # noqa: E741 val = int(hashlib.md5(string.encode("utf-8")).hexdigest()[:3], 16) tup = colorsys.hls_to_rgb(val / 4096.0, l, s) return "#%02x%02x%02x" % (i...
StarcoderdataPython
3267763
<filename>src/rewriteu2a.py #!/usr/bin/env python # Replaces Unicode characters in input XML file text content with # ASCII approximations based on file with mappings between the two. # This is a component in a pipeline to convert PMC NXML files into # text and standoffs. The whole pipeline can be run as # # pytho...
StarcoderdataPython
1696228
<reponame>Antonio-Neves/Brasil-Portugal<gh_stars>1-10 """ Models for User Account - The username is the Email and not a name. - The user is staff """ from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): use_in_migrations =...
StarcoderdataPython
3318457
<reponame>tomijarvi/kerrokantasi<filename>democracy/factories/user.py # -*- coding: utf-8 -*- import factory import factory.fuzzy from django.contrib.auth import get_user_model class UserFactory(factory.django.DjangoModelFactory): class Meta: model = get_user_model() # XXX: This makes this file not safe...
StarcoderdataPython
6633587
from math import * from decimal import * import numpy as np # getcontext().prec define a quantidade de casas decimais a calculadas com precisão getcontext().prec = 8 # define novo valor pi com uma precisão maior que a nativa na biblioteca math pi = Decimal('3.141592653589793238462643383279502884197169399375') # Gera...
StarcoderdataPython
204743
"""Given GO ids and an obo, creates a small sub-graph DAG. Sub-graphs can be used to create shortcut paths and eliminate nodes. """ from collections import defaultdict from goatools.godag_small import GODagSmall __copyright__ = "Copyright (C) 2016-2017, <NAME>, <NAME>, All rights reserved." __author__ = "<NAME>" ...
StarcoderdataPython
11315363
<reponame>carsonmclean/CSC411-CSC2515 import csv import nltk from nltk.tokenize import word_tokenize import re, string; pattern = re.compile('[^a-zA-Z0-9_]+') def write_fake(): titles = set() try: for line in csv.DictReader(open("data/fake.csv")): if line['thread_title']: ot...
StarcoderdataPython
6553510
# Generated by Django 2.1.4 on 2019-02-11 22:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('assets', '0005_carrealtimetest'), ] operations = [ migrations.AlterField( model_name='carrealtimetest', name='Chargi...
StarcoderdataPython
1970477
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\apartments\situations\neighbor_complaint_response.py # Compiled at: 2016-03-24 21:44:32 # Size of so...
StarcoderdataPython
326538
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class SpotFleetRequest(pulumi.CustomR...
StarcoderdataPython
1813766
# Utility module for RF objects #------------------------------------------------------------------------------- import collections import numpy as np from probayes.vtypes import isscalar from probayes.pscales import iscomplex, rescale, prod_rule, prod_pscale #---------------------------------------------------------...
StarcoderdataPython
143529
<gh_stars>1000+ try: import distutils from distutils import sysconfig from distutils.command.install import install from distutils.core import setup, Extension except: raise SystemExit, "Distutils problem" prefix = "__PREFIX__" inc_dirs = [prefix + "/include"] lib_dirs = [prefix + "/lib"] libs = ["...
StarcoderdataPython
1731695
<filename>prj/Complaint.py #main program import spacy import pandas as pd import preprocess from preprocess import data_clean #preprocess.py import dataframes from dataframes import dataframing import tokenise from tokenise import tokenisation import frequency from frequency import word_frequency import topwords from t...
StarcoderdataPython
5010197
<reponame>tpimentelms/phonotactic-complexity<gh_stars>1-10 import numpy as np import sys sys.path.append('./') from data_layer.parse import read_src_data from model import opt_params from util import argparser from train_base import read_info, write_csv, convert_to_loader, _run_language full_results = [['lang', 'fold...
StarcoderdataPython
244122
from OctaHomeCore.OctaFiles.menus import * class DeviceUsersSettingsNavBarItem(SettingsSideNavBarItem): Priority = 60 DisplayName = "Device Logins" @property def Link(self): return reverse('SettingsPage', kwargs={'page':'DeviceUsers'})
StarcoderdataPython
11309405
import importlib from django.conf import settings def str_to_class(s): modules = s.split(".") concrete = modules[-1] modules = ".".join(modules[:-1]) mod = importlib.import_module(modules) return getattr(mod, concrete) def concrete_list(l): return list(map(str_to_class, l)) def unpack_requ...
StarcoderdataPython
3439417
#!/usr/bin/env python3 from __future__ import print_function import sys import os from array import array import cv2 import numpy as np import time import openncc as ncc import struct min_score = 0.8 media_head = 'iII13I' def coordinate_is_valid(x1, y1, x2, y2): if ((x1 < 0) or (x1 > 1)): ...
StarcoderdataPython
11253170
"""A Tcl kernel for Jupyter""" __version__ = '0.0.4'
StarcoderdataPython
1920127
<gh_stars>0 import datetime from flask import * import MySQLdb import gc def connection(): conn = MySQLdb.connect(host="localhost", user="root", passwd="<PASSWORD>", db="inventory") c = conn.cursor() return c, conn app = Fla...
StarcoderdataPython
8167674
''' A collection of example models that can be fed into zap-cosmics. ''' from .imports import * class Model(): ''' A base model, defining a handy plot tool. ''' def plot(self, tmin=-0.5, tmax=0.5, n=1000, **plotkw): t = np.linspace(tmin, tmax, n) plt.plot(t, self(t), label='{}'.format(...
StarcoderdataPython
5179577
# -*- coding: utf-8 -*- # -------------------------------------------------------------------------- # _____ ______________ # | __ \ /\|__ ____ __| # | |__) | / \ | | | | # | _ / / /\ \ | | | | # | | \ \/ ____ \| | | | # |_| \_\/ \_\_| |_| ... RFID ALL THE THINGS! # # A resource acc...
StarcoderdataPython
6563298
#!/usr/bin/env python # coding=utf-8 """ Unit tests for pygit module/PyGit class. Created: <NAME>, 24.04.2019 Modified: <NAME>, 25.05.2019 """ import unittest from pyutilities.tests.pyutils_test_helper import get_test_logger from pyutilities.pygit import PyGit class PyGitTest(unittest.TestCase): ...
StarcoderdataPython
187887
<reponame>dansandu/praline<gh_stars>0 from os.path import normpath from praline.client.project.pipeline.stages.load_clang_format import clang_format_style_file_contents, ClangFormatConfigurationError, load_clang_format from praline.common.testing.file_system_mock import FileSystemMock from unittest import TestCase cl...
StarcoderdataPython
6486937
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 22 08:49:20 2019 @author: john.onwuemeka; <NAME> """ import numpy as np from obspy.core import UTCDateTime def read_eventlist(self): """ Description: ------------ Read events infomation. Input: ------- events.dat: ...
StarcoderdataPython
1983264
<filename>010.py # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. def prastevilo(n): """ Pogleda, če je n praštevilo. """ if n <= 1: return False for i in range(2, round(n**(1/2) + 1)): if n % i == 0: return False re...
StarcoderdataPython
1608867
import sys,os,pickle,argparse import numpy as np from models import * from sklearn.model_selection import KFold #deprecated #from sklearn.cross_validation import KFold from scrape import * import argparse from torch.multiprocessing import Pool from random import shuffle def fit(X,Y,model,criterion= nn.NLLLoss(),epochs...
StarcoderdataPython
3348800
# -*- coding: utf-8 -*- """ Created on Fri Mar 6 20:19:31 2015 @author: matt """ import ete2 from taxonomy import taxonomy def build_tree_from_dict(dict_tree, tree=None): if tree is None: tree = ete2.Tree(name="root") for parent, children in dict_tree.iteritems(): subtree = tree.add_child(na...
StarcoderdataPython
9674464
""" Various processing utility functions Usage: import only """ import os import pandas as pd from pycytominer.cyto_utils import infer_cp_features def load_data( batch, profile_dir="profiles", suffix="normalized_feature_selected.csv.gz", combine_dfs=False, add_cell_count=False, cell_count_d...
StarcoderdataPython
3309662
<reponame>jappa/PyFR # -*- coding: utf-8 -*- """Converts .pyfr[m, s] files to a Paraview VTK UnstructuredGrid File""" from copy import copy import numpy as np import sympy as sy from pyfr.bases import BaseBasis, get_std_ele_by_name from pyfr.inifile import Inifile from pyfr.readers.nodemaps import GmshNodeMaps from ...
StarcoderdataPython
5085310
<filename>apps/snippet/models/__init__.py<gh_stars>0 from .snippet_models import Snippet
StarcoderdataPython
3403447
# -*- coding: utf-8 -*- from functools import wraps from datetime import datetime import socket from flask import current_app, request, make_response # Logging utils # def after_request_log(response): name = dns_resolve(request.remote_addr) current_app.logger.warn(u"""[client {ip} {host}] {http} "{method} {...
StarcoderdataPython
9724435
META = { 'author': '<NAME>, <NAME>', 'description': 'Rules for browser fuzzing', 'type':'Folder', 'comments': ['All rules must trigger a() function'] }
StarcoderdataPython
11295997
<filename>barcode_parser.py ''' Descripttion: version: Author: zpliu Date: 2021-07-15 20:29:47 LastEditors: zpliu LastEditTime: 2021-08-04 16:09:10 @param: ''' import pandas as pd import os import re import gzip import argparse import logging logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(leveln...
StarcoderdataPython
321472
<reponame>zhengfaning/vnpy_andy<gh_stars>1-10 # coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function # noinspection PyUnresolvedReferences from win32api import * # Try and use XP features, so we get alpha-blending etc. try: from winxpgui import ...
StarcoderdataPython
9760013
<reponame>Gwarglemar/PythonExercises class Card(): def __init__(self,suit,num): self.suit = suit self.num = num def __str__(self): return str(self.num + ' of ' + self.suit) __repr__ = __str__
StarcoderdataPython
4837385
<reponame>daojunL/Art-Event-Gallery # Generated by Django 2.1.5 on 2020-04-21 04:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dashboard', '0005_auto_20200421_0331'), ] operations = [ migrations.AlterModelOptions( name='artist'...
StarcoderdataPython
3228691
<filename>checks/checksls.py import yaml import sys from jinja2 import Environment, PackageLoader, Template import os def check(fn): print("Consider {0}".format(fn)) r = os.system("~/.local/bin/pylint -E --rcfile=pylint.rc %s" % fn) if r not in (0, 512) : # 512= check failed raise Exception('fail ...
StarcoderdataPython
5102374
<reponame>wang-junjian/scrapy-hub # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import scrapy import os import logging class ChinesePipeline(object): mp3_dir = 'mp3/' ...
StarcoderdataPython
11334643
import cv2 import torch import numpy as np import sys import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from .baseline.utils.tensorboard import TensorBoard from .baseline.Renderer.model import FCN from .baseline.Renderer.stroke_gen import * from argparse import Namespace torch.manual_...
StarcoderdataPython
1602483
# (c) Copyright 2022 <NAME> # # Short test program for arduino_dbg.io. import arduino_dbg.io as io import os if __name__ == "__main__": (left, right) = io.make_bidi_pipe() pid = os.fork() if pid == 0: # Child left.open() s = "Major Tom to ground control\n" left.write(s.enc...
StarcoderdataPython
12843857
# -*- coding: utf-8 -*- """ Created on Mon Jan 15 12:16:14 2018 @author: gdavila This is a example to get Full Band Channel information On Docsis 3.0 Full Band Channels is a feature that allows to get detailed info about the power distribution of the espectrum """ import docsisMon.cmDevices as cmDevices from docsis...
StarcoderdataPython
11303370
import os import glob import datetime import calendar def configuration_file(ncpu=16, start_date='19990101', end_date='19990131'): conf_txt = """#!/bin/bash #PBS -P en0 #PBS -q normal #PBS -l walltime=15:00:00 #PBS -l mem={mem}GB #PBS -l wd #PBS -l ncpus={cpu} #PBS -lother=gdata2 source activate radar python raji...
StarcoderdataPython
287181
############################################################################# # Dynamic time warping for 2D images import sys from java.awt import * from java.awt.image import * from java.io import * from java.lang import * from java.util import * from java.nio import * from javax.swing import * from edu.mines.jtk.aw...
StarcoderdataPython
6635490
<reponame>EneaMapelli/SafecastPy # -*- coding: utf-8 -*- """ SafecastPy.exceptions ~~~~~~~~~~~~~~~~~~ This module contains SafecastPy specific Exception classes. """ class SafecastPyError(Exception): """Generic error class, catch-all for most SafecastPy issues. Special cases are handled by TwythonAuthError &...
StarcoderdataPython
11361177
class Car: def __init__(self, maker, model): self.maker = maker self.model = model def __repr__(self): return f'<Car {self.maker} {self.model}>' class Garage: def __init__(self): self.cars = [] def __len__(self): return len(self.cars) def add_car(self, ca...
StarcoderdataPython
3325831
<reponame>AguilaDFG/Python from turtle import Turtle, Screen from random import randint turtle = Turtle() screen = Screen() screen.colormode(255) for a in range(50,randint(100,200)): turtle.setheading(90*randint(0,4)) turtle.speed(a/20) turtle.pensize(a/20) turtle.pencolor(randint(0,255), randint(0,255)...
StarcoderdataPython
12806037
import pandas as pd from bs4 import BeautifulSoup import requests import os # scrapes and saves average player stats when imported. from scraping_scripts.player_per_game_scrape import player_per_game_std def avg_dfs_score(): # read in data that was scraped via import statment df = pd.read_csv('scraped_da...
StarcoderdataPython
9792669
<gh_stars>1-10 import torch from torch.utils.data import Dataset, DataLoader import numpy as np from PIL import Image Image.MAX_IMAGE_PIXELS = None from data import get_train_transform, get_test_transform class CustomDataset(Dataset): img_aug = True imgs = [] transform = None def __init__(self, labe...
StarcoderdataPython
3404196
<reponame>rrgaya-zz/client-manager<filename>clientes/templatetags/filters.py from django import template register = template.Library() @register.filter def meu_filtro(data): return data + " - " + "Alterado pelo filtro" @register.filter def arredonda(value, casas): return round(value, casas) @register.fil...
StarcoderdataPython
8098173
<gh_stars>0 class MocketException(Exception): pass class StrictMocketException(MocketException): pass
StarcoderdataPython
1648621
<filename>concurrenflict/forms.py import simplejson from django import forms from django.core import serializers from django.utils.html import mark_safe class ConcurrenflictFormMixin(forms.ModelForm): """ Compares model instance between requests: first at for render, then upon submit but before save (i.e. on ...
StarcoderdataPython
4962085
# # Copyright (C) <NAME> 2020 <<EMAIL>> # import configparser import keyring import sqlite3 import subprocess import bluetooth import gi import datetime from . import config from .config import log from . import utility from .utility import WorkerThread gi.require_version('Gtk', '3.0') from gi.repository import Gtk,...
StarcoderdataPython
12846147
__author__ = '<NAME>' from pymongo import MongoClient import detectlanguage import json import logging import time logging.basicConfig( filename='emovix_twitter_detectlang.log', level=logging.WARNING, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%d-%m-%y %H:%M') # Configurat...
StarcoderdataPython
11346981
<reponame>asijit123/Python<filename>text_cleaning_comparisson.py<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[63]: from string import punctuation from unidecode import unidecode from time import process_time from re import sub, compile from nltk.corpus import stopwords, gutenberg from nltk.tokenize import ...
StarcoderdataPython
1947968
<gh_stars>1-10 def random_search(space, num_samples): configs = [] for _ in range(num_samples): c_ = {} for param_name, sample in space.items(): c_[param_name] = sample() configs.append(c_) return configs
StarcoderdataPython
140980
<reponame>UT-Covid/compartmental_model_case_studies from .param import (Param, String, Float, Integer, ListStrings, ListFloats, ListInts) EPI_DEMOGRAPHIC_COHORTS = 5 EPI_SCENARIOS = 7 __all__ = ['MatlabIntDate', 'ListMatlabIntDates', 'Triangular', 'IntDateRange'] class Triangular(ListFloats): ...
StarcoderdataPython
11368517
from pyrogram import Client, Filters from config import cmds from utils import meval import traceback import html @Client.on_message(Filters.command("eval", prefixes=".") & Filters.me) async def evals(client, message): text = message.text[6:] try: res = await meval(text, locals()) except: ...
StarcoderdataPython
5184832
<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import datetime as dt import matplotlib.dates as mdates import os from datetime import datetime TRANSIENT = False #Model = 'Bertrand' #steps = 1000 #start = 0 #drainages = 46 #path = '../modelruns_BC_2016/' Model = 'WRIA1_s' steps = 16894 s...
StarcoderdataPython
11286420
<filename>flask_jwt_extended/jwt_manager.py from flask import jsonify class JWTManager: def __init__(self, app=None): # Function that will be called to add custom user claims to a JWT. self.user_claims_callback = lambda _: {} # Function that will be called when an expired token is receive...
StarcoderdataPython
367248
import torch import numpy as np def measure(vector): return (vector**2).sum() def expm(q,rtol=1e-3,maxStep=15): accumulator = torch.eye(q.shape[-1]).to(q) tmpq = q i = 1 error = rtol*measure(q) while measure(tmpq) >= error: accumulator = tmpq +accumulator i+=1 tmpq = to...
StarcoderdataPython
9643718
<filename>fsm.py from transitions.extensions import GraphMachine import time import random Hp = 60 Lp = 60 Lk = 60 def TAMAGOCHI(): ret = 'Lp: '+str(Lp)+'\n' + 'Hp: '+str(Hp)+'\n' + 'Like: '+str(Lk)+'\n' return ret #def FULL_TEST(): # if Lp <= 50: # ret = "尚未吃飽\n"+"[a] 繼續餵食\n"+"[b] 停止餵食\n" # ...
StarcoderdataPython
3244339
import unittest from base import BaseTestCase class CreditCardTestCase(unittest.TestCase, BaseTestCase): """ Test cases for Credit Card number removal removal. All these will clash with PASSPORT filth. """ def test_american_express(self): """ BEFORE: My credit card is 37828224631...
StarcoderdataPython
9746845
<filename>NCPWD/apps/topics/urls.py from django.urls import path, include from .views import TopicAPIView from rest_framework import routers app_name = "topics" router = routers.DefaultRouter() router.register(r"topics", TopicAPIView) urlpatterns = [path('', include(router.urls))]
StarcoderdataPython
74982
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch.utils.data as Data import numpy as np import time import sys import utils print('生成测试数据') n_train, n_test, num_inputs = 20, 100, 200 t...
StarcoderdataPython
3350730
from .datetimewindow import DatetimeWindow __version__ = '0.1'
StarcoderdataPython
6629882
<filename>slingen/src/algogen/BackEnd/trsm2lgen.py from core.expression import Equal, Times, Minus, Inverse, Transpose, NList, Predicate, PatternDot import core.properties as props from core.functional import RewriteRule, Constraint, Replacement import Config import PredicateMetadata as pm pm.DB["ldiv_lni"] = pm.Pred...
StarcoderdataPython
32250
#Calcular el salario neto de un tnrabajador en fucion del numero de horas trabajadas, el precio de la hora #y el descuento fijo al sueldo base por concepto de impuestos del 20% horas = float(input("Ingrese el numero de horas trabajadas: ")) precio_hora = float(input("Ingrese el precio por hora trabajada: ")) sueldo_ba...
StarcoderdataPython
6649996
<filename>challenges/counting_syllabes.py def count(text): syllabes = text.split('-') return len(syllabes)
StarcoderdataPython
8094375
<reponame>jcarrete5/drexel-api from django.db import models class Course(models.Model): title = models.CharField(max_length=50) crn = models.CharField(max_length=5) course_num = models.CharField(max_length=4) subject_code = models.CharField(max_length=4) description = models.TextField() prereq...
StarcoderdataPython
1864968
# Copyright 2018 The TensorFlow Probability Authors. # # 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 o...
StarcoderdataPython
3502657
<filename>python/8896.py<gh_stars>1-10 import sys input = lambda: sys.stdin.readline().rstrip() def conv(c): if c == 'R': return 0 if c == 'S': return 1 return 2 for _ in range(int(input())): n = int(input()) v = [input() for _ in range(n)] check = [0] * n for i in range(len(v[0])): ...
StarcoderdataPython
5089641
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
StarcoderdataPython
5113323
import http.server import socketserver import json import geocode import logging from http_service import Request, Response from geocode_service import handle_geocode_request logging.basicConfig(level=logging.INFO) PORT = 8000 # Listening on all network interfaces on the given port listening_address = ("", PORT) LO...
StarcoderdataPython
9775548
# Decimal > Hex > ASCII converter. # by MikeTheScriptKid. # I made this for a CTF challenge on THM to decode a flag. decimal = int(input("Enter your decimal: ")) hex = hex(decimal)[2:] ascii = bytearray.fromhex(hex).decode() print("HEX:", hex , "\n" "ASCII:", ascii)
StarcoderdataPython
3334513
# Readable: can read during runtime/compile time # Writeable: can write during runtime and compile time """ ============ | List/Array | ============ Ordered Readable Writeable """ fooList = ["fooListItem", 123, True]; anotherList = list(("anotherListItem", 456, False)); print(fooList); print(...
StarcoderdataPython
9661192
def bubble_sort(items): ''' Return array of items, sorted in ascending order """ the bubble_sort algorithm takes in an unsorted list of numbers. returns a list in ascending order. Parameter ---------- items : list list of unordered numbers ...
StarcoderdataPython
11214104
import unittest from rekcurd.utils import RekcurdConfig, ModelModeEnum from rekcurd.data_servers import CephHandler from . import patch_predictor class CephHandlerTest(unittest.TestCase): """Tests for CephHandlerTest. """ def setUp(self): config = RekcurdConfig("./test/test-settings.yml") ...
StarcoderdataPython
8057389
from pyDiamondsBackground import Background from pyDiamondsBackground.models import WhiteNoiseOnlyModel bg = Background(kicID='123456789', modelObject=WhiteNoiseOnlyModel, rootPath="exampleFiles") bg.run() bg.writeResults("exampleFiles/results/KIC123456789/run", "background_")
StarcoderdataPython
326403
<filename>benchmarks/benchmark.py import os import sys import re import subprocess import traceback import statistics python = "python3" progname = "/Users/emery/git/scalene/benchmarks/julia1_nopil.py" number_of_runs = 1 # We take the average of this many runs. # Output timing string from the benchmark. result_regexp...
StarcoderdataPython
1795466
<reponame>PolusAI/toil # Copyright (C) 2015-2022 Regents of the University of California # # 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
3476110
<reponame>RhnSaxena/KonfHub import requests import json # Function that a link as a string parameter, # performs GET operation on the link # and returns the response. def requestGet(link): response = requests.get(link) if response.status_code == 200: return json.loads(response.text) else: p...
StarcoderdataPython
6476817
<reponame>paras55/officialWebsite from django.db import models from officialWebsite.members.models import Member class Project(models.Model): name = models.CharField(max_length=255) description = models.TextField() project_lead = models.ForeignKey(Member, related_name='lead', on_delete=models.CASCADE) ...
StarcoderdataPython