id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
5093531
<filename>window/classic_setup_win.py<gh_stars>0 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'classic_setup_win_template.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file ...
StarcoderdataPython
6660097
import logging import math import random import sys from typing import Callable, Set import numpy as np import pytest from leaker.api import DataSink, RandomRangeDatabase, InputDocument, RangeDatabase, BaseRangeDatabase, \ PermutedBetaRandomRangeDatabase, BTRangeDatabase, ABTRangeDatabase, Selectivity from leaker...
StarcoderdataPython
1892161
<reponame>D-Mbithi/Real-Python-Course-Solutions from reportlab.pdfgen import canvas c = canvas.Canvas("hello.pdf") c.drawString(250, 500, "hello world") c.save()
StarcoderdataPython
3352338
# -*- coding: utf-8 -*- """Top-level package for FlowPing.""" __author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ = '0.1.0'
StarcoderdataPython
1615638
<reponame>remarkablerocket/changelog-cli __version__ = "0.7.0"
StarcoderdataPython
5135410
<filename>desugar/__init__.py """Re-implement the parts of Python that allow removing its syntactic sugar.""" __version__ = "0"
StarcoderdataPython
6683655
#-*- coding: utf8 from __future__ import print_function, division from pyksc import ksc import myio import numpy as np def cluster(T, num_clust=5): ''' Runs the KSC algorithm on time series matrix T. Parameters ---------- T : ndarray of shape (row, time series length) The time series to ...
StarcoderdataPython
1846853
# Lint as: python # # Authors: Vittorio | Francesco # Location: Turin, Biella, Ivrea # # This file is based on the work of Francisco Dorr - PROBA-V-3DWDSR (https://github.com/frandorr/PROBA-V-3DWDSR) """Training class and some functions for training RAMS""" import tensorflow as tf from tensorflow.keras.utils import Pr...
StarcoderdataPython
270470
<reponame>ttbrunner/blackbox_starting_points import numpy as np def find_img_centroid(img, min_mass_threshold=0.): """ Finds the centroid of a grayscale image (center of mass for a saliency map). """ assert len(img.shape) == 2 # TD: Vectorize this in the next version vec_sum = np.zeros(2, dtype=np.f...
StarcoderdataPython
6645178
<filename>examples_source/2D_simulation(macro_amorphous)/plot_1_I=2.5.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ Czjzek distribution, ²⁷Al (I=5/2) 3QMAS ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ²⁷Al (I=5/2) 3QMAS simulation of amorphous material. """ # %% # In this section, we illustrate the simulation of a q...
StarcoderdataPython
45865
<reponame>pythonran/easy_server from view_core import View from easyserver import easyResponse import json class Index(View): def get(self, request): print request data = { "body": request.body, "option": "test" } return easyResponse(json.dumps(data))
StarcoderdataPython
4887823
<gh_stars>1-10 #!/usr/bin/env python3 import subprocess import json import os BASEDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") def tokei(paths, *, exclude=[]): args = [] for e in exclude: args.extend(["-e", e]) for p in paths: args.append(os.path.join(BASEDIR, p...
StarcoderdataPython
5147789
from django.db import models from django.utils.translation import gettext_lazy as _ from core.models import BaseAbstractModel from core.utils import IBANValidator from payments.managers import BankAccountQuerySet class Bank(BaseAbstractModel): """ Bank model """ name = models.CharField(max_length=100...
StarcoderdataPython
4962468
<gh_stars>0 # Copyright 2021 Sony Semiconductors Israel, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
StarcoderdataPython
3341855
<reponame>knuu/competitive-programming<filename>atcoder/abc/abc030_b.py N, M = map(int, input().split()) N %= 12 l = M / 60 s = (N + l) / 12 ans = 360 * abs(l - s) print('{:.12}'.format(min(ans, 360 - ans)))
StarcoderdataPython
6569439
import json import subprocess import pytest from cli.autocomplete import ac_table from cli.export import api_to_dict from jina.checker import NetworkChecker from jina.jaml import JAML from jina.parsers import set_pod_parser, set_pea_parser from jina.parsers.ping import set_ping_parser from jina.peapods import Pea d...
StarcoderdataPython
8023876
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated Tue Oct 10 00:42:20 2017 by generateDS.py version 2.28b. # Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] # # Command line options: # ('--no-process-includes', '') # ('-o', 'esociallib/v2_04/evtAltContratual.py') # # Command line arg...
StarcoderdataPython
3414155
# -*- coding: utf-8 -*- """Assignment_6_notebook_.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1UqM-uY5syVVVrflH5Uaj6hi1qnMuXuG2 **Import** *and* setup some auxiliary functions """ # Don't edit this cell import os import timeit import time im...
StarcoderdataPython
22301
from odoo import models, fields, api from odoo.exceptions import ValidationError class DemoOdooWizardTutorial(models.Model): _name = 'demo.odoo.wizard.tutorial' _description = 'Demo Odoo Wizard Tutorial' name = fields.Char('Description', required=True) partner_id = fields.Many2one('res.partner', strin...
StarcoderdataPython
6569101
<reponame>joepetrini/bike-counter from django.conf import settings from django.http import HttpResponseRedirect #from django.core.urlresolvers import reverse from django.contrib.auth import login as auth_login, logout, authenticate #from django.views.generic import ListView, DetailView from django.contrib.auth.forms im...
StarcoderdataPython
5123172
<filename>camkes/parser/tests/testexamples.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2017, Data61 # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # ABN 41 687 119 230. # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Not...
StarcoderdataPython
1962332
""" Reader for the hashtable, in combination with the :class:`SpatialRegion` objects from ``regions.py``. Use the :class:`SpatialLoader` class to set up and read from the hashtables. Note that all large data is actually contained in the region objects, and the loader class is really just a convenience object. """ fr...
StarcoderdataPython
8023202
<filename>tests.py from textgen import TextGenerator def test_add_item(): generator = TextGenerator() generator._add("x", "a") assert generator._get("x")[0] == "a" def test_add_two_items(): generator = TextGenerator() generator._add("x", "a") generator._add("x", "b") assert generator._...
StarcoderdataPython
4935352
<reponame>StudyForCoding/BEAKJOON import sys N=int(sys.stdin.readline()) num=[] for _ in range(N): num.append(list(map(int, sys.stdin.readline().split()))) result = [] for n in range(1,N+1): result.append([0]*n) result[0][0]=num[0][0] for i in range(1,N): for j in range(i+1): if j ==0: ...
StarcoderdataPython
3404109
<reponame>MatthewTsan/Leetcode # Definition for a binary tree node. from collections import defaultdict, deque from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def distanceK(self, root: TreeNode, target: Tre...
StarcoderdataPython
9606469
<filename>fips-generators/util/hlslcompiler.py<gh_stars>10-100 ''' Python wrapper for HLSL compiler (fxc.exe) NOTE: this module contains Windows specific code and should only be imported when running on Windows. ''' import subprocess, platform, os, sys import genutil as util if sys.version_info[0] < 3: import _win...
StarcoderdataPython
74996
<reponame>sgondala/Automix<filename>yahoo_with_mixtext/hyperopt_eval_single.py<gh_stars>1-10 import torch import torch.nn.functional as F from torch.utils.data import DataLoader import numpy as np from FastAutoAugment.read_data import * from FastAutoAugment.classification_models.MixText import * import pickle import ...
StarcoderdataPython
11229715
from abc import ABC from src.model.BagOfWords import BagOfWords class CoefficientStrategy(ABC): def exec(self): pass class DiceStrategy(CoefficientStrategy): def __init__(self, bag1: BagOfWords, bag2: BagOfWords): self.__bag1 = bag1 self.__bag2 = bag2 def exec(self): r...
StarcoderdataPython
3429871
<reponame>TheShadow29/subreddit-classification-dataset """ Creates the final json file to be submitted Author: <NAME> """ import json from pathlib import Path import pandas as pd def get_corpus_from_csv(csvf): """ Returns the corpus after reading the csv file """ csv_data = pd.read_csv(csvf) corp...
StarcoderdataPython
6485526
"""Unit tests for ProductManifold.""" import random import geomstats.backend as gs import geomstats.tests from geomstats.geometry.euclidean import Euclidean from geomstats.geometry.hyperboloid import Hyperboloid from geomstats.geometry.hypersphere import Hypersphere from geomstats.geometry.minkowski import Minkowski f...
StarcoderdataPython
6608308
<gh_stars>0 from azure.quantum.target.ionq import IonQ from azure.quantum.target.honeywell import Honeywell from azure.quantum.target.target import Target
StarcoderdataPython
8086773
#!/usr/bin/env python """ _NewWorkflow_ MySQL implementation of NewWorkflow """ from WMCore.Database.DBFormatter import DBFormatter class New(DBFormatter): """ Create a workflow ready for subscriptions """ sql = """insert into wmbs_workflow (spec, owner, name, task, type, alt_fs_close, priority) ...
StarcoderdataPython
1607209
from typing import Iterable from django.db.models import QuerySet from django.utils import timezone from accounts.models import User from schedules.models import Event, Attendant def get_events(church_name: str = None, limit: int = None, order_by_start: str = None) -> QuerySet[Event]: event_list = Event.objects...
StarcoderdataPython
1932708
# -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url( r'^admin/', include(admin.site.urls) ), # eg host/project_x/admin/ url( r'^', include('ebook_finder.urls_app') ), # eg host/project_x/anything...
StarcoderdataPython
357258
<reponame>AbrahamSanders/ir-dialogue-eval<filename>ir-dialogue-eval/dataset_loaders/frames_dataset_loader.py """ DatasetLoader implementation for the Frames dataset """ from os import path import json import re from dataset_loaders.dataset_loader import DatasetLoader from domain import Domain class FramesDatasetLoade...
StarcoderdataPython
9600158
<reponame>rjzamora/dask-cuda<filename>dask_cuda/tests/test_device_host_file.py from random import randint import dask.array as da from dask_cuda.device_host_file import ( DeviceHostFile, device_to_host, host_to_device, ) from distributed.protocol import deserialize_bytes, serialize_bytelist import numpy a...
StarcoderdataPython
1635406
# -*- coding: utf-8 -*- # @Time : 2018/6/7 下午5:22 # @Author : waitWalker # @Email : <EMAIL> # @File : MTTDataBase.py # @Software: PyCharm # 数据连接 import pymysql import time class MTTDataBase: error_code = '' instance = None # db = None # cursor = None timeout = 30 time_count = 0 ...
StarcoderdataPython
228888
import numpy as np def deadband(value, band_radius): return max(value - band_radius, 0) + min(value + band_radius, 0) def clipped_first_order_filter(input, target, max_rate, tau): rate = (target - input) / tau return np.clip(rate, -max_rate, max_rate)
StarcoderdataPython
1925268
<filename>WhatsAppManifest/automator/whatsapp/database/companion_devices.py from WhatsAppManifest.manifest.whatsapp.path import Path from WhatsAppManifest.automator.whatsapp.database.base import WhatsAppDatabase class WhatsAppDatabaseCompanionDevices(WhatsAppDatabase): """ WhatsApp Companion Devices Database ...
StarcoderdataPython
8068720
<reponame>RaviPandey33/gym-electric-motor-1 import numpy as np from gym.spaces import Box from ..random_component import RandomComponent from ..core import ReferenceGenerator from ..utils import instantiate class SwitchedReferenceGenerator(ReferenceGenerator, RandomComponent): """Reference Generator that switche...
StarcoderdataPython
12830687
<gh_stars>0 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union fro...
StarcoderdataPython
1942254
from schematics.models import Model from schematics.types import StringType from schematics.types.compound import DictType, ModelType from .schema import Schema from .headers import Headers class Response(Model): description = StringType(required=True, serialize_when_none=False) schema = ModelType(Schema, ser...
StarcoderdataPython
3555790
<filename>ancillary/Outliner.py True = 1 False = None class OutlinerNode: _expanded_p = True _parent = None _depth = 0 def __init__(self): self._children = [] def __repr__(self): tabdepth = self._depth - 1 if self.leaf_p(): tag = ' ' elif self.expanded_p(): tag...
StarcoderdataPython
6629380
from mock import MagicMock from nose.tools import assert_equals, assert_not_equals, raises, with_setup import json from hdijupyterutils.configuration import override, override_all, with_override from hdijupyterutils.configuration import _merge_conf # This is a sample implementation of how a module would use the conf...
StarcoderdataPython
96320
# -*- coding:utf-8 -*- import re def parse(s): l = re.sub(r'\s+', ', ', (' '+s.lower()+' ').replace('(', '[').replace(')', ']'))[2:-2] return eval(re.sub(r'(?P<symbol>[\w#%\\/^*+_\|~<>?!:-]+)', lambda m : '"%s"' % m.group('symbol'), l)) def cons(a, d): if atom(d): return (a, d) return (lambda...
StarcoderdataPython
79825
<reponame>PrinceOfPuppers/qbot<filename>qbot/density.py import numpy as np import numpy.linalg as linalg from qbot.helpers import ensureSquare, log2 import qbot.qgates as gates def ketsToDensity(kets:[np.ndarray],probs: [float] = None) -> np.ndarray: '''converts set of kets to a density matrix''' if probs == N...
StarcoderdataPython
8066305
<gh_stars>1-10 # -*- coding: utf-8 -* from search_functions import * from config import url_sc import time pyautogui.FAILSAFE = True screenWidth, screenHeight = pyautogui.size() pyautogui.hotkey('alt', 'Tab') open_url(url_sc, screenWidth * 0.2, screenHeight / 0.06) time.sleep(5) for song in open('song_list.txt', 'r'...
StarcoderdataPython
8196161
<reponame>roedoejet/wordweaver-legacy from wordweaver.app import app from wordweaver.config import ENV_CONFIG DEBUG = ENV_CONFIG['DEBUG'] HOST = ENV_CONFIG['HOST'] PORT = int(ENV_CONFIG['PORT']) THREADED = ENV_CONFIG['THREADED'] app.run(debug=DEBUG, host=HOST, port=PORT, threaded=THREADED)
StarcoderdataPython
38486
<filename>eventi/core/admin.py # coding: utf-8 from django.contrib import admin from eventi.core.models import Club, Info admin.site.register(Club) admin.site.register(Info)
StarcoderdataPython
6682506
from copy import copy from graphviz import Digraph from typing import List, Tuple, Dict from DataObjects.ClassState import State from DataObjects.ClassArchitecture import Architecture from DataObjects.ClassMachine import Machine from DataObjects.ClassSystemTuple import SystemTuple from Parser.ForkTree import ForkTree ...
StarcoderdataPython
3488976
""" package have crawling stuffs """ import logging import typing from http.client import responses import requests logger = logging.getLogger(__name__) class CodeForcesHTTPClient(object): host: str port: int lang: str # generate API key at: https://codeforces.cc/settings/api # (public, secret)...
StarcoderdataPython
1634712
"""shader_noise shader function and texture generator as described in "GPU Gems" chapter 5: http://http.developer.nvidia.com/GPUGems/gpugems_ch05.html """ __version__ = "$Id: shader_noise.py 37 2008-06-27 22:25:39Z casey.duncan $" from noise import pnoise3 import ctypes from pyglet.gl import * class ShaderNoiseText...
StarcoderdataPython
1922097
from dataclasses import dataclass from typing import List, Union import numpy as np import pytest from pytest_cases import cases_data, THIS_MODULE from eddington import ( constant, exponential, hyperbolic, linear, parabolic, polynom, cos, sin, straight_power, inverse_power, ...
StarcoderdataPython
4848343
# basic of simple calculator app # you only calculate between two numbers # the operation list are : +, -, *, /, and % # the ">" for adding a new number # set the global variable for store the current total subtotal = 0 total = 0 # error handling for input def error_handling(int_type, float_type1, float_type2): #...
StarcoderdataPython
258858
<gh_stars>1-10 import json import os from pathlib import Path from collections import Mapping from abc import abstractmethod import moodle.models as models # TODO, mebbe add locks for async usage. def _read_json(filename): with open(filename) as file: return json.load(file) def _dump_json(filename, da...
StarcoderdataPython
1972500
<gh_stars>10-100 import unittest import types from reverso_api.context import * # TODO: refactor class TestReversoContextAPI(unittest.TestCase): """TestCase for ReversoContextAPI Includes tests for: -- .get_examples() -- .get_translations() """ api = ReversoContextAPI(source_text="Github",...
StarcoderdataPython
382345
from concurrent.futures import ThreadPoolExecutor import time import requests def fetch(a,const): url = 'http://httpbin.org/get?a={0}'.format(a) r = requests.get(url) result = r.json()['args'] return (result,const) start = time.time() # if max_workers is None or not given, it will default to the num...
StarcoderdataPython
387833
from indice_pollution.extensions import db from importlib import import_module from indice_pollution.extensions import cache class Zone(db.Model): __table_args__ = {"schema": "indice_schema"} id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String) code = db.Column(db.String) libt...
StarcoderdataPython
8147483
<filename>econtent.py # MIT License # Copyright (c) 2016-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, c...
StarcoderdataPython
5025538
import os from django.conf import settings from django.contrib.staticfiles.finders import BaseFinder, AppDirectoriesFinder from django.contrib.staticfiles.storage import AppStaticStorage from django.core.files.storage import FileSystemStorage from django.utils._os import safe_join class AppMediaStorage(AppStaticStor...
StarcoderdataPython
4950764
<reponame>broaddeep/gdparser from setuptools import find_packages, setup with open("README.md", "r") as fh: long_description = fh.read() package_name = 'gdparser' version = '0.0.2' description = "Google Docstring Parser" url = "https://github.com/broaddeep/gdparser.git" setup( name=package_name, ve...
StarcoderdataPython
11212753
# 1910. <NAME>: сокрытый вход # solved sections_num = int(input()) sections_list = input().split(' ') max_power_sum = 0 max_power_mid_num = 0 mid_num = 0 for i in range(len(sections_list) - 2): power_sum = 0 for j in range(3): power_sum = power_sum + int(sections_list[i+j]) if j == 1: ...
StarcoderdataPython
8118991
<filename>deluca/lung/utils/__init__.py<gh_stars>1-10 from deluca.lung.utils.core import BreathWaveform from deluca.lung.utils.data.analyzer import Analyzer from deluca.lung.utils.data.munger import Munger # from deluca.lung.utils.data.featurizer import Featurizer # from deluca.lung.utils.data.featurizer import Scaling...
StarcoderdataPython
3274466
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. from ..remote_objects import RemoteObject class MockRemoteObject(RemoteObject): def __init__(self): self._propertie...
StarcoderdataPython
3370398
<gh_stars>0 from lib.imports.default import * import lib.settings.templates.parse_cursor as parse_cursor def call(**kwargs): manager = Manager() db = manager.db('webplatform') cursor = db.settings_templates.find() output = [template for template in cursor] return [parse_cursor.call(template) for templ...
StarcoderdataPython
4902862
from ipaddress import IPv4Address from django.conf import settings from django.core.exceptions import SuspiciousOperation from sfdo_template_helpers.addresses import get_remote_ip class AdminRestrictMiddleware: """ A middleware that restricts all access to the admin prefix to allowed IPs. """ def _...
StarcoderdataPython
4931754
import matplotlib.pyplot as plt in_path = "../res/terminal_freq.csv" with open(in_path) as f: data = f.read() data = [int(i) for i in data.split(",")] labels = [chr(i+97) for i in range(26)] ticks = range(26) plt.bar(ticks, data, align="center") plt.xticks(ticks, labels) plt.title("Terminal frequ...
StarcoderdataPython
3287770
<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import math import statistics from scipy import stats infilename = "RTK_DATA.txt" outfilename = "new_plot_data.txt" lines_seen = set() # holds lines already seen outfile = open(outfilename, "w") for line in open(infilename, "r"): if line not in lines...
StarcoderdataPython
9722678
""" Build the various language SDK packages for release """ import argparse import glob import os import platform import shutil from os.path import join, abspath, dirname from typing import Dict try: import requests except ImportError: os.system('pip install requests') import requests def parse_version_tag()...
StarcoderdataPython
3430904
from setuptools import setup, find_packages setup( name="neuraleduseg", version="1.0.0", description="Discourse segmentation", license="Apache License 2.0", url="https://github.com/rknaebel/NeuralEDUSeg", packages=find_packages(), author="<NAME>", author_email="<EMAIL>", classifiers...
StarcoderdataPython
4952641
<filename>account/forms.py from django import forms from django.core.exceptions import ValidationError import re from django.contrib.auth import authenticate, login class ChangePasswordForm(forms.Form): old_password = forms.CharField(max_length=64, widget=forms.PasswordInput()) password = forms.CharField(max_...
StarcoderdataPython
3212645
# -*- coding: utf-8 -*- """mnistfashionclassification.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1bkbxEu12u2eqexsnO4lROJFJMvFSZslu """ import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt...
StarcoderdataPython
5093870
# # This is an extremely simple demo application to showcase the # basic structure, features and use of cvui. # # Copyright (c) 2018 <NAME> <<EMAIL>> # Licensed under the MIT license. # import numpy as np import cv2 import cvui WINDOW_NAME = 'CVUI Hello World!' def main(): frame = np.zeros((200, 500, 3), np.uint8) ...
StarcoderdataPython
8188003
<filename>hityper/typeobject.py import re from hityper.stdtypes import stdtypes, exporttypemap, inputtypemap, typeequalmap from hityper import logger logger.name = __name__ class TypeObject(object): def __init__(self, t, category, added = False): self.type = t #categories: 0 - builtins #1...
StarcoderdataPython
6513402
import pytest from steputils.strings import step_encoder, step_decoder, StringDecodingError, StringBuffer, EOF def test_buffer(): b = StringBuffer('test') assert b.look() == 't' assert b.look(1) == 'e' assert b.get() == 't' assert b.look() == 'e' assert b.get() == 'e' assert b.get() == 's...
StarcoderdataPython
11371002
<reponame>cheperuiz/unlearn-python from dataclasses import dataclass, field from typing import List @dataclass class Ingredient: name: str = field() @dataclass class SliceableIngredient(Ingredient): slice_into: List[str] = field(default_factory=list, repr=False) def __init__(self, name, slice_into, *ar...
StarcoderdataPython
6667970
SECS_PER_MIN = 60 SECS_PER_HOUR = SECS_PER_MIN * 60 SECS_PER_DAY = SECS_PER_HOUR * 24 def secs_to_str(secs): days = int(secs) // SECS_PER_DAY secs -= days * SECS_PER_DAY hours = int(secs) // SECS_PER_HOUR secs -= hours * SECS_PER_HOUR mins = int(secs) // SECS_PER_MIN secs -= mins * SE...
StarcoderdataPython
322797
# imports import author_rank as ar import json # read in sample json with open("../data/author_network.json", 'r') as f: data = json.load(f) # create an AuthorRank object ar_graph = ar.Graph() # fit to the data ar_graph.fit( documents=data["documents"] ) # get the top authors for a set of documents top = a...
StarcoderdataPython
6642005
<filename>chainercb/policies/linear_thompson.py<gh_stars>1-10 from math import factorial from chainer import cuda, functions as F, as_variable from chainercb.policies.linear import LinearPolicy from chainercb.util import select_items_per_row class ThompsonPolicy(LinearPolicy): """ A strictly linear policy th...
StarcoderdataPython
1816219
from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.views.generic import TemplateView, CreateView from .forms import SignUpForm from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib import messages # Create yo...
StarcoderdataPython
4863157
# created by <NAME> # hide or show a widget def hide_widget(wid, dohide=True): if hasattr(wid, 'saved_attrs'): if not dohide: wid.height, wid.size_hint_y, wid.opacity, wid.disabled = wid.saved_attrs del wid.saved_attrs elif dohide: wid.saved_attrs = wid.height, wid.size_...
StarcoderdataPython
6435633
<reponame>Nic30/hwtHdlParsers class RedefinitionErr(Exception): pass class NonRedefDict(dict): def __setitem__(self, key, val): if key in self and val is not self[key]: raise RedefinitionErr(key) dict.__setitem__(self, key, val)
StarcoderdataPython
3586844
## This script requires root import docker import click import tempfile client = docker.from_env() def export_flatduck(image_name): tempfile.TemporaryDirectory(suffix="flatduck") image = client.images.pull('image_name') f = open('/tmp/busybox-latest.tar', 'wb') for chunk in image: f.write(ch...
StarcoderdataPython
3578637
<reponame>smelehy/wifi-scan WIFI_SCAN_CMD = 'sudo iwlist %(nwinterface)s scan' WIFI_CARD_NAME = 'wlan0' # wifi scan parameters # These rules dictate what and how information is pulled out of the iwscan results (which returns raw text) # STR_RULES is a dictionary of lists. each list has an embedded dictionary with ...
StarcoderdataPython
8150253
import torch import numpy as np from typing import Tuple, Union from torchvision import transforms as T def to_3dim(X: torch.Tensor, target_size: Tuple[int, int, int], dtype=torch.float32) -> torch.Tensor: """ Rearragne data matrix X of size (n_styles*dim_x, n_contents) to (n_styles, n_contents, dim_x) ...
StarcoderdataPython
11283347
import sys from data_storing.assets.common import Timespan import fundamentals.miscellaneous as fund_utils from utilities.common_methods import getDebugInfo from utilities.common_methods import Methods as methods from utilities import log def get_return_on_assets(equity, year): """ @fn get_return_on_assets ...
StarcoderdataPython
3319746
# Copyright (c) 2018, salesforce.com, inc. # All rights reserved. # Licensed under the BSD 3-Clause license. # For full license text, see the LICENSE file in the repo root # or https://opensource.org/licenses/BSD-3-Clause import torch from torch.autograd import Variable import matchbox from matchbox import functional ...
StarcoderdataPython
6695932
<gh_stars>0 # Copyright 2013 Violin Memory, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
StarcoderdataPython
3504036
<filename>buffer_and_clip_to_basins.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 25 10:49:37 2018 @author: charlie Hopefully a GRASS script to clip mosaiced DEM to study basins PLUS A 5 KM BUFFER ON EVERY SIDE so that local relief is appropriately calculated. """ import sys import os #imp...
StarcoderdataPython
1790639
<filename>lxserv/replay_fileSaveAs.py # python import lx, modo, replay from replay import message as message """A simple example of a blessed MODO command using the commander module. https://github.com/adamohern/commander for details""" class CommandClass(replay.commander.CommanderClass): """Saves the current Ma...
StarcoderdataPython
1888998
<filename>scripts/common/css/parse.py<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- from urllib2 import urlopen from codecs import EncodedFile import css, csslex, cssyacc from uri import uri __all__ = ('parse','export') def parse(data): parser = cssyacc.yacc() parser.lexer = csslex.lex() re...
StarcoderdataPython
228596
<reponame>ysc3839/vcmp-python-test # pylint: disable=missing-docstring from typing import Tuple from _vcmp import functions as func Vector = Tuple[float, float, float] Quaternion = Tuple[float, float, float, float] class Object: def __init__(self, object_id): self._id = object_id # Read-write prope...
StarcoderdataPython
1913431
<filename>files/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone import markupfield.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateMo...
StarcoderdataPython
5171400
<filename>topicnet/cooking_machine/recipes/exploratory_search_pipeline.py from .recipe_wrapper import BaseRecipe from .. import Dataset modality_selection_template = ( 'PerplexityScore{modality}' ' < 1.01 * MINIMUM(PerplexityScore{modality}) and SparsityPhiScore{modality} -> max' ) general_selection_template =...
StarcoderdataPython
9682492
import sys # import libraries import sqlite3 import pandas as pd from sqlalchemy import create_engine import nltk #nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger']) import pickle import warnings import re import numpy as np import pandas as pd from nltk.tokenize import word_tokenize from nltk.stem impor...
StarcoderdataPython
11342096
<filename>pynumdiff/optimize/__init__.py from pynumdiff.optimize.__optimize__ import docstring as docstring from pynumdiff.optimize import finite_difference as finite_difference from pynumdiff.optimize import smooth_finite_difference as smooth_finite_difference from pynumdiff.optimize import total_variation_regulariza...
StarcoderdataPython
1714901
from enum import Enum class Dot1xControlledDirectionEnum(str, Enum): DCD_BOTH = "DCD_BOTH" DCD_IN = "DCD_IN"
StarcoderdataPython
3448602
<reponame>HLasse/wav2vec_finetune import numpy as np import math sig = np.arange(0, 20) sampling_rate = 1 frame_length = 5 frame_stride = 2 zero_padding = True def stack_frames( sig, sampling_rate, frame_length, frame_stride, filter=lambda x: np.ones( (x, ...
StarcoderdataPython
205119
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 25 21:11:45 2017 @author: hubert """ import numpy as np import matplotlib.pyplot as plt class LiveBarGraph(object): """ """ def __init__(self, band_names=['delta', 'theta', 'alpha', 'beta'], ch_names=['TP9', 'AF7', 'A...
StarcoderdataPython
3430251
<gh_stars>0 # -*- coding: utf-8 -*- """ Helper utilities for the blog application. :author: <NAME> :date: 2/18/2019 """ # # Functions # def font_color_helper(background_color, light_color=None, dark_color=None): """Helper function to determine which font color to use""" light_color = light_color if light_...
StarcoderdataPython