text
string
size
int64
token_count
int64
import os import unittest from flask import current_app from flask_testing import TestCase from core import masakhane class TestDevelopmentConfig(TestCase): def create_app(self): masakhane.config.from_object('core.config.DevelopmentConfig') return masakhane def test_app_is_development(self)...
1,472
463
from flask import Blueprint from controllers.show import shows, create_shows, create_show_submission show_bp = Blueprint('show_bp', __name__) show_bp.route('/', methods=['GET'])(shows) show_bp.route('/create', methods=['GET'])(create_shows) show_bp.route('/create', methods=['POST'])(create_show_submission)
311
104
from .gfpgan import *
22
10
#!/usr/bin/python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Module that finds and runs a binary by looking in the likely locations.""" import os import subprocess import sys def run_comman...
1,950
589
from django.contrib.auth import get_user_model from django.test import TestCase # Create your tests here. class UserManagersTests(TestCase): def test_create_user(self): User = get_user_model() user = User.objects.create_user( email="normal@user.com", password="testing@123") s...
1,599
471
import os import asposewordscloud import asposewordscloud.models.requests from asposewordscloud.rest import ApiException from shutil import copyfile words_api = WordsApi(client_id = '####-####-####-####-####', client_secret = '##################') file_name = 'test_doc.docx' # Upload original document to cloud stora...
728
236
import json import os import sys import time from agogosml.common.abstract_streaming_client import find_streaming_clients from agogosml.tools.sender import send from agogosml.tools.receiver import receive eh_base_config = { "EVENT_HUB_NAMESPACE": os.getenv("EVENT_HUB_NAMESPACE"), "EVENT_HUB_NAME": os.getenv("...
2,577
1,055
#Filename="finanzassistent" #Type=Prerun import os def main(): ctx.gui_setMainLabel("Postbank Finanzassistent: Extracting key"); error="" dbkey="73839EC3A528910B235859947CC8424543D7B686" ctx.gui_setMainLabel("Postbank: Key extracted: " + dbkey) if not (ctx.fs_sqlcipher_decrypt(filename, ...
512
195
# Copyright 2016 Cisco Systems, 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 agreed to in writin...
1,615
528
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: """ [1,3,1] [1,5,1] [4,2,1] time O (nm) space O(nm) state -> sums[r][c] = min path sum till r, c position initial state -> sums[0][0…cols] = inf -> sums...
1,047
383
# -*- coding: utf-8 -*- """ proxy.py ~~~~~~~~ ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on Network monitoring, controls & Application development, testing, debugging. :copyright: (c) 2013-present by Abhinav Singh and contributors. :license: BSD, see LICENSE...
1,293
411
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from datetime import datetime from api_request import Weather builder = Gtk.Builder() builder.add_from_file('./glade/main.glade') class Handler: def __init__(self, *args, **kwargs): super(Handler, self).__init__(*args, **kwargs...
8,974
3,032
#----------------------------------------------------- # Mimas: conference submission and review system # (c) Allan Kelly 2016-2020 http://www.allankelly.net # Licensed under MIT License, see LICENSE file # ----------------------------------------------------- import unittest from google.appengine.ext import testbed ...
3,186
1,200
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ------------------------------------------------- @ Author : pengj @ date : 2018/11/26 19:28 @ IDE : PyCharm @ GitHub : https://github.com/JackyPJB @ Contact : pengjianbiao@hotmail.com ---------------...
63,620
60,453
from django.urls import path from .api import * from knox import views as knox_views urlpatterns = [ #domain.dn/api/v1/register/ | POST path('register/' , SignUpAPI.as_view() , name='register'), #domain.dn/api/v1/register/ | POST path('login/' , SignInAPI.as_view() , name='login'), #domain.dn/ap...
393
145
import re from itertools import combinations from utils.solution_base import SolutionBase class Solution(SolutionBase): def solve(self, part_num: int): self.test_runner(part_num) func = getattr(self, f"part{part_num}") result = func(self.data) return result def test_runner(s...
2,985
998
from portfolios.factories.skill_factory import create_skills_with_factory from django.db import transaction from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Generates dummy data" def _generate_dummy_data(self): # Create dummy data create_skills_with_fact...
520
150
import unittest import mock import requests import httpretty import settings from bitfinex.client import Client, TradeClient API_KEY = settings.API_KEY API_SECRET = settings.API_SECRET class BitfinexTest(unittest.TestCase): def setUp(self): self.client = Client() def test_should_have_server(self):...
8,397
3,343
import networkx as nx import pickle from bokeh.io import show, output_file from bokeh.plotting import figure from bokeh.models.graphs import from_networkx processed_data_folder = 'C:\\Users\\Alex\\Documents\\GitHub\\insight-articles-project\\data\\processed\\' filename = processed_data_folder + 'graph_and_labels' wi...
834
316
#!/usr/bin/env python # encoding=utf-8 from inspect import getblock import json import os from os import read from numpy.core.fromnumeric import mean import numpy as np import paddlehub as hub import six import math import random import sys from util import read_file from config import Config # 配置文件 conf = Config() c...
15,737
5,709
""" GroupBunk v.1.2 Leave your Facebook groups quietly Author: Shine Jayakumar Github: https://github.com/shine-jayakumar LICENSE: MIT """ from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.common.exceptions imp...
8,778
2,700
import numpy as np import numpy.linalg as la from MdlUtilities import Field, FieldList import MdlUtilities as mdl def get_osaCasing_fields(): OD = Field(2030) ID = Field(2031) Weight = Field(2032) Density = Field(2039) E = Field(2040) osaCasing_fields = FieldList() osaCasing_...
11,575
5,244
"""Test converting an image to a pyramid. """ import numpy as np import napari points = np.random.randint(100, size=(50_000, 2)) with napari.gui_qt(): viewer = napari.view_points(points, face_color='red')
212
83
from unittest import TestCase from mock import patch from .. import constants class mock_service_exeTestCase(TestCase): def setUp(self): super(mock_service_exeTestCase, self).setUp() self.addCleanup(patch.stopall) self.mock_os = patch.object(constants, 'os', autospec=True).start() d...
1,166
382
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015, 2016, 2017 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Li...
2,555
767
import pytest from array import array from game_map import GameMap from tests.conftest import get_relative_path sample_map_data = tuple( reversed( ( array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)), array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0...
3,145
1,937
# encoding: utf-8 from __future__ import unicode_literals import six from django.db.models import Manager from django.db.models.query import QuerySet from .compat import (ANNOTATION_SELECT_CACHE_NAME, ANNOTATION_TO_AGGREGATE_ATTRIBUTES_MAP, chain_query, chain_queryset, ModelIterable, ValuesQuery...
14,855
3,535
from __future__ import print_function, absolute_import import unittest, math import pandas as pd import numpy as np from . import * class T(base_pandas_extensions_tester.BasePandasExtensionsTester): def test_concat(self): df = pd.DataFrame({'c_1':['a', 'b', 'c'], 'c_2': ['d', 'e', 'f']}) df.en...
11,759
6,329
import os import sys from setuptools import find_packages, setup, Extension try: # for pip >= 10 from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from setuptools_rust import RustExtension except ImportError: import subprocess errno...
2,353
737
import numpy as np import math import pyrobot.utils.util as prutil import rospy import habitat_sim.agent as habAgent import habitat_sim.utils as habUtils from habitat_sim.agent.controls import ActuationSpec import habitat_sim.errors import quaternion from tf.transformations import euler_from_quaternion, euler_from_mat...
9,041
2,854
from django.contrib import admin from .models import Chat class ChatAdmin(admin.ModelAdmin): list_display = ("pk",) admin.site.register(Chat, ChatAdmin)
164
57
# -*- coding: utf-8 -*- from pythainlp.tokenize import etcc print(etcc.etcc("คืนความสุข")) # /คืน/ความสุข
109
62
#!/usr/bin/env python from cumulogenesis.interfaces import cli cli.run()
75
27
from __future__ import division import logging from nanpy.i2c import I2C_Master from nanpy.memo import memoized import time log = logging.getLogger(__name__) def to_s16(n): return (n + 2 ** 15) % 2 ** 16 - 2 ** 15 class Bmp180(object): """Control of BMP180 Digital pressure sensor (I2C) calculation i...
2,897
1,213
import logging import argh import pygna.command as cmd import pygna.painter as paint import pygna.utils as utils import pygna.block_model as bm import pygna.degree_model as dm """ autodoc """ logging.basicConfig(level=logging.INFO) def main(): argh.dispatch_commands([ # network summary and graph file ...
1,539
521
""" PyColourChooser Copyright (C) 2002 Michael Gilfix <mgilfix@eecs.tufts.edu> This file is part of PyColourChooser. This version of PyColourChooser is open source; you can redistribute it and/or modify it under the licensed terms. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRA...
4,752
1,428
import json import csv import pandas as pd from isic_api import ISICApi from pandas.io.json import json_normalize # Initialize the API; no login is necessary for public data api = ISICApi(username="SkinCare", password="unbdeeplearning") outputFileName = 'imagedata' imageList = api.getJson('image?limit=25000&offset=0&...
1,807
549
#!/usr/bin/env python """ generate-all-graphs.py python generate-all-graphs.py | gzip -c > all-graphs.gz """ import sys import json import itertools import numpy as np from tqdm import tqdm from nasbench.lib import graph_util from joblib import delayed, Parallel max_vertices = 7 num_ops = 3 max_edges ...
1,317
494
# FIXME: fix all "happy paths coding" issues import liblo from threading import Thread class Mext(object): device = None def __init__(self, device_port=5000): self.device_receiver = liblo.ServerThread(device_port) self.device_receiver.add_method("/monome/grid/key", "iii", self.on_grid_key) ...
1,500
479
import json import os import pytest from datetime import datetime, timedelta import boto3 from httmock import urlmatch, HTTMock from moto import mock_s3 from app import storage as test_storage from data import model, database from data.logs_model import logs_model from storage import S3Storage, StorageContext, Dist...
5,370
1,639
""" The base top-level plot model class. From this all data and plotting flow. """ from pageplot.exceptions import PagePlotParserError from pathlib import Path from typing import Any, Optional, Dict, List, Union from pageplot.extensionmodel import PlotExtension from pageplot.extensions import built_in_extensions fro...
6,699
1,840
from bs4 import BeautifulSoup as soup from selenium import webdriver class Scrapper: def getArticles(self, cryptoName): url = 'https://coinmarketcap.com/currencies/' + cryptoName + '/news/' driver = webdriver.Firefox() driver.get(url) page = driver.page_source page_soup = ...
853
296
#!/usr/bin/python3 """qsubm -- generic queue submission for task-oriented batch scripts Environment variables: MCSCRIPT_DIR should specify the directory in which the mcscript package is installed, i.e., the directory where the file qsubm.py is found. (Note that qsubm uses this information to locate c...
19,409
5,803
from ctypes import * class Node(Structure): pass Node._fields_ = [ ("leaf", c_int), ("g", c_float), ("min_samples", c_int), ("split_ind", c_int), ("split", c_float), ("left", POINTER(Node)), ("right", POINTER(Node))] trees = CDLL("./trees.so") trees.get_root.argtypes = (c_int, ) trees.get...
504
194
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
2,657
755
# coding: utf-8 """ Pure Storage FlashBlade REST 1.12 Python SDK Pure Storage FlashBlade REST 1.12 Python SDK. Compatible with REST API versions 1.0 - 1.12. Developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/...
8,080
2,247
import pytest from tests.actions.support.mouse import assert_move_to_coordinates, get_center from tests.actions.support.refine import get_events, filter_dict _DBLCLICK_INTERVAL = 640 # Using local fixtures because we want to start a new session between # each test, otherwise the clicks in each test interfere with ...
3,789
1,231
class BaseHandler: def send(self, data, p): pass def recv(self, data, p): pass def shutdown(self, p, direction=2): pass def close(self): pass
194
66
from typing import Any, Text, Dict, List from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from utils import convert_timestamp from rasa_sdk.events import AllSlotsReset import datetime from datetime import timedelta, date import dateutil.parser import boto3 from boto3.dynamodb.cond...
2,842
1,121
from scripts.downloader import * import fiona from shapely.geometry import shape import geopandas as gpd import matplotlib.pyplot as plt from pprint import pprint import requests import json import time import os # Constant variables input_min_lat = 50.751797561 input_min_lon = 5.726110232 input_max_lat = 50.938216069...
4,688
1,737
""" Script for serving a trained chatbot model over http """ import datetime import click from os import path from flask import Flask, request, send_from_directory from flask_cors import CORS from flask_restful import Resource, Api import general_utils import chat_command_handler from chat_settings import ChatSettings...
3,185
965
import twilltestlib import twill from twill import namespaces, commands from twill.errors import TwillAssertionError from mechanize import BrowserStateError def setup_module(): global url url = twilltestlib.get_url() def test_select_multiple(): namespaces.new_local_dict() twill.commands.reset_browser(...
1,907
638
# Copyright 2011 Nicholas Bray # # 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...
894
350
enru=open('en-ru.txt','r') input=open('input.txt','r') output=open('output.txt','w') s=enru.read() x='' prov={'q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'} slovar={} s=s.replace('\t-\t',' ') while len(s)>0: slovar[s[:s.index(' ')]]=s[s.index(' '):s.index('\...
657
301
#!/usr/bin/env python """ Siamese networks ================ """ import random import numpy as np import matplotlib.pyplot as plt from matplotlib import offsetbox import deeppy as dp # Fetch MNIST data dataset = dp.dataset.MNIST() x_train, y_train, x_test, y_test = dataset.data(flat=True, dp_dtypes=True) # Normaliz...
2,485
1,055
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
1,580
482
from twisted.internet import defer, task from twisted.python.failure import Failure from exchanges.base import ExchangeService from exchange import calcVirtualOrderBooks import copy import time def defaultErrHandler(failure): print(failure.getBriefTraceback()) return failure def handleMultipleErr(data): ...
12,988
3,525
import os from schema import Or from testplan.common.config import ConfigOption from ..base import ProcessRunnerTest, ProcessRunnerTestConfig from ...importers.cppunit import CPPUnitResultImporter, CPPUnitImportedResult class CppunitConfig(ProcessRunnerTestConfig): """ Configuration object for :py:class:`~...
7,989
2,225
import discord.ext.commands as dec import database.song from commands.common import * class Song: """Song insertion, querying and manipulation""" def __init__(self, bot): self._bot = bot self._db = database.song.SongInterface(bot.loop) _help_messages = { 'group': 'Song informatio...
8,191
2,320
""" main.py Main driver for the Linear Error Analysis program. Can be run using `lea.sh`. Can choose which plots to see by toggling on/off `show_fig` param. Author(s): Adyn Miles, Shiqi Xu, Rosie Liang """ import os import matplotlib.pyplot as plt import numpy as np import config import libs.gta_xch4 as gta_xch4 i...
2,468
980
"""Enum for amino acid.""" from enum import Enum from typing import Dict, TypedDict class AcidityBasicity(Enum): """Enum for acidity and basicity.""" U = 3 # Neutral A = 1 # Acid B = 2 # Base class Charge(Enum): """Enum for charge.""" U = 3 # Neutral P = 1 # Positive N = 2 #...
7,153
3,020
import logging import os import re import sublime # external dependencies (see dependencies.json) import jsonschema import yaml # pyyaml # This plugin generates a hidden syntax file containing rules for additional # chainloading commands defined by the user. The syntax is stored in the cache # directory to avoid the...
8,550
2,618
import os import numpy as np import sys sys.path.append("../") for model in ['lenet1', 'lenet4', 'lenet5']: for attack in ['fgsm', 'cw', 'jsma']: for mu_var in ['gf', 'nai', 'ns', 'ws']: os.system('CUDA_VISIBLE_DEVICES=0 python retrain_mu_mnist.py --datasets=mnist --attack=' + attack + ' --mode...
378
154
#!/usr/bin/env python3 from __future__ import print_function import gzip import json import re import sys # import time from argparse import ArgumentParser # from datetime import datetime class Options: def __init__(self): self.usage = 'characterise_inauthentic_tweets.py -i <file of tweets> [-v|--verbos...
5,197
1,837
import inspect import hashlib import logging import os from django.core.files.uploadedfile import TemporaryUploadedFile from django.db.models import FieldDoesNotExist from django.db.models.fields.files import FileField from django.http import QueryDict from django.utils.datastructures import MultiValueDict logger = l...
3,577
949
# coding=utf-8 from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from bika.lims.browser.bika_listing import BikaListingTable from bika.lims.browser.worksheet.views.analyses import AnalysesView class AnalysesTransposedView(AnalysesView): """ The view for displaying the table of manage_results...
4,228
1,125
from rest_framework import viewsets from .models import User, Photo from .serializers import UserSerializer, PhotoSerializer from .mixins import RequestLogViewMixin from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated, IsAuthenticate...
865
221
def conv(x): return int(''.join(t[c] for c in x)) b = input().split() N = int(input()) a = [input() for _ in range(N)] t = {b[i]: str(i) for i in range(10)} a.sort(key = lambda x: conv(x)) print(*a, sep='\n')
215
97
#!/usr/bin/env python """The setup script.""" from setuptools import setup, find_packages with open("README.adoc") as fh_readme: readme = fh_readme.read() install_reqs = [] setup( author="Sven Wilhelm", author_email='refnode@gmail.com', python_requires='>=3.8', classifiers=[ 'Developmen...
965
334
'''*-----------------------------------------------------------------------*--- Author: Jason Ma Date : Oct 18 2018 TODO File Name : pid.py Description: TODO ---...
4,126
1,776
# Copyright 2021 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, ...
32,091
9,153
from __future__ import absolute_import, division import os import fitsio import argparse import numpy as np from desiutil.log import get_logger from desispec.io import read_fiberflat,write_fiberflat,findfile,read_frame from desispec.io.fiberflat_vs_humidity import get_humidity,read_fiberflat_vs_humidity from desisp...
4,814
1,612
IS_TEST = True REPOSITORY = 'cms-sw/cmssw' def get_repo_url(): return 'https://github.com/' + REPOSITORY + '/' CERN_SSO_CERT_FILE = 'private/cert.pem' CERN_SSO_KEY_FILE = 'private/cert.key' CERN_SSO_COOKIES_LOCATION = 'private/' TWIKI_CONTACTS_URL = 'https://ppdcontacts.web.cern.ch/PPDContacts/ppd_contacts' TWI...
1,856
672
from enum import Enum from typing import Generator, Tuple, Iterable, Dict, List import cv2 import matplotlib.pyplot as plt import numpy as np import seaborn as sns from scipy.ndimage import label, generate_binary_structure from scipy.ndimage.morphology import distance_transform_edt as dist_trans import trainer.lib as...
5,748
2,264
from PyQt5.QtCore import Qt, pyqtSignal, QSize from PyQt5.QtWidgets import ( QLabel, QWidget, QTreeWidgetItem, QHeaderView, QVBoxLayout, QHBoxLayout, ) from .ImageLabel import ImageLabel from .AdaptiveTreeWidget import AdaptiveTreeWidget class ImageDetailArea(QWidget): # signal imageLoaded = pyqtSig...
7,613
2,369
import argparse import data_helper from sklearn.model_selection import train_test_split import re import lstm from lstm import * import time from viterbi import Viterbi xrange = range def simple_cut(text,dh,lm,viterbi): """对一个片段text(标点符号把句子划分为多个片段)进行预测。""" if text: #print("text: %s" %text) te...
3,005
1,281
# -*- coding: utf-8 -*- """ Created on Sat Feb 24 23:18:54 2018 @author: Rupesh """ # Multiple Linear Regression import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.style.use("ggplot") # loading dependies df = pd.read_csv("50_Startups.csv") df.head() X = df.iloc[:, :-...
930
366
#!/usr/bin/env python ''' Advent of Code 2021 - Day 9: Smoke Basin (Part 1) https://adventofcode.com/2021/day/9 ''' import numpy as np class HeightMap(): def __init__(self) -> None: self._grid = np.array([]) def add_row(self, row): np_row = np.array(row) if self._grid.size != 0: ...
2,945
883
"""Trigonometric and Hyperbolic Functions""" from typing import Callable import numpy from pipda import register_func from ..core.contexts import Context from ..core.types import FloatOrIter from .constants import pi def _register_trig_hb_func(name: str, np_name: str, doc: str) -> Callable: """Register trigono...
3,830
1,482
# Implementation of Randomised Selection """ Naive Approach --------- Parameters --------- An arry with n distinct numbers --------- Returns --------- i(th) order statistic, i.e: i(th) smallest element of the input array --------- Time Complexity --------- O(n.log...
1,463
487
import re from .common import regex_labels, re_number, re_string keywords = ['TODO'] re_keyword = re.compile(r'\b({})\b'.format('|'.join(keywords))) def init(document): document.OnGenerateLabeling.add(main) def main(document): regex_list = [(re_keyword, 'keyword'), (re_number, 'number'), (re_string, 'stri...
365
128
#!/usr/bin/env python import cgitb; cgitb.enable() print('Content-type: text/html\n') print( """<html> <head> <title>CGI 4 - CSS</title> <link rel="stylesheet" type="text/css" href="../css/estilo1.css"> </head> <body> <h1>Colocando CSS em um script a parte</h1> <hr> <p>Ola imagens CGI!</p> <di...
490
235
""" GNG vs SOM comparison example for PLASTK. This script shows how to: - Train PLASTK vector quantizers (SOM and GNG) - Set default parameters - Create a simple agent and environment. - Run an interaction between the agent and the environment with a GUI. $Id: gngsom.py,v 1.3 2006/02/17 19:40:09 jp Exp $ ...
4,769
1,511
import sublime from ui.read import settings as read_settings from ui.write import write, highlight as write_highlight from lookup import file_type as lookup_file_type from ui.read import x as ui_read from ui.read import spots as read_spots from ui.read import regions as ui_regions from core.read import read as core_rea...
3,444
1,069
from __future__ import absolute_import, division, print_function, unicode_literals import braintree from postgres.orm import Model class ExchangeRoute(Model): typname = "exchange_routes" def __bool__(self): return self.error != 'invalidated' __nonzero__ = __bool__ @classmethod def fro...
3,745
1,075
""" Defines a form to provide validations for course-specific configuration. """ from django import forms from openedx.core.djangoapps.video_config.forms import CourseSpecificFlagAdminBaseForm from openedx.core.djangoapps.video_pipeline.models import ( CourseVideoUploadsEnabledByDefault, VEMPipelineIntegration...
805
224
import os from os.path import dirname from unittest import TestCase import src.superannotate as sa class TestCloneProject(TestCase): PROJECT_NAME_1 = "test create from full info1" PROJECT_NAME_2 = "test create from full info2" PROJECT_DESCRIPTION = "desc" PROJECT_TYPE = "Vector" TEST_FOLDER_PATH...
1,779
568
import os import functools CORPUS_DIR = str(os.getcwd())[:str(os.getcwd()).index('spellingcorrector/')] \ + 'data/corpus.txt' NWORD = {} def checkCorpus(fn): @functools.wraps(fn) def new_func(*args, **kwargs): t = os.path.isfile(CORPUS_DIR) if t == False: raise IOEr...
903
335
import logging from rhasspy_weather.data_types.request import WeatherRequest from rhasspy_weather.parser import rhasspy_intent from rhasspyhermes.nlu import NluIntent log = logging.getLogger(__name__) def parse_intent_message(intent_message: NluIntent) -> WeatherRequest: """ Parses any of the rhasspy weathe...
653
213
""" 59.40% 其实是大数相加 """ class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ num1_index = len(num1) - 1 num2_index = len(num2) - 1 if num1_index < 0: return num2 if num2_inde...
1,028
349
import logging log = logging.getLogger(__name__) import json import requests import requests.exceptions import botologist.plugin BASE_URL = 'https://qdb.lutro.me' def _get_quote_url(quote): return BASE_URL + '/' + str(quote['id']) def _get_qdb_data(url, query_params): response = requests.get(url, query_params, ...
2,770
1,168
from pyldapi.renderer import Renderer from pyldapi.view import View from flask import render_template, Response from rdflib import Graph, URIRef, BNode import skos from skos.common_properties import CommonPropertiesMixin from config import Config class Method(CommonPropertiesMixin): def __init__(self, uri): ...
2,889
829
# Copyright 2019-2020 the .NET Foundation # Distributed under the terms of the revised (3-clause) BSD license. """Interacting with the WWT Communities APIs.""" import json import os.path import requests import sys from urllib.parse import parse_qs, urlparse from . import APIRequest, Client, enums __all__ = ''' Comm...
22,791
6,527
import pytest def vprintf_test(vamos): if vamos.flavor == "agcc": pytest.skip("vprintf not supported") vamos.run_prog_check_data("vprintf")
158
59
#!/usr/bin/env python3 import socket HOST = '127.0.0.1' # 服务器的主机名或者 IP 地址 PORT = 10009 # 服务器使用的端口 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: print(s) s.connect((HOST, PORT)) s.sendall(b'Hello, world') print(s) data = s.recv(1024) print('Received', repr(data))
304
153
import requests import Mark from colorama import Fore from util.plugins.common import print_slow, getheaders, proxy def StatusChanger(token, Status): #change status CustomStatus = {"custom_status": {"text": Status}} #{"text": Status, "emoji_name": "☢"} if you want to add an emoji to the status try: ...
752
246
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from hashlib import sha256 from recipe_engine import recipe_test_api class CloudBuildHelperTestApi(recipe_test_api.RecipeTestApi): def build_success_out...
1,979
692
import sklearn.mixture import matplotlib.pyplot as plt import numpy as np from matplotlib import ticker import matplotlib.patheffects as mpatheffects def get_gmm_and_pos_label( array, n_components=2, n_steps=5000 ): gmm = sklearn.mixture.GaussianMixture( n_components=n_components, covarianc...
7,011
2,789
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
4,627
1,971
#!/usr/bin/python3 import tkinter as tk from tkinter import messagebox as msg from tkinter.ttk import Notebook from tkinter import ttk import tkinter.font as font import requests class LanguageTab(tk.Frame): def __init__(self, master, lang_name, lang_code): super().__init__(master) # fonts for ...
6,892
2,271