id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
179584
<gh_stars>1-10 from scipy import special as sfunc from scipy.optimize import fsolve import numpy as np from tqdm import tqdm def update_statistics_parallel(statistic_L_i): """Parallel updating of the sufficient statistics with the current data. Parameters ---------- statistic_L_i : tuple Tup...
StarcoderdataPython
187319
from .storage import Storage
StarcoderdataPython
3359069
<reponame>huangenyan/Lattish # -*- coding: utf-8 -*- import unittest from mahjong.hand import FinishedHand from utils.tests import TestMixin class YakumanCalculationTestCase(unittest.TestCase, TestMixin): def test_is_tenhou(self): hand = FinishedHand() tiles = self._string_to_136_array(sou='123...
StarcoderdataPython
76375
#!/usr/bin/env python2 import sys import hyperdex.client import json import os from testlib import * from hyperdex.client import * c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs): return set([frozenset(x.items()) for x in xs]) # Empty Document assertTrue(c.put('kv', 'k', {})) a...
StarcoderdataPython
1690993
import numpy as np from discretize.utils.matrix_utils import mkvc from discretize.utils.code_utils import deprecate_function def cylindrical_to_cartesian(grid, vec=None): """ Take a grid defined in cylindrical coordinates :math:`(r, \theta, z)` and transform it to cartesian coordinates. """ grid =...
StarcoderdataPython
163052
import mock from nose.tools import assert_equal, assert_in, raises, assert_is, assert_is_instance, assert_false, assert_true from .. import metrics as mm, exceptions, histogram, simple_metrics as simple, meter class TestMetricsModule(object): def setUp(self): self.original_registy = mm.REGISTRY.copy() ...
StarcoderdataPython
1777009
<gh_stars>0 import sys import math import datetime as dt import numpy as np import pandas as pd from matplotlib import pyplot as plt DEFAULT_WIDTH = 20 DEFAULT_HEIGHT = 10 # Iterates from first to last inclusive, with the given step. def iterdate(first, last, step=dt.timedelta(days=1)): while first <= last: ...
StarcoderdataPython
1796814
import _nx import warnings from .utils import bit, cached_property AUTO_PLAYER_1_ID = 10 def refresh_inputs(): """Refreshes inputs. Should normally be called at least once within every iteration of your main loop. """ _nx.hid_scan_input() def _determine_controller_type(player): # TODO det...
StarcoderdataPython
165891
# Copyright (c) 2021 Massachusetts Institute of Technology # SPDX-License-Identifier: MIT from pathlib import Path from typing import Any, Callable, List, Mapping, Optional, Union from hydra._internal.callbacks import Callbacks from hydra._internal.hydra import Hydra from hydra._internal.utils import create_config_sea...
StarcoderdataPython
1659882
<filename>src/lesson_runtime_features/site_addsitedir.py<gh_stars>1-10 import site import os import sys script_directory = os.path.dirname(__file__) module_directory = os.path.join(script_directory, sys.argv[1]) try: import mymodule except ImportError as err: print('Could not import mymodule:', err) print() ...
StarcoderdataPython
1664969
<reponame>mrityunjaykumar911/gmailMailerPy #!/usr/local/bin/python """ Filename: main.py Author: mrityunjaykumar Date: 02/02/19 author_email: <EMAIL> """ from __future__ import absolute_import # from email_all import main_1 from fetch_sheet import main_1 from ma...
StarcoderdataPython
3257563
<reponame>ALFA-group/adv-malware-viz # coding=utf-8 import sys import os sys.path.insert(1, os.path.join(sys.path[0], '..')) from os import system from utils.utils import load_parameters, set_parameter import shutil import time if __name__ == "__main__": trained_experiment_model = sys.argv[1] original_param...
StarcoderdataPython
86714
<filename>app/redidropper/utils.py<gh_stars>1-10 """ Goal: Store helper functions not tied to a specific module @authors: <NAME> <<EMAIL>> <NAME> <<EMAIL>> <NAME> <<EMAIL>> """ import os import ast import json from datetime import datetime, timedelta from itsdangerous import URLSaf...
StarcoderdataPython
115258
default_app_config = ( 'wshop.apps.dashboard.vouchers.config.VouchersDashboardConfig')
StarcoderdataPython
3205694
from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from dashboard.forms import ExcuseResponseForm from dashboard.models import Excuse, Position from dashboard.utils import verify_position from dashboard.views._positions._attendance_utils import event_type_from_position ...
StarcoderdataPython
3240040
# Tables.py # @author <NAME> # Module to drop and add tables for AdviseMe db # Just a few things I need to make this work from mysql.connector import Error """ ---------------------------------------------------------------------------------------------------------- Drops capstone db tables """ def dropTables(cursor)...
StarcoderdataPython
121891
import torch from .num_nodes import maybe_num_nodes def contains_self_loops(edge_index): row, col = edge_index mask = row == col return mask.sum().item() > 0 def remove_self_loops(edge_index, edge_attr=None): row, col = edge_index mask = row != col edge_attr = edge_attr if edge_attr is None...
StarcoderdataPython
1616618
<gh_stars>10-100 import numpy as np import sys, os, pdb, pickle, time from .utils import * from .losses import * from .keras_models import * from .aux_dict import * from scipy.stats import norm import matplotlib.pyplot as plt from matplotlib import animation import seaborn as sns from tqdm import tqdm_notebook as tqdm...
StarcoderdataPython
1718521
# Generated by Django 2.1.7 on 2019-05-22 09:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Activities', '0006_auto_20190415_1456'), ] operations = [ migrations.AddField( model_name='sent...
StarcoderdataPython
1698889
"""Copy bumped workflows to the template folder, appending the `.jinja` suffix.""" from pathlib import Path from shutil import copy COMMON_PATH = ".github/workflows" source_folder = Path("./dependabot") / COMMON_PATH destination_folder = Path("./template/") / COMMON_PATH for source in source_folder.iterdir(): de...
StarcoderdataPython
25087
from tests.common.devices.base import AnsibleHostBase class VMHost(AnsibleHostBase): """ @summary: Class for VM server For running ansible module on VM server """ def __init__(self, ansible_adhoc, hostname): AnsibleHostBase.__init__(self, ansible_adhoc, hostname) @property def e...
StarcoderdataPython
1781613
from django.contrib import admin from users.models import CustomUser class CustomUserAdmin(admin.ModelAdmin): list_display = ("email", "first_name", "last_name", "date_joined", "is_superuser", "is_staff") list_filter = ("email", "date_joined", "is_superuser") admin.site.register(CustomUser, CustomUserAdmin)
StarcoderdataPython
1680963
import geometry import math import OpenGL.GL as gl import numpy as np import ctypes import json class signalgenerator(geometry.base): vertex_code = """ uniform mat4 modelview; uniform mat4 projection; in vec2 position; in vec2 texcoor; out vec2 v_texcoor; ...
StarcoderdataPython
3335014
<gh_stars>1-10 import os import torch import argparse import numpy as np from backend.quant_metric_inputs import ValidationLoader from metric_learning_main import plot_nearest_neighbours def compute_dist_naive(emb_train, emb_val): """ emb_train: NTrain, nlocs, emb_dim emb_val: NVal, nlocs, emb_dim...
StarcoderdataPython
141094
<filename>components/studio/studio/settings.py """ Django settings for studio project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproj...
StarcoderdataPython
1625762
def main(max_weight,weights,values): return 1 if __name__ == "__main__": # n , max_w = map(int,input().split()) # weights = [] # values = [] # for _ in range(n): # w,v=map(int,input().split()) # weights.append(w) # values.append(v) # print(weights , values) ...
StarcoderdataPython
1769460
<filename>exp_distech.py import numpy as np from pandas import DataFrame import utils import eval_utils import os from typing import Dict, List, Tuple import SpacePair import exp_unsup def read_3clusters(filenme:str) -> (List[str], List[str]): dis_words = [] tech_words = [] with open(filenme, "r") as ...
StarcoderdataPython
75326
""" Response selection methods determines which response should be used in the event that multiple responses are generated within a logic adapter. """ import logging def get_most_frequent_response(input_statement, response_list): """ :param input_statement: A statement, that closely matches an input to the ch...
StarcoderdataPython
1752954
<gh_stars>0 import collections import dataclasses import functools import inspect import re import types from typing import Any import numpy as np import torch import torchdynamo from .. import mutation_guard from .. import skipfiles from ..allowed_functions import is_allowed from ..allowed_functions import is_built...
StarcoderdataPython
3239413
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from net.utils.graph import Graph class Model(nn.Module): def __init__(self, in_channels, num_class, graph_args, edge_importance_weighting, **kwargs): super().__init__() self....
StarcoderdataPython
3385983
<filename>fluentogram/misc/__init__.py<gh_stars>0 # coding=utf-8 from .timezones import timezones __all__ = ["timezones"]
StarcoderdataPython
1633056
<gh_stars>1-10 import random import numpy as np from sinkhorn_knopp import sinkhorn_knopp from simulated.Packet import Packet class Traffic_Generator(object): def __init__(self, size, seed, load): super(Traffic_Generator, self).__init__() self._size = size self._seed = seed self._l...
StarcoderdataPython
3321813
<reponame>beli302/Pitches from flask import render_template, request, redirect, url_for, abort, flash from flask_login import login_required, current_user from . forms import PitchForm, CommentForm, CategoryForm, UpdateProfile from .import main from .. import db from ..models import User, Pitch, Comments, PitchCategory...
StarcoderdataPython
1766974
<filename>tests/test_compiler.py from .context import lux import pytest import pandas as pd def test_underspecifiedNoVis(test_showMore): noViewActions = ["Correlation", "Distribution", "Category"] df = pd.read_csv("lux/data/car.csv") test_showMore(df,noViewActions) assert len(df.viewCollection)==0 # test only on...
StarcoderdataPython
120702
<reponame>Zepyhrus/tf2<filename>src/4-4.py import tensorflow as tf import tensorflow_datasets as tfds tf.compat.v1.disable_v2_behavior() def get_iris_data(): ds_train, *_ = tfds.load(name='iris', split=['train']) with open('iris.csv', 'w') as f: for i, ds in enumerate(ds_train): features = ds['feature...
StarcoderdataPython
93349
print('Gathering psychic powers...') import re import numpy as np from gensim.models.keyedvectors import KeyedVectors word_vectors = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True, limit=200000) # word_vectors.save('wvsubset') # word_vectors = KeyedVectors.load("wvsubset...
StarcoderdataPython
3386902
<gh_stars>0 # -*- coding: utf-8 -*- import json import struct import threading from io import BytesIO from collections import OrderedDict from tempfile import TemporaryFile from configparser import RawConfigParser class Result(dict): def __init__(self, code=0, msg=r'', data=None, extra=None): super()....
StarcoderdataPython
3228956
""" agents Created by: <NAME> On: 21-11-19, 12:04 """ from abc import abstractmethod from tqdm import trange from drugex.api.agent.callbacks import AgentMonitor from drugex.api.agent.policy import PolicyGradient from drugex.api.environ.models import Environ from drugex.api.pretrain.generators import Generator from d...
StarcoderdataPython
20058
import os import json import ConfigParser import logging.config base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # load the shared settings file settings_file_path = os.path.join(base_dir, 'config', 'settings.config') settings = ConfigParser.ConfigParser() settings.read(settings_file_path) # s...
StarcoderdataPython
1603221
<gh_stars>1-10 import unittest from typing import Optional from ravendb.documents.indexes.index_creation import AbstractIndexCreationTask from ravendb.documents.session.loaders.include import QueryIncludeBuilder from ravendb.documents.session.misc import TransactionMode, SessionOptions from ravendb.documents.session.q...
StarcoderdataPython
1709880
<filename>txt2svg/txt2svg.py<gh_stars>1-10 import sys from re import compile import networkx as nx import numpy as np import math R = 30 def parse_input(): regex = compile('(\w+)\s*->\s*((?:[^\s]+)?)\s+(\w+)') fname = sys.argv[1] with open(fname, 'r') as f: lines = f.readlines() edges = [] for line in lines:...
StarcoderdataPython
92325
<reponame>TacPhoto/Learning<gh_stars>0 import numpy arr = numpy.array([ [1, 2, 3, 4], [10, 20, 30, 40], [100, 200, 300, 400], [1000, 2000, 3000, 4000] ]) print(arr) print('Arr shape: ' + str(arr.shape)) print(arr[0,]) print(arr...
StarcoderdataPython
67954
from ..li.api import LIReader class LIViolationReader(LIReader): endpoint = 'violationdetails' def get(self, code, since=None, until=None, params={}): filters = [ "violation_code eq '%s'" % code, ] if since: filters.append("violation_datetime gt %s" % s...
StarcoderdataPython
1656912
import json class DataManager: """The DataManager class works with an Environment class' instance. It manages the information by returning it when requested, while also storing the program's data on the data file precissed.""" def __init__(self, environment): self.this_environment = environme...
StarcoderdataPython
4828407
from uuid import uuid4 from moto.core import BaseBackend, BaseModel from moto.wafv2 import utils from .utils import make_arn_for_wacl, pascal_to_underscores_dict from .exceptions import WAFV2DuplicateItemException from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict import datetime from collect...
StarcoderdataPython
54170
<filename>srdk/cy/lang_tools/get_stressed_phones_for_htk.py import sys, re, traceback from llef.llef import get_stressed_phones def get_stressed_phones_for_htk(word): try: stressed_phones = get_stressed_phones(word) except (ValueError, TypeError): return '','','' lexiconword=word if lexiconword.startswith("'"...
StarcoderdataPython
1608610
""" This module to call hyperlink_preview and display the result in a webbrowser. Provided as sample html and how to call hyperlink_preview. """ from pathlib import Path import shutil import tempfile import time import webbrowser import argparse from . import hyperlink_preview as HLP import html if __name__ == "__ma...
StarcoderdataPython
3236002
import os import numpy as np from flask import Flask, request, jsonify, render_template, send_from_directory import tensorflow as tf from tensorflow import keras import cv2 import matplotlib.image as mpimg IMAGE_UPLOADS = 'static/uploads/' app = Flask(__name__) app.config['IMAGE_UPLOADS'] = IMAGE_UPLOADS model = ker...
StarcoderdataPython
1760580
# Generated by Django 3.1.4 on 2020-12-17 08:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("puzzles", "0019_auto_20201217_0708"), ] operations = [ migrations.AddConstraint( model_name="puzzletag", constraint=...
StarcoderdataPython
129582
<reponame>motraor3/py-Goldsberry<filename>goldsberry/sportvu/__init__.py from goldsberry.sportvu._SportVu2 import *
StarcoderdataPython
1667716
<reponame>niranjanreddy891/pclpy<gh_stars>1-10 import pclpy_dependencies from pclpy import io from pclpy import view
StarcoderdataPython
6332
# nuScenes dev-kit. # Code written by <NAME> & <NAME>, 2018. # Licensed under the Creative Commons [see licence.txt] import argparse import json import os import random import time from typing import Tuple, Dict, Any import numpy as np from nuscenes import NuScenes from nuscenes.eval.detection.algo import accumulate...
StarcoderdataPython
1776815
""" 10-6. Addition: One common problem when prompting for numerical input occurs when people provide text instead of numbers. When you try to convert the input to an int, you’ll get a ValueError. Write a program that prompts for two numbers. Add them together and print the result. Catch the ValueError if either input v...
StarcoderdataPython
1722299
import os from xbrr.base.reader.base_element import BaseElement from xbrr.edinet.reader.element_value import ElementValue class Element(BaseElement): def __init__(self, name, element, reference, reader): super().__init__(name, element, reference, reader) self.name = name self.element = el...
StarcoderdataPython
3249958
from shop import app app.run(debug=True, port=8001)
StarcoderdataPython
40543
# -*- coding: utf-8 -*- # @Time : 2019-09-01 17:49 # @Author : EchoShoot # @Email : <EMAIL> # @URL : https://github.com/EchoShoot # @File : test_others.py # @Explain : from sheen import Str import pytest class TestOthers(object): raw = 'xxooAß西xoox' obj = Str.red(raw) obj[2:-2] = Str.green ...
StarcoderdataPython
3306634
<filename>udemy/spiders/udemy_course.py<gh_stars>0 #!/usr/bin/env python """ETL process for gathering Udemy courses metadata. """ __author__ = "<NAME>" __license__ = "MIT" __email__ = "<EMAIL>" # standard libraries import re # third parties libraries import scrapy class UdemyCourseSpider(scrapy.Spider): name =...
StarcoderdataPython
1795945
<filename>source/segment/nnmf.py import torch import torch.nn as nn import numpy as np from utils import softminus import math import numbers from torch.nn import functional as F class SubNet(nn.ModuleList): def __init__(self, list): super(SubNet, self).__init__(list) def forward(self, input): ...
StarcoderdataPython
1707612
<gh_stars>0 import pluggy from scenario_player.constants import HOST_NAMESPACE from scenario_player.services.rpc.blueprints.instances import instances_blueprint from scenario_player.services.rpc.blueprints.tokens import tokens_blueprint from scenario_player.services.rpc.blueprints.transactions import transactions_blue...
StarcoderdataPython
1743333
<gh_stars>1-10 from .buttons import create_toggle_button from numpy import ceil from ipywidgets import GridspecLayout import pandas as pd from typing import List # A simple class for creating a grid of toggle buttons # It has some additional utilities such as # get_values or load_values methods class ToggleGrid: ...
StarcoderdataPython
153212
<reponame>voximplant/apiclient-python from voximplant.apiclient import VoximplantAPI, VoximplantException if __name__ == "__main__": voxapi = VoximplantAPI("credentials.json") # Create a new subuser for account_id = 1. KEY_ID = "ab98c70e-573e-4446-9af9-105269dfafca" DESCRIPTION = "test_desc" ...
StarcoderdataPython
1753933
import sqlite3 import logging # create logger module_logger = logging.getLogger(__name__) class DBConnection: def __init__(self, filename="bot.db"): self.filename = filename self.connection = sqlite3.connect(filename, timeout=20) # don't wait for the disk to finish writing self.c...
StarcoderdataPython
3314973
<filename>test/echo_server.py import asyncio import json import logging import sys import aiohttp from aiohttp import web async def async_main(): stdout_handler = logging.StreamHandler(sys.stdout) for logger_name in ["aiohttp.server", "aiohttp.web", "aiohttp.access"]: logger = logging.getLogger(logg...
StarcoderdataPython
4814811
cash = float(17.50) hours = float(raw_input("Hours worked in the past two weeks? ")) # def hours def payment(): # calc reg pay return hours * cash def over(): if hours > 80: OT = (hours - 80) * 8.75 # calc overtime hours return OT else: OT = 0 return OT def f...
StarcoderdataPython
1759336
<reponame>impedimentToProgress/ratchet<gh_stars>1-10 import sys import re cp_re = re.compile("[0-9A-F]{8}: CP: ([0-9]*).*$") read_re = re.compile("[0-9A-F]{8}: (?:Flash|Ram) read at (0x[0-9A-F]{8})=0x[0-9A-F]{8}$") write_re = re.compile("[0-9A-F]{8}: (?:Flash|Ram) write at (0x[0-9A-F]{8})=0x[0-9A-F]{8}$") def pri...
StarcoderdataPython
38141
<reponame>vrautela/hail states = {'Pending', 'Ready', 'Creating', 'Running', 'Cancelled', 'Error', 'Failed', 'Success'} complete_states = ('Cancelled', 'Error', 'Failed', 'Success') valid_state_transitions = { 'Pending': {'Ready'}, 'Ready': {'Creating', 'Running', 'Cancelled', 'Error'}, 'Creating': {'Read...
StarcoderdataPython
195287
from eth.vm.forks.byzantium import ByzantiumVM from .blocks import StretchBlock from eth.vm.forks.byzantium.state import ByzantiumState from .xmessage import StretchXMessage from typing import ( Tuple, ) from .headers import StretchBlockHeader from eth.db.trie import make_trie_root_and_nodes class StretchVM(Byza...
StarcoderdataPython
4809464
# -*- coding: utf-8 -*- #Plotting is on python since this will make it much easier to debug and adjsut #no need to recompile everytime i change graph color.... #needs a serious refactor from matplotlib import pyplot as plt import numpy as np from .nputil import mid, minmax, vector_apply from util import parse_arg, de...
StarcoderdataPython
71432
<reponame>wy1157497582/arcpy #import arcpy """----------------------------------------------------------------------------- Script Name: Clip Multiple Feature Classes Description: Clips one or more shapefiles from a folder and places the clipped feature classes into a geodatabase. Cr...
StarcoderdataPython
3277883
<reponame>Whosemario/stackless-python from stacklessness import * def f(): print 'f1' schedule() print 'f2' def g(): print 'g1' schedule() print 'g2' def h(): print 'h1' schedule() print 'h2' t1 = tasklet(f)() t2 = tasklet(g)() t3 = tasklet(h)() t1.run()
StarcoderdataPython
197403
<reponame>FatliTalk/learnenglish # Generated by Django 3.2.12 on 2022-03-10 05:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('words_in_sentences', '0005_review'), ] operations = [ migrations.RemoveField( model_name='review', ...
StarcoderdataPython
4808657
""" Characteristic matrices """ from larlib import * print "\n>>> brc2Csr" V = [[0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [2, 1]] FV = [[0, 1, 3], [1, 2, 4], [1, 3, 4], [2, 4, 5]] EV = [[0,1],[0,3],[1,2],[1,3],[1,4],[2,4],[2,5],[3,4],[4,5]] csrFV = csrCreate(FV) csrEV = csrCreate(EV) print "\ncsrCreate(FV) =\n", csrFV V...
StarcoderdataPython
3347700
<filename>labs/stacktrain/core/node_builder.py import stacktrain.config.general as conf import stacktrain.core.autostart as autostart import stacktrain.batch_for_windows as wbatch def build_nodes(cluster_cfg): config_name = "{}_{}".format(conf.distro, cluster_cfg) if conf.wbatch: wbatch.wbatch_begin_...
StarcoderdataPython
3298478
<reponame>vishalbelsare/event-registry-python<gh_stars>100-1000 from eventregistry._version import __version__ from eventregistry.Base import * from eventregistry.EventForText import * from eventregistry.ReturnInfo import * from eventregistry.Query import * from eventregistry.QueryEvents import * from eventregistry.Q...
StarcoderdataPython
3394263
""" extract within- and between-module correlation for each module/session """ import os,sys import numpy import ctypes basedir=os.environ['MYCONNECTOME_DIR'] def r_to_z(r): # fisher transform z=0.5*numpy.log((1.0+r)/(1.0-r)) z[numpy.where(numpy.isinf(z))]=0 z[numpy.where(numpy.isnan(z))]=0 ...
StarcoderdataPython
3351068
#!/usr/bin/env python import argparse import bluetooth joy_con_names = ['Joy-Con (L)', 'Joy-Con (R)'] def parse_cmd_line_args(): parser = argparse.ArgumentParser( description='Interface with Nintendo switch joy con over bluetooth') parser.parse_args() def main(): # Find services print 'Loo...
StarcoderdataPython
106223
<reponame>atanna/bm # -*- coding: utf-8 -*- from __future__ import absolute_import from functools import partial from matplotlib import pyplot as plt def magic_benchpy(line='', cell=None): """ Run benchpy.run %benchpy [[-i] [-g] [-n <N>] [-m <M>] [-p] [-r <R>] [-t <T>] -s<S>] statement where statem...
StarcoderdataPython
164150
"""This module contains functions that visualise solar agent control.""" from __future__ import annotations from typing import Tuple, Dict, List import numpy as np import matplotlib.pyplot as plt import matplotlib import seaborn as sns from solara.plot.constants import COLORS, LABELS, MARKERS def default_setup(figs...
StarcoderdataPython
146567
<filename>dcorch/common/endpoint_cache.py<gh_stars>0 # Copyright 2015 Huawei Technologies Co., Ltd. # 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 # # ...
StarcoderdataPython
4802010
<filename>testing/build/gen_fixtures_location_symbol.py #!/usr/bin/env python # Copyright 2013 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import subprocess import sys import os def main(): parser = ...
StarcoderdataPython
3250883
def fbx_definitions_elements(root, scene_data): """ Templates definitions. Only used by Objects data afaik (apart from dummy GlobalSettings one). """ definitions = elem_empty(root, b"Definitions") elem_data_single_int32(definitions, b"Version", FBX_TEMPLATES_VERSION) elem_data_single_int32(defi...
StarcoderdataPython
155677
<reponame>rohansaini886/Peer-Programming-Hub-CP-Winter_Camp<filename>Sergeant-RANK/PRACTICE/1420A.py for _ in range(int(input())): n = int(input()) l = list(map(int, input().split(" "))) is_true = False for i in range(1, n): if l[i] >= l[i-1]: is_true = True break if ...
StarcoderdataPython
3203611
"""Base class for MailComposer objects.""" import os import textwrap from .exceptions import MailComposerError class BaseMailComposer(object): """Base class for MailComposer objects. Your subclass should implement the display() method to open the message in its corresponding external application. "...
StarcoderdataPython
4810257
<filename>atividade2/util.py # -*- coding: utf-8 -*- ''' Metodos a serem usados em mais de uma questao serao colocados aqui ''' # Definicao de metodos def truncar(valor): if(valor < 0.0): return 0.0 elif(valor > 255.0): return 255.0 return valor
StarcoderdataPython
133673
<gh_stars>0 # Import Vancouver's lost animals into Elasticsearch import urllib import json from pprint import pprint from datetime import datetime from elasticsearch import Elasticsearch vancouverLostAnimalsFtp = 'ftp://webftp.vancouver.ca/OpenData/json/LostAnimals.json' print "Importing Vancouver lost & found anima...
StarcoderdataPython
1679812
<reponame>Mesitis/community ''' - login and get token - process 2FA if 2FA is setup for this account - Returns whether or not a given security exists using either name or ticker. ''' import requests import json get_token_url = "https://api.canopy.cloud:443/api/v1/sessions/" validate_otp_url = "https://api.canopy.clo...
StarcoderdataPython
3338239
<filename>tests/test_main.py<gh_stars>1-10 import csv import os from tempfile import TemporaryDirectory import pytest from click.testing import CliRunner from qdc_converter import main as converter_main from qdc_converter.utils import get_files_recursively @pytest.fixture(scope='module') def runner(): return Cli...
StarcoderdataPython
3334223
<filename>bikeshares/programs/boston.py<gh_stars>1-10 import bikeshares import pandas as pd import numpy as np def convert_rider_gender(x): if type(x) != str and np.isnan(x): return np.nan if x == "Male": return "M" if x == "Female": return "F" raise Exception("Unrecognized gender variable: {0}".format...
StarcoderdataPython
1788881
<reponame>cyperior7/MBEDataMechanics<filename>mergedList.py import json import dml import prov.model import datetime import pandas as pd import uuid class mergedList(dml.Algorithm): contributor = 'ashwini_gdukuray_justini_utdesai' reads = ['ashwini_gdukuray_justini_utdesai.masterList', 'ashwini_gdukuray_justi...
StarcoderdataPython
3262822
<reponame>birds-on-mars/birdsonearth<filename>VGGish_model.py import torch import torch.nn as nn from torch.nn.functional import relu, softmax from torch.utils.data import DataLoader import h5py as h5 import os import params as p class VGGish(nn.Module): def __init__(self, params): super(VGGish, self)....
StarcoderdataPython
1661156
<filename>Objects/Background.py from Objects.Object import Object class Background(Object): def __init__(self, pPixellength): self.pixellength = pPixellength self.color = [0, 0, 0] super().__init__(True, self.pixellength - 1, [self.color] * self.pixellength) def setColor(self, color)...
StarcoderdataPython
33941
import numpy as np import time import pytest import jax.numpy as jnp import jax.config as config import torch import tensorflow as tf from tensornetwork.linalg import linalg from tensornetwork import backends from tensornetwork.backends.numpy import numpy_backend from tensornetwork.backends.jax import jax_backend #pyli...
StarcoderdataPython
1769536
<gh_stars>0 #!/usr/bin/python import sys import time def creat_newpost(post_name): # current_time = time.time() post_url = '-'.join(post_name.split()) post_date = time.strftime('%Y-%m-%d') post_time = time.strftime('%Y-%m-%dT%H:%M:%S') post_path = './{}-{}.md'.format(post_date, post_url) init_content = \ """---...
StarcoderdataPython
3307132
from shapes import PolygonInterpolator, normals_offset, midpoints import matplotlib.pyplot as plt import shapely.geometry as geom import numpy as np import matplotlib.animation as animation import scipy.spatial as spatial from copy import copy #p1s = geom.box(0, 0, 1, 1) #p2s = geom.box(-1, -1, 2, 2) p1s = geom.Pol...
StarcoderdataPython
3314718
<filename>common/mysqldatabasecur.py """ @author: @file: mysqldatabasecur.py @time: 2018/3/9 15:46 """ """ 接口用例测试查询测试数据库测试结果对比, 现在支持查询mysql,进行对比 """ from pymysql import * '''链接数据库,code为1即链接成功,error为错误信息,conne为返回的链接的实例''' def cursemsql(host, port, user, password, database): try: conne = connect(host=ho...
StarcoderdataPython
1605820
import os import collections import gym import numpy as np import joblib import tensorflow.compat.v1 as tf from baselines.common.policies import build_policy from gfootball.env import football_action_set from gfootball.env import player_base from gfootball.env.wrappers import Simple115StateWrapper class Player(player...
StarcoderdataPython
3347129
from django.urls import path from pastry_shop.blog.views import ( PostListView, PostDetailView, PostCreateView, PostEditView, PostDeleteView, CommentEditView, CommentDeleteView, ) app_name = "blog" urlpatterns = [ path("posts/", PostListView.as_view(), name="post-list"), path("pos...
StarcoderdataPython
3202764
<gh_stars>1-10 import logging import sys from calculator_handler import CalculatorHandler if __name__ == '__main__': root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)...
StarcoderdataPython
38462
import numpy as np import random import numexpr as ne def gen_layer(rin, rout, nsize): R = 1.0 phi = np.random.uniform(0, 2*np.pi, size=(nsize)) costheta = np.random.uniform(-1, 1, size=(nsize)) u = np.random.uniform(rin**3, rout**3, size=(nsize)) theta = np.arccos( costheta )...
StarcoderdataPython
76293
# Lint as: python3 # Copyright 2020 DeepMind Technologies Limited. 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 # # ...
StarcoderdataPython