id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3290392
from comrak._comrak import py_markdown_to_html, PyComrakOption COMRAK_UNSAFE_HTML = 'unsafe' COMRAK_EXT_AUTOLINK = 'ext_autolink' COMRAK_EXT_GFM_TABLE = 'ext_gfm_table' COMRAK_EXT_TABLE = COMRAK_EXT_GFM_TABLE def markdown_to_html(md, *extensions): """ Convert markdown to html :param str md: Markdown tex...
StarcoderdataPython
86975
<filename>code/chapter_04/listing_04_17.py<gh_stars>10-100 import pandas as pd import matplotlib.pyplot as plt my_dataset = pd.read_excel( 'Smith_glass_post_NYT_data.xlsx', sheet_name='Supp_traces') epochs = ['one', 'two', 'three', 'three-b'] colors = ['#c8b4ba', '#f3ddb3', '#c1cd97', '#e18d96'] markers = ['o', '...
StarcoderdataPython
1682038
<gh_stars>1-10 # Copyright © 2019 Province of British Columbia # # 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 applic...
StarcoderdataPython
76673
import pytest from antu.io.token_indexers.single_id_token_indexer import SingleIdTokenIndexer from antu.io.fields.text_field import TextField from collections import Counter from antu.io.vocabulary import Vocabulary class TestSingleIdTokenIndexer: def test_single_id_token_indexer(self): sentence = ['This'...
StarcoderdataPython
1724686
<filename>controller/archive/jsconverter.py from evdev import InputDevice, categorize, ecodes from threading import Thread class JSConverter(Thread): MLIMITLOW = 32 LLIMITLOW = 96 MLIMITHIGH = 255 LLIMITHIGH = 512 VALID_CODES = [0,1,3,4] def __init__(self, device): Thread.__init__(self...
StarcoderdataPython
3357211
<filename>apps/config.py # common FILE_NAME_URL_PREFIX = '.url_prefix' SESSION_KEY_URL_PREFIX = 'url_prefix' SESSION_KEY_URL_INDEX = 'url_index' ROOTDIR = 'apps/' # auth APP_NAME_AUTH = 'auth' URL_INDEX_AUTH = '/auth' ## DB NAME DBNAME_AUTH = 'user.db' DBDIR_AUTH = 'apps/' ## request form key FORM_KEY...
StarcoderdataPython
4800203
import os import math import argparse import time import tensorflow as tf from ruamel.yaml import YAML, dump, RoundTripDumper from raisim_gym.env.RaisimGymVecEnv import RaisimGymVecEnv as Environment from raisim_gym.env.env.ANYmal import __ANYMAL_RESOURCE_DIRECTORY__ as __RSCDIR__ from raisim_gym.algo.ppo3 import PPO3 ...
StarcoderdataPython
148474
""" System - Bot management commands Dependancies: Auth """ from enum import Enum from glob import glob import asyncio, os from typing import Optional import disnake from disnake.ext import commands class Actions(int, Enum): """ Actions that can be performed on an option """ list = 0 load = 1 unload = 2 ...
StarcoderdataPython
194883
from typing import List, Optional from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from sqlalchemy_utils import TSVectorType from dispatch.database import Base from dispatch.enums import Visibility from dispatch.models import DispatchBase class IncidentType(Base): ...
StarcoderdataPython
1791366
<filename>fenix/engine/service.py # Copyright (c) 2018 OpenStack Foundation. # 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/...
StarcoderdataPython
142822
<reponame>xiaohalo/LeetCode # Time: O(n * l^2) # Space: O(n * l) # Given a list of words, please write a program that returns # all concatenated words in the given list of words. # # A concatenated word is defined as a string that is comprised entirely of # at least two shorter words in the given array. # # Example: ...
StarcoderdataPython
3379616
<filename>_13_FUNCTIONS/_5_Calculate_Rectangle_Area.py width = int(input()) height = int(input()) def area(a, b): return a * b print(area(width, height))
StarcoderdataPython
18062
<gh_stars>1-10 from django.conf.urls import patterns, url from main import views urlpatterns = patterns('', url(r'^$', views.inicio, name='inicio'), url(r'^acerca/', views.acerca, name='acerca'), url(r'^contacto/', views.contacto, name='contacto'),...
StarcoderdataPython
114765
<gh_stars>1-10 def yield_test(n): for j in range(n): yield call(j) print("j=",j) #做一些其它的事情 print("do something.") print("end.") def call(j): return j*2 #使用for循环 # for i in yield_test(5): # print(i,",") def createGenerator(): mylist = range(3) for i in mylist: y...
StarcoderdataPython
3367012
<gh_stars>1-10 from ..utils import convert_to_snake_case PRINT_IMPORTS = ['from django.forms.models import model_to_dict', 'from django.conf import settings', 'from django.test import TestCase', 'from django.db import IntegrityError' ] PRINT_TEST_CLAS...
StarcoderdataPython
181325
<gh_stars>0 import decimal import math from dislog.util import debug def _round_sqrt(n): # Conversion to handle decimal operations on big numbers dec_n = decimal.Decimal(n) # Set precision for calculating the square root of n up to at least one # digit beyond the decimal point num_digits = dec_n.a...
StarcoderdataPython
1700767
# Lint as: python3 # Copyright 2020 DeepMind Technologies Limited. 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 # # https://www.apache.org/licenses/LICENSE-2.0 # #...
StarcoderdataPython
3329524
<reponame>sih4sing5hong5/tai5-uan5_gian5-gi2_phing5-tai5<gh_stars>10-100 from 臺灣言語資料庫.資料模型 import 來源表 from 臺灣言語資料庫.資料模型 import 版權表 from 臺灣言語資料庫.欄位資訊 import 會使公開 from 臺灣言語資料庫.資料模型 import 種類表 from 臺灣言語資料庫.欄位資訊 import 字詞 def before_scenario(context, scenario): 種類表.objects.get_or_create(種類=字詞) 來源表.objects.get_or_...
StarcoderdataPython
1687740
import pandas as pd def read(file_name): extension = file_name[-3:] if extension == 'psv': sep = '|' elif extension == 'tsv': sep = '\t' else: sep = ',' return pd.read_csv(file_name, sep=sep) # variable_map = { # 'temperature': ['Temp', 'temp', 'TEMPERATURE'] # } variable_map = { 'temperature': 'Temp...
StarcoderdataPython
1795579
a = range(30) print a[19::-7]
StarcoderdataPython
4809118
# # MythBox for XBMC - http://mythbox.googlecode.com # Copyright (C) 2011 <EMAIL> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) a...
StarcoderdataPython
3396175
import numpy as np from pathlib import Path from argparse import ArgumentParser import matplotlib.pyplot as plt import matplotlib.cm as cm from configparser import ConfigParser class ConfigParser_with_eval(ConfigParser): def get(self, *argv, **kwargs): import numpy val = super(ConfigParser_with_ev...
StarcoderdataPython
3224732
<gh_stars>0 #!/usr/bin/env python3 import hashlib def part1(inp): ans = 0 for x in inp.split("\n"): if len(x)>0: ans += fuelCounter(int(x)) return ans def part2(inp): ans = 0 for x in inp.split("\n"): if len(x)>0: ans += realFuelCounter(int(x)) return an...
StarcoderdataPython
3272866
<reponame>gurmeetkhehra/python-practice alien_color = 'green' if alien_color == 'green': print('You just got five points!') houses = [] print(houses) houses = () print (houses)
StarcoderdataPython
1646473
from keras import backend as K from keras.models import load_model from keras.optimizers import Adam #from scipy.misc import imread import numpy as np from matplotlib import pyplot as plt import argparse import json from models.keras_ssd300 import ssd_300 from keras_loss_function.keras_ssd_loss import SSDLoss from ker...
StarcoderdataPython
1791200
import torch from torchvision import datasets, models, transforms import torch.nn as nn from torch.nn import functional as F import torch.optim as optim import torchvision import numpy as np import matplotlib.pyplot as plt from PIL import Image import os import random from src.model import CrackClassifier from src.data...
StarcoderdataPython
57991
import numpy as np import pandas as pd import datetime as dt import operator import time import os def most_common_day(dataframe): start = time.time() most_common_day_dict = dataframe['Day of the Week'].value_counts().to_dict() popular_day_of_the_week = max(most_common_day_dict.items() , key=operator.item...
StarcoderdataPython
103461
#! /usr/bin/env python3 import numpy as np from sklearn.metrics import adjusted_rand_score as ari from sklearn.preprocessing import LabelEncoder as labeler import lsbm ## Import labels lab = np.loadtxt('../data/drosophila_labels.csv', dtype=str) lab = labeler().fit(lab).transform(lab) ## Import embeddings X = np.loadt...
StarcoderdataPython
3379618
<reponame>indylab/xdo import math from math import pi import numpy as np from gym.spaces import Box, Discrete from ray.rllib.utils import merge_dicts from ray.rllib.env.multi_agent_env import MultiAgentEnv def direction_to_coord(direction): """takes x \in [0,1), returns 2d coords on unit circle""" return tupl...
StarcoderdataPython
1760920
<reponame>sysr-q/wopr.py<filename>wopr/__init__.py<gh_stars>1-10 # -*- coding: utf-8 -*- import cmd import sys import socket import gevent import gevent.server from gevent import sleep from telnetsrv.green import TelnetHandler, command import junk class Phases(object): LOGON = 0 GAMES = 1 JOSHUA = 2 ...
StarcoderdataPython
3204520
<filename>pyqg/diagnostic_tools.py<gh_stars>0 """Utility functions for pyqg model data.""" import numpy as np from numpy import pi def spec_var(model, ph): """Compute variance of ``p`` from Fourier coefficients ``ph``. Parameters ---------- model : pyqg.Model instance The model object from wh...
StarcoderdataPython
3397851
from setuptools import setup, find_packages setup( name="jasmine", version="3.1.2", url="http://jasmine.github.io", author="<NAME>", author_email="<EMAIL>", description=('Jasmine is a Behavior Driven Development' ' testing framework for JavaScript.' ' It does n...
StarcoderdataPython
1785758
<gh_stars>100-1000 # (C) Copyright 2019 IBM Corp. # # 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 ag...
StarcoderdataPython
3343794
<gh_stars>0 from unittest import TestCase import os,sys,inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent_dir) import megszamol class TestOsszeg(TestCase): def test_feladat02(self): aktualis =...
StarcoderdataPython
3210331
from flask import Flask from flask.ext.socketio import SocketIO as ServerSocketIO, send socketio = ServerSocketIO() def create_app(config_name): app = Flask(__name__) socketio.init_app(app) return app, socketio @socketio.on('message') def test_message(message): send('', "Hello, " + message) #emit...
StarcoderdataPython
1638683
# Modules import string import inspect import importlib from os import listdir from os.path import exists from ..utils.colors import color from ..utils.logging import error from .runtime.exec import Executer from ..utils.bases import BaseCommand from .runtime.globals import generate_globals # Storage object class ...
StarcoderdataPython
1694046
import logging import unittest from panda3d.core import ConfigVariableBool ConfigVariableBool('editor_mode', False).set_value(True) ConfigVariableBool('no_ui', False).set_value(True) logging.basicConfig( level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', ) if __name__ == '__main__': ...
StarcoderdataPython
1676253
from openslides_backend.shared.filters import And, FilterOperator, Not, Or def test_filter_operator() -> None: filter = FilterOperator("f", "=", 1) assert filter.to_dict() == { "field": "f", "operator": "=", "value": 1, } def test_not_operator() -> None: filter = FilterOperat...
StarcoderdataPython
3219029
<gh_stars>0 # -*- coding: utf-8 -*- from requests import post from factory import create_celery_app celery = create_celery_app() @celery.task def CR_installer(crs_csrs_payload, sink_url, source_url): # Get these as parameter or inside crs_csrs_payload endpoint = "/api/1.2/cr/add_cr" print(crs_csrs_payload...
StarcoderdataPython
24667
from django import forms class ContactForm(forms.Form): user_name = forms.CharField(max_length=60, label='', required=True, widget=forms.TextInput(attrs={'placeholder': '<NAME>'})) user_email = forms.EmailField(label='', required=True) message = forms.CharField(label='', required=True, widget=forms.Texta...
StarcoderdataPython
124341
<filename>usienarl/agent.py # # Copyright (C) 2019 <NAME> # University of Siena - Artificial Intelligence Laboratory - SAILab # # # USienaRL is licensed under a BSD 3-Clause. # # You should have received a copy of the license along with this # work. If not, see <https://opensource.org/licenses/BSD-3-Clause>. # Import ...
StarcoderdataPython
3309570
import os import gc import atexit from sys import exit import numpy as np from scipy import sparse from sklearn.ensemble import RandomForestRegressor import joblib import h5py from .validation import Validation from .plot import Plot from .utils import convert_1d_arrays, create_directories from .conf import set_rf_para...
StarcoderdataPython
88021
<gh_stars>0 from enum import Enum class EventTypes(Enum): LOG_IN = "sn.user.login" LOG_IN_CHALLENGE = "sn.user.login.challenge" LOG_IN_FAILURE = "sn.user.login.failure" LOG_OUT = "sn.user.logout" SIGN_UP = "sn.user.signup" AUTH_CHALLENGE = "sn.user.auth.challenge" AUTH_CHALLENGE_SUCCESS = ...
StarcoderdataPython
4813671
# -*- coding: utf-8 -*- # Copyright (c) 2013 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. """All things Chrome OS signing related""" from __future__ import print_function import os from six.moves import configpars...
StarcoderdataPython
17910
import flask import functools import bs4 import urllib.parse from .. import auth from .. import themes from .. import settings INVALID_PERMISSIONS_FLASH_MESSAGE = "Sorry, you don't have permission to view that page." def checkForSession(): if "uid" in flask.session: session = auth.validateSession(flask.se...
StarcoderdataPython
4821123
""" Copyright 2020-2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwa...
StarcoderdataPython
28054
<filename>assignments/assignment2/solutions/Nkarnaud/devhub-0.1.0/src/account/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from account.models import Account class AccountCreateForm(UserCreationForm): first_nam...
StarcoderdataPython
1796044
import os import gc import time import torch import random import argparse import numpy as np import pandas as pd from glob import glob from trains import * from config import * from utils.log import * from utils.metricsTop import * from utils.functions import * from utils.gpu_memory_log import gpu_memory_log from mod...
StarcoderdataPython
4823704
import requests from parsel import Selector BASE_URL = 'https://www.fifaindex.com' START_URL = BASE_URL + '/players/fifa18wc/' def parse(resp: requests.Response): sel = Selector(resp.text) player_css = 'td[data-title="Name"] a::attr(href)' tasks = [(BASE_URL + url, parse_player) for url in sel.css(play...
StarcoderdataPython
182480
import os import torch from torchvision.datasets import MNIST from data import DATA_PATH class UnsupervisedMNIST(MNIST): def __init__(self, root=DATA_PATH, train=True, transform=None, download=False, label=False): super(UnsupervisedMNIST, self).__init__(root, ...
StarcoderdataPython
149542
<filename>run.py #!/usr/bin/env python import json from flask import Flask, request app = Flask(__name__) def start_tcp_server(): @app.route("/hello") def hello(): response = {} response["headers"] = dict(request.headers) response["request"] = dict(request.data) status_code = ...
StarcoderdataPython
1614522
# Generated by Django 2.2.9 on 2020-01-11 20:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('bio_app', '0012_auto_20200111_2034'), ] operations = [ migrations.AlterField( model_name='gene_...
StarcoderdataPython
168917
import json import typing import jsonrpcclient as rpc_client from pycspr.api import constants from pycspr.client import NodeConnectionInfo from pycspr.serialisation.json.encoder.deploy import encode_deploy from pycspr.types import Deploy def execute(connection_info: NodeConnectionInfo, deploy: Deploy) -> str: ...
StarcoderdataPython
3212384
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 5 20:12:09 2019 @author: jsulloa """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import pickle from maad import features from librosa.core import resample def rms(s): return np.sqrt(np.mean(s**2)) fpath = '../platan...
StarcoderdataPython
1666758
import argparse import asyncio import csv import logging import os import random import time import statistics import numpy as np from nepytune.benchmarks.query_runner import get_query_runner from nepytune.benchmarks.connection_pool import NeptuneConnectionPool QUERY_NAMES = [ 'get_sibling_attrs', 'undecided_use...
StarcoderdataPython
1655785
<reponame>andersjo/hals<gh_stars>0 import random from typing import List, Any import numpy as np from sentences import Sentence from transition_parser.parallel_util import ParallelParse, SentenceBatch from transition_parser.performance import measure_performance class ThreadedTransitionParser: def __init__(self...
StarcoderdataPython
1664710
<filename>tools/nntool/graph/types/tensor_arithmetic.py # Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # Licen...
StarcoderdataPython
1746543
<gh_stars>0 # --------------------------------------------------------------------------- # # PIECTRL Control wxPython IMPLEMENTATION # Python Code By: # # <NAME>, @ 31 Oct 2005 # Latest Revision: 30 Nov 2009, 17.00 GMT # # # TODO List/Caveats # # 1. Maybe Integrate The Very Nice PyOpenGL Implementation Of A PieChart C...
StarcoderdataPython
3399952
import networkx as nx import EoN import matplotlib.pyplot as plt G = nx.grid_2d_graph(100,100) #each node is (u,v) where 0<=u,v<=99 #we'll initially infect those near the middle initial_infections = [(u,v) for (u,v) in G if 45<u<55 and 45<v<55] sim = EoN.fast_SIS(G, 1.0, 1.0, initial_infecteds = initial_infections, ...
StarcoderdataPython
123767
<filename>forge.py<gh_stars>0 from flask import Flask, render_template app = Flask(__name__) def run(): print(render_template('blog.html', blog_text='This is my text')) with app.app_context(): run()
StarcoderdataPython
195
print(1)
StarcoderdataPython
1738598
<reponame>rhender5/mobile-deep-learning # -*- coding: utf-8 -*- """convert caffe model to the format the metal can read""" import os import sys import numpy as np caffemodel_file = "squeezenet_v1.1.caffemodel" out_dir = "./Parameters" print("Loading the Caffe model...") import caffe_pb2 data = caffe_pb2.NetParameter...
StarcoderdataPython
4801139
# Turtle moving around cubes ##### INFO ##### import turtle2 import random # Here we define a turtle and its speed t = turtle2.Turtle() t.speed("fastest") t.color("black") # Here we calculate the size of the screen screen = turtle2.Screen() screen.bgcolor("blue") width = screen.window_width() height = screen.window_...
StarcoderdataPython
1750068
<reponame>vagnerd/stack-mapping import time import logging import json import os from time import gmtime, strftime # # Environment Variables & File handling & logging # # --- Format for displaying actions display = "OwnerID : {} ! {:6.2f} % ! Region : {:16} ! {} ({}){}" # --- Initial values for inventory files nam...
StarcoderdataPython
3208419
#!/usr/bin/env python # coding: utf-8 # # # 读入数据 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt # In[2]: path = 'ex2data1.txt' exam1 = 'exam1' exam2 = 'exam2' admitted = 'admitted' data = pd.read_csv(path, header=None, names=[exam1, exam2, admitted]) # data.head() # # 可视化 # ...
StarcoderdataPython
122907
# imports import sys import argparse from gaevol import gaevol parser = argparse.ArgumentParser(description="Enter string you want to see evolve:") parser.add_argument("string", help="Add string without number and special characters") parser.add_argument("populate", help="Enter poplation of each Generation") parser.ad...
StarcoderdataPython
62672
<gh_stars>1-10 import datetime from gdata.analytics import client as ga_client from gdata.client import RequestError from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.contrib.sites.models import Site from django.conf import settings class AnalyticsSo...
StarcoderdataPython
171695
<reponame>RobinQrtz/egglayingwoolmilksow<gh_stars>0 import torch import torch.nn.functional as F from utils import batched_concat_per_row, create_parameter class Attention: @staticmethod def edge_factory(dim, attention_type): if attention_type == "bilinear": return BilinearEdgeAttention(di...
StarcoderdataPython
4834160
<filename>backend/intro/admin.py from django.contrib import admin from .models import Introduction, Links, NavTabs, ResumePDF # Register your models here. admin.site.register(Introduction) admin.site.register(Links) admin.site.register(NavTabs) admin.site.register(ResumePDF)
StarcoderdataPython
16037
import argparse import json from data_management.DatasetFactory import datasetFactory from config import cfg import numpy as np if __name__ == "__main__": parser = argparse.ArgumentParser(description='Calculates metrics from output of a Classification network.' + ...
StarcoderdataPython
3327968
# This example shows how you can access additional attributes from the request object. # For additional information on how to use the request object, see # https://bottlepy.org/docs/stable/tutorial.html#request-data # # Ex: curl -H "Say-Hello-To: John" http://<IP>:<PORT>/<FUNCTION>?greeting=Hola # should return "<N...
StarcoderdataPython
1780560
# Licensed Materials - Property of IBM # Copyright IBM Corp. 2020 import unittest import itertools import os import sys from streamsx.topology.topology import * from streamsx.topology.topology import Topology from streamsx.topology.context import submit, ContextTypes, ConfigParams, JobConfig class TestEdge(unittest....
StarcoderdataPython
3325213
import discord import sys import os import io import datetime import asyncio import aiohttp import random import json from discord.ext import commands class Economy: def __init__(self, bot): self.bot = bot @commands.command() async def daily(self, ctx): await ctx.send("You got $40...
StarcoderdataPython
118142
<reponame>CMU-313/fall-2021-hw2-451-unavailable-for-legal-reasons<filename>mayan/apps/user_management/handlers.py<gh_stars>1-10 from django.apps import apps def handler_initialize_new_user_options(sender, instance, **kwargs): UserOptions = apps.get_model( app_label='user_management', model_name='User...
StarcoderdataPython
143298
""" Purpose ------- A Portfolio represents a collection of Aggregate objects. Applications include * Model a book of insurance * Model a large account with several sub lines * Model a reinsurance portfolio or large treaty """ import collections import json import logging from copy import deepcopy import matplotl...
StarcoderdataPython
219
<reponame>jstzwjr/mmdetection<gh_stars>1-10 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule, build_upsample_layer from mmcv.ops import Conv2d from mmcv.ops.carafe import CARAFEPack from mmcv.runner import auto_fp16, force_fp32 from torch.nn.modules.u...
StarcoderdataPython
1794952
from flask import Flask from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from instance.config import app_config api = Api() db = SQLAlchemy() def create_app(config): app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[config]) db.init_app(app) ...
StarcoderdataPython
3376629
from typing import Optional from mlcube.common.utils import Utils class Status(object): RUNNING = 'RUNNING' STOPPING = 'STOPPING' TERMINATED = 'TERMINATED' class Instance(object): """ Just a wrapper around GCP instance dict v1. """ def __init__(self, instance: Optional[dict]) -> None: s...
StarcoderdataPython
4819369
def _primefactor(n): d = 2 l = [] c = 0 while n>1: if not(n%d): c += 1 n /= d if n==1: l.append((d,c)) else: if c>0: l.append((d,c)) c = 0 if d==2: d = 3 else: d += 2 return l def _ndivs(n): l = _primefactor(n) return reduce(lambda x,y: x*y,map(lambda x:x+1,[c for (d,c) ...
StarcoderdataPython
3351536
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 14 15:32:03 2021 @author: sohini """ # Importing the libraries import numpy as np from flask import Flask, request, jsonify, render_template import pandas as pd import pickle import os app=Flask(__name__)#create instance on flask model=pickle.loa...
StarcoderdataPython
1767959
<reponame>streamlit-badge-bot/a3-a3_proj_xi-shirley import subprocess import sys subprocess.check_call([sys.executable, "-m", "pip", "install", 'plotly']) subprocess.check_call([sys.executable, "-m", "pip", "install", 'sklearn']) import pandas as pd import streamlit as st import plotly.express as px from sklearn.model...
StarcoderdataPython
3222805
<reponame>AlbertoZerbinati/sentag<filename>users/models.py from django.db import models from tag_sentenze.models import Judgment, Task from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # create a custom user model class Profile(models.Mod...
StarcoderdataPython
3349682
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys import math import time import json import sqlite3 from werkzeug.wrappers import Response from werkzeug.exceptions import PreconditionFailed if sys.version_info < (2, 7): import __builtin__ class Float(float): def __new__(self, x, i): ...
StarcoderdataPython
3222020
from wordgoal.config.defaults import Defaults from wordgoal.config.file import File from wordgoal.config.files import Files from wordgoal.config.style import Style __all__ = ["Defaults", "File", "Files", "Style"]
StarcoderdataPython
1691601
from logging import getLogger from fastapi import FastAPI, Request, status from fastapi.exceptions import RequestValidationError from fastapi.logger import logger as fastapi_logger from fastapi.responses import ORJSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.middl...
StarcoderdataPython
1760727
import logging import rpyc from paramiko.client import AutoAddPolicy from plumbum import ProcessExecutionError from plumbum.machines.paramiko_machine import ParamikoMachine from rpyc.core.service import VoidService from rpyc.core.stream import SocketStream from rpyc.lib.compat import BYTES_LITERAL import signal def...
StarcoderdataPython
59614
<gh_stars>0 class TicTacToe: def __init__(self): self.cells = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] self.matrix = [self.cells[0:3], self.cells[3:6], self.cells[6:9]] # Vertical lines list, to be divided in 3 inner lists: self.v_lines = [] # Diagonal lines: sel...
StarcoderdataPython
1718545
from typing import Any, Optional import requests import requests_mock from requests import Response from helix_fhir_client_sdk.fhir_client import FhirClient def test_fhir_client_patient_delete() -> None: with requests_mock.Mocker() as mock: # Arrange url = "http://foo" def delete_matche...
StarcoderdataPython
3211417
# Switching to python... sorry. Haskell was too much to handle. import re import copy # 11573 for A too low # 17734 for A too low # 17738 for A was right # 17739 for A too high def parse(text): battle = [] faction = None counter = dict() for line in text.splitlines(): if line == "": continue if line =...
StarcoderdataPython
3341616
#!/usr/bin/env python3 import fileinput import logging from itertools import combinations from math import gcd class Moon(object): def __init__(self,x,y,z): self.x = x self.y = y self.z = z self.velx = 0 self.vely = 0 self.velz = 0 def update_relative_vel(self, other): if other.x > sel...
StarcoderdataPython
3324848
# -*- coding: utf-8 -*- # bot.py # speechrecognition, pyaudio, brew install portaudio import sys sys.path.append("./") import requests import datetime import dateutil.parser import json import RPi.GPIO as GPIO import time import calendar import psutil import os import traceback from nlg import NLG from speech0 impor...
StarcoderdataPython
3224896
<reponame>marcortiz11/FastComposedModels from Source.genetic_algorithm.fitting_functions import f1_time_param_penalization as fit from Source.system_evaluator import evaluate import Source.protobuf.FastComposedModels_pb2 as fcm import Source.protobuf.make_util as make import Source.io_util as io import numpy as np impo...
StarcoderdataPython
1752276
<filename>lib/bot.py """ Created by <NAME> on 1/6/2020. """ from lib import info from lib.command import Command from lib.logger import log_call, log from lib.config import save_whitelist, save_jackpot, Config, _format_dict from lib.formatter import Formatter from lib.live_counter import LiveCounter def _log_respons...
StarcoderdataPython
94578
<gh_stars>100-1000 # # FontNameToDisplayNameTransformer.py # ControlledPreferences # # Converted by u.fiedler on 04.02.05. # with great help from <NAME> - Thank you Bob! # # The original version was written in Objective-C by <NAME> # at http://homepage.mac.com/mmalc/CocoaExamples/controllers.html from Foundation...
StarcoderdataPython
1630046
from abc import ABC, abstractmethod class SenderInterface(ABC): """Interface for sending messages and photos""" @abstractmethod def send_message(self, message): """Method to send message""" @abstractmethod def send_photo(self, photo): """Method to send photo"""
StarcoderdataPython
1761039
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # MODEL POM - Princeton Ocean Model # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # # # ROUTINE: Profq # # DESCRIPTION # # ...
StarcoderdataPython
1749692
<filename>codes_auto/902.minimum-number-of-refueling-stops.py # # @lc app=leetcode.cn id=902 lang=python3 # # [902] minimum-number-of-refueling-stops # None # @lc code=end
StarcoderdataPython
121595
<filename>Python/hmm/test/__init__.py # # Copyright <NAME> 2007, 2008 # """ Code to test L{hmm}. """ import unittest from test_build_pssm import * from test_count_mers import * from test_simple_pssm import * if __name__ == '__main__': unittest.main()
StarcoderdataPython
3236577
<filename>matching_algorithms.py from sys import float_info from essentia.standard import Mean import numpy as np from scipy.ndimage.interpolation import shift from constants import ( PLSH_INDEX, NLSH_INDEX, COSINE_SIMILARITY, JACCARD_SIMILARITY, MANHATTAN_DISTANCE, LINEAR_SCALING, BALS, ...
StarcoderdataPython
3286410
class Game: def addMap(self, battle_map): self.battle_map = battle_map def getMapCells(self): return self.battle_map.getCells() def addCharcter(self, character, x, y): self.battle_map.add(character, x, y)
StarcoderdataPython