text
string
size
int64
token_count
int64
import numpy as np from scipy.special import factorial from itertools import permutations, product from pysat.solvers import Minisat22, Minicard from pysat.pb import PBEnc from clauses import build_clauses, build_max_min_clauses from clauses import build_permutation_clauses from clauses import build_cardinality_lits,...
11,203
3,915
# TODO: autmatate finding best agents
38
11
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
2,653
752
import time import unittest from Data.parameters import Data from SI.MAP.check_infrascore_with_download_functionality import SchoolInfra_scores from SI.MAP.check_sc_map_clusterwise_records import test_school_map_schoollevel_records from SI.MAP.click_on_anydistrict_and_download_csv import download_icon from SI.MAP.clic...
7,901
2,483
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 3 15:24:46 2020 @author: hamishgibbs """ import pandas as pd import re import numpy as np #%% ox = pd.read_csv('https://raw.githubusercontent.com/OxCGRT/covid-policy-tracker/master/data/OxCGRT_latest_withnotes.csv') #%% ox = ox[0:100] #%% ox.fil...
4,217
1,374
# -*- coding: utf-8 -*- """Decorator guaranteeing uniform function calls.""" from inspect import Parameter, signature def extract_uniform_args_kwargs(f, *args, ignore=None, **kwargs): """Extract uniform arguments given a function and the parameters it is called with. Args: f (callable): Function bein...
2,082
630
#!/usr/bin/env python3 """ Implements a TF Model class by inheriting the Model base class. @author: David Curry @version: 1.0 """ from base.base_model import BaseModel import tensorflow as tf class MnistModel(BaseModel): def __init__(self, config): """ Constructor to initialize the TF model clas...
2,862
945
import pygame as pg from settings import * import pytmx class Map: def __init__(self, filename): self.data = [] with open(filename, 'rt') as f: for line in f: self.data.append(line.strip()) self.tilewidth = len(self.data[0]) self.tileheight...
2,388
776
try: import pathlib except ImportError as e: try: import pathlib2 as pathlib except ImportError: raise e def name_to_asserted_group_path(name): path = pathlib.PurePosixPath(name) if path.is_absolute(): raise NotImplementedError( "Absolute paths are currently not...
768
229
#!/usr/bin/env python # # import modules used here -- sys is a very standard one from __future__ import print_function import argparse import csv import logging import zipfile from collections import OrderedDict from glob import glob import os import sys import nibabel as nb import json import pandas as pd import num...
15,292
4,925
def bubblesort(L): keepgoing = True while keepgoing: keepgoing = False for i in range(len(L)-1): if L[i]>L[i+1]: L[i], L[i+1] = L[i+1], L[i] keepgoing = True
226
84
class threshold: def threshold(num, threshold): if ( threshold < 0 ) || ( threshold >= 1 ) error('threshold input must be in the range [0,1]'); end fractional = num - floor( num ); idx1 = fractional > threshold; idx2 = fractional <= threshold; difference = 1 - frac...
431
127
from .base import * import os import dj_database_url ALLOWED_HOSTS = ['*'] DEBUG = False MIDDLEWARE += [ 'whitenoise.middleware.WhiteNoiseMiddleware' ] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', ] + INSTALLED_APPS DATABASES = { 'default': dj_database_url.config() } EMAIL_USE_TLS = True EM...
514
214
import os import sys """ Notes: - It's great that you've used functions even though we haven't reached that part of the course. Also, the naming of the function is clear and a good variable name. - Typically, the docstring for the function starts immediately after the triple quote otherwise we introduce a newline (...
1,175
335
""" >>> G = Graph(6) >>> G.insert(0, 1, 3) >>> G.insert(0, 2, 7) >>> G.insert(0, 4, 8) >>> G.insert(0, 5, 1) >>> G.insert(1, 2, 2) >>> G.insert(1, 4, 13) >>> G.insert(2, 3, 15) >>> G.insert(3, 5, 17) >>> G.insert(4, 5, 9) >>> G.dijkstra(0)[0] [0, 3, 5, 20, 8, 1] >>> G...
2,313
778
# Example of faking classes with a closure import sys class ClosureInstance: def __init__(self, locals=None): if locals is None: locals = sys._getframe(1).f_locals # Update instance dictionary with callables self.__dict__.update((key,value) for key, value in locals.items() ...
854
278
# Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ U{array<http://docs.python.org/library/array.html>} adapter module. Will convert all array.array instances to a python list before encoding. All type information is lost (but degrades nicely). @since: 0.5 """ from __future__ import absolute_impor...
434
146
from .scheme_factory import SchemeFactory from .schemes import schemes _default_scheme_id = 'default' def get_scheme(scheme_id=None): """Возвращает схему по scheme_id. Args: scheme_id: Строка, уникальное имя схемы. Returns: Scheme или None, если схемы с scheme_id не существует. ""...
929
342
''' Utilities useful for datasets ''' import os from functools import partial from urllib.request import urlretrieve import requests from tqdm import tqdm from torch.utils.data.dataloader import DataLoader from torch.utils.data.sampler import BatchSampler, RandomSampler, SequentialSampler from data.sampler import Se...
4,425
1,304
import json import os import sys from astropy_changelog import loads from github import Github event_name = os.environ['GITHUB_EVENT_NAME'] if event_name not in ('pull_request_target', 'pull_request'): print(f'No-op for {event_name}') sys.exit(0) event_jsonfile = os.environ['GITHUB_EVENT_PATH'] with open(ev...
3,092
1,021
#!/usr/bin/python3 # -*- coding: utf-8 -*- ##===-----------------------------------------------------------------------------*- Python -*-===## ## ## S E R I A L B O X ## ## This file is distributed under terms of BSD license. ## See LICENSE.txt for more information. ## ##===-...
4,037
1,382
from dataclasses import dataclass from datetime import datetime, timedelta import json import os.path from dateutil.parser import parse import pytz import redis from redis.lock import LockError import requests from . import settings from .logger import logger UNCACHED_HEADERS = ( 'Age', 'Cache-Control', ...
6,793
2,075
''' File: discretizer.py Description: function definition History: Date Programmer SAR# - Description ---------- ---------- ---------------------------- Author: w. x. chan 29Apr2016 - Created ''' import numpy as np from . import pinm as pinm from stl import mesh from mpl_toolkits import mplot3d...
25,609
7,690
from urllib.parse import parse_qs, urlencode, urlparse from .. import settings def normalize(request, url: str) -> str: parts = urlparse(url) url = f"{settings.BASE_URL}{parts.path}" if "background" in parts.query: background = parse_qs(parts.query)["background"][0] else: background =...
881
307
''' Function(s) for the postanalysis toolkit ''' import logging log = logging.getLogger(__name__) from . import _reweight from ._reweight import (stats_process, reweight_for_c) from .matrix import FluxMatrix
211
68
# Hydro settings TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' APPLICATION_NAME = 'HYDRO' SECRET_KEY = '8lu*6g0lg)9w!ba+a$edk)xx)x%rxgb$i1&amp;022shmi1jcgihb*' # SESSION_TIMEOUT is used in validate_session_active decorator to see if the # session is active. SECOND = 1 MINUTE = SECOND * 60 SECONDS_IN_DAY = SECOND*86400 ...
1,573
641
from ...forms.checks import check_is_logged from django.shortcuts import redirect def no_login_required(view_function): def exec_view_function(*args, **kwargs): request = args[0] if check_is_logged(request): return redirect('/') return view_function(*args, **kwargs) ...
357
105
# Copyright 2020 DeepMind Technologies 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed t...
12,000
4,108
from collections import defaultdict from pathlib import Path from typing import Dict, Iterable, List, Optional, Tuple, Union import networkx as nx import onnx from . import graph_ir as g from .onnx_attr import get_node_shape, node_attr_to_dict, node_to_shape PathLike = Union[str, Path] GraphT = onnx.GraphProto NodeT...
13,476
4,348
import csv import json import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': formats = ['png', 'pdf', 'svg', 'eps'] metrics = [ {'gmetric': 'groc', 'lmetric': 'lroc', 'metric': 'AUC'}, {'gmetric': 'gauc', 'lmetric': 'lauc', 'metric': 'PRAUC'}, ] datasets = [ ...
4,435
1,615
def array_left_rotation(a, n, k): return a[k:] + a[0:k] n, k = map(int, raw_input().strip().split(' ')) a = map(int, raw_input().strip().split(' ')) answer = array_left_rotation(a, n, k); print ' '.join(map(str,answer))
226
96
#!/usr/bin/env python """Using unsat cores to give hints.""" from SudokuLib import Puzzle from Solver import Solver from yices.Yices import Yices from yices.Census import Census puzzle_blank = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0], # [ 0, 0...
4,127
2,810
import os import flask import mwoauth import yaml from flask import request, Response app = flask.Flask(__name__) # Load configuration from YAML file __dir__ = os.path.dirname(__file__) app.config.update( yaml.safe_load(open(os.path.join(__dir__, 'config.yaml')))) if __name__ == '__main__': app.run_server(...
2,715
866
def load_external_repo(): native.local_repository( name = "ext_repo", path = "test/external_repo/repo", )
130
42
# Copyright (c) 2020 StackHPC 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 in wr...
1,817
562
#!/usr/bin/env python from flask import Flask, request,Response import logging import os import json import cognitoHelper as cog #logging config logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',level=logging.INFO,datefmt='%Y-%m-%d %H:%M:%S') logger = logging.getLogger(__name__) #globals MODULE = "...
3,864
1,265
from abc import ABC, abstractmethod from typing import Set, Type, Optional from hallo.events import ( EventSecond, EventMinute, EventHour, EventDay, EventPing, EventMessage, EventJoin, EventLeave, EventQuit, EventNameChange, EventKick, EventInvite, EventNotice, E...
4,204
1,160
#!/usr/bin/env python3 # Copyright (c) 2019 Arm Limited and Contributors. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """This script checks for checker for unwanted TCP/UDP open ports.""" import os import json import logging from enum import Enum import mbl.open_ports_checker.connection as connect...
4,332
1,134
# Copyright (C) Huangying Zhan 2019. All rights reserved. import argparse from kitti_odometry import KittiEvalOdom parser = argparse.ArgumentParser(description='KITTI evaluation') parser.add_argument('--result', type=str, required=True, help="Result directory") parser.add_argument('--align', type...
1,036
331
import pygame import random import os import time import neat import visualize import pickle import bcolors as b pygame.font.init() SCORE_MAX = [0, 0, 0] WIN_WIDTH = 600 WIN_HEIGHT = 800 FLOOR = 730 STAT_FONT = pygame.font.SysFont("comicsans", 50) END_FONT = pygame.font.SysFont("comicsans", 70) DRAW_LINES = False WI...
9,115
3,450
#original from https://github.com/csinva/hierarchical-dnn-interpretations/blob/master/acd/scores/cd.py import torch import torch.nn.functional as F from copy import deepcopy from torch import sigmoid from torch import tanh import numpy as np stabilizing_constant = 10e-20 def propagate_three(a, b, c, activation): ...
34,273
12,600
# coding: utf8 from __future__ import unicode_literals STOP_WORDS = set( """ à às área acerca ademais adeus agora ainda algo algumas alguns ali além ambas ambos antes ao aos apenas apoia apoio apontar após aquela aquelas aquele aqueles aqui aquilo as assim através atrás até aí baixo bastante bem boa bom breve c...
2,554
845
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'miaschiev.ui' # # Created: Wed Aug 06 17:13:17 2014 # by: pyside-uic 0.2.15 running on PySide 1.2.1 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Miaschiev(object): ...
13,906
4,793
import os import pytest from assertpy import assert_that from ..models.granule import Granule from ..models.granule_count import GranuleCount from ..models.status import Status from ..session import _get_url, get_session, get_session_maker @pytest.mark.usefixtures("db_connection_secret") def test_that_db_correctly_...
1,673
580
import numpy as np import pytest from arbol import aprint from dexp.processing.utils.normalise import Normalise from dexp.utils.backends import Backend from dexp.utils.testing.testing import execute_both_backends @execute_both_backends @pytest.mark.parametrize( "dexp_nuclei_background_data", [dict(length_xy=...
1,478
523
__version__ = '0.0.1' from . import utils from .utils import *
64
26
import socket def get_ip(): # https://stackoverflow.com/a/28950776/9471339 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 1)) IP = s.getsockname()[0] except Exception: IP = '127.0.0.1' final...
427
181
from ..utils import AnalysisException from .expressions import Expression class Literal(Expression): def __init__(self, value): super().__init__() self.value = value def eval(self, row, schema): return self.value def __str__(self): if self.value is True: retur...
844
233
# -*- coding: utf-8 -*- """ Created on Wed Oct 8 14:45:02 2014. @author: mje """ import mne import sys from mne.io import Raw from mne.preprocessing import ICA, create_eog_epochs, create_ecg_epochs import matplotlib matplotlib.use('Agg') from my_settings import * subject = sys.argv[1] # SETTINGS n_jobs = 1 l_fr...
3,812
1,430
""" PRIVATE MODULE: do not import (from) it directly. This module contains types that are not available by default. """ import typing from inspect import Parameter T = typing.TypeVar('T') KT = typing.TypeVar('KT') VT = typing.TypeVar('VT') Empty = Parameter.empty Unknown = type('Unknown', (Empty, ), {}) Module = typ...
428
143
from .utils import * from scipy.spatial.distance import pdist import scipy.cluster.hierarchy as hierarchicalcluster def rank_environment_and_phenotypes(environment, phenotypes, k=15): """ Clusters sets of resources/tasks using a weighted hamming distance such that you can have few enough values to give ea...
11,172
3,169
''' Created on May 26, 2012 @author: Charlie ''' class MainModule01(object): def __init__(self): pass
119
45
""" Example: Shows how to create and use an image dataset. """ import urllib3 import feersum_nlu from feersum_nlu.rest import ApiException from examples import feersumnlu_host, feersum_nlu_auth_token # from feersum_nlu_util import image_utils # Configure API key authorization: APIKeyHeader configuration ...
2,109
664
# -*- coding: utf-8 -*- import atexit import os import signal import time from flask_restful import Api from actinia_core.testsuite import ActiniaTestCaseBase, URL_PREFIX from actinia_core.core.common.config import global_config from actinia_core.core.common.app import flask_app, flask_api from actinia_statistic_plugin...
2,536
867
""" Byterund 的基本测试""" import vmtest class It(vmtest.VmTestCase): def test1(self): self.assert_ok("""\ class Thing(object): @staticmethod def smeth(x): print(x) @classmethod def cmeth(cls, x): ...
5,560
1,853
# -*- coding: utf-8 -*- from importlib import import_module def get_annotations_compiler_flag() -> int: future = import_module("__future__") assert future is not None annotations = getattr(future, "annotations") assert annotations is not None compiler_flag = getattr(annotations, "compiler_flag") ...
387
115
import os import warnings import xarray as xr import numpy as np # forget about using dask for now, dask_ndmeasure takes a huge amount of memory # try: # # raise ImportError # # import dask_ndmeasure as ndimage # # register a progressbar so we can see progress of dask'ed operations with xarray # from dask.diagnostics...
10,503
3,387
from ann import * x, y = utils.get_mnist_samples(100) m = Model(x[0].shape) m.add(Conv2D()) m.add(MaxPooling()) m.add(Flatten()) m.add(Dense(15)) m.add(Dense(10, a_func='sigmoid'))
181
94
#! /usr/bin/env python3 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import argparse import hashlib import json import os import subprocess import sys parser = argp...
1,923
694
#!/usr/bin/env python3 # Copyright 2013-2015 The Meson development team # 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...
8,310
2,656
import fileimp # divide rows 0-127 # F = lower half # B = upper half # divide columns 0-7 # R = upper half # L = lower half # seat ID = row * 8 + col # list of IDs # max list def idcalc(list): seats = [] for i in list: row = '' col = '' for j in i: if j == 'F': ...
1,085
376
#!/usr/bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Copyright (c) 2012 Michael Hull. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are m...
3,618
1,182
import os import sys # import common package in parent directory sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common')) import mongodb_client import news_topic_modeling_service_client if __name__ == '__main__': db = mongodb_client.get_db() cursor = db['news'].find({}) count = 0 for ...
766
218
from http.server import BaseHTTPRequestHandler,HTTPServer from socketserver import ThreadingMixIn import threading import subprocess import urllib.parse # todo: factor out common server stuff # todo: these should probably have limited # access to files, so something like only # uploads dir may be good. # then there i...
2,559
758
# # PySNMP MIB module GENERIC-3COM-VLAN-MIB-1-0-7 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GENERIC-3COM-VLAN-MIB-1-0-7 # Produced by pysmi-0.3.4 at Wed May 1 11:09:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python versio...
26,692
9,279
from tastypie.authentication import SessionAuthentication class UberAuthentication(SessionAuthentication): """ Handles authentication for the course resources. """ def is_authenticated(self, request, **kwargs): if request.method == 'GET': return True else: return...
388
91
from .layer_send import AxolotlSendLayer from .layer_control import AxolotlControlLayer from .layer_receive import AxolotlReceivelayer
135
42
from django.db import models from django.urls import reverse from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator from core import utils from core.models import User from contacts.models import Contact class Acti...
3,199
953
from functools import reduce print(reduce(lambda x, y: x * (y**5), list(map(int, input().split())), 1))
104
39
from yaw_controller import YawController from pid import PID GAS_DENSITY = 2.858 ONE_MPH = 0.44704 class Controller(object): def __init__(self, wheel_base, steer_ratio,max_lat_accel,max_steer_angle, accel_limit,decel_limit): self.yaw = YawController(wheel_base, steer_ratio, 0., max_lat_accel, m...
1,176
535
import numpy as np golden = np.array([ [100.0, 100.0], [206.226840616, 179.610387213], [1190.25124092, 1197.15702025], [1250.76639667, 1250.3933971], [1261.76760093, 1250.17718583], [1237.4846285, 1237.56490579], [1273.56730356, 1266.82141705], [1272.899992, 1259.92589118], [1.17000308922e-06, ...
627
571
""" User configuration file for the client. """ SERVER_ADDRESS = "127.0.0.1" SERVER_PORT = 50000
98
43
from selenium.common.exceptions import WebDriverException, NoSuchElementException from Element.Waitor import Waitor from Element.Find import Find from Utilitys.WaitUtils import WaitUtils class Element(Find): def __init__(self, driver): Find.__init__(self) self.driver = driver self.interva...
3,479
935
''' production setting ''' # include all base settings from .base import * # pylint: disable=W0401,W0614 # include credentials (not included in repo) from . import credentials as crd # pylint: disable=W0401,W0611 # disable debugging DEBUG = False # ======================== # SECRET_KEY # https://d...
2,047
688
from solution import str_range def test_same_start_end(): r = str_range('a', 'a') assert iter(r) == r assert ''.join(list(r)) == 'a' def test_simple(): r = str_range('a', 'c') assert ''.join(list(r)) == 'abc' def test_simple_with_step(): r = str_range('a', 'c', 2) assert ''.join(list(r...
636
270
''' Copyright (C) 2018 Intel Corporation ? 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...
8,227
2,897
#MenuTitle: Find And Replace In Anchor Names # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals from builtins import str __doc__=""" Replaces strings in anchor names of all selected glyphs. """ import vanilla class SearchAndReplaceInAnchorNames( object ): def __init__( self ):...
3,811
1,393
import sys import math if __name__ == '__main__': a = int(sys.argv[1]) b = int(sys.argv[2]) c = int(sys.argv[3]) d = b * b - 4 * a * c x1 = (-b + math.sqrt(d)) / (2 * a) x2 = (-b - math.sqrt(d)) / (2 * a) print(int(x1)) print(int(x2))
269
128
import numpy as np from fishspot.filter import white_tophat from fishspot.detect import detect_spots_log def blob_detection( image, min_blob_radius, max_blob_radius, **kwargs, ): """ """ wth = white_tophat(image, max_blob_radius) spots = detect_spots_log( wth, min_blob...
2,258
862
#!/usr/bin/python # Copyright 2018 GRAIL, 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 agr...
8,736
2,713
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-06-29 17:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djasana', '0006_adds_defaults'), ] operations = [ migrations.AlterField( ...
450
159
''' x Total plays x Total artists x Total unique songs Average song per artist x Favourite track Favourite artist (by plays or time) Favourite album (req. api) Average/total/unique plays per range Average/total/unique artists per range Average/total time listened per range Favourite genre (req. api) (by p...
6,375
1,945
from django.conf import settings from django.contrib.auth.decorators import login_required from django.urls import path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions from rest_framework.authentication import SessionAuthentication schema_view_param = { ...
861
261
#!/usr/bin/python """ Author: Mohamed K. Eid (mohamedkeid@gmail.com) Description: trains a generative model for stylizing an unseen image input with a particular style Args: train: path to image with style to learn """ import argparse import os import tensorflow as tf import generator import he...
1,889
697
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import glob import os import pygame import random import subprocess import time import maze_map MIN_MARGIN = 32 PROGRESS_BAR_HEIGHT = 8 SELF_DIR = os.path.dirname(os.path.realpath(__file__)) class Game: def __init__(self, map_size: int, maze: bool...
9,512
2,930
from flask import Flask, render_template, flash,request,redirect,url_for from flask_sqlalchemy import SQLAlchemy from flaskmodel.config import * from flask_wtf import FlaskForm from wtforms import StringField,SubmitField from wtforms.validators import DataRequired app = Flask(__name__) # 创建数据库连接 db = SQLAlchemy(app) ...
5,342
2,377
import asyncio import json from hypercorn.asyncio import serve from hypercorn.config import Config from bareasgi import Application, text_reader, text_writer import bareutils.header as header async def get_info(scope, info, matches, content): accept = header.find(b'accept', scope['headers']) if accept != b'a...
1,012
340
from .mem_bank import RGBMem, CMCMem from .mem_moco import RGBMoCo, CMCMoCo def build_mem(opt, n_data): if opt.mem == 'bank': mem_func = RGBMem if opt.modal == 'RGB' else CMCMem memory = mem_func(opt.feat_dim, n_data, opt.nce_k, opt.nce_t, opt.nce_m) elif opt.mem == '...
567
218
# -*- coding:utf-8 -*- from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # from celery_once import QueueOnce # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Aves2.settin...
803
260
from typing import Union, List, Optional, Tuple, Set from hwt.hdl.operator import Operator from hwt.hdl.operatorDefs import AllOps from hwt.hdl.portItem import HdlPortItem from hwt.hdl.statements.assignmentContainer import HdlAssignmentContainer from hwt.hdl.statements.codeBlockContainer import HdlStmCodeBlockContaine...
14,374
4,503
from dataclasses import dataclass from functools import partial from typing import Dict, List, Optional from urllib.parse import urljoin from pyvultr.utils import BaseDataclass, VultrPagination, get_only_value, merge_args from .base import BaseVultrV2, command from .enums import LoadBalanceAlgorithm, LoadBalanceProto...
12,009
3,485
#!/usr/bin/env python2 # Author: Alamot import json import time import uuid import fcntl import base64 import urllib import random import requests from pwn import * def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), ...
12,848
5,570
import io import unittest from unittest.mock import patch from kattis import k_apaxiaaans ############################################################################### class SampleInput(unittest.TestCase): '''Problem statement sample inputs and outputs''' def test_sample_input_1(self): '''Run and a...
1,735
502
""" We give you an Array of friend's list. Write a function called greeting_for_all_friends that takes one argument, friends. This method takes an array of friends name and return a greeting messages Array. Message sample: for the friend "Bilal" we get "Hello, Bilal!" Rules: If the argument is null, the method sho...
829
247
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import unittest from collections import Counter import numpy as np import torch from pytorchvideo.data.utils import thwc_to_cthw from pytorchvideo.transforms import ( ApplyTransformToKey, Normalize, OpSampler, RandomShortSideScale...
11,469
3,972
""" # !/usr/bin/env python # -*- coding: utf-8 -*- @Time : 2022/2/24 20:12 @Author : shengdl999links@gmail.com @ProjectName : udacity-program_self_driving_car_engineer_v1.0_source.0 @File : full_pipeline.py """ import numpy as np import cv2 import os import matplotlib.image as mpimg import matplotli...
20,905
7,393
import pyblaze.nn.data.extensions from .noise import NoiseDataset, LabeledNoiseDataset from .zip import ZipDataLoader from .transform import TransformDataset
158
47
import requests import os import random from dotenv import load_dotenv import sys def get_response(url, payload): try: response = requests.get(url, params=payload) response.raise_for_status() except requests.HTTPError: sys.stderr.write("Error with URL\n") return response def get...
3,128
1,080
# -*- coding: utf-8 -*- # Copyright 2013 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 require...
9,636
2,821
import rospy import sys from gazebo_msgs.srv import * from geometry_msgs.msg import * import tf.transformations as tft import numpy as np import math import roslib from std_msgs.msg import Empty as EmptyMsg from std_msgs.msg import Float64 from nav_msgs.msg import Odometry import time from tool.mecanum_utils import * ...
18,526
6,692