text
string
size
int64
token_count
int64
# **************************************************************************** # # # # ::: :::::::: # # logger.py :+: :+: :+...
1,630
480
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################### # Author: Mu yanru # Date : 2019.2 # Email : muyanru345@163.com ################################################################### from dayu_widgets.avatar import MAvatar from dayu_widgets.divider import...
2,550
813
#Assignment 9.4 #print('Hello World') fname = input('Enter name: ') if len(fname) < 1 : fname = 'mbox-short.txt' handle = open(fname) di = {} #create an empty dictionary for line in handle: line = line.rstrip() wds = line.split() #the second for-loop to print each word in the list for w in wds : ...
1,254
426
from bs4 import BeautifulSoup from difflib import SequenceMatcher class _Check: """ Parent check class. All other checks should be a subclass of this class. """ key = "check" name = "Check" description = "Parent check" class _BlindCheck(_Check): """ These checks identify issues in in...
7,467
1,903
from django.contrib import admin from django import forms from .models import Annotation, Clip, Food, Image, Language, Website, UserProfile class AnnotationAdminForm(forms.ModelForm): class Meta: model = Annotation fields = '__all__' class AnnotationAdmin(admin.ModelAdmin): form = Annotation...
2,863
871
from os.path import abspath, join, dirname from colibris.conf import settings STATIC_PATH = abspath(join(dirname(__file__), 'swagger')) UI_URL = settings.API_DOCS_URL STATIC_URL = '{}/static'.format(UI_URL) APISPEC_URL = '{}/apispec'.format(UI_URL)
252
96
#!/usr/bin/env python from arc import models from arc import methods from arc import black_boxes from arc import others from arc import coverage
145
37
# -*- coding: utf-8 -*- from qcloudsdkcore.request import Request class TerminateTaskInstanceRequest(Request): def __init__(self): super(TerminateTaskInstanceRequest, self).__init__( 'batch', 'qcloudcliV1', 'TerminateTaskInstance', 'batch.api.qcloud.com') def get_JobId(self): ret...
961
300
""" Step Chart ----------------- This example shows Google's stock price over time. """ import altair as alt from vega_datasets import data source = data.stocks() chart = alt.Chart(source).mark_line(interpolate = 'step-after').encode( x = 'date', y = 'price' ) chart.transform = [{"filter": "datum.symbol==='...
329
112
# -*- coding: utf-8 -*- """ file: graph_networkx.py Provides a NetworkX compliant Graph class. """ from graphit.graph import GraphBase from graphit.graph_exceptions import GraphitException, GraphitNodeNotFound from graphit.graph_algorithms import degree, size from graphit.graph_utils.graph_utilities import graph_und...
5,429
1,605
import os import random #initiate a list called emails_list emails_list = [] Directory = '/home/azureuser/spam_filter/enron1/emails/' Dir_list = os.listdir(Directory) for file in Dir_list: f = open(Directory + file, 'r') emails_list.append(f.read()) f.close()
260
94
import cv2 as cv import mediapipe as mp class PoseDetector: def __init__(self, mode=False, complexity=1, smooth=False, confidence=0.5, tracking_confidence=0.5) -> None: self.mode = mode self.complexity = complexity self.smooth = smooth self.confidence = confidence s...
1,135
374
r""" This is the base module for all other objects of the package. + `LaTeX` returns a LaTeX string out of an `Irene` object. + `base` is the parent of all `Irene` objects. """ def LaTeX(obj): r""" Returns LaTeX representation of Irene's objects. """ from sympy.core.core import all_classes ...
3,012
898
from stanza.server import CoreNLPClient import os # example text print('---') print('input text') print('') # text = "Chris Manning is a nice person. Chris wrote a simple sentence. He also gives oranges to people." text = "PyTables is built on top of the HDF5 library, using the Python language and the NumPy package....
4,346
1,367
#!/usr/bin/env python # By Jinyuan Sun def fasta2dic(fastafilename): #read a fasta file into a dict fasta_dict = {} with open(fastafilename) as fastafile: for line in fastafile: if line[0] == ">": head = line.strip() fasta_dict[head] = '' else: ...
1,617
561
import enum from typing import Optional, Dict import httpx from tea import serde from tea_client import errors from tea_client.models import TeaClientModel class AuthorizationMethod(enum.Enum): basic = "Basic" token = "Token" jwt = "JWT" class HttpClient: """Generic requests handler. Handles ...
10,248
2,479
import unittest from typing import List import Connector class PRPConnectorTest(unittest.TestCase): connection: Connector.PRPConnector = Connector.PRPConnector('admin', 'adminTest', 'https://marblch.pythonanywhere.com/') def test_test_message(self): response: dict = PRPConnectorTest.connection.test_...
3,809
1,168
import tensorflow as tf from tensorflow import keras class VAE(keras.Model): def __init__(self, encoder, decoder, **kwargs): super(VAE, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder self.e_count = 0 def train_step(self, data): # if isinstance(...
1,302
430
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2020, 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...
2,121
680
#from https://github.com/mfurukawa/imu_sensor/tree/master/src/Python # September 03, 2020 # Yuto Nakayachi from __future__ import unicode_literals ,print_function import serial from time import sleep import numpy as np import matplotlib.pyplot as plt import io import csv import time import datetime import stru...
6,070
2,468
import matplotlib as mpl mpl.use('agg') import glob import argparse from time import time import numpy as np import pylab as plt import rficnn as rfc parser = argparse.ArgumentParser() parser.add_argument('--arch', required=False, help='choose architecture', type=str, default='1') parser.add_argument('--trsh', requir...
1,754
719
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.header import Header from email.mime.base import MIMEBase from email import encoders import os import uuid import smtplib import re class CTEmail(object): def __i...
4,544
1,307
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class RequestExtShopItem(object): def __init__(self): self._brand_code = None self._category_code = None self._description = None self._item_code = None self._kb...
3,782
1,169
#!/usr/bin/env python # # Copyright 2009 Facebook # # 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 a...
9,644
2,877
# 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, ...
6,697
1,947
class TypeRef: '''Represents temporary type references by an integer; to be resolved to actual types later ''' def __init__(self, type_ref: int): self.type_ref = type_ref def __hash__(self): return hash(self.type_ref) def __eq__(self, other): return isinstance(other,...
462
144
import numpy as np loss_arr = np.array(list()) with open("total_loss.txt", "r") as f_loss: cnt = 0 for loss in f_loss.readlines(): cnt += 1 # print(loss) loss_arr = np.append(loss_arr, float(loss)) print(cnt)
260
101
'''Image utils''' from io import BytesIO from PIL import Image import matplotlib.pyplot as plt def save_and_open(save_func): '''Save to in-memory buffer and re-open ''' buf = BytesIO() save_func(buf) buf.seek(0) bytes_ = buf.read() buf_ = BytesIO(bytes_) return buf_ def fig_to_pil(fig: ...
443
161
import hashlib import logging from struct import unpack import sys import time from . import (connector_wire_messages as cwm, AtLeastOnceSourceConnector, ProtocolError, ConnectorError) if sys.version_info.major == 2: from .base_meta2 import BaseMeta, abstractmethod e...
15,070
4,012
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
3,090
933
#!/usr/bin/env python # encoding: utf-8 def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, "doc/page/login.asp", "Hikvision")
147
57
"""In this module we provide a list paths, urls and other usefull settings.""" GITHUB_URL = "https://github.com/MarcSkovMadsen/awesome-panel/" GITHUB_BLOB_MASTER_URL = "https://github.com/MarcSkovMadsen/awesome-panel/blob/master/" GITHUB_RAW_URL = "https://raw.githubusercontent.com/MarcSkovMadsen/awesome-panel/maste...
495
194
import pickle import pytest import numpy as np from astropy.coordinates import Longitude from astropy import coordinates as coord from astropy.tests.helper import pickle_protocol, check_pickling_recovery # noqa # Can't test distances without scipy due to cosmology deps from astropy.utils.compat.optional_deps import ...
1,789
603
#!/usr/bin/env python # # Copyright (C) 2017 ShadowMan # import operator import numpy as np group = np.array([ [1.0, 1.1], [1.0, 1.0], [0.0, 0.0], [0.0, 0.1] ]) labels = ['A', 'A', 'B','B'] def auto_normal(data_set): # 寻找一行/列中的最小值 # axis:表示行(1)或者列(0) min_values = data_set.min(axis = 0) ...
3,683
2,256
import os from typing import Tuple, List from controller.invoker.invoker_task_exporting import TaskExportingInvoker from controller import config from controller.label_model.label_studio import LabelStudio from controller.utils.app_logger import logger def prepare_label_dir(working_dir: str, task_id: str) -> Tuple[s...
3,101
1,035
import os from flask import Flask from googleapiclient.discovery import build import json import sys from google.oauth2 import service_account import googleapiclient.discovery app = Flask(__name__) workflow_service = build('workflowexecutions', 'v1') @app.route("/") def hello_world(): parent = "projects/uri-...
719
244
from math import pi, sin, cos from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.task import Task from floorplan import Floorplan import numpy as np import random import copy class Viewer(ShowBase): def __init__(self): ShowBase.__init__(self) #self.scene = self.loader.loadM...
9,264
3,609
# # Autogenerated by Thrift Compiler (0.9.1) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import * from thrift.Thrift import TProcessor from thrift.transport import TTransport ...
118,425
41,683
import numpy as np class KF1D: # this EKF assumes constant covariance matrix, so calculations are much simpler # the Kalman gain also needs to be precomputed using the control module def __init__(self, x0, A, C, K): self.x = x0 self.A = A self.C = C self.K = K self.A_K = self.A - np.dot(se...
626
245
import datetime import logging import os import boto3 from qiskit import IBMQ from qiskit import QuantumCircuit, execute logger = logging.getLogger() logger.setLevel(logging.INFO) backend_candidates = [ "ibmq_athens", "ibmq_santiago", "ibmq_belem", "ibmq_quito", "ibmq_lima", ] def _get_provider...
3,985
1,303
# -*- coding: utf-8 -*- # SPDX-License-Identifier: GPL-2.0+ # # Copyright 2017 Google, Inc # import contextlib import os import re import shutil import sys import tempfile import unittest import gitutil import patchstream import settings @contextlib.contextmanager def capture(): import sys from cStringIO im...
8,558
2,698
from animeblkom import Animeblkom, animeblkom_episode from downloader import blkom from requests import get download_list = [] anime_url = input('Anime Url: ') # ex. https://animeblkom.net/watch/one-piece episodes = Animeblkom.get_anime_episodes(anime_url) print(f'{len(episodes)} episodes found.') episodes...
832
339
import logging from fastapi import APIRouter from spaceone.core.locator import Locator _LOGGER = logging.getLogger(__name__) router = APIRouter() @router.get('/check') async def check(): return {'status': 'SERVING'}
225
71
""" @author: mkowalska """ import os import numpy as np from numpy.linalg import LinAlgError import matplotlib.pyplot as plt from figure_properties import * import matplotlib.gridspec as gridspec from kcsd import KCSD1D import targeted_basis as tb __abs_file__ = os.path.abspath(__file__) def _html(r, g, b): ret...
7,617
2,885
#!/usr/bin/env python # coding=utf-8 from celery import Celery from pprint import pprint import time app = Celery('tasks', backend='redis://localhost:6379/0', broker = 'redis://localhost:6379/0') @app.task def get(message): #=========== #pprint(message) #=========== return {"app":"Get Got"} @app.tas...
392
142
import re COMMENT_REGEX = re.compile(r'(checkov:skip=|bridgecrew:skip=) *([A-Z_\d]+)(:[^\n]+)?')
98
48
# Generated by Django 2.1.4 on 2020-04-20 23:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('plugins', '0033_pluginparameter_short_flag'), ] operations = [ migrations.AlterField( model_name='computeresource', ...
438
143
''' Created on Dec 21, 2014 @author: Milos ''' ''' Forma za eventualna prosirenja djangovog user-a ''' from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404...
4,112
1,235
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os imp...
4,775
1,660
"""Create the distribution file (pypi).""" import importlib import setuptools from pathlib import Path this_package_name = 'remote_import' version_file = Path(__file__).absolute().parent / this_package_name / "__version__.py" setuptools.setup( name=this_package_name, url="https://github.com/kiranmantri/pytho...
932
302
from flask import request import pytest import json from app import create_app, create_rest_api from db import get_db @pytest.fixture def client(): local_app = create_app() create_rest_api(local_app) client = local_app.test_client() yield client def test_get_aquarium_invalid_id(client): with c...
1,958
653
import json import os import cv2 import imutils import numpy as np import torch import torchvision.transforms.functional as tvf from PIL import Image from models.rapid import RAPiD from tracker.deep_sort import DeepSort from utils import utils weights_path = "weights/pL1_HBCP608_Apr14_6000.ckpt" model = RAPiD(backbo...
4,172
1,655
import os import sys from loguru import logger from rich.console import Console console_args = {} if "pytest" in sys.modules: console_args["width"] = 120 console = Console(**console_args) cpu_count = None def escape_logging(s): return str(s).replace("<", "\\<").replace("{", "{{").replace("}", "}}") def CP...
5,194
1,653
# -*- coding: utf-8 -*- # 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, softw...
1,808
864
from http import HTTPStatus from flask_restful import Resource from ..extensions import cache from ..models.country import Country from ..schemas.continent import ContinentSchema continent_list_schema = ContinentSchema(many=True) class ContinentListResource(Resource): @cache.cached(timeout=60, query_string=Tru...
618
168
import sublime import sublime_plugin import threading import os.path from pickle import dump, load, UnpicklingError, PicklingError from copy import deepcopy from .common import * from .bookmark import * from .visibilityHandler import * from .ui import * BOOKMARKS = [] UID = None #list of bookmarks that have ben d...
14,547
5,318
import logging import random from typing import Dict from xrpc.dsl import rpc, RPCType, regular, signal from xrpc.error import TerminationException from xrpc.runtime import sender, service # todo: the issue is actually that not only the request-reply pattern wouldn't work # todo: but also the fact that an RPC might h...
3,677
1,170
import matplotlib.pyplot as plt import pandas as pd import pytest from ml_matrics import ROOT @pytest.fixture(autouse=True) def run_around_tests(): # Code that runs before each test yield # Code that runs after each test plt.close() y_binary, y_proba, y_clf = pd.read_csv(f"{ROOT}/data/rand_clf.cs...
413
159
# -*- coding: utf-8 -*- #!/usr/bin/env python from __future__ import print_function import community_ext import networkx as nx fn1 = "datasets/polblogs/polblogs.edges" fn2 = fn1.replace(".edges",".clusters") print("DATASET:",fn1) # load graph G = nx.Graph() for line in open(fn1): from_node, to_node = map(int, li...
2,907
974
import os,sys,math,numpy as np, matplotlib.pyplot as plt def runstuff(): #savept= './scores_v2_23042021' #0.7580982029438019 0.5812124161981046 #savept= './scores_v2_23042021_sizes' #0.7552803814411163 0.583345946110785 #savept= './scores_v2_23042021_sizes_posenc' #0.7596977412700654 0.583193539083004 #savep...
1,961
1,109
from keras.models import Model, Sequential from keras.layers import Input, Convolution2D, ZeroPadding2D, MaxPooling2D, Flatten, Dense, Dropout, Activation import numpy as np from os import listdir,path from os.path import isfile, join from PIL import Image from keras.preprocessing.image import load_img, save_img, img_t...
5,282
2,030
"""Module with view functions that serve each uri.""" from datetime import datetime from learning_journal.models.mymodel import Journal from learning_journal.security import is_authenticated from pyramid.httpexceptions import HTTPFound, HTTPNotFound from pyramid.security import NO_PERMISSION_REQUIRED, forget, remem...
3,879
1,115
""" Created by Joseph Edradan Github: https://github.com/josephedradan Date created: 3/23/2020 Purpose: The most generic DFS algorithm capable of being modified to Fit your needs. It is also optimized. Details: Description: Notes: IMPORTANT NOTES: Explanation: Time Complexity: Reference: """ from typi...
4,854
1,685
from django.db import models import json class ParametersMM(): corGrafico = { "Novos Casos": "pink", "Média Móvel": "red" } def cores(self, tipo): cores = [] for cat in self.categorias(self, tipo): cores.append(self.corGrafico[cat]) ...
657
200
import json import logging from PyQt5.QtCore import QObject, pyqtSignal from ..core.constants import ( API_TEST_CASE_RECORD_TYPE, HTTP_EXCHANGE_RECORD_TYPE, ENVIRONMENT_RECORD_TYPE, PROJECT_INFO_RECORD_TYPE, APP_STATE_RECORD_TYPE, API_CALL_RECORD_TYPE, ) from ..model.app_data import ( ApiC...
4,151
1,440
import unittest from dfttopif.parsers.pwscf import PwscfParser from ..test_pif import unpack_example, delete_example from pypif.obj.common.value import Value import os import shutil class TestPWSCFParser(unittest.TestCase): def get_parser(self,name): '''Get a PwscfParser for a certain test''' ...
120,882
108,837
# Generated by Django 3.1.3 on 2021-02-10 01:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('labels', '0001_initial'), ] operations = [ migrations.AddField( model_name='species', name='de', field=m...
1,009
294
import numpy as np def conjgrad(A, b, x, T, tol): r = b - A@x p = r rsold = np.sum(r * r, 0) for i in range(T): Ap = A@p alpha = rsold / np.sum(p*Ap, 0) x = x + alpha*p r = r - alpha*Ap rsnew = np.sum(r*r, 0) if np.sqrt(np.sum(rsnew)) < tol: b...
399
170
import model sticker_storage = model.get_storage() def my(_, update): """Prints stickers added by user""" message = update.message user_id = update.message.from_user.id stickers = sticker_storage.get_for_owner(user_id, max_count=20, tagged=True) text = '\n\n'.join( 'Tags: {tags}\n' ...
569
198
#!/usr/bin/env python3 import argparse import getpass import os import sys import argcomplete from datetime import datetime from forest import cmake_tools from forest.common.eval_handler import EvalHandler from forest.common.install import install_package, write_setup_file, write_ws_file, check_ws_file, uninstall_pac...
9,587
2,781
""" Given an array of numbers, find the subarray that maximizes the sum of all elements in the array. Note that these numbers can be negative """ import random def createArray(n): nums = [] for i in range(n): nums.append(random.randint(-10, 10)) return nums def bruteForceBest(a): best = a...
1,849
685
#!/usr/bin/env python # coding: utf-8 from setuptools import setup, find_packages import os def package_files(directory, relative_to): paths = [] for (path, directories, filenames) in os.walk(directory): for filename in filenames: full_path = os.path.join(path, filename) final...
1,101
374
#coding:utf-8 N = int(raw_input()) S = '' stack = [S] for _ in xrange(N): s = raw_input() if s.startswith('1'): S = ''.join((S, s.split()[-1])) stack.append(S) elif s.startswith('2'): k = int(s.split()[-1]) S = S[:-k] stack.append(S) elif s.startswith('3'): ...
469
185
from datetime import datetime from typing import Optional, List, Dict import sys sys.path.append("../../") from backend.server.pd_model import * from backend.queue.services import add_task, stop_all_ws_task from backend.database.main import gis_stac __all__ = ["preview_processing", "vector_processing", "refuse_proces...
2,601
837
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.views.generic.base import TemplateView from diario.models import Entry from observations.models import Measurement class HomePageView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomePageV...
530
162
""" Adds a ubt command which adds basic block counts to frames within a backtrace. Usage: ubt Contributors: Isa Smith, Toby Lloyd Davies Copyright (C) 2019 Undo Ltd """ import gdb from undodb.debugger_extensions import ( debugger_utils, udb, ) class BacktraceWithTime(gdb.Command): def __init__(self)...
1,516
412
# # @author Kevin Jesse # @email kevin.r.jesse@gmail.com # """ Database Connect serves to connect to the database postgres, as the master user. Autocommit has been turned on so all inserts, updates, and deletes will be enforced atomically """ import psycopg2 def db_connect(): cur = None try: conn = p...
680
207
""" Integration test for remove_participants_under_18years module Original Issues: DC-1724 The intent is to remove data for participants under 18 years old from all the domain tables.""" # Python Imports import os import datetime # Project Imports from common import VISIT_OCCURRENCE, OBSERVATION from common import...
6,590
2,401
import pandas as pd canucks = pd.read_csv('data/canucks.csv') # Identify any columns with null values with .info() # Save this dataframe as canucks_info canucks_info = canucks.info() canucks_info # Create a new column in the dataframe named Wealth # where all the values equal "comfortable" # Name the new dataframe ...
609
209
# # @lc app=leetcode.cn id=461 lang=python3 # # [461] 汉明距离 # # https://leetcode-cn.com/problems/hamming-distance/description/ # # algorithms # Easy (79.21%) # Likes: 459 # Dislikes: 0 # Total Accepted: 137K # Total Submissions: 170K # Testcase Example: '1\n4' # # 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 # # 给出两个整数 x ...
1,412
701
"""Database Layer for the Emmission API. """ from functools import wraps from sqlalchemy import create_engine, Column, DateTime, Integer, Float, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import geoalchemy2 from emissionsapi.config import config import emi...
4,413
1,332
# This file is part of the Edison Project. # Please refer to the LICENSE document that was supplied with this software for information on how it can be used. # Create your views here. from django.http import Http404, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.template im...
2,217
642
from setuptools import setup setup( name = 'pypdb', packages = ['pypdb'], # same as 'name' version = '1.310', install_requires=[ 'xmltodict', 'beautifulsoup4', 'requests' ], description = 'A Python wrapper for the RCSB Protein Data Bank (PDB) API', author = 'William Gilpin', author_...
553
208
wt1_10_10 = {'192.168.122.110': [5.5754, 5.5952, 9.2422, 8.5338, 9.0058, 8.4025, 8.7557, 8.4405, 8.1397, 8.1318, 8.0657, 7.8501, 8.1701, 8.0757, 7.8899, 7.7329, 7.6153, 7.9967, 7.9363, 7.838, 8.7936, 8.6351, 8.5151, 8.6381, 8.7262, 8.816, 8.8984, 8.7799, 8.8584, 8.9543, 8.8833, 8.794, 8.6935, 8.735, 8.635, 8.5429, 8.6...
409,678
409,497
from django.conf import settings from django.conf.urls.static import static from django.conf.urls import include,url from . import views urlpatterns=[ url(r'api/user/user-id/(?P<pk>[0-9]+)/$', views.UserDescription.as_view()), url(r'api/project/project-id/(?P<pk>[0-9]+)/$', views.ProjectDesc...
940
343
import yaml import argparse from ansible_vault import Vault def create_file(args): svc = open("netbox_tools/webhook_proxy_svc.py", "r") all_lines = svc.readlines() svc = open("netbox_tools/webhook_proxy_svc.py", "w") for index, content in enumerate(all_lines): if "'token'" in content: ...
3,485
1,196
# -*- coding: utf-8 -*- """ The data is (should be) based on the lecture Energie und Klimasysteme II, Erneuerbare Energieerzeugung am Gebäude, FS 2019, Folie 30, """ from __future__ import print_function def get_performance_ratio(performance_scenario): # return "\n".join("{key}: {value}".format(key=key, value=va...
448
152
import netCDF4 from os import path from test_utils.utils import count_strings, read_log_file import pytest SCRIPT_PATH = path.dirname(path.realpath(__file__)) class TestChm15kProcessing: product = 'lidar' instrument = 'chm15k' @pytest.fixture(autouse=True) def _fetch_params(self, params): s...
2,901
1,134
from django.contrib.auth.models import AbstractUser from django.db import models from .validators import validate_bet, validate_course class User(AbstractUser): email = models.EmailField('email address', unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class FootballType(models.Model...
1,371
417
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import logging import popdist import popdist.poptorch import horovod.torch as hvd def handle_distributed_settings(opts): # Initialise popdist if popdist.isPopdistEnvSet(): init_popdist(opts) else: opts.use_popdist = False def init_...
759
258
from .docs import docs from .request import ( request_schema, use_kwargs, # for backward compatibility path_schema, # request_schema with locations=["path"] querystring_schema, # request_schema with locations=["querystring"] form_schema, # request_schema with locations=["form"] json_schema, ...
589
165
# -*- coding: utf-8 -*- # # Copyright (C) 2018 Red Hat, 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 la...
1,943
686
#!/usr/bin/env python # -*- coding: utf-8 -*- """Logging Handler integrating RabbitMQ and Graylog Extended Log Format (GELF)""" import json from logging import Filter from logging.handlers import SocketHandler from amqplib import client_0_8 as amqp # pylint: disable=import-error from graypy.handler import BaseGELF...
4,355
1,275
import boto3 comprehend = boto3.client(service_name='comprehend') translate = boto3.client(service_name='translate') def detect_language(text): """ Detects the dominant language in a text Parameters ---------- text: string, required Input text Returns ------- string Rep...
1,323
358
# 2020.05.10 # update topNscore # learner on subspace # particular designed for encounter missing class in this subspace # if one class do not exists in training data, probability for this class would be zeros under anytime # # learner: a regressor or classifier, must have methods named 'predict' # num_class: tota...
3,768
1,251
import time import pritunl_wireguard_client.utils.random as utils class Tokens: def __init__(self): self.store = dict() def get(self, profile_id: str, ttl: int): """Return token for profile_id""" if profile_id not in self.store: self.init(profile_id, ttl) self.upda...
1,077
335
#!/usr/bin/env python3 from __future__ import print_function import getpass import os import shutil import time from datetime import datetime from github import Github, GithubException, GithubObject from git import git_init class GithubUtilException(Exception): "General GitHub utilities exception" class Met...
16,812
4,547
import logging import os import platform from datetime import datetime from moabb.analysis import plotting as plt from moabb.analysis.meta_analysis import ( # noqa: E501 compute_dataset_statistics, find_significant_differences, ) from moabb.analysis.results import Results # noqa: F401 log = logging.getLogg...
2,299
718
from numba import guvectorize, float64, int64, njit import numpy as np from smm import numba_target as target_preset @guvectorize([(int64, float64, float64[:, :], float64[:])], '(),(),(M,n)->(n)', nopython=True, target=target_preset) def indexed_x_axpy(ix, a, x, res): # pragma:...
2,180
894
""" How to find only the duplicates """ some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] duplicates = [] # o noua lista unde adaugam duplicatele for value in some_list: if some_list.count(value) > 1: # cand in lista numaram fiecare valoarea si se gaseste mai mult de o data if value not in duplicates...
783
275