id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
137893 | import numpy as np
from mapper_0000 import Mapper_0000
class Cartridge:
def __init__(self, name: str):
# Variables for values about the cartridge
self.bImageValid = False
self.nMapperID = np.uint8(0)
self.nPRGBanks = np.uint8(0)
self.nCHRBanks = np.uint8(0)
... | StarcoderdataPython |
5138917 | <reponame>two/megumegu.py
# -*- coding: utf-8 -*-
from __future__ import print_function
import warnings
import MySQLdb
class QueryMixin(object):
def sql(self):
raise NotImplementedError
def get_sites(self):
return self.sql("""SELECT mm_site.id as id, name, mm_site.url as url, url2, schedule... | StarcoderdataPython |
8057755 | <gh_stars>10-100
def sum1(a,b):
c = a+b
return c
def mul1(a,b):
c = a*b
return c
| StarcoderdataPython |
1779718 | <filename>backend/migrations/versions/f58846daf788_.py<gh_stars>0
"""empty message
Revision ID: f<PASSWORD>
Revises: None
Create Date: 2016-02-01 13:11:53.606417
"""
# revision identifiers, used by Alembic.
revision = 'f58846daf<PASSWORD>'
down_revision = None
from alembic import op
import sqlalchemy as sa
def up... | StarcoderdataPython |
12821576 | <filename>arekit/contrib/networks/context/architectures/base/att_pcnn_base.py
import tensorflow as tf
from arekit.contrib.networks.attention import common
from arekit.contrib.networks.attention.helpers import embedding
from arekit.contrib.networks.context.architectures.pcnn import PiecewiseCNN
class AttentionPCNNBas... | StarcoderdataPython |
393944 | <reponame>denkasyanov/education-backend
import pytest
from freezegun import freeze_time
from a12n.utils import get_jwt
pytestmark = [
pytest.mark.django_db,
pytest.mark.freeze_time('2049-01-05'),
]
@pytest.fixture
def refresh_token(api):
def _refresh_token(token, expected_status_code=201):
retur... | StarcoderdataPython |
60061 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 15:41:38 2018
@author: steve
"""
import re,types
from HeroLabStatBase import VERBOSITY,Character
OPERATORS = ["<",">","==",">=","<=","<>","!=","is","not","in","and","or"]
class Matcher(object):
"""
Container for attributes and methods related to finding repla... | StarcoderdataPython |
11253363 | # -*- coding: utf8 -*
from time import sleep
import logging
from main_data import MainData
from toolbox import exit_prog, log_record
from read_options import read_opt
from webdriver import (
get_webdriver,
open_url,
wait_window,
get_webdriver_quit,
find_one_element_by_id,
get_info_... | StarcoderdataPython |
9688457 | # vim: filetype=python
## load our own python modules
import system
import os, string, platform, subprocess, shutil
import re
## create a top level alias so that the help system will know about it
ALIASES = ''
def top_level_alias(env, name, targets):
global ALIASES
ALIASES = '%s %s' % (ALIASES, name)
env.A... | StarcoderdataPython |
5087681 | <gh_stars>0
""""
This is a parser for the header section of KAF/NAF
"""
from lxml import etree
import time
import platform
class CfileDesc:
"""
This class encapsulates the file description element in the header
"""
def __init__(self,node=None):
"""
Constructor of the object
@t... | StarcoderdataPython |
8181088 | from dataclasses import dataclass
from typing import Any, Tuple
from omegaconf import MISSING
@dataclass
class OptimizerConfig:
params: Any = MISSING
lr: float = MISSING
@dataclass
class AdamConfig(OptimizerConfig):
_target_: str = "torch.optim.Adam"
betas: Tuple[float, float] = MISSING
eps: fl... | StarcoderdataPython |
1893420 | <filename>submissions/abc061/c.py<gh_stars>1-10
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
n, k = map(int, readline().split())
ab = [tuple(map(int, readline().split())) for _ in range(n)]
ab.sort()
for a, b in ab:
... | StarcoderdataPython |
3592225 | <gh_stars>0
#! /Users/nsanthony/miniconda3/bin/python
import rooms.room_class as rc
blank = rc.room()
blank.name = 'cottage'
blank.descript = 'This is a plane old cottage....'
blank.size = 'small'
blank.occupied = 1
blank.people = '<NAME>buff sharpening an axe'
blank.coord = [1,2,-1]
blank.seen = 0
cottage = blank
| StarcoderdataPython |
5045940 | <reponame>daniele-mc/HacktoberFest2020-4
def orangesRotting( grid):
rotten = []
r, c, fresh, t = len(grid), len(grid[0]), 0, 0
for i in range(r):
for j in range(c):
if grid[i][j] == 2: rotten.append([i, j])
elif grid[i][j] == 1: fresh += 1
while len(ro... | StarcoderdataPython |
4841030 | """
The SRP definition for CPHD 0.3.
"""
from typing import Union
import numpy
from sarpy.compliance import integer_types
from sarpy.io.phase_history.cphd1_elements.base import DEFAULT_STRICT
# noinspection PyProtectedMember
from sarpy.io.complex.sicd_elements.base import Serializable, _SerializableDescriptor, \
... | StarcoderdataPython |
1725214 | import numpy as np
from scipy import ndimage
from sHAM import nu_CWS
import gc
def find_index_first_dense(list_weights):
i = 0
for w in list_weights:
if len(w.shape)==2:
return i
i += 1
def idx_matrix_to_matrix(idx_matrix,centers):
return centers[idx_matrix.reshape(-1,1)].re... | StarcoderdataPython |
6562731 | from datetime import datetime
import os
import os.path
from django.db import models
from django.contrib.auth.models import User, Group
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.hashcompat import sha_constructor
from django.db.models.signals import post_s... | StarcoderdataPython |
6671765 | <reponame>Ernestyj/PyStudy<gh_stars>1-10
# -*- coding: utf-8 -*-
import unittest
import os
import pickle
import pandas as pd
import numpy as np
from td_query import ROOT_PATH
from td_query.data_manipulate_cc import data_manipulate_cc_instance as instance
from teradata import UdaExec
class TestDataManipulateCC(unitte... | StarcoderdataPython |
4805633 | from typing import Dict, List, Set
import docker
import os
import yaml
from docker import DockerClient
from docker.errors import ImageNotFound
from dbuild.config.config import Config
from dbuild.denvironment import BuildHandler, BuildContainer
def getOrCreateImage(client: DockerClient, config: Config):
image_na... | StarcoderdataPython |
1626084 | """IRC transport implementation."""
import re
import asyncio
import functools
from abc import ABCMeta, abstractmethod
from typing import *
from ..util import LogMixin
from .. import common
from . import response
__all__ = ["ConnectInfo", "ClientProtocol", "Message", "response"]
class User:
"""
An IRC user.... | StarcoderdataPython |
1693434 | import sys
import os
def add_rel_path(*args):
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), *args)))
add_rel_path('..', 'code')
os.environ.setdefault('WALDO_SETTINGS', 'settings.waldo')
| StarcoderdataPython |
5155659 | <gh_stars>1-10
import numpy as np
import matplotlib.pyplot as plt
class ModelParameters:
""" Encapsulates model parameters. """
def __init__(self,
all_s0, all_time, all_delta, all_sigma, gbm_mu,
jumps_lamda=0.0, jumps_sigma=0.0, jumps_mu=0.0,
cir_a=0.0, cir_mu... | StarcoderdataPython |
11362102 | <filename>marseille/pdtb_fields.py
# Author: <NAME> <<EMAIL>>
# License: BSD 3-clause
# interpretation of fields from Penn Discourse Treebank file format
PDTB_FIELDS = [
'reltype',
'section',
'file',
'conn_span',
'conn_gorn_addr',
'conn_raw',
'position',
'sent_no',
'head',
'con... | StarcoderdataPython |
6689338 | #!/usr/bin/env python
# Copyright 2014 The Chromium 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 in_generator
from name_utilities import lower_first
class CSSProperties(in_generator.Writer):
defaults = {
'alias_... | StarcoderdataPython |
6617252 | <reponame>localmed/django-assetfiles
from __future__ import unicode_literals
from nose.tools import *
from assetfiles import settings
from assetfiles.filters.coffee import CoffeeScriptFilterError
from tests.base import AssetfilesTestCase, filter
class TestCoffeeScriptFilter(AssetfilesTestCase):
def setUp(self... | StarcoderdataPython |
12856963 | ###########################
# 6.00.2x Problem Set 1: Space Cows
from ps1_partition import get_partitions
import time
#================================
# Part A: Transporting Space Cows
#================================
def load_cows(filename):
"""
Read the contents of the given file. Assumes th... | StarcoderdataPython |
3263633 | <gh_stars>0
from collections import deque
import numpy as np
import torch
class RolloutBuffer:
def __init__(self, buffer_size, state_shape, action_shape, device):
self._p = 0
self.buffer_size = buffer_size
self.states = torch.empty(
(buffer_size + 1, *state_shape), dtype=torc... | StarcoderdataPython |
6581848 | <gh_stars>1-10
import os
import cv2
import tensorflow as tf
from tensorflow.keras import layers
imgpath='./tr-vf/'
imgnames=os.listdir(imgpath)
for i in range(0,len(imgnames)):
img=cv2.imread(imgpath+imgnames[i])
height=img.shape[0]
width=img.shape[1]
depth=img.shape[2]
print(imgnames[i],height,w... | StarcoderdataPython |
11377114 | from sys import stdout,platform
from os import path,geteuid
from time import sleep
from subprocess import Popen, PIPE, STDOUT, run , check_output ,CalledProcessError
from collections import Counter
from re import *
from platform import *
class GeneralGui:
def __init__(self,):
#Renk Tanımlamalarını Yap.
se... | StarcoderdataPython |
9637085 | from colorama import Fore, init
from discord.ext import commands, tasks
import threading, os, random, pyfade
from colorfull import init; init()
# Put "user_id" -> mention user
__MESSAGE__ = '''
'''
__TOKEN__ = '<KEY>'
class Worker(threading.Thread):
def __init__(self, token: str):
thread... | StarcoderdataPython |
1938926 | <reponame>xu-kai-xu/OpenPNM
r"""
Collection of pre-defined algorithms
====================================
The ``algorithms`` module contains classes for conducting transport
simulations on pore networks.
"""
from ._mixins import *
from ._generic_algorithm import *
from ._generic_transport import *
from ._reactive_... | StarcoderdataPython |
4873638 | import logging
from behave import given, then, when
from structlog import wrap_logger
from acceptance_tests import browser
from acceptance_tests.features.pages import create_survey_form, survey
from common.respondent_utilities import create_ru_reference
from common.string_utilities import substitute_context_values
l... | StarcoderdataPython |
3424895 | <reponame>vgalaktionov/snaql-migration
try:
import unittest2 as unittest
except ImportError:
import unittest
from io import StringIO
from click import ClickException
from click.testing import CliRunner
from snaql_migration.snaql_migration import snaql_migration, _parse_config, _collect_migrations
class Tes... | StarcoderdataPython |
6686024 | <gh_stars>1-10
"""
File storage routines for openedx_export_plugins Django app.
"""
import logging
import boto
from boto.s3.key import Key
from .app_settings import AWS_ID, AWS_KEY, COURSE_EXPORT_PLUGIN_BUCKET, COURSE_EXPORT_PLUGIN_STORAGE_PREFIX
logger = logging.getLogger(__name__)
def do_store_s3(tmp_fn, stora... | StarcoderdataPython |
8076952 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^chant/', include('chant.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('common.urls')),
url(r'social/', include('social.apps.django_app.u... | StarcoderdataPython |
11264595 | """
MIT License
Copyright (c) 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... | StarcoderdataPython |
3312323 | <gh_stars>1-10
# Source code reference: Microsoft Azure Machine Learning.
import subprocess
def az_login(sp_user : str, sp_password : str, sp_tenant_id : str):
"""
Uses the provided service principal credentials to log into the azure cli.
This should always be the first step in executing az cli commands.
... | StarcoderdataPython |
4857216 | <gh_stars>0
import validators
import logging
import random
import requests
import requests.utils
import json
class Downloader:
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'
attempts = 3
default_timeout = 45
http... | StarcoderdataPython |
3386796 | <reponame>jawaidm/moorings
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-11-16 06:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mooring', '0041_booking_send_invoice'),
]
operations = [... | StarcoderdataPython |
1964779 | <reponame>GunshipPenguin/stockings<gh_stars>1-10
#!/usr/bin/env python3
import socket
import threading
import select
import sys
import struct
import ipaddress
import argparse
import const
def build_socks_reply(cd, dst_port=0x0000, dst_ip='0.0.0.0'):
'''
Build a SOCKS4 reply with the specified reply code, des... | StarcoderdataPython |
349852 | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from NodeSite import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# 账户设置,系统设置
url(r'^accounts/', include('NodeSite.accounts.urls')),
... | StarcoderdataPython |
8186081 | import random
def strategy(history, memory):
"""
Author: zelosos
Lets write down some assumptions:
- In a group most of the players will not be exploited.
- Players will test, if they can exploit others.
- Both cooperating for the hole time is best for both.
With this said:
- target should be... | StarcoderdataPython |
329590 | # Neat trick to make simple namespaces:
# http://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute-in-python
class Namespace(dict):
def __init__(self, *args, **kwargs):
super(Namespace, self).__init__(*args, **kwargs)
self.__dict__ = self
| StarcoderdataPython |
1930660 | <reponame>TeddyTeddy/robot-fw-browser-library-tests
import unittest
from mockito import unstub, verify, verifyNoUnwantedInteractions, expect, mock
from LibraryLoader import LibraryLoader
import LibraryLoaderStub
from Locators import locator, number_of_add_buttons, number_of_change_buttons
from AddGroupPage import AddGr... | StarcoderdataPython |
391657 | <filename>tools/cygprofile/mergetraces.py
#!/usr/bin/python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Use: ../mergetraces.py `ls cyglog.* -Sr` > merged_cyglog
""""Merge multiple logs files from di... | StarcoderdataPython |
1881769 | <reponame>NunoEdgarGFlowHub/studio
import unittest
import yaml
import uuid
import os
import time
import tempfile
import shutil
import requests
import subprocess
import boto3
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from studio import model
from studio.auth impor... | StarcoderdataPython |
321244 | import os
from fppy import __version__
def docs():
"""生成DOC
"""
build_dir = 'docs/build/'+ __version__
source_dir = 'docs/source'
build_main_dir = 'docs/build/main'
os.system((
f'sphinx-build -b html {source_dir} {build_dir}'
))
os.system((
f'sphinx-build -b html {so... | StarcoderdataPython |
6446691 | import random
class BaseReplacementPolicy:
"""
Defines the base set of features a replacement policy controls. These include its clock counter, its name, its
default or instantiation number, its eviction properties, and its update / touch property
"""
def __init__(self):
"""
Assumi... | StarcoderdataPython |
1703691 | <reponame>engjoaofaro/irrigation-service-mqtt
import boto3
import base64
from botocore.exceptions import ClientError
import AWSIoTPythonSDK.MQTTLib as awsIot
class AwsConfig:
def __init__(self, name_device, endpoint, ca_file_path, key_path, certificate_path):
self.__name_device = name_device
sel... | StarcoderdataPython |
33924 | <gh_stars>10-100
import random
from pandac.PandaModules import Point3
from direct.gui.DirectGui import DirectFrame, DirectLabel
from direct.fsm import FSM
from direct.interval.IntervalGlobal import *
from pirates.audio import SoundGlobals
from pirates.audio.SoundGlobals import loadSfx
import RepairGlobals
MIN_SCALE = 1... | StarcoderdataPython |
322009 | """Testing for TransitionGraph"""
import numpy as np
import pytest
from scipy.sparse import csr_matrix
from sklearn.exceptions import NotFittedError
from giotto.graphs import TransitionGraph
X_tg = np.array([[[1, 0], [2, 3], [5, 4]],
[[0, 1], [3, 2], [4, 5]]])
X_tg_res = np.array([
csr_matrix((... | StarcoderdataPython |
8007655 | <reponame>tinesife94/projecteuler.net-solutions
"""Python code to solve problem 6 on the projecteuler.net website, available
at:
https://projecteuler.net/problem=6
For your convinience:
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of th... | StarcoderdataPython |
9775309 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-19 19:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('jobs', '0005_server_job_running'),
]
operations = [... | StarcoderdataPython |
4945571 | # -*- coding: utf-8 -*-
"""Holds APIs used by the front end"""
from flask import Response, request
from flask_login import current_user
from sqlalchemy import asc
from app import wjl_app
from app.errors import NotFoundException
from app.model import Session, Match, Team, Field, DB
from app.logging import LOGGER
from ap... | StarcoderdataPython |
1932714 | #!/usr/bin/env python3
from . import command_codes as cc
import asyncio
from collections import namedtuple
import logging
import re
from typing import List, Callable, Union, Sequence, Any
from types import coroutine
class LoggerMetaClass(type):
def __new__(mcs, name, bases, namespace):
inst = type.__ne... | StarcoderdataPython |
12820167 | <reponame>sandeepb2003/neural
# coding: utf-8
import random
import sys
from werkzeug.datastructures import FileStorage
from flask import current_app
from flask.ext.admin import form
from flask.ext.admin.form.upload import ImageUploadInput
from flask.ext.admin._compat import urljoin
from quokka.core.models import SubC... | StarcoderdataPython |
5189572 | <filename>tests/modules/utils.py
import re
import os
import json
from zomato.zomato import Zomato
def do_init(instance="common"):
z = Zomato(API_KEY="e74778cd3728858df3578092ecea02cf")
# o = getattr(s, instance)
if instance.lower() == "common":
return z.common
elif instance.lower() == "locatio... | StarcoderdataPython |
1841847 | #!/bin/sh
""":" .
exec python "$0" "$@"
"""
# -*- coding: utf-8 -*-
"""
Copyright (c) 2018 beyond-blockchain.org.
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... | StarcoderdataPython |
9729383 | from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('libretto', '0017_migrate_types_de_parente'),
]
operations = [
... | StarcoderdataPython |
8086194 | <filename>config/measurement_config.py
"""The measurement configuration file consists of the parameters required when inferring with point cloud data obtained from measurement systems
:param ms_parameters['measurement_files']: List of measurement files obtained from the measurement system, curr... | StarcoderdataPython |
84957 | <reponame>isabella232/nnabla
# Copyright 2021 Sony 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
9681106 | #!/usr/bin/python
import base
import string
import re
import sidetrack
from string import upper
import sys
if sys.platform != "win32":
import readline
import os
targ = None
imp = None
running = 0
#-----------------------------------------------------------------------------
# Name : ReadCommand
# Purpose: Promp... | StarcoderdataPython |
4993534 | <filename>musicapp-test/musicapp/models.py
from datetime import datetime
from musicapp import db, login_manager
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
listened = db.Table('listened',
db.Column('user_id' ,db.Integer, db.F... | StarcoderdataPython |
4962966 | <filename>UserKnox/ApiKnox/apps.py
from django.apps import AppConfig
class ApiknoxConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'ApiKnox'
| StarcoderdataPython |
391355 | """General tests to demonstrate the parametric suite. Possible arguments are given below (defaults).
To test more than one option, pass in an Iterable of requested options.
All Parametric Groups
---------------------
'group_type': Controls which type of ParametricGroups to test. Will test all groups if not specified
'... | StarcoderdataPython |
1662930 | <reponame>milos-simic/neural-normality
import os
from bisect import bisect
import numpy as np
import pandas as pd
import scipy.stats
import random
import datetime
import pickle
import os
import pathlib
import traceback
from kernelgofs import kernel_normality_test, kernel_normality_test_statistic
import rpy2.robjects ... | StarcoderdataPython |
6511333 | <reponame>miswanting/python-spider-starter
import collections
import json
import os
import threading
import time
import urllib.request
from urllib.parse import urlencode
from bs4 import BeautifulSoup
import SpiderEngine
# CACHE_FILE_NAME = 'cache.json'
# cache = {
# 'current_page': 0,
# 'nodes': {},
# 'ta... | StarcoderdataPython |
3322531 | <reponame>lonePatient/TorchBlocks
from torchblocks.metrics.classification import *
from torchblocks.metrics.regression import *
from torchblocks.metrics.utils_ner import *
from torchblocks.metrics.sequence_labeling import *
| StarcoderdataPython |
3436112 | <reponame>AtmegaBuzz/minirobosim-main
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@organization: CHArt - Université Paris 8
"""
from Box2D import b2
from Box2D import (b2CircleShape, b2FixtureDef, b2Vec2)
import numpy as np
class World():
VEL_ITERS, POS_ITERS = 10, 10
def __init__( self, grav... | StarcoderdataPython |
111851 | <gh_stars>0
from vs_currency import get_supported_vs_currencies_api
import unittest
class TestVsCurrency(unittest.TestCase):
def test_api_status_without_status_code(self):
url = url = "https://api.coingecko.com/api/v3/"
actual = get_supported_vs_currencies_api(url=url)
expected = [
... | StarcoderdataPython |
1724676 | <reponame>aimof/rain<filename>python/rain/client/pycode.py
import inspect
import contextlib
import time
import base64
import cloudpickle
from collections import OrderedDict
from .task import Task
from .data import blob
from .session import get_active_session
from ..common import RainException, RainWarning
from .input ... | StarcoderdataPython |
6591318 | import FWCore.ParameterSet.Config as cms
from Calibration.EcalCalibAlgos.ecalPedestalPCLHarvester_cfi import ECALpedestalPCLHarvester
from DQMServices.Components.EDMtoMEConverter_cfi import *
EDMtoMEConvertEcalPedestals = EDMtoMEConverter.clone()
EDMtoMEConvertEcalPedestals.lumiInputTag = cms.InputTag("MEtoEDMConvert... | StarcoderdataPython |
1694047 | <gh_stars>0
# Copyright (c) Facebook, Inc. and its affiliates.
"""
Example command
python fairmotion/tasks/clustering/clustering.py \
--features $FEATURES_FILE # see generate_features.py \
--type kmeans \
--num-clusters $NUM_CLUSTERS \
--normalize-features \
--clip-features 90 \
--output-file $... | StarcoderdataPython |
3353737 | import select, socket, queue, json
from arduino import MIS_Arduino
from threading import Thread, Lock
from time import time
def socket_data_process(from_socket):
from_socket.strip()
#print(from_socket)
head, message = from_socket[:5], from_socket[6:]
#print(head, message)
head = int(head)
#prin... | StarcoderdataPython |
3332702 | """ Email """
import re
from dataclasses import dataclass
from src.domain.domainmodel.exceptions.invalid_email import InvalidEmail
@dataclass
class Email:
""" This class represents the Email datatype """
value: str
""" Email value object """
def __init__(self, value: str):
if self._valida... | StarcoderdataPython |
6610894 | <gh_stars>10-100
##################################################################
# Views User Authentication and login / logout
# Author : <NAME> , All Rights reserved with Dr.E<NAME>.
# License : GNU-GPL Version 3
# Date : 01-01-2013
##################################################################
# Import S... | StarcoderdataPython |
11260367 | <reponame>zubairfarahi/Data-Science--Machine-Learning-
"""
Ex. 13: Scrieti un decorator care sa modifice modul de functionare
al functiei f. Puteti alege voi cum. Momentan, f intoarce 'cmi', un exemplu
ar fi sa intoarca 'CmI' dupa aplicarea decoratorului.
"""
def dec(func):
def wrapper():
x = ... | StarcoderdataPython |
107686 | <filename>Files/read_sql_fn4.py
'''
this function can handle oracle script with block comment
handle change drop table table to
begin execute immediate \'drop table UTLMGT_DASHBOARD.temp_gen_dm_auth_2\'; exception when others then null; end
'''
def convertToBODSScript ( path):
f0 = open(path,'r')
f1 =... | StarcoderdataPython |
3474867 | from __future__ import annotations
from typing import Any, TypeVar, List, Set, Dict, Tuple, Optional, Union
from grapl_analyzerlib.node_types import (
EdgeT,
PropType,
PropPrimitive,
EdgeRelationship,
)
from grapl_analyzerlib.queryable import Queryable
from grapl_analyzerlib.schema import Schema
from g... | StarcoderdataPython |
5112109 | import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
#from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
# initial network was from here: https://github.com/pytorch/examples/blob/master/mnist/main.py
def custom_init_we... | StarcoderdataPython |
33159 | <gh_stars>1-10
# 设置类
class Settings():
'''保存设置信息'''
def __init__(self):
'''初始化游戏的静态设置'''
self.screen_width = 850
self.screen_heght = 600
self.bg_color = (230, 230, 230)
# 玩家飞船数量设置
self.ship_limit = 3
# 子弹设置
self.bullet_width = 3
... | StarcoderdataPython |
5104860 | <filename>sdc/hiframes/pd_timestamp_ext.py
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditi... | StarcoderdataPython |
5064653 | """
Notes:
1) Known numerical errors. Choosing the initial condition [-9.44500792, 2.92172601] for the trajectory generator and
the initial condition [-9.06892831, -9.7230096 ] for the closed-loop system leads to a trajectory error, when the
odeint is executed with the option mxstep<1500
"""
import l... | StarcoderdataPython |
9732857 | <reponame>dawar-s/algo-ds-sol-python
def selectionSort(array):
i = 0
while i < len(array):
j = i
k = j
smallest = array[i]
while j < len(array):
if array[j] < smallest:
smallest = array[j]
k = j
j += 1
array[i], arra... | StarcoderdataPython |
125748 | import numpy
import cv2
def make2Dcolormap(
colors=(
(1, 1, 0),
(0, 0, 1),
(0, 1, 0),
(1, 0, 0),
), size=20):
######################
colormap = numpy.zeros((2, 2, 3))
colormap[1, 1] = colors[0]
colormap[0, 1] = colors[1]
colormap[0, ... | StarcoderdataPython |
162944 | <reponame>anmolmalik01/mediapipe<filename>holistic.py<gh_stars>1-10
import cv2
import mediapipe as mp
import time
class mediapipe:
# ============================================ init =================================================
def __init__(self):
# mediapipe solutions variable
mp_drawing = mp.so... | StarcoderdataPython |
6602925 | from PIL import Image
import torch
from torch.utils.data import Dataset
from data.transforms import simple_image_preprocess
class CassavaDataset(Dataset):
"""Torch dataset for the problem
Args:
Dataset (Dataframe): Pandas dataframe containing informations
"""
def __init__(self, df, augmentat... | StarcoderdataPython |
3525273 | class Solution:
def gameOfLife(self, board):
self.m = len(board)
self.n = len(board[0])
self.board = [rows.copy() for rows in board]
for i in range(self.m):
for j in range(self.n):
state = self.board[i][j]
dataDict = self.CheckNeigh... | StarcoderdataPython |
3201426 | #!/usr/bin/python
# This script computes the round key of the 10th round from the output of the 9th round (faulty ciphertext) and output of the 10th round (non-faulty ciphertext).
#
# The output of the 9th round is acquired by skipping the last round of the algorithm via LFI (see paper section VII.A).
# When provided w... | StarcoderdataPython |
1649826 | <filename>lidopt/model.py
# ## Running the simulation in SWMM
import numpy as np
from pyswmm import Simulation, LidGroups
from pyswmm.lidlayers import Soil
from pyswmm.lidcontrols import LidControls
from .parsers import parse_experiment, parse_report, merge_and_correct
from . import EXP, SIM, METRICS
def evaluate(inpu... | StarcoderdataPython |
16822 | <reponame>gautams3/reacher-done
import gym
from gym import error, spaces, utils
from gym.utils import seeding
from gym.envs.mujoco.reacher import ReacherEnv
import numpy as np
class ReacherDoneEnv(ReacherEnv):
metadata = {'render.modes': ['human']}
# def __init__(self):
# ...
def step(self, action):
sel... | StarcoderdataPython |
269636 | import json
from dataclasses import dataclass, is_dataclass, asdict
from typing import List, Dict
from collections import defaultdict
import sys
def custom_default(o):
if is_dataclass(o):
return asdict(o)
raise TypeError(f"{o!r} is not JSON serializable")
@dataclass
class AtomicCard:
converted_m... | StarcoderdataPython |
1984183 | <filename>test.py
from subprocess import call
from sys import exit
returncode = call(["python", "-m", "unittest", "discover", "-v", "tests"])
exit(returncode)
| StarcoderdataPython |
5048899 | import lbann
from lbann.modules import Module
import math
class DenseGCNConv(Module):
global_count = 0
def __init__(self, input_channels, output_channels, name=None):
super().__init__()
DenseGCNConv.global_count += 1
self.name = (name if name else 'Dense_GCN_{}'.format(DenseGCNConv.... | StarcoderdataPython |
8117929 | <filename>src/prism-fruit/Games-DQL/examples/games/car/networkx/algorithms/approximation/tests/test_matching.py<gh_stars>0
from nose.tools import *
import networkx as nx
import networkx.algorithms.approximation as a
def test_min_maximal_matching():
# smoke test
G = nx.Graph()
assert_equal(len(a.min_... | StarcoderdataPython |
170612 | def f(xs):
ys = 'string'
for x in xs:
g(ys)
def g(x):
return x.lower()
| StarcoderdataPython |
9706248 | <gh_stars>1-10
def quick_sort(data):
yield from __quick_sort(data, 0, len(data) - 1)
def __quick_sort(data, start, end):
"""Quick sort: O(nlogn)"""
if start >= end:
return
pivot = data[end]
pivot_idx = start
for i in range(start, end):
if data[i] < pivot:
data[i],... | StarcoderdataPython |
6520385 | <reponame>okfde/odm-datenerfassung<gh_stars>1-10
# -*- coding: utf-8 -*-
import urllib2
import urllib
import json
import pprint
import os
import metautils
#This is a one time operation to create organisations based on the originating portal in ODM DB
#Run prior to importing data
url = os.environ['CKANURL']
apikey = ... | StarcoderdataPython |
6589872 | #!/usr/bin/python3
"This module is used to generate xml file readed by crete"
import subprocess
def json2xml(workload_str=str, setup_list=list,
function_name=str, full_path=str):
"Convert json format to xml"
json_list = list(workload_str.split(" "))
xml_str = ""
xml_str += "<?xml version=\"1.0\" en... | StarcoderdataPython |
3423265 | import os
import sys
import re
if __name__ == "__main__":
data = None
wdir = os.path.dirname(sys.argv[0])
with open(os.path.join(wdir, "input.txt")) as f:
data = f.readlines()
needle = "shiny gold bag"
bags = []
for d in data:
m = re.match("^(?P<bag>.*bag)s\s*contain (?P<contai... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.