id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
389337 | <filename>set1/challenge6.py
from common.tools.base64 import Base64Decoder
from common.challenge import MatasanoChallenge
from common.attacks.xor import RepeatingKeyXORDecrypter
class Set1Challenge06(MatasanoChallenge):
FILE = 'set1/data/6.txt'
def expected_value(self):
return open('... | StarcoderdataPython |
9749537 | """
This example shows how to use a PointsDensity
actor to show the density of labelled cells
"""
import random
import numpy as np
from brainrender import Scene
from brainrender.actors import Points, PointsDensity
from rich import print
from myterial import orange
from pathlib import Path
print(f"[{orange}]... | StarcoderdataPython |
5027451 | #!/usr/bin/env python3
'''
Author: AGDC Services
Website: AGDCservices.com
Date: 20210501
This is a Command and Control(C2) server simulator for TCP traffic
Usage:
- Fill in the variables at the top of main
- write your custom C2 code in the "Start of C2 Simulation Code"
section in main a... | StarcoderdataPython |
277844 | <filename>test/test_cli.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import inspect
import io
import os
import sys
import textwrap
import unittest
# prefer local copy to the one which is installed
# hack from http://stackoverflow.com/a/6098238/280539
_top_level_path = os.path.realpath(
os.path.abspath(
os... | StarcoderdataPython |
3354987 | import django_dynamic_fixture as fixture
from allauth.account.views import SignupView
from django.contrib.auth.models import User
from django.core.cache import cache
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from readthedocs.organizations.models im... | StarcoderdataPython |
1986251 | import plotly.graph_objects as go
def return_graphs(df):
''' Module to create Plotly figures '''
# extract data needed for visuals
genre_counts = df.groupby('genre').count()['message']
genre_names = list(genre_counts.index)
# create visuals
genres_graph = []
genres_graph.appe... | StarcoderdataPython |
5058211 | <filename>start1.py<gh_stars>1-10
#import libraries
import gym
import time
#create environment
environment = gym.make('CartPole-v0')
#reset environment
environment.reset()
#iterator for rendaring the environment
for _ in range(100):
time.sleep(0.05)
environment.render()
_, _, completed, _ = e... | StarcoderdataPython |
4906026 | <filename>demo/demo.py
from gearbox.transmission.gears import *
from gearbox.standards.iso import Pitting as isoPitting
from gearbox.standards.iso import Bending as isoBending
from gearbox.standards.agma import Pitting as agmaPitting
from gearbox.standards.agma import Bending as agmaBending
from gearbox.export.export i... | StarcoderdataPython |
5044279 | """Contains layer-related utility functions.
"""
import tensorflow as tf
from tensorflow.keras.layers import Concatenate, Flatten, Layer, Activation
from typing import List, Any
from .activation import Dice
def _concat(inputs: List, axis: int = -1) -> tf.Tensor:
"""Concatenate list of input, handle the case when ... | StarcoderdataPython |
4912123 | <filename>pytify/linux.py
# -*- coding: utf-8 -*-
import sys
import dbus
from pytifylib import Pytifylib
import time
class Linux(Pytifylib):
def __init__(self):
try:
self.interface = dbus.Interface(
dbus.SessionBus().get_object(
'org.mpris.MediaPlayer2.spoti... | StarcoderdataPython |
6553117 | <filename>tests/test_cmd.py
#!/usr/bin/env python
"""Tests for processing the cli."""
import os
import unittest
from tally_ho import cmd, tally_ho
class TestCLICmds(unittest.TestCase):
def setUp(self):
self.th = tally_ho.TallyHo('test.db')
def tearDown(self):
os.remove('test.db')
de... | StarcoderdataPython |
11251672 | <reponame>Aniiket7/Assignments<filename>Programming Assignment/p3.py
def maxArea(A, Len) :
area = 0
for i in range(Len) :
for j in range(i + 1, Len) :
area = max(area, min(A[j], A[i]) * (j - i))
return area
a = [int(n) for n in input("Enter an array: ").split()]
len1 = len(a)
print(m... | StarcoderdataPython |
3276847 | <filename>tests/test_models.py
# Copyright 2016, 2021 <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | StarcoderdataPython |
8071362 | <gh_stars>0
x=5
if x=="test":
print(x)
| StarcoderdataPython |
5174998 | # Generated by Django 3.1 on 2020-09-11 06:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("verification", "0019_auto_20200909_0752"),
("verification", "0018_auto_20200910_0929"),
]
operations = []
| StarcoderdataPython |
6689447 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import datetime
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.urlresolvers import reverse
from django.forms import *
from django.forms.widg... | StarcoderdataPython |
12811439 | <gh_stars>1-10
from .pt_reader import PTReader
from .cls_reader import DocClsReader
from .pt_cls_reader import DocRepClsReader
| StarcoderdataPython |
1882448 | from django.db import models
# Create your models here.
class Servicio(models.Model):
titulo=models.CharField(max_length=50)
contenido=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='servicios')
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_n... | StarcoderdataPython |
6646503 | from django.apps import AppConfig
class ModulosArtigosConfig(AppConfig):
name = 'icsmp_project.modulos_artigos'
| StarcoderdataPython |
168708 | <filename>2020/day12/solution.py
import re
import sys
def main():
with open(sys.argv[1]) as f:
instructions = [l.strip() for l in f]
part1(instructions)
part2(instructions)
def part1(instructions):
x = 0
y = 0
direction = (1, 0)
for instruction in instructions:
operation ... | StarcoderdataPython |
163988 | <filename>diffrend/numpy/camera.py
import numpy as np
from diffrend.numpy.vector import Vector
from diffrend.numpy.quaternion import Quaternion
import diffrend.numpy.ops as ops
class Camera(object):
def __init__(self, pos, at, up, viewport):
#assert isinstance(orientation, Quaternion)
self.pos = n... | StarcoderdataPython |
97936 | <reponame>CN-UPB/FutureCoord<filename>utils/graph_generator.py
import random
import argparse
import numpy as np
import networkx as nx
from geopy.distance import geodesic
def graphml_reader(seed, compute, bandwidth, inputfile, outputfile):
'''Creates a gpickle graph from a graphml file. The node capacity (compute... | StarcoderdataPython |
6404694 | __author__ = 'zhanghe'
class shortTextFilter:
def __init__(self,min_length=10):
self.min_length = min_length
def filterFile(self,src_filename,dst_filename):
f_dst = open(dst_filename,'a+')
with open(src_filename,'r') as src:
for line in src:
count = len(line.s... | StarcoderdataPython |
6612563 | from skimage import io
import os
import numpy as np
DEBUG = 0
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
if DEBUG:
print(BASE_DIR)
PICS_DIR = os.path.join(BASE_DIR,"..\\pics\\test_match")
if DEBUG:
print(PICS_DIR)
GREY = [247, 247, 247]
GREEN = [148, 211, 77]
WHITE = [255, 255, 255]
vertex_top = 12... | StarcoderdataPython |
5003905 | <filename>ex022-Analisando um Texto.py
'''
EXERCÍCIO 022: Analisador de Textos
Crie um programa que leia o nome completo de uma pessoa e mostre:
> O nome com todas as letras maiúsculas e minúsculas.
> Quantas letras ao todo (sem considerar espaços).
> Quantas letras tem o primeiro nome.
'''
def lin():
print('-'*80... | StarcoderdataPython |
4907209 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | StarcoderdataPython |
9796127 | <reponame>scuml/django_bench_runner
import os
import sys
from setuptools import setup, find_packages
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
if 'publish' in sys.argv:
if 'test' in sys.argv:
os.system('python setup.py sdist bdi... | StarcoderdataPython |
6471707 | <filename>myaccounts/encoders.py
# encoding: utf-8
from django.forms.models import model_to_dict
from django.db.models import Model
from django.db.models.fields.files import FieldFile
from datetime import datetime
from enum import Enum
from decimal import Decimal
import json
from rest_framework.utils.encoders import JS... | StarcoderdataPython |
6572644 | #
# IMPORTS
#
import bpy
import imp
import mathutils
import utilities
imp.reload( utilities )
from math import radians
############################################################
#
# GLOBALS
#
############################################################
############################################################... | StarcoderdataPython |
3526693 | <gh_stars>1-10
"""
Simple utility to render an .svg to a .png
"""
import os
import argparse
import pydiffvg
import torch as th
def render(canvas_width, canvas_height, shapes, shape_groups):
_render = pydiffvg.RenderFunction.apply
scene_args = pydiffvg.RenderFunction.serialize_scene(
canvas_width, canv... | StarcoderdataPython |
5187721 | """
Created on Oct 2, 2012
@author: <NAME>
Adapted from cos.py from Nghia & Georgiana
"""
import numpy as np
from composes.similarity.similarity import Similarity
from scipy.spatial.distance import jaccard
class JaccardSimilarity(Similarity):
"""
Computes the jaccard similarity of two vectors.
"""
... | StarcoderdataPython |
9763090 | # -*- coding:utf8 -*-
# File : query_pipe.py
# Author : <NAME>
# Email : <EMAIL>
# Date : 3/19/17
#
# This file is part of TensorArtist.
from . import configs, utils
from ...core import get_logger
from ...core.utils.callback import CallbackManager
from ...core.utils.meta import notnone_property
import zmq
impo... | StarcoderdataPython |
9788934 | <gh_stars>0
from django.db import models
from leasing.models.mixins import TimeStampedModel
from ..utils import generate_unique_identifier
class Form(TimeStampedModel):
name = models.CharField(max_length=255)
description = models.TextField(blank=True)
is_template = models.BooleanField(default=False)
... | StarcoderdataPython |
11354979 | from aiohttp import web
def redirect(request, router_name, **kwargs):
url = request.app.router[router_name].url_for(**kwargs)
return web.HTTPFound(url)
| StarcoderdataPython |
1767559 | <reponame>att/Snappy-Frontend
#!/usr/bin/python
from contextlib import closing
from datetime import datetime
import json
import MySQLdb
import sys
import os
DB_USER = os.environ["SNAPPY_USER"]
DB_PASS = os.environ["SNAPPY_PW"]
DB_NAME = os.environ["SNAPPY_DB"]
DB_IP = os.environ["SNAPPY_HOST"]
DB_PORT = int(os.enviro... | StarcoderdataPython |
1869137 | # -*- coding: utf-8 -*-
""" Base interfaces for dipy """
from __future__ import print_function, division, unicode_literals, absolute_import
import os.path as op
import numpy as np
from ... import logging
from ..base import (traits, File, isdefined,
BaseInterface, BaseInterfaceInputSpec)
IFLOGGER =... | StarcoderdataPython |
6548102 | <filename>mynie/__init__.py
# This file contains the entry_point callable that is responsible for
# dynamically adding the parsers into the Genie framework.
from mynie.parser import linux, myos
__all__ = []
def add_my_parsers():
"""
See genie/libs/parser/utils/entry_points.py for more information.
"""
... | StarcoderdataPython |
5136311 | """
CUDA PARALLEL PROGRAMMING: parallel_numba.py
* Purpose: Python code for performing matrix operations on the GPU using Numba CUDA.JIT
* @author <NAME>
* @version 1.0 15/10/18
"""
import numpy as np
from numba import cuda
NUM_THREADS = 32
def get_cuda_execution_config(m, n):
""" Calculates the execution conf... | StarcoderdataPython |
12861982 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('group', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('commun... | StarcoderdataPython |
11349456 | <filename>flask/ytegg/ytegg/app.py<gh_stars>0
import os, click, sqlite3
from flask import Flask, g, redirect, url_for
from .config import DefaultConfig
from .model import db, User
from .todo import todo
from .user import user
from . import model
__all__ = ['create_app']
def create_app(config=None, app_name=None):
... | StarcoderdataPython |
9742477 | # SPDX-FileCopyrightText: 2021 Genome Research Ltd.
#
# SPDX-License-Identifier: MIT
from main.service import SpeciesService
from main.swagger import SpeciesSwagger
from .base import BaseResource, setup_resource
api_species = SpeciesSwagger.api
@setup_resource
class SpeciesResource(BaseResource):
class Meta:
... | StarcoderdataPython |
11379066 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Used to access API for retrieving information about competitions.
from .get import get_competitions # noqa: F401
from .competition import Competition # noqa: F401
from .standing import CompetitionStanding ... | StarcoderdataPython |
295906 | # coding=utf-8
import logging
import sys
import traceback
from collections import OrderedDict
from datetime import datetime
from queue import Empty
from queue import Queue
from threading import Thread
from mongoengine import fields
from zspider.confs.conf import INNER_IP
from zspider.confs.conf import LOG_DATEFORMAT
... | StarcoderdataPython |
31872 | <gh_stars>0
from . import views
from django.contrib.auth import views as auth_views
from django.urls import path
urlpatterns = [ #Kari CSV_TO_TABLE Commit
path('csv_upload/', views.csv_table, name='csv_table'),
path('today/', views.today_table, name='today_table'),
path('search/', views.search, name='se... | StarcoderdataPython |
248529 | <reponame>AminAliH47/PicoStyle<filename>account/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from account.models import User
UserAdmin.fieldsets += ('Seller', {'fields': (
'is_seller', 'company_name', 'co_address', 'co_country_registered', 'co_website_address', 'co_ema... | StarcoderdataPython |
5055712 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
import constants
remote_repository_id_list = []
def app_url(content):
"""
Generate APPLICATION_URL from ENV VAR.
"""
url = os.environ['APPLICATION_URL']
return content.replace('$APP_URL', url)
def repository_group(content):
"""... | StarcoderdataPython |
9693163 | # SPDX-FileCopyrightText: Copyright (c) 2021 <NAME>
#
# SPDX-License-Identifier: MIT
# The MIT License (MIT)
#
# Copyright (c) 2019 <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 w... | StarcoderdataPython |
8010961 | <reponame>snasiriany/parasol<filename>parasol/control/mpc.py
import tqdm
import numpy as np
from .common import Controller
import parasol.util as util
import scipy.stats as st
class MPC(Controller):
control_type = 'mpc'
def __init__(self, model, env, horizon,
diag_cost=False,
... | StarcoderdataPython |
4892111 | <filename>src/onnx2ks/onnx-build-prelude.py
#
# onnx-build-prelude - Convert ONNX Schemas to Knossos prelude
#
# References:
# https://github.com/onnx/onnx/blob/master/docs/IR.md
# https://github.com/onnx/onnx/blob/72b701f7a55cafa4b8ab66a21dc22da0905b2f4c/onnx/onnx.in.proto
#
# This is largely a run-once script. Its m... | StarcoderdataPython |
6649489 | """
Defines ``FIPS_TO_STATE``, ``STATE_ABBR``, ``OFFICE_NAMES`` and ``PARTY_NAMES``
look-up constants.
"""
FIPS_TO_STATE = {
'CT': {
'09001': 'FAIRFIELD',
'09003': 'HARTFORD',
'09005': 'LITCHFIELD',
'09007': 'MIDDLESEX',
'09009': 'NEW HAVEN',
'09011': 'NEW LONDON',
... | StarcoderdataPython |
6535052 |
import warnings
from pydiatra.checks import check_source
from .base import PythonTool, Issue, AccessIssue
class PyDiatraIssue(Issue):
tool = 'pydiatra'
class PyDiatraTool(PythonTool):
"""
pydiatra is yet another static checker for Python code.
"""
@classmethod
def get_all_codes(cls):
... | StarcoderdataPython |
193159 | #!/usr/bin/env python
__all__ = ['tumblr_download']
from ..common import *
import re
def tumblr_download(url, output_dir = '.', merge = True, info_only = False):
html = get_html(url)
html = parse.unquote(html).replace('\/', '/')
title = unescape_html(r1(r'<meta property="og:title" content="([^"]*)"... | StarcoderdataPython |
168725 | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describ... | StarcoderdataPython |
3473146 | <reponame>jonathan-winn-geo/cmatools
"""Tests for io_common module."""
import os
from unittest.mock import patch
import pytest
from cmatools.definitions import ROOT_DIR
from cmatools.io.io_common import check_access, return_datadir_root_dir
# extract_archive_singlefile,; return_datadir_inputs_dir,; write_source_con... | StarcoderdataPython |
11210218 | import logging
import os
from typing import Tuple, Optional, List, Dict
import requests
from requests import Response
from swift_cloud_py.authentication.authentication import authenticate
from swift_cloud_py.common.errors import UnauthorizedException, BadRequestException, \
UnknownCloudException, SafetyViolation
... | StarcoderdataPython |
6618280 | <gh_stars>0
import re, json
from . import dump
from . import action
class Post:
def __init__(self, ses, data):
try:
if type(data) == str:
data = json.loads(data)
self.ses = ses
self.data = data["node"]
if self.data.get("id"):
self.id = self.data["id"]
else:
self.id = ""
... | StarcoderdataPython |
12852500 | <filename>pyaccords/pysrc/ec2instanceinfo.py
##############################################################################
#copyright 2013, <NAME> (<EMAIL>) Prologue #
#Licensed under the Apache License, Version 2.0 (the "License"); #
#you may not use this file except in compliance with the Lic... | StarcoderdataPython |
5129436 | """Convolutional LSTM
针对Time × 240min x 58fac 量价数据封装类,
并参考GoogLeNet对inputs使用两层1D卷积核降维
猫狗大战 <EMAIL>
2017-11-30
"""
import numpy as np
import tensorflow as tf
# import sonnet as snt
from sonnet.python.modules.rnn_core import RNNCore as sntRNNCore
from sonnet.python.modules.conv import Conv2D as sntConv2D
from params im... | StarcoderdataPython |
1685207 | <filename>tests/acceptance/test_invalid_schema_files.py
def test_checker_non_json_schemafile(run_line, tmp_path):
foo = tmp_path / "foo.json"
bar = tmp_path / "bar.json"
foo.write_text("{")
bar.write_text("{}")
res = run_line(["check-jsonschema", "--schemafile", str(foo), str(bar)])
assert res.... | StarcoderdataPython |
9685483 | <reponame>lol768/eu2019model<gh_stars>0
# -*- coding: utf-8 -*-
"""Top-level package for eu2019model."""
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '1.0.0'
| StarcoderdataPython |
5132445 | # The MIT License (MIT)
# Copyright (c) 2021 by the xcube development team and contributors
#
# 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... | StarcoderdataPython |
6697831 | #!/usr/bin/env python3
import os
import sys
import re
import argparse
# Package use pattern
package_use_re = re.compile('(\w+)::([\*\w]+)')
# Include use pattern
include_use_re = re.compile('`include\s+["<]([\w/\.\d]+)[">]')
# Module instance pattern, assuming parentheses contents removed
module_instance_re = re.co... | StarcoderdataPython |
6507881 | import asyncio
import pathlib
import threading
import aiofiles
import pytest
import requests
from baguette.app import Baguette
from baguette.headers import Headers
from baguette.httpexceptions import NotImplemented
from baguette.middleware import Middleware
from baguette.rendering import render
from baguette.request ... | StarcoderdataPython |
1904623 | import grpc
import time
import echo_pb2
import echo_pb2_grpc
import utils
from concurrent import futures
from datetime import datetime
class Server(object):
def __init__(self, port=5000):
self.port = port
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
echo_pb2_g... | StarcoderdataPython |
12813514 | <reponame>brandon-rhodes/pycon2010-mighty-dictionary
import _dictdraw, sys
d = {'ftp': 21, 'ssh': 22, 'smtp': 25, 'time': 37, 'www': 80}
surface = _dictdraw.draw_dictionary(d, [4])
surface.write_to_png(sys.argv[1])
| StarcoderdataPython |
9710245 | <reponame>tuomas777/tunnistamo<filename>oidc_apis/scopes.py
from django.utils.translation import ugettext_lazy as _
from oidc_provider.lib.claims import ScopeClaims, StandardScopeClaims
from .models import ApiScope
from .utils import combine_uniquely
class ApiScopeClaims(ScopeClaims):
@classmethod
def get_sc... | StarcoderdataPython |
6535242 | # Copyright (c) 2021 tapiocode
# https://github.com/tapiocode
# MIT License
import micropython
from led_array import led_array
from machine import Timer
micropython.alloc_emergency_exception_buf(100)
sequences = [
'sweeper',
'linear',
[4, 5, 3, 6, 2, 7, 1, 8, 0, 9, -1, -1, -1, -1, -1, -1], # Burst out fro... | StarcoderdataPython |
6665183 | import io
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.models as models
from PIL import Image
from flask import Flask, request, send_from_directory
from flask_cors import CORS
from functools import reduce
with open('detail... | StarcoderdataPython |
1908614 | <filename>tests/test_fastq.py
from .minimal import minimal
from hypothesis import errors, given
import pytest
from hypothesis_bio.hypothesis_bio import fastq, fastq_quality, MAX_ASCII
def test_fastq_quality_smallest_example():
actual = minimal(fastq_quality())
expected = ""
assert actual == expected
de... | StarcoderdataPython |
6450237 | <filename>docx_output.py
# -*- coding: utf-8 -*-
import codecs
import MySQLdb
import parse_html
import sys
from docx import Document
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
from docx.shared import RGBColor
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared im... | StarcoderdataPython |
5051517 | <filename>src/25.py
"""
1000-digit Fibonacci number
The Fibonacci sequence is defined by the recurrence relation:
F_n = F_n−1 + F_n−2, where F_1 = 1 and F_2 = 1.
Hence the first 12 terms will be:
F_1 = 1
F_2 = 1
F_3 = 2
F_4 = 3
F_5 = 5
F_6 = 8
F_7 = 13
F_8 = 21
F_9 = 34
F_10 = 55
F_11 = 89
F_12 = 144
The 12th term, ... | StarcoderdataPython |
9700576 | <reponame>AravinthPanch/code-snippets<gh_stars>1-10
__author__ = '<NAME>'
__email__ = "<EMAIL>"
__date__ = '22/04/15'
import matplotlib.pyplot as plt
if __name__ == '__main__':
print "In"
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show() | StarcoderdataPython |
6627223 | <filename>Cas_1/Kinetic Energy/A_Kinetic_energy.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import xgcm
import cartopy.crs as ccrs
from xmitgcm import open_mdsdataset
from matplotlib.mlab import bivariate_normal
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITU... | StarcoderdataPython |
7698 | <reponame>LukoninDmitryPy/agro_site-2<filename>agro_site/orders/migrations/0001_initial.py
# Generated by Django 2.2.16 on 2022-04-12 13:28
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.expressions
import django.utils.timezone
class... | StarcoderdataPython |
1951088 | #!/usr/bin/env python3
import argparse
import sys
def xor(data, key):
res = b''
for i in range(len(data)):
curr_key = ord(key[i % len(key)])
res += bytes(chr(data[i] ^ curr_key), 'latin-1')
if i == len(data) - 1:
res += b'\0'
return res
def print_output(ciphertext, pad... | StarcoderdataPython |
6503856 | import io
from unittest import TestCase
import pytest
import vcr
from ohapi.api import (
SettingsError, oauth2_auth_url, oauth2_token_exchange,
get_page, message, delete_file, upload_file, upload_stream)
parameter_defaults = {
'CLIENT_ID_VALID': 'validclientid',
'CLIENT_SECRET_VALID': 'validclientsec... | StarcoderdataPython |
9695673 | <gh_stars>0
"""
Module: 'uasyncio' on esp8266 v1.9.3
"""
# MCU: (sysname='esp8266', nodename='esp8266', release='2.0.0(5a875ba)', version='v1.9.3-8-g63826ac5c on 2017-11-01', machine='ESP module with ESP8266')
# Stubber: 1.1.2 - updated
from typing import Any
DEBUG = 0
class EventLoop:
""""""
def call_at_(s... | StarcoderdataPython |
240034 | <reponame>sky-2002/weaviate-examples<gh_stars>0
import weaviate
import json
import helper
client = weaviate.Client("http://localhost:9999")
client.timeout_config = (10000)
client.schema.delete_all()
schema = {
"classes": [
{
"class": "Podcast",
"properties": [
{
... | StarcoderdataPython |
1971351 | from django.test import LiveServerTestCase
from selenium import webdriver
import unittest
import os
from unittest import skipIf
class BlogTest(LiveServerTestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def tearDown(self):
self.driver.quit()
@skipIf(os.getenv('DJANGO_SET... | StarcoderdataPython |
6447392 | <filename>utils.py<gh_stars>1-10
#coding:UTF-8
from contextlib import contextmanager
import cv2
import time
#捕获当前屏幕并resize成(84*84*1)的灰度图
def resizeBirdrToAtari(observation):
observation = cv2.cvtColor(cv2.resize(observation, (84, 84)), cv2.COLOR_BGR2GRAY)
_, observation = cv2.threshold(observation,1,255,cv2.TH... | StarcoderdataPython |
83216 | from collections import namedtuple
class PackageError(Exception):
"""Exception to be raised when user wants to exit on error."""
class RecipeError(Exception):
"""Exception to be raised when user wants to exit on error."""
class Error(namedtuple('Error', ['file', 'code', 'message'])):
"""Error class cr... | StarcoderdataPython |
3278627 | <filename>tests/dhcpv4/kea_only/config_backend/test_relay.py
"""Kea config backend testing relay."""
import pytest
from dhcp4_scen import get_address, get_rejected
from cb_model import setup_server_for_config_backend_cmds
pytestmark = [pytest.mark.v4,
pytest.mark.v6,
pytest.mark.kea_only... | StarcoderdataPython |
4965812 | <reponame>otimgren/centrex-molecule-trajectories<filename>src/trajectories/beamline_elements/electrostatic_lens.py
import pickle
from abc import ABC, abstractmethod
from dataclasses import dataclass
from os.path import exists
from pathlib import Path
import h5py
import matplotlib.pyplot as plt
import numpy as np
from ... | StarcoderdataPython |
5005391 | <reponame>m4reQ/spyke
import dataclasses
import logging
import typing as t
import functools
from os import path
import numpy as np
import glm
from OpenGL import GL
from spyke.enums import ShaderType
from spyke.exceptions import GraphicsException, SpykeException
from spyke.graphics import gl
_logger = logging.getLogg... | StarcoderdataPython |
4830686 | preco= float(input('Digite o preço $'))
desconto= preco * 0.95
print('O valor do produto após o desconto será de {}'.format(desconto)) | StarcoderdataPython |
9610576 | <gh_stars>100-1000
import datetime
import msgpack
import typing
from . import _serializer
from ... import objects
class Serializer(
_serializer.Serializer,
):
name: str = 'msgpack'
def __init__(
self,
) -> None:
self.msgpack_packer = msgpack.Packer(
autoreset=True,
... | StarcoderdataPython |
5070111 | <reponame>AristodamusAdairs/Agents-and-Environment<gh_stars>1-10
import Random
class Agent(object):
def__init__(self,env):
"""set up the agent"""
self.env=env
def go(self,n):
"""acts for n time steps"""
raise NotImplementedError("go") # abstract method
from display import Displayable
class Environment(Dis... | StarcoderdataPython |
6490644 | <gh_stars>0
import MySQLdb, sys, random
from mysql_passwords import database, user, password
from swisscalc import calculateTop8Threshold
class DeckCursor:
def __init__(self, cur):
self.cur = cur
def __enter__(self):
return self.cur
def __exit__(self, type, value, traceback):
self.cur.close()
class DeckDB:
... | StarcoderdataPython |
248280 | <gh_stars>0
from typing import List, Any
from fastapi import APIRouter, HTTPException
from sqlalchemy.future import select
from starlette import status
from starlette.requests import Request
from models.users import User
from schemas.users import UserCreate, UserDB, UserUpdate, UserOut
from utils.password import pass... | StarcoderdataPython |
1734920 | #
# @lc app=leetcode.cn id=575 lang=python3
#
# [575] 分糖果
#
# https://leetcode-cn.com/problems/distribute-candies/description/
#
# algorithms
# Easy (68.32%)
# Total Accepted: 64K
# Total Submissions: 89.9K
# Testcase Example: '[1,1,2,2,3,3]'
#
#
# 给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹... | StarcoderdataPython |
6444421 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
("wagtailcore", "0002_initial_data"),
)
def forwards(self, orm):
# Adding ... | StarcoderdataPython |
6500609 | <gh_stars>1-10
import copy
import sys
def DFS_directed_recur(G, s, nodes_explored, t, f, leader, current_leader):
#Breadths first search for finding all the nodes connected to s undirected graph, also compute the distance to the s.
#G: the undirected graph, nodes form 1 to N
#s: the starting node
#curr... | StarcoderdataPython |
6671992 | <reponame>zveronics/zveronics-python-server<filename>src/zveronics/server.py
import json
import logging
import socketserver
import struct
import msgpack
log = logging.getLogger(__name__)
def unpack(data):
return msgpack.unpackb(data, raw=False)
def pack(data):
return msgpack.packb(data, use... | StarcoderdataPython |
3336825 | <reponame>UPstartDeveloper/CS-1.3-Core-Data-Structures
#!python
class Node(object):
def __init__(self, data):
"""Initialize this node with the given data."""
self.data = data
self.next = None
def __repr__(self):
"""Return a string representation of this node."""
retur... | StarcoderdataPython |
6642185 | from scholarly_citation_finder.apps.citation.mag.IsiFieldofstudy import IsiFieldofstudy
class ScfjsonSerializer:
'''
Convert a publication to SCF JSON format.
'''
def __init__(self, database):
self.database = database
def serialze(self, publication, citations=None, isi_fieldof... | StarcoderdataPython |
9616722 | from test_plus.test import TestCase
from ..models import Email
from .factories import EmailFactory
from foundation.offices.tests.factories import OfficeFactory
class EmailTest(TestCase):
def setUp(self):
self.obj = EmailFactory(email="<EMAIL>")
def test__str__(self):
self.assertEqual(self.ob... | StarcoderdataPython |
3392513 | <gh_stars>1-10
# coding: utf-8
"""
Jamf Pro API
## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in ... | StarcoderdataPython |
9707209 | <filename>tests/integration/cartography/intel/aws/test_iam.py
import cartography.intel.aws.iam
import cartography.intel.aws.permission_relationships
import tests.data.aws.iam
TEST_ACCOUNT_ID = '000000000000'
TEST_REGION = 'us-east-1'
TEST_UPDATE_TAG = 123456789
def _create_base_account(neo4j_session):
neo4j_sess... | StarcoderdataPython |
8114450 | <gh_stars>0
"""
Première tentative d'implémenter A* pour le projet ASD1-Labyrinthes.
On part d'une grille rectangulaire. Chaque case est un "noeud". Les
déplacements permis sont verticaux et horizontaux par pas de 1, représentant
des "arêtes" avec un coût de 1.
Tout est basé sur une grille rectangulaire.
L'objet de ... | StarcoderdataPython |
6402333 | # Generated by Django 2.1.2 on 2018-11-01 08:00
import autoslug.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.