text
string
size
int64
token_count
int64
""" This is a django-split-settings main file. For more information read this: https://github.com/sobolevn/django-split-settings Default environment is `development`. To change settings file: `DJANGO_ENV=production python manage.py runserver` """ import django_heroku from split_settings.tools import include base_set...
1,138
320
class Solution: def XXX(self, s: str) -> bool: i=0 j = len(s)-1 #lower()把所有大写字母改成小写,其余不变 s = s.lower() while i<j: while not(97 <= ord(s[i]) <= 122 or 48 <= ord(s[i]) <= 57): if i == j: return True i += 1 ...
584
213
from django.conf.urls import patterns, url, include from django.contrib import admin from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import template_test urlpatterns = patterns( '', url(r'^test/', template_test, name='template_test'), url(r...
688
219
from typing import Sequence, Union import numpy as np from scipy.ndimage.interpolation import rotate as np_rotate from PIL.Image import Image from torch import Tensor, tensor from torchvision.transforms.functional import rotate class ImageRotation(object): def __init__(self, degree): self.degree = degree...
1,645
501
# Course: CS261 - Data Structures # Author: Mohamed Al-Hussein # Assignment: 06 # Description: Directed graph implementation. from collections import deque import heapq class DirectedGraph: """ Class to implement directed weighted graph - duplicate edges not allowed - loops not allowed - only pos...
14,355
4,019
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time: 2020/5/14 20:41 # @Author: Mecthew import time import numpy as np import pandas as pd import scipy from sklearn.svm import LinearSVC from sklearn.linear_model import logistic from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import ac...
6,847
2,573
import os import scrapy from scrapy.crawler import CrawlerProcess import requests from disaster_data.sources.noaa_coast.utils import get_geoinfo, get_fgdcinfo class NoaaImageryCollections(scrapy.Spider): name = 'noaa-coast-imagery-collections' start_urls = [ 'https://coast.noaa.gov/htdata/raster2/...
4,754
1,268
import pytest from rlo import factory @pytest.mark.parametrize("use_subtree_match_edges", [True, False]) @pytest.mark.parametrize("loss", ["pinball=0.6", "huber"]) def test_torch_model_from_config(use_subtree_match_edges, loss): # Check we can construct a Model config = { "num_embeddings": 3, ...
2,004
752
# coding=utf-8 # Copyright 2014 Dirk Dittert # # 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 agree...
1,285
380
# Copyright 2019 Jeremiah Sanders. # # 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 wri...
6,432
2,330
""" DATA DESCRIPTION sentiment140 dataset. It contains 1,600,000 tweets extracted using the twitter api . The tweets have been annotated (0 = negative, 4 = positive) and they can be used to detect sentiment . It contains the following 6 fields: target: the polarity of the tweet (0 = negative, 2 = neutral, 4 = positi...
977
365
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from flask import redirect, request, session from werkzeug.except...
1,803
566
from csapp.models import Kruptos from rest_framework import viewsets, permissions from rest_framework.response import Response from rest_framework import status from .serializers import KruptosSerializer class KruptosViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.AllowAny ]...
622
187
from os import path import autolens as al import autolens.plot as aplt from test_autogalaxy.simulators.imaging import instrument_util test_path = path.join("{}".format(path.dirname(path.realpath(__file__))), "..", "..") def pixel_scale_from_instrument(instrument): """ Returns the pixel scale from...
7,612
2,654
from .conftest import GoProCameraTest from socket import timeout from urllib import error class GpControlSetTest(GoProCameraTest): def test_gp_control_set(self): # on success, this is an empty json blob self.responses['/gp/gpControl/setting/foo/bar'] = '{}' assert '{}' == self.goprocam.gp...
687
228
from utils import CanadianScraper, CanadianPerson as Person COUNCIL_PAGE = 'http://www.abbotsford.ca/city_hall/mayor_and_council/city_council.htm' CONTACT_PAGE = 'http://www.abbotsford.ca/contact_us.htm' class AbbotsfordPersonScraper(CanadianScraper): def scrape(self): councillor_seat_number = 1 ...
1,727
594
from anchorecli.cli import repo
32
10
''' nome = input('Insira seu nome: ') if nome == 'Mendes': print('Que nome lindo você tem!') else: print('Seu nome é tão normal!') print('Bom dia {}!'.format(nome)) ''' #DESAFIO_28 ''' from random import randint from time import sleep x = randint(0,5) y = int(input('Digite um número de 0 à 5: ')) print('Loading...
2,692
1,123
#/usr/bin/python import serial import time import matplotlib.pyplot as plt import numpy as np import os """"""""""""""""""""""""""""""""""" """""""NEVS BEER SCRIPT"""""""""""" """"""""""""""""""""""""""""""""""" ###need to add exception handler for serial disconnection ## SETUP SERIAL PORT try: ...
4,902
1,791
from abc import ABC, abstractmethod from domain.errors.failure import Failure from domain.errors.image_failure import ImageFailure from domain.repositories.image_repository_abstraction import ImageRepositoryAbstraction class GetAllGlaucomatousImagesPathsAbstraction(ABC): @abstractmethod def __init__(self, re...
874
242
import pygame import math pygame.init() pi = ('Pi = ' + str(math.pi)) e = ('E = ' + str(math.e)) f = ('F = 0,1,1,2,3,5,8,13...') p = ('P = 1,2,5,12,29...') l = ('L = 2,1,3,4,7,11,18,29...') pl = ('P-L = 2,6,14,34,82...') display = pygame.display.set_mode((800,600)) pygame.display.set_caption('Nums') font = p...
944
492
import io import csv import logging from StringIO import StringIO from datetime import datetime from gzip import GzipFile import boto3 from celery import shared_task from flask import current_app from flask_mail import Attachment from invenio_mail.api import TemplatedMessage logger = logging.getLogger(__name__) def...
5,980
1,814
from system.db import db from telegram_bot.handlers.utils.decorators import remember_new_user, \ send_typing, write_logs from telegram_bot.handlers.utils.menu_entries import MenuEntry from telegram_bot.handlers.utils.reply_markup import create_main_reply_markup from telegram_bot.models import User @write_logs @se...
756
253
# Generated by Django 3.2 on 2022-02-27 11:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_spotless_app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='service', name='picture_url', ...
374
125
# -*- coding: utf-8-*- import os import base64 import tempfile import pypinyin from aip import AipSpeech from . import utils, config, constants from robot import logging from pathlib import Path from pypinyin import lazy_pinyin from pydub import AudioSegment from abc import ABCMeta, abstractmethod from .sdk import Tenc...
8,983
3,330
from channels.db import database_sync_to_async from .exceptions import ClientError from .models import Game @database_sync_to_async def get_game_or_error(game_id, user): if not user.is_authenticated: raise ClientError("USER_HAS_TO_LOGIN") try: game = Game.objects.get(pk=game_id) except Game...
392
126
import os import pytest from ddb.__main__ import load_registered_features from ddb.config import config from ddb.feature import features from ddb.feature.core import CoreFeature from ddb.utils import file from ddb.utils.file import FileWalker, FileUtils class TestHasSameContent: def test_should_return_true_if_s...
2,328
797
# Copyright (C) 2021, Pyronear contributors. # This program is licensed under the GNU Affero General Public License version 3. # See LICENSE or go to <https://www.gnu.org/licenses/agpl-3.0.txt> for full license details. import unittest import tempfile from pathlib import Path import json from PIL.Image import Image i...
9,666
3,388
# -*- coding: utf-8 -*- # # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # # pylint: disable= no-member, arguments-differ, invalid-name # # Utilities for using pre-trained models. import torch from dgl.data.utils import _get_dgl_url, download from .molecule...
26,116
8,041
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import pyrobot.utils.util as prutil from pyrobot.core import Camera from pyrobot.utils.util import try_cv2_import cv2 = tr...
5,608
1,946
import serial ser = serial.Serial('COM7',115200, timeout=1) while True: print("R: ", ser.readline())
105
41
import sys import random import avro.schema from avro.datafile import DataFileWriter from avro.io import DatumWriter NAME_POOL = ['george', 'john', 'paul', 'ringo'] OFFICE_POOL = ['office-%d' % _ for _ in xrange(4)] COLOR_POOL = ['black', 'cyan', 'magenta', 'yellow'] def main(argv): try: schema_fn = arg...
1,009
359
import numpy as np import unittest from chainer.dataset import DatasetMixin from chainer import testing from chainercv.utils import assert_is_bbox_dataset from chainercv.utils import generate_random_bbox class BboxDataset(DatasetMixin): def __init__(self, options=(), empty_bbox=False): self.options = o...
2,604
898
# Copyright (c) 2012-2016 Seafile Ltd. from __future__ import unicode_literals import unicodedata import urlparse import json from functools import wraps from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden class _HTTPException(Exception): def __init__(self, message=''): se...
3,002
897
"""Provide default settgins""" from pathlib import Path BIOPIPEN_DIR = Path(__file__).parent.parent.resolve() REPORT_DIR = BIOPIPEN_DIR / "reports" SCRIPT_DIR = BIOPIPEN_DIR / "scripts"
187
74
from flask_settings import GEOTIFF_FULL_PATH import sys import traceback sys.path.append('../') import numpy as np import json from datetime import timedelta from functools import update_wrapper from pextant.EnvironmentalModel import GDALMesh from pextant.explorers import Astronaut from pextant.analysis.loadWaypoints...
6,172
1,907
#!/usr/bin/python3 import shutil import os import base64 from time import sleep import flask import requests.exceptions import blueprint from flask_cors import CORS from confhttpproxy import ProxyRouter, ProxyRouterException from flask import Flask, jsonify import rest_routes from lmsrvcore.utilities.migrate import...
10,085
3,049
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> # Copyright (C) 2007 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://bitte...
37,112
10,585
import numpy as np import pandas as pd from sklearn.linear_model import Ridge from sklearn.model_selection import cross_val_score, train_test_split from sklearn.model_selection import RepeatedKFold from sklearn.preprocessing import OneHotEncoder import pickle from flask import Flask, request np.random.seed(42...
2,555
956
"""Enrollment event models context fields definitions""" from typing import Literal, Union from ...base import BaseContextField class EdxCourseEnrollmentUpgradeClickedContextField(BaseContextField): """Represents the `context` field of the `edx.course.enrollment.upgrade_clicked` server statement. In ad...
1,088
312
import os import pytest from fontbakery.utils import TEST_FILE from fontbakery.checkrunner import ERROR def test_check_fontvalidator(): """ MS Font Validator checks """ from fontbakery.profiles.fontval import com_google_fonts_check_fontvalidator as check font = TEST_FILE("mada/Mada-Regular.ttf") # we want t...
834
266
from run import app from functools import wraps from flask import render_template,flash,redirect,logging,session,url_for,request from .models.database import user_register, user_login, get_feed, get_user_info, update_feed, change_password #kullanıcı giriş decorator'u. bu yapı tüm decoratorlarda aynı. def lo...
3,662
1,435
import click import logging import sys from typing import Tuple from kubails.commands import helpers from kubails.services.config_store import ConfigStore from kubails.services.service import Service from kubails.resources.templates import SERVICE_TEMPLATES from kubails.utils.command_helpers import log_command_args_fac...
4,671
1,451
from __future__ import absolute_import from hashlib import sha256 import hmac import json import six from sentry import options from sentry.models import ApiToken, ProjectKey from sentry.testutils import TestCase UNSET = object() class BaseWebhookTest(TestCase): def setUp(self): super(BaseWebhookTest, ...
10,703
3,200
from math import exp,sqrt from random import randrange class neurone: def __init__(self,a,b): self.a=a self.b=b def proceed(self,z): t = z[0]*self.a + z[1]*self.b return 1/(1+exp(-t)) n = 100 X_app = [(randrange(-500,501)/1000,randrange(-500,501)/1000) for i in range(n)] Y_app ...
669
332
import json import datetime import mimetypes from urllib.parse import urlparse from arcgis import env from arcgis.gis import GIS from arcgis.gis import Item from ._ref import reference class JournalStoryMap(object): """ Represents a Journal Story Map =============== ===================================...
29,113
6,073
from aoc2015.core import dispatch def test_dispatch_fail(capsys): '''Dispatch fails properly when passed a bad day''' # capsys is a pytest fixture that allows asserts agains stdout/stderr # https://docs.pytest.org/en/stable/capture.html dispatch(['204']) captured = capsys.readouterr() assert '...
703
238
from myoperator import BlockOperator import re class output_DE(BlockOperator): """ Select one line per DE-cluster with the best quality description. Creates cluster_data column 'desc','genename' Inputs: data columns 'clusid','desc','FF','status' cluster_data column 'clu...
2,749
739
import os from StringIO import StringIO from zipfile import ZipFile import subprocess import shutil import fcntl import time import signal import imp import sys,traceback def dir_clean_error(function,path,excinfo): print 'WARNING: Ran into issues trying to remove directory:',path,str(function),str(excinfo) def cle...
6,016
1,986
from __future__ import absolute_import, unicode_literals try: from importlib import reload except ImportError: pass from django.conf.urls import url from django.test import TestCase from mock import patch try: import wagtail.core.urls as wagtail_core_urls except ImportError: # pragma: no cover; fallback...
1,432
479
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2021, Nigel Small # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
1,295
407
class LeapYearFinder(object): def __init__(self): pass def findLeapYear(self, startYear, endYear): leapYearRecord = [] for i in range(int(startYear),int(endYear)): year = i print(year,end = "\t") #If year is divisible by 4...
656
239
# check to strings that represent version numbers and finds the greatest, # 'equals' if they are the same version or 'Invalid Format' # example: “1.2” is greater than “1.1”. # for reusability this function just returns the version number or the word equals # if a more elaborated answer is needed an interface would be...
1,662
426
# This sample tests type narrowing of subject expressions for # match statements. from typing import Literal def func1(subj: int | dict[str, str] | tuple[int] | str, cond: bool): match subj: case (3 | "hi"): t_v1: Literal["Literal[3, 'hi']"] = reveal_type(subj) return cas...
824
279
import sys import os sys.path.append(os.getcwd()) import argparse import numpy as np import pmdarima import torch import torch.nn.functional as F from torch import nn from fusions.common_fusions import Stack from unimodals.common_models import LSTMWithLinear from datasets.stocks.get_data import get_dataloader parser...
1,869
671
# -- Imports ------------------------------------------------------------------ from __future__ import print_function from __future__ import unicode_literals from Foundation import CFPreferencesAppSynchronize, CFPreferencesCopyAppValue from os import getenv # -- Class -----------------------------------------------...
3,329
874
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'leftIMPLIESSIMPLIESleftANDORleftRPARENLPARENrightNEGATIONALPHABET AND IMPLIES LPAREN NEGATION OR PREDICATE RPAREN SIMPLIESexpr : expr AND exprexpr : ALPHABETexpr : expr...
1,916
1,029
'''Please write a program to read the scan and print out The maximum voxel intensity The mean voxel intensity The coordinates of the centre of the image volume, in the scanner coordinate system. ''' import pydicom import numpy as np import matplotlib.pyplot as plt import cv2 import glob import os import image_slicer ...
6,936
2,728
def find_paths(start, connections, visited=None, small_cave_visited_twice=False): if visited is None: visited = ["start"] possible_connections = [e for s, e in connections if s == start] + [s for s, e in connections if e == start] paths = [] if not possible_connections: raise ValueErro...
1,759
527
"""An unofficial Python wrapper for the Binance exchange API v3 .. moduleauthor:: Sam McHardy .. modified by Stephan Avenwedde for Pythonic """
146
43
import os from tests import PMGTestCase from tests.fixtures import dbfixture, CommitteeQuestionData class TestQuestionAnswer(PMGTestCase): def setUp(self): super(TestQuestionAnswer, self).setUp() self.fx = dbfixture.data(CommitteeQuestionData,) self.fx.setup() def tearDown(self): ...
1,643
487
class Tree: def __init__(self, val,left = None, right = None): self.val = val self.left = left self.right = right root = Tree(4, left = Tree(3), right=Tree(5, left= Tree(4))) #InOrderTraversal def InOrderTraversal(root, res = []): if root is None: return res ...
1,470
513
from datetime import datetime # Rest framework from rest_framework import status from rest_framework.decorators import action from rest_framework.mixins import RetrieveModelMixin, ListModelMixin, UpdateModelMixin, CreateModelMixin from rest_framework.response import Response from rest_framework.viewsets import Generic...
4,429
1,307
# 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, ...
11,984
3,839
""" Thornleigh Farm - VPN Watchdog Failure Email Module author: hugh@blinkybeach.com """ from th_watchdog.email import Email class FailureEmail(Email): """ An email notifying the administrator of a failed state """ SUBJECT = 'Starport VPN connection lost' BODY = 'Starport has lost connection to th...
417
132
__all__ = ['TextDataLayer'] from functools import partial import torch from torch.utils.data import DataLoader, DistributedSampler from nemo.backends.pytorch.common.parts import TextDataset from nemo.backends.pytorch.nm import DataLayerNM from nemo.core import DeviceType from nemo.core.neural_types import * from nem...
2,749
823
import logging from datetime import time, timedelta from functools import wraps # Telegram bot libraries from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler from telegram import KeyboardButton, ReplyKeyboardMarkup, ParseMode, Bot, InlineKeyboardButton, InlineKeyboardMarkup f...
21,161
6,888
from server import db, auth, emolytics from server.models import Tweet from classifier import create_classifier from tweepy import Stream from tweepy.streaming import StreamListener from flask.ext.rq import job import json import random from multiprocessing import Process from sqlalchemy.exc import IntegrityError d...
2,591
763
import csv import os import shutil from datetime import datetime from grid import * #from cluster import * from regions import * start_time = datetime.now() print("Allocating...") #grid2 #gridSystem = GridSystem(-74.04, -73.775, 5, 40.63, 40.835, 5) #gridname = "grid2" #grid3 #gridSystem = GridSystem(-74.02, -73.9...
1,340
624
# Lint as: python3 # Copyright 2019 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 # # ...
6,472
2,465
def run_rename(args): from pocketbook.address_book import AddressBook from pocketbook.key_store import KeyStore address_book = AddressBook() key_store = KeyStore() # make sure that the new name is not present either as a key, or as an address new_present = args.new in address_book.keys() or ar...
1,205
364
# -*- coding: utf-8 -*- """ Wrapper for RoBO """ __descr__ = "TODO" __license__ = "BSD 3-Clause" __author__ = u"Epistímio" __author_short__ = u"Epistímio" __author_email__ = "xavier.bouthillier@umontreal.ca" __copyright__ = u"2021, Epistímio" __url__ = "https://github.com/Epistimio/orion.algo.robo" from ._version imp...
395
174
""" Znaleść kąt á, przy którym zasięg skoku z wahadła będzie maksymalny. Należy posłużyć się metodą złotego podziału. Mateusz Ostrowski Index:216708 """ import matplotlib.pyplot as plt import numpy as np class Zloty_podzial: def __init__(self, h, line, a0): tau = (np.sqrt(5) - 1) / 2 a = 0.2 ...
2,343
1,031
from app.database import MOCK_PRODUCT_DATA import re from app.products.base_handler import BaseHandler class ProductInfoHandler(BaseHandler): """ A class used to represent a mini-bot to handle product queries. """ def __init__(self) -> None: super().__init__() def create_match_paterns(se...
3,967
1,114
import sys import copy import pprint pp = pprint.PrettyPrinter(width=120) import inspect import numpy as np from .. import __version__ from .. import qcvars from ..driver.driver_helpers import print_variables from ..exceptions import * from ..molecule import Molecule from ..pdict import PreservingDict from .worker im...
5,940
2,182
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class User_details(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) team_count = models.Intege...
670
201
#Main Sedov Code Module #Ported to python from fortran code written by James R Kamm and F X Timmes #Original Paper and code found at http://cococubed.asu.edu/papers/la-ur-07-2849.pdf import numpy as np from globalvars import comvars as gv from sedov_1d import sed_1d from sedov_1d_time import sed_1d_time ...
10,685
3,540
from lib import action class RGBAction(action.BaseAction): def run(self, light_id, red, green, blue, transition_time): light = self.hue.lights.get(light_id) light.rgb(red, green, blue, transition_time)
224
74
import unittest from typing import Dict, List from src.math_challenge import Challenge, DEFAULT_EMPTY_ANS from src.student_info import StudentInfo class TestChallenge(unittest.TestCase): def test_preprocess(self): self.assertEqual(Challenge.preprocess_ans("a. 37th floor, b. 42nd floor, c. 39th floor, d. ...
1,755
607
import hlt import logging from collections import OrderedDict # GAME START game = hlt.Game("Spoof_v7") logging.info('Starting my %s bot!', game._name) TURN = 0 def navigate(ship, entity, multiplier = 1): navigate_command = ship.navigate( ship.closest_point_to(entity), game_map, speed=int(h...
6,784
2,084
import pytest from eph.horizons import * @pytest.fixture(params=[ ('earth', '399'), ('\'earth\'', '399'), ('Earth', '399'), ('399', '399'), ('\'399\'', '399'), ('pluto', 'pluto'), ]) def codify_obj_data(request): return request.param def test_codify_obj(codify_obj_data): data, resul...
2,875
1,118
# -*- coding: utf-8 -*- import time import sqs_service """Usage: python demo.py Expected set environment variables: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY - AWS_DEFAULT_REGION - AWS_SESSION_TOKEN for IAM roles - AWS_SECURITY_TOKEN for IAM roles Send 'Hello World' to queue 'TEST', listen to the queue and print...
950
335
# Copyright 2020 The FedLearner Authors. 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 applica...
34,106
7,207
import os import shutil def delete_configs(config, dataset, username): if config != 'all': paths = [os.path.join('user_data', username, dataset, config)] else: paths = [os.path.join('user_data', username, dataset, d) for d in os.listdir(os.path.join('user_data', username, data...
675
218
import os import bz2 import json import random import pickle from collections import defaultdict, Counter from tqdm import tqdm import torch from data.crosswoz.data_process.dst.trade_preprocess import ( EXPERIMENT_DOMAINS, Lang, get_seq, get_slot_information, ) class CNEmbedding: def __init__(s...
14,693
5,196
from django.conf.urls import url from django.views.generic import TemplateView from reports import views urlpatterns = [ url(r'balance/$', views.balance, name='report_balance'), url(r'performance/$', views.performance, name='report_performance'), url(r'last_activity/$', views.last_activity, name='last_ac...
789
247
from pycam.Utils.events import get_event_handler, get_mainloop class ProgressContext: def __init__(self, title): self._title = title self._progress = get_event_handler().get("progress") def __enter__(self): if self._progress: self._progress.update(text=self._title, percen...
1,150
316
#!/usr/bin/env python3 # This file is covered by the LICENSE file in the root of this project. import zipfile import argparse import os class ValidationException(Exception): pass if __name__ == "__main__": parser = argparse.ArgumentParser( description="Validate a submission zip file needed to evaluate on...
4,030
1,182
#! /usr/bin/env python # License: Apache 2.0. See LICENSE file in root directory. # # For simple behaviors that can run syncronously, Python provides # a simple way to implement this. Add the work of your behavior # in the execute_cb callback # import rospy import actionlib import behavior_common.msg import time imp...
5,231
1,739
from collections import defaultdict, namedtuple import torch # When using the sliding window trick for long sequences, # we take the representation of each token with maximal context. # Take average of the BERT embeddings of these BPE sub-tokens # as the embedding for the word. # Take *weighted* average of the word ...
7,831
2,640
from rest_framework import serializers from .models import Lecture class LectureSerializer(serializers.ModelSerializer): class Meta: model = Lecture fields = ('id', 'title', 'lecturer_name', 'date', 'duration', 'slides_url', 'is_required')
282
80
from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('', (r'^$', 'suggestions.views.list_all'), (r'^post/$', 'suggestions.views.add_suggestion'), (r'^vote/(?P<suggestion_id>.*)/$', 'suggestions.views.add_vote'), (r'^unvote/(?P<suggestion_id>.*)/$', 'suggestions.views.remove_v...
396
164
#Esse codigo é utilizado para calcular a fronteira eficiente de um portfolio #Esse codigo tem como objetivo avaliar a eficiencia das de um portfolio import numpy as np import pandas as pd import matplotlib.pyplot as plt from pandas_datareader import data as wb assets = ['PG', '^GSPC'] pf_data = pd.Dat...
3,850
1,451
""" Tests for the wily build command. All of the following tests will use a click CLI runner to fully simulate the CLI. Many of the tests will depend on a "builddir" fixture which is a compiled wily cache. TODO : Test build + build with extra operator """ import pathlib import pytest from click.testing import CliRunn...
7,607
2,519
import unittest from zmq_integration_lib import RPCClient, RPCServer import unittest.mock as mock class TestOBPHelper(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def logout(self, mock_zmq): self.assertTrue(True) def get_login_token(self, mock_zmq):...
356
120
import os import numpy as np import tqdm as tqdm def cvt_Data(): if not os.path.exists('./fphab_data/newData'): os.mkdir('./fphab_data/newData') #for i in range(1,7): # os.mkdir('./fphab_data/newData/Subject_'+str(i)) subject_list=os.listdir('./fphab_dat...
1,657
520
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
2,412
714
import json import os.path class StorageHelper: __document = None __path = None @staticmethod def write(key, data): StorageHelper.__init() StorageHelper.__document[key] = json.dumps(data) StorageHelper.__store() @staticmethod def read(key): StorageHelper.__ini...
1,171
313
import ndex.client as nc from ndex.networkn import NdexGraph import io import json from IPython.display import HTML from time import sleep import os, time, tempfile import sys import time import logging import grpc import networkx as nx import cx_pb2 import cx_pb2_grpc import numpy as np import inspect from concurre...
12,383
3,749
""" OPENSIGNALSFACTORY PACKAGE INITIALISATION FILE (WITH IMPORT STATEMENTS) The main purpose of biosignalsnotebooks package is to support the users of PLUX acquisition devices, such as biosgnalsplux or bitalino, in some processing tasks that can be applied to the acquired electrophysiological signals, namely ECG, EMG....
3,509
864