id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
186160
#------------------------------------------------------------------------------- # The evolution of a uniform, magnetized conducting fluid. #------------------------------------------------------------------------------- from math import * from Spheral import * from SpheralTestUtilities import * from SpheralVisitDump i...
StarcoderdataPython
35359
<filename>code/src/main.py<gh_stars>100-1000 import torch import utility import data import model import loss from option import args from trainer import Trainer def print_network(net): num_params = 0 for param in net.parameters(): num_params += param.numel() print(net) print('Total number of ...
StarcoderdataPython
1729051
# -*- coding: utf-8 -*- # @Author : jjxu # @time: 2019/1/17 10:23 from app.libs.redprint import Redprint from app.validators.user_form import UserEmailForm api = Redprint("client") @api.route("/register", methods=["POST"]) def register(): # 1/0 form = UserEmailForm().validate_for_api() print(form) ...
StarcoderdataPython
148003
<reponame>globus-gladier/kanzus_client from .flow_data_transfer import TransferFlow from .flow_data_block_transfer import BlockTransferFlow from .flow_stills import StillsFlow from .flow_publish import PublishFlow from .flow_prime import PrimeFlow __all__ = ['TransferFlow', 'BlockTransferFlow', 'Stil...
StarcoderdataPython
4829316
from __future__ import unicode_literals import hashlib import hmac import re import time from .common import InfoExtractor from ..compat import compat_str from ..utils import ( ExtractorError, js_to_json, int_or_none, parse_iso8601, try_get, unescapeHTML, update_url_query, ) class ABCIE(...
StarcoderdataPython
189382
# 字符串 str= 'reverse this string', 请使用三种方法翻转字符串。 # 方法1: str= 'reverse this string' print(str[::-1]) # 方法2: str= 'reverse this string' length=len(str) str1='' for i in range(length,0,-1): str1+=str[i-1] print(str1) # 方法3: str= 'reverse this string' str3=reversed(str) str4='' for i in str3: str4+=i print(str4)...
StarcoderdataPython
49077
<filename>TAO/Firewall/BUZZDIRECTION/BUZZ_1120/LP/Scripts/Lp_UserInterface.py import cmd import os import Lp_FrontEndFunctions import Lp_CursesDriver import Lp_XmlParser import Lp_RpcDispatcher import string import sys import socket import textwrap import time import subprocess import signal import platform import thre...
StarcoderdataPython
1729237
import requests from bs4 import BeautifulSoup URL = input() page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") text = soup.find(id="maincontent") paragraphs = text.find_all("p") for paragraph in paragraphs: print(paragraph.text, "\n")
StarcoderdataPython
153586
<filename>pset6/hello.py from cs50 import get_string # Prompt uset for name n = get_string("What is your name? ") print("hello,", n)
StarcoderdataPython
99081
<reponame>DanielSoaresFranco/Aulas.py def mensagem(cor='', msg='', firula='', tamanho=0): if '\n' in msg: linha = msg.find('\n') else: linha = len(msg) limpa = '\033[m' if tamanho == 0: tamanho = firula * (linha + 4) if firula == '': print(f'{cor} {msg} {limpa}') ...
StarcoderdataPython
3306224
<filename>tools.py import datetime import functools import io import math import pathlib import pickle import re import uuid import imageio import gym import numpy as np import tensorflow as tf import tensorflow.compat.v1 as tf1 import tensorflow_probability as tfp from tensorflow.keras.mixed_precision import experimen...
StarcoderdataPython
4832402
from __future__ import unicode_literals from builtins import str import six @six.python_2_unicode_compatible class Token: def __init__(self, string="", metadata=None): self.string = string self.metadata = metadata or {} def __str__(self): return self.string def __repr__(self): ...
StarcoderdataPython
3265753
<filename>version_2/demo/software/example/overlay/usr/bin/axil2ipb.py #!/usr/bin/python f=open("/dev/ipb_0","r+b",0) import struct import mmap import time regs=mmap.mmap(f.fileno(),0x10,mmap.MAP_SHARED,mmap.ACCESS_WRITE,offset=0x000) def set_val(mm,pos,val): s=struct.pack("<L",val) mm[(pos*4):((pos+1)*4)]=s def f...
StarcoderdataPython
3347106
<reponame>py-az-cli/py-az-cli from ..... pyaz_utils import _call_az def list(resource_group, workspace_name): ''' List all data export ruleses for a given workspace. Required Parameters: - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults grou...
StarcoderdataPython
1618381
import os import asyncio import hashlib import pathlib import synapse.tests.utils as s_t_utils import synapse.tools.pullfile as s_pullfile class TestPullFile(s_t_utils.SynTest): async def test_pullfile(self): async with self.getTestAxon() as axon: axonurl = axon.getLocalUrl() t...
StarcoderdataPython
1650957
# Generated by Django 3.0.9 on 2020-10-07 12:35 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20200923_1557'), ] operations = [ migrations.RenameField( model_name='customermore', old_name='collector'...
StarcoderdataPython
96506
<reponame>levinsamuel/rand from datetime import datetime from pymongo import MongoClient from bson.objectid import ObjectId import pprint import logging import json from people import Person logging.basicConfig() log = logging.getLogger('mongocl') log.setLevel(logging.DEBUG) def client(): return MongoClient('loc...
StarcoderdataPython
145727
from __future__ import absolute_import, unicode_literals from django.contrib import messages from django.core.files.base import ContentFile from django.db import transaction from django.http import Http404, HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.template import RequestContext f...
StarcoderdataPython
1623161
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import sys import os import time import tempfile import re import datetime reload(sys) # sys.setdefaultencoding("utf-8") # url = 'localhost' # header = {"Accept": " application/json", "Content-Type": " application/json"} # request = urllib2.Reque...
StarcoderdataPython
156902
#!/usr/bin/env python3 import unittest import torch from torch.distributions import Distribution from Lgpytorch.distributions import MultitaskMultivariateNormal, MultivariateNormal from Lgpytorch.likelihoods import SoftmaxLikelihood from Lgpytorch.test.base_likelihood_test_case import BaseLikelihoodTestCase class ...
StarcoderdataPython
68997
import pandas as pd def preprocess(): train_data = pd.read_csv("datasets/adult/adult.data", sep = ', ', header=None, names = ('age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-...
StarcoderdataPython
3319027
from datetime import datetime import offchain from offchain import FundPullPreApprovalStatus from flask import Response from flask.testing import Client from tests.wallet_tests.resources.seeds.one_funds_pull_pre_approval import TIMESTAMP from wallet.services.offchain import ( offchain as offchain_service, fund...
StarcoderdataPython
112860
from typing import Optional, Union import tensorflow as tf from tensorflow.python.framework.convert_to_constants import ( convert_variables_to_constants_v2_as_graph, ) from tensorflow.keras import Sequential, Model import keras_flops.flops_registory def get_flops(model: Union[Model, Sequential], batch_size: Opt...
StarcoderdataPython
3399005
<gh_stars>1-10 # Copyright (c) FULIUCANSHENG. # Licensed under the MIT License. from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union from PIL import Image from unitorch.models.vit import ViTProcessor as _ViTProcessor from unitorch.cli import cached_path from unitorch.cli import ( add_default_s...
StarcoderdataPython
3232212
<reponame>noklam/blog<filename>_demo/leetcode/617.merge-two-binary-trees.py # # @lc app=leetcode id=617 lang=python3 # # [617] Merge Two Binary Trees # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self...
StarcoderdataPython
3280600
import numpy as np from numpy import linalg as la import matplotlib.pyplot as plt import matplotlib.axes as ax #matplotlib inline import psyneulink as pnl import psyneulink.core.components.functions.transferfunctions from psyneulink.core.components.functions.learningfunctions import BackPropagation nouns = ['oak', 'pi...
StarcoderdataPython
3393169
<gh_stars>1-10 # -*- coding: utf-8 -*- import os from glob import glob from os.path import join import torch import torchvision import transformers import more_itertools import numpy as np import matplotlib.pyplot as plt import torch.nn.functional as F from tqdm.auto import tqdm from PIL import Image from einops impor...
StarcoderdataPython
3331734
<gh_stars>1-10 import argparse def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--path", help="path to the config file directory") # Folder settings parser.add_argument("--prefix", help="experiment prefix, if given creates subfolder in experiment directory") parser.add_argu...
StarcoderdataPython
50099
<filename>LeetCode/Problems/15. 3Sum.py class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res = [] for i,a in enumerate(nums): # If same as the previous value just continue, alread...
StarcoderdataPython
1602703
# -*- coding: utf-8 -*- # Copyright 2011 Nelen & Schuurmans from django.conf import settings from django.core.management.base import BaseCommand from lizard_auth_server.models import Token import datetime import logging import pytz logger = logging.getLogger(__name__) TOKEN_TIMEOUT = datetime.timedelta(minutes=sett...
StarcoderdataPython
193923
from .dataclass import frequency ANALYTICS_API_URL = "https://appstoreconnect.apple.com/analytics/api/v1" # TODO: use Config class Instead of config dict. class Config(): def __init__(self, app_id): self.startTime = None self.endTime = None self.adamId = [app_id] self.group = None...
StarcoderdataPython
144906
<filename>snipping/main.py """Main """ import sys from snipping import application from snipping import prompt_toolkit def main(): init_file = None if len(sys.argv) > 1: init_file = sys.argv[1] app = application.get_application(init_file=init_file) return prompt_toolkit.run(app)
StarcoderdataPython
3331359
# a * x + b * y = gcd(a, b) def egcd(a: int, b: int) -> (int, int, int): if a == 0: return b, 0, 1 else: gcd, x, y = egcd(b % a, a) return gcd, y - (b // a) * x, x if __name__ == '__main__': print(egcd(50, 30))
StarcoderdataPython
1653434
from process_json import * import numpy as np BS = 32 """def create_tags(text,a): #Text includes entities marked as BEG__w1 w2 w3__END. Transform to a tags list. mya = a.lower() a = mya.split() tags = [] inside = False for w in text.split(): w_stripped = w.strip() if w_stripped...
StarcoderdataPython
1677732
""" The tool to check the availability or syntax of domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ █...
StarcoderdataPython
1622390
from flask.ext.assets import Environment import os from . import pipeline from shutil import copytree, rmtree, copy assets = Environment() assets.register('js', pipeline.js) assets.register('js_map', pipeline.js_map) assets.register('js_polyfills_ie9', pipeline.js_polyfills_ie9) assets.register('js_polyfills_ie8', pi...
StarcoderdataPython
1734616
<filename>sensors_communication/src/sonic_stream.py #!/usr/bin/env python import json import rospy from std_msgs.msg import String from sonic_sensor import HCSR04 if __name__ == "__main__": rospy.init_node('sonic_data_streamer') pub = rospy.Publisher('/sonic_data', String, queue_size=10) rate = rospy....
StarcoderdataPython
113961
__version__ = "0.8.0-alpha.8" __api_version__ = "v1"
StarcoderdataPython
3348463
<filename>lib/spack/spack/container/writers/__init__.py # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) """Writers for different kind of recipes and related convenience fu...
StarcoderdataPython
3297434
<filename>FeatureVectorGeneration/extract_total_img.py from xml.etree.ElementTree import ElementTree import glob import subprocess import os import codecs import threading import time import hoggen taskParam_noThread = 10 taskParam_apklistfilename = './apklist.txt' taskParam_resultfilename = 'Hogs.txt' taskParam_rawda...
StarcoderdataPython
3223285
import topogenesis as tg import numpy as np np.random.seed(0) # agent class class agent(): def __init__(self, origin, stencil, id): # define the origin attribute of the agent and making sure that it is an intiger self.origin = np.array(origin).astype(int) # define old origin attribute and ...
StarcoderdataPython
1749491
<gh_stars>10-100 from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.framework import ops from tensorflow.python.training import optimizer import tensorflow as tf import numpy as np class Grad(optimizer.Optimi...
StarcoderdataPython
59620
<reponame>Lapu-Lapu/mp-prediction # -*- coding: utf-8 -*- """ This script is used with the data of the VR-Psychophysics Experiment to: - clean the dataset from training trials - clean the dataset from catch trials, as well as creating a csv-file containing all catch trials for catch_analysis - crea...
StarcoderdataPython
3386381
# type: ignore # # Autogenerated by Thrift Compiler (0.13.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # import sys from thrift.protocol.TProtocol import TProtocolException from thrift.Thrift import ( TApplicationException, TException, TFrozenDict, T...
StarcoderdataPython
36892
<reponame>jasmine92122/NightClubBackend # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-08-13 12:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('places', '0085_placetype_name_plural'), ] o...
StarcoderdataPython
1694010
<reponame>ikhlo/LinkPrediction_Kaggle<gh_stars>0 import csv import networkx as nx import numpy as np from random import randint from sklearn.linear_model import LogisticRegression # Create a graph G = nx.read_edgelist('edgelist.txt', delimiter=',', create_using=nx.Graph(), nodetype=int) nodes = list(G.nodes()) n = G.n...
StarcoderdataPython
3358939
<filename>parsi_io/modules/quranic_extractions.py #In the name of Allah import re import pickle import pandas as pd import time import zipfile import os from tqdm import tqdm from tashaphyne.normalize import strip_tashkeel, strip_tatweel from camel_tools.utils.normalize import normalize_alef_maksura_ar, normalize_teh_...
StarcoderdataPython
168732
import copy from dlgo.gotypes import Player, Point from dlgo.scoring import compute_game_result from dlgo import zobrist neighbor_tables = {} corner_tables = {} def init_neighbor_table(dim): rows, cols = dim new_table = {} for r in range(1, rows + 1): for c in range(1, cols + 1): p =...
StarcoderdataPython
3247535
<gh_stars>1-10 import unittest import numpy as np from PEPit.pep import PEP from PEPit.point import Point from PEPit.expression import Expression from PEPit.function import Function from PEPit.functions.smooth_strongly_convex_function import SmoothStronglyConvexFunction class TestPEP(unittest.TestCase): def set...
StarcoderdataPython
131969
class Monster: def __init__(self, name, color): self.name = name self.color = color def attack(self): print('I am attacking...') class Fogthing(Monster): def attack(self): print('I am killing...') def make_sound(self): print('Grrrrrrrrrr\n') fogthing = Fogth...
StarcoderdataPython
3394307
<filename>burndown.py import sys, gitlab, collections, datetime, dateutil.parser, pickle import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import scipy.interpolate as interpolate import scipy.signal as signal def dd_int(): return collections.defaultdict(int) # hotpatch python-gitla...
StarcoderdataPython
31434
<filename>vscode/app.py from flask import Flask, render_template, request, make_response, g import os import socket import random import json import collections hostname = socket.gethostname() votes = collections.defaultdict(int) app = Flask(__name__) def getOptions(): option_a = 'Cats' option_b = 'Dogs' ...
StarcoderdataPython
3331565
<gh_stars>0 import re DIRECTIONS = { 'e': lambda a, b: (a+1, b), 'se': lambda a, b: (a+1 if b % 2 else a, b+1), 'ne': lambda a, b: (a+1 if b % 2 else a, b-1), 'w': lambda a, b: (a-1, b), 'sw': lambda a, b: (a-1 if (b+1) % 2 else a, b+1), 'nw': lambda a, b: (a-1 if (b+1) % 2 else a, b-1) } line...
StarcoderdataPython
3305213
<reponame>hefen1/chromium<filename>tools/perf/profile_creators/profile_safe_url_generator.py # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import HTMLParser import json import logging import urllib2 impo...
StarcoderdataPython
3300903
<filename>swagger_server/test/operational_controllers/test_resource_permissions_for_roles.py # coding: utf-8 from __future__ import absolute_import from ge_core_shared import db_actions, decorators from flask import json from project.settings import API_KEY_HEADER from swagger_server.models import Permission, Resour...
StarcoderdataPython
3246282
#!/usr/bin/env python import sys from comms import * import serial import time if len(sys.argv) != 3: print("give me a serial port and address") exit() port = sys.argv[1] s = serial.Serial(port=port, baudrate=COMM_DEFAULT_BAUD_RATE, timeout=0.1) address = int(sys.argv[2]) client = BLDCControllerClie...
StarcoderdataPython
118848
<filename>src/chaos_service/main.py import click from flask import Flask from chaos_service.api import api, config from chaos_service.config.config_storage import ConfigStorage @click.group() @click.version_option("0.0.1") def cli(): """ First version of chaos service. """ @cli.command() @click.option(...
StarcoderdataPython
36331
<gh_stars>1-10 import os from setuptools import setup, find_packages DIR_PATH = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(DIR_PATH, 'README.md')) as file: long_description = file.read() install_requires = [line.rstrip('\n') for line in open(os.path.join(DIR_PATH, 'requirements.txt'))] s...
StarcoderdataPython
188371
from random import choice class Game: def __init__(self, gui: object): self.gui: object = gui self.field = gui.grid.field self.current_sym: str = choice(["X", "0"]) for row in range(3): for col in range(3): btn = self.gui.grid.field[row][col] ...
StarcoderdataPython
1625516
#!/usr/bin/python # -*- coding: utf-8; -*- # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
StarcoderdataPython
3342390
from tkinter import filedialog, Tk from typing import List import matplotlib.pyplot as plt import numpy as np from lmfit import Model from lmfit.models import GaussianModel, LinearModel from pandas import read_csv, read_hdf, DataFrame, set_option from scipy import fftpack, interpolate from scipy.optimize import curve_...
StarcoderdataPython
1608545
<filename>mayan/apps/storage/tests/test_management_commands.py<gh_stars>100-1000 from django.core import management from django.utils.encoding import force_text from mayan.apps.documents.tests.base import GenericDocumentTestCase from mayan.apps.documents.storages import storage_document_files from mayan.apps.mimetype....
StarcoderdataPython
1693212
<gh_stars>1-10 import random import time class Nonogramm: def __init__(self, size, inputInfo): self.sizeX = size[0] self.sizeY = size[1] self.inputInfoX = inputInfo[0] self.inputInfoY = inputInfo[1] self.field = [[0 for x in range(self.sizeX)] for y in range(self.sizeY)] ...
StarcoderdataPython
57180
<gh_stars>0 import vk import os from urllib.request import urlopen from time import sleep session = vk.Session() api = vk.API(session, v='5.53', lang='ru', timeout=10) def get_photos_urls(user_id): photos_json = api.photos.get(owner_id=user_id, album_id='saved') photos_amount = photos_json['count'] photos...
StarcoderdataPython
1738281
# Elastic search mapping definition for the Molecule entity from glados.es.ws2es.es_util import DefaultMappings # Shards size - can be overridden from the default calculated value here # shards = 7 replicas = 0 analysis = DefaultMappings.COMMON_ANALYSIS mappings = \ { 'properties': { ...
StarcoderdataPython
3223724
<filename>scripts/cubic_traj_planner.py #!/usr/bin/env python import rospy from AR_week4_test.msg import cubic_traj_params, cubic_traj_coeffs from AR_week4_test.srv import compute_cubic_traj, compute_cubic_trajRequest def callback(data_value): rospy.wait_for_service('polynomial_trajectory') try: poly_t...
StarcoderdataPython
1738840
<filename>p01-feature-splits.py # Decision Trees: Feature Splits #%% # Python typing introduced in 3.5: https://docs.python.org/3/library/typing.html from typing import List # As of Python 3.7, this exists! https://www.python.org/dev/peps/pep-0557/ from dataclasses import dataclass # My python file (very limited for...
StarcoderdataPython
1755221
<reponame>Yuri-Lima/Fake_No_More_Blog from django.db import models from django.conf import settings from django.urls import reverse from django.contrib.auth import get_user_model from users.models import User UserModel = get_user_model() # Create your models here. class SendContactEmail(models.Model): subject = mo...
StarcoderdataPython
3252466
# Generated by Django 2.2.7 on 2019-12-02 19:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('paper', '0018_auto_20191120_1647'), ('paper', '0018_auto_20191125_1956'), ] operations = [ ]
StarcoderdataPython
111336
from bocadillo import App app = App( enable_cors=True, cors_config={"allow_origins": ["*"], "allow_methods": ["*"]}, ) _COURSES = [ { "id": 1, "code": "adv-maths", "name": "Advanced Mathematics", "created": "2018-08-14T12:09:45", }, { "id": 2, "code"...
StarcoderdataPython
3261673
# Copyright (c) 2021, NVIDIA CORPORATION from geopandas.geoseries import is_geometry_type as gp_is_geometry_type from cuspatial.geometry.geoseries import GeoSeries, GeoColumn def is_geometry_type(obj): """ Returns `True` if the column is a `GeoPandas` or `cuspatial.GeoSeries` """ if isinstance(obj, (...
StarcoderdataPython
1707734
# idel_utils.py import os import json # Constants STR_CFN = 'cfn' STR_AWS = 'aws' STR_DEPLOY = 'deploy' STR_DELETE = 'delete' CHANGE_MODE_CHANGE = 'change' CHANGE_MODE_PROVISION = 'provision' CHANGE_MODE_DESTROY = 'destroy' CHANGE_MODE_ON = 'on' CHANGE_MODE_OFF = 'off' # Sample continuationToken """ { "StackName...
StarcoderdataPython
1697291
<filename>omtk/widget_list_influences.py import re import pymel.core as pymel from PySide import QtCore from PySide import QtGui from ui import widget_list_influences import libSerialization from omtk.libs import libSkinning from omtk.libs import libQt from omtk.libs import libPython from omtk.libs import libPymel im...
StarcoderdataPython
175613
import matplotlib.pyplot as pl import os import numpy as np from ticle.data.dataHandler import normalizeData,load_file from ticle.analysis.analysis import get_significant_periods pl.rc('xtick', labelsize='x-small') pl.rc('ytick', labelsize='x-small') pl.rc('font', family='serif') pl.rcParams.update({'font.size': 20})...
StarcoderdataPython
81814
import json import re import requests import threading from flask import current_app as app ingredLock = threading.RLock() posLock = threading.RLock() recipeLock = threading.RLock() imgDownloadLock = threading.RLock() processLocker = threading.RLock() def recipesByIngredients(ingredientsList, maxRecpts='20', ranki...
StarcoderdataPython
1768484
#coding=utf-8 """ __create_time__ = '13-10-13' __author__ = 'Madre' """ from django.contrib import admin from translation.models import Translation class TranslationAdmin(admin.ModelAdmin): list_display = ('m_type', 'title', 'tran_title', 'user', 'index', 'show') list_display_links = ['title'] list_editab...
StarcoderdataPython
3267826
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import core.utils class Migration(migrations.Migration): dependencies = [ ('core', '0029_auto_20170209_1656'), ] operations = [ migrations.AddField( model_name='lesson', ...
StarcoderdataPython
1714004
<reponame>Jeetandra/cortx-s3server # # Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates # # 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/LI...
StarcoderdataPython
1623357
import pygame as pg class CoinDebris(object): """ Coin that appears when you hit the question block. """ def __init__(self, x_pos, y_pos): self.rect = pg.Rect(x_pos, y_pos, 16, 28) self.y_vel = -2 self.y_offset = 0 self.moving_up = True self.current_image = ...
StarcoderdataPython
3259584
"""Datatypes.""" # pylint: disable=invalid-name,too-many-instance-attributes,missing-class-docstring from dataclasses import dataclass from typing import List, Optional @dataclass class TrackingProperties: streak: int username: str creation_age: int is_age_restricted: bool creation_date: str ...
StarcoderdataPython
3301382
# Generated by Selenium IDE import pytest import time import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWa...
StarcoderdataPython
3276777
lista = [] pos = 0 x = 0 for i in range(6): lista.append(float(input())) for i in lista: if i >= 0: pos += 1 x = i + x media = x / pos media = round(media) print("{} valores positivos".format(pos)) print(media)
StarcoderdataPython
1740464
<gh_stars>1-10 # BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE import pytest # noqa: F401 import numpy as np # noqa: F401 import awkward as ak # noqa: F401 def test(): array = ak.from_numpy(np.zeros((3, 0), dtype=np.int32)) buffs = ak.to_buffers(array) new_array...
StarcoderdataPython
3272978
from io import BytesIO from pprint import pformat from unittest import mock from urllib.response import addinfourl from urllib.error import HTTPError import pytest from simplecep import CEPAddress from simplecep.providers import ALL_PROVIDERS from .providers_tests_data import providers_tests_data from .captured_resp...
StarcoderdataPython
3301232
<reponame>IMrIDarkWolf/wagtail-opengraph-image-generator<filename>wagtail_opengraph_image_generator/conf.py from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured PREFIX = 'WAGTAIL_OG_IMAGE_GENERATOR_' DEFAULT_SETTINGS = { 'IMAGE_WIDTH': 1200, 'I...
StarcoderdataPython
3274072
<filename>src/web/modules/dashboard/controllers/edit.py # edit dashboard from flask import request, render_template import web.util.tools as tools def get(p): if request.method == "POST": # save dashboard tools.set_conf(p['host'], p['navigation']['id'], "dashboard", request.f...
StarcoderdataPython
3258160
from Escritor import Escritor from PostgreSQL.ConexionSQL import ConexionSQL import json import datetime class EscritorTweets(Escritor): """docstring for EscritorTweets""" def __init__(self, searchID): super(EscritorTweets, self).__init__(searchID) conSql = ConexionSQL() self.conn = conSql.getConexion() self....
StarcoderdataPython
124044
<filename>tools/benchmarks.py # -*- coding: utf-8 -*- """ @date: 2020/11/4 下午2:06 @file: benchmarks.py @author: zj @description: """ import time import numpy as np import torch from zcls.util.distributed import get_device, get_local_rank from zcls.util.metrics import compute_num_flops from zcls.config import cfg fr...
StarcoderdataPython
1734433
<reponame>Dokeey/Buy-Sell from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.contenttypes.models import ContentType from django.db.models import Sum, Count, FloatField, IntegerField from django.db.models.functions import Cast from django.http import Http40...
StarcoderdataPython
1744237
import pytest from django import forms from getin.forms import InvitationCodeField class RegistrationForm(forms.Form): invitation_code = InvitationCodeField() @pytest.mark.parametrize( "invitation, result", [ ("unsent_invitation", False), ("sent_invitation", True), ("consumed_in...
StarcoderdataPython
1654262
#-*-coding:utf-8-*- from flask import Flask app = Flask(__name__) from celery import Celery from celery import platforms #如果你不是linux的root用户,这两行没必要 platforms.C_FORCE_ROOT=True #允许root权限运行celery def make_celery(app): celery = Celery('flask_celery', #此处官网使用app.import_name,因为这里将所有代码写在同一个文件flask_celery.py,所以直接写名字...
StarcoderdataPython
3228506
<filename>mynewsite/board/admin.py<gh_stars>0 from django.contrib import admin from board import models # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ("nickname", "message", "enabled", "pub_time") ordering = ("-pub_time", ) admin.site.register(models.Mood) admin.site.register(...
StarcoderdataPython
3242554
<reponame>ULNE/MicroPython<gh_stars>0 import pyb import time while True: pyb.LED(3).on() #LED3 = orange time.sleep(1) pyb.LED(3).intensity(20) time.sleep_ms(500)
StarcoderdataPython
1767837
<reponame>brianbruggeman/rl import random import numpy as np def perlin(samples=None, seed=None, size=None): # permutation table size = 256 if size is None else size samples = 100 if samples is None else samples seed = random.randint(0, size) if seed is None else seed np.random.seed(seed) lin...
StarcoderdataPython
1722248
<reponame>ShivamPytho/parsifal from django import forms from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMultiAlternatives from django.db.models.functions import Lower from django.template.loader import render_to_string from django...
StarcoderdataPython
3254868
<reponame>altcnews/bitmex_grid<gh_stars>1-10 import logging from market_maker.settings import settings from datetime import datetime import os def setup_custom_logger(name, log_level=settings.LOG_LEVEL): os.environ['TZ'] = 'Europe/Moscow' formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(modul...
StarcoderdataPython
44390
<reponame>mfeindt0705/pynetmf<gh_stars>0 #!/usr/bin/env python from getpass import getpass from pprint import pprint from napalm import get_network_driver # Supress SSL Certificate Warnings import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnin...
StarcoderdataPython
3279264
# coding: utf-8 """ SimScale API The version of the OpenAPI document: 0.0.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from simscale_sdk.configuration import Configuration class OneOfDimensionalVectorFunctionPressureValue(object): """NOTE: T...
StarcoderdataPython
1600294
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.9.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% import matplotli...
StarcoderdataPython
4820646
import logzero logzero.json() log = logzero.logger
StarcoderdataPython