id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3287044
from discord.ext import commands from discord import errors from cogs.utils import utils import traceback import datetime import storage import discord import glob import helpformat description = '''Nurevam's Command List. To enable more commands, you must visit dashboard to enable certain plugins you want to run. ...
StarcoderdataPython
3270906
from os import environ def assert_in(file, files_to_check): if file not in files_to_check: raise AssertionError("{} does not exist in the list".format(str(file))) return True def assert_in_env(check_list: list): for item in check_list: assert_in(item, environ.keys()) return True
StarcoderdataPython
1799468
# Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. sal = float(input('Digite o salário: ')) print('O salario com aumento é de R$ {:.2f}'.format(sal * 1.15))
StarcoderdataPython
3362530
<filename>03/kunningklown/solution.py """ read file split data on line return file_line1 file_line2 split data on comma for both lines iterate through each instruction for each line to create wire1 wire2 if points go from (0,0) to (0,3) line = (0,0),(0,1),(0,2),(0,3) if r,l,u,d add number """ class TraceCircuit(): ...
StarcoderdataPython
89889
<reponame>fr33ky/signalserver<filename>fileuploads/migrations/0010_auto_20160605_2219.py # -*- coding: utf-8 -*- # Generated by Django 1.10.dev20160107235441 on 2016-06-05 22:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =...
StarcoderdataPython
3221268
<reponame>dwoz/pytest-salt # -*- coding: utf-8 -*- # Import python libs import logging if not hasattr(logging, 'TRACE'): logging.TRACE = 5 logging.addLevelName(logging.TRACE, 'TRACE') if not hasattr(logging, 'GARBAGE'): logging.GARBAGE = 1 logging.addLevelName(logging.GARBAGE, 'GARBAGE') pytest_plug...
StarcoderdataPython
3225819
from django.contrib import admin from problem.models import Problem, SolvedProblem, ProblemStatusByLevel # Register your models here. admin.site.register(Problem) admin.site.register(SolvedProblem) admin.site.register(ProblemStatusByLevel)
StarcoderdataPython
99836
from collections import namedtuple import numpy as np from untwist import data, utilities, transforms Anchors = namedtuple('Anchors', ['Distortion', 'Artefacts', 'Interferer', 'Quality'], ) class ...
StarcoderdataPython
1683973
#Todo: Create a setup file
StarcoderdataPython
3202414
# compute nim values using negamax and a dictionary # that holds values already computed RBH 2019 def get_piles(): while True: raw = input('nim game pile sizes (eg. 3 5 7) ') try: dim = tuple( int(x) for x in raw.split() ) if len(dim) > 0 and all(d >= 0 for d in dim): ...
StarcoderdataPython
1778184
from __future__ import division, print_function import tensorflow as tf import numpy as np import os import pprint import sys import keras from keras.models import Sequential, Model from keras.layers import Dense, Activation, Dropout, Input from keras.utils import to_categorical from keras import regularizers, initiali...
StarcoderdataPython
3348718
<reponame>volodink/ubx-decoder-embedded from ubx import * print 'Writing data file ...' # create file and write message in it dataFile = open('../sender/data.txt', 'wb') packet = getPacket(3) packet.tofile(dataFile) packet = getPacket(0) packet.tofile(dataFile) packet = getPacket(3) packet.tofile(dataFile) packet...
StarcoderdataPython
3358713
# Migration test # # Copyright (c) 2019 Red Hat, Inc. # # Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # This work is licensed under the terms of the GNU GPL, version 2 or # later. See the COPYING file in the top-level directory. import tempfile from avocado_qemu import Test from avocado import skipUnless fro...
StarcoderdataPython
164729
<reponame>capaximperii/Alyke from resource import Resource def dummy_compute_digest(path): return "digest" class TestResource(object): def setup(self): self.resource = Resource('/tmp/a', dummy_compute_digest) def teardown(self): print ("Resource teardown") def test_get(self): ...
StarcoderdataPython
1655661
import cv2 import os def seq2avi(): seq_dir = r'G:\Dataset\PAMIRain\Dataset831\train\Bs' avi_dir = r'G:\Dataset\PAMIRain\Dataset831\train\Bs.avi' img_list = os.listdir(seq_dir) fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') writer = cv2.VideoWriter(avi_dir, fourcc, 20.0, (256, 256)) for ...
StarcoderdataPython
132240
<reponame>Razdeep/PythonSnippets<filename>AUG16/02.py<gh_stars>0 # implicit conversion num_int=123 num_float=1.23 result=num_int+num_float print('datatype of num_int is',type(num_int)) print('datatype of num_float is',type(num_float)) print('datatype of result is',type(result)) # it automatically converts int to flo...
StarcoderdataPython
4822504
<filename>Tensorflow/demo/custom/mnist.py import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers import numpy as np # 载入数据 (train_data, train_label), (test_data, test_label) = keras.datasets.mnist.load_data() print('train_data.shape {} test_data.shape {}'.format(train_data.s...
StarcoderdataPython
3376709
import pygame import os from settings import Settings from button import Button from helpers import draw_text class EndGameMenu(): def __init__(self, center_x, center_y, cached_fonts): self.score_menu_img = pygame.image.load( os.path.join('images', 'score_menu.png')) self.x = center_x ...
StarcoderdataPython
1755091
<filename>tests/test_analysis.py import pytest from diffy_api.analysis.views import * # noqa @pytest.mark.parametrize("token,status", [("", 200)]) def test_analysis_list_get(client, token, status): assert client.get(api.url_for(AnalysisList), headers=token).status_code == status @pytest.mark.parametrize("token...
StarcoderdataPython
3360657
import torch import torch.nn as nn class UNetSame(nn.Module): def __init__(self): super(UNetSame, self).__init__() self.encoder1 = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=1), nn.Conv2d(in_channels=64, out_channels=64, ker...
StarcoderdataPython
103902
# Generated by Django 2.2.13 on 2021-02-01 11:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('project', '0036_auto_20210201_1120'), ] operations = [ migrations.AlterField( model_name='project', name='pi', ...
StarcoderdataPython
138811
<reponame>poliakustyczny/deepl.py #!/usr/bin/python3 import sys, requests, json URL = "https://www.deepl.com/jsonrpc" def encodeRequest(text): return(json.dumps({"jsonrpc" : "2.0", "method" : "LMT_handle_jobs", "params" : { "jobs" : [ { "kind" : "default", "raw_en_sentence" : text } ], "lang" : { "user_preferred...
StarcoderdataPython
1700662
# coding: utf-8 """Manage the differents pages of the site""" import markdown import bleach from urlparse import urlparse from datetime import datetime from flask import Flask, render_template, request, flash, redirect, url_for from flask_babel import gettext, format_datetime from mjpoll import app, babel from data ...
StarcoderdataPython
3365183
from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class sports(models.Model): title_field = models.CharField(max_length=256) purchaser_field = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) description_fiel...
StarcoderdataPython
3304083
#!/usr/bin/python from lxml import etree import grokscrap as gs import os import subprocess as subp import re #This class allows for (very handy) re-entrant lists of command-line calls. All you need is to call startStep() at the beginning and make sure to call endStep() at the end only if there was no problem and the...
StarcoderdataPython
1790823
<gh_stars>1-10 # The MIT License (MIT) # Copyright (c) 2015 <NAME> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, cop...
StarcoderdataPython
1775573
<gh_stars>10-100 import psycopg2 from psycopg2.extensions import AsIs, ISOLATION_LEVEL_AUTOCOMMIT from settings import DB_NAME, USER, PASSWORD import logging class DBObject(object): _db_con = None _db_cur = None def __init__(self, db, user, password): try: self._db_con = psycopg2.conne...
StarcoderdataPython
1704088
<filename>server/daqbrokerServer.py from tornado.wsgi import WSGIContainer from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer #import gevent.monkey # gevent.monkey.patch_all() import time import sys import json import traceback import logging import multiprocessing import ntplib import socket ...
StarcoderdataPython
127254
<gh_stars>1-10 """ Ada-GVAE training script for dsprites dataset, using disentanglement_lib. Also evaluates DCI metric and saves outputs. <NAME> ETHZ 2020 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import warnings warnings.simplefilter(action='igno...
StarcoderdataPython
3370424
<filename>third_party/logilab/astroid/scoped_nodes.py # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:<EMAIL> # # This file is part of astroid. # # astroid is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser G...
StarcoderdataPython
1764060
import click from testplan.cli.converter import convert @click.group() def cli(): pass cli.add_command(convert) if __name__ == "__main__": cli()
StarcoderdataPython
3325224
<filename>program.py import json import jsonpatch import traceback from adh_sample_library_preview import (ADHClient, Role, RoleScope, Trustee, TrusteeType, User, UserInvitation, AccessControlList, AccessControlEntry, AccessType, CommonAccessRightsEnum, SdsType, SdsTypeProperty,...
StarcoderdataPython
3372327
<gh_stars>0 from NetworkModeCTE import * from PacketManager import * src = 2 dest1 = 3 is_ack = PACKET_FIELD_ISACK_NO_ACK SN = PACKET_FIELD_SN_FIRST dest2 = 7 packet_type = NETWORK_PACKET_TYPE_CONTROL pl = bytearray(NETWORK_PAYLOAD_SIZE) pl[-1] = NETWORK_PACKET_CONTROL_REPLY_YES_PAYLOAD packet = create_packet(src, d...
StarcoderdataPython
92373
from .binarytrees import *
StarcoderdataPython
1711098
from __future__ import annotations __all__ = ["Bind"] from dataclasses import dataclass from typing import TYPE_CHECKING, Dict, Generic, List, Optional, TypeVar, Union, cast from funchacks.errors import TemporaryError if TYPE_CHECKING: from funchacks.sig.impl import ArgdefSignature from funchacks.typehints ...
StarcoderdataPython
3337041
""" Definition of the :class:`PrivateDataElement` class, representing a single "UN" data element. """ from types import FunctionType from typing import Any from dicom_parser.data_element import DataElement from dicom_parser.utils.siemens.private_tags import ( parse_siemens_b_matrix, parse_siemens_bandwith_per_...
StarcoderdataPython
1683089
<filename>BlackVision/Dep/3rdParty/glad/glad/lang/c/loader/wgl.py from glad.lang.common.loader import BaseLoader from glad.lang.c.loader import LOAD_OPENGL_DLL, LOAD_OPENGL_DLL_H, LOAD_OPENGL_GLAPI_H _WGL_LOADER = \ LOAD_OPENGL_DLL % {'pre':'static', 'init':'open_gl', 'proc':'get_proc', 'ter...
StarcoderdataPython
28399
<filename>game.py from Enemy.bosses import * from Enemy.desert_enemies import * from Enemy.field_enemies import * from Enemy.graveyard_enemies import * from Enemy.magic_enemies import * from Enemy.moon_enemies import * from Enemy.winter_enemies import * from Enemy.fire_enemies import * from menu import VerticalMenu fro...
StarcoderdataPython
3262949
<filename>Protheus_WebApp/Modules/SIGACRM/CRMA290TESTCASE.py from tir import Webapp from datetime import datetime DataSystem = datetime.today().strftime('%d/%m/%Y') import unittest class CRMA290(unittest.TestCase): Contr = "" @classmethod def setUpClass(inst): inst.oHelper = Webapp() inst....
StarcoderdataPython
3390617
<gh_stars>0 import aspose.slides as slides import aspose.pydrawing as drawing def rendering_3d(): dataDir = "./examples/data/" outDir = "./examples/out/" with slides.Presentation() as pres: shape = pres.slides[0].shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 200, 150, 200, 200) shape....
StarcoderdataPython
45312
<reponame>EnjoyLifeFund/macHighSierra-py36-pkgs # !/usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 <NAME> and <NAME>. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of ...
StarcoderdataPython
3285783
from fabrik_chain_3d import Chain as Chain, Bone as Bone, Utils as Util import math import sys sys.path.append('..') def main(default_target_position): # This is an example of using this code for solving inverse kinematic of FRANKA robot # Step 1 : specify the target position and orientation(in quaternion) ...
StarcoderdataPython
3376811
<filename>assignmentsApp/admin.py from django.contrib import admin from assignmentsApp.models import Assignments from assignmentsApp.models import Submissions admin.site.register(Assignments) admin.site.register(Submissions)
StarcoderdataPython
3244463
<filename>nlpsc/representation/word_embedding/word2vec/word2vec_train.py import plac import gensim import multiprocessing from pathlib import Path def word2vec_train(infile, outfile, fmtfile, epoch, size, mini): sentences = gensim.models.word2vec.LineSentence(infile) model = gensim.models.Word2Vec(sentences, ...
StarcoderdataPython
178077
<filename>m6anet/scripts/dataprep.py import argparse import numpy as np import pandas as pd import os import multiprocessing import ujson from operator import itemgetter from collections import defaultdict from itertools import groupby from io import StringIO from . import helper from .constants import M6A_KMERS, NUM...
StarcoderdataPython
3302522
import sqlite3 from car import Car from cars_sql_scheme import create_table_cars, create_table_repairs """Represents a sample car. Arguments: make - car make e.g. Honda model - car model e.g. Civic year - year of production vrn - vehicle registration number vin - VIN number sold - if car ...
StarcoderdataPython
1674957
from GameAI.QLearner import QLearnerGameAI import pickle from os import path, makedirs import time import random from builtins import input def ensureDir(f): d = path.dirname(f) if not path.exists(d): makedirs(d) class Game(object): def playGame(self, players): state = self.start ...
StarcoderdataPython
180641
<reponame>malharlakdawala/DevelopersInstitute def mergeSortedArrays(L, R): sorted_array = [] i = j = 0 while i < len(L) and j < len(R): if L[i] < R[j]: sorted_array.append(L[i]) i += 1 else: sorted_array.append(R[j]) j += 1 # When ...
StarcoderdataPython
3269004
import asyncio import datetime from collections import Counter from typing import Any, NamedTuple, Optional import asyncpg import discord from discord.ext import commands, menus, tasks from donphan import MaybeAcquire from ... import BotBase, Cog, Context, CONFIG from ...db.tables import Commands from ...utils.pagi...
StarcoderdataPython
1738805
import probability as prb import pprint import random import itertools as it #todo: opening fire, expected value of strategic bombing raid against risk, sub withdrawal, #sub/plane individuation: # sub not hit planes, # chance of taking territory (planes can't take territory) # planes potential targets...
StarcoderdataPython
1628931
<reponame>ABBARNABIL/Turing-Machine<gh_stars>0 # V1.2 2019/09/19 <NAME> import argparse import curses from time import sleep class UI_Curses: def __init__(self, sim): self.sim = sim curses.wrapper(self.term) def yx(self, p, t): p += self.COLS // 2 return (p // self.COLS) * (se...
StarcoderdataPython
3381798
class NotFoundError(Exception): code = 404 pass class ServerError(Exception): code = 500 pass
StarcoderdataPython
1617971
<filename>src/whoosh/codec/legacy.py # Copyright 2011 <NAME>. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # ...
StarcoderdataPython
3314566
<filename>bsl/Z3/z3_smt.py<gh_stars>1-10 from z3 import * import sys import time # ====== load file ===== def extract_edge(edge): tokens = edge.split(",") assert len(tokens) == 2, "ill-format edge: a,b" return [int(tokens[0]), int(tokens[1])] def load_polyg(poly_f): with open(poly_f) as f: l...
StarcoderdataPython
146866
#/usr/bin/env python # encoding: utf-8 import os import sys import atexit import json import time import tempfile import wave import traceback import urllib2 from subprocess import check_output from Queue import Queue, Empty import numpy as np import pyaudio class Spectrum(object): FORMAT = pyaudio.paFloat32 ...
StarcoderdataPython
3359864
<reponame>kdschlosser/home-assistant """ Support for retrieving status info from Google Wifi/OnHub routers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.google_wifi/ """ import logging from datetime import timedelta import voluptuous as vol imp...
StarcoderdataPython
103510
#!/usr/bin/python # Copyright (c) 2018 # Call file: # python ./generate_cpp17.py > TupleConversions/Private/structurebindings_generated.h ############################################################################################################################ import sys import string # Skipping some letters that...
StarcoderdataPython
142214
<gh_stars>1-10 from . import adapters from . import mol_toolkit if mol_toolkit.HAS_OE: from . import cp_openeye if mol_toolkit.HAS_RDK: from . import cp_rdk if not mol_toolkit.HAS_OE and not mol_toolkit.HAS_RDK: raise Exception("Neither OpenEye or RDKit is installed"\ "ChemPer requires at least one of th...
StarcoderdataPython
1752325
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The ios_static_routes class It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessary...
StarcoderdataPython
1676872
from django.db import models from river.models.fields.state import StateField class Shipping(models.Model): product = models.CharField(max_length=50, null=True, blank=True) customer = models.CharField(max_length=50, null=True, blank=True) shipping_status = StateField() def __str__(self): retu...
StarcoderdataPython
54525
<gh_stars>0 # split the Neale Lab UK Biobank summary statistics by chromosome import argparse CHROM = list(map(str, range(1, 23))) CHROM.append("X") def main(): parser = argparse.ArgumentParser() parser.add_argument("fname", help = "Input variants file") args = parser.parse_args() # open all the out...
StarcoderdataPython
30252
<filename>mmdet/apis/__init__.py from .env import get_root_logger, init_dist, set_random_seed from .inference import inference_detector, init_detector, show_result from .train import train_detector __all__ = [ 'init_dist', 'get_root_logger', 'set_random_seed', 'train_detector', 'init_detector', 'inference_dete...
StarcoderdataPython
82607
# -*- coding: utf-8 -*- """ Graph of the system x - 2y = 0 x - 4y = 8 I calculated solution as (-8,-4) graph agrees """ #%reset -f import matplotlib.pyplot as plt def get_x_i(y): """ Returns x -2y = 0 solved for x i.e. x = 2y """ return 2*y def get_x_ii(y): ...
StarcoderdataPython
111033
from datetime import datetime from time import mktime def micro_time(): """ Returns the current time since epoch, accurate to the value returned by gettimeofday(), usually ~1microsecond. Datetime is more accurate than time.clock """ now = datetime.now() return long(mktime(now.timetuple()) ...
StarcoderdataPython
1704007
<reponame>tervay/the-blue-alliance<gh_stars>100-1000 import csv import StringIO from datafeeds.parser_base import ParserBase class CSVTeamsParser(ParserBase): @classmethod def parse(self, data): """ Parse CSV that contains teams Format is as follows: team1, team2, ... teamN ...
StarcoderdataPython
1621798
<reponame>SimLeek/pglsl-neural<filename>pygp_retina/tests_interactive/show_average.py from cv_pubsubs import webcam_pub as camp from cv_pubsubs import window_sub as win from pygp_retina.simple_average import avg_total_color if False: from typing import Tuple def display_average(cam, request_size=...
StarcoderdataPython
26464
<filename>Plug-and-play module/attention/CBAM/cbam.py import torch import torch.nn as nn def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, ...
StarcoderdataPython
3327582
# OTP Generator # | IMPORT import base64 import os import pickle import shortuuid from datetime import datetime from random import randint, seed from typing import Any, Dict, Union # | GLOBAL EXECUTIONS & GLOBAL VARIABLES CHAR_SET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # | FUNCTIONS def g...
StarcoderdataPython
47508
<filename>deeppavlov/models/go_bot/dto/dataset_features.py<gh_stars>1000+ from typing import List import numpy as np # todo remove boilerplate duplications # todo comments # todo logging # todo naming from deeppavlov.models.go_bot.nlu.dto.nlu_response import NLUResponse from deeppavlov.models.go_bot.policy.dto.digit...
StarcoderdataPython
1651709
name = input() print( name + ", " + name + ", bo-b" + name[1:] + "\n" + "banana-fana fo-f" + name[1:] + "\n" + "fee-fi-mo-m" + name[1:] + "\n" + name + "!" )
StarcoderdataPython
1688884
<filename>openmdao/components/meta_model.py """ Metamodel provides basic Meta Modeling capability.""" import sys import numpy as np from copy import deepcopy from openmdao.core.component import Component, _NotSet from six import iteritems class MetaModel(Component): """Class that creates a reduced order model f...
StarcoderdataPython
162924
<reponame>sarodriguez/audio-source-separation<gh_stars>0 import numpy as np from glob import glob from preprocess.config import config import logging import os import librosa def get_config_as_str(): return { 'FR': config.FR, 'FFT_SIZE': config.FFT_SIZE, 'HOP': config.HOP } def spec_complex(...
StarcoderdataPython
1783779
import logging import os import argparse from simpletransformers.language_generation import LanguageGenerationModel logging.basicConfig(level=logging.INFO) transformers_logger = logging.getLogger("transformers") transformers_logger.setLevel(logging.WARNING) def main(): parser = argparse.ArgumentParser() # Re...
StarcoderdataPython
1673966
# This algorithm is limited to algorithm verification import argparse import cv2 import os import numpy as np import pandas as pd import sys from tqdm import tqdm from skimage import transform from pprint import pprint from mtcnn.mtcnn import MTCNN import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) ...
StarcoderdataPython
23438
<filename>integration/phore/tests/shardsynctest.py import logging from phore.framework import tester, validatornode, shardnode from phore.pb import common_pb2 class ShardSyncTest(tester.Tester): def __init__(self): logging.info(logging.INFO) super().__init__() def _do_run(self): bea...
StarcoderdataPython
3372262
from analyzer.syntax_kind import SyntaxKind class VariableDeclarationSyntax(object): def __init__(self, var_token, variables, export_token, semicolon_token): self.kind = SyntaxKind.VariableDeclaration self.var_token = var_token self.variables = variables self.export_token = export_...
StarcoderdataPython
183609
from .base import BaseUrlsTestCase from .registration import RegistrationUrlsTestCase from .login import LoginUrlsTestCase from .logout import LogoutUrlsTestCase from .auth_info import AuthInfoUrlsTestCase
StarcoderdataPython
3329518
import streamlit as st from utils.streamlit_utils import paint def app(): st.title("Deaths") st.header("Welcome to the COVID 19 Deaths Page") paint("deaths")
StarcoderdataPython
1782734
#!/usr/bin/env python # -*- coding: utf-8 -*- from chainer import cuda from chainer import initializers from chainer import link from chainer import variable from lib.functions.connection import graph_convolution from lib import graph class GraphConvolution(link.Link): """Graph convolutional layer. This li...
StarcoderdataPython
4821382
import markdown.extensions def process_posts_and_pages(*, posts, pages, settings): """Dummy processer that sets an attribute on posts and pages""" for post in posts: post.test_attr = 'post' for page in pages: page.test_attr = 'page' return {'posts': posts, 'pages': pages} def process...
StarcoderdataPython
3284354
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def forwards_func(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Party = apps.get_model("party", "Party") for part...
StarcoderdataPython
145549
<filename>submissions/abc125/b.py n = int(input()) v = list(map(int, input().split())) c = list(map(int, input().split())) ans = 0 for i in range(n): xy = v[i] - c[i] if xy > 0: ans += xy print(ans)
StarcoderdataPython
1711979
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- from typing import Dict, Any import warnings from aws_lambda_powertools import Logger, Metrics, Tracer from aws_lambda_powertools.utilities.typing import LambdaContext from controltowerapi.models import AccountModel from responses import build_response, er...
StarcoderdataPython
3391897
# -*- coding: utf-8 -*- """ File Name: largest-perimeter-triangle.py Author : jynnezhang Date: 2020/11/29 12:55 下午 Description: https://leetcode-cn.com/problems/largest-perimeter-triangle/ """ class Solution: def largestPerimeter(self, A=[]) -> int: if not A or len(A) < 3: retu...
StarcoderdataPython
4824493
<filename>examples/python-mpi-example.py<gh_stars>0 from mpi4py import MPI from time import sleep import sys import subprocess import random import socket log_priority_threshold = 0 def logprint(priority, message): global log_priority_threshold if priority >= log_priority_threshold: print(message) ...
StarcoderdataPython
27382
import os # exemplo alterado de EX_10.5.py para 10_5.py for nome in os.listdir('./Minicurso/Minicurso API'): # alterar conforme sua necessidade de geração de nomes e layout de arquivos os.rename("./Minicurso/Minicurso API/"+nome, "./Minicurso/Minicurso API/"+nome+"_Minicurso_API.png") print("arquivo ...
StarcoderdataPython
4822373
<gh_stars>0 from zmq_cache.zmq_cache_server import CacheServer
StarcoderdataPython
3326574
# coding=utf-8 ############################################################################### # # This file is part of pyglfw project which is subject to zlib license. # See the LICENSE file for details. # # Copyright (c) 2013 <NAME> <<EMAIL>> # ############################################################...
StarcoderdataPython
4809940
<reponame>gpetretto/emmet from emmet.builders.settings import EmmetBuilderSettings SETTINGS = EmmetBuilderSettings()
StarcoderdataPython
3304907
# -*- coding: utf-8 -*- import datetime import json import scrapy from scrapy import Selector from spider.consts import MYSQL_ITEM_PIPELINES, DOWNLOADER_MIDDLEWARES_HTTP_PROXY_OFF from spider.items import SpiderLoaderItem, AnimationBangumiItem, AnimationEpisodeItem class JiadiandmSpider(scrapy.Spider): name = "...
StarcoderdataPython
88260
<reponame>xiling42/VL-BERT from .resnet_vlbert_for_pretraining import ResNetVLBERTForPretraining from .resnet_vlbert_for_pretraining_multitask import ResNetVLBERTForPretrainingMultitask from .resnet_vlbert_for_attention_vis import ResNetVLBERTForAttentionVis
StarcoderdataPython
1742228
<filename>Colloquiums/2020-2021/Colloquium_3/Exercise_3_edmonds_karp.py<gh_stars>1-10 import collections def bfs(graph, s, t, parent): visited = [False] * len(graph) queue = collections.deque() queue.append(s) visited[s] = True while queue: u = queue.popleft() for ind, val in enume...
StarcoderdataPython
3282596
<gh_stars>10-100 import grpc import proto.connection_pb2_grpc import proto.connection_pb2 from concurrent import futures from libs.core.Log import Log from libs.core.Event import Event import threading class GlobalServer(proto.connection_pb2_grpc.GlobalServerServicer): group_messages = [] topology_messages =...
StarcoderdataPython
3331870
"""Simple FUSE filesystem that mirrors a dir but hides symlinks.""" import os import os.path from loopback import Loopback class HideSymlinks(Loopback): """A loopback filesystem that overrides geattr to hide symlinks.""" symlink = None def getattr(self, path, fh=None): stat = os.stat(path) ...
StarcoderdataPython
3231678
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
StarcoderdataPython
119353
<reponame>artcz/adventofcode lines = open("input").read().strip().splitlines() print("--- Day11 ---") class Seat: directions = [ (dx, dy) for dx in [-1, 0, 1] for dy in [-1, 0, 1] if (dx, dy) != (0, 0) ] def __init__(self, x, y, dx, dy): self.x = x self.y = y self.dx = ...
StarcoderdataPython
1678161
<filename>features/Composers/composerTypes.py<gh_stars>1-10 from ariadne import load_schema_from_path, ObjectType, QueryType, MutationType from features.Composers.composer import resolve_composer, create_composer, update_composer, get_composers from features.Songs.song import resolve_songs from features.Songs.songTypes...
StarcoderdataPython
184796
<filename>nuzlockeai/utils/pokecache.py import requests import json from typing import List, Tuple, Optional class PokeCache: """ """ def __init__(self, fpath: Optional[str] = None): """ """ self.dex_cache = {} self.species_cache = {} if fpath is not None: ...
StarcoderdataPython
3267100
<reponame>strawsyz/straw import torch import torch.nn as nn from torch.autograd import Variable class VAE(nn.Module): """实现简单的VAE模型""" def __init__(self): super(VAE, self).__init__() # encoder部分 self.fc1 = nn.Linear(784, 400) self.fc21 = nn.Linear(400, 20) self.fc22 = ...
StarcoderdataPython
12650
<gh_stars>1-10 import sys from time import sleep from random import randint from urllib.request import urlopen from urllib.parse import urlencode if len(sys.argv) != 2: print('Por favor, usar: ' + sys.argv[0] + ' {idSensor}') print('Exemplo: ' + sys.argv[0] + ' 8') else: sensorId = sys.argv[1] URL_SERV...
StarcoderdataPython