content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import pandas as pd
from anacode.agg import aggregation as agg
@pytest.fixture
def frame_absa():
ent_header = ['doc_id', 'text_order', 'entity_name', 'entity_type',
'surface_string', 'text_span']
ents = pd.DataFrame([
[0, 0, 'L... |
#
# _test_end_of_track_event.py
# crest-python
#
# Copyright (C) 2017 Rue Yokaze
# Distributed under the MIT License.
#
import crest_loader
import unittest
from crest.events.meta import EndOfTrackEvent
class TestEndOfTrackEvent(unittest.TestCase):
def test_ctor(self):
EndOfTrackEvent()
def te... |
# -*- coding: utf8 -*-
import dataclasses
import json
from loguru import logger
from .session import Session
from .models import Game,User
def db_user_add(tweet,user_ra):
session = Session()
try:
user = User(sender_id = tweet.user.id,
... |
# //Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade,
# Se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento.
# Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
from datetime im... |
# Copyright (c) 2018 European Organization for Nuclear Research.
# 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/LIC... |
from heap.task_scheduler import TaskScheduler
class TestTaskScheduler:
def test_all_unique(self):
tsc = TaskScheduler()
result = tsc.leastInterval(["A", "B", "C"], 2)
assert result == 3
def test_all_same(self):
tsc = TaskScheduler()
result = tsc.leastInterval(["A", "A... |
#%%
from pywaffle import Waffle
import pandas as pd
import matplotlib.pyplot as plt
#%%
df_raw = pd.read_csv('df.csv')
#%%
df_raw
#%%
df_class = df_raw.groupby('class').size().reset_index(name='counts_class')
n_categories = df_class.shape[0]
colors_class = [plt.cm.Set3(i/float(n_categories)) for i in range(n_categor... |
# -*- coding: utf-8 -*-
"""
Editor: Zhao Xinlu
School: BUPT
Date: 2018-01-29
Function: 链表合并的递归实现
"""
class ListNode(object):
def __init__(self, val):
self.val = val
self.next_ = None
def Merge2LinkLists(lists1, lists2):
"""
链表合并的递归实现
:param lists1:
:param lists2:
:return:
""... |
import asyncio
import os
import pytest
import re
import uuid
from arq import Worker
from buildpg import Values, asyncpg
from buildpg.asyncpg import BuildPgConnection
from foxglove import glove
from foxglove.db import PgMiddleware, prepare_database
from foxglove.db.helpers import DummyPgPool, SyncDb
from foxglove.test_s... |
from selenium.webdriver.common.keys import Keys
from django.test.utils import override_settings
from .. import test_widget_select as test
from . import VisualTest
@override_settings(ROOT_URLCONF='tests.test_widget_select')
class Test(VisualTest):
def test_test_default_usecase(self):
self.driver.get('%s%s... |
from pydantic import BaseModel
class RecommendedResourceResponse(BaseModel):
label: str
rating: int
description: str
organisation: str
|
from django.urls import path
from . import views
urlpatterns = [
# go to main site
path('', views.main, name='home'),
path('newProduct/', views.model_form_upload, name='new_product'),
path('en/', views.transEn, name='en'),
path('ko/', views.transKo, name='ko'),
]
|
__author__ = 'katharine'
from setuptools import setup, find_packages
from pkg_resources import resource_string
requirements_str = resource_string(__name__, 'requirements.txt')
requirements = [line.strip() for line in requirements_str.splitlines()]
__version__= None # Overwritten by executing version.py.
with open('... |
import numpy
from wofrywise2.beamline.wise_optical_element import WiseOpticalElement
from wiselib2.Fundation import OpticalElement, PositioningDirectives
from wiselib2.Optics import Detector
class WiseDetector(WiseOpticalElement):
def __init__(self,
name="Undefined",
detector = ... |
import pytest
from pysignature import exceptions
from pysignature import typechecked
from pysignature.types import (
Any, String, Or, Tuple, List, InstanceOf, Set,
Dictionary, Boolean, Numeric
)
# Decorated functions
@typechecked(a=int, b=int, c=String)
def x(a, b, c):
return c + str(a + b)
@typechecked(... |
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
row = len(matrix)
col = len(matrix[0])
i,j = row-1,0
... |
"""
open-mtg MIT license granted by Hylnur Davíð Hlynsson for simulating the game (https://github.com/hlynurd/open-mtg)
Original simulator coded by Hylnur and Erik Martinez
"""
import copy
from cards import *
def heuristic_value(player, game):
if player.get_opponent(game).has_lost:
return 9999
if pla... |
# -*- coding: UTF-8 -*-
"""
..
---------------------------------------------------------------------
___ __ __ __ ___
/ | \ | \ | \ / the automatic
\__ |__/ |__/ |___| \__ annotation and
\ | | | | \ ... |
import sys
sys.path.append('../')
import speedifysettings
import logging
logging.basicConfig(handlers=[logging.FileHandler('test.log'),logging.StreamHandler(sys.stdout)],format='%(asctime)s\t%(levelname)s\t%(module)s\t%(message)s', level=logging.INFO)
# Get the default settings, and apply them to just put us in a kn... |
from django.apps import AppConfig
class MetOfficeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'met_office'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from grcanosabot.grcanosabot import GrcanosaBot
def main():
n = GrcanosaBot("/mnt/shared","/data")
n.start()
n.idle()
if __name__ == '__main__':
main() |
################# Features #################
# 1. Read the link list file and get links
# 2. Each 3~4 min viste random links
# 3. Each 30~45 min change user agent and ip address
################# import module #################
# selenium lib
# from selenium import webdriver
from seleniumwire... |
#MASS CLIPPING (ogr2ogr)
#Stefan Safranek
#Shape Files by US-States
import os, glob
import subprocess
from osgeo import ogr
# Input folders
saveFolder = "C:\\Users\\Stefan\\Desktop\\CLIPPING\\statesClipped"
# Input layers
folderOne = glob.glob("C:\\Users\\Stefan\\Desktop\\CLIPPING\\states\\*.shp")
folde... |
"""
Solution of 1D differential equation by linear combination of
basis functions in function spaces and a variational formulation
of the differential equation problem.
"""
import sympy as sym
import numpy as np
import mpmath
import matplotlib.pyplot as plt
def solver(integrand_lhs, integrand_rhs, psi, Omega,
... |
import tensorflow as tf
from tensorflow.contrib.layers import fully_connected
from tensorflow.examples.tutorials.mnist import input_data
n_inputs = 28*28
n_hidden1 = 300
n_hidden2 = 150 # codings
n_hidden3 = 300
n_outputs = n_inputs
learning_rate = 0.01
l2_reg = 0.001
activation = tf.nn.elu
regularizer = tf.contrib... |
from unittest import TestCase
from mock import mock
from pictures.dedupe import dedupe
from tests import helpers
def create_mock_cmp(equal_files):
return lambda f1, f2: f1 in equal_files and f2 in equal_files
class TestDedupe(TestCase):
EQUAL_FILES = ['filename1', 'filename2', 'filename3']
NON_EQUAL_FI... |
"""
Copyright 2016 Brandon Warner
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, software... |
################################################################################
# Copyright 2020 Advanced Micro Devices, Inc. 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 So... |
"""
unittest.TestCase for JavaScript tests.
"""
from __future__ import absolute_import
import os
import os.path
import shutil
import sys
import threading
from . import interface
from ... import config
from ... import core
from ... import utils
class JSTestCase(interface.TestCase):
"""
A jstest to execute.
... |
from output.models.sun_data.stype.st_facets.st_facets00114m.st_facets00114m_xsd.st_facets00114m import Test
__all__ = [
"Test",
]
|
a = [1,2,43,3,5,43,3,2,1,100,200,110,100,200,100,3,2,4,6,5,2,6,5,3,12,13,43,45,43]
counts = {}
for val in a:
if not val in counts:
counts[val] = 1
else:
counts[val] += 1
print(counts) |
from numpy import *
from configobj import ConfigObj
class Contrast(dict):
def __init__(self, indict=None,verbose=0):
dict.__init__(self)
if indict != None:
for entry in indict.keys():
if entry != "Type" and entry != "Dimension":
if verbose: print indi... |
description = 'motor driver of CASCADE detector'
group = 'optional'
tango_base = 'tango://miractrl.mira.frm2:10000/mira/'
devices = dict(
# co_dtx = device('nicos.devices.entangle.Sensor',
# lowlevel = True,
# tangodevice = tango_base + 'detector/dtx_enc',
# unit = 'mm',
# ),
mo_dt... |
import pytest
from json_modify import apply_to_dict
DELIM = "/"
def test_apply_to_dict_add(mocker):
mocker.patch("json_modify.get_path")
section = {}
action = {"action": "add", "value": {"a": 10}}
apply_to_dict(section, action, DELIM)
assert section == {"a": 10}
def test_apply_to_dict_add_with... |
import unittest
from ... import stringutils
class TestReplace(unittest.TestCase):
def test_replace(self):
self.assertEqual(stringutils.Replace('Hello World').replace('World', 'World!'), 'Hello World!')
def test_will_fail(self):
self.assertEqual(stringutils.Replace('Hello World').replace('World... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2020 Fetch.AI 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 ... |
from model.markowitz import Markowitz
from model.black_litterman import Black_Litterman
from model.equal_weight import EqualWeight
from database.tables.user import User, get_companys
from database.tables.company import Company
from database.tables.portfolio import Portfolio
import numpy as np
def return_portfolio(mode... |
from flask import Flask, render_template, url_for, request, session, redirect, jsonify, json, flash
from flask_pymongo import PyMongo
from pymongo import MongoClient
from jinja2 import Template, TemplateNotFound
from flask_dotenv import DotEnv
from bson.json_util import dumps
from bson.objectid import ObjectId
from wer... |
try:
import urwid
except ImportError:
print("Could not import the Python module 'urwid'.")
raise SystemExit
import random
def handle_input(input):
if input in UI.keys['escape']:
raise urwid.ExitMainLoop()
if input in UI.keys['left'] + UI.keys['right']:
main_frame.set_focus('footer... |
from abc import ABC, abstractmethod
from typing import Optional
from uuid import UUID, uuid4
from pydantic.main import BaseModel
from pydantic.schema import Schema
from db import CRUD, Database
DEFAULT_NAMESPACE = "default"
class BaseRecordConfig(BaseModel, ABC):
class Config:
use_enum_values = True
... |
##
#
import os
from pyrogram import filters
from pyrogram.types import Message
from telegraph import upload_file
from megumin import megux, Config
from megumin.utils import get_string
@megux.on_message(filters.command(["telegraph", "tg"], Config.TRIGGER))
async def telegraph(c: megux, message: Message):
replie... |
import requests
import requests_cache
import json
from urllib.parse import quote_plus as urlencode
class CircleApiError(Exception):
def __init__(self, error):
self.error = error
class BuildStep():
def __init__(self, json, build_num):
self.build_num = build_num
self.raw_json = json
... |
from learning_to_adapt.policies.base import Policy
from learning_to_adapt.utils.serializable import Serializable
import numpy as np
class MPCController(Policy, Serializable):
def __init__(
self,
name,
env,
dynamics_model,
reward_model=None,
d... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... |
import pandas as pd
import numpy as np
import re
import os
import tensorflow as tf
from collections import Counter
import pickle
from rouge import Rouge
from nltk.translate.bleu_score import sentence_bleu
with open("Vocabulary.p",'rb') as fp:
vocab = pickle.load(fp)
with open("Reverse_vocab.p",'rb') as... |
# this was written for Python >3.5; and might not work with Python 2.x
import glob
import itertools
import re
import sys
def main():
to_process = itertools.chain.from_iterable((glob.iglob(f, recursive=True) for f in sys.argv[1:]))
pat = re.compile(r'''___file_subst___\((?P<quote>['"])(?P<subst_name>.+?)(?P=quot... |
# Copyright 2020-2021 The Kraken 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 ... |
from django.core.management.base import BaseCommand
from olympia.users.models import UserProfile
class Command(BaseCommand):
"""Make sure we are correctly anonymizing deleted users."""
help = 'Re-anonymize already deleted users.'
def handle(self, *args, **options):
for user in UserProfile.object... |
# coding=utf-8
import numpy as np
import scipy.signal as sig
from pypint.utilities import assert_is_callable, assert_is_instance, \
assert_condition
# from pypint.plugins.multigrid.multigrid_problem import MultigridProblem
# from pypint.plugins.multigrid.stencil import Stencil
from... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import uuid
class Migration(migrations.Migration):
dependencies = [
('hhlregistrations', '0007_auto_20150412_2220'),
]
operations = [
migrations.AddField(
model_name='eve... |
from multiprocessing.dummy import current_process
import threading
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from djan... |
from app.auth.views import auth # noqa
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.utils.translation import ugettext_lazy as _
from .forms import MyAdminChangeForm, SignupForm
from .mode... |
from pytest import raises
from tests import ZSetTestCase
class TestZSetSlicing(ZSetTestCase):
def setup_method(self, method):
super(TestZSetSlicing, self).setup_method(method)
self.zset.add(1, 1)
self.zset.add(2, 2)
self.zset.add(3, 3)
self.zset.add(4, 4)
def test_get_... |
# rewrite from https://github.com/vspandan/IFuzzer/blob/master/codegen/fitness.py
import math
from random import random, randint
MAX = 'max'
MIN = 'min'
CENTER = 'center'
FITNESS_TYPES = [MAX, MIN, CENTER]
SCALING_LINEAR = 'linear'
SCALING_TRUNC = 'truncation'
SCALING_EXPONENTIAL = 'exponential'
SCALING_LOG = 'loga... |
import stokepy as sp
import numpy as np
# instantiate class
fmc = sp.FiniteMarkovChain()
# create initial distribution vector
phi = np.array([0, 0, 1, 0, 0])
# generate Markov chain with no boundary conditions
fmc.gen_from_params(phi, p = 0.6, num_states = 5, dim = 1)
# apply boundary condition: absorbing, reflecti... |
#!/usr/bin/env python
"""Copies model output files from ILAMBv1 to ILAMBv2."""
import os
import shutil
src_dir = '/home/csdms/ILAMB/MODELS/original'
dst_dir = '/home/csdms/ilamb/MODELS'
for root, dirs, files in os.walk(src_dir):
if len(files) == 0:
model_name = os.path.basename(root)
new_model_... |
################################### (ADDED) Helper functions below, all added ######################################
def get_post_means(obj):
nu_W = obj.nu_W
rho_W = obj.rho_W
nu_H = obj.nu_H
rho_H = obj.rho_H
good_k = obj.good_k
W_post_mean = np.zeros(nu_W[:, good_k].shape)
for ... |
import pickle
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
class Main(object):
def __init__(self):
with open("tokenizer.pickle", "rb") as handle:
self.tokenizer = pickle.load(handle)
with open("label_tokenizer.pickle", ... |
from behave import *
from tests.acceptance.page_model.create_event_page import CreateEventPage
use_step_matcher('re')
@when('I enter "(.*)" in the "(.*)" field')
def step_impl(context, content, field_name):
page = CreateEventPage(context.driver)
page.form_field(field_name).send_keys(content)
@when('I press... |
'''
Find paths for RGZ data and use it to load raw data such as contour files
Looks in local directories first; if not found, sends request over network to AWS
Kyle Willett, UMN
'''
import os
import json
import requests
def make_pathdict(local=False):
# Get dictionary for finding the path to FITS files and WCS... |
import numpy as np
import glob
from src import parseTrackletXML as pt_XML
from kitti_foundation import Kitti, Kitti_util
image_type = 'color' # 'gray' or 'color' image
mode = '00' if image_type == 'gray' else '02' # image_00 = 'graye image' , image_02 = 'color image'
image_path = './image_' + mode + '/data'
velo_p... |
import pickle
import pandas as pd
import numpy as np
from sklearn.metrics import classification_report
from sklearn import metrics
from sklearn import tree
from config import Config
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors i... |
# THIRD PARTY IMPORTS
# LOCAL IMPORTS
from views import *
app.add_url_rule('/signin', view_func=Signin.as_view('signin'))
app.add_url_rule('/signup', view_func=Signup.as_view('signup'))
app.add_url_rule('/account', view_func=AccountView.as_view('account'))
app.add_url_rule('/account/signout', view_func=Sign... |
import mysql.connector
from mysql.connector import errorcode
user = 'aniket'
password = 'aniket'
root = 'admin'
database = 'twitter'
host = '127.0.0.1'
TABLES = {}
TABLES['tweet'] = (
"CREATE TABLE `tweet` ("
" `tweet_id` int(18) NOT NULL,"
" `actor_id` int(18) NOT NULL,"
" `id_str` varc... |
from unittest import TestCase, main
import warnings
import numpy as np
import numpy.testing as npt
import pandas as pd
import pandas.testing as pdt
import skbio
from qiime2 import Artifact
from q2_sidle._taxonomy import (reconstruct_taxonomy,
# _combine_taxonomic_annotation,
... |
# Copyright 2017 The TensorFlow 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... |
import sys
import os
# to proj root
sys.path.insert(
0,
os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))))
)
|
#!/bin/python3
import sys
def sockMerchant(n, ar):
# Complete this function
all_sizes = list(set(ar))
pairs_num = 0
for s in all_sizes:
s_num = ar.count(s)
pairs_num += s_num // 2
return pairs_num
n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
result ... |
# coding=utf-8
import os
from mkdocs.config import config_options
from mkdocs.plugins import BasePlugin
from mkdocs import utils
class RenderOtherfilePlugin(BasePlugin):
config_scheme = (
('on', config_options.Type(bool, default=False)),
('ext', config_options.Type(list, default=[]))
)
... |
import os
import platform
from kivy.config import Config
from kivy.event import EventDispatcher
from kivy.metrics import sp
from kivy.properties import NumericProperty
from fivecalls.singleton import Singleton
class KivyConfig(EventDispatcher, metaclass=Singleton):
font_size = NumericProperty(20)
def __ini... |
from enum import IntEnum, unique
@unique
class Ideogram(IntEnum):
NONE = 0
SINGLE_LINE_UNDER_OR_RIGHT = 1
DOUBLE_LINE_UNDER_OR_RIGHT = 2
SINGLE_LINE_OVER_OR_LEFT = 3
DOUBLE_LINE_OVER_OR_LEFT = 4
STRESS = 5
|
# 9.4 Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail
# messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the
# mail. The program creates a Python dictionary that maps the sender's mail address to a co... |
import json
from os import path
from flask import flash, request
from database.study_models import Study, Survey
def copy_existing_study_if_asked_to(new_study):
if request.form.get('copy_existing_study', 'false') == 'true':
old_study = Study.objects.get(pk=request.form.get('existing_study_id', None))
... |
# --- Normalize species and specimen data
#
# This code takes a metadata file and normalizes the species and specimen
# fields. The actual code is in normalize/mapping.py
#
# normalize-step1.py [--yaml] --in ~/tmp/pubseq/state.json file(s)
#
# Example:
#
# python3 ./workflows/tools/normalize-step1.py -s ~/tmp/yamlfa... |
class User:
def __init__(self, name, identifier, bank=None, address=None):
self.name = name
self.identifier = identifier
self.bank = bank
self.address = address
class UserBank:
def __init__(self, bankId, branchCode, accountNumber, accountVerifier, bankName=""):
self... |
__all__ = ['sensors', 'everloop', 'GPIO']
from . import bus
from . import sensors
from . import everloop
from . import GPIO
|
#
#
# =================================================================
# =================================================================
"""Provides the REST API implementation for the /storage-providers URI"""
import webob.exc
from cinder.api import extensions
from cinder.api.openstack import wsgi
from cinder.api... |
import pytest
from tests.functional.coercers.common import resolve_unwrapped_field
@pytest.mark.asyncio
@pytest.mark.ttftt_engine(
name="coercion",
resolvers={"Query.intWithDefaultField": resolve_unwrapped_field},
)
@pytest.mark.parametrize(
"query,variables,expected",
[
(
"""quer... |
from pyhop_anytime import *
global state, goals
state = State('state')
state.calibration_target = Oset([('instrument0','groundstation2'),('instrument1','groundstation1'),('instrument2','groundstation0'),('instrument3','groundstation0'),('instrument4','groundstation2'),('instrument5','groundstation1'),('instrument6','gr... |
# MD5 encryption cracker
import argparse
import hashlib
"""Creating parser to get multiple arguments from command line"""
parser = argparse.ArgumentParser(description='MD5 Cracker')
"""Adding arguments to the parse """
# Adding first argument '-md5'
parser.add_argument('-md5', dest='hash', help='md5 hash'... |
#############################################################################################
# Append the path to ummon3 to PATH-Variable so that ummon can be imported during development
import sys
sys.path.insert(0,'../../ummon3') # for python basicusage.py
sys.path.insert(0,'../ummon3') # for python examples/ba... |
__all__ = ["Photon_v1"]
def Photon_v1():
code = """
namespace edm{
struct Photon_v1{
/* Branch variables */
uint32_t RunNumber{};
unsigned long long EventNumber{};
float avgmu{};
float LumiBlock{};
/* Egamma */
bool ph_... |
"""Sensor for keymaster."""
from functools import partial
import logging
from typing import Dict, List, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_platform
from homeassistant.helpers.dispatcher import async_dispatc... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
#load input image
source_input = "/Users/nhant/Google Drive/OnlineLearning/selflearning_CV_with_Python/practice_sources/images/input.jpg"
image = cv2.imread(source_input)
"""
cv2.calcHist(images, channels, mask, hintSize, ranges[,hist[, accumulate]])... |
import alignfaces as af
import numpy as np
mother_folder = "/Users/carl/Studies/facepackage-macbook/facepackage-slim/results/"
aligned_folders = ["CAS-female-aligned/", "CAS-male-aligned/",
"GUFD-female-aligned/", "GUFD-male-aligned/"]
# Default values used in results_1_preprocessing.py
EF = ['jawl... |
from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import JSONField
from common.models import DateTracking
class User(DateTracking, AbstractUser):
"""
Django model for an individual user that has some kind of access to Fake News Links.
This could be admin or lower lev... |
from django.apps import AppConfig
class SendGridConfig(AppConfig):
name = 'send_grid'
|
B = int(input())
for i in range(B):
N, K, M = map(int, input().split())
arr = []
for j in range(N):
A = input()
arr.append(A)
arr.sort(key=lambda x: x[:M])
print(arr[K - 1])
|
from super_spirals.metrics.pairwise import (
minkowski_distances,
cosine_distances,
cosine_similarity,
)
__all__ = ["minkowski_distances", "cosine_distances", "cosine_similarity"]
|
class Solution(object):
def numFriendRequests(self, ages):
"""
:type ages: List[int]
:rtype: int
"""
count = dict()
for age in ages:
count[age] = count.setdefault(age, 0) + 1
friend_requests = 0
for ageA, countA in count.items(... |
import izi
import part_1
import part_2
@izi.get('/')
def say_hi():
return "Hi from root"
@izi.extend_api()
def with_other_apis():
return [part_1, part_2]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is referred and derived from project NetworkX
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
#
#... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown copyright. The Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are me... |
from datetime import datetime, timedelta
FEETS_TO_METER = 0.3048 # ratio feets to meter
FPM_TO_MS = FEETS_TO_METER / 60 # ratio fpm to m/s
KNOTS_TO_MS = 0.5144 # ratio knots to m/s
KPH_TO_MS = 0.27778 # ratio kph to m/s
HPM_TO_DEGS = 180 / 60 # ratio between ... |
from abc import ABC
from app.domain.repository.interfaces.abstract_repository import AbstractRepository
from app.domain.repository.interfaces.abstract_repository_create_action import AbstractRepositoryCreateAction
from app.domain.repository.interfaces.abstract_repository_delete_action import AbstractRepositoryDeleteAc... |
from dbt.adapters.mysql.connections import MySQLConnectionManager
from dbt.adapters.mysql.connections import MySQLCredentials
from dbt.adapters.mysql.relation import MySQLRelation
from dbt.adapters.mysql.column import MySQLColumn
from dbt.adapters.mysql.impl import MySQLAdapter
from dbt.adapters.base import AdapterPlu... |
from django.db import models
from django.utils.text import slugify
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from images.models import Image
class Gallery(models.Model):
"""Includes one or more images and a unique name."""
name = models.CharField(max_... |
"""Top-level package for haiopy."""
__author__ = """The pyfar developers"""
__email__ = 'marco.berzborn@akustik.rwth-aachen.de'
__version__ = '0.1.0'
|
N, C = map(int, input().split())
xy = []
for _ in range(N):
xy.append(tuple(map(int, input().split())))
ans = 0
cal_sum_A = [0 for _ in range(N)]
cal_sum_A[0] = xy[0][1] - xy[0][0]
for i in range(1, N):
cal_sum_A[i] += cal_sum_A[i - 1] + xy[i][1] - xy[i][0] + xy[i - 1][0]
cal_sum_B = [0 for _ in range(N)]
cal_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.