id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1659355 | <filename>python/ef5_inundation.py
#
# Processes Flood Inundation Maps from EF5 http://flash.ou.edu/pakistan/
#
import os, sys
from datetime import date
from dateutil.parser import parse
import glob, fnmatch, urllib, math, shutil
from osgeo import gdal
import numpy
import argparse
import config
import json
from brow... | StarcoderdataPython |
3283925 | <filename>hypernode_monitoring/hn_config.py
"""
Bismuth
Configuration variables for HN monitoring script
"""
IP="127.0.0.1"
PORT="6969"
HN_PATH="/root/hypernode/modules"
HN_ADDRESS="your_hypernode_address_here_starts_with_a_B"
TIMEOUT_1=20
TIMEOUT_2=30
OUTFILE_1="/path/status.json"
OUTFILE_2="/path/hypernodes.json"
OU... | StarcoderdataPython |
20121 | <filename>models/dl-weights.py
"""
This script downloads the weight file
"""
import requests
URL = "https://pjreddie.com/media/files/yolov3.weights"
r = requests.get(URL, allow_redirects=True)
open('yolov3_t.weights', 'wb').write(r.content)
| StarcoderdataPython |
3241370 | import numpy as np
import cv2
from mscoco import table
def get_classes(index):
obj = [v for k, v in table.mscoco2017.items()]
sorted(obj, key=lambda x:x[0])
classes = [j for i, j in obj]
np.random.seed(420)
colors = np.random.randint(0, 224, size=(len(classes), 3))
return classes[index], tuple... | StarcoderdataPython |
71582 | <reponame>mbarbon/vdebug<gh_stars>1-10
import vdebug.opts
import vdebug.log
import vim
import re
import os
import urllib
import time
class Keymapper:
"""Map and unmap key commands for the Vim user interface.
"""
exclude = ["run","set_breakpoint","eval_visual"]
def __init__(self):
self._reload... | StarcoderdataPython |
1745363 | from argparse import ArgumentParser
from typing import List, Dict
import pandas as pd
import numpy as np
import os
from glob import glob
from itertools import combinations, product
from common import Role, Argument
from evaluate import Metrics, joint_len, iou
from evaluate_dataset import eval_datasets, yield_paired_p... | StarcoderdataPython |
3317585 | <reponame>Alex014/CryptoContainer
from classes.CryptorRSA import CryptorRSA
import base64
import rsa
cryptor = CryptorRSA(rsa_bits=512, blowfish_bits=256)
(pubkey, privkey) = cryptor.generate()
print("\n *** Public key: \n" + pubkey.decode('utf-8'))
print("\n *** Private key: \n" + privkey.decode('utf-8'))
msg = "P... | StarcoderdataPython |
1622837 | name = ''
while True:
print('Please type your name.')
name = input()
# if name equals to 'your name', then jump out of loop
if name == 'your name':
break
print('Thank you!')
| StarcoderdataPython |
1702327 | from utils import *
from pprint import pprint as pp
import requests, json, sys, decimal
from datetime import datetime, timedelta
#organizations/self/accounts/LIQUID/transactions\?start=2020-08-01T00:00:00\&end=2020-08-14T00:00:00\&includeTransactionType=PAYOUT
if len(sys.argv) != 2:
sys.stderr.write('Usage: %s <d... | StarcoderdataPython |
4817207 | from __future__ import print_function
import logging
import backoff
from throttle import throttle
from config import __packagename__
class Resiliently(object):
def __init__(self, config):
self._config = config
if config.verbose:
logging.getLogger('backoff').addHandler(logging.StreamHand... | StarcoderdataPython |
1775431 | #!/usr/bin/python2.7
"""
Copyright (c) 2014, ICFLIX Media FZ LLC All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
Desc: Generate Nagios configuration from given file, resp. from check_multi.
"""
import logging
import logging.handlers
import json
imp... | StarcoderdataPython |
1643023 | #! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from builddata_ecir import *
from capsuleNet_SEARCH17 import CapsE
np.random.seed(1234)
tf.set_random_seed(1234)
# Parameters
# ==================... | StarcoderdataPython |
3363506 | <reponame>epfl-dcsl/ptf-persona<filename>app/simple.py
# Copyright 2019 École Polytechnique <NAME>. 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.apa... | StarcoderdataPython |
1709088 | # -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import lxml
import json
import time
from random import randrange
FILE = 'ParseResults.csv'
HOST = 'https://www.citilink.ru/catalog/smartfony/'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/'
... | StarcoderdataPython |
3283558 | from unittest import TestCase
from piccolo.apps.user.tables import BaseUser
from piccolo.conf.apps import AppRegistry, AppConfig, table_finder
from ..example_app.tables import Manager
class TestAppRegistry(TestCase):
def test_get_app_config(self):
app_registry = AppRegistry(apps=["piccolo.apps.user.picc... | StarcoderdataPython |
3267824 | <filename>LeetCode_easy/1-bit&2-bitCharacters_717.py
# -*- coding: utf-8 -*-
'''
717. 1-bit and 2-bit Characters
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
Now given a string represented by several bits. Return w... | StarcoderdataPython |
3238233 | from django.contrib.auth.models import User, Group
from restapp.models import Character
from rest_framework import viewsets
from restapp.serializers import UserSerializer, GroupSerializer, CharacterSerializer
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from django.shortcuts import ... | StarcoderdataPython |
1636057 | <gh_stars>10-100
# -*- coding: utf-8 -*-
import configparser
import os
cfile = os.path.join(os.path.dirname(__file__), 'config.ini')
cfg = configparser.ConfigParser()
cfg.read(cfile)
try:
cfg.has_section('API')
except:
raise Exception('Config File was not read.')
def get_urlroot():
urlroot = cfg['API... | StarcoderdataPython |
4801058 | <reponame>dan-fritchman/Hdl21<filename>scratch/diff.py
"""
# Hdl21 Differential Bundle and Facilities for Differential Circuits
"""
from pydantic.dataclasses import dataclass
# Local imports
from .signal import Signal
from .bundle import bundle
from .instantiable import Instantiable
@bundle
class DiffSomething:
... | StarcoderdataPython |
3375465 | <filename>auth-utils/s3iamcli/s3iamcli/accountloginprofile.py<gh_stars>10-100
#
# Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates
#
# 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 ... | StarcoderdataPython |
174970 | <reponame>cgmark101/mark1-translate
import re, requests
agent = {
'User-Agent': "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1;.NET CLR 1.1.4322;.NET CLR 2.0.50727;.NET CLR 3.0.04506.30)"}
def translate(to_translate, to_language="auto", from_language="auto"):
base_link = f"http://translate.google.com/m... | StarcoderdataPython |
1731099 | <gh_stars>0
from .account import AccountView
from .meta import MetaView
from .structures import StructuresView
| StarcoderdataPython |
3381926 | <reponame>mwk0408/codewars_solutions
from functools import reduce
def nico(key, message):
temp=[[] for i in range(len(key))]
for i in range(len(message)):
temp[i%len(key)].append(message[i])
maxlen=len(temp[0])
dict={}
for i in range(len(temp)):
dict[key[i]]=temp[i]
res=sorted(di... | StarcoderdataPython |
1756932 | <gh_stars>1-10
_ = input()
a = set(input().split())
_=input()
b = set(input().split())
print(len(a.difference(b)))
| StarcoderdataPython |
3301049 | #!/usr/bin/env
# -*- coding: utf-8 -*-
import config
"""
This function prints log message on console along with the Tag string
@param log_type - Tag string ("ERROR", "TEST", "INFO").
@param log_msg - log message to print.
"""
def LOG ( log_type, log_msg ):
if log_type == "TEST":
print ("["+log_type+"]... | StarcoderdataPython |
3205889 | <gh_stars>0
__all__ = ['biobrain', 'utils']
| StarcoderdataPython |
1717299 | <gh_stars>1-10
from src.message_listener import MessageListener
from src.message_type import MessageType
class MessageSender:
def __init__(self):
self.message_listeners = []
def register_message_listener(self, message_listener: MessageListener):
self.message_listeners.append(message_listener)... | StarcoderdataPython |
1758354 | <filename>microstrategy_api/task_proc/task_proc.py<gh_stars>0
import re
import urllib.parse
import warnings
from enum import Enum
import time
from fnmatch import fnmatch
from typing import Optional, List, Set, Union
import requests
import logging
from bs4 import BeautifulSoup
from microstrategy_api.task_proc.doc... | StarcoderdataPython |
1744788 | <reponame>markscheel/scri<gh_stars>10-100
import math
import numpy as np
import quaternion
import spinsfast
import spherical_functions as sf
def _process_transformation_kwargs(input_ell_max, **kwargs):
original_kwargs = kwargs.copy()
# Build the supertranslation and spacetime_translation arrays
supertran... | StarcoderdataPython |
4832982 | # Generated by Django 3.1 on 2020-09-29 05:33
import django.db.models.deletion
import django_extensions.db.fields
from django.conf import settings
from django.db import migrations, models
import library.django_utils
import library.utils
class Migration(migrations.Migration):
initial = True
dependencies = ... | StarcoderdataPython |
3322348 | <filename>src/mau/lexers/base_lexer.py
import re
import string
from functools import partial
from collections.abc import Sequence
from mau import text_buffer
class TokenTypes:
EOL = "EOL"
EOF = "EOF"
LITERAL = "LITERAL"
TEXT = "TEXT"
WHITESPACE = "WHITESPACE"
class LexerError(ValueError):
p... | StarcoderdataPython |
1655628 | <reponame>BryceHaley/curriculum-jbook<gh_stars>1-10

<a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=ma... | StarcoderdataPython |
3341285 | import os
import pandas as pd
from tqdm import tqdm
def load_tag_info(path):
tag_info = open(path).read()
tag_info = tag_info.replace(' ', ' ')
tag_info = tag_info.replace(' ', ' ')
tag_info = tag_info.replace(' ', ' ')
tag_info = tag_info.replace(':', '')
tag_info = tag_info.replace(' \n'... | StarcoderdataPython |
3379507 | from dataclasses import dataclass
from typing import Generic, GenericAlias, TypeVar
T = TypeVar("T")
U = TypeVar("U")
@dataclass
class _Point(Generic[T, U]):
x: T
y: U
class _Point_(_Point):
@classmethod
def __class_getitem__(cls):
return GenericAlias
class _Display_(_Point):
def __re... | StarcoderdataPython |
1674545 | <gh_stars>0
from flask import Flask
from flask import render_template
app = Flask(__name__)
app.config.update(
DEBUG=True,
SEND_FILE_MAX_AGE_DEFAULT=0
)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True, port=80)
| StarcoderdataPython |
1611988 | from __future__ import unicode_literals
import json
from django.db import models
from django.utils.six import text_type as str
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from django.utils import timezone
from django.contrib.auth.models import (AbstractBaseUser, Permissions... | StarcoderdataPython |
1711305 | import torch
import torch.nn as nn
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class DQN(nn.Module):
def __init__(self, n_action_space):
super(DQN, self).__init__()
self.s1 = nn.Sequential(
nn.C... | StarcoderdataPython |
1621099 | from brigitte.repositories.models import Repository
from brigitte.accounts.models import SshPublicKey
from brigitte.repositories.backends.base import ShellMixin
import os
def generate_gitolite_conf(file_path):
file_obj = open(file_path, 'w')
lines = [
'repo gitolite-admin\n',
'\tRW+ =... | StarcoderdataPython |
185255 | from Piece import Piece, Pawn, Rook, Knight, Bishop, Queen, King
class Move(object):
"""Contains all the move methods"""
def __init__(self):
pass
def set_new_game(self):
"""
Initializes pieces for a new chess game.
Uses two for loops and if/else statements to set the pieces... | StarcoderdataPython |
38661 | #!/usr/bin/env python3
"""Benchmark icontract against deal when used together with hypothesis."""
import os
import sys
import timeit
from typing import List
import deal
import dpcontracts
import hypothesis
import hypothesis.extra.dpcontracts
import hypothesis.strategies
import icontract
import tabulate
import icontr... | StarcoderdataPython |
1794796 | from django.db import models
# Create your models here.
class Location(models.Model):
location_name = models.CharField(max_length = 25)
def __str__(self):
return self.location_name
def save_location(self):
self.save()
def delete_location(location_id):
Location.objects.filter(... | StarcoderdataPython |
3277683 | begin_unit
comment|'# Copyright (c) 2012 Rackspace Hosting'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
c... | StarcoderdataPython |
183923 | class Node:
def __init__(self, data) -> None:
self.data = data
self.right = self.down = None
class LinkedList:
def __init__(self) -> None:
self.head = self.rear = None
def insert(self, item, location):
temp = Node(item)
if self.rear == None:
... | StarcoderdataPython |
1709001 | <filename>tests/test_theme.py
from typing import Any, Dict
import pytest
from grgr.ggplot2.theme import Theme, ThemeElement
@pytest.mark.parametrize("kwargs, answer", [
({
"foo": '"bar"'
}, 'test(foo="bar")'),
({
"foo_bar": '"bar"'
}, 'test(foo.bar="bar")'),
({
"foo": '"ba... | StarcoderdataPython |
1671800 | <filename>main.py
from openie import StanfordOpenIE
import os
import sys
import spacy
import neuralcoref
import stanza
from nltk.parse import stanford
from nltk.parse.stanford import StanfordParser
from nltk.tree import ParentedTree, Tree
from numpy import *
import warnings
warnings.filterwarnings('ignore')
java_pat... | StarcoderdataPython |
1602173 | """
Download Youtube Watch Later playlist to a local directory, eternalize it,
then remove playlist.
Usage:
yt-download-watch-later [options]
Options:
-h, --help Display this message.
--version Show version information.
"""
VERSION = 1.0
import subprocess
import shutil
import glob
import sys, os
im... | StarcoderdataPython |
182620 | <reponame>andrew-miao/ECE657A_Project-text-classification
import torch
import torch.nn as nn
import torch.nn.functional as F
from LSTM_Attn_GRU.config_LSTMAttnGRU import Config
class LSTMAttnGRU(nn.Module):
def __init__(self, output_size):
super(LSTMAttnGRU, self).__init__()
self.lstm = nn.LSTM(C... | StarcoderdataPython |
3258288 | <filename>JPS_Chatbot/UI/source/test/fill_the_cache.py
# in one hour, after one c
#
import time
import urllib
import urllib.parse
import urllib.request
import re
from datetime import datetime
import random
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulS... | StarcoderdataPython |
79291 | <filename>{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/settings.py<gh_stars>0
"""
Global settings for project.
May be just some literals, or path-related values.
{%- if cookiecutter.use_environment_based_settings %}
All environment-based settings should be declared here too.
{%- endif %}
"""
import pa... | StarcoderdataPython |
119714 | <filename>explicates/exporter.py
# -*- coding: utf8 -*-
"""Exporter module."""
import json
import string
import tempfile
import zipfile
import unidecode
from flask import current_app
from sqlalchemy import and_
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
from explicates.... | StarcoderdataPython |
4816211 |
import logging
import webapp2
import json
import logic
from models import Rating, PFuser, ClusterRating, Place, Discount
from google.appengine.api import memcache, taskqueue
from datetime import datetime
def put_user_in_cluster(user):
ratings = Rating.get_list({'user': user.key.id()})
rlist = {}
fo... | StarcoderdataPython |
4801690 | ###############################################################################
# Copyright (c) 2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory
# Written by <NAME>, <EMAIL>.
#
# LLNL-CODE-734340
# All rights reserved.
# This file is part of MaestroWF, Version: 1... | StarcoderdataPython |
1792310 | <reponame>frenzylabs/ancilla<filename>ancilla/ancilla/foundation/node/api/file.py
'''
file.py
ancilla
Created by <NAME> (<EMAIL>) on 01/08/20
Copyright 2019 FrenzyLabs, LLC.
'''
import time
import os, random, string
import asyncio
import math
from .api import Api
from ..events import FileEvent
from ...data.mod... | StarcoderdataPython |
189660 | import unittest
import file01 as file
class TestBasicCalculation(unittest.TestCase):
def test_check_key(self):
self.assertEqual(file.check_key(-1), False)
self.assertEqual(file.check_key(0), True)
self.assertEqual(file.check_key(1), True)
self.assertEqual(file.check_key(50), True)... | StarcoderdataPython |
3376932 | <filename>Bugscan_exploits-master/exp_list/exp-1639.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#__Author__ = zhiyuan
#___Sertype___ = WordPress wp-miniaudioplayer任意文件下载漏洞
def assign(service, arg):
if service == "wordpress":
return True, arg
def audit(arg):
payload = 'wp-content/plugins/wp-... | StarcoderdataPython |
1792182 | import sys
import os, os.path
import shutil
if sys.version_info < (3,):
range = xrange
def CheckParameter():
outputPath = None
searchStartDir = None
isIncludeFolder = None
excludePaths = None
count = len(sys.argv)-1
if count >= 8:
for i in range(1, count):
if sys.argv[i] == "-OutputPath":
ou... | StarcoderdataPython |
1793470 | <filename>apps/questions_app/api/views.py<gh_stars>0
from rest_framework import generics
from apps.questions_app.api.serializers import (QuestionSerializer)
from apps.questions_app.models import Question
import random
class QuestionsListAPIView(generics.ListAPIView):
"""this endpoint randomly returns a list of ... | StarcoderdataPython |
37372 | #!/usr/bin/python3
'''
BubbleSort.py
by <NAME>
'''
array = []
print("Enter at least two numbers to start bubble-sorting.")
print("(You can end inputing anytime by entering nonnumeric)")
# get numbers
while True:
try:
array.append(float(input(">> ")))
except ValueError: # exit inputing
break
print("\nThe array... | StarcoderdataPython |
31734 |
# IMAGES #
# UI NAVIGATION #
img_addFriend = "add_friend.png"
img_allow = "allow.png"
img_allowFlash = "enableflash_0.png"
img_allowFlash1 = "enableflash_1.png"
img_allowFlash2 = "enableflash_2.png"
img_alreadyStarted = "alreadystarted.png"
img_alreadyStarted1 = "alreadystarted1.png"
img_backButton = "back_button.png... | StarcoderdataPython |
22808 | import os
import sys
import shutil
import glob
import time
import multiprocessing as mp
if len(sys.argv)!=4:
print("Usage: ")
print("python extract_features_WORLD.py <path_to_wav_dir> <path_to_feat_dir> <sampling rate>")
sys.exit(1)
# top currently directory
current_dir = os.getcwd()
# input audio direct... | StarcoderdataPython |
3256213 | <filename>visualizer/main_ui.py<gh_stars>0
import eel
import json
import cv2
import base64
import numpy as np
from PIL import Image as PILlib
import io
import re
import sys, os
from threading import Thread
class Images:
@staticmethod
def read(im_path):
return cv2.imread(im_path)
@staticmethod
... | StarcoderdataPython |
1793830 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'page2.ui'
#
# Created by: PyQt5 UI code generator 5.15.5
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui,... | StarcoderdataPython |
1656308 | from mock import MagicMock
from tests.unit import UnitTestBase
from express.properties.non_scalar.two_dimensional_plot.band_structure import BandStructure
from tests.fixtures.data import BAND_STRUCTURE, HSE_EIGENVALUES_AT_KPOINTS, HSE_BAND_STRUCTURE, EIGENVALUES_AT_KPOINTS
class BandStructureTest(UnitTestBase):
... | StarcoderdataPython |
106746 | <reponame>cogment/cogment-verse
# Copyright 2021 AI Redefined Inc. <<EMAIL>>
#
# 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 requi... | StarcoderdataPython |
110039 | # This is a dummy file to allow the automatic loading of modules without error on none.
def setup(robot_config):
return
def say(*args):
return
def mute():
return
def unmute():
return
def volume(level):
return | StarcoderdataPython |
3353275 | <filename>tests/test_compile_acs.py
import os
from mazeexplorer.compile_acs import compile_acs
dir_path = os.path.dirname(os.path.realpath(__file__))
def test_compile_acs(tmpdir):
compile_acs(tmpdir.strpath)
assert os.path.isfile(os.path.join(tmpdir, "outputs", "maze.o"))
assert os.path.getsize(os.path.... | StarcoderdataPython |
3238450 | import random
import pygame
from basic_model.block import Block
from basic_model.occupant import Occupant
from simu_model.simuboard import SimuBoard
from simu_model.status import Status
class GuiBoard(SimuBoard):
def __init__(self, height, width):
super(GuiBoard, self).__init__(height,width)
self... | StarcoderdataPython |
1745854 | <gh_stars>0
'''
@author: daniel
'''
## mongoDB
mongoDB_IP = '127.0.0.1'
mongoDB_Port = 27017 # default local port. change this if you use SSH tunneling on your machine (likely 4321 or 27017).
mongoDB_db = 'pub'
## conferences we analysed
booktitles = ['ACL', 'JCDL','SIGIR','ECDL','TPDL','TREC', 'ICWSM', 'ESWC', 'ICS... | StarcoderdataPython |
66150 | <gh_stars>0
from aiflearn.explainers.explainer import Explainer
from aiflearn.explainers.metric_text_explainer import MetricTextExplainer
from aiflearn.explainers.metric_json_explainer import MetricJSONExplainer
| StarcoderdataPython |
3205834 | <reponame>nojoven/CommentsGate
from datetime import datetime
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
from utils.helpers import generate_uuid
from database import Base
class Comment(Base):
__tablename__ = "comments"
id = Column(
String, unique=True, primary_key... | StarcoderdataPython |
9009 | import pandas as pd
from tqdm import tqdm
data_list = []
def get_questions(row):
global data_list
random_samples = df.sample(n=num_choices - 1)
distractors = random_samples["description"].tolist()
data = {
"question": "What is " + row["label"] + "?",
"correct": row["description"],
... | StarcoderdataPython |
4811432 | from application import db
class TimestampMixin(object):
created = db.Column(db.TIMESTAMP,
default=db.func.utc_timestamp())
modified = db.Column(db.TIMESTAMP,
default=db.func.utc_timestamp(),
onupdate=db.func.utc_timestamp()) | StarcoderdataPython |
3382595 | #!/usr/bin/env python3
"""
Duplicate OpenGL coordinate system...
See:
https://gamedev.stackexchange.com/questions/153078/what-can-i-do-with-the-4th-component-of-gl-position
"""
import sys
from math import sin, cos, pi, sqrt
import numpy
scalar = numpy.float64
EPSILON = 1e-6
class Mat(object):
def __init__(sel... | StarcoderdataPython |
146911 | # coding=utf-8
# Copyright 2022 The Google Research 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | StarcoderdataPython |
1784148 | from xml.etree.cElementTree import parse, Element, ElementTree, dump
from os import walk
from os.path import join
from optparse import OptionParser
description = "Update the master package.config from individual project ones."
command_group = "Developer tools"
# Snippet used from the ElementTree documentation.
# Tidy... | StarcoderdataPython |
4819507 | import os
import random
import mnemonic
import string
from pyblake2 import blake2b
import base58
def generate_mnemonic(language='english'):
""" Generate Mnemonic: Creates insecure random nmemonics for testing
Args:
language (str): defaults to english , all bip languages are supported.
Returns:
... | StarcoderdataPython |
1739075 | <gh_stars>0
import os
import json
import requests
import datetime
import time
from tqdm import tqdm
from multiprocessing import Pool
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i : i + n]
app_key = ""
app_id = ""
with open("credentials.json", "r") as cred_file:
creds = json.load(c... | StarcoderdataPython |
144890 | import numpy as np
import pytest
from ome_zarr.scale import Scaler
class TestScaler:
@pytest.fixture(
params=(
(1, 2, 1, 256, 256),
(3, 512, 512),
(256, 256),
),
ids=["5D", "3D", "2D"],
)
def shape(self, request):
return request.param
... | StarcoderdataPython |
1791615 | import logging
from bs4 import BeautifulSoup
from dateutil import parser
from config import Config
from jamaClient import JamaClient
class Process:
def __init__(self):
self.jama_client = JamaClient()
self.items = []
self.jama_config = Config()
self.jama_client.setConfig(self.jama... | StarcoderdataPython |
3212202 | <filename>DGF/__init__.py
from .fields import Field
from .models import Schema
from .combiner import Combiner
from .pipeline import BaseLink, QUERY, ADD, CHANGE, DELETE
from .auth.permission import BasePermission
from .auth.authenticator import BaseAuthenticator
from .auth.permission import BasePermission
from .excepti... | StarcoderdataPython |
3293146 | from .loss import EvidentialLossSumOfSquares
from .paper_loss import PaperEvidentialLossSumOfSquares
| StarcoderdataPython |
1696172 | <reponame>20c/django-inet<filename>tests/test_models.py
import ipaddress
import pytest
from django.core.exceptions import ValidationError
from django.test import TestCase
from models import FullModel
from django_inet.models import (
ASNField,
IPAddressField,
IPNetworkField,
IPPrefixField,
MacAddre... | StarcoderdataPython |
169554 | '''
Module to define the dataset(s) used for training and validation
'''
__author__ = '<NAME>'
from simpleml.datasets import PandasDataset
import os
import numpy as np
import pandas as pd
import requests
import cv2
from tqdm import tqdm
current_directory = os.path.dirname(os.path.realpath(__file__))
NEGATIVE_IMAG... | StarcoderdataPython |
178020 | <filename>examples/heartbeat/service.py
import asyncio
import traceback
import json
from asyncio.queues import Queue
from collections import defaultdict
from uuid import uuid4 as uuidv4
import websockets
from helpers import ServmanAgent, action
from typings import IParcel
from path import Path
class PongService(Servm... | StarcoderdataPython |
1676424 | #
# This file contains the Python code from Program 6.8 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by <NAME>.
#
# Copyright (c) 2003 by <NAME>, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm06_08.txt
#
class StackAsLinkedList(Stack):
... | StarcoderdataPython |
10601 | # Copyright 2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | StarcoderdataPython |
3285863 | <gh_stars>0
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
c... | StarcoderdataPython |
4826743 | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
This is an example where:
1. An sequence of fMRI volumes are simulated
2. A design matrix describing all the effects related to the data is computed
3. A GLM is applied to all vox... | StarcoderdataPython |
55569 | <filename>toughradius/manage/models.py<gh_stars>1-10
#!/usr/bin/env python
#coding:utf-8
import sqlalchemy
import warnings
warnings.simplefilter('ignore', sqlalchemy.exc.SAWarning)
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation
from sqlalchemy.orm im... | StarcoderdataPython |
3328820 | <filename>app/accounts/btc_xpub.py
import requests
from btcpy.setup import setup
from btcpy.structs.hd import ExtendedPublicKey
from btcpy.structs.address import P2shAddress, P2wpkhAddress
from .. import Account
setup('mainnet')
# TO DO:
# Separate addresses into different balances (name each, e.g. 'change0, spend1'... | StarcoderdataPython |
3207136 | #!/bin/python3
import os
import sys
import heapq
def addNum(num, lowers, highers):
if not lowers or num < -lowers[0]:
heapq.heappush(lowers,-num)
else:
heapq.heappush(highers,num)
def rebalance(lowers, highers):
if len(lowers) - len(highers) >= 2:
heapq.heappush(highers,-heapq... | StarcoderdataPython |
1635085 | <reponame>lazypwny751/ChmodCalculator
import tkinter as tk
import os
from modules import *
if os.name == "nt":
os.system("cls")
elif os.name == "posix":
os.system("clear")
banner = Beyaz+"""
██╗ ██████╗ ██████╗ ███████╗
██║ ██╔═══██╗██╔════╝ ██╔════╝
██║ ██║ ██║██║ ███╗███████╗
█... | StarcoderdataPython |
3256949 | <reponame>mgiangreco/apartments-scraper
import boto3
import csv
import datetime
import json
import re
import sys
import datetime
import requests
import os
from bs4 import BeautifulSoup
# Config parser was renamed in Python 3
try:
import configparser
except ImportError:
import ConfigParser as configparser
def ... | StarcoderdataPython |
1754735 | <filename>devdb/forms.py
from django import forms
from models import DeveloperRegistration
from datetime import datetime
import logging
import md5
class DeveloperRegistrationForm(forms.Form):
contact_name = forms.CharField(initial='<NAME>')
website_url = forms.URLField(label='Your website')
email = forms.EmailField... | StarcoderdataPython |
3395958 | from django.shortcuts import render
import requests
import json
import pandas as pd
# Create your views here.
def parseapi(request):
api= requests.get('https://s3.amazonaws.com/open-to-cors/assignment.json')
print(api.status_code)
data = api.text
# storing the JSON response from url in data
parse_... | StarcoderdataPython |
102684 | from .assigners import BaseAssigner, HungarianAssigner
from .builder import build_sampler, build_assigner
from .samplers import BaseSampler, PseudoSampler, SamplingResult
from .transforms import hoi2result
__all__ = [
'BaseAssigner', 'HungarianAssigner', 'build_assigner', 'build_sampler',
'BaseSampler', 'Pseud... | StarcoderdataPython |
90674 | <filename>test_stats.py
from copy import copy, deepcopy
import os
import time
import unittest
from characteristics_damages import *
from stats import Stats
class TestStats(unittest.TestCase):
def test_create_empty(self):
empty_characteristics = [0 for _ in range(CHARACTERISTICS_COUNT)]
empty_dam... | StarcoderdataPython |
1780142 | from __future__ import unicode_literals
from youtube_dlc.extractor.common import InfoExtractor
class SamplePluginIE(InfoExtractor):
_WORKING = False
IE_DESC = False
_VALID_URL = r'^sampleplugin:'
def _real_extract(self, url):
self.to_screen('URL "%s" sucessfully captured' % url)
| StarcoderdataPython |
3303820 | <filename>threads/kmeans_test.py
def main():
## Initialisation
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
df=pd.read_csv('sampledata.csv')
#print(df1)
a=df.iloc[0]
b=df.iloc[1]
c=df.iloc[2]
d=df.iloc[3]
e=df.iloc[4]
f=df.il... | StarcoderdataPython |
3243350 | <gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.cont... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.