id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
1874352 | <gh_stars>1-10
from django.urls import path
from administracao.views import (
IndexAdministracaoView,
AdministracaoSearchView,
)
urlpatterns = [
path('', IndexAdministracaoView.as_view(), name='index-administracao'),
path('busca/', AdministracaoSearchView.as_view(), name='busca-ad'),
]
| StarcoderdataPython |
398521 | # Copyright © 2019 Province of British Columbia
#
# 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 agr... | StarcoderdataPython |
386455 | <gh_stars>0
from django.urls import path
app_name = "{{django_app_name}}-api"
urlpatterns = [
] | StarcoderdataPython |
4843926 | # this is not right
# i am not a dictionary
# I am your Brain..
# This is just a random text..
# Don't try to make sense of everything
import this | StarcoderdataPython |
6503560 | from __future__ import absolute_import
from kafka.protocol.api import Request, Response
from kafka.protocol.types import Int16, Int32, Int64, String, Array, Schema, Bytes
class ProduceResponse_v0(Response):
API_KEY = 0
API_VERSION = 0
SCHEMA = Schema(
('topics', Array(
('topic', Strin... | StarcoderdataPython |
1694647 | # Licensed to the StackStorm, Inc ('StackStorm') 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
# (the "License"); you may not use th... | StarcoderdataPython |
3491941 | from functools import partial
from typing import *
import attr
import dlms_cosem.utils
from dlms_cosem import a_xdr, cosem, dlms_data
from dlms_cosem import enumerations as enums
from dlms_cosem.cosem import selective_access
from dlms_cosem.dlms_data import (
VARIABLE_LENGTH,
AbstractDlmsData,
DlmsDataFac... | StarcoderdataPython |
6613473 | # -*- coding: utf-8 -*-
import abc
import torch.nn as nn
from DLtorch.base import BaseComponent
import DLtorch.utils.torch_utils as torch_utils
class BaseModel(BaseComponent):
def __init__(self):
super(BaseModel, self).__init__()
self.logger.info("Module Constructed.")
self.logger.info(... | StarcoderdataPython |
4950912 | <filename>CommonTools/ParticleFlow/python/Isolation/pfElectronIsolation_cff.py
import FWCore.ParameterSet.Config as cms
from RecoParticleFlow.PFProducer.electronPFIsolationDeposits_cff import *
from RecoParticleFlow.PFProducer.electronPFIsolationValues_cff import *
pfElectronIsolationTask = cms.Task(
electronPFIs... | StarcoderdataPython |
11329958 | """empty message
Revision ID: <KEY>
Revises: <PASSWORD>
Create Date: 2017-09-23 21:30:06.863897
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto ... | StarcoderdataPython |
9763216 | """Common configure functions for nat"""
# Python
import logging
# Unicon
from unicon.core.errors import SubCommandFailure
log = logging.getLogger(__name__)
def configure_nat_in_out(
device,
inside_interface=None,
outside_interface=None,
):
""" Enable nat IN and OUT over interface
Args:
... | StarcoderdataPython |
1791238 | <filename>SLpackage/private/pacbio/pythonpkgs/pbsvtools/lib/python2.7/site-packages/pbsvtools/tasks/scatter_align_json_to_svsig.py
#! python
"""
Scatter inputs of pbsvtools.tasks.align_json_to_svsig
align takes two inputs:
Input: idx 0 - datastore.json containing a list of AlignmentSet files,
o... | StarcoderdataPython |
12804189 | <gh_stars>0
import math
line = input().split()
n = int(line[0])
m = int(line[1])
a = int(line[2])
answer = math.ceil(m/a) * math.ceil(n/a)
print(str(int(answer)))
| StarcoderdataPython |
3212513 | # Copyright (c) 2019, <NAME> - SW Consulting. All rights reserved.
# For the licensing terms see LICENSE file in the root directory. For the
# list of contributors see the AUTHORS file in the same directory.
from conans import ConanFile, CMake, tools
from os import sep
class VTKDicomConan(ConanFile):
name = "vtk_... | StarcoderdataPython |
310953 | <reponame>showa-yojyo/bin
#!/usr/bin/env python
"""async14tcpclient.py: TCP Echo client protocol
Assume that sync14tcpserver.py is running in another console.
Usage:
async14tcpclient.py
"""
import asyncio
async def tcp_echo_client(message, loop):
reader, writer = await asyncio.open_connection(
'127.0.... | StarcoderdataPython |
4918078 | <filename>prometheus/monitoring.py
import requests
from prometheus.metrics import Metrics, BatchMetrics
from prometheus.utils import Time, TimeSince
from prometheus import settings
class Monitor:
metrics_cls = Metrics
def __init__(self, app_name):
self.app_name = app_name
self.metrics = self.... | StarcoderdataPython |
141674 | """
Nose2 Unit Tests for the clusters module.
"""
from pprint import pprint
from os import environ, getenv
from atlasapi.atlas import Atlas
from atlasapi.organizations import Organization
from atlasapi.teams import TeamRoles
from atlasapi.atlas_users import AtlasUser
from json import dumps
from tests import BaseTests... | StarcoderdataPython |
105502 | from __future__ import absolute_import
from rest_framework import status
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint, ProjectSettingPermission
from sentry.api.serializers import serialize
from sentry.api.serializers.rest_framework.rule import RuleSerializer
from s... | StarcoderdataPython |
9738390 | <filename>overload/pvf/queries.py
# constructs Z3950/SierraAPI/PlatformAPI queries for particular resource
import logging
from pymarc import Record
from connectors.sierra_z3950 import Z3950_QUALIFIERS, z3950_query
from bibs.patches import remove_oclc_prefix
from logging_setup import LogglyAdapter
module_logger = Lo... | StarcoderdataPython |
6523937 | from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext as _
class MyMoneyAuthenticationForm(AuthenticationForm):
"""
Override default authentication form for theming only.
"""
def __init__(self, request=None, *args, **kwargs):
super(MyMoneyAuthe... | StarcoderdataPython |
11389606 | <gh_stars>0
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split(' ')
if len(words) != len(pattern):
return False
hashmap = {}
mapval = {}
for i in ... | StarcoderdataPython |
95666 | <filename>morsecodetoolkit/data/__init__.py
from morsecodetoolkit.data.synthetic_dataset import SyntheticMorseDataset
__all__ = [
"SyntheticMorseDataset"
]
| StarcoderdataPython |
6613105 | """Sourcefile containing deck builder class for decks with multiple cards"""
from collections import OrderedDict
from copy import deepcopy
from archiTop.base_classes import DeckBuilder
from archiTop.resources import (card_asset_template, card_deck_template,
card_template)
from archiTop.... | StarcoderdataPython |
4842252 | known_users = ['admin', 'root', 'administrator', 'cisco', 'guest', 'sa', 'nsroot', 'super', 'ubnt']
| StarcoderdataPython |
4879193 | #-*-coding: UTF-8-*-
import numpy as np
import random
import math
import matplotlib.pyplot as plt
from LHSamples import Sample
import os
############################################
def dispPulse (t,Dp,t1,Tp):
"""
Baker et al. displacement pulse point value (cm)
:param t: time point(s)
:param Dp: perman... | StarcoderdataPython |
1777867 | #!/usr/bin/env python
# encoding: utf-8
from t import T
import requests,urllib2,json,urlparse
class P(T):
def __init__(self):
T.__init__(self)
def verify(self,head='',context='',ip='',port='',productname={},keywords='',hackinfo=''):
target_url = "http://"+ip+":"+str(port)+"/plugins/weathermap/e... | StarcoderdataPython |
304008 | <reponame>winkemoji/snmp-collector
import subprocess
import traceback
def start():
res = subprocess.run(['python', 'superserver.py'])
if res.returncode!=0:
raise Exception
def main():
try:
start()
except BaseException as e:
traceback.print_exc()
if __name__ == '__main__':
... | StarcoderdataPython |
258393 | #!/usr/bin/env python3
try:
import systemd.daemon
from systemd import journal
systemd_enable=True
except ImportError:
systemd_enable=False
def ready():
if systemd_enable:
systemd.daemon.notify('READY=1') | StarcoderdataPython |
11365190 | # -*- coding: utf-8 -*-
from unittest import TestCase
from mypretty import httpretty
# import httpretty
import harvester.fetcher as fetcher
from test.utils import LogOverrideMixin
from test.utils import DIR_FIXTURES
class PreservicaFetcherTestCase(LogOverrideMixin, TestCase):
@httpretty.activate
def testPrese... | StarcoderdataPython |
11318390 | from __future__ import annotations
from mentormatch.api.applicant.applicant_abc import Applicant
from mentormatch.utils import ApplicantType
from typing import TYPE_CHECKING, Dict
if TYPE_CHECKING:
from mentormatch.api.sorter.sorter_abc import Sorter
class Mentor(Applicant):
applicant_type = ApplicantType.ME... | StarcoderdataPython |
8060585 | <reponame>AmudhanManisekaran/AI-Cop
import os
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score
from sklearn.externals import joblib
from skimage.io import imread
from skimage.filters import threshold_otsu
# letters = [
# '0', '1', '2', '3', '4', '5', '6', '... | StarcoderdataPython |
12816628 | <filename>src/UCB.py<gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
class UCB:
def __init__(self, avg: np.ndarray):
self.true_means = avg # true means of the arms
self.num_arms = avg.size # num arms (k)
self.best_arm = int(np.argmax(self.true_means)) # True best arm
... | StarcoderdataPython |
1959680 | <gh_stars>1-10
# -*- coding:utf-8 -*-
# Author: <NAME> <<EMAIL>>, <<EMAIL>>
# License: Apache-2.0 license
# Copyright (c) SJTU. ALL rights reserved.
from __future__ import absolute_import, division, print_function
import numpy as np
import math
def gaussian_label(label, num_class, u=0, sig=4.0):
"""
Get gaus... | StarcoderdataPython |
11358513 | <filename>papermerge/test/test_tags.py
from pathlib import Path
from django.test import TestCase
from papermerge.core.models import (
Document,
Folder,
Tag
)
from papermerge.test.utils import create_root_user
# points to papermerge.testing folder
BASE_DIR = Path(__file__).parent
class TestDocument(TestC... | StarcoderdataPython |
5040017 | <filename>2_Python Advanced/7_Gui/21_progressBar.py
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 23:57:18 2018
@author: SilverDoe
"""
from tkinter import *
from tkinter.ttk import Progressbar
from tkinter import ttk
window = Tk()
window.title("Welcome to LikeGeeks app")
window.geometry('350x200')
style = ttk.St... | StarcoderdataPython |
8037081 | from .dicts import JSONDecodeError
from .dicts import JsonDict
from .dicts import ReadOnlyJsonDict
from .exceptions import DataIntegrityError
from .exceptions import KeyDoesExistError
from .exceptions import KeyDoesNotExistError
from .exceptions import PeerDoesExistError
from .exceptions import PeerDoesNotExistError
f... | StarcoderdataPython |
6597120 | #it includes part of the code of the image_registration repository
"""Copyright (c) 2012 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitati... | StarcoderdataPython |
1682101 | from ydk.services import CRUDService
from ydk.providers import NetconfServiceProvider
from ydk.models.cisco_ios_xe import Cisco_IOS_XE_interfaces_oper as xe_interface
import device
ios_xe = device.xe_sandbox()
# EXERCISE : Construct an instance of the NetconfServiceProvider class.
# Use the YDK documentation on NETCON... | StarcoderdataPython |
8006871 | from six import wraps
class Response(object):
"""
Transloadit http Response Object
:Attributes:
- data (dict):
Dictionary representation of the returned JSON data.
- status_code (int):
HTTP response status code
- headers (dict):
Dictionary repre... | StarcoderdataPython |
137298 | <reponame>joegomes/BasicSR<gh_stars>1-10
import math
import numpy as np
import torch
def cubic(x):
"""cubic function used for calculate_weights_indices."""
absx = torch.abs(x)
absx2 = absx**2
absx3 = absx**3
return (1.5 * absx3 - 2.5 * absx2 + 1) * (
(absx <= 1).type_as(absx)) + (-0.5 * ab... | StarcoderdataPython |
176985 | <reponame>raphael-abrantes/exercises-python
from random import randint
from time import sleep
from operator import itemgetter #usando pra pegar uma parte do dicionario 0 = chave / 1 = valor
jogo = dict()
rank = list()
cont = 0
while True:
num = randint(1,6)
if num not in jogo.values():
cont... | StarcoderdataPython |
9722038 | <gh_stars>0
from unittest import IsolatedAsyncioTestCase
from src.pyscoresaber import ScoreSaberAPI, NotFoundException
class TestScoreSaber(IsolatedAsyncioTestCase):
valid_player_ids = [
"76561198029447509",
"76561198333869741",
"76561198187936410",
"76561198835772160",
"7... | StarcoderdataPython |
5118129 | <filename>gym_tak/tak/game/tak_game.py
from gym_tak.tak.board import Presets, Board
from gym_tak.tak.piece import Colors, Types
from gym_tak.tak.player import Player
class TakGame:
def __init__(self, preset: Presets, player1: str, player2: str) -> None:
super().__init__()
self.preset = preset
... | StarcoderdataPython |
5055374 | <filename>ccxt_rate_limiter/okex.py
# not accurate
def okex_wrap_defs():
# https://github.com/ccxt/ccxt/blob/master/python/ccxt/okex.py#L104
return [
{
'regex': 'Get|Post|Delete',
'tags': ['all'],
'count': 1,
},
{
'regex': 'Get.*(Position|B... | StarcoderdataPython |
1722037 | <filename>apps/courses/models.py<gh_stars>10-100
# -*-coding:utf-8-*-
# -------------------python--------------
from __future__ import unicode_literals
from datetime import datetime
import sys
# -------------------django---------------
from django.db import models
# -------------------model----------------
from organiz... | StarcoderdataPython |
8002340 | import click
from testplan.cli.utils.command_list import CommandList
from testplan.importers.cppunit import CPPUnitResultImporter
from testplan.importers.gtest import GTestResultImporter
reader_commands = CommandList()
def with_input(fn):
return click.argument(
"source", type=click.Path(exists=True), re... | StarcoderdataPython |
11332366 | <filename>cogs/admin.py
import discord
from discord.ext import commands
from logging import info
import jishaku
import os
import sys
from core.database import SQL # pylint: disable=import-error
from core.files import load_locales
class Admin(commands.Cog):
def __init__(self, bot):
"""Комманды для владель... | StarcoderdataPython |
6583992 | <reponame>walkr/ciex<gh_stars>0
# Utility functions
import sys
from ciex.contrib.workers.elixir import *
from ciex.contrib.workers.golang import *
def load_contrib_worker(worker_name):
""" Load a local worker """
return globals()[worker_name]
def load_other_worker(worker_dirpath, worker_modname, worker_na... | StarcoderdataPython |
3224889 | <gh_stars>0
def add_numbers(x, y):
"""Add numbers together"""
if type(x) != int or type(y) != int:
return None
return x + y
| StarcoderdataPython |
3469407 | <gh_stars>0
# Copyright 2019 The Feast Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | StarcoderdataPython |
6425558 | from typing import List, Optional, Tuple
import numpy as np
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
from .utils import discretize_points, offset_points, trilinear_interp
from .base import Explicit3D
from .._C.rep import _ext
MAX_DEPTH = 10000.0
class VoxelGrid(Expl... | StarcoderdataPython |
1825092 | import json
import os
import sys
def get_installed_modules():
txt = []
for line in os.popen(f'"{sys.executable}" -m pip list --format json'):
txt.append(line)
if not txt:
return {}
data = {}
for (name, version) in map(lambda x: x.values(), json.loads("".join(txt))):
data[name.lower()] = version
return d... | StarcoderdataPython |
6554058 | <filename>app.py
from flask import Flask, render_template, request, Response, make_response
from analysis.user_base import IDGenerator
from analysis.user_handling import UserCreator, UserHandler, UserPairHandler, all_matches
from config import PREVENT_SERVER_CRASH
app = Flask(__name__)
@app.route("/", methods=["GET... | StarcoderdataPython |
3509996 | import sys
import numpy as np
import pdb
class StaticFns:
@staticmethod
def termination_fn(obs, act, next_obs):
assert len(obs.shape) == len(next_obs.shape) == len(act.shape) == 2
notdone = np.isfinite(next_obs).all(axis=-1) \
* (np.abs(next_obs[:,1]) <= .2)
do... | StarcoderdataPython |
6656854 | <reponame>mgielda/hwt<gh_stars>0
from hwt.hdl.types.hdlType import HdlType
class HStream(HdlType):
"""
Stream is an abstract type. It is an array with unspecified size.
:ivar elmType: type of elements
"""
def __init__(self, elmType):
super(HStream, self).__init__()
self.elmType =... | StarcoderdataPython |
4920833 | '''
Functions for loading the zBUS, PA5 and RPcoX drivers and connecting to the
specified device. In addition to loading the appropriate ActiveX driver, some
minimal configuration is done.
Network-aware proxies of the zBUS and RPcoX drivers have been written for
TDTPy. To connect to TDT hardware that is running... | StarcoderdataPython |
3304378 | <gh_stars>1-10
import datetime
import time
import boto3
from unittest import TestCase
from mock import MagicMock
from src.cloudwatch_metrics_client.cloudwatch import CloudWatchSyncMetrics, CloudWatchSyncMetricReporter
class TestCloudwatch(TestCase):
def setUp(self) -> None:
boto3.client = MagicMock()
... | StarcoderdataPython |
8135929 | from django.urls import path
from . import views
urlpatterns=[
path("",views.index,name="index"),
path("register",views.register,name="register"),
path("login",views.login,name="login"),
path("logout",views.logout,name="logout")
] | StarcoderdataPython |
6475949 | <reponame>busterb/attackerkb-api<filename>tests/test_read.py<gh_stars>1-10
import pytest
import os
from attackerkb_api import AttackerKB, ApiError
API_KEY = os.environ.get("API_KEY")
def test_api_fail():
with pytest.raises(ApiError):
api = AttackerKB(api_key="")
def test_api():
api = AttackerKB(api_k... | StarcoderdataPython |
3212227 | <filename>Python/SampleScripts/simple_form.py
#!/usr/bin/python
# Import the CGI module
import cgi
# Required header that tells the browser how to render the HTML.
print "Content-Type: text/html\n\n"
# Define function to generate HTML form.
def generate_form():
print "<html>\n"
print "<head>\n"
print "\t<meta con... | StarcoderdataPython |
1604769 | from typing import Iterable, Union, TYPE_CHECKING
from dotty_dict import Dotty
from marshmallow import Schema
from marshmallow.fields import Nested, Dict, List
if TYPE_CHECKING:
from ddb.feature import Feature
def _get_stop_fields_from_schema(schema: Schema, stack, ret):
for field_name, field in schema.fiel... | StarcoderdataPython |
11316199 | <filename>plot_result.py
import numpy as np
import argparse
import matplotlib.pyplot as plt
import copy
import scipy.io as sio
if __name__ == '__main__':
trial = 50
K = 20
N = 1
SNR = 100
B = 0
E = 1
lr = 0.05
PL = 3.0
P_r = 0.1
iid = 1
noniid_level = 2
loc = 50
kap... | StarcoderdataPython |
3527698 | import os, sys, subprocess
import glob
import datetime
import random
import pyttsx3
import time
import psutil
import speech_recognition as sr
import webbrowser
import requests
#for voice in voices:
# print(voice, voice.id)
def stop(program):
try:
for pid in (process.pid for process in psutil.process... | StarcoderdataPython |
8054055 | <gh_stars>100-1000
import pytest
@pytest.mark.php_fpm
def test_ping(host):
cmd = host.run("php-fpm-healthcheck")
assert cmd.rc == 0
@pytest.mark.php_fpm
def test_ping_verbose(host):
cmd = host.run("php-fpm-healthcheck -v")
assert cmd.rc == 0
assert "Trying to connect to php-fpm via:" in cmd.stdout... | StarcoderdataPython |
3209 | <gh_stars>10-100
# Generated by Django 2.1.7 on 2019-08-09 09:36
from django.db import migrations, models
def migrate_public_event(apps, schema_editor):
"""Migrate options previously with no contents (displayed as "Other:")
to a new contents ("other").
The field containing these options is in CommonReque... | StarcoderdataPython |
168853 | from huobi import RequestClient
request_client = RequestClient()
trade_statistics = request_client.get_24h_trade_statistics("btcusdt")
print("---- Statistics ----")
print("Timestamp: " + str(trade_statistics.timestamp))
print("High: " + str(trade_statistics.high))
print("Low: " + str(trade_statistics.low))
print("Ope... | StarcoderdataPython |
1620555 | <reponame>Naopil/EldenBot<gh_stars>0
import discord
from util.exception import InvalidArgs, NotFound
class CmdReaction:
async def cmd_addreaction(self, *args : str, client, channel, message, **_):
if len(args) < 2:
raise InvalidArgs("Invalid syntax, ``/addreaction message_id emoji_name``")
... | StarcoderdataPython |
4890456 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import sys
from setuptools.command.test import test as TestCommand
#try:
# import multiprocessing # Workaround for http://bugs.python.org/issue15881
#except ImportError:
# pass
# Pytest
class PyTest(TestCommand):
def finalize_opt... | StarcoderdataPython |
9602237 | times = int(input())
# the whole alphabet
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for i in range(times):
characters = {char.lower() for char in list(input().rstrip())} # test with set instead of list
#removed... | StarcoderdataPython |
1963411 | <filename>rnn_model.py
import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn
from tensorflow.contrib import legacy_seq2seq
class RNNModel:
def __init__(self,
vocabulary_size,
batch_size,
sequence_length,
hidden_layer_size... | StarcoderdataPython |
3587317 | # Generated by Django 2.1.7 on 2019-03-09 06:44
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
('core', '0005_auto_20190309_0304'),
... | StarcoderdataPython |
4940169 | # ch8ex7_goldbachc
"""Has the find_prime_summands(n) and its supporting functions."""
from math import sqrt, floor
def find_prime_summands(n):
"""Find two primes that add up to n.
Parameters:
n - even natural number"""
if n % 2 == 1:
return None, None
prime = 1
for i in range(n//2):
... | StarcoderdataPython |
5051749 | from flask import request
from flask_restplus import fields, Namespace, Resource
from http import HTTPStatus
from typing import Dict, List
from .. import API_V1
from ..models import Brand
from ..repos import BRANDS
from ..shared.constants import (AUTHORIZATION_HEADER_DESC, NOT_FOUND,
SUC... | StarcoderdataPython |
6618477 | # -*- coding: utf-8 -*-
'''
Connection module for Elasticsearch
notice: early state, etc.
:depends: elasticsearch
'''
# TODO
# * improve error/ exception handling
# * implement update methods?
from __future__ import absolute_import
# Import Python libs
import logging
log = logging.getLogger(__name__)
# Import thi... | StarcoderdataPython |
1860001 | <gh_stars>100-1000
# Copyright (c) 2017, 2018, 2019, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.T... | StarcoderdataPython |
6463649 | """Marsha URLs configuration."""
from django.conf import settings
from django.urls import include, path, re_path
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import get_schema_view
from marsha.core import models
from marsha.core.ad... | StarcoderdataPython |
1643202 | <gh_stars>0
import logging
import pyqtgraph as pg
import numpy as np
from matplotlib import cm as mcmaps, colors as mcolors
from PyQt5 import QtWidgets, QtCore, QtGui
from collections import OrderedDict
from irrad_control.gui.widgets.util_widgets import GridContainer
# Matplotlib default colors
_MPL_COLORS = [tuple(ro... | StarcoderdataPython |
8120549 | import os, hashlib, warnings, requests, json
import base64
from Crypto.Cipher import DES3
class PayTest(object):
"""this is the getKey function that generates an encryption Key for you by passing your Secret Key as a parameter."""
def __init__(self):
pass
def getKey(self,secret_key):
has... | StarcoderdataPython |
3248535 | import numpy as np
import pickle
lexicon = []
with open('ptb.txt','r') as f:
contents = f.readlines()
for l in contents[:len(contents)]:
all_words=l.split()
lexicon += list(all_words)
lexicon = list(set(lexicon));
print(lexicon)
vocb_size=len(lexicon)+1
print('vocb_size', vocb_size... | StarcoderdataPython |
12816082 | <gh_stars>0
def linear_search(arr, n, x):
for i in range(n):
if arr[i] == x:
return True
return False
arr = [23,512,214,12,5,67,1,4,65]
result = linear_search(arr, len(arr), 214)
print('Search Element is found', result)
| StarcoderdataPython |
5147365 | # -*- coding: utf-8 -*-
""" systemcheck - A Python-based extensive configuration validation solution
systemcheck is a simple application that has two primary functions:
* Compare the configuration of a specific system parameters against a list of desired values
* Document the configuration of a specific system.
... | StarcoderdataPython |
5002959 | from monitor import *
runner = monitor()
print 'valid classifier', runner.valid_S2L()
print 'valid CLM:', runner.valid_L2S() | StarcoderdataPython |
278867 | # -*- coding: utf-8 -*-
"""Parser for Extensible Storage Engine (ESE) database files (EDB)."""
import pyesedb
from plaso.lib import specification
from plaso.parsers import interface
from plaso.parsers import logger
from plaso.parsers import manager
from plaso.parsers import plugins
class ESEDatabase(object):
"""E... | StarcoderdataPython |
1732819 | import os
import glob
from PIL import Image
import numpy as np
import random
image_dir = "[DIRECTORY OF SCRAPED IMAGES]"
out_dir = "./out_pruned_images"
os.makedirs(out_dir, exist_ok=True)
filelist = glob.glob(os.path.join(image_dir, "*.png"))
random.shuffle(filelist)
uninteresting_count = 0
uninteresting_sat_stdevs ... | StarcoderdataPython |
6571021 | """Resolve import locations and type hints."""
from functools import lru_cache
from importlib import import_module
from typing import Optional, Tuple, Any, Union
from ..parse import Name, NameBreak
def resolve_location(chain: Name) -> Optional[str]:
"""Find the final type that a name refers to."""
comps = []
... | StarcoderdataPython |
11238972 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 23 16:36:03 2019
@author: yanik
"""
import cv2
from math import sqrt, pi, cos, sin
import numpy as np
image = cv2.imread("./Material/marker.png")
row, col, ch = image.shape
#Apply Gaussian Blur
blur = cv2.GaussianBlur(image,(5,5),0)
#Convert image to ... | StarcoderdataPython |
3561365 | <reponame>nightlyds/library-basic-authentication-server<filename>order/serializers.py<gh_stars>0
from rest_framework import serializers
from .models import Order
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = ('id', 'user', 'book', 'created_at', 'end_at', 'p... | StarcoderdataPython |
5037081 | <filename>puzzle.ixtutorial/plugins/inventory/tutorial_inventory.py
# copyright, author, ...
DOCUMENTATION = '''
name: tutorial_inventory
plugin_type: inventory
short_description: generate random hostname
description:
- A (useles) example inventory for our tutorial.
- Creates inventory ... | StarcoderdataPython |
152669 | <gh_stars>0
class AuthFailed(Exception):
pass
class SearchFailed(Exception):
pass
| StarcoderdataPython |
3512310 | <reponame>Kortemme-Lab/covariation<filename>analysis/utils/pdb.py<gh_stars>1-10
#!/usr/bin/env python2
# encoding: utf-8
# The MIT License (MIT)
#
# Copyright (c) 2015 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Sof... | StarcoderdataPython |
8037223 | horizontal = 0
depth = 0
aim = 0
instructions = []
with open("Day02.txt", "r") as f:
data = f.read()
data = data.splitlines()
for i in data:
instructions.append(i.split(" "))
for i in instructions:
i[1] = int(i[1])
def part1(depth, horizontal):
for items in instructions:
i... | StarcoderdataPython |
11358353 | <reponame>inhumantsar/fr2ics
from os.path import abspath
import os
import sys
import webbrowser
import nox
try:
from urllib import pathname2url
except:
from urllib.request import pathname2url
def _browser(path):
webbrowser.open("file://" + pathname2url(abspath(path)))
@nox.session(reuse_venv=True, python=['3.... | StarcoderdataPython |
11359575 | <filename>text_extraction/lingpipe.py<gh_stars>1-10
import subprocess
#import xml.dom.minidom
import time
class LingPipe:
path = ''
def __init__(self, pathToLingPipe):
self.path = pathToLingPipe
self.process = subprocess.Popen([self.path],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
def parse(self, text):
... | StarcoderdataPython |
3384442 | <reponame>OsbornHu/tensorflow-ml
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2018/12/8 下午1:52
# 5.6 用TensorFlow实现图像识别
# 1. 导入必要的编程库
import random
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image
from tensorflow.examples.tutorials.mnist i... | StarcoderdataPython |
6564934 | <filename>zobs/orecharge/Point_Analysis/ETRM_Point_SAUA_spider_only.py<gh_stars>1-10
# ===============================================================================
# Copyright 2016 dgketchum
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance
# with th... | StarcoderdataPython |
1796065 | # File name: test_libraries.py
# Author: <NAME>
# Date created: 23-08-2018
"""Tests buf.libraries."""
from unittest import TestCase, mock
import unittest
from buf import libraries
import os
import sys
import tempfile
class TestMakeDir(TestCase):
"""Tests buf.libraries.make_library."""
def test_already_exist... | StarcoderdataPython |
9733997 | <reponame>SideShowBoBGOT/EPAM-project
"""
Module contains classes to work with REST API for Employees.
Classes:
EmployeesAPIget(Resource)
EmployeesAPIadd(Resource)
EmployeesAPIedit(Resource)
EmployeesAPIdel(Resource)
"""
from flask_restful import Resource, abort, reqparse
from flask import redirect
imp... | StarcoderdataPython |
1673420 | <gh_stars>10-100
#import sys
# sys.path.insert(0, '/content/gdrive/MyDrive/Tese/code') # for colab
from src.classification_scripts.SupConLoss.train_supcon import FineTuneSupCon
from src.classification_scripts.ALS.train_ALSingle import FineTuneALS
from src.classification_scripts.cross_entropy.train_ce import FineTuneC... | StarcoderdataPython |
3333503 | # -*- coding:utf-8 -*-
import pytest
from gitticket import github
from gitticket import ticket
from gitticket import config
from gitticket import util
def mock_git():
return {'ticket.name': 'user',
'ticket.repo': 'testrepo',
'ticket.service': 'github',
'ticket.format.list': 'l... | StarcoderdataPython |
5105491 | <gh_stars>0
#!/usr/bin/env python
# concatenator for audit
import pandas as pd
from pathlib import Path
import numpy as np
import subprocess
import os
import sys
csv_dir = sys.argv[1]
#2 *rest*multiband*fsLR_desc-qc_bold.csv
cntr = 0
for csv_path in Path(csv_dir).rglob('sub-*rest*multiband*fsLR_desc-qc_bold.csv'):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.