id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
9665232
<filename>{{cookiecutter.project_slug}}/app/spacy_extractor.py<gh_stars>100-1000 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from typing import Dict, List import spacy from spacy.language import Language class SpacyExtractor: """class SpacyExtractor encapsulates ...
StarcoderdataPython
3271975
<reponame>comcon1/ASPAM_webinterface<filename>server/src/image_loader.py #!/usr/bin/python # -*- coding: utf-8 -*- import os, sys, argparse from config import * from servutils import * import profile,traceback ''' Standalone script that loads images by parameters. In future this script should be replaced with more fa...
StarcoderdataPython
346963
nome = ((str(input('\033[0;34mQual é seu nome? \033[m'))).strip()) print('\033[0;35mOlá {}, prazer em conhece-lo\033[m'.format(nome))
StarcoderdataPython
386034
<reponame>django-doctor/lite-frontend import bleach from django import template from django.template import engines from markdown import Markdown register = template.Library() @register.simple_tag(takes_context=True) def markdown_to_html(context): """ Template tag to render the html and replace placehol...
StarcoderdataPython
3452929
<filename>writer.py import argparse from bs4 import BeautifulSoup import calendar import csv import json import markdown import os import sys import time from tqdm import tqdm _owner_path_template = os.path.join('{src_dir}', '{owner}') _repo_path_template = os.path.join('{src_dir}', '{owner}', '{repo}') _pull_path_tem...
StarcoderdataPython
9666265
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
StarcoderdataPython
1798959
from django import forms from .models import InlineImage class InlineImageForm(forms.ModelForm): class Meta: model = InlineImage fields = ( 'image_file', ) def __init__(self, *args, **kwargs): super(InlineImageForm, self).__init__(*args, **kwargs) ...
StarcoderdataPython
3463281
<reponame>ast0815/likelihood-machine """Binning/histogramming classes for scientific computing YAML interface ============== All classes defined in `binning` can be stored as and read from YAML files using the ``binning.yaml`` module:: with open("filename.yml", 'w') as f: binning.yaml.dump(some_binning, ...
StarcoderdataPython
1890063
<gh_stars>0 from tkinter import * def showPosEvent(event): print('Widget=%s X=%s Y=%s' % (event.widget, event.x, event.y)) def showAllEvent(event): print(event) for attr in dir(event): if not attr.startswith('__'): print(attr, '=>', getattr(event, attr)) def onKeyPress(eve...
StarcoderdataPython
1923413
# Generated by Django 3.2.9 on 2021-11-25 17:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_auto_20211125_1714'), ] operations = [ migrations.CreateModel( name='Venue', fields=[ ...
StarcoderdataPython
6614650
<reponame>sa-y-an/retro<filename>stress_detector/dev_settings.py from pathlib import Path import os import json # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent params = json.load(open(os.path.join(BASE_DIR, 'stress_detector/config.json'), 'r')) ...
StarcoderdataPython
129869
# This example scans for any BLE advertisements and prints one advertisement and one scan response # from every device found. This scan is more detailed than the simple test because it includes # specialty advertising types. from adafruit_ble import BLERadio from adafruit_ble.advertising import Advertisement from ada...
StarcoderdataPython
1742814
<reponame>vmiheer/t2sp<gh_stars>10-100 import halide as hl import numpy as np import gc def test_ndarray_to_buffer(): a0 = np.ones((200, 300), dtype=np.int32) # Buffer always shares data (when possible) by default, # and maintains the shape of the data source. (note that # the ndarray is col-major by...
StarcoderdataPython
5184982
<gh_stars>1-10 """ Markov Chain methods in Python. A toolkit of stochastic methods for biometric analysis. Features a Metropolis-Hastings MCMC sampler and both linear and unscented (non-linear) Kalman filters. Pre-requisite modules: numpy, matplotlib Required external components: TclTk """ __version__ = '2.1alpha' ...
StarcoderdataPython
11235702
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import argparse import json import os import time import sys if sys.version_info[0] == 2: reload(sys) sys.setdefaultencoding('utf-8') import tqdm from selenium import webdriver b = webdriver.Chrome() url = "https://cn.bing.com...
StarcoderdataPython
6617268
# -*- coding: UTF-8 -*- lan = 980 for i in range(5): lan += 10 print(lan) for i in range(5): lan -= 10 print(lan) for i in range(5): lan *= 10 print(lan) for i in range(5): lan /= 10 print(lan) for i in range(5): lan %= 10 print(lan) for i in range(5): lan **= 10 print(lan) for i i...
StarcoderdataPython
8141849
<gh_stars>1-10 ea = BeginEA() functions_with_assert = set() function_renames = {} for function_start in Functions(SegStart(ea), SegEnd(ea)): function_name = GetFunctionName(function_start) if not function_name.startswith('sub_'): continue function_end = FindFuncEnd(function_start) current_address = fu...
StarcoderdataPython
6512282
import osmnx as ox import numpy as np import networkx as nx from networkx.readwrite import json_graph import matplotlib.pyplot as plt import re import json #creating a graph #simplify graph G = ox.graph_from_point((33.775259139909664, -84.39705848693849), distance = 500, network_type='drive') #fig, ax = ox.plot_grap...
StarcoderdataPython
9751340
<reponame>jsalvatier/Theano-1 import unittest import theano import theano.tensor as T from theano import function, shared from theano.tests import unittest_tools as utt from theano.tensor.nnet.ConvTransp3D import convTransp3D from theano.tensor.nnet.ConvGrad3D import convGrad3D from theano.tensor.nnet.Conv3D import con...
StarcoderdataPython
11382427
import compressible_sr.eos as eos def test_eos_consistency(): dens = 1.0 eint = 1.0 gamma = 1.4 p = eos.pres(gamma, dens, eint) dens_eos = eos.dens(gamma, p, eint) assert dens == dens_eos rhoe_eos = eos.rhoe(gamma, p) assert dens*eint == rhoe_eos h = eos.h_from_eps(gamma, ei...
StarcoderdataPython
1910902
<reponame>nikhilvijay-symc/cwa-remediation-packages<filename>AWS remediation scripts/SYMC_CWA_Remediation_Worker_S3/raise_sns_notification.py import boto3 import json import sys def prepareSNSJsonMessage(message): try: outputMessage = dict() outputMessage['default']=message outputMessage['l...
StarcoderdataPython
1974672
"""Top level intialization of BubbleBox""" from . import api from . import library from . import resources
StarcoderdataPython
3249169
<filename>Leetcode/Python/_347.py class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: counter = {} for num in nums: if num not in counter: counter[num] = 0 counter[num] += 1 lst = sorted(counter.items(), key=lambda item: item[...
StarcoderdataPython
3472156
# Given a string, sort it in decreasing order based on the frequency of characters. # Example 1: # Input: # "tree" # Output: # "eert" # Explanation: # 'e' appears twice while 'r' and 't' both appear once. # So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. # Example 2: # Input: #...
StarcoderdataPython
110656
<gh_stars>0 from django.db import models # Create your models here. from billing.models import BillingProfile ADDRESS_TYPES = ( # ('billing', 'Facturacion'), # ('billing','Billing'), ('shipping', 'Envio'), # ('shipping','Shipping'), ) class Address(models.Model): billing...
StarcoderdataPython
4844580
# 服务端 import sys import json import requests from PyQt5.QtNetwork import QTcpServer, QHostAddress from PyQt5.QtWidgets import QApplication, QWidget, QTextBrowser, QVBoxLayout from neo4j import * from ModelProcess import * import pickle class Server(QWidget): def __init__(self, model, prediction, vocabulary): ...
StarcoderdataPython
64562
<reponame>Marsll/md-simulator """tests for short_ranged for the lennard jones forces and potential""" from ..neighbor_order_pbc import create_nb_order from ..neighbor_list import NeighborList from ..short_ranged import pair_potential, pair_force, potentials import numpy as np import numpy.testing as npt import scipy.c...
StarcoderdataPython
1610637
# Copyright 2021 Huawei Technologies Co., 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/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
StarcoderdataPython
1707911
##Gladiator Arena 2.0 ##<NAME> ##10-12-17 ##A remake of Gladiator Arena in python from random import randint ######################## def deathScreen(): print("You died!!") playAgain=input("Would you like to play again? (yes/no)\n") if playAgain=="yes": fight() else: quit() ######...
StarcoderdataPython
11370817
<gh_stars>1-10 # Author: Yubo "Paul" Yang # Email: <EMAIL> # Routines to read linear combination of atomic orbitals (LCAO) hdf5 file from qharv.seed import xml from qharv.seed.wf_h5 import read, ls # ====================== level 1: extract basic info ======================= def abs_grid(fp, iabs): """Extract <grid>...
StarcoderdataPython
9777459
# -*- coding: utf-8 -*- # Copyright © 2018, 2019 <NAME> <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software for # any purpose with or without fee is hereby granted, provided that the # above copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS...
StarcoderdataPython
6401692
<filename>ChessOpenings.py from bs4 import BeautifulSoup import requests req = requests.get('https://www.365chess.com/eco.php') soup = BeautifulSoup(req.content, 'html.parser') table = soup.find_all('div', class_ = 'opname' ) chessOpenings = [i.getText() for i in table] print(len(chessOpenings))
StarcoderdataPython
185165
<reponame>AkashSCIENTIST/CompetitiveSolutions<filename>HackerRank/Python/Validating phone numbers.py # Enter your code here. Read input from STDIN. Print output to STDOUT import re r = re.compile("[789]\d{9}$") for _ in range(int(input())): s = input() if bool(r.match(s)): print("YES") else: ...
StarcoderdataPython
9766941
<gh_stars>0 from graph_component.models import * # noqa
StarcoderdataPython
3468267
from __future__ import print_function from __future__ import absolute_import from __future__ import division import time import datetime __all__ = [ 'timestamp', 'now' ] def timestamp(): """Generate a timestamp using the current date and time. Returns ------- str The timestamp. ...
StarcoderdataPython
1722246
<gh_stars>0 from doab.tests.test_types import IntersectAcceptanceTest, TestManager, ReferenceParsingTest from doab.parsing.reference_miners import ( BloomsburyAcademicMiner, CambridgeCoreParser, CitationTXTReferenceMiner, SpringerMiner, ) @TestManager.register class PalgraveCUPIntersect(IntersectAccept...
StarcoderdataPython
3207948
<filename>matrix_game/q_mix.py """TF2 simple Qmix Implementation for matrix game.""" # Import all packages import tensorflow as tf class QmixNet(tf.keras.Model): def __init__(self, matrix_dims, name='Qmix', **kwargs): super(QmixNet, self).__init__(name=name, **kwargs) q_init = tf.zeros_initializer() s...
StarcoderdataPython
9610736
"""Utilities for TableNet.""" from .marmot import MarmotDataModule, MarmotDataset from .tablenet import TableNetModule __all__ = ['MarmotDataModule', 'TableNetModule']
StarcoderdataPython
9776055
<gh_stars>10-100 import numpy import pandas as pd from datetime import datetime import math import pathlib import sys import os from pyexcel_ods import get_data import sativ_indemnity_parser_out_2020 import sinat_indemnity_parser_out_2020 import mativ_indemnity_parser_jan_2020 import mativ_indemnity_parser_fev_2020 imp...
StarcoderdataPython
6410177
from django.db import models from moondance.meta_models import MetaModel class Tax_Rate_State(MetaModel): state = models.CharField(max_length=200, unique=True) base_rate = models.DecimalField( max_digits=4, decimal_places=2, null=True, blank=True ) def __str__(self): return "{}".forma...
StarcoderdataPython
1859681
<filename>djangoql/forms.py from django import forms from .models import Query class QueryForm(forms.ModelForm): class Meta: model = Query fields = ['name', 'text', 'private']
StarcoderdataPython
1693633
import time import warnings from collections import defaultdict import numpy as np import pandas as pd import torch from sklearn.model_selection import train_test_split from torch import nn from transformers import * from nlp_model import SentimentClassifier from preprocessing import data_loader, preprocess, tokenize...
StarcoderdataPython
12826662
# coding=utf-8 import uuid from virtualisation.clock.abstractclock import AbstractClock from virtualisation.wrapper.abstractwrapper import AbstractComposedWrapper, AbstractWrapper from virtualisation.sensordescription import SensorDescription from virtualisation.wrapper.history.csvhistory import CSVHistoryReader from v...
StarcoderdataPython
3315324
<reponame>JonnyBoy2000/Kira-Public import discord import random import asyncio import datetime from datetime import timedelta from discord.ext import commands from utils import checks from utils.mod import mass_purge, slow_deletion class Mod(commands.Cog): def __init__(self, bot): self.bot = bot def f...
StarcoderdataPython
3351588
from abc import abstractmethod, ABC from typing import Optional, Tuple import gym import numpy as np from .. import BaseTask from ..normalizer import Normalizer class Controller(ABC): """ An abstract base class for the different types of controllers (e.g. torque or velocity controller). """ def __i...
StarcoderdataPython
3275400
<filename>p3_collab-compet/ddpg_agent.py<gh_stars>0 import numpy as np import random import copy from collections import namedtuple, deque from model import Actor, Critic from sum_tree import SumTree import torch import torch.nn.functional as F import torch.optim as optim BUFFER_SIZE = int(1e6) # replay buffer size...
StarcoderdataPython
9699271
<reponame>lcmonteiro/tool-gtrans # ################################################################################################# # ------------------------------------------------------------------------------------------------- # File: google_browser.py # Author: <NAME> # # Created on jan 6, 2020, 22:00 PM ...
StarcoderdataPython
9695721
from sklearn import preprocessing import sklearn from sklearn.utils import shuffle from sklearn.neighbors import KNeighborsClassifier import pandas as pd import numpy as np from sklearn import linear_model, preprocessing data = pd.read_csv("car.data") print(data.head()) # Preprocesing convert string to numbers le=pre...
StarcoderdataPython
122021
<filename>find majority element.py #Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. #You may assume that the array is non-empty and the majority element always exist in the array. #solution 1 from collections import Counter class Solution:...
StarcoderdataPython
6622948
import math import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from PIL import Image # from tf_cnnvis import * def weight(shape): return tf.Variable(tf.truncated_normal(shape, stddev=0.1)) def bias(length): return tf.Variable(tf.constant(0.1, shape=[length])) def layer(input, num_i...
StarcoderdataPython
11208730
<filename>Executor/lib/conn_device.py import logging import yaml from jnpr.junos import Device from jnpr.junos.exception import ConnectError # Logging logger = logging.getLogger(__name__) class ConnDevice(object): def __init__(self, config_path='config/devices.yaml'): """Common interface for connecting t...
StarcoderdataPython
4819436
# Um professor quer sortear um dos seus quatro alunos para # apagar o quadro. Faça um programa que ajude ele, lendo o nome deles e # escrevendo nome do escolhido """import random print('Escolhendo um aluno... ') n = random.randint(1, 4) if (n == 1): print('O aluno escolhido foi o Ciro') elif (n == 2): print('O ...
StarcoderdataPython
6481650
#!/usr/bin/python import argparse from board_server_manager import BoardServerManager def main(): parser = argparse.ArgumentParser(description='Board server settings') parser.add_argument('-sp', '--PORT', help='server port', type=int, default=80, required=False) parser.add_argume...
StarcoderdataPython
9765934
class Unpacker(object): """Helper class to unpack data received from WIZNet device""" def __init__(self, data, pos=0): self.data = data self.initialpos = self.pos = pos def unpack(self, s2e): self.pos = self.initialpos for field in s2e._fields: name = field[0...
StarcoderdataPython
11369351
<reponame>MisterAI/AutoTeSG #!/usr/bin/python import sys, getopt import astor from ast import walk, FunctionDef from CodeInstrumentator import CodeInstrumentator, RemovePrintStmts from TestDataGenerator import TestDataGenerator import BranchCollector from AVM import AVM __version__ = '0.0.1' def main(argv): try: ...
StarcoderdataPython
4838907
from .WebIDLLexer import WebIDLLexer from .WebIDLParser import WebIDLParser from .WebIDLParserVisitor import WebIDLParserVisitor
StarcoderdataPython
30168
from django.shortcuts import render # Create your views here. from django.shortcuts import render,redirect, render_to_response from .models import * from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse from django.http import HttpRespo...
StarcoderdataPython
346070
s = "abcxyz" print "original("+s+")" print "strip("+s.lstrip("cba")+")"
StarcoderdataPython
274857
'''Soma Simples''' A = int(input()) B = int(input()) def CalculaSomaSimples(a: int, b: int): resultado = int(a+b) return('SOMA = {}'.format(resultado)) print(CalculaSomaSimples(A,B))
StarcoderdataPython
5192698
<filename>referrals/migrations/0001_initial.py # Generated by Django 2.0.2 on 2018-04-16 07:53 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swa...
StarcoderdataPython
4840816
#!/usr/bin/python import sys import os sys.path.append("../../src/") sys.path.append("../util/") import commands import common CXXTAGS_QUERY = "../../bin/cxxtags_query" if len(sys.argv) != 2: print "usage: cmd db_file" exit(1) cur_dir = os.getcwd() db_dir = sys.argv[1] q_list = [ # main.cpp "ref " + db_di...
StarcoderdataPython
6574620
<gh_stars>1-10 import unittest.mock from app.exit_code import ExitCode from app.scene import Scene from app.window import Window from tests import events class WindowTestCase(unittest.TestCase): @unittest.mock.patch('pygame.event.get', return_value=[events.quit_event, events.any_key_event]) def test_should_r...
StarcoderdataPython
1919707
""" This file contains extensions to Click """ from collections import OrderedDict import click class PywbemcliGroup(click.Group): """ Extend Click Group class to: 1. Order the display of commands within the help. The commands are ordered in the order that their definitions appears in th...
StarcoderdataPython
25920
from .unit_change_dialog import UnitChangeDialog
StarcoderdataPython
3256781
#!/usr/bin/env python3 # MQTT Minecraft server feeder # Feeds Minecraft server via RCON with commands received via MQTT # requirements # pip3 install paho-mqtt # pip3 install mcrcon # pip3 install python-dotenv import paho.mqtt.client as mqtt from time import time, sleep import signal import socket import sys from m...
StarcoderdataPython
3319067
<reponame>rayheberer/LambdaCodingChallenges<filename>Week 14 Reinforcement Learning/Code Challenges/Day 2 Discounted Rewards/reward.py def reward(R, gamma): total_R = 0 reward = R epsilon = 0.00001 while abs(reward) > epsilon: total_R += reward reward *= gamma return total_R
StarcoderdataPython
3389312
from multiprocessing import TimeoutError from FreeTAKServer.controllers.FederatedCoTController import FederatedCoTController from FreeTAKServer.model.FTSModel.Event import Event from FreeTAKServer.model.protobufModel.fig_pb2 import FederatedEvent import codecs import socket from FreeTAKServer.model.ServiceObjects.Feder...
StarcoderdataPython
9723726
from __future__ import annotations # Packages import pygame # Helpers from ..Helpers.Cords import Cords # Elements from .Element import Element class Position(Element): def __init__(self: Position, x: float = 0.00, y: float = 0.00, color: pygame.Color = pygame.Color(255, 255, 255)) -> Position: """Init...
StarcoderdataPython
4947400
<filename>Atividades/PY 01/maximo_3.py def maximo(x,y,z): if x > y and x > z: return x elif y > z and y > x: return y elif x == y == z: return x else: return z
StarcoderdataPython
6520343
<reponame>code-review-doctor/amy<gh_stars>10-100 # -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-06-08 16:10 from __future__ import unicode_literals from django.db import migrations def forward(apps, schema_editor): Group = apps.get_model('auth', 'Group') Group.objects.get_or_create(name='adminis...
StarcoderdataPython
3200873
<reponame>bobobo80/python-crawler-test<filename>tasks/workers.py """ celery workers 启动文件 """ from celery import Celery from kombu import Exchange, Queue import config tasks = ['tasks.links', 'tasks.logs'] app = Celery('mfw_task', include=tasks, broker=config.CELERY_BROKER, backend=config.CELERY_BACKEND) app.conf.u...
StarcoderdataPython
8032304
<filename>keystone_tempest_plugin/tests/rbac/v3/test_role_assignment.py # Copyright 2020 SUSE LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICEN...
StarcoderdataPython
1709240
# -*- coding: utf-8 -*- # snapshottest: v1 - https://goo.gl/zC4yUc from __future__ import unicode_literals from snapshottest import Snapshot snapshots = Snapshot() snapshots['TestDatasetMutations.test_create_dataset 1'] = { 'data': { 'createDataset': { 'dataset': { 'datasetTy...
StarcoderdataPython
1702495
from os.path import dirname, join from unittest import TestCase from pytezos import pytezos, ContractInterface initial_storage = { 'admin': { 'admin': pytezos.key.public_key_hash(), 'paused': False }, 'assets': { 'hook': { 'hook': """ { DROP ; ...
StarcoderdataPython
1877984
<gh_stars>1-10 # -*- encoding: utf-8 -*- ''' @File : test_axml.py @Author : Loopher @Version : 1.0 @License : (C)Copyright 2020-2021, Loopher @Desc : None ''' # Here put the import lib import os import unittest from androyara.core.axml_parser import AndroidManifestXmlParser root = os.path.abspath(o...
StarcoderdataPython
8130588
<filename>sb_code/sb_train.py<gh_stars>0 #from stable_baselines3.common.env_checker import check_env from gym_duckietown.envs.duckietown_env import DuckietownEnv from gym_duckietown.simulator import Simulator from sb_code.wrapper import NormalizeWrapper, ResizeWrapper, RewardWrapper, FinalLayerObservationWrapper, \ ...
StarcoderdataPython
6497302
<gh_stars>1-10 ''' Module containing the main menu instances Written by <NAME> ''' import sys sys.path.insert(0, '..') from classes import interface from instances import instance_config as icng import pygame as pg COLORS = pg.colordict.THECOLORS text = [ interface.text_center( text=...
StarcoderdataPython
5134025
from flask.signals import Namespace _signals = Namespace() # session_ended = _signals.signal('session-ended')
StarcoderdataPython
1766986
<gh_stars>0 import json from collections import OrderedDict class Cube(object): def __init__(self, dimensions): super().__init__() self.dimensions = dimensions self.cube = {} self.dictionaries = {} self._current_cells = {} # a dictionary dim->cell for the current fact ...
StarcoderdataPython
6619881
<reponame>kimholmgren/grocerystore_path_simulation<filename>grocerypathsim/path_generator.py<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import cv2 from pathfinding.core.diagonal_movement import DiagonalMovement from pathfinding.core.grid import Grid from pathfinding.finder.a_star import AStarFinder ...
StarcoderdataPython
11256828
<gh_stars>0 import sys import warnings warnings.warn("package 'chainerio' is deprecated and will be removed." " Please use 'pfio' instead.", DeprecationWarning) # make sure pfio is in sys.modules import pfio # NOQA sys.modules[__name__] = __import__('pfio')
StarcoderdataPython
188524
<gh_stars>1-10 """Custom storage classes for static and media files.""" from django.conf import settings from storages.backends.s3boto import S3BotoStorage class StaticStorage(S3BotoStorage): """Custom storage class for static files.""" location = settings.STATICFILES_LOCATION
StarcoderdataPython
11309845
""" Every user gets their own Redis hash to store "temporary" values in. All values time out 24h after last update. The hash is reset when the user logs out, or the user's id changes. This is intended to persist some data between Dash callbacks. If you use this for routes that take JWT authentication, there is no "logo...
StarcoderdataPython
12859930
"""Create plots for learning from varying numbers of demonstrations.""" import os import matplotlib import matplotlib.pyplot as plt import pandas as pd from predicators.scripts.analyze_results_directory import create_dataframes, \ get_df_for_entry pd.options.mode.chained_assignment = None # default='warn' # pl...
StarcoderdataPython
9735995
<reponame>philipjameson/buckit load("@bazel_skylib//lib:partial.bzl", "partial") load("@bazel_skylib//lib:paths.bzl", "paths") load("@fbcode_macros//build_defs/facebook:python_wheel_overrides.bzl", "python_wheel_overrides") load("@fbcode_macros//build_defs/lib:cxx_platform_info.bzl", "CxxPlatformInfo") load("@fbcode_ma...
StarcoderdataPython
4942235
<filename>netbox_netdisco/core/__init__.py from .inventory import Inventory #Inventory.collect()
StarcoderdataPython
1945649
import sys import argparse from ._docker import run_docker from ._kubernetes import run_kubernetes from ._native import run_native, RUNFILE_ENV_VAR import yaml import logging MODULE_NAME = "fv3config.run" STDOUT_FILENAME = "stdout.log" STDERR_FILENAME = "stderr.log" DOCKER_FLAGS = "-it" def _parse_args(): parser...
StarcoderdataPython
9695782
#!/Python27/python import cgi, cgitb form = cgi.FieldStorage() if form.getvalue('subject'): subject = form.getvalue('subject') else: subject = "Not set" print("Content-type:text/html\r\n\r\n") print("<html>") print("<head>") print("<title>Radio for CGI Program</title>") print("</head>") print("<body>...
StarcoderdataPython
1671635
"""Initial database Revision ID: 7c3929047190 Revises: Create Date: 2021-03-13 13:22:38.768112 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7c3929047190' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto ge...
StarcoderdataPython
3488118
import unittest import quarkchain.db from quarkchain.cluster.root_state import RootState from quarkchain.cluster.shard_state import ShardState from quarkchain.cluster.tests.test_utils import get_test_env from quarkchain.core import Address from quarkchain.core import CrossShardTransactionList from quarkchain.diff impo...
StarcoderdataPython
9790648
import math import numpy as np import torch from torch.nn.parameter import Parameter from torch import nn from torch.nn import functional as F from torch.utils import model_zoo from copy import deepcopy from .resnet12 import resnet12 eps = 1e-10 class CNNEncoder(nn.Module): def __init__(self, in_c=3): s...
StarcoderdataPython
6421178
############################### ## 100DaysOfCode ## ## d02_ecercice03 ## ############################### # Love Calculator print("Welcome to the Love Calculator!") name1 = input("\nWhat is your name? ") name2 = input("What is their name? ") lower_names = name1.lower() + name2.lower() decimal ...
StarcoderdataPython
9602130
<filename>RandomFileQueue.py # MusicPlayer, https://github.com/albertz/music-player # Copyright (c) 2012, <NAME>, www.az2000.de # All rights reserved. # This code is under the 2-clause BSD license, see License.txt in the root directory of this project. # loosely inspired from https://github.com/albertz/PictureSlider/b...
StarcoderdataPython
3509599
<gh_stars>1-10 # Generated by Django 3.0.3 on 2020-09-21 17:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MovieModel', fields=[ ...
StarcoderdataPython
1939693
import random from flask import Flask, jsonify, render_template, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) ##Connect to Database app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ##Cafe TABLE Configurati...
StarcoderdataPython
6453698
<filename>server.py from flask import Flask, request, flash, redirect, render_template import cv2 import FocFace import face_recognition import os ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) UPLOAD_FOLDER = './temp_photos' app = Flask(__name__) app.secret_key = "secret key" app.config['UPLO...
StarcoderdataPython
160743
#!/usr/bin/env python3 import os import json import torch from misc_scripts import run_cl_exp, run_rep_exp from utils import get_mini_imagenet, get_omniglot from core_functions.vision import evaluate from core_functions.vision_models import OmniglotCNN, MiniImagenetCNN, ConvBase from core_functions.maml import MAML ...
StarcoderdataPython
1816000
class Matrix: def __init__(self, matrix_string): self.lista = [[int(i) for i in j.split()] for j in matrix_string.splitlines()] def row(self, fila): return list(self.lista[fila-1]) def column(self, column): return [i[column-1] for i in self.lista] matriz = Matrix("9 8 ...
StarcoderdataPython
3367881
from pyframework.exceptions.custom_exceptions import ArgumentException from pyframework.helpers.lists import array_column from .base_fire import BaseFire, Event from ...models.city_endpoint import CityEndpoint from ...models.restaurant import Restaurant class FireRestaurantsInfoDownload(BaseFire): _name = 'fire:...
StarcoderdataPython
1925266
# -*- coding: utf-8 -*- """ Leetcode - Find the Difference https://leetcode.com/problems/find-the-difference Created on Sat Nov 3 19:11:50 2018 Updated on Wed Nov 28 12:25:06 2018 @author: <NAME> """ ## REQUIRED MODULES import sys ## MODULE DEFINITIONS class Solution: """ Iteration and b...
StarcoderdataPython