text
string
size
int64
token_count
int64
# Authors: Davide Zoni from m5.params import * from m5.proxy import * from BasicRouter import BasicRouter class GarnetRouter_PNET_Container_d(BasicRouter): type = 'GarnetRouter_PNET_Container_d' cxx_class = 'Router_PNET_Container_d' cxx_header = "mem/ruby/network/garnet/fixed-pipeline/Router_PNET_Containe...
1,158
372
import os location = os.path.join(os.path.dirname(__file__), 'Functions\\') #location = 'Tests\\' execfile(location + 'getVersion.py') execfile(location + 'writeSBML.py') #execfile(location + 'computeSteadyStateValues.py') execfile(location + 'evalModel.py') #execfile(location + 'getAvailableSymbols.py') ...
4,699
1,630
""" Models for Conditions app """ from django.db import models from common.models import OwnedModel class Condition(OwnedModel): """ Condition model """ name = models.CharField(unique=True, max_length=255, db_index=True) description = models.TextField() def __str__(self): return f'Condition:...
334
102
from curriculum.utils import set_env_no_gpu, format_experiment_prefix set_env_no_gpu() import argparse import math import os import os.path as osp import sys import random from multiprocessing import cpu_count import numpy as np import tensorflow as tf from rllab.misc.instrument import run_experiment_lite from rllab...
11,214
3,510
def decode_lines(lines_bytes, encoding: str): if isinstance(lines_bytes[0], bytes): lines_str = [line.decode(encoding) for line in lines_bytes] elif isinstance(lines_bytes[0], str): lines_str = lines_bytes else: raise TypeError(type(lines_bytes[0])) return lines_str
307
95
# Fitness monday variables morning_1 = "10:00" morning_2 = "8:00" afternoon_1 = "13:00" afternoon_2 = "14:30" afternoon_3 = "15:30" afternoon_4 = "17:55" evening_1 = "20:30" evening_2 = "21:10" date_announce = [1, 2, 3, 4, 5] image_file_list = [ 'Exercise_Three.png', 'Exercise_Two_2.png' ] ...
2,176
831
#!/usr/bin/env python # coding: utf-8 # # Author: Kazuto Nakashima # URL: https://kazuto1011.github.io # Date: 07 January 2019 from __future__ import absolute_import, division, print_function import click import cv2 import matplotlib import matplotlib.cm as cm import matplotlib.pyplot as plt import...
6,559
2,427
import setuptools import md_tangle with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name=md_tangle.__title__, version=md_tangle.__version__, license=md_tangle.__license__, author=md_tangle.__author__, author_email=md_tangle.__author_email__, description="Ge...
1,131
346
import torch import torch.nn as nn import torch.nn.functional as F from .bayes_layers import VariationalLinearCertainActivations, VariationalLinearReLU from .variables import GaussianVar class MLP(nn.Module): def __init__(self, x_dim, y_dim, hidden_size=None): super(MLP, self).__init__() self.siz...
3,658
1,259
from datetime import date from django.db import models # Create your models here. class Gemeente(models.Model): naam_text = models.CharField(max_length=50) deelgemeente_text = models.CharField(max_length=50) class Segment(models.Model): gemeente = models.CharField(max_length=55) straat = models.CharF...
917
302
#!/usr/bin/env python """Simple test client to call the debugger SOAP service""" import os import sys import base64 import getpass from suds.client import Client from suds.cache import NoCache from suds import WebFault, MethodNotFound from clfpy import AuthClient auth_endpoint = 'https://api.hetcomp.org/authManager...
1,757
551
#!/usr/bin/python3 # from time import time # from math import sqrt # with open("inp.txt", "r") as f: # a, b = list(i for i in f.read().split()) a, b = input().split() # print(a,b,c, type(a), type(int(a))) a = int(a) b = int(b) # st = time() # ----- s1 = a * (a - 1) // 2 cuoi = b - 2 dau = b - a s2 = (dau + cuoi) *...
393
191
# import tcs # import daqctrl, inspect # ------------------------------------------------------------------ # install the script by: # cd $INTROOT/config/scripts # ln -s $guiInstalDir/ctaOperatorGUI/ctaGuiBack/ctaGuiBack/acs/guiACS_schedBlocks_script0.py # ----------------------------------------------------------...
6,295
1,967
""" Module to scan for empty folders and directories """ from time import time from msort.check import BaseCheck, CheckSkip class AgeCheck(BaseCheck): """ A simple checker which will validate a file or folders age. """ def __call__(self, section, path): if self.conf.getboolean('minimum_age', '...
576
169
n = int(input()) a = input().split() a = [str(m) for m in a] for i in a: if i == "Y": print("Four") exit() print("Three")
143
59
#!/usr/bin/env python3 # Copyright 2019 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """PackageManager provides an interface to the JSON FPM API. The PackageManager interface provides a simple way to retrieve data from t...
5,141
1,391
""" Solve 2021 Day 1: Sonar Sweep Problem """ def solver_problem1(inputs): """ Count the number of increasement from given list """ num_increased = 0 for i in range(1, len(inputs)): if inputs[i] > inputs[i - 1]: num_increased += 1 return num_increased def solver_problem2(...
977
380
from smooth.components.component_power_converter import PowerConverter import oemof.solph as solph def test_init(): power_converter = PowerConverter({}) params = {"efficiency": 0, "output_power_max": 100} power_converter = PowerConverter(params) assert power_converter.efficiency == params["efficiency"...
928
309
from demos.setup import np, plt from compecon import BasisChebyshev, BasisSpline from compecon.tools import nodeunif __author__ = 'Randall' # DEMAPP06 Chebychev and cubic spline derivative approximation errors # Function to be approximated def f(x): g = np.zeros((3, x.size)) g[0], g[1], g[2] = np.exp(-x),...
2,094
781
import random import gym import numpy as np from collections import deque from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import Adam import tensorflow as tf import os import logging os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' logging.getLogger('tensorflow').disabled = Tr...
5,411
1,836
from .core import ACSDataset import collections __all__ = ["PerCapitaIncome"] class PerCapitaIncome(ACSDataset): """ PER CAPITA INCOME IN THE PAST 12 MONTHS (IN 2018 INFLATION-ADJUSTED DOLLARS) """ AGGREGATION = None UNIVERSE = "total population" TABLE_NAME = "B19301" RAW_FIELDS = coll...
370
155
""" Card games exercise """ def get_rounds(number): """ :param number: int - current round number. :return: list - current round and the two that follow. """ return [i + number for i in range(3)] def concatenate_rounds(rounds_1, rounds_2): """ :param rounds_1: list - first rounds...
1,642
566
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import SavepointCase class TestStockQuantityHistoryLocation(SavepointCase): @classmethod def setUpClass(cls): super(TestStockQuantityHistoryLocation, cls).setUpClass() cls.su...
3,109
986
# -*- coding:utf-8 -*- states = ("B","M","E","S") test_input = "BBMESBMEBEBESSMEBBME" observations = [obs for obs in test_input] #์‹œ์ž‘ํ™•๋ฅ  start_prob = {"B":0.4,"M":0.2,"E":0.2,"S":0.2} #์ „์ดํ™•๋ฅ  transit_prob = {"B": {"B": 0.1, "M": 0.4, "E": 0.4, "S": 0.1}, "M": {"B": 0.1, "M": 0.4, "E": 0.4, "S": 0.1}, ...
1,463
727
""" Path to CNS-related files. Most paths are defined by dictionaries that gather several related paths. Here, instead of defining the dictionaries with static paths, we have functions that create those dict-containing paths dynamically. The default values are defined by: - axis - tensors - translation_vectors - wate...
2,534
879
""" Provides helper routines for reanalysis DBNs study. """ # License: MIT from __future__ import absolute_import from .computation import (calc_truncated_svd, downsample_data, meridional_mean, pattern_correlation, select_lat_band, select...
3,185
984
from output.models.ms_data.regex.re_k14_xsd.re_k14 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
121
58
#!/usr/bin/python2.7 # Copyright 2012 Google 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 # # Unless requi...
2,364
712
from pyeventbus import * from timeit import default_timer as timer import numpy import sys from os import getcwd import json class Events: class IOHeavyTestEvent: start = 0 finish = 0 duration = 0 def __init__(self): pass def setStart(self, time): sel...
10,237
3,147
# Generated by Django 4.0 on 2021-12-15 09:04 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('book', '0005_alter_book_rented_count'), ] operations = [ migrations.AlterField( model_name='book', ...
511
168
hrs = input("Enter Hours:") rate=2.75 print ("Pay: " + str(float(rate) * hrs))
79
36
from __future__ import absolute_import from __future__ import division from __future__ import print_function import _thread import sys import time from math import exp from random import random from typing import List, Tuple, Set from scipy import spatial import numpy as np import torch from torch import nn from torc...
34,005
12,099
import discord import time import random import datetime import asyncio import json import config from discord.ext import commands from data.data_handler import data_handler from itertools import chain from collections import OrderedDict def gainedRP(player, gained_rp): if player['Level']['timeOfNextEarn'] > time...
25,395
7,306
#!BPY """ Name: 'Follow Active (quads)' Blender: 242 Group: 'UVCalculation' Tooltip: 'Follow from active quads.' """ __author__ = "Campbell Barton" __url__ = ("blender", "blenderartists.org") __version__ = "1.0 2006/02/07" __bpydoc__ = """\ This script sets the UV mapping and image of selected faces from adjacent unse...
7,985
3,354
# Copyright 2020 Thomas Rogers # SPDX-License-Identifier: Apache-2.0 LOWER_LINK_TAG = 6 UPPER_LINK_TAG = 7 UPPER_WATER_TAG = 9 LOWER_WATER_TAG = 10 UPPER_STACK_TAG = 11 LOWER_STACK_TAG = 12 UPPER_GOO_TAG = 13 LOWER_GOO_TAG = 14 LOWER_LINK_TYPES = {LOWER_LINK_TAG, LOWER_WATER_TAG, LOWER_STACK_TAG, LOWER_GOO_TAG} UP...
1,196
659
from .common import * # NOQA import requests AUTH_PROVIDER = os.environ.get('RANCHER_AUTH_PROVIDER', "") ''' Prerequisite: Enable SBX without TLS, and using testuser1 as admin user. Description: In this test, we are testing the customized user and group search filter functionalities. 1) For customized user search...
6,107
2,062
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
7,738
2,194
# Copyright 2021 Huawei Technologies Co., Ltd # # 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...
1,551
489
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os def get_package_data(): paths_test = [os.path.join('data', '*.out')] return {'pyradex.tests': paths_test}
189
71
# Author: Milan Kubik, 2017 """Backend entry point manipulation""" import logging from pkg_resources import iter_entry_points RESOURCE_GROUP = "ipaqe_provision_hosts.backends" log = logging.getLogger(__name__) def load_backends(exclude=()): """Load all registered modules""" log.debug("Loading entry points...
566
188
from .exceptions import ( # noqa: F401 MissingCFPAttributes, MissingEnvironmentVariable, )
100
34
import urllib.request import os import subprocess import pandas as pd from tqdm import tqdm import sys sys.path.append("probefilter") sys.path.append("probefilter/libsvm-3.23/python") from sitesfinder.imads import iMADS from sitesfinder.imadsmodel import iMADSModel from sitesfinder.plotcombiner import PlotCombiner fr...
8,309
3,125
def pattern(n): res="" for i in range(n,0,-1): for j in range(i): res+=str(n-j) res+="\n" return res[:-1]
145
58
import dagos.platform.platform_utils as platform_utils from .command_runner import CommandRunner from .command_runner import ContainerCommandRunner from .command_runner import LocalCommandRunner from .platform_domain import CommandNotAvailableIssue from .platform_domain import OperatingSystem from .platform_domain impo...
633
142
"""Finds Guids that do not have referents or that point to referents that no longer exist. E.g. a node was created and given a guid but an error caused the node to get deleted, leaving behind a guid that points to nothing. """ import sys from modularodm import Q from framework.guid.model import Guid from website.app ...
1,593
484
""" This script is for testing/calling in several different ways functions from QRColorChecker modules. @author: Eduard Cespedes Borrร s @mail: eduard@iot-partners.com """ import unittest import hashlib import dateutil from chalicelib.server import Server import sys import json from datetime import datetime sys.pat...
13,836
5,169
#!/usr/bin/env python import os import json import unittest from collections import OrderedDict from spdown.config import Config TEST_CONFIG_PATHS = OrderedDict([ ('local', 'config.json'), ('home', os.path.join( os.path.expanduser('~'), '.config', 'spdown', 'config' )) ]) TEST_CONFIG = { ...
3,497
1,006
from emulation._emulate.microphysics import TimeMask from emulation.config import ( EmulationConfig, ModelConfig, StorageConfig, _load_nml, _get_timestep, _get_storage_hook, get_hooks, ) import emulation.zhao_carr import datetime def test_EmulationConfig_from_dict(): seconds = 60 m...
2,167
735
from typing import List # O(n^2) def insertion_sort(arr: List[int], desc: bool = False) -> None: for i, item in enumerate(arr): if i == 0: continue j: int = i - 1 while j >= 0 and (arr[j] > item) ^ desc: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = it...
323
120
from datetime import datetime from urllib.parse import urlsplit, parse_qs from dateutil.tz import tzutc import pystac import pytest from pystac_client import Client from pystac_client.conformance import ConformanceClasses from .helpers import STAC_URLS, TEST_DATA, read_data_file class TestAPI: @pytest.mark.vcr...
8,939
2,761
from setuptools import ( find_packages, setup, ) setup( name="text2qrcode", version="1.0-a1", description="Render a QR code image from input text", author="Matt Patey", packages=find_packages(), install_requires=["qrcode", "pillow"], entry_points={ "console_scripts": [ ...
378
136
import numpy as np import random from proyecto2.image import Image class TestImage: def test_pixels(self): for _ in range(5): x = random.randrange(1920, 4368, 1) y = random.randrange(1080, 2912, 1) matrix = np.random.rand(y, x) image = Image(matrix) ...
363
127
from os import path import numpy as np import pytest import autofit as af import autolens as al from autolens.mock import mock pytestmark = pytest.mark.filterwarnings( "ignore:Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of " "`arr[seq]`. In...
2,236
782
formats = {"KiB": 1024, "KB": 1000, "MiB": 1024**2, "MB": 1000**2, "GiB": 1024**3, "GB": 1000**3, "TiB": 1024**4, "TB": 1000**4} # Converts shorthand into number of bytes, ex. 1KiB = 1024 def shortToBytes(short): if short is not None: try: for format, multiplie...
1,737
636
# The UI interface and analysis of the lofar solar beam from import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '..') from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon from PyQt5.uic import loadUi from PyQt5.QtCore import Qt import matplotlib from matplotlib.backends.backend_...
12,023
4,201
""" """ __all__ = ["export_notebook", "grade_submission"] import os import sys import shutil import tempfile from contextlib import redirect_stdout try: from contextlib import nullcontext except ImportError: from .utils import nullcontext # nullcontext is new in Python 3.7 from .argparser import get_parser...
2,169
634
from .pressureprofile import PressureProfile import numpy as np class ArrayPressureProfile(PressureProfile): def __init__(self, array, reverse=False): super().__init__(self.__class__.__name__, array.shape[-1]) if reverse: self.pressure_profile = array[::-1] else: ...
930
280
#!/usr/bin/env python # This script is based on the example at: https://raw.githubusercontent.com/nf-core/test-datasets/viralrecon/samplesheet/samplesheet_test_illumina_amplicon.csv import os import sys import errno import argparse def parse_args(args=None): Description = "Reformat nf-core/vcreport samplesheet ...
2,857
872
from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import random lol = pd.read_csv('./data/sample_SilverKDA.csv') lol.drop(['Unna...
2,093
1,045
from datadog import initialize, api options = { 'api_key': '16ff05c7af6ed4652a20f5a8d0c609ce', 'app_key': 'e6a169b9b337355eef90002878fbf9a565e9ee77' } initialize(**options) title = "Mymetric timeboard" description = "Mymetric Timeboard" graphs = [ { "definition": { "events": [], ...
1,300
464
#! /usr/bin/env python3 from subprocess import call r = call(["python3", "-m", "korali.rlview", "--help"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--test"]) if r!=0: exit(r) r = call(["python3", "-m", "korali.rlview", "--dir", "abf2d_vracer1", "--maxObservations", ...
1,104
548
def generated_file_staleness_test(name, outs, generated_pattern): """Tests that checked-in file(s) match the contents of generated file(s). The resulting test will verify that all output files exist and have the correct contents. If the test fails, it can be invoked with --fix to bring the checked-in...
1,643
500
from assets.lambdas.transform_findings.index import TransformFindings import boto3 from moto import mock_s3 def __make_bucket(bucket_name: str): bucket = boto3.resource('s3').Bucket(bucket_name) bucket.create() return bucket @mock_s3 def test_fix_dictionary(): bucket = __make_bucket('tester') tr...
4,894
1,796
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-01-10 16:35 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 = [ ('Breeze', '0005_forgetpass'...
1,431
431
# -*- coding: utf-8 -*- ################################################################################ # | # # | ______________________________________________________________ # # | :~8a.`~888a:::::::::::::::88......88:::::::::...
25,414
8,036
import io import os import click import frappe from frappe.website.page_renderers.base_template_page import BaseTemplatePage from frappe.website.router import get_base_template, get_page_info from frappe.website.utils import ( cache_html, extract_comment_tag, extract_title, get_frontmatter, get_next_link, get_s...
9,670
3,820
# Copyright 2015 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # # 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 # # Unl...
17,013
5,501
"""Package list handling""" load(":private/set.bzl", "set") def pkg_info_to_ghc_args(pkg_info): """ Takes the package info collected by `ghc_info()` and returns the actual list of command line arguments that should be passed to GHC. """ args = [ # In compile.bzl, we pass this just before a...
3,286
990
import subprocess def clone(url: str, target_directory: str) -> None: print(f'Cloning {url} into {target_directory} ...') subprocess.run( ['git', 'clone', url, target_directory], capture_output=True )
223
72
#!/usr/bin/python3 """ =============================================================================== โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ• โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ• โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ...
2,220
873
"""EESG.py Created by Latha Sethuraman, Katherine Dykes. Copyright (c) NREL. All rights reserved. Electromagnetic design based on conventional magnetic circuit laws Structural design based on McDonald's thesis """ from openmdao.api import Group, Problem, Component,ExecComp,IndepVarComp,ScipyOptimizer,pyOptSparse...
39,191
19,405
# Copyright 2020 DeepMind Technologies Limited. 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 # # Unless required by ...
2,879
978
#!/usr/bin/env python """A more advanced Reducer, using Python iterators and generators.""" from itertools import groupby from operator import itemgetter import sys def read_mapper_output(file, separator='\t'): for line in file: yield line.rstrip().split(separator, 1) def main(separator='\t'): data...
519
173
from pylps.core import * initialise(max_time=5) create_actions('say(_, _)', 'say_single(_)') create_events('member(_, _)') create_facts('inp(_, _)') create_variables('X', 'Y', 'F', 'Item', 'List', 'Tail') inp([], [[]]) inp('z', ['a', 'b', 'c', 'd', 'e']) inp('a', ['b', 'c', 'a']) inp(['b', 'c'], ['d', ['a', 'c']]) i...
486
225
import copy import logging import os from typing import Dict, List, Tuple import checksumdir import imageio import numpy as np import torch from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from ..adapter import download_object logger = logging.getLogger("fastface.dataset") class _IdentitiyTra...
6,663
2,197
from typing import Optional from typing import Tuple import attr @attr.s(auto_attribs=True) class SlotAttentionParams: lr: float = 0.0004 batch_size: int = 64 val_batch_size: int = 64 resolution: Tuple[int, int] = (128, 128) num_slots: int = 7 # 5 change to 7 according to official code num_i...
1,565
556
import pygame import math coef_turn = 0.3 coef_drift = 0.07 # adhรฉrence au sol coef_vel = 10 class Car: def __init__(self): self.dir_target = -1 self.dir = -1 self.posx = 0 self.velx = -1 self.w = 50 self.h = 100 def update(self, dt): self.dir += dt * ...
989
394
import pytest import numpy from grunnur import ( cuda_api_id, opencl_api_id, StaticKernel, VirtualSizeError, API, Context, Queue, MultiQueue, Array, MultiArray ) from grunnur.template import DefTemplate from .mock_base import MockKernel, MockDefTemplate, MockDefTemplate from .mock_pycuda import PyCUDADevi...
6,014
2,214
def sortedDict(adict): keys = adict.keys() keys.sort() return map(adict.get, keys) ipint2str = lambda x: '.'.join([str(x/(256**i)%256) for i in range(3,-1,-1)]) ipstr2int = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])]) src_ip = dict() dst_ip = dict() i =0 with open('hash_key_valu...
1,024
415
import os import sys import string def is_active(): return True def get_name(): return "WinRT" def can_build(): if (os.name=="nt"): #building natively on windows! if (os.getenv("VSINSTALLDIR")): return True return False def get_opts(): return [] def get_flags(): return [] def configure(env): ...
8,212
3,777
# Copyright 2015-2017 FUJITSU LIMITED # # 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...
6,934
2,242
import logging class NewLogger: def __init__(self, log_abs_path:str): self.logger = logging.getLogger() handler = logging.FileHandler(log_abs_path) handler.setLevel(logging.ERROR) self.logger.addHandler(handler) def log(self, msg:str): self.logger.log(logging.ERROR, m...
328
106
from bast import Route route = Route() route.get('/', 'HelloController.index')
80
24
from paradrop.base.output import out from paradrop.lib.utils import uci from . import configservice, uciutils def getOSWirelessConfig(update): """ Read settings from networkInterfaces for wireless interfaces. Store wireless configuration settings in osWirelessConfig. """ # old code under lib.inter...
1,626
458
import taichi as ti import numpy as np from functools import reduce # from sph_base import SPHBase # ti.init(arch=ti.cpu) # Use GPU for higher peformance if available ti.init(arch=ti.gpu, device_memory_GB=4, packed=True) # ๅ› ไธบ้‚ปๅฑ…ๆœ็ดข็š„็ฝ‘ๆ ผไธไผšๅš๏ผŒๆ‰€ไปฅๅฐบๅฏธๆ•ฐๆฎๅชๅฅฝไนŸๆฒฟ็”จๅŠฉๆ•™็š„ๅ†™ๆณ• # res = (720,720) res = (512,512) dim = 2 assert...
44,518
24,215
import inspect from fnmatch import fnmatchcase from ..sched import meta from .base import BaseFactory class ModuleFactory(BaseFactory): """ Takes an imported module object and extracts callable objects from it. A valid callable is any object that can be called and has pexen.sched metadata. Argum...
1,129
309
# Beispielprogramm fรผr das Buch "Python Challenge" # # Copyright 2020 by Michael Inden def solve_water_jugs(size1, size2, desired_liters): return __solve_water_jugs_rec(size1, size2, desired_liters, 0, 0, {}) def __solve_water_jugs_rec(size1, size2, desired_liters, ...
2,431
822
import vstruct from vstruct.primitives import * EI_NIDENT = 4 EI_PADLEN = 7 class Elf32(vstruct.VStruct): def __init__(self, bigend=False): vstruct.VStruct.__init__(self) self.e_ident = v_bytes(EI_NIDENT) self.e_class = v_uint8() self.e_data = v_uint8() s...
9,424
3,541
__all__ = ["UserAccount"] _user_root = "identity/users" def _encode_username(username): """This function returns an encoded (sanitised) version of the username. This will ensure that the username is valid (must be between 3 and 50 characters). The sanitised username is the encoded version, meanin...
10,041
2,644
# Copyright (c) 2013 Mirantis Inc. # # 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 writ...
3,337
983
# -*- coding: utf-8 -*- import pytest def test_translator(): def translator(string): translations = {'String value is too long.': 'Tamanho de texto muito grande.'} return translations.get(string, string) from schematics.translator import register_translator register_translator(translator...
584
178
# generate 900k word and 900k query to test the runtime from main import TrieTree import time import random vocal = list(range(26)) trie = TrieTree() words = [[random.choice(vocal) for _ in range(random.randrange(1, 11))] for _ in range(100000)] queries = [[random.choice(vocal) for _ in range(random.randrange(1, 11...
641
243
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openvino.tools.mo.ops.mvn import MVNOnnx from openvino.tools.mo.front.common.partial_infer.utils import int64_array from openvino.tools.mo.front.extractor import FrontExtractorOp from openvino.tools.mo.front.onnx.extractors.utils im...
894
312
""" Module for managing enemies. """ import random import constants as const import pygame import random import platforms from spritesheet_functions import SpriteSheet class Enemy(pygame.sprite.Sprite): # -- Methods def __init__(self, x_cord, y_cord,level, x_speed=2, char_type=0): """ Constructor ...
11,661
3,610
import argparse import inspect import logging import sys from .__main__ import setup_logging log = logging.getLogger() DESCRIPTION = """ hic-internal is used for automation, not intend to be used by end user. Use hicluster instead. """ EPILOG = '' def impute_chromosome_internal_subparser(subparser): parser =...
10,715
3,320
import asyncio import socket import pytest from mock import AsyncMock, MagicMock, patch import aioatomapi.host_resolver as hr from aioatomapi.core import APIConnectionError @pytest.fixture def async_zeroconf(): with patch("zeroconf.asyncio.AsyncZeroconf") as klass: yield klass.return_value @pytest.fix...
5,013
1,890
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
85,241
23,014
class Solution: def XXX(self, root: TreeNode) -> bool: stack = [] cur = root last = float("-inf") while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() if cur.val > last: ...
432
112
import numpy as np import os, cv2 imgs = np.load('test_set_ck_extended_no_resize.npy') lbls = np.load('test_labels_ck_extended_no_resize.npy') for i in range(imgs.shape[0]): print (lbls[i]) cv2.imshow('img', imgs[i]) cv2.waitKey(0)
237
110
from pydantic import BaseModel import typing as t ### SCHEMAS FOR USERS ### class UserBase(BaseModel): alias: str primary_wallet_address_id: t.Optional[int] profile_img_url: t.Optional[str] is_active: bool = True is_superuser: bool = False class UserOut(UserBase): pass class UserCreate(U...
773
265