id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3339453 | # -*- coding: utf-8 -*-
# Library dependancies
import csv
import json
import math
import os
import sys
# Files
MOVIES_INPUT_FILE = 'data/top_10_movies_2006-2015.json'
CENSUS_INPUT_FILE = 'data/census_2014.json'
REPORT_OUTPUT_FILE = 'data/hollywood_census_report.csv'
# Init
races = []
people = []
census = []
hollywoo... | StarcoderdataPython |
11397233 | <reponame>RaspberryPi-Samples/py-my-key<filename>py_my_key/samples/sample_nxppy.py<gh_stars>1-10
import nxppy
import time
mifare = nxppy.Mifare()
# Print card UIDs as they are detected
while True:
try:
uid = mifare.select()
print(uid)
except nxppy.SelectError:
# SelectError is raised i... | StarcoderdataPython |
8009607 | <reponame>LexcaliburR/notebook
import torch
import torch.nn as nn
from torch.onnx import register_custom_op_symbolic
from torch.onnx.symbolic_helper import parse_args
# Define custom symbolic function
@parse_args("v", "v", "f", "i")
def symbolic_foo_forward(g, input1, input2, attr1, attr2):
return g.op("custom_do... | StarcoderdataPython |
8604 | <gh_stars>0
# -*- coding: utf-8 -*-
"""Template Helpers used in workbox"""
import logging
import socket
from datetime import datetime
from markupsafe import Markup
import psutil
import tg
log = logging.getLogger(__name__)
def current_year():
""" Return current year. """
now = datetime.now()
return now.... | StarcoderdataPython |
9662543 | <reponame>KKoga/UniRapidJson
# coding: utf-8
# Copyright (c) 2017 <NAME>
#
# UniRapidJson is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
import uuid
import os
import time
import tempfile
import shutil
import tarfile
import gzip
PROJ_ROOT = os.path.join(os.path.dirname(os.path.ab... | StarcoderdataPython |
3524004 | from Crypto.PublicKey import RSA
from Crypto.Signature import pss
from Crypto.Hash import SHA256
message = None
with open('secret2.txt', 'rb') as f:
message = f.read()
with open('private_key.pem', 'rb') as f:
private_key = RSA.import_key(f.read())
hash = SHA256.new(message)
print(f'hash: {hash.hexdigest()}')
... | StarcoderdataPython |
47115 | import argparse
import os
import cv2
import numpy as np
import torch
from torch import nn
from deepface.backbones.iresnet import iresnet18, iresnet34, iresnet50, iresnet100, iresnet200
from deepface.backbones.mobilefacenet import get_mbf
from deepface.commons import functions
import gdown
url={
'ms1mv3_r50':'https:... | StarcoderdataPython |
214980 | from typing import List, Tuple, Set, Iterable
import itertools
import numpy as np
class GridError(Exception):
"""
Custom Exception for grid validation
"""
pass
def input_grid(grid: List[str] = None) -> List[str]:
"""
Inputting grid and splitting it to list of strings
:param grid: (option... | StarcoderdataPython |
266497 | <reponame>mithi/algorithm-playground
import numpy as np
import plotly.graph_objects as go
# rotate about y, translate in x
def frame_yrotate_xtranslate(theta, x):
theta = np.radians(theta)
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
return np.array([
[cos_theta, 0, sin_theta, x],
[0, 1, 0, 0],... | StarcoderdataPython |
4993917 | from ui import Widget, Text, MuiFont, Display, MotionEvent
| StarcoderdataPython |
215044 | <reponame>EkremBayar/bayar
from typing import TypeVar, Union
import numpy as np
import numpy.typing as npt
T = TypeVar("T", bound=npt.NBitBase)
def add(a: np.floating[T], b: np.integer[T]) -> np.floating[T]:
return a + b
i8: np.int64
i4: np.int32
f8: np.float64
f4: np.float32
reveal_type(add(f8, i8)) # E: nump... | StarcoderdataPython |
5153278 | <reponame>marvincosmo/Python-Curso-em-Video<filename>ex058 - Jogo da adivinhação v2.0.py
""" 58 - Melhore o jogo do desafio 028, onde o computador vai 'pensar' em um número entre 0 e 10. Só que agora o
jogador vai tentar adivinhar até acertar, mostrando, no final, quantos palpites foram necessários para vencer. """
''... | StarcoderdataPython |
6670796 | import logging
import numpy as np
import tqdm
from lwrl.utils.visualizer import Visualizer
import lwrl.utils.logging as L
class Runner:
def __init__(self, agent, env, test_env=None):
self.agent = agent
self.env = env
self.test_env = test_env if test_env is not None else self.env
def... | StarcoderdataPython |
346579 | """Optimize services and applications deployed on Kubernetes with Opsani.
"""
from __future__ import annotations, print_function
import abc
import asyncio
import collections
import contextlib
import copy
import datetime
import decimal
import enum
import functools
import itertools
import json
import operator
import os
... | StarcoderdataPython |
31025 | <gh_stars>0
# @lc app=leetcode id=230 lang=python3
#
# [230] Kth Smallest Element in a BST
#
# https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
#
# algorithms
# Medium (63.45%)
# Likes: 4133
# Dislikes: 90
# Total Accepted: 558.7K
# Total Submissions: 876.8K
# Testcase Example: '[3,1,4,nu... | StarcoderdataPython |
170360 | import tensorflow as tf
slim = tf.contrib.slim
from helper_net.inception_v4 import *
import pickle
import numpy as np
def get_weights():
checkpoint_file = '../checkpoints/inception_v4.ckpt'
sess = tf.Session()
arg_scope = inception_v4_arg_scope()
input_tensor = tf.placeholder(tf.float32, (None, 299, 299, 3))
with... | StarcoderdataPython |
11201220 | # Computational Linear Algebra Ep#2 ex1
# By: <NAME>
import numpy as np
import time
if __name__ == "__main__":
print("A:")
# Generates a random 10x10 upper triangular matrix with values between zero to 100
A = np.array(np.random.randint (0,100,(10,10)))
A1 = np.triu(A)
print(A)
print("A1:")
print(A1)
print("... | StarcoderdataPython |
1717756 | <reponame>liyuanyuan11/Python
bestFriends=["Jerry","Mark","Justin","Jonny","Tom","Marry","Jenny","Daniel","Tony"]
print(bestFriends)
print(bestFriends[0])
bestFriends[0]="Christina"
print(bestFriends)
bestFriends.append("Frozy")
print(bestFriends)
| StarcoderdataPython |
8126350 | from scipy import misc, signal
import mrcfile
import numpy as np
from aspire.utils.numeric import xp
from aspire.utils import ensure
class Micrograph:
def __init__(self, filepath, margin=None, shrink_factor=None, square=False, gauss_filter_size=None, gauss_filter_sigma=None):
self.filepath = filepath
... | StarcoderdataPython |
1838368 | <filename>Python/841.py
from collections import deque
class Solution(object):
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
if not rooms:
return True
openRooms = set([0])
queue = deque(rooms[0])
while... | StarcoderdataPython |
3470941 | from DPjudge import Power
class XtalballPower(Power):
# ----------------------------------------------------------------------
def __init__(self, game, name, type = None):
Power.__init__(self, game, name, type)
# ----------------------------------------------------------------------
def __repr__(self):
text = ... | StarcoderdataPython |
1886999 | <gh_stars>1-10
import socket
from sys import argv
import cv2
import mediapipe as mp
import itertools
import numpy as np
import time
import sys
from multiprocessing import Queue, Process
from queue import Empty
import atexit
from math import ceil
from collections import deque
sys.path.insert(1, './tools')
import holist... | StarcoderdataPython |
1773433 | <reponame>takatsugukosugi/illustration2vec
from abc import ABCMeta, abstractmethod
import numpy as np
class Illustration2VecBase(object):
__metaclass__ = ABCMeta
def __init__(self, net, tags=None, threshold=None):
self.net = net
if tags is not None:
self.tags = np.array(tags)
... | StarcoderdataPython |
6504423 | import os
import cv2
import keras.backend as K
import keras.layers as layers
import numpy as np
from keras import regularizers
from keras.applications import resnet50
from keras.applications.resnet50 import WEIGHTS_PATH_NO_TOP
from keras.initializers import TruncatedNormal
from keras.layers import Input, BatchNormaliz... | StarcoderdataPython |
9627145 | <filename>tests/unit/test_client.py
# Copyright 2014 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
171962 | #crop and resize the image
from PIL import Image
import os
#for image read and save
from skimage import io
from skimage.transform import resize
import time
#scriptDir = os.path.dirname(__file__)
#imagePath = os.path.join(scriptDir, '/home/tirth/Diabetic Retinopathy/TirthSampleTest/126_right.jpeg')
start_time_first = ... | StarcoderdataPython |
6462534 | #!/usr/bin/env python3
# Complete the isBalanced function below.
if __name__ == "__main__":
table = {")":"(", "]":"[", "}":"{"}
for _ in range(int(input())):
stack = []
for x in input():
if stack and table.get(x) == stack[-1]:
stack.pop()
else:
... | StarcoderdataPython |
1952269 | <reponame>yumauri/kings_and_pigs
import pygame
from ..functions import loader
from .animation import Animation
from .animated_entity import AnimatedEntity
# dialogue sprites loader
load_image = loader("kings_and_pigs/data/sprites/13-Dialogue Boxes")
class Dialogue(AnimatedEntity):
def __init__(self, x, y, show,... | StarcoderdataPython |
4802744 | <reponame>jklymak/dolfyn
from setuptools import setup, find_packages
import os
import shutil
# Change this to True if you want to include the tests and test data
# in the distribution.
include_tests = False
try:
# This deals with a bug where the tests aren't excluded due to not
# rebuilding the files in this ... | StarcoderdataPython |
11256496 | begin_unit
comment|'# Copyright 2010-2011 OpenStack Foundation'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\... | StarcoderdataPython |
1638100 | <gh_stars>1-10
# TODO : Clean var ; rem cache
import query_retreive as qr
import retreiveData as rd
import time,pickle
from flask import Flask, jsonify,request
app = Flask(__name__)
'''
ADD TEMPLATE :
'''
@app.route('/',methods=["GET"])
def query():
previous = ""
file = open("./aipc.pickle","rb")
pla... | StarcoderdataPython |
6628434 | <gh_stars>1-10
temperatura = int(input('informe a temperatura em graus celcius:'))
converssão = (temperatura*9/5)+32
print('A temperatura em graus celcius é de {}C \nApós de ser convertida para fharenheit fica {}F'.format(temperatura, converssão))
| StarcoderdataPython |
11258316 | #!BPY
"""
Name: 'Newton Alchemedia Format (.xml)'
Blender: 243
Group: 'Import'
Tooltip: 'Import from a Newton Alchemedia file format (.xml).'
"""
# --------------------------------------------------------------------------
# Licence
# Created: 20/08/2010
# Copyright: Copyright (c) <2010> <Newton Game Dynamics... | StarcoderdataPython |
3324819 | <filename>plasma-2040/lightAll96LEDsOnStrip.py
import plasma
from plasma import plasma2040
NUM_LEDS = 96
led_strip = plasma.WS2812(NUM_LEDS, 0, 0, plasma2040.DAT)
led_strip.start()
for i in range(NUM_LEDS):
led_strip.set_rgb(i, 127, 0, 0) | StarcoderdataPython |
12851508 | def fac(n):
if n in [0, 1]:
return 1
else:
return n * fac(n-1)
def sum_of_the_factorial_of_their_digits(n):
fac_of_the_digits = [fac_dic[int(x)] for x in str(n)]
return sum(fac_of_the_digits)
def main():
for n in range(10, 2540161):
if n == sum_of_the_fac... | StarcoderdataPython |
9783554 | azure_credentials_schema = {
"$id": "http://azure-ml.com/schemas/azure_credentials.json",
"$schema": "http://json-schema.org/schema",
"title": "azure_credentials",
"description": "JSON specification for your azure credentials",
"type": "object",
"required": ["clientId", "clientSecret", "subscrip... | StarcoderdataPython |
1777314 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | StarcoderdataPython |
3593461 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 16:20:44 2019
@author: joscelynec
"""
import math #Needed for distance formula
import heapq #Needed for Priority Queue
"""
Class used to encapsulate a graph node for use in
the Priority Queue
"""
class graph_node:
def __init... | StarcoderdataPython |
1848611 | <gh_stars>1-10
#!/usr/bin/env python3
# chip_list.py
#
import logging
import os
from pathlib import Path
import yaml
from . import chip
log = logging.getLogger(__name__)
class ChipList:
_chip_list = {}
_global_name_dict = {}
def __init__(self):
log.debug('ChipList.__init__()')
self.clear(... | StarcoderdataPython |
139116 | <filename>openmdao/devtools/docs_experiment/experimental_source/core/experimental_driver.py
"""Define a base class for all Drivers in OpenMDAO."""
from collections import OrderedDict
import warnings
import numpy as np
from openmdao.recorders.recording_manager import RecordingManager
from openmdao.recorders.recording_... | StarcoderdataPython |
3351788 | <gh_stars>0
#!/usr/bin/env python3
# Problem 14: Longest Collatz sequence
# https://projecteuler.net/problem=14
import sys
def euler014(bound):
best_start = 0
best_length = 0
for start in range(1, bound):
number = start
length = 0
while number != 1:
number = number // ... | StarcoderdataPython |
1715407 | <gh_stars>10-100
"""CB58 encode or decode FILE, or standard input, to standard output.
"""
import argparse
import sys
from . import __version__, cb58decode, cb58encode
EPILOG = """
CB58 is a base-58 encoding with a 32-bit checksum, used on the AVA network.
It's similar to base58check.
"""
def main(argv=None):
... | StarcoderdataPython |
8109782 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import logging
import torch
from torch import nn
from ...layers import TextEncoder
from ...layers import PWEmbeddingOutputDecoder
from ...utils.misc import get_n_params
from ...vocabulary import Vocabulary
from ...utils.topology import Topology
from ...utils.ml_metrics import Lo... | StarcoderdataPython |
4875588 | from twisted.internet import reactor, protocol
from twisted.protocols import basic
from World.Lib.telcodes import RED, NEWLINE, BLUE, RESET
import dircache, md5
import World
from World import WORLD
NOSTATE = 0
LOGIN = 1
PASSWORD = 2
NEWLOGIN = 3
NEWPASSWORD = 4
GAME = 5
INTRO = open("./Text/Intro.txt", ... | StarcoderdataPython |
5188759 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `openclsim` package."""
import pytest
import simpy
import shapely.geometry
import logging
import datetime
import time
import numpy as np
from click.testing import CliRunner
from openclsim import core
from openclsim import model
from openclsim import cli
lo... | StarcoderdataPython |
5065062 | #!/usr/bin/env python3
import os
import logging
import time
import requests
from .nitro import NitroClient
from .frrouting import FrroutingClient
logger = logging.getLogger(__name__)
class SyncService():
def __init__(self, url, username, password, nexthop):
self.frr_client = FrroutingClient()
self.nitro_cl... | StarcoderdataPython |
1733556 | from django.db import models
class Tweet(models.Model):
content = models.TextField(blank= True,null=True)
image = models.FileField(upload_to= 'images/', blank= True,null=True)
| StarcoderdataPython |
6580108 | <gh_stars>100-1000
# Python program to demonstrate Basic Euclidean Algorithm
# Function to return gcd of a and b
def gcd(a, b):
if a == 0 :
return b
return gcd(b%a, a)
# example with 2 numbers which could be taken as input also
a = 10
b = 15
print(gcd(a, b))
| StarcoderdataPython |
3374151 | import math
import random
import geomstats.backend as gs
from geomstats.geometry.spd_matrices import SPDMatrices
from tests.data_generation import _OpenSetTestData, _RiemannianMetricTestData
SQRT_2 = math.sqrt(2.0)
LN_2 = math.log(2.0)
EXP_1 = math.exp(1.0)
EXP_2 = math.exp(2.0)
SINH_1 = math.sinh(1.0)
class SPDMat... | StarcoderdataPython |
5000611 | <reponame>lodino/Camera-Feature-Extraction
import glob
def load_img_from_dir(dir_path: str, f: str) -> [str]:
if dir_path == '':
return glob.glob('*')
else:
if dir_path[-1] != '/':
dir_path += '/'
return list(glob.glob(dir_path + '*.' + f))
| StarcoderdataPython |
3206717 | def main():
try:
option = 0
while (option != 4):
print()
print("1 - Divide by zero")
print("2 - Open a nonexistent file")
print("3 - Bad list index")
print("4 - Quit")
print()
op... | StarcoderdataPython |
6440184 | import requests
import pandas as pd
#data = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&outputsize=full&apikey=demo').json()
data = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=AAPL&outputsize=full&apikey=<KEY>').json()
df = pd.D... | StarcoderdataPython |
5180201 |
"""
Methods and heuristics used to build the bitcoin user network graph from transactions list
"""
from .graph_database_driver import GraphDatabaseDriver
class UserNetwork:
""" Process transactions and populate the GraphDatabaseDriver with addresses and their relations
"""
def __init__(self):
s... | StarcoderdataPython |
6404291 | <reponame>diofeher/ctf-writeups
def solution(A, B, K):
if A % K == 0:
return (B - A) // K + 1
else:
return (B - (A - A % K )) // K | StarcoderdataPython |
4806894 | <reponame>wittawatj/kernel-mod
"""
Utility functions specific for experiments. These functions are less general
than the ones in kmod.util.
"""
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import kmod.util as util
import numpy as np
from scipy import linalg
from sklearn.me... | StarcoderdataPython |
3529524 | #!/usr/bin/env python
'''
Copyright (c) 2019, Robot Control and Pattern Recognition Group, Warsaw University of Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions... | StarcoderdataPython |
5141971 | # coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | StarcoderdataPython |
4862119 | <filename>infoqscraper/__init__.py<gh_stars>10-100
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, <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:
# * Redistributions of source code must r... | StarcoderdataPython |
3321184 | <reponame>rnui2k/vivisect
from ctypes import *
from ctypes import util
iokit = cdll.LoadLibrary(util.find_library('IOKit'))
cf = cdll.LoadLibrary(util.find_library('CoreFoundation'))
cf.CFStringCreateWithCString.argtypes = [c_void_p, c_char_p, c_int32]
cf.CFStringCreateWithCString.restype = c_void_p
cf.CFStringGetC... | StarcoderdataPython |
1890760 | # -*- coding: utf-8 -*-
"""
Numpy and Scipy script files that are common to both Keras+TF and PyTorch
"""
import numpy as np
import re
from scipy.spatial.distance import cdist
import torch
from torch.optim import Optimizer
__all__ = ['classes', 'eps', 'parse_name', 'rotation_matrix', 'get_gamma', 'get_accuracy']
# ... | StarcoderdataPython |
1952783 | import traceback
from typing import Any
from dotenv import find_dotenv, load_dotenv
from fastapi import FastAPI
from pydantic.fields import ModelField
from starlette.responses import PlainTextResponse
import main_dramatiq # type: ignore
load_dotenv(find_dotenv(".env"), verbose=True)
def create_app():
from trai... | StarcoderdataPython |
70049 | # Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | StarcoderdataPython |
20244 | <reponame>cloudify-cosmo/cloudify-manager-blueprints
#!/usr/bin/env python
from os.path import join, dirname
from cloudify import ctx
ctx.download_resource(
join('components', 'utils.py'),
join(dirname(__file__), 'utils.py'))
import utils # NOQA
# Most images already ship with the following packages:
#
# ... | StarcoderdataPython |
5157005 | <gh_stars>10-100
from flask import Flask
from .root import root
from .maskmap import maskmap
from .indonesia import indonesia
def register_route(app: Flask):
app.register_blueprint(root, url_prefix='/')
app.register_blueprint(maskmap, url_prefix='/maskmap')
app.register_blueprint(indonesia, url_prefix='/i... | StarcoderdataPython |
5063083 | """Implementations for metadata analysis are kept here."""
| StarcoderdataPython |
4822491 | <reponame>yup8j/ScholarPaperManagement
from backend.resources import *
from backend.handlers.InfoHandler import *
from flask_jwt_extended import jwt_required, get_jwt_identity
class GetInfo(API):
@jwt_required
def post(self):
"""
:return:
"""
''' 用户鉴权:获得userid '''
requ... | StarcoderdataPython |
3589186 | <filename>CameraLib/cameraPi.py
import io
import time
import picamera
from picamera.array import PiRGBArray
from .baseCamera import BaseCamera
from IotLib.log import Log
class Camera(BaseCamera):
width = 1280
height = 720
def __init__(self, width=1280, height=720, crosshair=False):
""" initialize ... | StarcoderdataPython |
12837444 | import numpy as np
import reciprocalspaceship as rs
import tensorflow as tf
from tensorflow import keras as tfk
from IPython import embed
class SelfAttentionBlock(tfk.layers.Layer):
def __init__(self, attention_dims, num_heads, ff_dims=None):
super().__init__()
attention_dims = attention_dims
... | StarcoderdataPython |
13422 | <filename>core/gf/test.py
import pytest
import server
@pytest.fixture(scope="session")
def authorship_grammar():
with open("test_grammars/Authorship.gf", "r") as f:
abstract = {"content": f.read()}
with open("test_grammars/AuthorshipEng.gf", "r") as f:
inst = {"content": f.read(), "key": "Eng"... | StarcoderdataPython |
4908689 | <gh_stars>0
from model.utils import *
from model.DL_ClassifierModel import *
dataClass = DataClass('data.txt', validSize=0.2, testSize=0.0, kmers=3)
dataClass.vectorize("char2vec", feaSize=64)
s, f, k, d = 64, 128, 3, 64
model = TextClassifier_SPPCNN(classNum=5, embedding=dataClass.vector['embedding'], SPPSize=s, feaS... | StarcoderdataPython |
9606980 | '''
Author : <NAME>
Codeforces ID : Kazi_Amit_Hasan
Problem: Codeforces 71A (Way Too long words)
'''
class WayTooLongWords:
def solve(self, strInputs):
strOutputs = list()
for line in strInputs:
if (len(line) > 10):
line = line[0] + str(len(line) - 2) + line[-1]
... | StarcoderdataPython |
3555985 | from PreprocessData.all_class_files.Intangible import Intangible
import global_data
class Brand(Intangible):
def __init__(self, additionalType=None, alternateName=None, description=None, disambiguatingDescription=None, identifier=None, image=None, mainEntityOfPage=None, name=None, potentialAction=None, sameA... | StarcoderdataPython |
190037 | <reponame>joshlyman/Josh-LeetCode
# refer from:
# https://leetcode.com/problems/flatten-binary-tree-to-linked-list/solution/
# 2. Iterative Morris traversal
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
... | StarcoderdataPython |
1873327 | """
Stage class designed to be inherited by PISA Pi services, such that all basic
functionality is built-in.
"""
from __future__ import absolute_import, division
from collections import OrderedDict
from numba import SmartArray
from pisa.core.base_stage import BaseStage
from pisa.core.binning import MultiDimBinning
... | StarcoderdataPython |
109209 | from app import jwt, app
from werkzeug.exceptions import HTTPException
# 处理全局未授权错误
@jwt.unauthorized_loader
def handle_unauthorized_error(e):
res = { "code": 401, "msg": str(e) }
return res
@app.errorhandler(Exception)
def handle_error(e):
code = 500
msg = str(e)
if isinstance(e, HTTPException):
... | StarcoderdataPython |
9767792 | <reponame>wjsi/mars<filename>mars/core/entity/__init__.py
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licen... | StarcoderdataPython |
11252654 | """
Abstract base class and subclasses for producing different embeddings from
standard computer vision models
"""
import tensorflow as tf
import numpy as np
from abc import ABC, abstractmethod
class Predictor(object):
def __init__(self, args):
self.batch_size = args.batch_size
self.model = self.... | StarcoderdataPython |
4945279 | from typing import Dict
from typing import List
from botocore.paginate import Paginator
class GetOfferingStatus(Paginator):
def paginate(self, PaginationConfig: Dict = None) -> Dict:
pass
class ListArtifacts(Paginator):
def paginate(self, arn: str, type: str, PaginationConfig: Dict = None) -> Dict:
... | StarcoderdataPython |
1852880 | <gh_stars>1000+
"""!
@brief Unit-tests for Oscillatory Neural Network based on Kuramoto model.
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
import unittest;
# Generate images without having a window appear.
import matplotlib;
matplotlib.use('Agg');
from pyclustering.nnet.t... | StarcoderdataPython |
11216838 | #Exercício Python 15:
# Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de #dias
# pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 #por Km rodado.
print('------------------------------')
print(' LOCADORA D... | StarcoderdataPython |
6428625 | <reponame>mltony/nestts
import copy
import numbers
import sys
import topology
from topology import ValidationError
import util
from variable import Variable
class TopologyError(Exception):
'''Topology error. Might indicate that there is a loop in the network.'''
pass
class Connection:
'''Represents a con... | StarcoderdataPython |
3483149 | import sys
import numpy as np
from .skeleton import Skeleton, Bone
from . import posquat as pq
fbxsdkpath = r'D:\Software\fbx_python37_x64'
if fbxsdkpath not in sys.path:
sys.path.append(fbxsdkpath)
import FbxCommon as fb
import fbx
def find_mesh_node(pScene):
def _get_mesh(pNode):
if isinstance(pNo... | StarcoderdataPython |
88818 | <reponame>mlewis1973/pyosirix
# test_dictionary.py
"""Test suite for dicom_dictionary.py"""
# Copyright (c) 2008 <NAME>
# This file is part of pydicom, released under a modified MIT license.
# See the file license.txt included with this distribution, also
# available at http://pydicom.googlecode.com
import unitt... | StarcoderdataPython |
3348315 | # md5 : 7cf8d5549f3c4b0a7870d0e515a9c033
# sha1 : 2be54bd63ab58118a845ed5fd57ad35ee54301b4
# sha256 : b3094ce056324c5d330849d020e0c3a2e4a7359b17434be3ae13e0f8354ce14d
ord_names = {
1: b'OleUIAddVerbMenuA',
2: b'OleUICanConvertOrActivateAs',
3: b'OleUIInsertObjectA',
4: b'OleUIPasteSpecialA',
5: b'O... | StarcoderdataPython |
4887067 | <filename>trustMonitor/trust_monitor/verifier/ra_verifier.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ra_verifier.py: execute the integrity analyses
#
# Copyright (C) 2014 Politecnico di Torino, Italy
# TORSEC group -- http://security.polito.it
#
# Author: <NAME> <<EMAIL>>
#
# This library is... | StarcoderdataPython |
1792881 | <reponame>Decathlon/decavision<filename>decavision/utils/data_utils.py
import os
from random import shuffle
import sys
import tarfile
import urllib.request
import zipfile
import numpy as np
import PIL
from PIL import Image
import tensorflow as tf
def prepare_image(image_path, target_size, rescaling=255):
"""
... | StarcoderdataPython |
120729 | """
OpenVINO DL Workbench
Interfaces class for error processing classes
Copyright (c) 2018 Intel Corporation
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/licens... | StarcoderdataPython |
1901771 | name = "langsci"
#__all__ = ['asciify', 'assignproofreaders', 'autoindex', 'bibnouns',
#'delatex', 'doc2tex', 'extractaw','fixindex','langscibibtex','normalizebib','sanitycheck','sanitygit','zenodo']
| StarcoderdataPython |
3402861 | """Entire flask app."""
from datetime import datetime
from flask import Flask, jsonify, request, Response
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPTokenAuth
from functools import wraps
import json
import os
from passlib.hash import pbkdf2_sha256 as hasher
app = Flask(__name__)
app.config... | StarcoderdataPython |
54155 | # Multiple Comparisons
# the way vs. the better way
# simplify chained comparison
# <NAME>
# <NAME> day of 2020
time_of_the_day = 6
day_of_the_week = 'mon'
# this way
if time_of_the_day < 12 and time_of_the_day > 6:
print('Good morning')
# a better way
if 6 < time_of_the_day < 12:
print('Good morning')
# this w... | StarcoderdataPython |
6500984 | import statistics
from colors import Colors
from shared.utils import Utils
class Informer():
def __init__(self, averageTimes):
self.times = averageTimes
"""
Preliminar report with overall data
"""
def print_response_times_data(self, times):
# TODO: implement full report with enhanc... | StarcoderdataPython |
5058506 | # Copyright 2018 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | StarcoderdataPython |
179932 | # -*- coding: utf-8 -*-
# Authors: <NAME> <<EMAIL>>
import unittest
from .. import SingleElementinaSortedArray
class test_SingleElementinaSortedArray(unittest.TestCase):
solution = SingleElementinaSortedArray.Solution()
def test_singleNonDuplicate(self):
self.assertEqual(self.solution.singleNonDup... | StarcoderdataPython |
11359410 | <gh_stars>10-100
""" Command line interface for working with cached data for YATSM algorithms
"""
import fnmatch
import logging
import os
import time
import click
from . import options
from .. import io
from ..cache import (get_line_cache_name, get_line_cache_pattern,
update_cache_file, write_cac... | StarcoderdataPython |
4981884 | <gh_stars>0
import numpy as np
import time
current_dir = 0 #0 = up , 1 = down ||, 2 = left , 3 = right
orientation = 0
def horizontal_move(direction):
if(direction == 'left'):
current_dir = 2
print 'moving left' + str(current_dir)
time.sleep(2)
elif(direction == 'right'):
cur... | StarcoderdataPython |
3588320 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
from pathlib import Path
from itertools import islice
class My_dict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
class Df():
def __init__(self, raw_data_location):
... | StarcoderdataPython |
6518660 | <filename>examples/recsys/multivae.py
# flake8: noqa
from typing import Dict, List
import torch
from torch import nn, optim
from torch.nn import functional as F
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import DataLoader
from catalyst import dl, metrics
from catalyst.contrib.datasets import Mo... | StarcoderdataPython |
6625417 | from __future__ import absolute_import
import logging
import threading
from galaxy.web.stack import register_postfork_function
from .sleeper import Sleeper
log = logging.getLogger(__name__)
DEFAULT_MONITOR_THREAD_JOIN_TIMEOUT = 5
class Monitors(object):
def _init_monitor_thread(self, name, target_name=None, ... | StarcoderdataPython |
168138 | <reponame>splumb/PuTTY
import sys
import numbers
import itertools
assert sys.version_info[:2] >= (3,0), "This is Python 3 code"
from numbertheory import *
class AffinePoint(object):
"""Base class for points on an elliptic curve."""
def __init__(self, curve, *args):
self.curve = curve
if len(... | StarcoderdataPython |
5127245 | <filename>chalk/__init__.py
import math
from functools import reduce
from typing import Iterable, List, Tuple, Optional
try:
from importlib import metadata
except ImportError: # for Python<3.8
import importlib_metadata as metadata # type: ignore
from chalk.core import Diagram, Empty, Primitive
from chalk.s... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.