id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
9655119 | <reponame>Heron-Repositories/Transfer-Learning-In-Animals
import numpy as np
import copy
class MTT:
def __init__(self, _min_distance_to_target, _max_distance_to_target,
_target_offsets, _trap_offsets,
_dt, _man_speed, _must_lift_at_target, up_or_down):
self.... | StarcoderdataPython |
312747 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import pytest
import mock
from addons.onedrive import settings
from addons.onedrive.client import OneDriveClient
from addons.onedrive.tests.utils import (raw_root_folder_response, raw_me_response,
raw_user_personal_drive_response, dum... | StarcoderdataPython |
3215451 | <gh_stars>1-10
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.core.settings import AttributeProxyPro... | StarcoderdataPython |
9739325 | """
testing case_class.utils
Copyright (c) 2016 <NAME> -- licensed under MIT, see LICENSE
"""
from unittest import TestCase
from case_class import utils
class TestUtils(TestCase):
""" Tests the Utilities. """
def test_exec_(self):
""" Tests that the exec_ function can run code. """
local_... | StarcoderdataPython |
205165 | import numpy as np
from glob import glob
from os.path import join, basename, splitext
import open3d as o3d
load_dir = '/home/alex/github/waymo_to_kitti_converter/tools/dataloader/one_example'
pc_range = [-51.2, -51.2, -3, 51.2, 51.2, 9]
test_range = [0, -40, -3.0, 70.4, 40, 3.0]
# load_dir = '/home/alex/github/waymo_... | StarcoderdataPython |
379387 | # Tabela verdade do operador not
x = True
y = False
print(not x)
print(not y)
# Tabela verdade do operador and (e)(apenas true e true da true)
x = True
y = False
print(x and y)
# Tabela verdade do operador or (ou) (apenas false ou false da false)(o resto da true)
x = True
y = False
print(x or y)
# exemplo 1 not
x = ... | StarcoderdataPython |
1898569 | def plaindrome(phrase):
return phrase==phrase[::-1]
print(plaindrome("anna")) | StarcoderdataPython |
5112574 | <gh_stars>0
import mechanize, urllib2
from bs4 import BeautifulSoup
url = "http://foodscores.state.al.us/(S(bcxxpt55pb2zrt45ki3yef55))/Default.aspx"
def prep():
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/... | StarcoderdataPython |
1715458 | <reponame>gyger/PICwriter
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Default MPB launch-file for computing electromagnetic modes of arbitrary PICwriter waveguides.
MCM = "MPB Compute Mode"
Launches a MPB simulation to compute the electromagnetic mode profile for a given waveguide template and
material stack.
... | StarcoderdataPython |
6481907 | <filename>mil/metrics/manager.py
from mil.metrics import *
from mil.errors.custom_exceptions import ExpectedListError
from mil.errors.custom_warnings import invalid_metric_string
class MetricsManager:
def __init__(self, metrics=[]):
self.check_exceptions(metrics)
self.import_metrics(metrics)... | StarcoderdataPython |
4802688 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | StarcoderdataPython |
5131714 | <gh_stars>0
# -*- coding: utf-8 -*-
print "test" #中文注释
print u"为了巩固记忆,手打代码,不要偷懒(也不怎么费时间吧\n"
#ex1~ex4 省略了
#ex5 格式化字符
# my_name = 'Zed'
# my_age = 35;my_height = 74;my_weight = 180
# my_eyes = 'blue'
# my_teeth = 'white'
# my_hair = 'brown'
# print "let's talk about %s \nHe's %d inches tall" %(my_name,my_... | StarcoderdataPython |
4982864 | <filename>bin/macro_gen.py
#!/bin/python
from os import path, walk
import sys
import argparse
import yaml
import re
import json
def macro_gen(STRONTIC_PATH, REPO_PATH, VERBOSE):
macros = []
macro = dict()
with open(STRONTIC_PATH, 'r', encoding='utf-8-sig') as file:
strontic_objects = json.load(fi... | StarcoderdataPython |
3127 | from __future__ import absolute_import
import unittest
from testutils import ADMIN_CLIENT
from testutils import TEARDOWN
from library.user import User
from library.project import Project
from library.repository import Repository
from library.repository import pull_harbor_image
from library.repository import push_imag... | StarcoderdataPython |
4909291 | <reponame>jhconning/DevII<gh_stars>10-100
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fsolve
Pc = 4
Pw = 8
c = 1/2
d = 1/2
def F(x,P=Pc,c=c):
'''Cattle Profit Function'''
return P*x - c*x**2
def AG(x, P=Pw):
'''Wheat farm profit before crop damage'''
return P*(x**0... | StarcoderdataPython |
1753012 | import os, sys, argparse, codecs, getpass
from xml.dom.minidom import parse
from urllib.parse import unquote
from platform import system
from re import search, sub
from tkinter import Tk
from tkinter.filedialog import askopenfilename, askdirectory
##################################################################
## C... | StarcoderdataPython |
5102034 | <reponame>ArkDu/nanomanufacturing
import numpy as np
import cv2, statistics, pprint
from pathlib import Path
from argparse import ArgumentParser, RawTextHelpFormatter
import os
import sys
class Config:
'''Configuration and Argument Parser for particle detection.'''
def __init__(self, args):
self.parser... | StarcoderdataPython |
7823 | <reponame>obilaniu/orion<filename>tests/unittests/plotting/test_plotly_backend.py
"""Collection of tests for :mod:`orion.plotting.backend_plotly`."""
import copy
import numpy
import pandas
import plotly
import pytest
import orion.client
from orion.analysis.partial_dependency_utils import partial_dependency_grid
from ... | StarcoderdataPython |
3419619 | <reponame>pento-group/terran
from terran.tracking.face import face_tracking # noqa
| StarcoderdataPython |
78996 | <filename>board/viewmixins.py
import logging
from .models import Board
class BoardContextMixin(object):
logger = logging.getLogger(__name__)
def dispatch(self, *args, **kwargs):
self.board = Board.objects.get(slug=self.kwargs.get('slug'))
self.block_size = self.board.block_size
self... | StarcoderdataPython |
209927 |
import re
class Lexer(object):
def __init__(self, code):
self.code = code
def tokenize(self):
tokens = []
code = self.code.split()
code_len = 0
while code_len < len(code):
word = code[code_len]
if word == "var":
tokens.append(["VARIABLE", word])
elif re.match('[a-z]', word) or ... | StarcoderdataPython |
9798590 | <gh_stars>0
import logging
from ssl import CertificateError
import discord
from aiohttp import ClientConnectorError
from discord.ext.commands import BadArgument, Context, Converter
log = logging.getLogger(__name__)
class ValidPythonIdentifier(Converter):
"""
A converter that checks whether the given string... | StarcoderdataPython |
9707469 | <gh_stars>100-1000
from uuid import uuid4
from datetime import datetime
from typing import List, Optional, Union
from pydbantic import DataBaseModel, PrimaryKey
class Department(DataBaseModel):
department_id: str
name: str
company: str
is_sensitive: bool = False
positions: List[Optional['Positions... | StarcoderdataPython |
1752211 | <reponame>forestGzh/VTK
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
vtk.vtkMultiThreader.SetGlobalMaximumNumberOfThreads(1)
reader = vtk.vtkImageReader()
reader.SetDataByteOrderToLittleEndian()
reader.SetDataExtent(0,63,0,63,1,93)
reader.SetDataSpacing(3.... | StarcoderdataPython |
1986549 | <reponame>dlitz/vimfiles<filename>pack/vendor/start/taghelper.vim/pythonx/taghelper_c.py
def parse(buffer, tags):
curtag = None
last_unindented_line = ''
last_unindented_line_number = 1
for n, line in enumerate(buffer, 1):
line = line.rstrip()
# For now we assume a particular C style:
... | StarcoderdataPython |
6474069 |
class RsDnsError(RuntimeError):
def __init__(self, error):
self.error_msg = ""
try:
for message in error['validationErrors']['messages']:
self.error_msg += message
except KeyError:
self.error_msg += "... (did not understand the RsDNS response)."
... | StarcoderdataPython |
6502546 | #! /usr/bin/env python3
#
# Copyright 2018 California Institute of Technology
#
# 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
#
# Unle... | StarcoderdataPython |
1668226 | <filename>sgm/plot.py
import argparse
import datetime
import os
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
def returns_v_cleanup_steps(df):
# Hack for current planner names
df.loc[df["Planner"] == "SGM", "Planner"] = "Sparse Graphical Memory (ours)"
df.loc[df["Planner"] == ... | StarcoderdataPython |
129917 | <reponame>jachallbound/kmeans_python<filename>src/GaussianDistributionGenerator.py
import numpy as np
import numpy.random as npr
def generate_gaussian_data(D,
ndim,
samples,
priors = None,
means = None,
... | StarcoderdataPython |
8095169 | """Trivial redis store for domains.
Will be used to store a 7-day "sliding window" count of domains appearing in
delta reports.
Reads from Heroku Dataclip of domains in delta reports, writes to Redis.
Dataclip is:
select distinct delta_value->>0 as domain
from (
select
json_array_elements(data... | StarcoderdataPython |
11273670 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'miniMaxSum' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def miniMaxSum(arr):
# Write your code here
sum = 0
for i in arr:
sum+= i
print(sum-max(arr), sum-min(arr))
if ... | StarcoderdataPython |
3476769 | <reponame>ldtri0209/robotframework<filename>atest/testdata/test_libraries/dynamic_libraries/DynamicLibraryWithoutArgspec.py
class DynamicLibraryWithoutArgspec(object):
def get_keyword_names(self):
return [name for name in dir(self) if name.startswith('do_')]
def run_keyword(self, name, args):
... | StarcoderdataPython |
12827874 | # -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import Snapshot
snapshots = Snapshot()
snapshots["test_weather_route_payload_errors Missing payload"] = {
"detail": [
{
"loc": ["body", "lat"],
"msg": "fiel... | StarcoderdataPython |
340555 | <filename>rtamt/node/ltl/since.py
from rtamt.node.binary_node import BinaryNode
class Since(BinaryNode):
"""A class for storing STL Since nodes
Inherits TemporalNode
"""
def __init__(self, child1, child2):
"""Constructor for Since node
Parameters:
child1... | StarcoderdataPython |
1983203 | import os
import raven
from .base import * # noqa
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(' ')
DEBUG = False
# Persistent database connections
if os.environ.get('DATABASE_CONN_MAX_AGE'):
DATABASES['default']['CONN_MAX_AGE'] = int(os.environ.get('DATABASE_CONN_MAX_AGE'))
# Avoid server side ... | StarcoderdataPython |
5157827 | '''
Created on 12.12.2020
MIT License
Copyright (c) 2020 <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, cop... | StarcoderdataPython |
92963 | from typing import Optional, List
from seedwork.domain.entities import Aggregate
from seedwork.domain.value_objects import UUID
from modules.iam.domain.value_objects import Session
ANONYMOUS_ID = UUID("00000000-0000-0000-0000-000000000000")
class User(Aggregate):
id: UUID
username: str
email: str = ""
... | StarcoderdataPython |
6645387 | import os
import sys
sys.path.append("/data/luowei/MMIN")
# print(sys.path)
import json
from typing import List
import torch
import numpy as np
import h5py
from torch.nn.utils.rnn import pad_sequence
from torch.nn.utils.rnn import pack_padded_sequence
from data.base_dataset import BaseDataset
class MultimodalDataset... | StarcoderdataPython |
1657125 | <reponame>kirillzx/Math-projects
def helix(n):
t = [[0]*n for i in range (n)]
i, j = 0, 0
for k in range(1, n*n+1):
t[i][j]=k
if k == n*n: break
if i<=j+1 and i+j<n-1:
j+=1
elif i<j and i+j>=n-1:
i+=1
elif i>=j and i+j>n-1:
... | StarcoderdataPython |
9704767 | """URL route definitions for secure authorization tool."""
import json
from flask import render_template, flash, redirect, url_for
from app.routes import routes_bp
from app.util.crypto import get_public_key_hex
@routes_bp.route("/secure_auth", methods=["GET", "POST"])
def secure_auth():
result = get_public_key_h... | StarcoderdataPython |
4866679 | <filename>egs/babel/tts1/babel_prepare.py<gh_stars>0
import os
import numpy as np
import librosa
UNK = ['(())']
NONWORD = '~'
EPS = 1e-3
LOGEPS = -60
DEBUG = True
def VAD(y, fs, thres=EPS, coeff=1.0):
L = y.shape[0]
window_len = min(int(fs * 0.1), L)
dur = float(y.shape[0]/fs)
exp_filter = coeff ** (np.arange... | StarcoderdataPython |
11325016 | import io
import json
import logging
import struct
import sys
import traceback
import typing
from fastavro import schemaless_reader, schemaless_writer
from schema_registry.client import SchemaRegistryClient, schema
from schema_registry.client.errors import ClientError
from .errors import SerializerError
log = loggi... | StarcoderdataPython |
4963258 | # -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://support.direct.ingenico.com/documentation/api/reference/
#
from ingenico.direct.sdk.data_object import DataObject
class OrderTypeInformation(DataObject):
"""
| Object that holds the purchase and usage type ind... | StarcoderdataPython |
184292 | import gmplot
import matplotlib.pyplot as plt
import pvlib as pv
import mplcursors
from datetime import datetime, timedelta
from analytics.location.path import Path, LinearPath
from loguru import logger
def main():
path = LinearPath.create(
start_loc=pv.location.Location(latitude=42, longitude=-71),
... | StarcoderdataPython |
1913027 | <gh_stars>1-10
from typing import Any
from rx.core import ObservableBase, Observable
def of(*args: Any) -> ObservableBase:
"""This method creates a new Observable instance with a variable number
of arguments, regardless of number or type of the arguments.
Example:
res = rx.Observable.of(1,2,3)
... | StarcoderdataPython |
8131445 | from django.shortcuts import render
from django.http import Http404
def home(request):
return render(request, 'ashgear/home.html',
{'projects': ['project1', 'project2']})
def handler404(request, exception):
return render(request, "errors/404.html", {})
def products(request):
raise Ht... | StarcoderdataPython |
6520984 | aluno = dict()
aluno['nome'] = str(input('Nome: ')).strip()
aluno['media'] = float(input(f'Média de {aluno["nome"]}: '))
print(f'Média é igual a {aluno["media"]}')
if aluno['media'] < 7:
print('Situação é igual a Reprovado!')
else:
print('Situação é igual a Aprovado!')
| StarcoderdataPython |
1973341 | <reponame>doobdev/doob
import logging
from random import choice, randint, random
from typing import Optional
from aiohttp import request
from datetime import datetime
from asyncio import sleep
from discord import Member, Embed, Colour
from discord.ext.commands import Cog, command, cooldown, BucketType, group
from disc... | StarcoderdataPython |
3448697 | import os, time, flask, string, MySQLdb, openpyxl, wtforms, jinja2
from flask import Flask, Blueprint, render_template, request, redirect, url_for, flash, sessions, session, send_from_directory, send_file
from flaskr import app, allowed_file, flask_bcrypt, db, bcrypt, models
from os.path import join, dirname, realpa... | StarcoderdataPython |
3272787 | # Calculate level completion rates via mixpanel export API
# TODO: unique users
# TODO: align output
# TODO: order output
import sys
from mixpanel import Mixpanel
try:
import json
except ImportError:
import simplejson as json
# NOTE: mixpanel dates are by day and inclusive
# E.g. '2014-12-08' is any date th... | StarcoderdataPython |
8115101 | <filename>Service/__init__.py
__author__ = 'sgrubor'
| StarcoderdataPython |
9633667 | <filename>api/handlers/orders.py
from datetime import datetime
from fastapi import APIRouter, status
from sqlalchemy import and_
from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse
from sqlalchemy.exc import IntegrityError
from db.base import Session
from api.schema import Ord... | StarcoderdataPython |
6654461 | #
# Created on Tue Dec 21 2021
#
# Copyright (c) 2021 Lenders Cooperative, a division of Summit Technology Group, Inc.
#
from django.conf import settings
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.shortcuts import redirect
... | StarcoderdataPython |
1964321 | <reponame>WING-NUS/RL-for-Question-Generation<filename>src/onqg/models/decoders/TransfDecoder.py
import torch
import torch.nn as nn
import onqg.dataset.Constants as Constants
from onqg.models.modules.MaxOut import MaxOut
from onqg.models.modules.Layers import DecoderLayer
from onqg.utils.mask import get_non_pad_mask... | StarcoderdataPython |
359653 | # coding: utf-8
"""
Idfy.Signature
Sign contracts, declarations, forms and other documents using digital signatures. ## Last update Last build date for this endpoint: 18.03.2019
"""
import pprint
import re
from typing import List, Dict
from datetime import datetime as datetime
from idfy_sdk.services.... | StarcoderdataPython |
8082784 | import sys
import subprocess
import logging
from pathlib import Path
import numpy as np
from types import SimpleNamespace
import io
from contextlib import redirect_stdout
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import Qt, QObject, pyqtSlot, QThread, pyqtSignal, QLocale
from PyQt5.QtGui import QIco... | StarcoderdataPython |
5070196 | from rpy2.robjects.packages import importr, isinstalled
from rpy2.rinterface import FloatSexpVector, ComplexSexpVector
from rpy2.robjects.conversion import Converter
import rpy2.robjects as robjects
import pandas as pd
# method to return Python representation of R vectors
@robjects.conversion.py2ri.register(FloatSexpV... | StarcoderdataPython |
72613 | ######################################################################################################################
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | StarcoderdataPython |
3362345 | <filename>leasing/tests/test_utils.py
from datetime import date
from leasing.utils import calculate_increase_with_360_day_calendar, days360
def test_days360_year():
date1 = date(year=2020, month=1, day=1)
date2 = date(year=2021, month=1, day=1)
days = days360(date1, date2, True)
assert days == 360
... | StarcoderdataPython |
9688759 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-12-26 10:21
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | StarcoderdataPython |
203316 | <reponame>abhikpal/p5-examples
from p5 import *
def draw():
no_loop()
arc((180, 180), 251, 251, 0, PI + QUARTER_PI, 'OPEN')
run()
| StarcoderdataPython |
9607256 | <reponame>calhewitt/snewpdag<gh_stars>0
"""
Node in the directed acyclic graph.
Implemented on observer-observable pattern.
Plugins should subclass Node and override alert, revoke, reset, report.
"""
import logging
from snewpdag.values import History
class Node:
def __init__(self, name, **kwargs):
"""
Ini... | StarcoderdataPython |
12840129 | <gh_stars>0
"""
A simple example for Reinforcement Learning using table lookup Q-learning method.
An agent "o" is on the left of a 1 dimensional world, the treasure is on the rightmost location.
Run this program and to see how the agent will improve its strategy of finding the treasure.
View more on my tutorial page: ... | StarcoderdataPython |
9603949 | <filename>debugwire.py
import time
import avrasm as asm
from collections import namedtuple
class DummyProfiler:
def step(self, title): pass
class SimpleProfiler:
def __init__(self):
self.prev = time.monotonic()
def step(self, msg):
now = time.monotonic()
print("{:10.6f}s {}".forma... | StarcoderdataPython |
12825916 | #!/usr/bin/env python3
#_*_ coding: utf-8 _*_
__author__ = "monkey"
from dal import autocomplete
from apps.blog.models import Category, Tag
class CategoryAutoComplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated:
return Category.objects... | StarcoderdataPython |
11254263 | <filename>sprp_dialog.py
# -*- coding: utf-8 -*-
"""
/***************************************************************************
SimplePhotogrammetryRoutePlannerDialog
A QGIS plugin
A imple photogrammetry route planner.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Pl... | StarcoderdataPython |
4998956 | # -*- coding: utf-8 -*-
from collections import Counter
class Solution:
def hasGroupsSizeX(self, deck):
counts = Counter(deck).values()
min_count = min(counts)
if min_count == 1:
return False
partition_size = min_count
for count in counts:
remaind... | StarcoderdataPython |
19870 | # Imports
import socket
import subprocess
import os
import requests
# from prettytable import PrettyTable
import getpass
import CONFIG
def send_message(text):
try:
requests.post('https://slack.com/api/chat.postMessage', {
'token': CONFIG.SLACK_TOKEN,
'channel': CONFIG.SLACK_CHANNEL_INFO,
... | StarcoderdataPython |
3384887 | <gh_stars>10-100
"""Logging."""
import logging
import platform
# Logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
file_handler = logging.FileHandler('.plonk.log')
console_handler.setLevel(logging.INFO)
file_handler.setLevel(logging.DEBUG)
console... | StarcoderdataPython |
11386020 | <filename>src/PolygonGrouper.py
from __future__ import division
import numpy as np
from matplotlib.patches import Polygon
import collections
import matplotlib.pyplot as plt
import matplotlib.path as path
#from SpectrumImagePlotter import PatchWatcher
class PolygonGroupManager(object):
def __init__(self, axis):
... | StarcoderdataPython |
1939573 | <filename>counter/migrations/0003_auto_20201205_2353.py<gh_stars>0
# Generated by Django 3.1.4 on 2020-12-05 21:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('counter', '0002_auto_20201205_2349'),
]
operations = [
migrations.RemoveField(
... | StarcoderdataPython |
8176775 | <reponame>Nitin-Mane/Python-Deep-Learning-Projects<filename>Chapter05/3. rnn_lstm_seq2seq.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import numpy as np , os
import tensorflow as tf
import collections
# Data Preparation
def build_dataset(words, n_words):
count = [['GO', 0], ['PAD', 1], ['EOS', 2], ['UNK', ... | StarcoderdataPython |
1961431 | import torch
import numpy as np
from collections import Counter
def _pairwise_distances(embeddings, squared=False):
# Get the dot product between all embeddings
# shape (batch_size, batch_size)
dot_product = torch.matmul(embeddings, torch.transpose(embeddings, 0, 1))
# Get squared L2 norm for each em... | StarcoderdataPython |
3309272 | <gh_stars>1-10
# Part of web_progress. See LICENSE file for full copyright and licensing details.
from odoo import models, api, registry, fields, _
import uuid
class IrCron(models.Model):
_inherit = 'ir.cron'
@api.model
def _callback(self, cron_name, server_action_id, job_id):
"""
Add web... | StarcoderdataPython |
5030519 | #!/usr/bin/env python3
#*******************************************************************************
#* reducer.py
#*
#* Copyright (C) 2018 <NAME> <<EMAIL>>
#*
#* All rights reserved. Published under the BSD-2 license in the LICENSE file.
#****************************************************************************... | StarcoderdataPython |
264560 | from functools import wraps
from flask import abort, request
def validate_json(f):
"""
Checks if a requests content-type is "application/json"
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if request.is_json:
return f(*args, **kwargs)
else:
retu... | StarcoderdataPython |
6640373 | #
# Copyright Logimic,s.r.o., www.logimic.com
#
# 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 agre... | StarcoderdataPython |
4973863 | <reponame>andreymal/certbot-dns-sweb
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import random
import logging
import zope.interface
from certbot import errors, interfaces
from certbot.plugins import dns_common
from .sweb_client import SWebClient
from .sweb_api i... | StarcoderdataPython |
3593331 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, <NAME> (@anvitha-jain) <<EMAIL>>
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: aci_clo... | StarcoderdataPython |
6614944 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, date
sample_size = 500
sigma_e = 3.0 # true value of parameter error sigma
random_num_generator = np.random.RandomState(0)
x = 10.0 * random_num_generator.rand... | StarcoderdataPython |
1725218 | <gh_stars>10-100
class User():
def __init__(self,first_name,last_name,username,email,number,age):
self.first_name = first_name
self.last_name = last_name
self.username = username
self.email = email
self.number = number
self.age = age
def describe_user(self):
... | StarcoderdataPython |
139031 | <reponame>NOAO/astroquery
"""
CSIRO ASKAP Science Data Archive (CASDA)
"""
from astropy import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astroquery.casda`.
"""
server = _config.ConfigItem(
['https://casda.csiro.au/casda_vo_tools/sia2/query'],
... | StarcoderdataPython |
43901 | """
sphinx_c_autodoc is a package which provide c source file parsing for sphinx.
It is composed of multiple directives and settings:
.. rst:directive:: .. c:module:: filename
A directive to document a c file. This is similar to :rst:dir:`py:module`
except it's for the C domain. This can be used for both c... | StarcoderdataPython |
1824141 | # Copyright 2018 Google LLC
#
# 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 writing, s... | StarcoderdataPython |
1708240 | <reponame>zakness1/painel<gh_stars>1-10
import requests
from data import ui
def consultar(token='2<PASSWORD>',self=0):
Sair = False
while(Sair == False):
if self == 1:
ip_input = ''
else:
ip_input = ui.input_dialog()
if len(ip_input) < 1:
ui.er... | StarcoderdataPython |
1630703 | <reponame>kavyapnaik/PythonRemoteServer<gh_stars>100-1000
from __future__ import print_function
import sys
class Logging(object):
def logging(self, message, level='', evaluate=False, stderr=False):
if evaluate and evaluate != 'False':
message = eval(message)
if level:
mes... | StarcoderdataPython |
5144225 | <reponame>minMaximilian/webdev2<gh_stars>0
#!/usr/bin/python3
import os
import sys
restricted = "../restricted"
sys.path.append(os.path.abspath(restricted))
from cgi import FieldStorage
from html import escape
import pymysql as db
import passwords
import funcs
from os import environ
from http.cookies import SimpleC... | StarcoderdataPython |
3220566 | import tensorflow as tf
from detext.layers.embedding_layer import create_embedding_layer
from detext.utils.layer_utils import get_sorted_dict
from detext.utils.parsing_utils import InputFtrType, InternalFtrType
class LstmLayer(tf.keras.layers.Layer):
def __init__(self, bidirectional, rnn_dropout, num_layers, for... | StarcoderdataPython |
6422046 | <gh_stars>100-1000
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from rotkehlchen.db.dbhandler import DBHandler
def upgrade_v16_to_v17(db: 'DBHandler') -> None:
"""Upgrades the DB from v16 to v17
- Deletes all ethereum transactions and query ranges from the DB so they
can be saved again with ... | StarcoderdataPython |
8040038 | #!/usr/bin/env python
"""
Locate libpython associated with this Python executable.
"""
# https://pypi.org/project/find-libpython/
# License
#
# Copyright 2018, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Softwar... | StarcoderdataPython |
9632871 | <filename>tests/converter/test_converter.py
import pytest
import random
from qctools.converter import Converter
@pytest.fixture
def example_converter():
''' Returns an example converter '''
converter = Converter.from_dct('example', 'ref', {
'ref': (1, 'direct'),
'eV': (27, 'direct'),
... | StarcoderdataPython |
299963 | <gh_stars>10-100
# --------------------------------
# Testing
# --------------------------------
# is it a test run?
# test runs reduce the dataset to 100 instances only
from enum import IntEnum
TEST = False
# --------------------------------
# FileTypes
# --------------------------------
# Do we only look at product... | StarcoderdataPython |
105855 | from django.views.generic import TemplateView, ListView
from .models import Spool
from django.db.models import Q
# Create your views here.
class HomePageView(TemplateView):
template_name = 'home.html'
class SearchResultsView(ListView):
model = Spool
template_name = 'search_results.html'
def get_q... | StarcoderdataPython |
6499442 | # pylint: disable=missing-module-docstring
from dataclasses import dataclass
from typing import List
from league_history_collector.models.player import Player
from league_history_collector.utils import CamelCasedDataclass
@dataclass
class Roster(CamelCasedDataclass):
"""Contains data for a roster."""
# Usi... | StarcoderdataPython |
4944660 | from aiohttp_requests import requests
from typing import Optional
from dotenv import load_dotenv
import json
import asyncio
import os
load_dotenv()
APIKEY = os.getenv('APIKEY')
def _simplify(
url: str
) -> str:
return url.replace('http://', '').replace('https://', '')
def get_gif_id(
url: str
) -> str... | StarcoderdataPython |
87683 | <reponame>mikesmiley/lzh<gh_stars>1-10
{
"targets": [
{
"target_name": "lzh",
"sources": [ "src/binding.cc", "src/lzh.c" ],
"include_dirs": [
"<!(node -e \"require('nan')\")",
"<!(node -e \"require('cpp-debug')\")"
]
}
]
}
| StarcoderdataPython |
5166020 | <reponame>Eve-ning/reamber_base_py
from tests.test import algorithms, base, osu, timing
__all__ = ['algorithms', 'base', 'osu', 'timing']
| StarcoderdataPython |
11243013 | #!/usr/bin/env python3
"""
Describe in this sentence what this program does.
Copyright (c) 2019 <NAME>. All rights reserved.
"""
import argparse
import submodule.main
def main():
program_options = get_program_options()
x = submodule.main.yourfunction()
# Continue here
return x
def get_program_op... | StarcoderdataPython |
8142220 | <gh_stars>0
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError
class ClientWrapper(object):
"""
This class is a Wrapper to pull and push clients from/to the table openidclients in MySQL
"""
def __init__(self, db_uri):
self._db_uri = db_uri
def __setitem__(self... | StarcoderdataPython |
4867235 | <reponame>chunlin-pan/DYSTA
import json
import sympy
class BasicNode(object):
def __init__(self):
self.time_complexity = sympy.Rational(1)
self.__children = []
self.col = 0
self.line_number = 0
self.parent = None
self.__type = self.__class__.__name__
pass... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.