id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
144971 | <reponame>vdot/mdet<gh_stars>1-10
#!/usr/bin/env python3
import rospy
import numpy as np
from tf import TransformListener
from std_msgs.msg import Empty
from sensor_msgs.msg import PointCloud2
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import TransformStamped
from tf2_sensor_msgs.tf2_sensor_msgs im... | StarcoderdataPython |
4801103 | <filename>ManWeiHiro.py
#!/usr/bin/python
#coding: utf-8
from wordcloud import WordCloud,STOPWORDS
import pandas as pd
import jieba
import sqlite3
import matplotlib.pyplot as plt
#import seaborn as sns
from pyecharts import Geo,Style,Line,Bar,Overlap,Map
import io
import requests
import time
import random
import json... | StarcoderdataPython |
3377989 | <gh_stars>10-100
from rest_framework import serializers
from orchestra.api import router
from orchestra.utils.db import database_ready
from .models import Resource, ResourceData
class ResourceSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField()
unit = serializers.ReadOnlyField... | StarcoderdataPython |
3266438 | #!/usr/bin/env python
import io
import os
import setuptools
setuptools.setup(
name='vxi11aio',
version='0.0.1',
python_requires='>=3.7',
install_requires=['aioserial'],
)
| StarcoderdataPython |
3333282 | from app.models.models import Kongqishidu,Kongqiwendu,Turangshidu,Turangwendu,Guangzhao
from app.tools.orm import ORM
session = ORM.db()
kw = session.query(Kongqiwendu).order_by(Kongqiwendu.create_dt.desc()).first()
print(kw.percent) | StarcoderdataPython |
3207539 | <filename>tests/large_test.py
#!/usr/bin/env python
# Copyright 2016 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import random
import unittest
# Mutates sys.path.
import test_env
from utils import large
... | StarcoderdataPython |
1662999 | #!/usr/bin/env python3
"""Convert JWK from/to PEM and other formats"""
import argparse
import json
from binascii import hexlify
from getpass import getpass
from typing import Optional
from cryptography.hazmat.primitives import serialization
from cryptojwt.jwk import JWK
from cryptojwt.jwk.ec import ECKey
from crypto... | StarcoderdataPython |
3237278 | # coding: utf-8
"""
Masking API
Schema for the Masking Engine API # noqa: E501
OpenAPI spec version: 5.1.8
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import... | StarcoderdataPython |
1693937 | # -*- coding: utf-8 -*-
from pyramid.view import view_config
@view_config(route_name='admin_index',
request_method='GET',
renderer='h:templates/admin/index.html.jinja2',
permission='admin_index')
def index(_):
return {}
def includeme(config):
config.scan(__name__)
| StarcoderdataPython |
3295084 | from django.urls import path
from . import views
urlpatterns = [
path('view-path/', views.my_view, name='view-name'),
]
| StarcoderdataPython |
1617453 | import requests
url = 'http://127.0.0.1:5000/cars/08%20C%201234'
response = requests.delete(url)
print (response.status_code)
print (response.text) | StarcoderdataPython |
3379383 | <filename>.leetcode/68.text-justification.py
# @lc app=leetcode id=68 lang=python3
#
# [68] Text Justification
#
# https://leetcode.com/problems/text-justification/description/
#
# algorithms
# Hard (30.13%)
# Likes: 995
# Dislikes: 1966
# Total Accepted: 168.2K
# Total Submissions: 556.2K
# Testcase Example: '[... | StarcoderdataPython |
3266721 | <gh_stars>0
# --------------
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# code starts here
df = pd.read_csv(path)
# probability of fico score greater than 700
p_a = df[df['fico'].astype(float) >700].shape[0]/df.shape[0]
print(p_a)
# probability of purpose == debt_consolidation
p_b = df... | StarcoderdataPython |
4817909 | from dataclasses import dataclass
from typing import Generator, Any
from datek_jaipur.domain.compound_types.card import Card, CardSet
from datek_jaipur.domain.compound_types.goods import GoodsType
from datek_jaipur.domain.compound_types.player import Player
@dataclass
class Scenario:
name: str
player1: Playe... | StarcoderdataPython |
1676180 | <filename>tests/core/test_path_mapping.py
# Copyright 2020 ScyllaDB
#
# 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 a... | StarcoderdataPython |
3333964 | #!/usr/bin/env python3
# encoding: utf-8
# By @LyricLy
# Public Domain / CC-0 <https://creativecommons.org/publicdomain/zero/1.0/>
import time
from collections import defaultdict
class Entity:
def __init__(self, value):
self.value = value
self.pos = 0
self.vel = value
def move(self):
self.pos += self.vel... | StarcoderdataPython |
1683626 | <filename>backend/app/route/survey/provider.py
from app.api.base.base_sql import Sql
from app.api.base import base_name as names
class Provider:
"""
Класс для работы с товарами
"""
@staticmethod
def post_survey(args):
"""
Занести результаты теста
:param args:
:retur... | StarcoderdataPython |
3202315 | """
========================================================
Filename: test_suite.py
Author: <NAME>
Description:
The test suit constist of a test bench, a testharness
and a set of design files.
The test suite is used for compiling and running
a set of simulations/tests.
(c) 20... | StarcoderdataPython |
1640977 |
from typing import Union
from collections import OrderedDict
from ..api.syntax import TaskDeclaration
from ..api.syntax import GroupDeclaration
from ..inputoutput import SystemIO
STATUS_STARTED = 'started'
STATUS_ERRORED = 'errored'
STATUS_FAILURE = 'failure'
STATUS_SUCCEED = 'succeed'
class QueueItem(object):
... | StarcoderdataPython |
23298 | from flask_wtf import Form
from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField
from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange
from wtforms.widgets import SubmitInput
class SignUp(Form):
username = TextFie... | StarcoderdataPython |
3396265 | <reponame>zeljkofilipin/how-to-code
print("bok")
| StarcoderdataPython |
4834949 | """UniFi sensor platform tests."""
from collections import deque
from copy import deepcopy
from asynctest import patch
from homeassistant import config_entries
from homeassistant.components import unifi
from homeassistant.components.unifi.const import (
CONF_CONTROLLER,
CONF_SITE_ID,
CONTROLLER_ID as CONF... | StarcoderdataPython |
1665447 | from mayan.apps.common.tests.base import GenericViewTestCase
from mayan.apps.documents.tests.base import GenericDocumentViewTestCase
from ..literals import WIDGET_CLASS_TEXTAREA
from ..models import WorkflowTransition
from ..permissions import (
permission_workflow_edit, permission_workflow_transition,
permiss... | StarcoderdataPython |
75643 | from django.contrib import admin
from .models import Quiz, Question, Response
# Register your models here.
class InLineResponse(admin.StackedInline):
model = Response
extra = 0
class InLineQuestion(admin.StackedInline):
model = Question
extra = 0
class QuizAdmin(admin.ModelAdmin):
inlines = [... | StarcoderdataPython |
4812253 | #
# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
#
# SPDX-License-Identifier: GPL-2.0-only
#
from typing import List
from hardware.device import WrappedNode
from hardware.fdt import FdtParser
# documentation for CPU bindings:
# https://www.kernel.org/doc/Documentation/devicetree/bindings/arm/cpus.yaml
def ge... | StarcoderdataPython |
3362516 | #! /usr/bin/env python3
import sys
import numpy as np
import filtering as flt
from time import time
kappa_z_array = np.array([0.01,0.03,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,2,3,4,5,6,7,8,9,10])
# choose a kappa_y according to system variable
kappa_z = kappa_z_array[int(sys.argv[1])]
# pass the number of iteration... | StarcoderdataPython |
3325540 | <gh_stars>1-10
"""Provides a formatter for AoE2 AI rule files."""
from .formatter import format_per
| StarcoderdataPython |
3341903 | <gh_stars>0
"""
Support for Haiku with SenseME ceiling fan and lights.
For more details about this platform, please refer to the documentation at
https://github.com/mikelawrence/homeassistant-custom-components
"""
import logging
import voluptuous as vol
from datetime import timedelta
from homeassistant.const import (... | StarcoderdataPython |
3240882 | from .contacts_helper import ContactsHelper
from .controller import Controller
from .permissions_helper import PermissionsHelper
from forms import DataSourceForm
class DataSourcesController(Controller):
"""Controller for DataSource GUI
Manage data_source and related models from combined GUI.
"""
def... | StarcoderdataPython |
3316128 | # import the necessary packages
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
import argparse
import imutils
import cv2
# construct argument parser and parse arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--cascade", req... | StarcoderdataPython |
1743977 | import pandas as pd
from unittest2 import TestCase # or `from unittest import ...` if on Python 3.4+
import category_encoders as encoders
class TestBackwardsEncoder(TestCase):
def test_backwards_difference_encoder_preserve_dimension_1(self):
train = ['A', 'B', 'C']
test = ['A', 'D', 'E']
... | StarcoderdataPython |
45998 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import web.models
class Migration(migrations.Migration):
dependencies = [
('web', '0006_auto_20150627_1942'),
]
operations = [
migrations.AddField(
model_n... | StarcoderdataPython |
41478 | <reponame>Nabeel965/AgriTechies
from django.http import HttpResponse
from django.shortcuts import render
import joblib
import pandas as pd
import numpy as np
from .models import crop_data
from .recommender import CropDataForm
model = joblib.load('model.pkl')
xl_file = pd.ExcelFile('Features - Rev02.xlsx')
storage_df=x... | StarcoderdataPython |
1783432 | <reponame>scvannost/clustergrammer-py
'''
The clustergrammer python module can be installed using pip:
pip install clustergrammer
or by getting the code from the repo:
https://github.com/MaayanLab/clustergrammer-py
'''
# from clustergrammer import Network
from clustergrammer import Network
net = Network()
# load mat... | StarcoderdataPython |
1708336 | #%%
import os
import sys
import joblib
from numpy.lib.function_base import select
import sklearn
import warnings
import tarfile
import urllib
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from pandas.plotting import scatter_matrix
from... | StarcoderdataPython |
3323710 | <gh_stars>1-10
import arrow
import pandas as pd
WARN_DURATION_VARIATION = 5 * 60 # seconds
MAX_DURATION_VARIATION = 45 * 60 # seconds
def get_expected_config_map_for_calibration(sd):
expected_config_map = {}
for ct in sd.curr_spec["calibration_tests"]:
expected_config_map[ct["id"]] = ct["config"]["sen... | StarcoderdataPython |
62506 | <gh_stars>0
#!/usr/bin/env,python3
#,-*-,coding:,utf-8,-*-
'''
Problem 32
Find the sum of all products whose multiplicand/multiplier/product
identity can be written as a 1 through 9 pandigital.
e.g. 39 × 186 = 7254
'''
import itertools
def tuple_to_jointed_int(tp):
return int(''.join(map(str,tp)))
d... | StarcoderdataPython |
49624 | <reponame>nleguillarme/snr_tools_and_methods
import merpy
merpy.create_lexicon_from_file("ncbi.txt", "ncbi")
merpy.process_lexicon("ncbi")
| StarcoderdataPython |
3329575 | def parse_spec(s):
a, b = s.split("/")
return int(a), int(b)
def compose(*sharders):
sharders = [x for x in sharders if x]
if not sharders:
return identity
def f(stream):
for sharder in sharders:
stream = sharder(stream)
return stream
return f
def from_spec(spec... | StarcoderdataPython |
4841514 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib_venn import venn2
def box_plot(pseudoCount, controlCount):
x = np.arange(2)
counts = [pseudoCount, controlCount]
fig, ax = plt.subplots()
plt.bar(x, counts)
plt.xticks(x, ('Pseudouridine', 'control'))
#save box... | StarcoderdataPython |
3291997 | <filename>ceilometerclient/tests/unit/test_utils.py
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://ww... | StarcoderdataPython |
51206 | from moai.monads.human.pose.openpose import (
Split as OpenposeSplit,
JointMap as OpenposeJointMap
)
__all__ = [
'OpenposeSplit',
'OpenposeJointMap',
] | StarcoderdataPython |
1794664 | <reponame>blakev/stencil<filename>stencil/objects.py
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# >>
# stencil-blog, 2020
# - blake
# <<
import os
from datetime import datetime
from dataclasses import dataclass, field, asdict
from typing import Any, Dict, List, NamedTuple
import toml
class Validation(Name... | StarcoderdataPython |
17494 | <reponame>judge2020/crossover-viz
from main import extract_data
if __name__ == '__main__':
top = {}
out = extract_data('CrossoverWiki.xml')
for name in out:
for link in name['links']:
w = link['with']
top[w] = top[w] + 1 if w in top else 1
top = dict(reversed(sorted(top.... | StarcoderdataPython |
1612228 | <gh_stars>0
# Copyright (C) 2011 Google Inc. 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, this list of conditio... | StarcoderdataPython |
3380145 | #Importing the required libraries
import numpy as np
import matplotlib.pyplot as plt
#Creating a new figure
plt.figure()
#Initializing x and y values
x_values = np.arange(-200, 250, 0.1)
y_values = (x_values - 25)**2 + 20
#Plotting the values of x and y in the output
plt.plot(x_values, y_values, '-m', lw = 2)
#Anno... | StarcoderdataPython |
96633 | <filename>src/utils/pythonSrc/watchFaceParser/models/elements/goalProgress/circularGoalProgressElement.py
import logging
from watchFaceParser.models.elements.common.circularProgressElement import CircularProgressElement
class CircularGoalProgressElement(CircularProgressElement):
def __init__(self, parameter, par... | StarcoderdataPython |
41668 | #!/usr/bin/env python3
import zipfile
# The file to USE inside the zip, before compression
filein = "index.php"
print("[i] FileIn: %s\n" % filein)
# How deep are we going?
depth = ""
# Loop 11 times (00-10)
for i in range(11):
# The .zip file to use
zipname = "depth-%02d.zip" % i
print("[i] ZipName: %s" % zip... | StarcoderdataPython |
3285806 | <filename>auxilearn/hypernet.py<gh_stars>10-100
from abc import abstractmethod
from torch import nn
from torch.nn.utils import weight_norm
class HyperNet(nn.Module):
"""This module is responsible for taking the losses from all tasks and return a single loss term.
We can think of this as our learnable loss cr... | StarcoderdataPython |
1645897 | # -*- coding=utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | StarcoderdataPython |
113233 | from .core import GetJob
# program Design
# get available meshroombot Job
# search in scan directory for the first available folder
# check with rename
# folder name indicated status
# available
# [-] busy
# [#] done
# search in [#] scans for Meshroom/mesh.obj
... | StarcoderdataPython |
34948 | <filename>webtool/server/models/equipment.py
# -*- coding: utf-8 -*-
from django.db import models
from .mixins import SeasonsMixin
from .time_base import TimeMixin
from . import fields
class EquipmentManager(models.Manager):
def get_by_natural_key(self, code):
return self.get(code=code)
class Equipmen... | StarcoderdataPython |
3310938 | # (C) Copyright (2018,2020) Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, ... | StarcoderdataPython |
3227453 | <gh_stars>1-10
# Standard library
# 3rd party packages
import pytest
# Local source
from parametrization_clean.domain.cost.reax_error import ReaxError
@pytest.mark.usefixtures('reax_energies', 'dft_energies', 'weights')
def test_reax_error(reax_energies, dft_energies, weights):
reax_energy = reax_energies[0][0... | StarcoderdataPython |
1692572 | #!/usr/bin/env python3
# Simple test for NeoPixels on Raspberry Pi
import time
import board
import neopixel
# Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18
# NeoPixels must be connected to D10, D12, D18 or D21 to work.
pixel_pin = board.D18
global_brightness=0.2
# The number of Ne... | StarcoderdataPython |
187203 | <reponame>shagun30/djambala-2<gh_stars>0
from django.core import validators
from django.core.exceptions import ImproperlyConfigured
from django.db import backend, connection, models
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext_lazy as _
from django.utils.encodi... | StarcoderdataPython |
3300663 | #
"""Demonstrate WeakValueDictionary.
"""
# end_pymotw_header
import gc
from pprint import pprint
import weakref
gc.set_debug(gc.DEBUG_UNCOLLECTABLE)
class ExpensiveObject:
def __init__(self, name):
self.name = name
def __repr__(self):
return "ExpensiveObject({})".format(self.name)
def... | StarcoderdataPython |
1611454 | <reponame>davidkhala/oci-designer-toolk
# Copyright (c) 2020, 2021, Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
"""Provide Module Description
"""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | StarcoderdataPython |
1707623 | <reponame>tulth/diy-acura-bluetooth<filename>target_desktop/py_lib/mbus/__init__.py
#!/bin/env python
from __future__ import print_function
import sys
import os
import ctypes
from . import nibbles
BIT_TIME = 3100
BIT_ZERO_LOW_TIME = 675
BIT_ONE_LOW_TIME = 1890
BIT_ONEVAL_THRESH_TIME = (BIT_ZERO_LOW_TIME + BIT_ONE_LOW_... | StarcoderdataPython |
3357873 | <filename>eternity_backend_server/blueprints/admin/admin.py
# -*- coding: utf-8 -*-
from flask import (
Blueprint,
current_app,
flash,
redirect,
render_template,
request,
url_for,
abort
)
from flask_login import login_required, login_user, logout_user, current_user
from eternity_backend_... | StarcoderdataPython |
1624952 | import numpy
import matplotlib.pyplot as plot
def relu(arr):
return numpy.maximum(0, arr)
x = numpy.arange(-10, 10, 0.1)
y = relu(x)
plot.plot(x, y, label="Sigmoid function")
plot.xlabel('x')
plot.ylabel('y')
plot.show()
| StarcoderdataPython |
3381310 | <filename>setup.py
#!/usr/bin/env python
from setuptools import setup, find_packages
# Get version string
with open('gdx2py/version.py') as f:
exec(f.read())
with open("README.md", "r") as f:
readme = f.read()
setup(
name='GDX2py',
version=__version__, # pylint: disable=undefined-variable
autho... | StarcoderdataPython |
1652612 | from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Testing basic Http Response in form views.py")
# Create your views here.
| StarcoderdataPython |
25142 | #!/usr/bin/env python
# Lint as: python3
"""E2E tests for the timeline flow."""
import csv
import io
from typing import Sequence
from typing import Text
from absl.testing import absltest
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.util import temp
from grr_response_proto.api import timeline_... | StarcoderdataPython |
1652371 | from PIL import Image
import os
basepath = 'fashionshop\static\img\product\Fragrance'
# os.chdir(basepath)
def save_img(img):
i = Image.open(os.path.join(basepath,img))
t, f_ext = os.path.splitext(i.filename)
text = t.replace("-"," ")
f = text + f_ext
print('infor:',img, i.format, i.size, i.mode)
... | StarcoderdataPython |
162045 | import os
from subaligner.predictor import Predictor
from subaligner.subtitle import Subtitle
if __name__ == "__main__":
examples_dir = os.path.dirname(os.path.abspath(__file__))
output_dir = os.path.join(examples_dir, "tmp")
os.makedirs(output_dir, exist_ok=True)
video_file_path = os.path.join(example... | StarcoderdataPython |
3221604 | <gh_stars>0
# Parameter:
# config-file: path to cfg file
# weight_path: path to the pretrained weight
# dataset_path: path to a directory of images
# This script predicts bboxes of every image in the dataset path,
# write the ground truth into yolo format .txt filess
import argparse
import glob
import multiprocessing... | StarcoderdataPython |
1760424 | #!/usr/bin/env python3
# Mikhail (myke) Kolodin
# testing redis and redis-queue (rq)
# from http://python-rq.org/ etc
# 2016-02-04 2018-05-05 1.4
import redis
import requests
from redis import Redis
from rq import Queue
# test redis itfself
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')... | StarcoderdataPython |
3397105 | import pandas as pd
from sqlalchemy import rgb_db.py
df = pd.read_csv('https://github.com/techthumb1/DS-Unit-3-Sprint-2-SQL-and-Databases/blob/master/module1-introduction-to-sql/buddymove_holidayiq.csv')
df.to_sql('Buddy Move', con) | StarcoderdataPython |
4836765 | <gh_stars>0
# Copyright 2015 IBM Corp.
#
# 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 ... | StarcoderdataPython |
3203793 | <reponame>IssacCyj/RepDistiller
from __future__ import print_function
import os
import argparse
import socket
import time
import tensorboard_logger as tb_logger
import torch
import torch.optim as optim
import torch.nn as nn
import torch.backends.cudnn as cudnn
import numpy as np
from models import model_dict
from d... | StarcoderdataPython |
1625655 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 08:20:26 2021
@author: shane
"""
import dash
import dash_bootstrap_components as dbc
# Meta tags make the app mobile friendly
app = dash.Dash(__name__, suppress_callback_exceptions=True,
external_stylesheets=[dbc.themes.BOOTSTRAP],
meta... | StarcoderdataPython |
23636 | <gh_stars>0
# -*- coding: utf-8 -*-
import argparse
import logging
import os
import re
from .. import __version__
from ..config import ALLOWED_IMAGE_REGEXPS
from ..config import ALLOWED_PORT_MAPPINGS
from ..config import CAPS_ADD
from ..config import CAPS_DROP
from ..config import ENV_VARS
from ..config import ENV_VA... | StarcoderdataPython |
1730961 | <gh_stars>1-10
# ----------------------------------------------------------------------------
# Title: Scientific Visualisation - Python & Matplotlib
# Author: <NAME>
# License: BSD
# ----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from ... | StarcoderdataPython |
3245368 | # ==============================================================================
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
# C... | StarcoderdataPython |
3372161 | <gh_stars>1-10
import pytest
import mock
import pwd
import grp
import subprocess
from collections import namedtuple
from lib.user_management import UserManagement
@mock.patch('pwd.getpwnam')
@pytest.mark.parametrize("login", [("elaine")])
def test_user_exist(mock_pwd, login):
UserManagement.user_exist(login)
... | StarcoderdataPython |
1600399 | <gh_stars>10-100
import torch.nn as nn
from utils import *
from torch.nn.utils.rnn import pad_packed_sequence, pack_sequence, pack_padded_sequence
import Constants
try:
from apex import amp
APEX_AVAILABLE = True
except ModuleNotFoundError:
APEX_AVAILABLE = False
class Trainer(object):
def __init__(se... | StarcoderdataPython |
1763661 | <gh_stars>0
from typing import List, Tuple
import matplotlib.pyplot as plt
import random
from sys import stderr
from parameters import *
"""
Represents an individual in our population (in our case, a path going through
each city exactly once)
"""
class Individual:
# used to assign an individual id for each ind... | StarcoderdataPython |
1644118 | import logging
from botocore.exceptions import ClientError
from library.aws.utility import convert_tags
class EBSOperations:
@staticmethod
def snapshot_make_private(ec2_client, snapshot_id):
"""
Remove public permissions on EBS snapshot
:param ec2_client: EC2 boto3 client
:p... | StarcoderdataPython |
3343697 | # Copyright 2017 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | StarcoderdataPython |
4803420 | import re
import json
from collections import Counter
from transition_amr_parser.amr import JAMR_CorpusReader
import ast
import xml.etree.ElementTree as ET
def read_frame(xml_file):
'''
Read probpank XML
'''
root = ET.parse(xml_file).getroot()
propbank = {}
for predicate in root.findall('... | StarcoderdataPython |
163812 | <reponame>PerimeterX/perimeterx-python-ws<filename>setup-gae.py
#!/usr/bin/env python
from setuptools import setup, find_packages
version = 'v3.2.1'
setup(name='perimeterx-python-wsgi-gae',
version=version,
license='MIT',
description='PerimeterX WSGI middleware for Goolge App Engine',
author='... | StarcoderdataPython |
3251446 | <reponame>Zor-X-L/redis-cluster-manager
#!/usr/bin/env python3
import subprocess
exec(open('common.py').read())
args = ['./redis-trib.rb', 'create', '--replicas', str(config['replicas'])]
for host in config['hosts']:
for port in range(port_range_start, port_range_end):
args.append(host + ':' + str(port)... | StarcoderdataPython |
1696193 | <gh_stars>0
# -*- coding: utf-8 -*-
# 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/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
1718525 | <filename>My Own projects/Playing Songs/main.pyw
import os
from tkinter import *
from tkinter import filedialog
try:
from mutagen.mp3 import MP3
except:
os.system('pip install mutagen')
from mutagen.mp3 import MP3
try:
import pygame
except:
os.system('pip install pygame')
import pygame
import ... | StarcoderdataPython |
49329 | from flask_wtf import FlaskForm
from wtforms import *
from wtforms.validators import InputRequired
class LoginForm(FlaskForm):
username = TextField('username',validators=[InputRequired()])
password = PasswordField('password',validators=[InputRequired()]) | StarcoderdataPython |
1768178 | <filename>pythons_app/views.py
from django.forms.widgets import Media
from django.shortcuts import render, redirect
from .forms import PythonCreateForm
from .models import Python
# Create your views here.
def index(request):
pythons = Python.objects.all()
return render(request, 'index.html', {'pythons': pytho... | StarcoderdataPython |
96677 | <filename>test/unit/test_jinja.py
import unittest
from dbt.clients.jinja import get_template
class TestJinja(unittest.TestCase):
def test_do(self):
s = '{% set my_dict = {} %}\n{% do my_dict.update(a=1) %}'
template = get_template(s, {})
mod = template.make_module()
self.assertEqu... | StarcoderdataPython |
4815611 | <gh_stars>1-10
import pytest
import cv2
import numpy as np
from plantcv.plantcv import roi_objects
@pytest.mark.parametrize("mode,exp", [["largest", 221], ["cutto", 152], ["partial", 221]])
def test_roi_objects(mode, exp, test_data):
"""Test for PlantCV."""
# Read in test data
img = cv2.imread(test_data.s... | StarcoderdataPython |
199359 | """Package setup entrypoint."""
from typing import IO, Sequence
from setuptools import find_packages as __find_packages, setup as __compose_package
from uurl import (
__author__ as __author,
__doc__ as __full_doc,
__email__ as __email,
__license__ as __license,
__name__ as __name,
__version__ as... | StarcoderdataPython |
1732749 | <gh_stars>1-10
"""OTE-API OPTIMADE-specific Python exceptions."""
class BaseOteapiOptimadeException(Exception):
"""Base OTE-API OPTIMADE exception."""
class ConfigurationError(BaseOteapiOptimadeException):
"""An error occurred when dealing with strategy configurations."""
class RequestError(BaseOteapiOpti... | StarcoderdataPython |
3355520 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# --- Rot Motion
freq1= 0.8
freq2= 0.4
tMax = 10
dt = 0.1
omega1 = 2*np.pi*freq1
T1 = 1/freq1
omega2 = 2*np.pi*freq2
T2 = 1/freq2
time = np.arange(0,tMax+dt/2,dt)
pos = np.zeros((len(time), 6)) # positions: x,y,z, theta_x, theta_y, the... | StarcoderdataPython |
52867 | # Топ-3 + Выигрышные номера последнего тиража
def test_top_3_winning_numbers_last_draw(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_top_3()
app.ResultAndPrizes.button_get_report_winners()
assert "ВЫИГРЫШНЫЕ НОМЕРА" in app.ResultAndPrizes.parser_report_text_w... | StarcoderdataPython |
23501 | #--- Exercício 2 - Variáveis
#--- Crie um menu para um sistema de cadastro de funcionários
#--- O menu deve ser impresso com a função format()
#--- As opções devem ser variáveis do tipo inteiro
#--- As descrições das opções serão:
#--- Cadastrar funcionário
#--- Listar funcionários
#--- Editar funcionário
#--... | StarcoderdataPython |
3298557 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# pylint: disable=invalid-name,too-few-public-methods
"""
EM Slack Tableflip module: slack_tableflip.storage.
- Sets database schema for storing user data
- Initializes database structure
Copyright (c) 2015-2016 <NAME>
Permission is hereby granted, fr... | StarcoderdataPython |
61259 | #!/usr/bin/env python3
from setuptools import find_packages, setup
setup(
name="lean_proof_recording",
version="0.0.1",
packages=find_packages(),
package_data={},
install_requires=[
"mpmath",
"pandas",
"jsonlines",
"tqdm",
],
)
| StarcoderdataPython |
6040 | import json
from os import path
from tweepy import OAuthHandler, Stream
from tweepy.streaming import StreamListener
from sqlalchemy.orm.exc import NoResultFound
from database import session, Tweet, Hashtag, User
consumer_key = "0qFf4T2xPWVIycLmAwk3rDQ55"
consumer_secret = "<KEY>"
access_token = "<KEY>"
acces_token_... | StarcoderdataPython |
53358 | from django_datatables_view.base_datatable_view import BaseDatatableView
from django.db.models import Q
from django.contrib.postgres.aggregates.general import ArrayAgg
from website.models import Genome
class GenomeTableAjax(BaseDatatableView):
# The model we're going to show
model = Genome
# set max limi... | StarcoderdataPython |
1772798 | <filename>100-200q/129.py
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [... | StarcoderdataPython |
173816 | "This module holds the mixer state of the X-Air device"
# part of xair-remote.py
# Copyright (c) 2018, 2021 <NAME>
# Additions Copyright (c) 2021 <NAME>
# Some rights reserved. See LICENSE.
import time
import subprocess
import struct
import json
from collections import deque
from lib.xair import XAirClient, find_mixer... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.