text
string
size
int64
token_count
int64
# Copyright European Organization for Nuclear Research (CERN) # # 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 # # Authors: # - Vincent Garonne, <vin...
2,147
792
""" This code is attributed to Yingtong Dou (@YingtongDou) and UIC BDSC Lab DGFraud (A Deep Graph-based Toolbox for Fraud Detection in TensorFlow 2.X) https://github.com/safe-graph/DGFraud-TF2 """ import argparse import numpy as np from tqdm import tqdm import tensorflow as tf from tensorflow.keras import optimizers ...
4,024
1,329
""" find the Schwarzschild radius of the Sun in m using pint""" import pint class Sun: """ Class to describe a star based on its mass in terms of solar masses """ def __init__(self, mass): self.ureg = pint.UnitRegistry() self.ureg.define("Msolar = 1.98855*10**30 * kilogram") self.mass ...
849
302
from ....crud.rulesprovider.base import RulesProvider from .. import exc from ..app import App from ..utils import has_role from .model import UserCollection, UserModel class UserRulesProvider(RulesProvider): context: UserModel def change_password(self, password: str, new_password: str, secure: bool = True)...
1,009
272
from dsa.parsing.line_parsing import line_parser from dsa.parsing.token_parsing import make_parser _parser = line_parser( 'Huffman table entry', make_parser( 'Huffman table entry data', ('integer', 'encoded bit sequence'), ('hexdump', 'decoded bytes') ) ) class Huff...
1,523
485
def split_in_three(data_real, data_fake): min_v = min(data_fake.min(), data_real.min()) max_v = max(data_fake.max(), data_real.max()) tercio = (max_v - min_v) / 3 # Calculate 1/3 th_one = min_v + tercio # Calculate 2/3 th_two = max_v - tercio first_f, second_f, third_f = split_data(th_...
891
362
from unittest.mock import patch import urllib from django.urls import reverse from django.core import mail from django.conf import settings from django.test import override_settings from model_bakery import baker from evap.evaluation import auth from evap.evaluation.models import Contribution, Evaluation, UserProfil...
6,486
1,968
import argparse import os.path as osp from glob import glob import cv2 import pandas as pd from tqdm import tqdm from gwd.converters import kaggle2coco def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--image-pattern", default="/data/SPIKE_images/*jpg") parser.add_argument("--an...
1,827
687
import json from shuttl import app from shuttl.tests import testbase from shuttl.Models.Reseller import Reseller from shuttl.Models.organization import Organization, OrganizationDoesNotExistException class OrganizationViewTest(testbase.BaseTest): def _setUp(self): pass def test_index(self): #...
5,090
1,581
# This file contains functions designed for # loading cron tables and storing new feeds. from emissary import db from sqlalchemy import and_ from emissary.controllers.utils import spaceparse from emissary.controllers.cron import parse_timings from emissary.models import APIKey, Feed, FeedGroup def create_feed(log, db...
3,477
1,371
"""Vodgen app""" from msilib.schema import Directory import sys import json import re from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QFileDialog, QLabel, QLineEdit, QMainWindow, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget) from videocutter import create_video from thumbnail import Thumbnail,...
7,661
2,327
# # Copyright (C) 2018 ETH Zurich and University of Bologna # # 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 applicab...
1,733
585
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ nums_set = set(nums) full_length = len(nums) + 1 for num in range(full_length): if num not in nums_set: return num
300
94
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Tests the shell console :author: Thomas Calmant """ # Pelix from pelix.utilities import to_str, to_bytes # Standard library import random import string import sys import threading import time # Tests try: import unittest2 as unittest except ImportError: ...
5,177
1,298
import os import math def dotProduct(v1, v2): return sum(x * y for x, y in zip(v1, v2)) def sigmoid(x): return 1.0 / (1.0 + math.exp(-x)) def getResourcesPath(): return os.path.abspath(os.path.join(os.path.dirname( __file__ ), os.pardir, 'resources')) def readTrainModel(filePath, num...
708
282
# -*- coding: utf-8 -*- # @Author: Juan Quintana # @Date: 2018-09-26 10:01:02 # @Last Modified by: Juan Quintana # @Last Modified time: 2018-09-26 16:04:24 """ XGBOOST Regressor with Bayesian tuning: OPTION 3 In this case it will be used hyperopt-sklearn and his native algorithm "xgboost_regression". NOTE: sciki...
3,530
1,347
# O Departamento Estadual de Meteorologia lhe contratou para desenvolver um programa que leia as um conjunto indeterminado de temperaturas, e informe ao final a menor e a maior temperaturas informadas, bem como a média das temperaturas. temperaturas = [] while True: graus = float(input("Digite a temperatura em gr...
719
217
#!/usr/bin/env python """ Created by howie.hu at 2021/4/7. Description:通用函数 Changelog: all notable changes to this file will be documented """ import hashlib def md5_encryption(string: str) -> str: """ 对字符串进行md5加密 :param string: 加密目标字符串 :return: """ m = hashlib.md5() m.update(...
369
150
""" PEP 0484 ( https://www.python.org/dev/peps/pep-0484/ ) describes type hints through function annotations. There is a strong suggestion in this document that only the type of type hinting defined in PEP0484 should be allowed as annotations in future python versions. """ import re from parso import ParserSyntaxErro...
14,612
4,085
"""Below Python Programme demonstrate rpartition functions in a string""" string = "Python is fun" # 'is' separator is found print(string.rpartition('is ')) # 'not' separator is not found print(string.rpartition('not ')) string = "Python is fun, isn't it" # splits at last occurence of 'is' print(string.rpartition('...
326
104
data = ( 'Mie ', # 0x00 'Xu ', # 0x01 'Mang ', # 0x02 'Chi ', # 0x03 'Ge ', # 0x04 'Xuan ', # 0x05 'Yao ', # 0x06 'Zi ', # 0x07 'He ', # 0x08 'Ji ', # 0x09 'Diao ', # 0x0a 'Cun ', # 0x0b 'Tong ', # 0x0c 'Ming ', # 0x0d 'Hou ', # 0x0e 'Li ', # 0x0f 'Tu ', # 0x10 'Xiang ...
4,583
2,964
import sys import unittest def merge(nums1, nums2): """ :param nums1: Sorted list of numbers. :param nums2: Sorted list of numbers. :return: Combined sorted list of numbers. """ merged = list() while len(nums1) != 0 and len(nums2) != 0: if nums1[0] <= nums2[0]: merged...
2,023
848
# Copyright (c) OpenMMLab. All rights reserved. import tempfile from mmocr.utils import list_from_file, list_to_file lists = [ [], [' '], ['\t'], ['a'], [1], [1.], ['a', 'b'], ['a', 1, 1.], [1, 1., 'a'], ['啊', '啊啊'], ['選択', 'noël', 'Информацией', 'ÄÆä'], ] def test_list_t...
1,548
501
import cv2 from Text_Detection import detect_characters, detect_string, detect_words import re from live_recognition import facial_recognition # def rescale_frame(frame, percent=75): width = int(frame.shape[1] * percent/ 100) height = int(frame.shape[0] * percent/ 100) dim = (width, height) ret...
2,638
1,070
##! python3 ##============================================================================== ## Copyright (c) 2021 COMPAL Electronic Inc. All rights reserved. ## This program contains proprietary and confidential information. ## All rights reserved except as may be permitted by prior written consent. ## ## ...
17,268
5,580
import matplotlib.pyplot as plt import numpy as np # darts_025 = [0, 0, 0, 0, 2, 5, 6, 7, 8] darts_025 = [0, 0, 0, 2, 3, 5, 7, 8] darts_05 = [0, 0, 3, 3, 4, 4, 5, 7, 7] adas_025_9 = [0, 0, 0, 0, 3, 5, 7] adas_05_9 = [0, 0, 1, 4, 5, 6, 6, 7, 7, 7, 7] adas_05_95 = [] adas_05_97 = [0, 0, 0, 2, 4, 4, 4, 4, 4, 6, 8] mile ...
1,504
1,023
from wagtail.admin.edit_handlers import ( InlinePanel, HelpPanel, FieldPanel, FieldRowPanel, MultiFieldPanel, PageChooserPanel, ) from wagtail.documents.edit_handlers import DocumentChooserPanel from wagtail.images.edit_handlers import ImageChooserPanel from core.helpers import make_translated_interface from c...
21,040
4,882
divisor = int(input()) bound = int(input()) for num in range(bound, 0, -1): if num % divisor == 0: print(num) break
137
51
from floodsystem.geo import stations_within_radius from floodsystem.stationdata import build_station_list def run(): """Requirements for Task 1C""" # Build list of stations stations = build_station_list() # Store the coordinates of Cambridge City Centre CambCoord = (52.2053, 0.1218) #store the...
595
194
from model.objects import Objects import time class ProjectHelper: def __init__(self, app): self.app = app project_cache = None def get_project_list(self): if self.project_cache is None: wd = self.app.wd self.open_manage_project_page() self.project_ca...
2,072
668
cities = [ 'Budapest', 'Debrecen', 'Miskolc', 'Szeged', 'Pecs', 'Zuglo', 'Gyor', 'Nyiregyhaza', 'Kecskemet', 'Szekesfehervar', 'Szombathely', 'Jozsefvaros', 'Paradsasvar', 'Szolnok', 'Tatabanya', 'Kaposvar', 'Bekescsaba', 'Erd', 'Veszprem', ...
4,597
2,244
# Generated by Django 3.1.1 on 2020-09-09 12:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("carbon_quiz", "0009_auto_20200908_2201"), ] operations = [ migrations.RemoveField( model_name="mission", name="descr...
969
282
import json from ..webstack import run as webstack_run def process(json_file_list): for json_filename in json_file_list: with open(json_filename) as json_file: json_data = json.load(json_file) webstack_data = json_data.get('webstack', None) if webstack_data: ...
353
107
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright (c) 2011-2019, Gianluca Fiore # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # ...
4,396
1,259
import trio import os import json from itertools import count # Experiment with generating Chrome Event Trace format, which can be browsed # through chrome://tracing or other mechanisms. # # Screenshot: https://files.gitter.im/python-trio/general/fp6w/image.png # # Trace format docs: https://docs.google.com/document/d...
4,344
1,327
from data_refinery_common.models.surveys import SurveyJob, SurveyJobKeyValue from data_refinery_common.models.batches import ( BatchStatuses, Batch, BatchKeyValue, File ) from data_refinery_common.models.jobs import ( WorkerJob, DownloaderJob, ProcessorJob ) from data_refinery_common.models....
345
116
from zeep import Client from models import RequestParameter class Caller: def __init__(self): wsdl_url = "http://0.0.0.0:8080/?wsdl" self._name = "dummy_name" self._times = 3 self._client = Client(wsdl_url) def call_say_hello_1(self): result = self._client.service.say...
1,144
365
from rest_framework import generics from .permissions import IsOwner from .serializers import BucketlistSerializer, UserSerializer from .models import Bucketlist from django.contrib.auth.models import User from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import SessionAuthentica...
1,600
415
# coding: utf-8 # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
7,113
2,168
from django.contrib import auth, messages from django.shortcuts import redirect, render from django.views.decorators.http import require_POST, require_safe @require_safe def index(request): context = {} return render(request, 'prikmeter/index.html', context) @require_POST def login(request): email = req...
752
220
import balanced balanced.configure('ak-test-1o9QKwUCrwstHWO5sGxICtIJdQXFTjnrV') order = balanced.Order.fetch('/orders/OR7qAh5x1cFzX0U9hD628LPa')
146
78
from typing import List # 移动零 class Solution: # 新开一个数组 def moveZeroes1(self, nums: List[int]) -> None: temp, k = [0] * len(nums), 0 for n in nums: if n != 0: temp[k] = n k += 1 nums[:] = temp[:] # 双指针解法 def moveZeroes2(self, nums:...
490
197
from __future__ import print_function import tensorflow as tf import numpy as np from collections import namedtuple, OrderedDict from subprocess import call import scipy.io.wavfile as wavfile import argparse import codecs import timeit import struct import toml import re import sys import os def _int64_feature(value)...
6,368
2,000
from myShop import MyShop from myBot import MYBOT from sMenu import Menu class software: @staticmethod def runShowTables(): #подключаем библиотеку import xml.dom.minidom as minidom from sMenu import Menu #читаем XML из файла dom = minidom.parse("myShop.xml") dom.normalize() #Читаем таблицу def ...
1,684
734
import time, sys, os, hashlib, json, re import requests, random, js2py import urllib.request import urllib.parse # 检验是否含有中文字符 def language(strs): for char in strs: if (u'\u4e00' <= char and char <= u'\u9fff'): return 'zh', 'en' # 含有中文 return 'en', 'zh' # 不含有中文 class Baidu(): def __...
22,963
10,385
import xNormal xNormal.run("piano_high.obj", "piano_low.obj", "piano.png", width=256, height=256, gen_normals = True, gen_ao = True)
132
56
from typing import Sequence, Any, Optional from . import BaseRankingEvaluator class RecallEvaluator(BaseRankingEvaluator): """A :class:`RecallEvaluator` evaluates the Precision of the search. It computes how many of the first given `eval_at` groundtruth are found in the matches """ metric = 'Reca...
1,266
355
"""Test CLI usage.""" import logging import subprocess # nosec import sys from functools import wraps from os import linesep from tqdm.cli import TqdmKeyError, TqdmTypeError, main from tqdm.utils import IS_WIN from .tests_tqdm import BytesIO, _range, closing, mark, raises def restore_sys(func): """Decorates `f...
7,995
2,961
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @REQUEST_M0viz from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from script import script @Client.on_message(filters.command(["start"]) & filters.private) async def start(client, message): try: awa...
2,881
942
from copy import deepcopy from typing import Tuple import jax.numpy as jnp from jax.scipy.linalg import cho_factor, cho_solve from multipledispatch import dispatch from .types import Array def I(n: int) -> Array: """ Compute an n x n identity matrix. :param n: The size of of the matrix. :return: An ...
3,583
1,047
import os def replace_version(old_version, new_version): if not isinstance(old_version, tuple) or not isinstance(new_version, tuple): raise ValueError("`old_version` and `new_version` must be a version tuple. Eg: (1.2.3)") major, minor, micro = old_version[:3] old_version = f'{major}.{minor}.{mic...
999
346
import argparse import math import matplotlib.pyplot as plt import os import numpy as np import shutil import pandas as pd import seaborn as sns sns.set() sns.set_context("talk") NUM_BINS = 100 path = '../Data/Video_Info/Pensieve_Info/PenieveVideo_video_info' video_mappings = {} video_mappings['300'] = '320x180x30_v...
10,625
3,754
from typing import TYPE_CHECKING, Any, Dict, List from aiopoke.utils.minimal_resources import MinimalResource from aiopoke.utils.resource import Resource if TYPE_CHECKING: from aiopoke.objects.resources import EncounterConditionValue, EncounterMethod class Encounter(Resource): min_level: int max_level: ...
936
272
def read_file(test = True): if test: filename = '../tests/day1.txt' else: filename = '../input/day1.txt' with open(filename) as file: temp = list() for line in file: temp.append(line.strip()) return temp def puzzle1(): temp = read_file(False)[0] floo...
834
267
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup setup(name='starsearch', version='0.3', description='Package to dig into the ESO archives', author='João Camacho', author_email='joao.camacho@astro.up.pt', license='MIT', url='https://github.com/jdavidrcamac...
466
155
import os import tempfile from unittest.mock import patch from galaxy.exceptions import ( ObjectNotFound, ReferenceDataError, ) from galaxy_test.driver import integration_util BUILDS_DATA = ( "?\tunspecified (?)", "hg_test\tdescription of hg_test", "hg_test_nolen\tdescription of hg_test_nolen", ) ...
4,192
1,440
import numpy as np import pandas as pd import os from tqdm import tqdm import pacmap import matplotlib.pyplot as plt from sklearn.manifold import TSNE import umap def darius1(numberDirectory): path = "" if(numberDirectory == 1): directorys = [ ['training_setA/training/', 'p0'] ] ...
2,310
841
# Copyright (c) 2013 Yubico AB # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditi...
5,757
1,856
# Credit goes to https://bitbucket.org/spookylukey/django-fabfile-starter/src import os import datetime as dt from io import StringIO import json import posixpath import fabric import requests from fabsettings import (USER, HOST, DJANGO_APP_NAME, DJANGO_APPS_DIR, LOGS_ROOT_DIR, ...
10,949
3,505
import torch from torch import nn from torch.autograd import Variable import config def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_normal_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) def conv(in_chann...
5,273
1,957
# Copyright 2021 Michael Olson # # 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 to in wri...
6,264
1,861
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
13,750
4,782
# coding:utf-8 #!/usr/bin/python # # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # # ------------------------------------------------------------------------...
13,948
5,426
import torch import torchvision.datasets as datasets import torchvision.transforms as transforms from lib.data.data_util import ImageNetPolicy, ToBGRTensor from lib.config import cfg from lib.data.transformer_v2 import get_transforms def finetune_imagenet(): transformation = get_transforms(input_size=cfg.dataset...
1,958
614
# -*- encoding: utf-8 -*- try: import unittest2 as unittest except ImportError: import unittest from multiprocessing import Manager from random import randint import logging import sys import os import copy import shutil # add kamma path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dir...
6,519
2,324
#!/usr/bin/env python import freenect import matplotlib.pyplot as mp import frame_convert import signal keep_running = True def get_depth(): return frame_convert.pretty_depth(freenect.sync_get_depth()[0]) def get_video(): return freenect.sync_get_video()[0] def handler(signum, frame): """Sets up the ...
855
304
#import models from models.modules.LPIPS import perceptual_loss as models #################### # metric #################### model = None def calculate_lpips(img1_im, img2_im, use_gpu=False, net='squeeze', spatial=False): '''calculate Perceptual Metric using LPIPS img1_im, img2_im: BGR image from [0,255] ...
1,189
430
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
59,338
23,278
import typing if typing.TYPE_CHECKING: from evntbus.bus import Bus def listen_decorator(evntbus: 'Bus'): class ListenDecorator(object): def __init__(self, event: typing.Type, priority: int = 5): self.event = event self.priority = priority def __call__(self, f: typing....
456
142
# crestprocessor.py import threading from PySide import QtCore from crest.crest import Crest class CrestProcessor(QtCore.QObject): """ CREST Middle-ware """ login_response = QtCore.Signal(str) logout_response = QtCore.Signal() location_response = QtCore.Signal(str) destination_response = ...
1,481
470
# -*- coding: utf-8 -*- import click from src.commands.project import Project from src.commands.server import Server from src.commands.config import WebServer from src.common.context import CommandContext from src.common.decorators import settings, update_config_file class Pipeline: @staticmethod @setting...
4,496
1,288
from pybuilder.core import use_plugin, init use_plugin("python.core") use_plugin("python.unittest") use_plugin("python.install_dependencies") use_plugin("python.flake8") use_plugin("python.coverage") name = "ActionServerPybuilder" default_task = ['install_dependencies', 'analyze', 'publish'] @init def set_properties...
1,341
446
#!/usr/bin/env python2 # -*- mode: python -*- # # Electrum - lightweight Bitcoin client # Copyright (C) 2016 The Electrum developers # # 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...
4,278
1,231
import unittest from seattle_flu_incidence_mapper.utils import get_model_id class TestGetIdFromQuery(unittest.TestCase): def test_ids_match_expected(self): ids = { "f39442e6883958971ecc1d0213c59f91": {"model_type":"inla","observed":["encountered_week","flu_shot","PUMA5CE","sampling_location"...
631
254
import csv input = open('MovieI.csv', 'rb') output = open('MovieO.csv', 'wb') writer = csv.writer(output) for row in csv.reader(input): for i in range(len(row)): if(row[0]==''): break elif(row[1]==''): break elif(row[2]==''): break elif(row[3]==''...
445
153
from django.apps import AppConfig class VenuesConfig(AppConfig): name = "venues"
87
28
""" The key is to use a set to remember if we seen the node or not. Next, think about how we are going to *remove* the duplicate node? The answer is to simply link the previous node to the next node. So we need to keep a pointer `prev` on the previous node as we iterate the linked list. So, the solution. Create a set ...
1,137
323
from __future__ import absolute_import from __future__ import unicode_literals import six from django.conf import settings from django.contrib.auth.signals import user_logged_in from corehq.apps.analytics.tasks import ( track_user_sign_in_on_hubspot, HUBSPOT_COOKIE, update_hubspot_properties, identify,...
3,344
1,041
from app import create_app, db from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = create_app("develop") manager = Manager(app) Migrate(app, db) manager.add_command("db", MigrateCommand) # 初始化管理员账号数据,添加manager命令 @manager.command def create_admin(): from app.models import Admi...
775
273
#!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework from unicorn.x86_const import ( UC_X86_REG_AX, UC_X86_REG_EAX, UC_X86_REG_RAX, UC_X86_REG_RCX, UC_X86_REG_RDI, UC_X86_REG_RDX, UC_X86_REG_RSI, UC_X86_REG_R8, UC_X86_REG_R9, UC_X86_REG_R10 ) from qiling import Qili...
2,954
1,336
### ----------- Python Code ------------### import csv from flask import Flask, render_template from flask_ask import Ask, statement, question, session import pandas as pd ### ------------- Start Alexa Stuff ---------### app = Flask(__name__) ask = Ask(app, "/") #logging.getLogger("flask_ask").setLevel(logging.DE...
2,639
884
import abc ''' Interfaz sobre la cual todo modelo implementa. Todo modelo dentro de la biblioteca hklearn implementa los siguientes comportamientos: -fit : Entrena el modelo con un a matriz de ejemplos X y sus respectivas etiquetas y -predict : El modelo entrenado, predice con base en una entrada X ...
846
260
# Copyright 2021 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://aws.amazon.com/apache2.0/ # # or in the "license" file acco...
35,951
11,997
from matchms import utils class Curator: """ Curator makes sure that all data is curated before the actual annotation can proceed. Currently, fixing CAS numbers to correct format is supported. """ def curate_spectra(self, spectra): """ Iterates over given spectrums and curates indi...
1,944
519
#!/usr/bin/env python # encoding=utf-8 # Copyright © 2017-2018 Intel Corporation # 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 ...
2,498
839
#!/usr/bin/env python import os import sys def midi_to_freq(num): """ Takes a MIDI number and returns a frequency in Hz for corresponding note. """ num_a = num - 69 freq = 440 * 2**(num_a / 12.0) return freq def fp(relative): #if hasattr(sys, "_MEIPASS"): # return os.path.join(sys._MEIPASS,...
478
201
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import os import sys import shutil import inspect from ferenda import TextReader, util from ferenda.testutil import RepoTester, file_parametrize from ferenda.compa...
2,896
863
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import...
2,319
1,148
from plumbum import local import benchbuild as bb from benchbuild.environments.domain.declarative import ContainerImage from benchbuild.source import HTTP from benchbuild.utils.cmd import make, tar class XZ(bb.Project): """ XZ """ VERSION = '5.2.1' NAME = 'xz' DOMAIN = 'compression' GROUP = 'benc...
2,652
964
import numpy as np import csv import cv2 from keras.models import Sequential from keras.layers import Dense, Flatten def load_data(): lines = [] with open('Data/driving_log.csv') as csvfile: reader = csv.reader(csvfile) for line in reader: lines.append(line) images = [] mea...
1,101
384
from abc import get_cache_token from collections import OrderedDict from torch import nn class ResidualBlock(nn.Module): def __init__(self, in_size, out_size): super().__init__() self.in_size, self.out_size = in_size, out_size self.blocks = nn.Identity() self.shortcut = nn.Identit...
3,226
1,115
""" Tests asserting that ModelTypes convert to and from json when working with ModelDatas """ # Allow inspection of private class members # pylint: disable=protected-access from mock import Mock from xblock.core import XBlock from xblock.fields import Field, Scope, ScopeIds from xblock.field_data import DictFieldData ...
2,114
645
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
10,592
3,408
from __future__ import division, print_function, absolute_import from .core import SeqletCoordinates from modisco import util import numpy as np from collections import defaultdict, Counter, OrderedDict import itertools import sys import time from .value_provider import ( AbstractValTransformer, AbsPercentileValTra...
42,844
13,839
import sys def lastWord ( inputString ): results = [] outputString = inputString[0] for i in range(1, len(inputString)): intermediateString = sorted([outputString + inputString[i], inputString[i] + outputString ]) outputString = intermediateString[1] return outputString numTests = in...
425
132
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # ...
62,817
18,280
# # Copyright (c) 2019 One Identity # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, di...
3,908
1,273
import json from django.utils.translation import ugettext as _ from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django.utils.encoding import smart_str from django.shortcuts import render_to_response from forum.modules import decorate from forum import views fro...
2,997
840
""" Translate an element, which is described by the YAML method file and a descriptor file, into a target function. Procedure: 1. When analyzing a YAML file, parse the call to the method-element, to get: - list of inputs, - list of outputs 2. Parse the YAML of that element, to know the name of the inputs and outputs...
7,077
2,144
#!/usr/bin/env python3 import csv import gzip import json import networkx as nx import sys import time import utils from argparse import ArgumentParser from calculate_activity_network import embedded_extended_tweet_url, root_of_conversation from collections import defaultdict from datetime import datetime from utils ...
16,351
5,760