id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
113773 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# code for python2.7
#
#
import rospy
import serial
import time
import signal
import sys
import math
import tf
from nav_msgs.msg import Odometry
from whipbot.msg import Posture_angle
from kondo_b3mservo_rosdriver.msg import Multi_servo_info
# variables to store timings o... | StarcoderdataPython |
70359 | <gh_stars>0
import sys
import logging
import logging.config
import configparser
from datetime import datetime
from robottelemetryservice.infrastructure.repository.measurement_event_sqlite_repository import MeasurementEventSQLiteRepository
try:
logging.config.fileConfig('./robottelemetryservice/resources/logging.co... | StarcoderdataPython |
3265730 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from django.core.management.base import BaseCommand, CommandError
import psycopg2
from disease.models import SNPMarker
def map_SNP_model_fields(gwas_dict):
def clean_NR(value):
if value in {'NR', 'NS'}:
value = None
return valu... | StarcoderdataPython |
1780339 | from django.conf.urls import patterns, url
urlpatterns = patterns('livesettings.views',
url(r'^$', 'site_settings', name='satchmo_site_settings'),
url(r'^export/$', 'export_as_python', name='settings_export'),
url(r'^(?P<group>[^/]+)/$', 'group_settings', name='livesettings_group'),
)
| StarcoderdataPython |
51631 | import subprocess
from flask import Flask
from os import environ
BOT_START_FILE = 'run_bot.py'
# for start PYTHON_PROCESS = 'python3'
# for testing
PYTHON_PROCESS = r"C:\Python3.7\python.exe"
app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
return "Bot is On"
print(f"Running {BOT_START_FIL... | StarcoderdataPython |
4836210 | <reponame>timt51/guildai<filename>guild/commands/runs_restore.py
# Copyright 2017-2021 TensorHub, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | StarcoderdataPython |
1736009 | <filename>ad_ldap/constants.py
#!/usr/bin/python
"""A module containing constants used by adldap module.
Copyright 2010 Google 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.... | StarcoderdataPython |
1765268 | from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from rest_framework.validators import UniqueValidator
class LoginSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField... | StarcoderdataPython |
1719299 | # blender modules
import bpy
# addon modules
from .. import ui
from .. import ops
class XRAY_PT_shader(ui.base.XRayPanel):
bl_space_type = 'NODE_EDITOR'
bl_label = 'Shader'
bl_category = ui.base.CATEGORY
bl_region_type = 'UI'
@classmethod
def poll(cls, context):
mat = context.materia... | StarcoderdataPython |
11546 | import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def main():
pygame.init()
glutInit()
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glTranslatef(0.0, 0.0, -5)
w... | StarcoderdataPython |
3267681 | <filename>other/model_wine.py
import pandas as pd
import numpy as np
from synthetic_datasets import GaussianLinearRegression, GaussianLinearBinary
from sklearn import preprocessing
from sklearn.neighbors import KNeighborsRegressor,KNeighborsClassifier
from sklearn.neural_network import MLPRegressor
from sklearn.linear_... | StarcoderdataPython |
1764239 | # Copyright (c) 2016 <NAME>.
# Cura is released under the terms of the LGPLv3 or higher.
import configparser
from UM.PluginRegistry import PluginRegistry
from UM.Logger import Logger
from UM.Settings.InstanceContainer import InstanceContainer # The new profile to make.
from cura.ProfileReader import ProfileReader
im... | StarcoderdataPython |
8294 | <gh_stars>0
# --------------
#Importing header files
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Code starts here
data = pd.read_csv(path)
data.hist(['Rating'])
data = data[data['Rating']<=5]
data.hist(['Rating'])
#Code ends here
# --------------
# code starts here
total_null = dat... | StarcoderdataPython |
4842619 | #!/usr/bin/env python3
import base64
import sys
import os
import re
import json
import tarfile
import anchore_engine.analyzers.utils
import anchore_engine.utils
analyzer_name = "retrieve_files"
try:
config = anchore_engine.analyzers.utils.init_analyzer_cmdline(sys.argv, analyzer_name)
except Exception as err:
... | StarcoderdataPython |
180588 | <filename>rally/task/validation.py
# Copyright 2014: Mirantis 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/... | StarcoderdataPython |
3525 | import inspect
import os
from pathlib import Path
class change_directory:
"""
A class for changing the working directory using a "with" statement.
It takes the directory to change to as an argument. If no directory is given,
it takes the directory of the file from which this function was call... | StarcoderdataPython |
3221060 | # -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. 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 requir... | StarcoderdataPython |
3303044 | <filename>source/codegen/metadata/nidcpower/attributes.py
# -*- coding: utf-8 -*-
# This file is generated from NI-DCPower API metadata version 20.7.0d8
attributes = {
1050002: {
'access': 'read-write',
'channel_based': False,
'name': 'RANGE_CHECK',
'resettable': False,
'type... | StarcoderdataPython |
3222202 | import numpy as np
import pytest
from gradgpad.foundations.metrics.acer import acer
@pytest.mark.unit
def test_should_throw_an_exception_when_input_is_not_np_array():
pytest.raises(
TypeError, lambda: acer([0.0, 0.2, 0.2, 0.5, 0.6], [1, 2, 2, 0, 0], 0.25)
)
@pytest.mark.unit
@pytest.mark.parametriz... | StarcoderdataPython |
126922 | <gh_stars>1-10
# This provides utilities for plotting convergence
# information for solvers
import numpy as np
import matplotlib.pyplot as plt
def plot_eigen_convergence(solver) :
""" Plots the eigenvalue and fission source error per iteration
"""
# return vec_dbl of eigenvalues
keffs = np.a... | StarcoderdataPython |
1650840 | # -*- coding: utf-8 -*-
import os
class GlobalVars:
def __init__(self):
self._execution_path = os.environ.get('BEHAVEX_PATH')
self._report_filenames = {
'report_json': 'report.json',
'report_overall': 'overall_status.json',
'report_failures': 'failures.txt',
... | StarcoderdataPython |
1693720 | <reponame>hocinebendou/bika.gsoc<filename>bika/lims/skins/bika/guard_cancel_transition.py
## Script (Python) "guard_cancel_transition"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
from bika.lims.permissions import Can... | StarcoderdataPython |
1761136 | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
url(r'^$',views.index,name='index'),
url(r'^profile/',views.profile,name='profile'),
url(r'^new/post/', views.new_post, name='new-post'),
url(r'^profile/edit',v... | StarcoderdataPython |
1674394 | from pathlib import Path
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
class Volume:
def __init__(self, path):
self.path = Path(path)
self.nifti = nib.load(str(self.path))
self.data = self.nifti.get_fdata().squeeze()
self.current_data = self.pad(self.dat... | StarcoderdataPython |
35349 | <reponame>ljhOfGithub/teether
from teether.cfg.instruction import Instruction
from teether.cfg.opcodes import potentially_user_controlled
from teether.explorer.backward import traverse_back
from teether.util.intrange import Range
def slice_to_program(s):
pc = 0
program = {}
for ins in s:
program[p... | StarcoderdataPython |
131648 | import numpy as np
import ray
import ray.rllib.algorithms.ppo as ppo
import onnxruntime
import os
import shutil
# Configure our PPO.
config = ppo.DEFAULT_CONFIG.copy()
config["num_gpus"] = 0
config["num_workers"] = 1
config["framework"] = "tf"
outdir = "export_tf"
if os.path.exists(outdir):
shutil.rmtree(outdir)
... | StarcoderdataPython |
180470 | # Author: <NAME>
# Finds probability of no collisions for hash function using function e^-(sum(1 -> t-1) / 365). Outputs things to a CSV file hashprob.csv
import sys
import math
import csv
def prob(t):
# Probability as float
p = math.e ** -(math.fsum(range(1, t)) / 365)
return p
def main():
# For sing... | StarcoderdataPython |
4837197 | <reponame>khromiumos/chromiumos-chromite<filename>lib/request_build.py
# -*- coding: utf-8 -*-
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Code related to Remote tryjobs."""
from __future__ ... | StarcoderdataPython |
3397573 | long_word = 3
long_sentence = 9
fillers = []
passive_indicators = []
tagger = None
abbreviations = r"\b[A-Z][a-zA-Z\.]*[A-Z]\b\.?|.+\..?"
| StarcoderdataPython |
3252499 | <filename>bluzelle/codec/crud/CrudValue_pb2.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: crud/CrudValue.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from ... | StarcoderdataPython |
4837980 | import datetime
import dateutil.relativedelta
def get_current_time():
# TODO return timezone or utc? get config from user?
return datetime.datetime.utcnow()
def get_time_delta(**kwargs):
return dateutil.relativedelta.relativedelta(**kwargs)
| StarcoderdataPython |
137271 | <reponame>angellmethod/DogFaceNet<filename>dogfacenet-dev/online_training.py
"""
DogFaceNet
Functions for training on bigger datasets then offline_training module.
It does not load all the dataset into memory but just a part of it.
It mainly relies on keras data generators.
It contains:
- Offline triplet generator: fo... | StarcoderdataPython |
92871 | <reponame>LouisFaure/scTree
from typing import Union, Sequence, Optional
from typing_extensions import Literal
import numpy as np
import pandas as pd
import igraph
import matplotlib.pyplot as plt
from scFates.tools.utils import get_X
import scanpy as sc
from matplotlib.colors import LinearSegmentedColormap
from matplot... | StarcoderdataPython |
1608086 |
import caffe
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
import timeit
import pdb
import scipy.stats as stats
#global params
#caffe_root = '../' # this file is expected to be in {caffe_root}/examples
caffe_root = os.environ["CAFFE_ROOT"]
sys.path.insert(0, caffe_root + 'python')
plt.rcP... | StarcoderdataPython |
1668280 | #!/usr/bin/env python
from datetime import datetime
import time
from kobot.msg import range_n_bearing_sensor, landmark_sensor, floor_sensor
import rospy
from geometry_msgs.msg import Twist, Vector3, PointStamped, PoseStamped
from std_msgs.msg import UInt8, Bool, String
from nav_msgs.msg import Odometry
import numpy as ... | StarcoderdataPython |
1709678 | from news import forms
from django.contrib import admin
from news.models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'created_time', 'modified_time', 'published')
search_fields = ('title', 'author', 'created_time')
def add_view(self, request, form_url='', extra_con... | StarcoderdataPython |
128174 | from BlockChain.BlockChain import BlockChain
import os
import json
def p(data,color="blue"):
print(data)
class Election:
def __init__(self,place_id,choices):
self.place_id = place_id
self.choices = choices
self.len_choices = len(self.choices)
self.kernel = BlockChain(self.plac... | StarcoderdataPython |
3314149 | import torch
from meta.peer import Peer
from misc.rl_utils import collect_trajectory
from misc.utils import log_performance
from gym_env import make_env
def meta_test(meta_agent, log, tb_writer, args):
# Initialize test_iteration
test_iteration = 0
# Set env
env = make_env(args)
env.seed(args.see... | StarcoderdataPython |
3375606 | <reponame>chentau/nbtui
_METADATA = {}
| StarcoderdataPython |
65295 | <filename>menpo/image/test/image_test.py<gh_stars>0
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from nose.tools import raises
from menpo.image import BooleanImage, MaskedImage
def mask_image_3d_test():
mask_shape = (120, 121, 13)
mask_region = np.ones(mask_shape)
return Boo... | StarcoderdataPython |
3384821 | <reponame>hpcc-systems/uptrends-python<filename>uptrends/models/timezone.py
# coding: utf-8
"""
Uptrends API v4
This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate di... | StarcoderdataPython |
9360 | from datasette import hookimpl
from datasette.utils import detect_spatialite
from shapely import wkt
def get_spatial_tables(conn):
if not detect_spatialite(conn):
return {}
spatial_tables = {}
c = conn.cursor()
c.execute(
"""SELECT f_table_name, f_geometry_column, srid, spatial_index_... | StarcoderdataPython |
1687948 | from sqlalchemy.sql import FromClause, column, ColumnElement, text
from sqlalchemy.orm import Query
from sqlalchemy.ext.compiler import compiles
class crosstab(FromClause):
def __init__(self, stmt, return_def, categories=None, auto_order=True):
if not (isinstance(return_def, (list, tuple))
... | StarcoderdataPython |
1743731 | from sklearn.neural_network import MLPClassifier
from Perceptron import *
import numpy as np
import pandas as pd
import time
trainData = np.array(pd.read_table('./dataset3/train.txt', header=None, encoding='gb2312', delim_whitespace=True))
testData = np.array(pd.read_table('./dataset3/test.txt', header=None, encoding=... | StarcoderdataPython |
1681161 | import logging
from typing import Dict, List, Optional, Tuple, Union
import numpy
from openff.toolkit.topology import Molecule
from simtk import unit
from typing_extensions import Literal, get_args
from chemiwrap.exceptions import ChargeCalculationError
from chemiwrap.providers import (
AromaticityProvider,
A... | StarcoderdataPython |
3346897 | <reponame>Viriliter/PedestrianSlayer
import serial
import time
class ArduinoCommunication(object):
'''
This class consist of set of necessary function to communicate with arduino.
The class is also able to open and close serial port and set its configuration.
It takes ready-to-transmission data and se... | StarcoderdataPython |
1719305 | from ares.defense.jpeg_compression import jpeg_compression
from ares.utils import get_res_path
import inception_v3
MODEL_PATH = get_res_path('./imagenet/inception_v3.ckpt')
def load(session):
model = InceptionV3Jpeg()
model.load(session, MODEL_PATH)
return model
@jpeg_compression(quality=75)
class In... | StarcoderdataPython |
1612198 | # main.py – Software ACUITEE
# Copyright 2021 b<>com. All rights reserved.
# This software is licensed under the Apache License, Version 2.0.
# 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... | StarcoderdataPython |
41844 | <gh_stars>10-100
from __future__ import division, print_function, absolute_import
import GPy
import numpy as np
import arguments
from safemdp.grid_world import (compute_S_hat0, shortest_path)
from utils.reward_utilities import RewardObj
from utils.safety_utilities import SafetyObj
from utils.mdp_utilities import (c... | StarcoderdataPython |
3393313 | import dataclasses
from koala.typing import *
from koala.message.base import JsonMessage
@dataclasses.dataclass
class RpcMessage:
meta: JsonMessage
body: bytes = b""
@classmethod
def from_msg(cls, meta: JsonMessage, body: bytes = b"") -> 'RpcMessage':
msg = RpcMessage(meta=meta, body=body)
... | StarcoderdataPython |
1706162 | <reponame>AkshatSh/BinarizedNMT<filename>translation/models/components/binarized_convolution.py<gh_stars>1-10
'''
This is from the Pytorch implementation of XNOR-NET
Implementation is linked here: https://github.com/jiecaoyu/XNOR-Net-PyTorch/blob/master/CIFAR_10/models/nin.py
'''
import torch.nn as nn
import torch
im... | StarcoderdataPython |
179429 | <gh_stars>1-10
import graphGenerator
import random
import subprocess
import math
import dir
# (1) We first set up a text file in the
# right folder, to save the results
st = dir.results() + "/thirdExperiment.txt"
file = open(st, 'w')
file.write("Algorithm "
+ "nodes "
+ "edges "
+ "po... | StarcoderdataPython |
4839246 | from scrapy.exceptions import DropItem
class PricePipeline(object):
vat_factor = 1.15
def process_item(self, item, spider):
if item.get('price'):
if item.get('price_excludes_vat'):
item['price'] = item['price'] * self.vat_factor
return item
else:
... | StarcoderdataPython |
1697018 | from django.urls import path
from todoApp import views
from django.urls import re_path
from django.views.generic import TemplateView
urlpatterns = [
path('user_login', views.user_login, name='user_login'),
path('user_add', views.user_add, name='user_add'),
path('reset_password', views.reset_password, name=... | StarcoderdataPython |
1622545 | #!/usr/bin/env python
# this node will be implemented on the master node
# this is a test script for drive motor
# in function of stop and front lights detection
# this script will be implemented in another node
# import libraries
import rospy,sys,time,atexit,numpy
from std_msgs.msg import String,Int16MultiArray
... | StarcoderdataPython |
159376 | <filename>packages/pystran/extrafunctions.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 27 21:00:33 2012
@author: VHOEYS
"""
import numpy as np
def rescale(arr,vmin,vmax):
arrout=(vmax-vmin)*arr+vmin
return arrout
############################################################################... | StarcoderdataPython |
3299134 | <filename>src_py/hat/chatter/__init__.py
"""Chatter communication protocol
This module implements basic communication infrastructure used for Hat
communication. Hat communication is based on multiple loosely coupled services.
To implement communication with other Hat components, user should always
implement independen... | StarcoderdataPython |
1798698 | from collections import Counter
import requests
def test_metrics():
"""Should expose cluster metrics as-is."""
# get cluster metrics exposed by yarnitor
yarnitor = requests.get('http://web:8080/api/clusters/default')
assert yarnitor.ok
# get last mock metrics generated by YARN
yarn = requests.... | StarcoderdataPython |
3278919 | <gh_stars>1-10
from setuptools import setup, find_packages
def parse_requirements(requirement_file):
with open(requirement_file) as f:
return f.readlines()
version = dict()
with open("./elastic_agent_setup/utils/version.py") as fp:
exec(fp.read(), version)
setup(
name='elastic-agent-setup',
... | StarcoderdataPython |
143664 | <gh_stars>0
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemin... | StarcoderdataPython |
1698656 | """Pythonic API for LDAP operations."""
import functools
import six
from twisted.internet import defer
from twisted.python.failure import Failure
from zope.interface import implementer
from ldaptor.protocols.ldap import ldapclient, ldif, distinguishedname, ldaperrors
from ldaptor.protocols import pureldap, pureber
fr... | StarcoderdataPython |
3291246 | # -*- coding: utf-8 -*-
"""
test
~~~~
Flask-CORS is a simple extension to Flask allowing you to support cross
origin resource sharing (CORS) using a simple decorator.
:copyright: (c) 2016 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
from ..base_test import FlaskCorsTestCase
from... | StarcoderdataPython |
80499 | <reponame>mhhoban/swappi-project<gh_stars>0
import subprocess
print('Starting Setup:')
subprocess.call('mkdir db', shell=True)
subprocess.call('pip install -r requirements.txt', shell=True)
import swappi.db_setup
_db_setup = swappi.db_setup.DbSetup()
_db_setup.db_init()
| StarcoderdataPython |
1627146 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
147271 | <filename>cyberweb/controllers/pkiproxy.py<gh_stars>0
import logging
import commands
import os
from pylons import request, response, session, app_globals, tmpl_context as c, config, url
from pylons.controllers.util import abort, redirect
from authkit.authorize.pylons_adaptors import authorize, authorized
import sqlalc... | StarcoderdataPython |
166815 | # Generated by Django 3.2 on 2022-01-22 10:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('archives', '0017_alter_report_type'),
]
operations = [
migrations.CreateModel(
name='AgencyDivision',
fields=[
... | StarcoderdataPython |
3354892 | <filename>Validation/RecoMuon/test/muonValidation_cfg.py
import FWCore.ParameterSet.Config as cms
processName = "MuonSuite"
process = cms.Process(processName)
readFiles = cms.untracked.vstring()
secFiles = cms.untracked.vstring()
process.source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = se... | StarcoderdataPython |
3331876 | import sys
import time
import zmq
import string
import random
import hashlib
context = zmq.Context()
vent = context.socket(zmq.PULL)
vent.connect("tcp://localhost:5557")
# Socket to send messages to
sink = context.socket(zmq.PUSH)
sink.connect("tcp://localhost:5558")
# Process tasks forever
while True:
message... | StarcoderdataPython |
2969 | <reponame>LaborBerlin/cubi-tk<filename>cubi_tk/snappy/kickoff.py
"""``cubi-tk snappy kickoff``: kickoff SNAPPY pipeline."""
import argparse
import os
import subprocess
import typing
from logzero import logger
from toposort import toposort
from . import common
from cubi_tk.exceptions import ParseOutputException
de... | StarcoderdataPython |
127056 | import inspect, time, math, random, multiprocessing, os, sys, copy
import numpy, scipy, scipy.stats
from . import FittingBaseClass
import zunzun.forms
from . import pid_trace
class FitOneEquation(FittingBaseClass.FittingBaseClass):
def __init__(self):
super().__init__()
self.interfaceString =... | StarcoderdataPython |
1690025 | <filename>05-02-2018/code.py
def largest_sum(arr):
largest = 0
for idx, x in enumerate(arr):
# create a second array of all values non-adjacent to this one
# (non-adjacent values have index distances greater than 1)
arr2 = [x2 for (idx2, x2) in enumerate(arr) if abs(idx - idx2) > 1]
# find largest s... | StarcoderdataPython |
3312219 | import os
import subprocess
from click.testing import CliRunner
from splitgraph.commandline import init_c
from splitgraph.config import SPLITGRAPH_META_SCHEMA
from splitgraph.core.engine import init_engine
from splitgraph.core.migration import get_installed_version
from splitgraph.engine import ResultShape, get_engin... | StarcoderdataPython |
1648211 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
import time, datetime, os, heapq
import threading
import traceback
import component
import log
class Router (component.Receiver):
incoming_phases = ('parse', 'handle', 'cleanup')
outgoing_phases = ('outgoing',)
def __init__(self):
... | StarcoderdataPython |
3239409 | <reponame>paperwhite/armory
"""apricot_dev dataset."""
import collections
import json
import os
import tensorflow.compat.v1 as tf
import tensorflow_datasets.public_api as tfds
_CITATION = """
@misc{braunegg2020apricot,
title={APRICOT: A Dataset of Physical Adversarial Attacks on Object Detection},
author... | StarcoderdataPython |
1782912 | # Copyright 2019-present Kensho Technologies, LLC.
from textwrap import dedent
import unittest
from graphql import parse
from graphql.language.printer import print_ast
from ...exceptions import GraphQLValidationError
from ...schema_transformation.rename_query import rename_query
from ...schema_transformation.rename_s... | StarcoderdataPython |
109803 | <reponame>eanfs/erpnext_chinese<filename>erpnext_chinese/erpnext_chinese/doctype/user_default/test_user_default.py
# Copyright (c) 2021, Fisher and Contributors
# See license.txt
# import frappe
import unittest
class TestUserDefault(unittest.TestCase):
pass
| StarcoderdataPython |
102916 | # -*- coding:utf-8 -*-
import abc
import six
from gopdb import common
from gopdb import privilegeutils
from gopdb import utils
from gopdb.api import endpoint_session
from gopdb.api import exceptions
from gopdb.models import GopDatabase
from gopdb.models import GopSalveRelation
from gopdb.models import GopSchema
from ... | StarcoderdataPython |
3351747 | <filename>api/api/efiling/efiling_resources.py
# Special thanks to eDivorce for this.
import json
import logging
import requests
from django.conf import settings
from django.core.cache import cache
from .efiling_hub_caller_base import EFilingHubCallerBase
logger = logging.getLogger(__name__)
class EFilingResources(... | StarcoderdataPython |
20398 | <reponame>julesGoullee/jesse
from jesse.store import store
from jesse import helpers
from jesse.services import logger
def save_daily_portfolio_balance():
balances = []
# add exchange balances
for key, e in store.exchanges.storage.items():
balances.append(e.assets[helpers.app_currency()])
# ... | StarcoderdataPython |
118519 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... | StarcoderdataPython |
3330007 | <reponame>charles-hefele/gym-digger<filename>gym_digger/envs/maps.py
import numpy as np
MAPS = {
'2x2_a': np.array([
[1, 1],
[1, 1]
]),
'2x2_b': np.array([
[2, 1],
[1, 2]
]),
'2x2_c': np.array([
[3, 1],
[0, 2]
]),
'2x2_d': np.array([
[... | StarcoderdataPython |
11159 | # Copyright (c) 2009-2020, quasardb SAS. All rights reserved.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice,... | StarcoderdataPython |
25754 | # SPDX-License-Identifier: BSD-3-Clause
# Depthcharge: <https://github.com/nccgroup/depthcharge>
"""
ARM 32-bit support
"""
import os
import re
from .arch import Architecture
class ARM(Architecture):
"""
ARMv7 (or earlier) target information - 32-bit little-endian
"""
_desc = 'ARM 32-bit, little-end... | StarcoderdataPython |
159582 | from onelang_core import *
from enum import Enum
import OneLang.One.Ast.AstTypes as astTypes
import OneLang.One.Ast.Types as types
class DETECTION_MODE(Enum):
ALL_IMPORTS = 1
ALL_INHERITENCE = 2
BASE_CLASSES_ONLY = 3
class GraphCycleDetector:
def __init__(self, visitor):
self.node_is_in_path =... | StarcoderdataPython |
52148 | #!/usr/bin/env python
from ciscoconfparse import CiscoConfParse
cisco_cfg = CiscoConfParse("cisco_ipsec.txt")
cry_map = cisco_cfg.find_objects(r"^crypto map CRYPTO")
for cr in cry_map:
print cr.text
for child in cr.children:
print child.text
| StarcoderdataPython |
181392 | <filename>tests/test_reduce_model.py
"""Test align model."""
import numpy as np
import embeddix
def test_align_model():
A = np.array([[0], [1], [2], [3], [4], [5]])
vocab = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'X': 4, 'Z': 5}
shared = {'D': 0, 'C': 1, 'B': 2, 'A': 3}
model = embeddix.reduce_dense(A, voca... | StarcoderdataPython |
4804012 | <reponame>jasasonc/pyidi
import numpy as np
class IDIMethod:
"""Common functions for all methods.
"""
def __init__(self, video, *args, **kwargs):
"""
The image displacement identification method constructor.
For more configuration options, see `method.configure()`
"""... | StarcoderdataPython |
132170 | <reponame>Jonghyun-Kim-73/SAMG_Project<filename>Table_6_6.py<gh_stars>0
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class table_6_6(QWidget):
""" 중간 디스플레이 위젯 """
qss = """
QWidget {
background: rgb(221, 221, 221);
}
... | StarcoderdataPython |
1714282 | <filename>arte/photometry/normalized_star_spectrum.py
import synphot
from synphot import SourceSpectrum
from arte.photometry.spectral_types import PickelsLibrary
from arte.photometry.filters import Filters
def get_normalized_star_spectrum(spectral_type, magnitude, filter_name):
"""
spec_data = get_normalized... | StarcoderdataPython |
3356924 | from sikuli import *
from subprocess import Popen
setAutoWaitTimeout(10)
Popen(["google-chrome",
"--no-default-browser-check",
"--make-default-browser"
"--no-sandbox",
"--start-maximized",
"--disable-save-password-bubble",
#"--proxy-server=... | StarcoderdataPython |
3206501 | <filename>pyfuzzy_toolbox/fis.py
import mf
class FuzzySet(object):
"""docstring for FuzzySet"""
TRIMF = 'trimf'
def __init__(self, name, params, _range, type=TRIMF):
self.name = name
self.type = type
self.params = params
self.range = _range
def _get_mf(self, input_v... | StarcoderdataPython |
3398347 |
import dash
import dash_core_components as dcc
from dateutil import rrule, parser
import dash_html_components as html
import plotly.express as px
import pandas as pd
import plotly.graph_objs as go
from plotly.subplots import make_subplots
from data_processing.read_csv import Data
from datetime import date
""" Predict... | StarcoderdataPython |
3303887 | <gh_stars>1-10
import datetime
from yahoo_fin.stock_info import get_stats
# This is a Python set which is nice because we can not
# get any duplication of data...
symbols = {"ui", "psa", "ip", "t"}
symbols.add("nly")
def get_day():
x = datetime.datetime.now()
y = x.strftime("%y-%m-%d")
return y
def bui... | StarcoderdataPython |
1603756 | <reponame>ekaputra07/django-menuz<filename>menuz/tests/test_template_tags.py
from django.test import TestCase
from django.test.utils import override_settings
from django.test.client import RequestFactory
from django.template import Template, RequestContext, TemplateSyntaxError
from django.db import models
from menuz.m... | StarcoderdataPython |
4835066 | <filename>agavepy/attic/tokens/utils.py<gh_stars>10-100
__all__ = ['tokens_url']
def tokens_url(tenant_url):
"""Returns the tokens API endpoint
"""
return '{0}/token'.format(tenant_url)
| StarcoderdataPython |
1602439 | <reponame>cfrs7xx/OLD
__author__ = 'khanta'
__author__ = 'tschlein'
from subprocess import call
import os
import configparser
import platform
def be_call(filename, path, configfile, verbose):
status = True
error = ''
logfile = ''
if verbose >= 2:
print(' [+] Entering be_call: ')
config = c... | StarcoderdataPython |
1783401 | <gh_stars>0
# -*- coding: utf-8 -*-
"""MRI waveform import/export files.
"""
import numpy as np
import struct
__all__ = ['signa', 'ge_rf_params', 'philips_rf_params']
def signa(wav, filename, scale=-1):
"""Write a binary waveform in the GE format.
Args:
wav (array): waveform (gradient or RF), may b... | StarcoderdataPython |
82967 | import numpy as np
import os
from .. import Globals
import PyFileIO as pf
def _ReadTestPos():
fname = Globals.ModulePath+"__data/testpos.dat"
return pf.ReadASCIIData(fname)
| StarcoderdataPython |
1719266 | <reponame>maxvonhippel/AttackerSynthesis
# ==============================================================================
# File : Characterize.py
# Author : <NAME> and <NAME>
# Authored : 30 November 2019 - 13 March 2020
# Purpose : Checks when models do or do not satisfy properties. Also inter-
# ... | StarcoderdataPython |
3369674 | import pandas
from pandas import DataFrame
import matplotlib.pyplot as plt
csv_file = "test.csv"
df = pandas.read_csv(csv_file)
iterations = df['iteration']
optimizer1 = df['optimizer1']
optimizer2 = df['optimizer2']
#dataFrame.plot(x = 'optimizer1', y = 'iteration', kind = 'line')
plt.plot(optimizer1, iterations,... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.