id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6406747 | """
Implements /src/Actionable/index.ts
"""
class Actionable:
"""
Enum implementation
"""
class Types:
WOOD = 'wood'
COAL = 'coal'
URANIUM = 'uranium'
def __init__(self, configs, cooldown=0.0) -> None:
"""
:param configs:
:param cooldown:
... | StarcoderdataPython |
11266979 | <reponame>dhyanivikas/stockStalker
'''
Created on Jan 3, 2021
@author: dhyaniv
'''
import mysql.connector
def getconnection():
config = {
"host":"localhost",
"user":"root",
"password":"<PASSWORD>",
"database":"stocks",
"auth_plugin":'mysql_native_password'
}
try:... | StarcoderdataPython |
8190825 | <reponame>talonchandler/polaris
from polaris import spang, util
import numpy as np
from scipy.special import hyp1f1
from dipy.data import get_sphere
import logging
log = logging.getLogger('log')
def three_helix(vox_dim=(130,130,130), px=(64,64,64), radius=600, scale=[1,1,1]):
phant = spang.Spang(np.zeros(px + (15,... | StarcoderdataPython |
273188 | #!/usr/bin/env python
"""fanotify: wrapper around the fanotify family of syscalls for watching for file modifcation"""
from .utils import PermissionError, UnknownError, CLOEXEC_DEFAULT
from collections import namedtuple
from os import O_RDONLY, O_WRONLY, O_RDWR
from os import getpid, readlink
from os import close
from... | StarcoderdataPython |
1977229 | from urllib.parse import urljoin
from scrapy import Request
from product_spider.items import RawData, ProductPackage
from product_spider.utils.functions import strip
from product_spider.utils.spider_mixin import BaseSpider
class AltaSpider(BaseSpider):
name = "alta"
brand = '阿尔塔'
base_url = "http://www.... | StarcoderdataPython |
101298 | <filename>tests/test_ast_db_populator.py
import json
import pytest
from pathlib import Path
from symbol_exporter.ast_db_populator import fetch_and_run
@pytest.mark.skip(reason="output data model not yet stable")
def test_fetch_and_run(tmpdir):
pkg, dst, src_url = (
"botocore",
"conda-forge/noarch... | StarcoderdataPython |
81454 | <reponame>SamirWeAli/DLProject<gh_stars>0
import gym
import numpy as np
from src.population.population import Population
from src.configs import *
class Game:
# Read existing weights.
def read_weights(self, weights_file_path):
file = open(weights_file_path, 'r')
weights_string = file.read().... | StarcoderdataPython |
5144648 | import os
import sys
import tempfile
import datetime
import warnings
import traceback
from collections import namedtuple
import jsonpickle
class Configuration:
TRANSACTION_STORAGE_DIRECTORY = '/tmp/'
TRANSACTION_PREFIX = 'transaction'
CLEANUP = True
CHATTY_EXCEPTIONS = True
class States:
PEN... | StarcoderdataPython |
8167621 | __author__ = 'LiGe'
#encoding:utf-8
import pymongo
import os
import csv
class mongodb(object):
def __init__(self, ip, port):
self.ip=ip
self.port=port
self.conn=pymongo.MongoClient(ip,port)
def close(self):
return self.conn.disconnect()
def get_conn(self):
... | StarcoderdataPython |
129734 | from positional_list import PositionalList
from favoritelist import FavoriteList
# if no. of acess tally, recently acesssed element is returned when top(k) is called
class FavoriteListMTF(FavoriteList):
"""List of elements ordered with move-to-front heuristics."""
# we override _move_up to provide move-to-fron... | StarcoderdataPython |
76979 | <reponame>Koukyosyumei/AIJack
import torch
from matplotlib import pyplot as plt
from ..base_attack import BaseAttacker
class MI_FACE(BaseAttacker):
"""Implementation of model inversion attack
reference: https://dl.acm.org/doi/pdf/10.1145/2810103.2813677
Attributes:
target_model: model of the vic... | StarcoderdataPython |
9668449 | from typing import List
from fastapi import APIRouter, Path, Query
from pydantic import BaseModel
from ..dependancies import model
router = APIRouter()
class WPClass(BaseModel):
class_names: List[str] = model.get_wp_classes()
@router.get(
"/classes/whatplane", response_model=WPClass, status_code=200, tags... | StarcoderdataPython |
3589793 | <filename>cuenta_apariciones.py
cadena = input('Introduce una cadena de texto > ')
dic = dict()
for caracter in cadena:
if caracter in dic.keys():
dic[caracter] = dic[caracter] + 1
else:
dic[caracter] = 1
for k in dic.keys():
print(f'{k}: {dic[k]}') | StarcoderdataPython |
4937288 | # Generated by Django 3.1.14 on 2022-03-04 18:13
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20220304_1810'),
]
operations = [
migrations.AddField(
model_name='user',
... | StarcoderdataPython |
4887329 | # Copyright 2018 Google 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/LICENSE-2.0
#
# Unless required by applicable law or agree... | StarcoderdataPython |
4818963 | # ==============================================================================
# Copyright 2018-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://ww... | StarcoderdataPython |
4841258 | import importlib
import sys
from inspect import isclass
from pathlib import Path
from types import ModuleType
from typing import List, Optional, Union
from loguru import logger
from streams_explorer.core.config import settings
def load_plugin(base_class: type, all: bool = False) -> Union[type, List[type], None]:
... | StarcoderdataPython |
4978535 | <filename>src/train_pipeline/train_model.py
"""Module to train a model with a dataset configuration."""
import json
import operator
import os
import statistics
import torch
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.metrics import pairwise_distances
from torch.utils.data import TensorDat... | StarcoderdataPython |
4981086 | <reponame>DjangoCrypto/django-crypto-extensions<filename>django_crypto_extensions/tests/models.py
# -*- coding: utf-8 -*-
from django.db import models
from django_crypto_extensions.django_fields import (
CryptoTextField,
CryptoCharField,
CryptoEmailField,
CryptoIntegerField,
CryptoDateField,
Cr... | StarcoderdataPython |
4972371 | <reponame>hedwig100/PRML
"""Probability Distribution
This module is about chapter2.
Binary, Multi, Gaussian1D, student's t-distribution, Histgram, Parzen, KNearestNeighbor, KNeighborClassifier
are implemented.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
f... | StarcoderdataPython |
5048792 | <filename>model.py
import numpy as np
from scipy.signal import convolve2d
from specutils.utils.wcs_utils import vac_to_air
from tqdm import tqdm
import astropy.units as u
from hankel import HankelTransform
class SeeingApertureMTF:
"""
This is the class that generates the effective aperture for a given Fried pa... | StarcoderdataPython |
4883332 | <reponame>dtact/pycryptoaddressextract
import re
import base58
import hashlib
import binascii
import coinaddr
from .tokenizer import Tokenizer
bitcoin = re.compile(r"^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,39}$")
ethereum = re.compile(r"^0x[a-fA-F0-9]{40}$")
litecoin = re.compile(r"^[LM3][a-km-zA-HJ-NP-Z1-9]{26,33}$")
moner... | StarcoderdataPython |
132771 | <filename>python/dynamic_graph/sot/torque_control/tests/test_magdwick.py
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 3 14:01:08 2017
@author: adelpret
"""
from dynamic_graph.sot.torque_control.madgwickahrs import MadgwickAHRS
dt = 0.001
imu_filter = MadgwickAHRS('imu_filter')
imu_filter.init(dt)
imu_filter.setBe... | StarcoderdataPython |
253935 | # -*- coding: utf-8 -*-
""" Smooth tube geometry element
Created on Thu Mar 9 16:08:21 2017
"""
import numpy as np
# shape
class smooth_pipe():
""" Smooth tube geometry element [*]_
.. [*] Not entirely sure why this module is in materialtools
"""
def __init__(self,**kwargs):
attr... | StarcoderdataPython |
1906043 | <filename>sorn/test_sorn.py
import unittest
import pickle
import numpy as np
from sorn.sorn import RunSorn, Generator
from sorn.utils import Plotter, Statistics, Initializer
from sorn import Simulator, Trainer
num_features = 10
inputs = np.random.rand(num_features, 1)
# Get the pickled matrices:
with open("sample_mat... | StarcoderdataPython |
3391068 | from plastiqpublicapi.plastiqpublicapi_client import PlastiqpublicapiClient
print("Hello world"); | StarcoderdataPython |
8138279 | <filename>setup_helper.py
from pathlib import Path
from PIL import Image
from plexapi.server import PlexServer
import numpy as np
import requests
import shutil
import os
import re
from configparser import ConfigParser
import platform
from colorama import Fore, Back, Style
import subprocess
config_object =... | StarcoderdataPython |
6593633 | <filename>juego/jugador.py<gh_stars>1-10
# coding: utf-8
from juego.ficha import Ficha
class Jugador():
def __init__(self, color: str, nickname: str):
self.color = color
self.nickname = nickname
self.retirado = False
self.finalizado = False
self.fichas = [Ficha(), Ficha(), ... | StarcoderdataPython |
9680419 | <filename>setup.py
from setuptools import setup
setup(name='LpSchedule',
version='0.1',
description='API for Lviv Polytechnik schedule',
author='<NAME>',
author_email='<EMAIL>',
url='http://example.com',
install_requires=[
'alembic>=0.8.4',
'Flask>=0.10.1',
... | StarcoderdataPython |
146146 | <filename>autotest/test_gwf_rch02.py
"""
MODFLOW 6 Autotest
Test to make sure that array based recharge is applied correctly when idomain
is used to remove part of the grid.
"""
import os
import pytest
import sys
import numpy as np
try:
import pymake
except:
msg = "Error. Pymake package is not available.\n"
... | StarcoderdataPython |
3497926 | # -*- coding: utf-8 -*-
'''
Python module for Mopidy Pummeluff web classes.
'''
from __future__ import absolute_import, unicode_literals
__all__ = (
'LatestHandler',
'RegistryHandler',
'RegisterHandler',
)
from json import dumps
from logging import getLogger
from tornado.web import RequestHandler
from ... | StarcoderdataPython |
6625398 | <reponame>ricardoteixeiraduarte/zulip
# Webhooks for external integrations.
from django.utils.translation import ugettext as _
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view... | StarcoderdataPython |
8032734 | <reponame>GE-Atomic6/ghg
""" Module to wrap factors in class """
import json
import pkgutil
from atomic6ghg import YearValueException, YearMapException
class MobileCombustionCh4AndN2oEmissionFactors:
""" Wrapper class for mobile_combustion_emission_factors.json """
def __init__(self):
self.factors = js... | StarcoderdataPython |
5076345 | # A Python text adventure with a graphical user interface
# This program containers the main driver for the game
from tkinter import *
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
audio = False
try:
import pygame
audio = True
except:
pass
from story import * # imports class Progress and ... | StarcoderdataPython |
11396080 | import random
from pyecharts import options as opts
from pyecharts.charts import HeatMap
from pyecharts.faker import Faker
value = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)]
c = (
HeatMap()
.add_xaxis(Faker.clock)
.add_yaxis("series0", Faker.week, value)
.set_global_opts(
... | StarcoderdataPython |
8135636 | <reponame>sendhilg/zendesk-search<gh_stars>1-10
# Generated by Django 2.2.2 on 2019-06-30 16:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('search', '0003_auto_20190701_0137'),
]
operations = [
migrations.AlterField(
mod... | StarcoderdataPython |
8182686 | #!/usr/bin/env python3
import re
import sys
def str_to_dict(input_list: list) -> list:
"""
Analyze a list of strings and return a list of dict with all found fields
example:
from:
['eyr:2028 iyr:2016 byr:1995 ecl:oth pid:543685203 hcl:#c0946f hgt:152cm cid:252']
to:
... | StarcoderdataPython |
3458735 | <filename>operadores basicos/potencia2.py
a = 103
b = 0.5
c = 40.74
print("a ** b ** c =",a ** b ** c)
| StarcoderdataPython |
3437918 | import numpy as np
class SOM(object):
def __init__(
self, data, x, y, eta_b=0.3, eta_n=0.1, n_radius=0.5,
eta_b_final=0.03, eta_n_final=0.01, n_radius_final=0.05):
"""A 2D self organising map.
"""
self.data = data
self.n_dim = data.shape[1]
self.x = x
self.y = y
self.eta_b = eta_b
self.eta_n = ... | StarcoderdataPython |
3510856 | <filename>migrations/versions/908243da03d0_adding_json_table.py<gh_stars>0
"""adding json table
Revision ID: 908243da03d0
Revises: e7c26165<PASSWORD>
Create Date: 2021-11-09 22:33:45.039500
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by A... | StarcoderdataPython |
5128540 | from .transform_addresses import transform_addresses
from .AddressDatabase import AddressDatabase
from .CSVData import CSVData
| StarcoderdataPython |
3327689 | from tkinter import *
""" Specifes CLEAR'S user input parameters. CLEAR sets the input parameters as global variables
whose values are NOT changed in any other module (these are CLEAR's only global variables).
Tkinter is used to provide some checks on the user's inputs. The file
'Input Parameters for CLEAR.pdf' ... | StarcoderdataPython |
4956164 | <reponame>JaneliaSciComp/osgpyplusplus<filename>examples/rough_translated1/osgcluster.py
#!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgcluster"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import arpa
from osgpypp i... | StarcoderdataPython |
142925 | import asyncio
import time
from asyncio import run, create_task, CancelledError
from typing import List, Dict
from dataclasses import dataclass, asdict, field
import json
import zmq
from zmq.asyncio import Context, Socket
import gamestate
#import traceback
SERVER_UPDATE_TICK_HZ = 10
async def update_from_client(gs:... | StarcoderdataPython |
12831055 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import tensorflow as tf
from scipy import misc
app_path = os.environ['APP_PATH']
for p in app_path.split(';'):
sys.path.append(p)
import os
import co... | StarcoderdataPython |
5023472 | <reponame>photoszzt/this
######################################################
# -*- coding: utf-8 -*-
# File Name: encode_benchmark.py
# Author: <NAME>
# Created Date: 2017-10-24
# Description: JPEG encoding benchmark
######################################################
import numpy as np
from PIL import Image
imp... | StarcoderdataPython |
1812619 |
path = "/home/frenky/PycharmProjects/HTTPSDetector/MachineLearning/data_model/2017_08_25/y_test.txt"
normal = 0
malware = 0
with open(path) as f:
for line in f:
if int(line) == 0:
normal += 1
elif int(line) == 1:
malware += 1
else:
print "Error: More lab... | StarcoderdataPython |
341713 | <reponame>gbeckers/jadeR
#!/usr/bin/env python
# This file can be either used from the command line (type
# 'python jadeR.py --help' for usage, or see docstring of function main
# below) or it can be imported as a module in a python shell or program
# (use 'import jadeR').
# Comments in this source file are from th... | StarcoderdataPython |
3567119 | <filename>SDKs/Aspose.Slides-Cloud-SDK-for-Python/asposeslidescloud/SlidesApi.py<gh_stars>0
#!/usr/bin/env python
import sys
import os
import urllib
import json
import re
from models import *
from ApiClient import ApiException
class SlidesApi(object):
def __init__(self, apiClient):
self.apiClient = apiCli... | StarcoderdataPython |
1648748 | from django.contrib import admin
from .models import *
admin.site.register(ApplicationTemplate)
admin.site.register(ApplicationQuestion) | StarcoderdataPython |
5159888 | #Importing Libraries
import numpy
from numpy import genfromtxt
from math import *
import csv
import heapq
import random
import os
import shutil
from shutil import copyfile
import copy
from random import *
#------------------------------------------------------------------------------------------------------------
path=... | StarcoderdataPython |
3544241 | from django.shortcuts import render, redirect
from .forms import detailsForm
# Create your views here.
def show(request):
# return render(request, 'userTitle/index.html')
form = detailsForm()
context = {'form':form}
return render(request, 'userTitle/index.html', context)
def save_data(request):
form = detailsFor... | StarcoderdataPython |
3494192 | <gh_stars>0
# coding: utf-8
import os
import sys
try:
_var = sys.argv[1]
except IndexError:
_var = 'temp'
ALPHA = 0.7
RED = '#AB0520'
BLUE = '#0C234B'
TITLE = 'UA HAS ADVI'
DATA_DIRECTORY = os.getenv('ADVI_DATADIR', '~/.wrf')
WS_ORIGIN = os.getenv('WS_ORIGIN', 'localhost:5006')
GA_TRACKING_ID = os.getenv('A... | StarcoderdataPython |
9741194 |
# ----------- This divides the Train Data to half, half for training and half for testing ------------ #
f=open('tr.csv','w')
g=open('ts.csv','w')
h=open('trainHistory.csv','r')
i=0
for line in h.readlines():
if i==0:
f.write(line)
k=line.split(',')
g.write(line)
elif i>0:
if... | StarcoderdataPython |
6476640 | import json
import uuid
import os
import boto3
from datetime import datetime, timedelta
DYNAMODB_USER = os.environ['DYNAMODB_USER']
EXPIRE_IN_SECOND = os.environ['EXPIRE_IN_SECOND']
client_dynamo = boto3.client('dynamodb')
ERRORS = {}
ERRORS['BAD_FORMAT'] = {
'result': 'error',
'body': 'Invalid format of req... | StarcoderdataPython |
53593 | <reponame>Eddy-zheng/ImageDT
# coding: utf-8
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import tensorflow as tf
from PIL import Image
def visual_records(tfrecords_path):
# make an input queue from the tfrecord file
filename_queue = tf.train.string_inpu... | StarcoderdataPython |
8101004 | <reponame>danibene/NeuroKit
import numpy as np
import pandas as pd
import scipy.integrate
from ..stats import density
def entropy_power(signal, **kwargs):
"""**Entropy Power (PowEn)**
The Shannon Entropy Power (PowEn or SEP) is a measure of the effective variance of a random
vector. It is based on the e... | StarcoderdataPython |
8067382 | <reponame>start2020/MSGC-Seq2Seq<filename>libs/para.py<gh_stars>0
# coding: utf-8
import argparse
def original_data_para():
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_dir', default='../metr/')
parser.add_argument('--data_file', default="matrix.npz")
parser.add_argument('--... | StarcoderdataPython |
3528620 | """
Copyright (c) 2018, INRIA
Copyright (c) 2018, University of Lille
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... | StarcoderdataPython |
4802073 | <filename>tests/gamestonk_terminal/stocks/due_diligence/test_finviz_view.py
# IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
import pytest
# IMPORTATION INTERNAL
from gamestonk_terminal.stocks.due_diligence import finviz_view
@pytest.mark.parametrize(
"val, expected",
[
("RANDOM_VALUE", "RANDOM_VALUE... | StarcoderdataPython |
9669789 | <gh_stars>0
import os
from utils.celery_client import celery_app
from workers.base_task import ObjectTask
from workers.default.ojs.ojs_api import publish, generate_frontmatter
def _generate_ojs_id(prefix, journal_code, result_id):
return f"{prefix}-{journal_code}-{result_id}"
class PublishToOJSTask(ObjectTask... | StarcoderdataPython |
154793 | # -*- coding: utf-8 -*-
#
# smartz.eth.contracts
#
from smartz.json_schema import load_schema, add_definitions, assert_conforms2definition, assert_conforms2schema_part
def abi_arguments2schema(abi_args_array):
"""
Конвертация массива аргументов функции контракта в json schema, пригодную для отрисовки и вал... | StarcoderdataPython |
11257208 | # -*- coding: utf-8 -*-
# Author: <NAME>
# Date: October 2018
"""
Driver file for the PCA9685 16-channel PWM controller. Communicates
with the device via I2C and implements the basic functions for integrating into
the SoftWEAR package.
"""
import time # Imported for d... | StarcoderdataPython |
1875086 | <reponame>xccheng/mars<gh_stars>1-10
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# 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
#
# U... | StarcoderdataPython |
6696459 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
# Кортежи. Конкатенация +
# Конкатенация двух кортежей
A = (1, 2, 3)
B = (4, 5, 6)
C = A + B # C = (1, 2, 3, 4, 5, 6)
print(f"C = {C}")
# Конкатенация кортежей со сложными объектами
D = (3, "abc") + (-7.22, ['a',... | StarcoderdataPython |
1940480 | ###
# Copyright (c) 2002-2005, <NAME>
# Copyright (c) 2009, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# ... | StarcoderdataPython |
3222001 | class MyHashTable():
def __init__(self, capacity):
self.cap = capacity
self.slot = [None] * capacity
def hash_function(self, key):
return key % self.cap
def find_idx(self, key):
idx = self.hash_function(key)
while self.slot[idx] is not None and self.... | StarcoderdataPython |
219051 | <reponame>Ornias1993/kadalu<filename>cli/kubectl_kadalu/__main__.py<gh_stars>1-10
"""
This is an CLI command to handle kadalu executions
"""
# To prevent Py2 to interpreting print(val) as a tuple.
from __future__ import print_function
import sys
from argparse import ArgumentParser
from version import VERSION
# Subco... | StarcoderdataPython |
6551861 | """
minimize (1.5 - x)^2 + 100 (y - x^2)^2
subject to
9 - x^2 >= 0,
9 - y^2 >= 0,
"""
from sympy import *
from Irene import SDPRelaxations
# define the symbolic variables and functions
x = Symbol('x')
y = Symbol('y')
print "Relaxation method:"
# initiate the SDPRelaxations object
Rlx = SDPRelaxations(... | StarcoderdataPython |
4893185 | #**************************************************************************#
# This file is part of pymsc which is released under MIT License. See file #
# LICENSE or go to https://github.com/jam1garner/pymsc/blob/master/LICENSE #
# for full license details. #
#***********... | StarcoderdataPython |
1952255 | <filename>mods/SnowBallFight.py
import bs
import bsVector
import bsSpaz
import bsBomb
import bsUtils
import random
import SnoBallz
#please note that this Minigame requires the separate file SnoBallz.py.
#It's a separate file to allow for snowballs as a powerup in any game.
def bsGetAPIVersion():
# see bombsquadga... | StarcoderdataPython |
6539073 | from django import forms
from tower import ugettext_lazy as _
class SearchForm(forms.Form):
q = forms.CharField(required=False, label=_(u'Search'))
| StarcoderdataPython |
12848011 | from __future__ import absolute_import, division, print_function
import argparse
import os
import shutil
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import tensorflow as tf
from xray import model
slim = tf.contrib.slim
tf.logging.set_verbosity(tf.logging.INFO)
log = tf.logging
def cal... | StarcoderdataPython |
11394162 | """Implementation of GraphTensor data type.
"""
import abc
from typing import Any, Dict, Mapping, Optional, Union
import tensorflow as tf
from tensorflow_gnn.graph import graph_constants as const
from tensorflow_gnn.graph import graph_piece as gp
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.fr... | StarcoderdataPython |
1893553 | <gh_stars>0
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass, field as _field
from ...config import custom_scalars, datetime
from gql_client.runtime.variables import encode_variables
from gql import gql, Client
from gql.transport.exceptions import TransportQueryE... | StarcoderdataPython |
348060 | <filename>example/wrapper/thridparty/set_yinshi_gripper.py<gh_stars>10-100
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2019, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <<EMAIL>> <<EMAIL>>
"""
Example: yinshi gripper Control
Please make sure that the gripper is atta... | StarcoderdataPython |
1744181 | <reponame>golismero/golismero-python-helpers
import mmh3
from typing import List
def hash_ip(data: dict):
return mmh3.hash128(data['ip'])
def hash_domain(data: dict):
return mmh3.hash128(data['domain'])
def hash_vulnerability(data: dict):
string_hash = []
for x in ('cve', 'id', 'cwe', 'title'):
... | StarcoderdataPython |
183357 | #!/usr/bin/env python
# System Libraries
import curses, logging
# LLNMS Libraries
import CursesTable
from NetworkAddWindow import NetworkAddWindow
from UI_Window_Base import Base_Window_Type
from WarningWindow import WarningWindow
# ---------------------------------------- #
# - Network Summary Window ... | StarcoderdataPython |
5177283 | from flask import Blueprint, render_template, request
stories_blueprint = Blueprint(
"stories_blueprint", __name__, template_folder="templates"
)
@stories_blueprint.route("/", methods=["GET"])
@stories_blueprint.route("/<story_id>", methods=["GET"])
def index(story_id=None):
story_text = f"story { story_id }... | StarcoderdataPython |
1976540 | from world.population import marriage_data
from .bank import Central
from .family import Family
from .firm import Firm, ConstructionFirm
from .house import House
from .region import Region
class Agent:
"""
This class represent the general citizen of the model.
Agents have the following variables:
(a) ... | StarcoderdataPython |
186390 | <gh_stars>0
SECRETS=[3,5,2,7,3]
| StarcoderdataPython |
9780996 | from __future__ import annotations
import logging
import os
from collections.abc import Mapping
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, cast
from warnings import warn
from pydantic import BaseModel, BaseSettings, ValidationError
f... | StarcoderdataPython |
4980431 | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
urlpatterns = patterns(
'proxmoxs.views',
url(r'^$', 'vms_list'),
url(r'^(?P<serverPk>[0-9]*)/(?P<vmId>[0-9]*)/delete/$', 'vms_delete'),
url(r'^(?P<serverPk>[0-9]*)/(?P<vmId>[0-9]*)/stop/$', 'vms_stop'),
url(r'^(?P<serverPk>[0-9]... | StarcoderdataPython |
5067163 | # -*- coding: utf-8 -*-
# @Time : 2020/4/19 16:44
# @Author : Chen
# @File : loss.py
# @Software: PyCharm
from mxnet.gluon.loss import Loss
from mxnet import autograd
import numpy as np
class ClsTripletLoss(Loss):
def __init__(self, margin=1.0, weight=1., batch_axis=0, **kwargs):
super(ClsTripletLo... | StarcoderdataPython |
6402734 | # -*- coding: utf-8 -*-
"""
Created on Sun May 24 16:36:41 2020
@Author: <NAME>, <NAME>
@Institution: CBDD Group, Xiangya School of Pharmaceutical Science, CSU, China
@Homepage: http://www.scbdd.com
@Mail: <EMAIL>; <EMAIL>
@Blog: https://blog.iamkotori.com
♥I love Princess Zelda forever♥
"""
from multiprocessing im... | StarcoderdataPython |
5105840 | ################################################################################
"""
The gig selection part of the game.
Where you get offered gigs, and you decide to take them or not.
"""
################################################################################
# STD LIBS
import os
import ... | StarcoderdataPython |
367726 | import os
import pickle as pkl
import sys
import time
import joblib
import numpy as np
import torch
from dgl import DGLGraph
class Graph:
def __init__(self, pyg_data=None, dgl_graph=None):
self.pyg_data = pyg_data
self.dgl_graph = dgl_graph
class Item:
def __init__(self, x):
self.x ... | StarcoderdataPython |
171676 | <reponame>dindamajesty13/web-risk
from lib.database import db_connect
def getSetelahUsulan():
conn = db_connect()
with conn:
cur = conn.cursor()
cur.execute(f"SELECT id_app, criteria_1, criteria_2, criteria_3, criteria_4, criteria_5, ((public.nilai_resiko_setelah_usulan.criteria_1*0.30) + (publ... | StarcoderdataPython |
341080 | <filename>clang_build/progress_bar.py
from tqdm import tqdm as _tqdm
from colorama import Fore as _Fore
_MAX_DESCRIPTION_WIDTH = 16
_ELLIPSIS_WIDTH = 2
_BAR_FORMAT = "{desc: <%s}: {percentage:3.0f}%% |%s{bar}%s| {n_fmt: >5}/{total_fmt: >5} [{elapsed: >8}]" % (_MAX_DESCRIPTION_WIDTH, _Fore.BLUE, _Fore.RESET)
def _for... | StarcoderdataPython |
11473 | """Extension for built-in Sass functionality."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from itertools import product
import math
import os.path
from pathlib import PurePosixPath
from six.moves import xrange
... | StarcoderdataPython |
1680539 | import logging
from mkdocs.config import config_options
from .drivers.event_hook import EventHookHandler
from .drivers.headless_chrome import HeadlessChromeDriver
from .drivers.relaxedjs import RelaxedJSRenderer
from .templates.template import Template
class Options(object):
config_scheme = (
('enabled... | StarcoderdataPython |
371872 | <reponame>Andre-Ceschia/TickerAnalysis<filename>TickerAnalysis/__init__.py
from TickerAnalysis.TickerAnalysis import Ticker | StarcoderdataPython |
243216 | from __future__ import with_statement
import os.path
import random
import string
# Current directory
ROOT = os.path.abspath(os.path.dirname(__file__))
# Check if Amon Lite is already installed
if os.path.exists('/etc/amonlite.conf'):
config_path = '/etc/amonlite.conf'
else:
config_path = os.path.join(ROOT... | StarcoderdataPython |
4995348 | import numpy as np
hidden_weights = np.array([[1,1,-5],[3,-4,2]])
output_weights = np.array([2,-1])
inputs = np.array([1,2,3])
hidden_thetas = []
for i in range(0,len(hidden_weights)):
x = np.dot(inputs,hidden_weights[i].T)
print (x)
hidden_thetas.append(x)
print
output = np.dot(hidden_thetas,output_wei... | StarcoderdataPython |
3382249 | <reponame>richung99/digitizePlots<filename>venv/Lib/site-packages/nibabel/tests/test_spaces.py<gh_stars>1-10
""" Tests for spaces module
"""
import numpy as np
import numpy.linalg as npl
from ..spaces import vox2out_vox, slice2volume
from ..affines import apply_affine, from_matvec
from ..nifti1 import Nifti1Image
fro... | StarcoderdataPython |
1934954 | <reponame>MatthiasHertel80/tensorflow
# Copyright 2018 The TensorFlow Authors. 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/LICE... | StarcoderdataPython |
26189 | <filename>webapp/assessdb/scripts/import_csv_instruments.py
import os
import sys
import transaction
import csv
from pyramid.paster import (
get_appsettings,
setup_logging,
)
from pyramid.scripts.common import parse_vars
from ..models.meta import Base
from ..models import (
get_engine,
get_session... | StarcoderdataPython |
6579964 | <gh_stars>0
import pytest
from retro_data_structures.conversion import conversions
from retro_data_structures.conversion.asset_converter import AssetDetails
from retro_data_structures.game_check import Game
@pytest.mark.parametrize("asset_type", [
"ANCS", "ANIM", "CINF", "CMDL", "CSKR", "EVNT", "PART", "TXTR"
])... | StarcoderdataPython |
1904324 | <filename>lexi/src/examples/tweets.py
# -*- coding: utf-8 -*-
# tweets.py
# author : <NAME>
import lbsa
tweet = """
The Budget Agreement today is so important for our great Military.
It ends the danger sequester and gives Secretary Mattis what he needs to keep America Great.
Republicans and Democrats must support our... | StarcoderdataPython |
11241891 | """pytest configuration and utilities."""
import os
from urllib.parse import urlparse
from flask.ext.migrate import upgrade
import pytest
from sqlalchemy import event
from sqlalchemy.orm import Session
from pygotham.core import db
from pygotham.factory import create_app
from tests import settings
@pytest.fixture(s... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.