id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
376260 | <filename>newsletter/models.py
from django.db import models
from model_utils.models import TimeStampedModel
class Signup(TimeStampedModel):
email = models.EmailField()
def __str__(self):
return self.email
| StarcoderdataPython |
6584827 | import socket
from math import sqrt, inf
serversocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
listOfGasStations = []
idDataMsg = 0
class Fuel:
def __init__(self, fuelType, fuelPrice):
self.fuelType = fuelType
self.fuelPrice = int(fuelPrice)
def __str__(self):
re... | StarcoderdataPython |
6584299 | # Generated by Django 3.2.1 on 2021-05-05 15:31
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('PersonalApp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='about_model',
... | StarcoderdataPython |
5094432 | """
Basic building blocks of nnpackage models. Contains various basic and specialized network layers, layers for
cutoff functions, as well as several auxiliary layers and functions.
"""
from nnpackage.nn.acsf import *
from nnpackage.nn.activations import *
from nnpackage.nn.base import *
from nnpackag... | StarcoderdataPython |
1621442 | <filename>challenges/array_binary_search/array_binary_search.py<gh_stars>0
def binarySearch(list, int):
for i in range( 0, len(list), 1) :
if list[i] == int:
return i
return -1
print(binarySearch([4,8,15,16,23,42], 15))
| StarcoderdataPython |
1687341 | <filename>util/nputils.py<gh_stars>1-10
#!/usr/bin/env python3
import numpy as np
def nan_like(array):
tmp = np.empty_like(array)
tmp.fill(np.nan)
return tmp
def no_op() -> None:
# The no-op function; it should obviously be empty!
pass
if __name__ == "__main__":
no_op()
| StarcoderdataPython |
6545141 | # Import necessary packages
from image_text_model.im_text_rnn_model import oasis_evaluation
checkpoint_dir = 'image_text_model/deep_sentiment_model'
scores = oasis_evaluation(checkpoint_dir)
# Save output and parameters to text file in the localhost node, which is where the computation is performed.
#with open('/data... | StarcoderdataPython |
398295 | <reponame>ganler/LEMON
# -*-coding:UTF-8-*-
"""get prediction for each backend
"""
import sys
import os
import redis
import pickle
import argparse
import configparser
from scripts.tools.utils import DataUtils
from scripts.logger.lemon_logger import Logger
import warnings
main_logger = Logger()
def custom_objects():
... | StarcoderdataPython |
6523666 |
from keras.layers import Concatenate, Input, Lambda, UpSampling2D
from keras.models import Model
from utils.utils import compose
from nets.attention import cbam_block, eca_block, se_block
from nets.CSPdarknet53_tiny import (DarknetConv2D, DarknetConv2D_BN_Leaky,
darknet_body... | StarcoderdataPython |
9688121 | from typing import Any, List, Optional
class Node:
"""Encapsulate the tree of a Python (or JSON) data structure."""
@staticmethod
def is_scalar(value):
"""Return True iff 'value' should be represented by a leaf node."""
return not isinstance(value, (dict, list, tuple, set))
@classmet... | StarcoderdataPython |
5044518 | import tkinter as tk
import time
BASE_BACKGROUND = '#292929'
HEADER_BASE_COLOR = '#F5F5F5'
HEADER_BASE_COLOR = '#F5F5F5'
HEADER_COLOR_PRIMARY = '#1c1c1c'
HEADER_COLOR_SECONDARY = '#8ec63e'
def Header_Menu_Animation(app):
Header_Frame = tk.Frame(app, background = HEADER_BASE_COLOR)
Header_Frame.place(relx=0.0 , re... | StarcoderdataPython |
9732164 | import torch.nn.functional
import typing as _typing
import dgl
from dgl.nn.pytorch.conv import SAGEConv
from .. import base_encoder, encoder_registry
from ... import _utils
class _SAGE(torch.nn.Module):
def __init__(
self, input_dimension: int,
dimensions: _typing.Sequence[int],
... | StarcoderdataPython |
3267807 | #Desenvolva um programa que leia o primeiro termo e a razão de uma PA.
# No final, mostre os 10 primeiros termos dessa progressão.
cores = {'limpa':'\033[m',
'bverde':'\033[1;32m',
'roxo':'\033[35m',
'bvermelho': '\033[1;31m',
'pretoebranco':'\033[7:30m'}
print('-=-'*... | StarcoderdataPython |
1613539 | import requests
from utility import *
from sql.database import DBOperations
from geolocation.iplocation import IPLocation
import json
from flask_caching import Cache
class Report:
"""
This is the class where all weather report is created for a user request.
Attributes:
reque... | StarcoderdataPython |
1892054 | """
This test will initialize the display using displayio
and draw a solid red background
"""
import board
import displayio
from adafruit_st7735r import ST7735R
spi = board.SPI()
tft_cs = board.D5
tft_dc = board.D6
displayio.release_displays()
display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs,... | StarcoderdataPython |
12826307 | <reponame>sethmccauley/cohort4
def divide(divident, divisor):
return divident / divisor | StarcoderdataPython |
4952454 | import numpy as np
a = np.array([[1,1],[1.5,4.0]])
b = np.array([2200,5050])
x = np.linalg.inv(a).dot(b) #analog way to solve a equation
print(x)
p = np.linalg.solve(a,b)
print(p) | StarcoderdataPython |
1677384 | <filename>tensorflow/python/autograph/pyct/cfg.py<gh_stars>1-10
# Copyright 2017 The TensorFlow Authors. 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://ww... | StarcoderdataPython |
134378 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Utilities that are useful for Mephisto-related scripts.
"""
from mephisto.abstractions.databases.local_database impo... | StarcoderdataPython |
1908617 | class Types:
STRING = str
INTEGER = int
FLOAT = float
| StarcoderdataPython |
4911750 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""A module that implements the Trainer class, the main class responsible for
the process of training a neural network.
"""
import sys
import logging
from time import time
import h5py
import numpy
import theano
from theanolm.backend import IncompatibleStateError
from th... | StarcoderdataPython |
153774 | class Fib:
def __init__(self,nn):
print("inicjujemy")
self.__n=nn
self.__i=0
self.__p1=self.__p2=1
def __iter__(self):
print('iter')
return self
def __next__(self):
print('next')
self.__i+=1
if self.__i>self.__n:
... | StarcoderdataPython |
8049106 | """Serializers for venues"""
from rest_framework import serializers
from django_countries.serializers import CountryFieldMixin
from .fields import TimeZoneField
from . import models
class VenueSerializer(CountryFieldMixin, serializers.ModelSerializer):
time_zone = TimeZoneField(
required=False, allow_... | StarcoderdataPython |
3261810 | # To split the given images in dataset into respective Dya & Night Instances.
import numpy as np
from PIL import Image
import glob
BUFFER_SIZE = 400
BATCH_SIZE = 1
IMG_WIDTH = 256
IMG_HEIGHT = 256
counter = 1
for filename in glob.glob("training/*.jpg"):
im = Image.open(filename)
im_arr = np.array(im)
width,... | StarcoderdataPython |
9686266 | import scrapeconfig as cng
import pandas as pd
from get_osebx_html_files import get_htmlfile
from get_yahoo_data import get_keystats
from datawrangle import merge_bors_and_yahoo_dfs
from borsscraper import SCRAPE_OSLOBORS_TITLE
if __name__ == '__main__':
# Obtain HTML pages of Oslo Bors
# print('Ob... | StarcoderdataPython |
5112942 | import load_data as ld
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D, GlobalAveragePooling2D
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
### where is this coming from?
input_shape = (1025,44,2)
(train_datas... | StarcoderdataPython |
9674170 | from .graph_export import export_scenegraph, export_subtree
from .graph_import import import_scenegraph, import_subtree
| StarcoderdataPython |
3438490 | <reponame>Napchat/mineapp
from flask import Blueprint, render_template, abort, g, redirect, url_for, session, request
from jinja2 import TemplateNotFound
from mineapp.forms import NameForm
blue1 = Blueprint('blue1', __name__, template_folder='templates', static_folder='static')
@blue1.before_app_first_request
def bef... | StarcoderdataPython |
373169 | <gh_stars>0
def featureNormalize(X):
import numpy as np
np.asarray(X)
mu=np.ndarray.mean(X,axis=0)
X_norm=X-mu
sigma=np.ndarray.std(X_norm,axis=0)
X_norm=X_norm/sigma
print('the mean is',mu)
print('and sigma is',sigma)
return X_norm
| StarcoderdataPython |
11387825 | <reponame>MartinoMensio/allennlp<gh_stars>10-100
# pylint: disable=no-self-use,invalid-name
import numpy
import pytest
from allennlp.common.checks import ConfigurationError
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data import Token
from allennlp.data.fields import TextField, IndexField
from a... | StarcoderdataPython |
6471640 | '''tests for the registry module'''
import pytest
from lima import exc, schema, registry
@pytest.fixture
def reg():
return registry.Registry()
# mock Schema class to register later on
class Schema:
pass
def test_register1(reg):
'''Test if mock Schema class can be registered without raising.'''
r... | StarcoderdataPython |
1763616 | import unittest
from pyportfolio.models import TradeList
from pyportfolio.trades.load import load
from pyportfolio.utils.testing import get_data_path
class TestImport(unittest.TestCase):
def test_csv(self):
trade_list = load.load_csv(get_data_path() + 'test.csv')
self.assertIsInstance(trade_list, ... | StarcoderdataPython |
8010427 | from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from mainwindow import Ui_MainWindow
from aboutdialog import Ui_aboutDialog
from rpg_tools.PyDiceroll import roll
import sys
die_types = ['D4', 'D6', 'D8', 'D10', 'D12', 'D20', 'D30', 'D66', 'D100']
class aboutDialog(QDialog, Ui_aboutD... | StarcoderdataPython |
1831897 | <reponame>geoffjay/shrt
from django.shortcuts import render
from django.views import View
from django.shortcuts import redirect
from shrt.url.models import Url
class UrlView(View):
"""Redirect view.
Handles a shortened URL by using the redirect shortcut.
"""
def get(self, request, tag):
url ... | StarcoderdataPython |
8160429 | from typing import Any, ClassVar, Dict, Type
import dataclasses
from bidict import bidict
def _compile_node_value(value: Any, **compile_options) -> Any:
if isinstance(value, Node):
return value.compile(**compile_options)
elif isinstance(value, list):
return [_compile_node_value(item, **compil... | StarcoderdataPython |
11347313 | <filename>test/connector/test_google_cloud_connector.py
import unittest
import os
import json
from datetime import datetime, timedelta
from spaceone.tester import TestCase
from spaceone.core.unittest.runner import RichTestRunner
from spaceone.core import config
from spaceone.core.unittest.result import print_data
from ... | StarcoderdataPython |
8081316 | <reponame>ZhangHCFJEA/bbp
#!/usr/bin/env python
"""
CB 08 NGA model
"""
from utils import *
class CB08_nga():
"""
Class of NGA model of Campbell and Bozorgnia 2008
"""
def __init__(self):
"""
Model initialization
"""
# ============
# NGA models (parameters and coefficients)
# ===========... | StarcoderdataPython |
3249572 | <reponame>coxmediagroup/nodemeister
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing M2M table for field groups on 'Group'
db.delete_table('enc_gr... | StarcoderdataPython |
1762442 | # third-party imports
import numpy as np
import logging
# OBSERVATION PREPROCESSING ==================================
def obs_preprocessor_tm_act_in_obs(obs):
"""
This takes the output of gym as input
Therefore the output of the memory must be the same as gym
"""
obs = (obs[0], obs[1], obs[2], ob... | StarcoderdataPython |
111350 | <reponame>antopen/alipay-sdk-python-all<filename>alipay/aop/api/response/AlipayCommerceLogisticsWaybillIstddetailQueryResponse.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayCommerceLogisticsWaybillIstddetailQueryResponse(Ali... | StarcoderdataPython |
4811091 | <reponame>reberhardt7/sofa
import logging
log = logging.getLogger(__name__)
# TODO: ResourceCreated, ResourceUpdated, and ResourceDeleted can be combined
# into one class: ResourceResponse
class ResourceCreated(object):
"""
Usage: return ResourceCreated()
"""
def __init__(self, resource_id, message='Re... | StarcoderdataPython |
11236925 | import urllib
def get_sentence_from_source(source):
# The next two lines are absolutely the most horrible lines I've written in five years!
direct = [{**t, "direct": True} for t in [{k: sentence[k] for k in ('text', 'id', 'lang')} for sentence in source[1]]]
indirect = [{**t, "direct": False} for t in [{k... | StarcoderdataPython |
219844 | # read numbers
numbers = []
with open("nums.txt", "r") as f:
lines = f.readlines()
numbers = [int(i) for i in lines]
print(numbers)
# part 1 soln
for x,el in enumerate(numbers):
for i in range(x+1, len(numbers)):
if el + numbers[i] == 2020:
print("YAY: {} {}".format(el, num... | StarcoderdataPython |
8033908 | <filename>olea/core/blueprints/pit/query.py
from flask import g
from models import Pit, Role
from core.auth import check_opt_duck, check_scopes
from core.base import single_query
from core.errors import AccessDenied
class PitQuery():
@staticmethod
def single(id_):
return single_query(model=Pit,
... | StarcoderdataPython |
173673 | <reponame>dizcza/entropy-estimators<gh_stars>1-10
from .NPEET.npeet.entropy_estimators import mi as npeet_mi
from .NPEET.npeet.entropy_estimators import entropy as npeet_entropy
from .NPEET.npeet.entropy_estimators import entropyd as discrete_entropy
from .NPEET.npeet.entropy_estimators import midd as discrete_mi
from ... | StarcoderdataPython |
11251134 | <gh_stars>0
from flask import Blueprint, render_template, request, redirect, url_for, Response
from app import mongo
from bson import ObjectId
import json
mod_main = Blueprint('main', __name__)
@mod_main.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
name = ["DEA", "DEA1"]... | StarcoderdataPython |
215927 | import os
import json
from io import BytesIO
from localstack.utils import testutil
from localstack.utils.common import *
from localstack.utils.aws import aws_stack
from localstack.services.awslambda import lambda_api
from localstack.services.awslambda.lambda_api import (LAMBDA_RUNTIME_NODEJS,
LAMBDA_RUNTIME_PYTHON2... | StarcoderdataPython |
3476373 | <gh_stars>0
# Copyright (c) 2021 <NAME>. All Rights Reserved.
"""Emmental parsing args unit tests."""
import logging
import shutil
from emmental import Meta, init
from emmental.utils.parse_args import parse_args, parse_args_to_config
logger = logging.getLogger(__name__)
def test_parse_args(caplog):
"""Unit te... | StarcoderdataPython |
381457 | import numpy as np
import pandas as pd
import nltk
nltk.download('punkt') # one time execution
import re
df = pd.read_csv("tennis_articles_v4.csv")
from nltk.tokenize import sent_tokenize
sentences = []
for s in df['article_text']:
sentences.append(sent_tokenize(s))
sentences = [y for x in sentences for y in x] # f... | StarcoderdataPython |
9641410 | <reponame>amihaita/GeekTraine
#Declare and initialize the variables
monthlyPayment = 0
loanAmount = 0
interestRate = 0
numberOfPayments = 0
loanDurationInYears = 0
#Ask the user for the values needed to calculate the monthly payments
strLoanAmount = input("How much money will you borrow? ")
strInterestRate = input("W... | StarcoderdataPython |
4882944 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 01:50:30 2018
@author: msi-pc
"""
import requests
import json
url="https://no13-asrbbe6isgzxtim.search.windows.net/indexes/c5a268aa-e90c-41f0-8a37-967f765b3623/docs?api-version=2017-11-11&search=bottle"
response=requests.get(url)
print(response) | StarcoderdataPython |
3468866 | import logging
import os
import pickle
import threading
from collections import defaultdict
from copy import deepcopy
import yaml
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.error import Unauthorized, ChatMigrated
from telegram.ext import Updater, CommandHandler, PicklePersistence, Ca... | StarcoderdataPython |
3504783 | from datetime import datetime, timezone
from django.db import models, migrations
from django.contrib.postgres.operations import CreateExtension
from django.utils.text import slugify
from django.contrib.gis.db import models as gis_models
class Dataset(models.Model):
name = models.CharField(max_length = 95, blank = ... | StarcoderdataPython |
1916032 | # def prime(num):
# if num < 0:
# return "error negative num given"
# results = []
# for i in range (2, num+1):
# if isPrime(i):
# results.append(i)
# return results
def isPrime(number):
# if number in
for i in range(2, number):
if number % i == 0:
... | StarcoderdataPython |
168964 | import pandas as pd
from re import findall
from sklearn.utils import shuffle
data = pd.read_csv('Trafficking_Data.csv')
urls = data['url'].tolist()
regional_data = []
category_data = []
def extract_region(list_of_urls):
for strings in list_of_urls:
regdata = findall('http://([A-Za-z]+).', strings)[0]
region... | StarcoderdataPython |
3573411 | import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from db.dao import add_user_photo_rec, add_photo_photo_rec
from pprint import pprint
USER_NUMBER = 23259
PHOTO_NUMBER = 8837
TOP_K_NUM = 10
def get_recommend_list_by_itemcf():
header = ['user_id', 'photo_id', 'is_fav']
... | StarcoderdataPython |
12854511 | <reponame>githaefrancis/fluent-exchange
import unittest
from app.models import User,Role,Post,Comment
class CommentModelTest(unittest.TestCase):
def setUp(self):
self.new_user=User(name="<NAME>",username='fgithae',password='password',email="<EMAIL>",role=Role.query.filter_by(id=1).first())
self.new_post=Pos... | StarcoderdataPython |
254535 | <filename>View/forms.py
from .models import Profile,Deals
from django.forms import ModelForm
from django.contrib.auth.models import User
class ProfileForm(ModelForm):
class META:
fields = '__all__'
model= Profile
class UserForm(ModelForm):
class Meta:
model = User
exclude = ['... | StarcoderdataPython |
5199454 | <reponame>loovien/meida-downloader
# -*- coding: utf-8 -*-
# website: https://loovien.github.io
# author: luowen<<EMAIL>>
# time: 2018/9/29 21:41
# desc:
import unittest
from src.tools.title_builder import title_gen
class TitleTest(unittest.TestCase):
def test_title(self):
title = title_gen()
p... | StarcoderdataPython |
8126333 | #!/usr/bin/env python3
import os
import rospy
from lg_mirror.capture_viewport import CaptureViewport
from lg_mirror.utils import get_viewport_image_topic
from interactivespaces_msgs.msg import GenericMessage
from lg_common.helpers import handle_initial_state, required_param
from sensor_msgs.msg import CompressedImage
... | StarcoderdataPython |
56621 | #!/usr/bin/env python
# Scrubs the output of msvc and prints out the dianostics.
#
# The only argument indicates the file containing the input.
#
# This script can produce lots of messages per diagnostic
#
# Copyright (c) 2007-2018 Carnegie Mellon University. All Rights Reserved.
# See COPYRIGHT file for details.
im... | StarcoderdataPython |
3599484 | <gh_stars>1-10
import logging
import faulthandler
CRASHLOGGER_NAME = "APPCRASH"
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, handler):
self.handler = handler
def fileno(self):
return se... | StarcoderdataPython |
3236308 | # =================================================================
#
# Authors: <NAME> <<EMAIL>>
#
# Copyright (c) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# res... | StarcoderdataPython |
3589597 | """
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
di... | StarcoderdataPython |
9769591 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-18 15:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reddit', '0002_auto_20160213_1617'),
]
operations = [
migra... | StarcoderdataPython |
6598149 | <reponame>pycampers/zproc
import multiprocessing
from typing import List, Mapping, Sequence, Any, Callable
import zmq
from zproc import util, serializer
from zproc.consts import DEFAULT_NAMESPACE, EMPTY_MULTIPART
from zproc.server.tools import ping
from .result import SequenceTaskResult, SimpleTaskResult
from .worker... | StarcoderdataPython |
3523556 | <reponame>WorksApplications/omni_torch<gh_stars>1-10
import torch
import torch.nn as nn
import omni_torch.networks.blocks as omth_blocks
class CifarNet_Vanilla(nn.Module):
def __init__(self):
super(CifarNet_Vanilla, self).__init__()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
... | StarcoderdataPython |
1677016 | <reponame>basilmahmood/Wsimple<filename>setup.py<gh_stars>0
from os import path
from setuptools import setup, find_packages
def read(fname):
return open(path.join(path.dirname(__file__), fname)).read()
def from_here(relative_path):
return path.join(path.dirname(__file__), relative_path)
with open('requiremen... | StarcoderdataPython |
5020012 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Editor: <NAME>
School: BUPT
Date: 2018-03-02
算法思想: 交叉字符串
动态规划,dp[i][j]表示s1前i个字符与s2前j个字符能否组成s3前i+j个字符
"""
class Solution:
"""
@param s1: A string
@param s2: A string
@param s3: A string
@return: Determine whether s3 is formed by interleaving of s1 and s2
... | StarcoderdataPython |
22848 | from typing import Callable
class Knapsack:
@staticmethod
def best_value(
capacity: int,
sizes: list,
values: list,
quantities,
min_max: Callable = max,
zero_capacity_value=0,
fill_to_capacity=True,
output_item_list=True
):
if capacit... | StarcoderdataPython |
1600550 | <reponame>yukiar/phrase_alignment_cted
import os, glob, pathlib
from xml.etree import ElementTree
class Node:
def __init__(self, id, tokens, start, end, pidx, cidx_list, pa1, pa2, pa3):
self.id = id # node id, e.g., c0 and t10
self.txt = ' '.join(tokens).strip(' ')
self.tokens = tokens
... | StarcoderdataPython |
6657724 | # pylint: disable=missing-docstring
import unittest
import numpy as np
import tensorflow as tf
import tf_encrypted as tfe
from tf_encrypted.keras.testing_utils import agreement_test, layer_test
np.random.seed(42)
class TestDense(unittest.TestCase):
def setUp(self):
tf.reset_default_graph()
def test_dense... | StarcoderdataPython |
8044175 | """
A simple animated scene that loads from OBJ, uses textures, and does deferred lighting with shadow map.
"""
import logging
import math
from time import time
from pathlib import Path
import pyglet
from pyglet import gl
from euclid3 import Matrix4, Point3
from fogl.debug import DebugWindow
from fogl.framebuffer im... | StarcoderdataPython |
1726359 | import numpy as np
import glob
import random
import torch
import torch.utils.data
from analyzer.data.utils.data_raw import *
from analyzer.data.utils.data_misc import *
from analyzer.data.augmentation import Augmentor
class PairDataset():
'''
This Dataloader will prepare sample that are pairs for feeding the c... | StarcoderdataPython |
6522607 | # Get numbers divisible by fifteen from a list using an anonymous function
numberlist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
answer=list(filter(lambda x:(x%2==0),numberlist))
print("the numbers divisible by 2 are :\n",answer)
# lambda operator or lambda function is used for creating small, one-time and ... | StarcoderdataPython |
11203026 | from pythonforandroid.recipe import PythonRecipe
class PycryptodomeRecipe(PythonRecipe):
version = '3.4.6'
url = 'https://github.com/Legrandin/pycryptodome/archive/v{version}.tar.gz'
depends = ['setuptools', 'cffi']
def get_recipe_env(self, arch=None, with_flags_in_cc=True):
env = super(Pycry... | StarcoderdataPython |
1725479 | <reponame>supdrewin/linux-enable-ir-emitter
import os
import yaml
import sys
import logging
from typing import List
from globals import SAVE_DRIVER_FILE_PATH, ExitCode
from driver.Driver import Driver
class DriverSerializer:
@staticmethod
def _deserialize_saved_drivers() -> List[object]:
"""Load all ... | StarcoderdataPython |
3586889 | import argparse
import requests
TEMPLATE = (
lambda labels: f"""\
ATOMIC_NUMBER_LABELS = {str(labels)}
"""
)
def main(args: argparse.Namespace):
result = requests.get(args.input).json()
labels = {
element["number"]: element["symbol"] for element in result["elements"]
}
file_content = TEMP... | StarcoderdataPython |
9750623 | def author_picture():
author_picture_list = [
"https://edu-test-1255999742.cos.ap-chengdu.myqcloud.com/portrait/20190612/"
"dd4f56aba5524d28beac93dbb2770783.jpg",
"https://edu-test-1255999742.cos.ap-chengdu.myqcloud.com/portrait/20190612/"
"3a09d554769e45fe9c1f68e58d44350a.jpg",
... | StarcoderdataPython |
356375 | <gh_stars>0
###
# Copyright 2019 <NAME>, Inc. 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
#
# Unless required... | StarcoderdataPython |
5070336 | <gh_stars>0
import numpy as np
import torch
class DistancesNumpy:
"""A collection of nearly all known distance functions implemented with numpy operators"""
@staticmethod
def braycurtis(a, b):
return np.sum(np.fabs(a - b)) / np.sum(np.fabs(a + b))
@staticmethod
def canberra(a, b):
r... | StarcoderdataPython |
4999941 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-07-01 18:19
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | StarcoderdataPython |
1995892 | <gh_stars>0
import torch
from torch import nn
from torch.nn import functional as F
from .i_attention_layer import SqueezeExcitation_c64
from .i_attention_layer import SqueezeExcitation_c100
from .i_attention_layer import SpatialAttention
from .i_attention_layer import ConvBNReLU
from .i_attention_layer import SE
from ... | StarcoderdataPython |
9721614 | # -*- coding: utf-8 -*-
"""column type"""
__all__ = ['ColumnType', 'DateColumnType', 'TimeColumnType', 'DateTimeColumnType', 'basic_column_type']
import abc
import datetime as dt
from .default import ValueFetcher
from pyqttable.editor import *
basic_column_type = [int, float, str, bool]
class ColumnType(metaclas... | StarcoderdataPython |
109826 | <gh_stars>0
#!/usr/bin/env python3
# Copyright 2021 Canonical 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 applic... | StarcoderdataPython |
11227747 | #!/usr/bin/python
# coding: utf-8
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.Qsci import QsciScintilla, QsciLexerXML
import packtools_wrapper
class SimpleXMLEditor(QsciScintilla):
ARROW_MARKER_NUM = 8
def __init__(self, parent=None):
super(SimpleXMLEditor, self).__init__(parent)
... | StarcoderdataPython |
3314543 | from django.test import TestCase
from .signals import send_newsletter
from .models import Newsletter, Topic
from .script import get_mailing_list
from user.models import Profile
from django.contrib.auth.models import User
import datetime
# Create your tests here.
class NewsletterTest(TestCase):
def setUp(self):
... | StarcoderdataPython |
9708586 | import base64
from googleapiclient import discovery
class Transcriber(object):
# the transcript chunks
transcript_chunks = []
def __init__(self, api_key):
self.api_key = api_key
def get_speech_service(self):
"""
Get the Google Speech service.
"""
return dis... | StarcoderdataPython |
1751957 | import paramiko
IP = '192.168.127.12'
USER = 'pruebaURJC'
PASSWORD = '<PASSWORD>'
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP, port=22, username=USER, password=PASSWORD)
sftp = ssh.open_sftp()
sftp.get('./Clases.py','Clases.py')
sftp... | StarcoderdataPython |
1918039 | <filename>test/vanilla/legacy/Expected/AcceptanceTests/BodyComplexPythonThreeOnly/bodycomplexpython3only/models/_auto_rest_complex_test_service_enums.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed unde... | StarcoderdataPython |
1859194 | import os
# Get box size from xyz file or use the default box size parameter
def get_box_info(input_file_name):
with open(input_file_name) as f:
load_lines = f.readlines()
try:
box_size_parameter = (((load_lines[1].split('['))[1].split(']'))[0]).split(',')
box_size_parameter... | StarcoderdataPython |
3588262 | """
Napisz program wczytujący liczbę naturalną z klawiatury i odpowiadający na pytanie,
czy jej cyfry stanowią ciąg rosnący.
"""
def are_digits_incresing(strnumber, i):
while i != len(strnumber):
if strnumber[i] > strnumber[i - 1]:
i += 1
elif len(strnumber) < len(strnumber) - 2:
... | StarcoderdataPython |
4805029 | # Copyright: <NAME> <<EMAIL>>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
from aqt.qt import *
from operator import itemgetter
from aqt.utils import showInfo, askUser, getText, maybeHideClose, openHelp
import aqt.modelchooser, aqt.clayout
from anki import stdmodels
from aqt.utils imp... | StarcoderdataPython |
4870432 | from PyQt5.QtCore import QObject, pyqtSignal
class CurrentThread(QObject):
_on_execute = pyqtSignal(object, tuple, dict)
def __init__(self):
super(QObject, self).__init__()
self._on_execute.connect(self._execute_in_thread)
def execute(self, f, args, kwargs):
self._on_execute.emit... | StarcoderdataPython |
1890325 | import os
import pytest
from featuretools import list_primitives
from featuretools.primitives import (
Age,
Count,
Day,
GreaterThan,
Haversine,
Last,
Max,
Mean,
Min,
Mode,
Month,
NumCharacters,
NumUnique,
NumWords,
PercentTrue,
Skew,
Std,
Sum,
... | StarcoderdataPython |
8121143 | from __future__ import division
__version__ = '0.0.3'
__author__ = '<NAME>'
import md5
from math import sqrt, log, sin, cos, pi
import types
TAU = 2.0*pi
def gaussian(value1, value2):
"""
Converts two flat distributed numbers into a gaussian distribution
Input from 0-1, output mean 0 STDDE... | StarcoderdataPython |
6492700 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
from logging import getLogger
from concurrent.futures import ProcessPoolExecutor, wait
import numpy as np
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
from .basics.classifier_cha... | StarcoderdataPython |
5169438 | import gym
import numpy as np
import matplotlib.pyplot as plt
from windy_gridworld import WindyGridworldEnv
import time, os
def create_state_action_dictionary(env):
Q = {}
for key in range(env.nS):
Q[key] = {a: 0.0 for a in range(env.nA)}
return Q
def epsilon_greedy_action(env, epsilon, s, Q):
... | StarcoderdataPython |
12818426 | from scipy.stats import entropy, ks_2samp, kstest, anderson
import numpy as np
EPSILON = 10e-10
# ############################################### #
# ##### Distribution Metrics for Testing G: ##### #
# ############################################### #
def calc_Dkl(true_samples, generated_samples, bin_num=100):
... | StarcoderdataPython |
4848492 | import urllib.request, json
from datetime import datetime
from django.utils import timezone
from django.conf import settings
from django.db.models import Q
from fbevents.models import Event
# Assume all the upcoming events are in the first page, paging is ignored
def sync_upcoming_events_with_fb():
fb_events_ap... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.