text
string
size
int64
token_count
int64
#!/usr/bin/env python """ site configuration for larch: init_files: list of larch files run (in order) on startup module_path: list of directories to search for larch code history_file: """ from __future__ import print_function import sys import os from os.path import exists, abspath, join from .utils impor...
4,510
1,527
#!/usr/bin/env python # -*- coding: utf-8 -*- ############## # GPathFinder: Identification of ligand pathways by a multi-objective # genetic algorithm # # https://github.com/insilichem/gpathfinder # # Copyright 2019 José-Emilio Sánchez Aparicio, Giuseppe Sciortino, # Daniel Villadrich Herrmannsdoerfer, Pablo Orenes C...
2,898
866
from django.conf.urls import url, include from .views import (GroupListAPIView, GroupCreateAPIView, AgendaListAPIView, AgendaDetailAPIView, AgendaCreateAPIView, AgendaPostAPIView, agenda_create, ...
1,666
564
from django.contrib import admin # Register your models here. #models에서 Shop을 임폴트 from .models import Shop from .models import Parsed_data from .models import Img_data from .models import Other admin.site.register(Shop) admin.site.register(Parsed_data) admin.site.register(Img_data) admin.site.register(Other)
312
107
import torch from models.gta import GraphTemporalEmbedding if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') x = torch.randn(32, 96, 122) model = GraphTemporalEmbedding(122, 96, 3) y = model(x) print(y.size()) # model = AdaGraphSage(num_nodes=10, s...
630
271
class Auth(): def __init__(self, client): self.client = client def get_profiles(self): return self.client.get('/auth/api/profiles/', {'page_size': 10000})['results'] def get_groups(self): return self.client.get('/auth/api/groups/') def get_group_map(self): return {gro...
638
211
''' Auteur : Joël Dendaletche But : tracé une figure géométrique à l'aide de la bibliothèque Turtle Le projet utilise l'objet file pour itérer le calcul de chaque nouveau point Les coordonnées des points d'un polygone sont placés dans une file l'algorithme consiste à calcule...
954
293
# -*- coding:utf-8 -*- # author: Xinge # @file: spconv_unet.py # @time: 2020/06/22 15:01 import time import numpy as np import spconv import torch import torch.nn.functional as F from torch import nn def conv3x3(in_planes, out_planes, stride=1, indice_key=None): return spconv.SubMConv3d(in_planes, out_planes, ker...
20,420
8,014
from .model import DummyModel, ImageNetModel
45
13
import numpy as np from prml.dimreduction.pca import PCA class BayesianPCA(PCA): def fit(self, X, iter_max=100, initial="random"): """ empirical bayes estimation of pca parameters Parameters ---------- X : (sample_size, n_features) ndarray input data i...
2,330
849
# Authors : Alexandre Gramfort, alexandre.gramfort@telecom-paristech.fr (2011) # Denis A. Engemann <denis.engemann@gmail.com> # License : BSD 3-clause import numpy as np from ..parallel import parallel_func from ..io.pick import _pick_data_channels from ..utils import logger, verbose, _time_mask from ..fixe...
11,492
3,834
from zope.interface import implementer from sqlalchemy import ( Column, String, Integer, Float, ForeignKey, CheckConstraint, ) from sqlalchemy.orm import relationship, backref from clld import interfaces from clld.db.meta import Base, CustomModelMixin from clld.db.versioned import Versioned fro...
5,690
1,735
import torch import torch.nn as nn class MLP(nn.Module): def __init__(self, num_features, hidden_sizes, dropout): super().__init__() self.layers = nn.ModuleList( [nn.Linear(num_features, hidden_sizes[0])] + [nn.Linear(hidden_sizes[i], hidden_sizes[i + 1]) for i in range(len(...
600
211
""" Twisted adapter for Kanone """ from twisted.python.failure import Failure from twisted.internet import defer from ..lib import Invalid from ..util import varargs2kwargs import logging, sys log = logging.getLogger( __name__ ) # hacky and redundant, but it'll do for now .. # TODO: move to proper twisted specific c...
27,662
7,359
#! /usr/bin/env python2 # # This file is part of khmer, http://github.com/ged-lab/khmer/, and is # Copyright (C) Michigan State University, 2009-2013. It is licensed under # the three-clause BSD license; see doc/LICENSE.txt. # Contact: khmer-project@idyll.org # import khmer import sys import screed import os.path from ...
1,579
626
""" Fetches demand statistics. Modified from Dan Zhao Original article: https://yaledailynews.com/blog/2020/01/10/yales-most-popular-courses/ Github: https://github.com/iamdanzhao/yale-popular-classes README: https://github.com/iamdanzhao/yale-popular-classes/blob/master/data-guide/course_data_guide.md """ import ...
3,187
997
from flask import Flask from flask_sqlalchemy import SQLAlchemy from qxf2_scheduler import models from qxf2_scheduler import db from qxf2_scheduler.__init__ import app from flask_script import Manager from flask_migrate import Migrate,MigrateCommand migrate=Migrate(app, db,render_as_batch=True) manager=Manager(app) m...
406
136
# import packages import requests import pandas as pd import time from functions import * # limit per sity max_results_per_city = 100 # db of city city_set = ['New+York','Toronto','Las+Vegas'] # job roles job_set = ['business+analyst','data+scientist'] # file num file = 1 # from where to skip SKIPPER = 0 # lo...
3,476
1,032
# Import Libraries import numpy as np import cv2 import argparse import time # Import User Libraries import L0_helpers # Image File Path image_r = "images/flowers.jpg" image_w = "out_serial.png" # L0 minimization parameters kappa = 2.0 _lambda = 2e-2 # Verbose output verbose = False def L0_smooth(input_path, outpu...
4,973
2,273
### Interpretable cnn for big five personality traits using audio data ### ### This script downsamples 41000 kz signal into 4000 kz signal ### from __future__ import absolute_import, division, print_function import pathlib import random import csv import numpy as np from scipy.io import wavfile import tensorflow as t...
2,565
924
# # Copyright 2022 The AI Flow Authors # # 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 w...
1,858
578
# Copyright 2020 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, ...
2,127
692
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def newFunc(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn("Call...
588
158
from torchvision.models import resnet18 import torch.nn.functional as F import torch.nn as nn import numpy as np import torch import pdb ############################## # Encoder ############################## class Encoder(nn.Module): def __init__(self, latent_dim): super(Encoder, self).__init__() ...
3,181
944
from oem_framework.models.core import ModelRegistry from oem_framework.plugin import Plugin from oem_framework.storage import ProviderStorage from oem_storage_file.core.base import BaseFileStorage from oem_storage_file.database import DatabaseFileStorage import appdirs import os class ProviderFileStorage(ProviderSto...
3,381
988
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import DEPS CONFIG_CTX = DEPS['gclient'].CONFIG_CTX ChromiumGitURL = DEPS['gclient'].config.ChromiumGitURL @CONFIG_CTX() def v8(c): soln = c.solutions.ad...
1,565
637
from models.instructions.shared import Instruction from models.Other.ambito import Ambito from controllers.three_address_code import ThreeAddressCode from controllers.procedures import Procedures from models.instructions.Expression.expression import DATA_TYPE, PrimitiveData class Parametro(Instruction): def __ini...
7,038
1,928
import typing import urllib.error import urllib.request from podcast.files import download_location from podcast.info import build_info_content from podcast.info import InfoContent from podcast.models import Channel from podcast.models import get_podcast_audio_link from podcast.models import NewStatus from podcast.mod...
2,386
667
from tests.base import TestCase, main, assets from ocrd_models.ocrd_page import ( AlternativeImageType, PcGtsType, PageType, TextRegionType, TextLineType, WordType, GlyphType, parseString, parse, to_xml ) simple_page = """\ <PcGts xmlns="http://schema.primaresearch.org/PAGE/gt...
5,630
2,140
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- """ Created on Wed Aug 13 15:35:50 2014 @author: rich """ import networkx as nx # assign component IDs to graph components, id=0 is giant component def componentIDs(network): # networkx algo only works on undirected network if isinstance(network, nx.DiGraph): ...
643
218
#!/usr/bin/python """composes the config from user definitions.""" import argparse import os import users import users.__config__ import importlib import csv # file indicators IND_DELIM = "_" USER_INDICATOR = "user" + IND_DELIM VLAN_INDICATOR = "vlan" + IND_DELIM AUTH_PHASE_ONE = "PEAP" AUTH_PHASE_TWO = "MSCHAPV2" c...
9,603
3,145
# Import the Twython class from twython import Twython, TwythonStreamer import json # import pandas as pd import csv import datetime def process_tweet(tweet): # Filter out unwanted data d = {} d['hashtags'] = [hashtag['text'] for hashtag in tweet['entities']['hashtags']] try: for key in { ...
3,673
1,252
#!/usr/bin/env python2 import sys; from yaml import load, dump, load_all from cassandra_attributes import * def main(): attributes = dict() for i in range(1, len(sys.argv)): attributes.update(load(open(sys.argv[i], 'r'))) print dump(dict(filter(lambda (a, b): a in cassandra_attributes, attributes....
389
128
import pytest import itertools # Cartesian product of file names and extensions # e.g. README.txt, README.md, CHANGELOG.txt, CHANGELOG.md ... file_extensions = ['txt', 'md'] names = ['README', 'CHANGELOG', 'CONTRIBUTING', 'LICENSE', 'CODE_OF_CONDUCT'] exempt_files = [('.'.join(x)) for x in itertools.product(names, fil...
526
181
import sys import unittest sys.path.append("../main") from sshtransport import * class FakeSocket(object): def __init__(self): self.recv_buffer = b"" self.send_buffer = b"" def recv(self, n): resp = self.recv_buffer[:n] self.recv_buffer = self.recv_buffer[n:] return r...
1,570
605
import random import time from pathlib import Path from typing import Dict, List, Tuple import numpy as np import torch from torch.utils import data from torch.utils.tensorboard import SummaryWriter import utils_graph import utils_io import utils_nn from feed_forward import FeedForward from hyperparameters import Hyp...
7,357
2,355
input = """ ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in """ def validate(passpor...
868
401
import os.path as osp from unittest import TestCase import pytest from flit_core.common import ( Module, get_info_from_module, InvalidVersion, NoVersionError, check_version, normalize_file_permissions, Metadata ) samples_dir = osp.join(osp.dirname(__file__), 'samples') class ModuleTests(TestCase): def te...
3,322
1,027
import datetime import logging from typing import Optional from betfairlightweight.resources.bettingresources import MarketBook, MarketCatalogue from .blotter import Blotter from ..events import events logger = logging.getLogger(__name__) class Market: def __init__( self, flumine, market...
3,017
903
import pytest from fastapi.testclient import TestClient from {{cookiecutter.project_name}}.app import app @pytest.fixture() def app_client() -> TestClient: client = TestClient(app) return client
206
63
import itertools import multiprocessing import json import numpy as np from tqdm import tqdm from lp_generators.features import coeff_features, solution_features from lp_generators.performance import clp_simplex_performance from search_operators import lp_column_neighbour, lp_row_neighbour from seeds import cli_see...
2,228
647
import unittest from iterable_collections import collect class TestList_(unittest.TestCase): def test_list(self): c = collect(list(range(10))).list_() self.assertEqual(c.iterable, list(list(range(10)))) def test_set(self): c = collect(set(range(10))).list_() self.assertEqual...
1,066
390
from parcels import FieldSet, ParticleSet, ScipyParticle, JITParticle, Variable from parcels import AdvectionRK4, AdvectionEE, AdvectionRK45 from argparse import ArgumentParser import numpy as np import math # NOQA import pytest from datetime import timedelta as delta ptype = {'scipy': ScipyParticle, 'jit': JITParti...
8,354
2,853
from httprunner import HttpRunner import time kwargs = { "failfast":False, #"dot_env_path": "/path/to/.env" } runner = HttpRunner(**kwargs) #入口 runner.run("/Users/wangjianqing/PycharmProjects/HttpRunner-master/tests/testcases/Release/账号管理-设置项.yml") runner.gen_html_report(html_report_name="reportTestForBeta...
456
172
''' Manage sensitivity classification recommendations. ''' from ...... pyaz_utils import _call_az def list(name, resource_group, workspace_name, filter=None, included_disabled=None, skip_token=None): ''' List the recommended sensitivity classifications of a given SQL pool. Required Parameters: - name ...
2,186
560
class Solution: def kthFactor(self, n: int, k: int) -> int: s1 = set() s2 = set() for i in range(1,int(n**0.5)+1): if n%i ==0: s1.add(i) s2.add(int(n/i)) l = list(s1|s2) l.sort() if k > len(l): return -1 ...
333
130
""" Testing array utilities """ import sys import numpy as np from ..arrfuncs import as_native_array, pinv, eigh from numpy.testing import (assert_array_almost_equal, assert_array_equal) from nose.tools import assert_true, assert_false, assert_equal, assert_raises NATIVE_ORDER = '<' if ...
1,755
680
# -*- coding: utf-8 -*- import time import sys import math #HOMEMADE WITHOUT ONLINE CODE by Aris #LIENCE BY ARIS class ProgressBar: def __init__(self,max_size=36): ProgressBar.max_size = max_size ProgressBar.tick = 20.0/max_size ProgressBar.progress_counter = 0.0 ProgressBar.counte...
1,571
495
"""Rail network map """ import os import sys from collections import OrderedDict import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader import matplotlib.pyplot as plt from vtra.utils import * def main(): config = load_config() output_file = os.path.join(config['paths']['figures'], 'rail-map.p...
1,895
659
# Generated by Django 3.1.1 on 2020-09-27 20:02 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( ...
3,189
938
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import numpy as np import os from astropy.tests.helper import raises from astropy.utils.data import get_pkg_data_filename from .. import Pydlspec2dException from ..spec1d import (HMF, findspec, spec_append, spec_path, template_metad...
4,471
1,794
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os from absl import flags import numpy as np import skimage.io as io import cv2 import matplotlib.pyplot as plt # import tensorflow as tf # from psbody.mesh import Mesh from smpl_webuser.seria...
7,800
3,227
#!/usr/bin/python import os os.system("sudo ./scan.py") os.system("sudo ./enable-wifi.py")
92
37
from sklearn.ensemble import RandomForestClassifier import xgboost def suggest_xgb(model_params, trial, xgb=None): n_estimators = trial.suggest_int( model_params.n_estimators.name, model_params.n_estimators.lower, model_params.n_estimators.upper, model_params.n_estimators.step, ...
1,538
534
from keras.optimizers import RMSprop from keras.layers import Input, Embedding, Dense, LSTM, Bidirectional, GRU from keras.layers import concatenate, Reshape, SpatialDropout1D from keras.models import Model from keras import backend as K from .AttentionWeightedAverage import AttentionWeightedAverage def textgenrnn_mo...
4,958
1,499
# Copyright 2015 Internap. # # 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, so...
121,331
42,459
import uuid from authtools import models as authtools_models from django.core.validators import URLValidator from django.db import models from django.utils import timezone from solo.models import SingletonModel class User(authtools_models.AbstractEmailUser): # django-allauth puts Google or EA.org SSO data in tho...
1,384
437
import numpy as np types = ["int", "float", "double"] def randi(*args): return np.random.randint(-10, 10, size=args) rngs = {"int": randi, "float": np.random.randn, "double": np.random.randn} embodiments = { "function": "R.%s(A,B).AllClose(C)", "op": "(A %s B).AllClose(C)", "inline_op": "(R = A, R ...
2,106
798
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # 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 # us...
2,824
951
from enum import Enum from sys import stderr class PlayerMovement(Enum): STOPPED = 0 WALKING = 1 RUNNING = 2 SLIPPED = 3 def to_json_representation(self): return (str(self).split('.')[1]).lower() class MovementNotAllowedError(ValueError): def __init__(self, message): super().__init__(message)
315
116
from django.contrib import admin from .models import Image @admin.register(Image) class ImageAdmin(admin.ModelAdmin): list_display = ('image', 'predict_covid', 'predict_no_findings', 'predict_pneumonia', 'created_at', 'updated_at', 'activated_at')
251
79
#!/usr/bin/env python # coding: utf-8 # In[2]: from time import time import networkx as nx from source.DiGraph import DiGraph from source.model.Edge import Edge def text_to_dict(filename): in_file = open("filename", "r") lines = in_file.read() in_file.close() open_bracket = lines.index("{") ...
1,247
420
''' https://resources.urionlinejudge.com.br/gallery/images/problems/UOJ_1000.png Bem-vindo ao URI Online Judge! O seu primeiro programa em qualquer linguagem de programação normalmente é o "Hello World!". Neste primeiro problema tudo o que você precisa fazer é imprimir esta mensagem na tela. Entrada Este problema nã...
451
153
# Solution of; # Project Euler Problem 668: Square root smooth Numbers # https://projecteuler.net/problem=668 # # A positive integer is called square root smooth if all of its prime factors # are strictly less than its square root. Including the number $1$, there are # $29$ square root smooth numbers not exceeding $...
615
228
from django import forms from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.forms import ValidationError, EmailField from user import models class MyAuthenticationForm(AuthenticationForm): ...
2,927
751
class Node(object): # Similar to Linked List initial set-up def __init__(self, value): # Constructor self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) def print_tree(self, traversal_type): ...
3,476
1,145
import curses import itertools import os from pathlib import Path import stat from typing import Optional, Union import config from colors import Colors class Item: """An item inside of a Directory.""" def __init__(self, path: Union[Path, str]): self._path = Path(path) self._selected = False ...
2,044
580
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. im...
12,647
3,627
#!/usr/bin/env python import sys import os import random import copy import subprocess from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter # PYTHON_DIR="/".join(os.environ['CONDA_EXE'].split("/")[:-2])+'/envs/allennlp_0.8.4/bin/' exit_threshold=0.9 def main(): parser = arg_parser() a...
6,517
2,219
import os import shutil import time def read_all_file(path): output = os.listdir(path) file_list = [] for i in output: if os.path.isdir(path+"/"+i): file_list.extend(read_all_file(path+"/"+i)) elif os.path.isfile(path+"/"+i): file_list.append(path+"/"+i) ...
918
467
"""Actev module: get-system git Actev modules are used to parse actev commands in order to get arguments before calling associated entry point methods to execute systems. Warning: this file should not be modified: see src/entry_points to add your source code. """ from diva_evaluation_cli.bin.commands.actev_command i...
1,897
512
import re textinput = widget_inputs["text1"] comments = [] def commentizer(new): if new not in comments: comments.append(new) is_correct = False result = re.match(".*window.*", textinput, flags=re.IGNORECASE) if result: is_correct = True commentizer("You're right, but there's a little more to it...
902
285
import unittest from html import escape from src.markdown_parser import convert_github_markdown_to_asana_xml class TestConvertGithubMarkdownToAsanaXml(unittest.TestCase): def test_basic_markdown(self): md = """~~strike~~ **bold** _italic_ `code` [link](asana.com)""" xml = convert_github_markdown_...
4,106
1,462
#!/usr/bin/python # Copyright (c) 2018 Cisco and/or its affiliates. # # This file is part of Ansible # # Ansible 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 ...
3,724
1,110
"""Trust ping admin routes.""" from aiohttp import web from aiohttp_apispec import docs from ..connections.models.connection_record import ConnectionRecord from .messages.ping import Ping from ...storage.error import StorageNotFoundError @docs(tags=["trustping"], summary="Send a trust ping to a connection") async d...
1,244
352
import os.path import tcprepl import BigWorld def echo(s): '''Send string to client''' if tcprepl.write_client is not None: tcprepl.write_client(s) def exec_file(filename, exec_globals=None): ''' Execute file Try to find file named `filename` and execute it. If `exec_globals` is spec...
619
204
class QuickenError(Exception): pass
40
12
"""Exception which are not actually thrown, only their docstrings are used.""" import colorama import sys __all__ = [ "Error", "ParentIsNotAFolderError", "InvalidURLError", "ImageFormatNotSupportedError", "ImageNotSpecifiedError", "FolderIconAlreadyExistsError", "DesktopIniError", "exc...
1,861
576
from six import python_2_unicode_compatible from .base import QuickbooksManagedObject, QuickbooksTransactionEntity, Ref, CustomField, MetaData @python_2_unicode_compatible class CompanyCurrency(QuickbooksManagedObject, QuickbooksTransactionEntity): """ QBO definition: Applicable only for those companies that ...
1,224
332
# Generated by Django 3.2 on 2021-04-10 12:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("books", "0003_auto_20210410_1231")] operations = [ migrations.AlterField( model_name="book", name="category", field=mod...
604
183
from itertools import zip_longest import syft from syft.generic.frameworks.hook import hook_args from syft.generic.abstract.tensor import AbstractTensor from syft.workers.abstract import AbstractWorker from syft_proto.execution.v1.placeholder_pb2 import Placeholder as PlaceholderPB class PlaceHolder(AbstractTensor):...
16,575
4,298
""" MAIN STYLING AND RENDERING FILE Requirements: ------------------------------------------------------------------------------ IMPORTANT! This has only been tested with Blender 2.79 API. We have run this on Linux and MacOS. Execution: ------------------------------------------------------------------------------ Th...
21,547
5,875
from foundations_spec import * from unittest.mock import call class TestArtifactDownloader(Spec): mock_archiver = let_mock() make_directory_mock = let_patch_mock('os.makedirs') @let def source_directory(self): return self.faker.uri_path() @let def download_directory(self): ...
5,004
1,510
# pylint: skip-file import unittest import array from collections import namedtuple from itertools import product from functional.pipeline import Sequence, is_iterable, _wrap, extend from functional.transformations import name from functional import seq, pseq Data = namedtuple("Data", "x y") def pandas_is_installed...
34,846
13,134
# -*- coding: utf-8 -*- import os from vilya.models.project import CodeDoubanProject from vilya.models import git from tests.base import TestCase from tests.utils import mkdtemp from vilya.libs import gyt from vilya.libs.permdir import get_repo_root class TestGit(TestCase): @property def u(self): ...
9,412
2,930
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import re import numpy as np from scipy.interpolate import interp2d from scipy.interpolate import interp1d class PredCountsFromQLF_Class(): def __init__(self): self.QLF_OK = False self.EFF_OK = False self.QLF_EFF_OK = False # QLF ...
11,704
5,061
"""Register controllers. """ from safe_control_gym.utils.registration import register register(id="mpc", entry_point="safe_control_gym.controllers.mpc.mpc:MPC", config_entry_point="safe_control_gym.controllers.mpc:mpc.yaml") register(id="linear_mpc", entry_point="safe_control_gym.controlle...
1,135
416
"""Test module ``plot_profile/utils.py``.""" # Standard library import logging # First-party from plot_profile.utils import count_to_log_level def test_count_to_log_level(): assert count_to_log_level(0) == logging.ERROR assert count_to_log_level(1) == logging.WARNING assert count_to_log_level(2) == loggi...
378
127
# _*_ coding: utf-8 _*_ """ util_config.py by xianhu """ __all__ = [ "CONFIG_FETCH_MESSAGE", "CONFIG_PARSE_MESSAGE", "CONFIG_MESSAGE_PATTERN", "CONFIG_URL_LEGAL_PATTERN", "CONFIG_URL_ILLEGAL_PATTERN", ] # define the structure of message, used in Fetcher and Parser CONFIG_FETCH_MESSAGE = "priority...
1,116
539
"""Allows the user to call the library as a cli-module.""" from argparse import ArgumentParser from .modularcmaes import evaluate_bbob parser = ArgumentParser(description="Run single function CMAES") parser.add_argument( "-f", "--fid", type=int, help="bbob function id", required=False, default=5 ) parser.add_ar...
1,087
366
import numpy as np class DifferentialEvolution: def __init__(self, lb, ub, mutation_prob=0.5, pop_size=10, max_generations=100, de_type='rand/1/bin', callback=None): self.lb = np.asarray(lb).reshape(1, -1) self.ub = np.asarray(ub).reshape(1, -1) self.population_size = pop_size self...
7,303
2,424
"""Define the CSRmatrix class.""" import numpy as np from scipy.sparse import coo_matrix from six import iteritems from openmdao.matrices.coo_matrix import COOMatrix class CSRMatrix(COOMatrix): """ Sparse matrix in Compressed Row Storage format. """ def _build(self, num_rows, num_cols): """...
2,122
613
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import re import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() with open("src/sdfconf/_version.py", "rt") as vf: VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" for line in vf: mo = re.search...
2,398
676
from aws_cdk import ( aws_cognito as cognito, aws_iam as iam, aws_ssm as ssm, core ) class CognitoStack(core.Stack): def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) prj_name = self.node.try_get_context("project_name") ...
2,453
704
from typing import Dict, List from cloudrail.knowledge.context.aws.iam.policy import S3Policy from cloudrail.knowledge.context.aws.iam.policy_statement import StatementEffect from cloudrail.knowledge.context.aws.s3.s3_bucket import S3Bucket from cloudrail.knowledge.context.aws.ec2.vpc import Vpc from cloudrail.knowled...
3,570
1,131
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
2,034
583
#!/usr/bin/python3 import argparse import os import sys import re import shutil import tempfile import pwd import grp import tarfile import time import glob import urllib.request from subprocess import Popen, PIPE import aur import pacman local_source_dir = '/makepkg/local_src' build_dir = os.path.abspath('/makepkg/b...
36,937
10,365
"""Test methods for testing the schemagen package (specifically, the SchemaGenerator class). Typical usage example: python -m unittest or, to run a single test: python -m unittest -k test__build_schema """ import unittest import pathlib import logging import copy import os import pandas as pd import numpy a...
12,680
4,237
# Generated by Django 2.2.1 on 2019-05-28 22:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0007_auto_20190523_1740'), ] operations = [ migrations.RenameField( model_name='snippet', old_name='post_content', ...
368
138
import os.path as osp import sys import subprocess subprocess.call(['pip', 'install', 'cvbase']) import cvbase as cvb import torch from torch.autograd import gradcheck sys.path.append(osp.abspath(osp.join(__file__, '../../'))) from biupdownsample import biupsample_naive, BiupsampleNaive from biupdownsample import bid...
2,740
1,145