id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1773558 | try:
from urllib.request import urlopen
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen
from urllib2 import HTTPError
| StarcoderdataPython |
1636452 | # Copyright (c) 2020-2021, NVIDIA 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | StarcoderdataPython |
1665892 | <reponame>campo1312/DataDome
# This tutorial is for informational purposes only. I guess you'll add the code to your scripts, go ahead but quote me, thanks.
# In the "examples" folder i'll load some DataDome html pages, to let you familiarize with it
# How to bypass it?
# Basically you need a cookie called "datadome"... | StarcoderdataPython |
3304557 | <reponame>abhinayy0/chat.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def chat():
return "My chat application."
if __name__=="__main__":
app.run(host = "127.0.0.1", port = 5000, threaded= True, debug= True) | StarcoderdataPython |
1649998 | <gh_stars>10-100
"""
Created: Tue Mar 26 09:45:46 2019
@author: <NAME> <<EMAIL>>
"""
import numpy as np
import os
from cffi import FFI
docompile = False
ffi = FFI()
if docompile:
cwd = os.getcwd()
ffi.set_source('_libuq', '', libraries=['uq'])
ffi.cdef("""
void __mod_unqu_MOD_init_uq();
... | StarcoderdataPython |
22186 |
# -*- coding: utf-8 -*-
import sys
import argparse
arg_no = len(sys.argv)
tool_parser = argparse.ArgumentParser(add_help=False)
tool_subparsers = tool_parser.add_subparsers(help='commands', dest='command')
# The rename command.
rename_parser = tool_subparsers.add_parser('rename', help='rename an existing user acco... | StarcoderdataPython |
3301536 | import os.path
from recoder import Recoder
from tk_recoder import gui
import config
config.load()
init_config = config.to_string()
log_file = os.path.join(config.application_path, f'{config.application_name}.log')
recoder = Recoder(config.config, log_file)
gui = gui.Gui(recoder, config.config)
def on_close():
... | StarcoderdataPython |
58841 | <reponame>YilinLiu97/MR_Fingerprinting
# import os.path
# import torchvision.transforms as transforms
# from data.base_dataset import BaseDataset, get_transform
from data.base_dataset import BaseDataset
# from data.image_folder import make_dataset
# from PIL import Image
# import PIL
import h5py
import random
import to... | StarcoderdataPython |
197056 |
def getLate():
v = Late(**{})
return v
class Late():
value = 'late'
| StarcoderdataPython |
66164 | ####################################################################################################
##
## Project: Embedded Learning Library (ELL)
## File: demoHelper.py
## Authors: <NAME>
## <NAME>
##
## Requires: Python 3.x
##
#####################################################################... | StarcoderdataPython |
1791692 | from django.apps import AppConfig
class DietConfig(AppConfig):
name = 'diet'
| StarcoderdataPython |
1716532 | <reponame>madaoCN/scopus_browser<filename>models/SearchRefModel.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/9 13:15 AM
# @Author : MADAO
class SearchRefModel(object):
def __init__(self):
super().__init__()
self.raw = None
self.doi = None
self.title = None
... | StarcoderdataPython |
1767897 | <filename>petstagram/petstagram/accounts/urls.py
from django.urls import path
from petstagram.accounts.views import UserLoginView, ProfileDetailsView, UserRegisterView
urlpatterns = [
path('login/', UserLoginView.as_view(), name='login user'),
path('<int:pk>/', ProfileDetailsView.as_view(), name='profile deta... | StarcoderdataPython |
1637157 | <reponame>lucasazevedo/bstgames<filename>bstgames/models.py
from django.db import models
from stdimage.models import StdImageField
from django.core.validators import MaxValueValidator
class GameGenre(models.Model):
genre = models.CharField('Genre', max_length=50, unique=True)
class Meta:
verbose_name... | StarcoderdataPython |
140287 | <filename>framework/contrib/PythonFMU/pythonfmu/tests/test_variables.py
from enum import Enum
from random import randint
import pytest
from pythonfmu import Fmi2Slave
from pythonfmu.enums import Fmi2Causality, Fmi2Initial, Fmi2Variability
from pythonfmu.variables import Boolean, Integer, Real, ScalarVariable, String
... | StarcoderdataPython |
164085 | <reponame>Ivancaminal72/mcv-m6-2018-team3
import cv2
import numpy as np
from track import track
from utils import write_images2
from homography_transformation import *
from speedlimit_emojis import speedlimit_emojis, watermark
# TODO: Check the thresholds (validate) & put in config file
selection = 'highway'
if sel... | StarcoderdataPython |
1679156 | <filename>testcase/tools/findleaves.py<gh_stars>1-10
#!/usr/bin/env python
#
# Copyright (C) 2009 The Android Open Source Project
#
# 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... | StarcoderdataPython |
3311118 | <reponame>liamrahav/TopicBERT-PyTorch<filename>vae_main.py
import sys
import torch
from datasets import Reuters8Dataset, IMDBDataset, Vocabulary, EmbeddingDataset
from training.pretrain_vae import pretrain
from models import VAEEncoder, Generator2
def run_vae_pretrain(opts):
verbose = opts['verbose']
if op... | StarcoderdataPython |
184213 | <reponame>ck-tm/biserici-inlemnite<gh_stars>0
# Generated by Django 3.1.13 on 2021-08-04 10:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('biserici', '0046_auto_20210804_1253'),
]
operations = [
migrations.AddField(
mode... | StarcoderdataPython |
3303078 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | StarcoderdataPython |
175811 | from census import Census
from census_tract_race_population import CensusTractRacePopulation
import sys
from us import states
if __name__ == '__main__':
if len(sys.argv) == 1:
print('Provide your Census API token as an argument when running this script.')
sys.exit()
api_key = sys.argv[1]
i... | StarcoderdataPython |
44131 | BATCH_SIZE = 100
# Constants describing the training process.
MOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.
NUM_EPOCHS_PER_DECAY = 50 # Epochs after which learning rate decays.
LEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.
INITIAL_LEARNING_RATE = 0.001 # Ini... | StarcoderdataPython |
3356821 | import numpy as np
import timeit
from collections import defaultdict
# 문제 구성 : {
# state : {x1, x2, x3, x4, x5, x6}
# action : {1, 0}
# reward : {1, -1}
# if prev_state_fp == 0,1,0,1,0 and currentAction == 0 {
# reward : 1000}
# }
class QLearningAgent:
# 상태 변환 확률은 1이므로 생략
def __in... | StarcoderdataPython |
1634786 | import tkinter
top = tkinter.Tk()
# Code to add widgets will go here
top.mainloop()
| StarcoderdataPython |
161281 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MACchangerGUI.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
... | StarcoderdataPython |
3281666 |
#!/usr/bin/env python
"""
Use an aggregation query to answer the following question.
What is the most common city name in our cities collection?
Your first attempt probably identified None as the most frequently occurring city name.
What that actually means is that there are a number of cities without a name field... | StarcoderdataPython |
3271860 | <reponame>zavolanlab/htsinfer<filename>htsinfer/models.py
"""Data models."""
from enum import (
Enum,
IntEnum,
)
import logging
import re
from typing import Optional
# pylint: disable=no-name-in-module,invalid-name
from pydantic import BaseModel
class CleanupRegimes(Enum):
"""Enumerator of cleanup regim... | StarcoderdataPython |
12312 | <filename>core/migrations/0010_wagtailsitepage_screenshot.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-21 23:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0009_wagtail112upgrade'),
]
operations = [
migrations... | StarcoderdataPython |
3343351 | """
"""
import pandas as pd
import numpy as np
from clintk.cat2vec.feature_selection import LassoSelector
from numpy.testing import assert_array_equal
values = {'feature1': [0, 0, 1, 1, 0],
'feature2': [0, 1, 1, 0, 1],
'feature3': [1, 0, 0, 0, 0],
'feature4': [1, 0, 0, 0, 1]}
coeffic... | StarcoderdataPython |
105265 | def differentSymbolsNaive(s):
diffArray = []
for i in range(len(list(s))):
if list(s)[i] not in diffArray:
diffArray.append(list(s)[i])
return len(diffArray) | StarcoderdataPython |
1614322 | <gh_stars>10-100
#!/usr/bin/env python3
#******************************************************************************
# (C) 2019, <NAME>, Austria *
# *
# The Space Python Library is free software; yo... | StarcoderdataPython |
1649958 |
from aliyun.log.etl_core import *
TRANSFORM_EVENT_lookup = [
( NO_EMPTY('csv_field'), ('csv_field', CSV("f_v1,f_v2,f_v3")) ),
( NO_EMPTY('dsv_field'), ('dsv_field', CSV("f_d1,f_d2,f_d3", sep='#', quote='|')) ),
( ANY, ([("f1", "c1"), ("f2", "c2")], LOOKUP('./data4_lookup_csv1.txt', ["d1", "d2"]) ) ),
... | StarcoderdataPython |
4834735 | <filename>Tests/func_deriv_check.py
#!/usr/bin/env python
"""\
Test the functional derivatives
"""
from PyQuante.DFunctionals import xpbe,xs,xb,cvwn,clyp
rho = 1.0
gam = 0
d = 1e-5
Funcs = dict(S=xs,B=xb,PBE=xpbe,VWN=cvwn,LYP=clyp)
hasg = dict(S=False,B=True,PBE=True,VWN=False,LYP=True)
for name in ['S','B','PBE']... | StarcoderdataPython |
7708 | <filename>Exercise_8.py
# Solution of Exercise 8 - Exercise_8.py
#
# Uploaded by <NAME> on 11/23/20.
# Updated by <NAME> on 11/06/21.
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, f... | StarcoderdataPython |
86580 | #!/usr/bin/env python
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLD... | StarcoderdataPython |
1662275 | <filename>Projects Cousera/Python For Everybory/random.py
def fred():
print("Zap")
def jane():
print("ABC")
jane()
fred()
jane()
def thing():
print('Hello')
print('There')
def func(x):
print(x)
func(10)
func(20)
def stuff():
print('Hello')
return
print('World')
stuff()
def ... | StarcoderdataPython |
3254554 | # 136. Single Number
class Solution:
# Math
def singleNumber(self, nums: list[int]) -> int:
# 2 ∗ (a + b + c) − (a + a + b + b + c) = c
return 2 * sum(set(nums)) - sum(nums) | StarcoderdataPython |
34987 | <gh_stars>0
import skimage.io # bug. need to import this before tensorflow
import skimage.transform # bug. need to import this before tensorflow
from resnet_train import train
from resnet import inference
import tensorflow as tf
import time
import os
import sys
import re
import numpy as np
from image_processing impo... | StarcoderdataPython |
3277059 | from typing import List
import pandas as pd
import streamlit as st
from pyspark.sql import DataFrame
def preview_df(df: DataFrame, n: int = 100):
preview_pdf = df.limit(n).toPandas()
st.markdown(f'Preview for first {n} rows out of {df.count()} loaded.')
st.dataframe(preview_pdf)
def highlight_columns(d... | StarcoderdataPython |
148744 | <reponame>tanimutomo/bag-of-local-features-models
import keras
from keras.models import load_model
__all__ = ['bagnet9', 'bagnet17', 'bagnet33']
model_urls = {
'bagnet9': 'https://bitbucket.org/wielandbrendel/bag-of-feature-pretrained-models/raw/d413271344758455ac086992beb579e256447839/bagnet8.h5',
... | StarcoderdataPython |
3231162 | <reponame>pk-hackerrank/python
def print_rangoli(size):
alphabets = list('abcdefghijklmnopqrstuvwxyz')
size_count = 1
loop_count = 2*size - 1
alphabets_size = len(alphabets)
# Print the upper code including the middle
for i in range(loop_count,0,-2):
str = "-"*(i-1)
sub_list = a... | StarcoderdataPython |
157607 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
## Autor: <NAME>
import numpy as np
from bubble2 import Bubble2
from bworld import Bworld
n = 1000
bubbles = []
bubbles.append(Bubble2(np.random.rand(n, 3) * 10, np.zeros((n, 3)),
radius = (np.random.rand(n) / 6), color = (0.5, 0.8, 1.0, 0.8)))
testworld = B... | StarcoderdataPython |
21714 | from __future__ import unicode_literals
import codecs
from django.conf import settings
from rest_framework.compat import six
from rest_framework.parsers import BaseParser, ParseError
from rest_framework import renderers
from rest_framework.settings import api_settings
import ujson
class UJSONParser(BaseParser):
... | StarcoderdataPython |
194493 | <gh_stars>0
# -*- coding: utf-8 -*-
__doc__ = """
bloombox: CLI color support
"""
# colorama
from colorama import init, Fore, Style
init()
def green(message):
""" Output a green message. """
print Fore.GREEN + message + Fore.RESET + Style.RESET_ALL
def red(message):
""" Output a red message. """
... | StarcoderdataPython |
1665122 | <reponame>zhongtianxie/fm-orchestrator
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import absolute_import
import os
import tempfile
import shutil
from textwrap import dedent
import kobo.rpmlib
import koji
import mock
import pytest
from module_build_service.common.config import conf
from mod... | StarcoderdataPython |
1705380 | <reponame>ViditSheth77/Solecthon
import cv2
import numpy as np
import math
path = "http://192.168.43.156:4747/video"
cap = cv2.VideoCapture('video.mp4')
# Laptop camera
pt = [(0,100), (-600,416), (416,100), (1016,416)]
LIMIT_CONE = 230+30-30
mid_c = 80-5
# intel camera
#pt = [(0,225), (-1500,500), (600,225), (210... | StarcoderdataPython |
1738199 | <gh_stars>0
from syne_tune import read_version
from setuptools import setup, find_packages
from pathlib import Path
def load_requirements(filename):
with open(filename) as f:
return f.read().splitlines()
def load_benchmark_requirements():
# the requirements of benchmarks are placed into the same dir... | StarcoderdataPython |
3387549 | <reponame>anuragpapineni/Hearthbreaker-evolved-agent<gh_stars>0
try:
import ctrnn # C++ extension
except ImportError:
print "CTRNN extension library not found!"
raise
def create_phenotype(chromo):
num_inputs = chromo.sensors
num_neurons = len(chromo.node_genes) - num_inputs
#num_outputs = chr... | StarcoderdataPython |
100607 | from collections import OrderedDict
import sys
import numpy as np
import onnx
from array import array
from pprint import pprint
def onnx2darknet(onnxfile):
# Load the ONNX model
model = onnx.load(onnxfile)
# Check that the IR is well formed
onnx.checker.check_model(model)
# Print a huma... | StarcoderdataPython |
22865 | import serial
class Agilent34970A:
def __init__(self):
self.timeout = 10
self.baudrate = 4800
self.bytesize = serial.EIGHTBITS
self.parity = serial.PARITY_NONE
self.stopbits = serial.STOPBITS_ONE
xonxoff = True
self.s = serial.Serial(port='/dev/ttyUSB3', time... | StarcoderdataPython |
3264006 | import inspect
import simplejson as json
from pprint import pprint
class jsonUtil(object):
def __init__(self):
pass
def dump_json(self, obj, **param):
return json.dumps(obj, param)
def dict_to_bytes(the_dict):
return json.dumps(the_dict).encode()
def readJson(self, file)... | StarcoderdataPython |
1690740 | from ..common import *
class Generic(object):
def __init__(self, arch, descr):
self._arch = arch
self._descr = descr
def generate(self, cpp, routineCache):
d = self._descr
if not d.add:
writeBB = boundingBoxFromLoopRanges(d.result.indices, d.loopRanges)
initializeWithZero(cpp,... | StarcoderdataPython |
81966 | """
10/26/2017
ACM-ICPC 6818 Reverse Rot
Accepted by OJ
"""
import sys
alphabet = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '_', '.', ]
# lines = open('ACM-ICPC_6818.txt').readlines()
# for line in lines:
for line in sy... | StarcoderdataPython |
1606579 | <gh_stars>1-10
#!/usr/bin/env python
import json
import logging
import requests
from s3vaultlib import __application__
from .base import MetadataBase
__author__ = "<NAME>"
__copyright__ = "Copyright 2017-2021, <NAME>"
__credits__ = ["<NAME>"]
__license__ = "BSD"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__stat... | StarcoderdataPython |
1638746 | <reponame>gbrls/CompetitiveCode
# one-line solution for palindrome string
# check if a string is the same as its reverse
palindrome_check = lambda s: s[::-1] == s
#tests
print(palindrome_check("racecar"))
print(palindrome_check("abba"))
print(palindrome_check("palindrome"))
| StarcoderdataPython |
1777406 | <reponame>PaulKGrimes/bolo-calc
#!/usr/bin/env python
import yaml
import argparse
from bolo import Top
def main():
"""Hook for setup.py"""
parser = argparse.ArgumentParser()
parser.add_argument('-i', "--input", default=None, required=True,
help="Input configuration file")
p... | StarcoderdataPython |
1755003 | <gh_stars>1-10
from django.db import models, transaction
from django.utils import timezone
from django.core import validators
from django.contrib.auth.models import AbstractUser
from main.utils.string_utils import generate_noise
from main.utils.user_utils import validate_multiuser_csv
class User(AbstractUser):
"... | StarcoderdataPython |
3243826 | """Tests of queue."""
import pytest
from data_structure.queue.oop_queue import Queue as ArrayQueue
from data_structure.queue.two_stacks_queue import Queue as StackQueue
from data_structure.exceptions.collection_exeption import CollectionIsEmptyExeption
from data_structure.exceptions.error_messages import queue_is_emp... | StarcoderdataPython |
1679824 | #!/usr/bin/python3
"""
Best-practices tracker for Tor source code.
Go through the various .c files and collect metrics about them. If the metrics
violate some of our best practices and they are not found in the optional
exceptions file, then log a problem about them.
We currently do metrics about file size, function... | StarcoderdataPython |
1775291 | import attr
from copy import *
from pprint import *
from .document import Document
from .has_settings import HasSettings
from .templated import Templated
from exam_gen.util.excel_cols import excel_col
from exam_gen.util.with_options import WithOptions
import exam_gen.util.logging as logging
log = logging.new(__nam... | StarcoderdataPython |
157226 | from django.conf import settings
from django.contrib import admin
from django.urls import path
app_name = "django_calendardate"
urlpatterns = [
path(settings.ADMIN_URL, admin.site.urls),
]
| StarcoderdataPython |
1764229 | <filename>plugin/view.py
#!/usr/bin/env python
import vim
from enml import *
from utils import *
from conn import *
# Maps buffer names to NoteTracker objects.
openNotes = {}
#
# Holds all information that needs to be tracked for any note that has been
# opened.
#
class NoteTracker(object):
def __init__(self, ... | StarcoderdataPython |
1720288 | <gh_stars>0
from flask import Flask, request, jsonify, render_template, url_for, send_file
from full_prediction import get_full_prediction
import io
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def test_predict():
if request... | StarcoderdataPython |
1645618 | <gh_stars>0
#!/usr/bin/env python3
#
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same... | StarcoderdataPython |
1631343 | <filename>__init__.py
from piperunner import GEJob, GEArrayJob, GESeriesJob, GEParallelJob
| StarcoderdataPython |
3256145 | <gh_stars>10-100
import os
import logging
from datetime import datetime
from pathlib import Path
import pytz
import pandas as pd
from margot.config import settings
logger = logging.getLogger(__name__)
class DailyMixin(object):
@property
def stale(self):
"""Check if we think there might be new data... | StarcoderdataPython |
1615762 | <reponame>KTH/aspen
__author__ = '<EMAIL>'
import unittest
from test import mock_test_data
from modules.steps.secret_verification import SecretVerification
from modules.util import data_defs, exceptions
class TestSecretVerification(unittest.TestCase):
def test_has_secrets_env_file(self):
pipeline_data = ... | StarcoderdataPython |
3313994 | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | StarcoderdataPython |
172958 | <reponame>ioannistsanaktsidis/flaskreactredux
from flask import Blueprint, jsonify
blueprint = Blueprint(
'testapp_api',
__name__,
url_prefix='/api'
)
@blueprint.route('/health', methods=['HEAD', 'GET'])
def ping():
"""Load balancer ping view."""
return jsonify({"health": "ok"})
| StarcoderdataPython |
1648362 | from typing import Iterable
from queue import Queue
TEST_INPUT = """2199943210
3987894921
9856789892
8767896789
9899965678""".splitlines()
def parse_input(puzzle: Iterable[str]) -> dict[tuple[int, int]]:
grid = {}
for y, row in enumerate(puzzle):
for x, char in enumerate(row):
grid[x, y]... | StarcoderdataPython |
177467 | <gh_stars>1-10
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = Node("head")
self.size = 0
def __str__(self):
cur = self.head.next
out = ""
while cur:
out += str(cur... | StarcoderdataPython |
1719188 | <reponame>BearerPipelineTest/google-ctf<filename>2020/quals/reversing-sprint/asm.py
# Copyright 2020 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/... | StarcoderdataPython |
50656 | <filename>milkviz/_dot.py
from typing import Optional, List, Union, Tuple, Any
import matplotlib as mpl
import matplotlib.axes
import matplotlib.pyplot as plt
import numpy as np
from milkviz.utils import adaptive_figsize, norm_arr, doc, set_size_legend, set_spines, set_ticks
def set_dot_grid(data,
... | StarcoderdataPython |
144743 | <reponame>nxtbesu/python-oligo
import unittest
from oligo.exception import SessionException, LoginException, ResponseException
class TestResponseException(unittest.TestCase):
def test_message(self):
login_exception = ResponseException(418)
self.assertEqual('Response error, code: 418', login_exce... | StarcoderdataPython |
140132 | <reponame>akrisanov/python_notebook<gh_stars>1-10
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 9000)) # max port is 65535
sock.listen(socket.SOMAXCONN)
conn, addr = sock.accept()
while True:
data = conn.recv(1024)
if not data:
break
print(data.dec... | StarcoderdataPython |
3208403 | <reponame>franklongford/ImageCol
"""
ColECM: Collagen ExtraCellular Matrix Simulation
UTILITIES ROUTINE
Created by: <NAME>
Created on: 01/11/2015
Last Modified: 12/04/2018
"""
from functools import wraps
import logging
import time
from stevedore import ExtensionManager
import numpy as np
logger = logging.getLogger(... | StarcoderdataPython |
3217221 | #!/usr/bin/python
# Copyright 2016 <NAME>
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distribu... | StarcoderdataPython |
1742455 | #!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
import codecs
from ..util import u, slugify
import os
from ..util import ERROR_COLOR, RESET_COLOR
class TextExporter(object):
"""This Exporter can convert entries and journals into text files."""
names = ["text",... | StarcoderdataPython |
3299471 | class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# my solution
nums.sort()
for i in range(1, len(nums)):
if nums[i-1] == nums[i]:
return True
return False
# more concise solution
# https://leetcode.com/pr... | StarcoderdataPython |
1643373 | <gh_stars>1-10
from datetime import datetime, date, time
from hun_date_parser import datetime2text, text2datetime, text2date, text2time
def test_datetime2text():
candidates = datetime2text(datetime(2020, 12, 21))
assert set(candidates) == {'dates', 'times'}
assert len([c for c in candidates['dates'] if ... | StarcoderdataPython |
3319608 | from botstory.ast import story_context
from botstory.ast.story_context import get_message_attachment
from botstory.middlewares import any, location, option, sticker, text
from botstory.integrations.commonhttp import errors as http_errors
import emoji
import datetime
import logging
from nasabot.geo import animation, til... | StarcoderdataPython |
1758086 | <reponame>MugeraH/Neighbourhood
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import LandingPageView,HomePageView,NeighbourHoodCreateView,ProfileView,NeigbourhoodDetail,UpdateNeigbourhood,add_business,add_post,update_post,update_business,join_hood,l... | StarcoderdataPython |
3320292 | <reponame>digitalepidemiologylab/text-classification
"""
Printing helpers
================
"""
import os
import pandas as pd
import logging
logger = logging.getLogger(__name__)
def print_misclassifications(run, num_samples):
f_path = os.path.join(os.getcwd(), 'output', run)
if not os.path.isdir(f_path):
... | StarcoderdataPython |
1750186 | import logging
from pyspark.sql import SparkSession
def run_spark_job(spark):
#TODO read format as Kafka and add various configurations
df = spark \
.readStream \
.load()
# Show schema for the incoming resources for checks
df.printSchema()
agg_df = df.count()
# TODO complete... | StarcoderdataPython |
143385 | <gh_stars>0
from typing import Dict
count = 0
# Part 1
with open("06.in", "r") as file:
group_unique = set()
for line in file.readlines():
line = line.replace("\n", "")
# New group
if line == "":
count += len(group_unique)
group_unique = set()
# Read u... | StarcoderdataPython |
1702287 | <reponame>QianLiGui/tfsnippet
import numpy as np
from tfsnippet.utils import DocInherit
from .base import DataFlow
__all__ = [
'DataMapper', 'SlidingWindow'
]
@DocInherit
class DataMapper(object):
"""
Base class for all data mappers.
A :class:`DataMapper` is a callable object, which maps input arra... | StarcoderdataPython |
1787826 | <reponame>rido-min/azure-iot-cli-extension
# 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.
# ----------... | StarcoderdataPython |
97095 | <filename>sesion28/tictactoe/core/routing.py
from django.conf.urls import url
from core.consumer import TicTacToeConsumer
websocket_urlpatterns = [
url(r'^ws/play/$', TicTacToeConsumer.as_asgi())
] | StarcoderdataPython |
3376682 | from random import random
class Synapse:
def __init__(self, from_neuron, to_neuron):
self.from_neuron = from_neuron
self.to_neuron = to_neuron
self.weight = random()
| StarcoderdataPython |
1782935 | <reponame>canyon289/nipymc
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import scipy as sp
import pymc3 as pm
from pymc3 import Deterministic
import theano.tensor as T
from sklearn.preprocessing import scale as standardize
import sys, pickle
from random ... | StarcoderdataPython |
1788564 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
class Calculator():
def power(self, n, p):
if n < 0 or p < 0:
raise Exception('n and p should be non-negative')
else:
... | StarcoderdataPython |
4814802 | <filename>hummingbird/ml/operator_converters/sklearn/label_encoder.py<gh_stars>1-10
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -... | StarcoderdataPython |
3377596 | #!/usr/bin/env python
#
# Copyright 2014 cloudysunny14.
#
# 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... | StarcoderdataPython |
4813849 | <filename>pocao.py<gh_stars>0
from pokemon import *
from pessoa import Pessoa
class Pocao(Pokemon, Pessoa):
def __init__(self, pokemon=None, jcoin=0):
self.pokemon = pokemon
self.preco = 350
self.jcoin = jcoin
def funcao_pocao(self):
pass
class Curar(Pocao):
def funcao_p... | StarcoderdataPython |
1718307 | <filename>lenstools/simulations/nbody.py
from __future__ import division
from abc import ABCMeta,abstractproperty,abstractmethod
from operator import mul
from functools import reduce
import sys,os
from .logs import logplanes,logstderr,peakMemory
import logging
from .. import extern as ext
import numpy as np
#ast... | StarcoderdataPython |
3396275 | <reponame>fitushar/3DCNNs_TF2Modelhub
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import tensorflow as tf
##########---tf bilinear UpSampling3D
def up_sampling(input_tensor, scale):
net = tf.keras.layers.TimeDistributed(tf.keras.layers.UpSampling2D... | StarcoderdataPython |
143829 | <reponame>tkg-framework/TKG-framework<filename>tkge/models/model.py
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
from enum import Enum
import os
from collections import defaultdict
from typing import Mapping, Dict
import random
from tkge.common.registry import Registrable... | StarcoderdataPython |
1731861 | from typing import Mapping, Sequence
import pandas as pd
from multilevel_panels import MultilevelPanel
known = [
('Felis', 'silvestris'),
('Canis', 'lupus'),
('Homo', None),
('Panthera', 'leo'),
('Panthera', 'tigris'),
('Bos', 'taurus'),
('Ovis', None),
]
candidate = [
('Felis', 'si... | StarcoderdataPython |
1672282 | from .models import Order
from django import forms
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ('description', 'product_type') | StarcoderdataPython |
1747100 | <reponame>deepmind/launchpad
# Copyright 2020 DeepMind Technologies Limited. 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/LICENS... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.