id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1740638 | <reponame>Myne-us/pedb
import os
import sys
import hashlib
walk_dir = sys.argv[1]
def md5_for_file(path, block_size=2**20):
f = open(path)
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
f.close()
return md5.digest().encode("hex")
... | StarcoderdataPython |
1763311 | from tempfile import mkdtemp, NamedTemporaryFile
import genomepy
import shutil
import pytest
import os
# Python 2
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
travis = "TRAVIS" in os.environ and os.environ["TRAVIS"] == "true"
@pytest.mark.skipif(travis,
reason="Too slow for T... | StarcoderdataPython |
1748693 | include("$(PORT_DIR)/boards/manifest.py")
freeze("$(PORT_DIR)/boards/UM_TINYPICO/modules", "dotstar.py")
freeze("modules")
| StarcoderdataPython |
1629315 | from urllib.parse import urlparse
def is_uri(uri, uri_type):
return '/' in uri and uri_type in uri
def get_feature_from_uri(uri, feature):
return uri.split(feature)[-1].split('/')[1]
def extract_artifact_id(artifact_uri):
return int(urlparse(artifact_uri).path.split('/')[-1])
def is_list(l):
# TODO:... | StarcoderdataPython |
1723575 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import itertools
import copy
import joblib
import numpy
import scipy.sparse
import segment
import collections
import skimage.io
import features
import color_space
def _calc_adjacency_matrix(label_img, n_region):
r = numpy.vstack([label_img[:, :-1].rave... | StarcoderdataPython |
122999 | <filename>tests/unit_tests/test_collection.py
import pytest
def test_collection_kwargs_become_properties(base_collection):
assert base_collection.custom_val == 'custom'
def test_collection_sorts_alphabetically(base_collection):
assert base_collection.pages[0].slug == 'Title_C'
| StarcoderdataPython |
87489 | <reponame>ashishdhngr/baserow
from unittest.mock import patch, call, ANY
import pytest
from django.db import transaction
from baserow.contrib.database.api.constants import PUBLIC_PLACEHOLDER_ENTITY_ID
from baserow.contrib.database.rows.handler import RowHandler
from baserow.contrib.database.views.handler import ViewH... | StarcoderdataPython |
1730466 | <reponame>adamlwgriffiths/jaweson
"""Provides Object -> JSON -> Object serialisation functionality.
This code is designed to avoid any `eval` calls which could be
exploited, if the database were compromised, with malicious code.
To avoid calling `eval` on the class type, classes must be registered
with the `register_... | StarcoderdataPython |
3210613 | <reponame>Jacky3213/face-recognition-system
from register import*
from live import*
if __name__ == '__main__':
root_path = '../data/NIR' ## images_NIR 20180625faceImages BGR
register_all(root_path)
test_live(root_path) | StarcoderdataPython |
46684 | <filename>dusty/systems/docker/testing_image.py<gh_stars>100-1000
from __future__ import absolute_import
import docker
from ...compiler.compose import container_code_path, get_volume_mounts
from ...compiler.spec_assembler import get_expanded_libs_specs
from ...log import log_to_client
from ...command_file import dusty... | StarcoderdataPython |
3319148 | import os
print("")
print(" Building report")
print("")
os.system("pdflatex manuel.tex")
os.system("makeindex manuel.tex")
os.system("pdflatex manuel.tex")
os.system("pdflatex manuel.tex")
print("")
print(" Clean directory")
print("")
files = ["manuel.aux", "manuel.log", "manuel.out", "manuel.glo", "manuel.i... | StarcoderdataPython |
32182 | import time
from contextlib import suppress, contextmanager
from astropy import units as u
from panoptes.utils import error
from panoptes.utils.utils import get_quantity_value
from panoptes.utils.time import current_time, wait_for_events, CountdownTimer
from panoptes.pocs.observatory import Observatory
from panoptes.... | StarcoderdataPython |
46837 | from unittest.mock import Mock, patch
import pandas as pd
import pytest
from faker import Faker
from faker.config import DEFAULT_LOCALE
from rdt.transformers.numerical import NumericalTransformer
from sdv.constraints.base import Constraint
from sdv.constraints.errors import MissingConstraintColumnError
from sdv.error... | StarcoderdataPython |
1674834 | <reponame>leelabcnbc/tang_jcompneuro_revision
from sys import argv
from tang_jcompneuro.model_fitting import run_all_scripts, generate_all_scripts
from tang_jcompneuro.model_fitting_gabor import models_to_train
header = """
#!/usr/bin/env bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=2
#SBATCH --time=24:00:00
#SBATC... | StarcoderdataPython |
3294705 | import sys,os,ssl
import pika,time
import logging
logger = logging.getLogger(__name__)
logging.getLogger('pika').setLevel(logging.WARNING)
#logging.getLogger('select_connection').setLevel(logging.DEBUG)
class MessageInterface:
def __init__(self,
username = '',
p... | StarcoderdataPython |
1773242 | from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten, Lambda
from keras.optimizers import Adam, SGD
from keras.callbacks import ModelCheckpoint, LearningRateScheduler, ReduceLROnPlateau
from ke... | StarcoderdataPython |
1651722 | # ######################################################################################################################
# Copyright 2020 TRIXTER GmbH #
# ... | StarcoderdataPython |
1785024 | <gh_stars>10-100
import numpy as np
from collections import deque
class HistoryBuffer():
def __init__(self,preprocess_fn,image_shape,frames_for_state) :
self.buf = deque(maxlen=frames_for_state)
self.preprocess_fn = preprocess_fn
self.image_shape = image_shape
self.clear()
def ... | StarcoderdataPython |
1732257 | from django.conf.urls import include
from django.conf.urls import patterns
from django.contrib import admin
from survey.urls import urlpatterns as survey_urls
from django.conf import settings
from django.conf.urls import (handler400, handler403, handler404, handler500)
admin.autodiscover()
urlpatterns = patterns('',
... | StarcoderdataPython |
3205580 | <filename>blueprints/azure_functions/management/start_function.py<gh_stars>10-100
"""
Start an azure function.
"""
from common.methods import set_progress
from infrastructure.models import CustomField
from common.methods import generate_string_from_template
import os, json
def run(job, resource, **kwargs):
functio... | StarcoderdataPython |
3279072 | from algo.number_theory.ncr.ncr import ncr
def ncr_lucas(n, r, pmod):
"""
Complexity -> O(logn base pmod).
"""
if r == 0:
return 1
next_n, n = divmod(n, pmod)
next_r, r = divmod(r, pmod)
return ncr(n, r, pmod) * ncr_lucas(next_n, next_r, pmod) % pmod
def main():
print(ncr_luc... | StarcoderdataPython |
3577 | """
# Definition for a Node.
"""
class TreeNode(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root is None:
... | StarcoderdataPython |
1763427 | from dataclasses import dataclass
@dataclass
class JupyterAPI:
host: str = "127.0.0.1"
port: int = 8888
token: str = ""
| StarcoderdataPython |
1603773 | from collections import deque
d = deque()
N = int(input())
for _ in range(N):
cmd, *args = input().split()
getattr(d, cmd)(*args)
print (*[item for item in d], sep = " ")
| StarcoderdataPython |
3366626 | # -*- coding: utf-8 -*-
"""
@date: 2021/9/25 下午12:16
@file: resnet.py
@author: zj
@description:
"""
import torch
from rfd.model.resnet.resnet import get_resnet
from rfd.config.key_word import KEY_FEAT
if __name__ == '__main__':
# model = get_resnet(arch='resnet18')
model = get_resnet(arch='resnet50')
p... | StarcoderdataPython |
3244909 | from typing import Callable
import torch
from torch import nn
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from tqdm import tqdm
from ..chemprop.data import MoleculeDataLoader
from ..chemprop.nn_utils import compute_gnorm, compute_pnorm, NoamLR
def train(model: nn.Module, data_... | StarcoderdataPython |
3295283 | import unittest
from unittest import mock
import copy
from tornado import gen
from tornado import testing
from jupyterhub_profiles import PrimeHubSpawner, OIDCAuthenticator
import jupyterhub
def mock_spawner():
return PrimeHubSpawner(_mock=True)
class AuthStateBuilder(object):
def __init__(self):
... | StarcoderdataPython |
3302997 | from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import session.routing as rout
application = ProtocolTypeRouter({
# http->django views is added by default
'websocket': AuthMiddlewareStack(
URLRouter(
rout.websocket_urlpatterns
... | StarcoderdataPython |
1739146 | <reponame>etaivan/stx-config
#
# Copyright (c) 2016-2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from sysinv.common import constants as sysinv_constants
from tsconfig import tsconfig
CONFIG_WORKDIR = '/tmp/config'
CGCS_CONFIG_FILE = CONFIG_WORKDIR + '/cgcs_config'
CONFIG_PERMDIR = tsconfig... | StarcoderdataPython |
1673923 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import lldb
import re
import optparse
import ds
import shlex
class GlobalOptions(object):
symbols = {}
@staticmethod
def addSymbols(symbols, options, breakpoint):
key = str(breakpoint.GetID())
GlobalOptions.symbols[key] = (symbols, options)
... | StarcoderdataPython |
1757354 | <reponame>ToniIvars/django-poll
# Generated by Django 3.2.3 on 2021-05-18 10:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.... | StarcoderdataPython |
3323690 | <filename>resource/convert.py
# coding=UTF-8
import time
def convert(path):
content = ""
with open(path, 'rb') as f:
content = f.read()
content = content.decode("gbk")
with open(path + "_" + str(time.time()), 'w') as f:
f.write(content)
if __name__ == "__main__":
convert("mysel... | StarcoderdataPython |
4804335 | # Code generated by lark_sdk_gen. DO NOT EDIT.
from pylark.lark_request import RawRequestReq, _new_method_option
from pylark import lark_type, lark_type_sheet, lark_type_approval
import attr
import typing
import io
@attr.s
class CreateCalendarEventAttendeeReqAttendee(object):
type: lark_type.CalendarEventAttende... | StarcoderdataPython |
137232 | <gh_stars>100-1000
"""
Coverage tracking internals.
"""
import sys
import threading
err = sys.stderr
import types, symbol
# use builtin sets if in >= 2.4, otherwise use 'sets' module.
try:
set()
except NameError:
from sets import Set as set
def get_interesting_lines(code):
"""
Count 'interesting' l... | StarcoderdataPython |
164385 | """
DANet for image segmentation, implemented in Chainer.
Original paper: 'Dual Attention Network for Scene Segmentation,' https://arxiv.org/abs/1809.02983.
"""
__all__ = ['DANet', 'danet_resnetd50b_cityscapes', 'danet_resnetd101b_cityscapes']
import os
import chainer.functions as F
from chainer import link
... | StarcoderdataPython |
3384583 | <filename>assets/img/baby_tcache/exploit.py
from pwn import *
import sys
HOST='192.168.127.12'
PORT=56746
context.terminal=['tmux', 'splitw', '-h']
if len(sys.argv)>1:
r=remote(HOST,PORT)
else:
r=process('./baby_tcache',env={"LD_PRELOAD":"./libc.so.6"})
libc=ELF("./libc.so.6")
def menu(opt):
r.sendline... | StarcoderdataPython |
61449 | #!/usr/bin/env python3
VERSION = "0.0.1-sig"
import requests, json, time, traceback
from random import random
from bs4 import BeautifulSoup
WEBHOOK_URL = "https://hooks.slack.com/services/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"
TEST_URL = "https://apps.apple.com/cn/app/goodnotes-4/id778658393"
SLEEP_IN = 3
U... | StarcoderdataPython |
106591 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
import char_class_utils
import tpactions
###################################################
def GetConditionName():
return "Swashbuckler"
print "Registering " + GetConditionName()
classEnum = stat_level_swashbuckler
classSpecModule = __imp... | StarcoderdataPython |
3267260 | from abc import abstractproperty
from collections import namedtuple
from math import ceil
from typing import Optional
from elftools.dwarf.die import DIE
from common.exceptions import WrongDIEType
from elf.constants import BITS_IN_BYTE, DIE_TYPE_COLLECTION_TAGS, DIE_TYPE_MODIFIER_TAGS, ENCODING, REFERENCE_FORM_WITH_O... | StarcoderdataPython |
3390038 | <filename>cogs/message.py
import discord, random, os, asyncio, time
from discord.ext import commands
import discord.ext.commands
import datetime, asyncpg
from cogs.pokemon import pokemon
from asyncio import sleep
from main import client
p = pokemon(client)
class message(commands.Cog):
"""A class co... | StarcoderdataPython |
1783937 | from os.path import join
import torch
from kornia import geometry
from ..agents.base import BaseModule
from ..dataset import JointsConstructor
from ..models.hourglass import HourglassModel
from ..models.metrics import MPJPE
from ..utils import average_loss
class HourglassEstimator(BaseModule):
"""
Agent for... | StarcoderdataPython |
144778 | <gh_stars>1-10
#!/usr/bin/env python2
#import pytest
from pyspark import SparkContext,HiveContext
################################################################
## Code for parsing Apache weblogs
## This is an improved parser that's tolerant of bad data.
## Instead of throwing an error, it return a Row() object
## ... | StarcoderdataPython |
42397 | from app.infrastructure.repositories.camera.capture import CameraCapture
def main():
CameraCapture().run()
| StarcoderdataPython |
3367602 | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from .resnext101_32x4d_features import resnext101_32x4d_features,resnext101_32x4d_features_blob
__all__ = ['ResNeXt101_32x4d', 'resnext101_32x4d']
pretrained_settings = {
'resnext101_32x4d': {
'imagenet': {
'url': 'http://data.lip... | StarcoderdataPython |
93658 | <reponame>KevinWhalen/pcml
"""
Copyright (c) 2014 High-Performance Computing and GIS (HPCGIS) Laboratory. All rights reserved.
Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Authors and contributors: <NAME> (<EMAIL>); <NAME> (<EMAIL>, <EMAIL>)
"""
from ..core.Operation... | StarcoderdataPython |
170839 | <reponame>rBrenick/copy-paste-overload<gh_stars>0
# Standard
import os
import sys
from functools import partial
# Not even going to pretend to have Maya 2016 support
from PySide2 import QtCore
from PySide2 import QtWidgets
from PySide2 import QtGui
from shiboken2 import wrapInstance
from PySide2 import QtUiTools
imp... | StarcoderdataPython |
107426 | def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the message... | StarcoderdataPython |
1617786 | <filename>src/utils/helpers.py
"""Helper functions for code sanity"""
import numpy as np
from tensorflow.keras.callbacks import Callback
from sklearn.metrics import accuracy_score, roc_auc_score
import re
from tqdm.notebook import tqdm
from sklearn import metrics
def regular_encode(texts, tokenizer, maxlen=512):
"... | StarcoderdataPython |
10354 | <filename>assignment4/rorxornotencode.py<gh_stars>10-100
#!/usr/bin/python
# Title: ROR/XOR/NOT encoder
# File: rorxornotencode.py
# Author: <NAME>
# SLAE-681
import sys
ror = lambda val, r_bits, max_bits: \
((val & (2**max_bits-1)) >> r_bits%max_bits) | \
(val << (max_bits-(r_bits%max_bits)) & (2**max_bits-... | StarcoderdataPython |
43154 | #!/usr/bin/python3
import requests
import json
import searchguard.settings as settings
from searchguard.exceptions import RoleMappingException, CheckRoleMappingExistsException, ViewRoleMappingException, \
DeleteRoleMappingException, CreateRoleMappingException, ModifyRoleMappingException, CheckRoleExistsException, ... | StarcoderdataPython |
3284417 | # this file replaces quantile/ensemble.py file of scikit-garden package
# this code, unlike the original code, makes use of all available cores when doing scoring
# also, unlike the original code, predict() function in the new code can generate predictions for multiple quantiles
import numpy as np
from numpy import ma... | StarcoderdataPython |
147997 | #!/usr/bin/env python
"""create_min_chi2_table.py.
Create Table of minimum Chi_2 values and save to a table.
"""
import argparse
import logging
import sys
from joblib import Parallel, delayed
from logutils import BraceMessage as __
from bin.coadd_analysis_script import main as coadd_analysis
from bin.coadd_chi2_db im... | StarcoderdataPython |
1622780 | <reponame>sokazaki/mmediting
import torch
import torch.nn as nn
import torchvision.models.vgg as vgg
from mmcv.runner import load_checkpoint
from mmedit.utils import get_root_logger
from ..registry import LOSSES
class PerceptualVGG(nn.Module):
"""VGG network used in calculating perceptual loss.
In this impl... | StarcoderdataPython |
193823 | <gh_stars>10-100
# Copyright (c) 2009, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this li... | StarcoderdataPython |
4826054 | #!/usr/bin/python3
"""
Demonstrates the use of Psi4 from Python level.
Useful notes:
o Use psi4.core module for most of the work
o Useful modules within psi4.core:
- MintsHelper
- Molecule
- BasisSet
- ExternalPotential
others
o Psi4 defines its own matrix type (psi4.core.Matrix).
... | StarcoderdataPython |
1772990 | <filename>console/helper/formatter_helper.py
# -*- coding: utf-8 -*-
from helper import Helper
from ..formatter.output_formatter import OutputFormatter
class FormatterHelper(Helper):
def format_section(self, section, message, style='info'):
return '<%s>[%s]</%s> %s' % (style, section, style, message)
... | StarcoderdataPython |
3366408 | # Look at the tick data for October and then using file 07
import os
import time
import pandas as pd
import requests, zipfile, io
# Doing 4500 to 4700 (4500-4699 inclusive)
# for num in range(4400, 4500):
# for num in range(4300, 4400):
def main():
num_hvnt_worked = list()
print("Downloading data...")
for ... | StarcoderdataPython |
168851 | # (C) Copyright 2018-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... | StarcoderdataPython |
3364514 | <reponame>pylangstudy/201706
try:
print('try')
raise Exception
except Exception as e:
print('except')
finally:
print('finally')
| StarcoderdataPython |
3284790 | import datetime
import json
import logging
import os
import fs
from fs.errors import FileExpected, ResourceNotFound
from .exceptions import Conflict, NotFound
from .settings import STORAGE_BASE, STORAGE_DIR
logger = logging.getLogger(__name__)
class Storage(object):
def __init__(self, use_memory_fs=False, data_... | StarcoderdataPython |
4804006 | """
Copyright (c) 2020, <NAME>.
Distributed under the terms of the MIT License.
The full license is in the file LICENSE, distributed with this software.
Created on Feb 21, 2020
@author
"""
class User:
a_pay = 15000 # class variables.
b_pay = 21000
def __init__(self, value):
self.list = []
... | StarcoderdataPython |
3228161 | import csv
class MTTFCalculator:
def __init__(self):
self.failures = []
self.read_from_file()
def calculate_mttf(self):
# TODO Berechne den Mittelwert der in "failures" gespeicherten Werte und gebe das Ergebnis zurueck.
# Tipp: Hierzu benoetigst du die "return"-Anweisung.
... | StarcoderdataPython |
1723729 | # -*- coding: utf-8 -*-
"""
Author: mcncm 2019
DySART job server
currently using http library; this should not be used in production, as it's
not really a secure solution with sensible defaults. Should migrate to Apache
or Nginx as soon as I understand what I really want.
Why am I doing this?
* Allows multiple clie... | StarcoderdataPython |
1760258 | <filename>Python/FreiStat_GUI/PopUp_Window/__init__.py<gh_stars>0
"""
PopUp window class of the FreiStat interface.
"""
__author__ = "<NAME>"
__contact__ = "University of Freiburg, IMTEK, <NAME>"
__credits__ = "<NAME>"
__version__ = "1.0.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>, <EMAIL>"
# Import dependenc... | StarcoderdataPython |
133204 | import sys
sys.path.append('..')
from utils import *
class Cascade:
# --------------------------
# Initiate Cascade
# --------------------------
def __init__(self, root_tweet_id, cascade_path, label=None):
self.file_id = root_tweet_id # For label.txt
self.root_tweet_id = root_tw... | StarcoderdataPython |
4809086 | <reponame>JulyKikuAkita/PythonPrac
__source__ = 'https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/kth-smallest-element-in-a-sorted-matrix.py
# Time: O(k * log(min(n, m, k))), with n x m matrix
# Space: O(min(n, m, k))
#
# Description: Lee... | StarcoderdataPython |
130588 | # urls.py
from __future__ import absolute_import
from django.conf.urls import include, url
from haystack.generic_views import SearchView
from haystack.forms import SearchForm
from .views import MySearchView
import cloud_notes.views
# required to set an app name to resolve 'url' in templates with namespacing
app_name ... | StarcoderdataPython |
4805296 | # -*- coding: utf-8 -*-
from flask_pymongo import PyMongo
mongo = PyMongo() | StarcoderdataPython |
1615755 | from running_modes.reinforcement_learning.configurations.learning_strategy_configuration import LearningStrategyConfiguration
from running_modes.reinforcement_learning.learning_strategy import BaseLearningStrategy
from running_modes.reinforcement_learning.learning_strategy import DAPStrategy
from running_modes.reinforc... | StarcoderdataPython |
1623273 | import graphene
class AuthInfoField(graphene.ObjectType):
message = graphene.String()
| StarcoderdataPython |
3323274 | # Testing DPSS codes.
import multitaper.mtspec as mtspec
import multitaper.utils as utils
import numpy as np
import matplotlib.pyplot as plt
npts = 100
nw = 4.0
kspec = 7
dpss, v = utils.dpss2(npts,nw,kspec)
dpss1, v1 = utils.dpss(npts,nw,kspec)
print(v, v1)
plt.figure()
plt.plot(dpss[:,0],'k')
plt.plot(dps... | StarcoderdataPython |
1681209 | <reponame>vladdez/multilayer_perceptron
import numpy as np
import copy
class Optimizer:
def __init__(self, params, lr):
self.params = params
self.lr = lr
def action(self, iter_num):
raise NotImplementedError
class SGD(Optimizer):
def __init__(self, params, lr):
super()._... | StarcoderdataPython |
117459 | import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
def exponential(x, a, b):
return a * b**x
def get_curve_pars(d20, d21):
year = np.linspace(1, 120, num=120)
temp_20 = np.linspace(0, d20*100, num=100)
temp_21 = np.linspace(d20*101, d20*100 + d21*20, num=20)
... | StarcoderdataPython |
111118 | import ast, collections, dis, types, sys
from functools import reduce
from itertools import chain
from check_subset import check_conformity
def Instruction(opcode, arg):
return bytes([opcode] if arg is None else [opcode, arg % 256, arg // 256])
def concat(assemblies): return b''.join(assemblies)
def SetLineNo... | StarcoderdataPython |
3253586 | from ..base import ShopifyResource
class ProductSearchEngine(ShopifyResource):
pass
| StarcoderdataPython |
8956 | import json
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import redirect, render
from .models import Game2048
# Create your views here.
# test_user
# 8!S#5RP!WVMACg
def game(request):
return render(request, 'game_2048/index.html')
def set_result(req... | StarcoderdataPython |
84778 | <filename>read_ims_legacy.py
def read_ims_legacy(name):
data = {}
dls = []
#should read in .tex file
infile = open(name + ".tex")
instring = infile.read()
##instring = instring.replace(':description',' :citation') ## to be deprecated soon
instring = unicode(instring,'utf-8')
meta =... | StarcoderdataPython |
80097 | import flask
app = flask.Flask(__name__)
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
from flask.ext.babel import Babel
babel = Babel(app)
from flask import render_template
from flask.ext.babel import gettext as _, ngettext
@babel.localeselector
def get_locale():
return 'fr... | StarcoderdataPython |
3221895 | <reponame>unstad/jarvis2<filename>jarvis/app.py
# -*- coding: utf-8 -*-
import json
import logging
import os
try:
import queue
except ImportError:
import Queue as queue
try:
import socketserver
except ImportError:
import SocketServer as socketserver
from apscheduler.schedulers.background import Backg... | StarcoderdataPython |
92562 |
import sys, json, requests, wget
#import urllib2 import urlopen, URLError, HTTPError
def clientbundle():
pass
url="https://ec2-54-183-194-88.us-west-1.compute.amazonaws.com/auth/login"
data = dict(username='docker', password='<PASSWORD>')
r = requests.post(url, json=data, verify=False)
auth_token = json.loads(r.c... | StarcoderdataPython |
3228021 | <reponame>Valmarelox/auto_struct
from struct import Struct
from typing import Optional, Sequence, Any
from auto_struct.exceptions.type import ElementCountException
def create_struct(fmt: str) -> Struct:
return Struct('=' + fmt.replace('=', ''))
class BaseTypeMeta(type):
FORMAT = None
@property
def... | StarcoderdataPython |
1603763 | <gh_stars>1-10
import os
from random import shuffle
from utils.file_functions import get_subfolder_names
from archive.loader_archive.XSensRecordingReader import XSensRecordingReader
import pandas as pd
import utils.settings as settings
from utils.Recording import Recording
def load_dataset(dataset_path: str) -> "list... | StarcoderdataPython |
74713 | from django.test import TestCase
from django_hats.bootstrap import Bootstrapper
class RolesTestCase(TestCase):
def setUp(self, *args, **kwargs):
'''Clears `Roles` cache for testing.
'''
for role in Bootstrapper.get_roles():
setattr(role, 'group', None)
return super(Rol... | StarcoderdataPython |
3303136 | <reponame>MiCHiLU/google_appengine_sdk
# (c) 2005 <NAME> and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Gives a multi-value dictionary object (MultiDict) plus several wrappers
"""
import cgi
import copy
import sys
fro... | StarcoderdataPython |
4802310 | <reponame>amazon-research/network-deconvolution-pp
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
r"""
Basic training script for PyTorch
"""
# Set up custom environment before nearly anything else is imported
# NOTE: this should be the first import (no not reorder)
from maskrcnn_benchmark.util... | StarcoderdataPython |
1687992 | from scrapy import signals
from scrapy.exporters import CsvItemExporter, XmlItemExporter
class DownloadPipeline(object):
@classmethod
def from_crawler(cls, crawler):
pipeline = cls()
crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
crawler.signals.connect(p... | StarcoderdataPython |
1687075 | #!/usr/bin/python3
from sanitise import *
def generate_orchestration(namespace, prefix, orchestration):
sane_prefix = sanitise_for_include_guard(prefix)
header_filename = '{}orchestration.hpp'.format(prefix)
with open(header_filename, 'w') as file:
header = \
'''#ifndef crocofix_libcrocofixdiction... | StarcoderdataPython |
173147 | from __future__ import absolute_import
import logging
from io import StringIO
import argparse
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions, StandardOptions, GoogleCloudOptions, SetupOptions
from apache_beam.io.gcp.internal.clients import bigquery
from dotenv import load_do... | StarcoderdataPython |
166260 | <reponame>starsep/NewsBlur<gh_stars>1000+
from apps.reader.models import UserSubscription, UserSubscriptionFolders, Feature
from django.contrib import admin
admin.site.register(UserSubscription)
admin.site.register(UserSubscriptionFolders)
admin.site.register(Feature) | StarcoderdataPython |
90957 | from django.conf import settings
# Map of mode -> processor config
# {
# 'js': {
# 'processor': 'damn.processors.ScriptProcessor',
# 'aliases': {},
# },
# }
PROCESSORS = getattr(settings, "DAMN_PROCESSORS", {})
# File extension -> mode name
MODE_MAP = getattr(settings, "DAMN_MODE_M... | StarcoderdataPython |
1700448 | import unittest
from dan import DanModel, QuestionDataset
import numpy as np
import torch
import torch.nn as nn
text1 = {'text':torch.LongTensor([[2, 3]]).view(1, 2), 'len': torch.FloatTensor([2])}
text2 = {'text':torch.LongTensor([[1, 3, 4, 2, 1, 0]]).view(1, 6), 'len': torch.FloatTensor([5])}
text3 = {'text':torch.L... | StarcoderdataPython |
1614806 | from django.urls import path
from. import views
urlpatterns = [
path('',views.index,name='index'),
path('index',views.index,name='index'),
path('about',views.about,name='about'),
path('buses',views.buses,name='buses'),
path('Route',views.Route,name='Route')
]
| StarcoderdataPython |
4817819 | <gh_stars>10-100
import unittest
from datetime import datetime, timezone
from pyspedas.utilities.time_string import time_string, time_datetime, time_string_one
from pyspedas.utilities.time_double import time_float_one, time_float, time_double
class TimeTestCases(unittest.TestCase):
def test_time_datetime(self):
... | StarcoderdataPython |
3232718 | """
"""
__author__ = '<NAME> (DRL)'
# region the regular Type-Hints stuff
try:
# support type hints in Python 3:
# noinspection PyUnresolvedReferences
import typing as _t
except ImportError:
pass
# endregion
| StarcoderdataPython |
114447 | <filename>code/lychrel_numbers/sol_55.py
# -*- coding: utf-8 -*-
'''
File name: code\lychrel_numbers\sol_55.py
Author: <NAME>
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #55 :: Lychrel numbers
#
# For more information see:
# https://projecteuler.net/problem=... | StarcoderdataPython |
16943 | #!/usr/bin/python
help_msg = 'get uniprot length of entire proteome'
import os, sys
CWD = os.getcwd()
UTLTS_DIR = CWD[:CWD.index('proteomevis_scripts')]+'/proteomevis_scripts/utlts'
sys.path.append(UTLTS_DIR)
from parse_user_input import help_message
from read_in_file import read_in
from parse_data import organism
... | StarcoderdataPython |
1708651 | <reponame>ENCODERS09/AMF
########################################################
# evaluator.py
# Author: <NAME> <<EMAIL>>
# Created: 2014/2/6
# Last updated: 2016/4/30
########################################################
import numpy as np
import time
from utils import logger
import evallib
import AMF
from scip... | StarcoderdataPython |
1762728 | import unittest
import numpy as np
from lander.environment import MarsLanderEnv
class MarsLanderEnvTest(unittest.TestCase):
def test_detection_landing_area(self):
# https://www.codingame.com/ide/puzzle/mars-lander - Initial speed, correct side
ground = np.array(
[
[... | StarcoderdataPython |
1782451 | <reponame>sakthiRathinam/fastapicorenew
from uuid import UUID
from pydantic import BaseModel
from typing import List, Optional
from .models import RazorPayPlans
class RazorData(BaseModel):
razorpay_order_id:str
razorpay_payment_id: str
razorpay_signature: str
error: Optional[bool] = False
class Creat... | StarcoderdataPython |
3363487 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/4/14 上午 10:26
# @File : run.py
# @Software: PyCharm
# @Author : LiTian
import subprocess
import ctypes
# 模拟按下降低音量按键
def set_speaker_vol(num):
WM_APPCOMMAND = 0x319
APPCOMMAND_VOLUME_UP = 0x0a
APPCOMMAND_VOLUME_DOWN = 0x09
APPCOMMAND_VOL... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.