text
string
size
int64
token_count
int64
""" This module provides a ``CompositePKModel`` which allows for basic retrieval and saving of models with composite keys. It is limited to the above tasks, and any use of the model past this is not guaranteed to work. A model with composite PK should look something like this:: from composite_pk import compos...
3,915
1,138
from math import erf, sqrt from functools import partial from ..library.multinomial import multinomial, to_multinomial def gaussian_cdf(x, mu, sigma): y = (1.0 + erf((x - mu) / (sigma * sqrt(2.0)))) / 2.0 y = (1.0 + erf((x) / (sqrt(2.0)))) / 2.0 assert y >= 0 and y <= 1.0, 'y is not a valid probability: y...
752
280
import numpy as np import torch import time from scipy import optimize from scipy.stats import norm import tmac.probability_distributions as tpd import tmac.fourier as tfo def tmac_ac(red_np, green_np, optimizer='BFGS', verbose=False, truncate_freq=False): """ Implementation of the Two-channel motion artifact cor...
8,299
2,594
from arguments import get_args import numpy as np from network.models import MLP_Net from utils.utils import get_env_params import torch import os, gym """ script to watch the demo of the ESIL """ # process the inputs def process_inputs(o, g, o_mean, o_std, g_mean, g_std, args): o_clip = np.clip(o, -args.clip_obs...
2,166
709
from datetime import datetime from kickbase_api.models._transforms import parse_date, parse_key_value_array_to_dict from kickbase_api.models.base_model import BaseModel from kickbase_api.models.league_user_season_stats import LeagueUserSeasonStats class LeagueUserStats(BaseModel): name: str = None profile_im...
1,071
332
""" Interfaces for FCRepoRequestFactory, FCRepoResponse and FCRepoResponseBody. """ from exceptions import NotImplementedError # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # class I_FCRepoResponseBody: def __init__(self, raw_content, mime_type): """ Constructor takes tow...
9,647
2,416
#utf8 from __future__ import print_function, division import subprocess import os import os.path import sys import time default_tmp_mesh_filename = '/tmp/Mesh_1.med' # salome 9.x may be too new for this script, some version released in 2018 is better # salome_app = '/media/sf_OneDrive/Salome-9.8.0/salome' salome_app =...
4,397
1,574
"""Values for controlled vocabularies from ENA. Taken from - https://ena-docs.readthedocs.io/en/latest/submit/reads/webin-cli.html """ # Constants for platform definitions. LS454 = "LS454" ILLUMINA = "ILLUMINA" PACBIO_SMRT = "PACBIO_SMRT" IONTORRENT = "ION_TORRENT" CAPILLARY = "CAPILLARY" ONT = "OXFOR...
8,141
4,423
""" Copyright 2012 Numan Sachwani <numan@7Geese.com> This file is provided to you 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...
1,463
421
from .lemkelcp import lemkelcp
31
11
""" Settings for re-running the experiments from the paper "Layer-wise relevance propagation for explaining deep neural network decisions in MRI-based Alzheimer’s disease classification". Please note that you need to download the ADNI data from http://adni.loni.usc.edu/ and preprocess it using https://github.com/ANT...
1,999
643
''' # Test the compiler ''' from ACOW import * data = ''' a1 U[1,2] !a0&G[1,3]a3 ''' print('MTL Formula:',data) # Test lex print('\nLex Test:') lexer.input(data) for tok in lexer: print(tok) # Test parser print('\nParser Test:') result = parser.parse(data) print(result)
274
117
import board import time import random import usb_hid from adafruit_hid.mouse import Mouse from adafruit_hid.keyboard import Keyboard mouse = Mouse(usb_hid.devices) goright=True while True: #2 parts to sequence, move mostly right, then mostly left # set up for big move #longwait=random.randint(250,35...
1,292
462
from django.contrib import admin from .models import Post, Comment, UserProfile class ProfileAdmin(admin.ModelAdmin): filter_horizontal =("followers", "following",) # Register your models here. admin.site.register(Post) admin.site.register(Comment) admin.site.register(UserProfile, admin_class=ProfileAdmin)
315
89
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-27 14:43 from __future__ import unicode_literals import ckeditor.fields from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import django_countries.fields ...
25,042
7,671
from Bio.SeqIO import parse from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq from Bio.Alphabet import IUPAC, generic_dna from Bio import Alphabet, Entrez from Bio.SeqUtils import GC from Bio.Blast import NCBIWWW, NCBIXML from Bio import pairwise2 from Bio.pairwise2 import format_alignme...
15,097
4,037
#!/usr/bin/env python # Exploit Title: Unauthenticated SQL Injection on CMS Made Simple <= 2.2.9 # Date: 30-03-2019 # Exploit Author: Daniele Scanu @ Certimeter Group # Vendor Homepage: https://www.cmsmadesimple.org/ # Software Link: https://www.cmsmadesimple.org/downloads/cmsms/ # Version: <= 2.2.9 # Tested on:...
6,456
2,245
import pymongo client = pymongo.MongoClient('''mongodb://dakotapope:passwrd@ cluster0-shard-00-00-iaoct.mongodb.net:27017,cluster0-shard-00 -01-iaoct.mongodb.net:27017,cluster0-shard-00-02-iaoct.mongodb. net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource= admin&retryWrites=true''') # investigate the databa...
968
387
#!/usr/bin/python3 import xlrd import csv import sys import getopt # input configuration iColDate = 0 iColTransactionType = 1 iColAmount = 3 iColDescription = 6 transactionType = 'Repayment' descriptionType = 'Interest' #output configuration outHeader = ['Datum', 'Typ', 'Wert'] outType = 'Zinsen' outDelimiter = ';' ...
2,799
992
"""Promises, promises, promises.""" from __future__ import absolute_import, unicode_literals import re from collections import namedtuple from .abstract import Thenable from .promises import promise from .synchronization import barrier from .funtools import ( maybe_promise, ensure_promise, ppartial, preplace...
1,096
387
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from LLC_Membranes.timeseries.forecast_ctrw import System from LLC_Membranes.llclib import file_rw import names residues = ["GCL", "SOH"] wt = 10 path = "/home/bcoscia/Documents/Gromacs/Transport/NaGA3C11" colors = ['blue', 'red'] opacity = 1 n...
1,965
937
def string_to_list(string,array): x=input(string) i=1 while x[i]!=']': if x[i]!=',': j=i temp='' while x[j]!=',': if x[j]==']': break temp+=x[j] j+=1 i=j array.append(i...
1,275
462
"""Added tariff Revision ID: 4dbaa3104f4 Revises: 1d6f96d1df Create Date: 2015-05-27 16:00:09.343862 """ # revision identifiers, used by Alembic. revision = '4dbaa3104f4' down_revision = '1d6f96d1df' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(engine_name): ...
3,000
1,052
#imports import os import subprocess from colorama import init,Fore, Back, Style import asyncio import urllib.parse import time from time import perf_counter init(convert=True) #vars ver = "Beta, Lots of commits going on!" ping = 0 pings = [] tempping = 0 searches = 0 base = 300 delay = 0 gotQ = "" dropTime = 0 reqTime...
4,970
1,850
#!/usr/bin/env python3 # # calc_qual.py # # A program to calculate the quality factors and magnetic angle within some defined region # of an Athena++ disk using MPI # # To run: # mpirun -n [n] python calc_qual.py [options] # for [n] cores. # import numpy as np import os import sys sys.path.insert(0, '/home/per29/rds/rd...
10,360
3,860
from sqlalchemy import Column, String, Integer, Text, Boolean, DateTime from config.access import Base from sqlalchemy.ext.declarative import declared_attr from datetime import datetime class BaseFunctions: """ Base class for common methods """ __tablename__ = None @declared_attr def import_...
4,838
1,600
import ctypes import struct import time from fixate.core.common import bits from fixate.core.exceptions import InstrumentError, InstrumentNotConnected import fixate.config import fixate.core.discover def open(ftdi_description=""): """Open is the public api for the bit bang driver for discovering and opening a con...
16,726
5,700
# You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N. #...
552
181
import unittest from nose.tools import eq_, ok_, raises from sqlalchemy import create_engine, MetaData, Column, Integer, func from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from geoalchemy2 import Geometry from sqlalchemy.exc import DataError, IntegrityError, InternalE...
5,621
1,938
from django.db import models # Create your models here. class Link(models.Model): key = models.SlugField(max_length = 100, unique = True, verbose_name = 'Nombre Clave') name = models.CharField(max_length = 200, verbose_name = 'Red Social') url = models.URLField(max_length = 200, null = True, blank = True, ...
689
223
#!/usr/bin/python # -*- utf-8 -*- # Definition for singly-linked list with a random pointer. # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # @param head, a RandomListNode # @return a RandomListNode def ...
940
294
from data_reader import Vocabulary, transform_data, save_vocabularies, Corpus from model import build_model from keras.callbacks import ModelCheckpoint def train(args): # ARGUMENTS training_file=args.data minibatch=64 max_sent_len_words=30 epochs=args.epochs corpus=Corpus(training_f...
1,904
694
# Copyright 2022 AI Singapore # # 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 writing...
6,198
1,692
from .base import * # 後で確認できるよう、ファイルとして残しておく EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' # filebasedを使う場合は、メールの保存先も指定すること # '.' の場合、カレントディレクトリに保存される # EMAIL_FILE_PATH = '.' EMAIL_FILE_PATH = str(pathlib.Path(BASE_DIR).joinpath('logs')) ADMINS = [('Admin1', 'admin1@example.com')] # 開発モードでもADMI...
1,119
462
from dateutil.relativedelta import relativedelta from uuid import uuid4 import unittest import pytz from django.test import TestCase from django.utils.timezone import datetime from core.tests.helpers import CoreProviderMachineHelper, CoreMachineRequestHelper, CoreInstanceHelper from service.machine import process_m...
7,494
2,180
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class DeviceZoneRemote(RemoteModel): """ Zones defined on a traffic filtering device. On devices that do not natively support zones (e.g., Cisco routers), there is one zone per interface, plus an additional 'intern...
3,455
928
from rest_framework.views import APIView from rest_framework.response import Response from django.shortcuts import render from django.http.response import JsonResponse from nitmis_admin.serializers.UserSerializer import UserSerializer def create_user(role="Guest"): """ """ def fun_wrapper(func): d...
1,510
387
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Apr 2 10:00 2017 @author: Timo Hinzmann (hitimo@ethz.ch) """ import math from math import floor, ceil import numpy as np import matplotlib.pyplot as plt from scipy.sparse import linalg as sla from scipy import array, linalg, dot from enum import Enum imp...
9,521
3,477
from django.utils.timezone import now class NotHistorical(TypeError): """No related history model found.""" def get_history_model_for_model(model): """Find the history model for a given app model.""" try: manager_name = model._meta.simple_history_manager_attribute except AttributeError: ...
1,019
277
""" A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc an...
1,174
359
from flask_login import LoginManager from PhoenixNow.model import User login_manager = LoginManager() login_manager.login_view = "regular.signin" @login_manager.user_loader def load_user(user_id): user = User.query.filter_by(id=user_id).first() return user
267
85
import os import datetime as dt import random import networkx # import matplotlib as mpl import matplotlib.pyplot as plt from const import * activity = {} with open(os.path.join(DATA_DIR, "mobiclique", "activity.csv")) as activity_fd: for line in activity_fd.readlines(): line = line.strip() ...
7,673
2,736
"""Unit tests for the General Linear group.""" import warnings import tests.helper as helper import geomstats.backend as gs import geomstats.tests from geomstats.geometry.general_linear import GeneralLinear RTOL = 1e-5 class TestGeneralLinear(geomstats.tests.TestCase): def setUp(self): gs.random.seed(...
6,995
2,468
from unittest import TestCase import os,sys,inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(current_dir) sys.path.insert(0, parent_dir) import feladatok class TestEBetukSzama6(TestCase): def test_feladat06(self): aktualis = fela...
454
173
from utils.Driver import Driver from pages.base_page import BasePage from pages.locators import MainPageLocators class MainPage(BasePage): def __init__(self, driver: Driver): self.locators = MainPageLocators super().__init__(driver=driver)
271
83
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-16 07:49 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migratio...
1,726
530
import math import unittest import torch from nuscenes.prediction.models import mtp class TestMTPLoss(unittest.TestCase): """ Test each component of MTPLoss as well as the __call__ method. """ def test_get_trajectories_and_modes(self): loss_n_modes_5 = mtp.MTPLoss(5, 0, 0) los...
7,801
2,903
#!/usr/bin/env python3 # Convert Yosys JSON to simple text hypergraph for performance testing import sys, json node_count = 0 edge2node = {} netlist = None with open(sys.argv[1]) as jf: netlist = json.load(jf) top_module = None for name, module in sorted(netlist["modules"].items()): if "attributes" not in modul...
1,067
418
from Tkinter import * import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd from torch.autograd import Variable master = Tk() goal = 0 var_goal = StringVar() GAMMA = 0.9 last_state = Variable(torch.Tensor([0,0,0,0,0,0])).u...
3,966
1,456
import os import sys compiler = r'../Binary/RelWithDebInfo/ShaderCompiler' #compiler = r'../Binary/Debug/ShaderCompiler' shader_dirs = ['.', './Editor'] count = 0 for d in shader_dirs: for fn in os.listdir(d): print(fn) ext = fn.split('.')[-1] if ext in ['surf', 'shader']: cmd = compiler + ' ' + os.path.ab...
500
215
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from rbb_swagger_server.models.base_model_ import Model from rbb_swagger_server.models.simulation_environment_detailed import SimulationEnvironmentDetailed # noqa: F40...
14,058
4,025
import docker import os import sys import pandas as pd import warnings from src.PRM import PRM from pathlib import Path from src.util import prepare_path_docker __all__ = ['PathLinker'] class PathLinker(PRM): required_inputs = ['nodetypes', 'network'] @staticmethod def generate_inputs(data, filename_map)...
5,857
1,587
# -*- coding: utf-8 -*- from .base import Hypothesiser from ..base import Property from ..types.multihypothesis import MultipleHypothesis from ..types.prediction import (TaggedWeightedGaussianStatePrediction, WeightedGaussianStatePrediction) from ..types.state import TaggedWeightedGaussi...
4,978
1,214
from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority from apps.authentication.serializers import UserSerializer class CommitteeSerializer(serializers.ModelSerializer): group_name...
1,458
362
import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import train_test_split import utils import glob, os import pca.dataanalyzer as da, pca.pca as pca from sklearn.metrics import accuracy_score # visulaize ...
2,909
1,050
# SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries # # SPDX-License-Identifier: Unlicense import adafruit_board_toolkit.circuitpython_serial comports = adafruit_board_toolkit.circuitpython_serial.repl_comports() if not comports: raise Exception("No CircuitPython boards found") # Pri...
421
139
import time import uuid from random import random def now(): return int(time.time() * 1000) def uuid1(): return str(uuid.uuid1()) def millis(s): return s * 1000 def seconds(ms): return ms / 1000 def exponential_backoff( attempts, base_delay, max_delay=None, jitter=True, ): ...
798
275
from dagster import job, op @op def get_name(): return "dagster" @op def hello(name: str): print(f"Hello, {name}!") @job(description="Hello world Dagster pipeline") def hello_dagster(): hello(get_name())
221
82
# -*- coding: utf-8 -*- import time import numpy as np from qulab.device import BaseDriver, QInteger, QOption, QReal, QString, QVector class Driver(BaseDriver): error_command = '*ESR?' support_models = ['AFG3102'] quants = [ QOption('Output',ch=1, set_cmd='OUTP%(ch)d %(option)s', get_...
4,508
2,065
# -*- coding: utf-8 -*- import torch import torch.nn as nn """ 输入3个句子,每个句子由5个单词构成,每个单词词向量10维 batch=3, seq_len=5, Embedding=10 """ # 设置LSTM参数,词向量维数10,隐藏元维度20,2个LSTM隐藏层,双向LSTM bilstm = nn.LSTM(input_size=10, hidden_size=20, num_layers=2, bidirectional=True) # 如下表示输入句子 input = torch.randn(5, 3, 10) # 初始化的隐藏元和记忆元,通常维度一样 ...
1,357
745
from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from apps.meiduo_admin.serializers.order import OrderInfoSerializer from apps.meiduo_admin.utils import PageNum from apps.orders.models import OrderInfo class OrderModelViewSet(M...
1,484
571
#!/usr/bin/python3.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 app...
29,587
9,473
from locust import HttpLocust, TaskSet def login(l): l.client.post("/login", {"username": "ellen_key", "password": "education"}) def info(l): l.client.get("/_info") def profile(l): l.client.get("/profile") class UserBehavior(TaskSet): tasks = {info: 1} class WebsiteUser(HttpLocust): task_s...
372
139
import nekos from ..utils import admin_cmd @borg.on(admin_cmd(pattern = "tcat$")) async def hmm(cat): if cat.fwd_from: return reactcat = nekos.textcat() await cat.edit(reactcat) @borg.on(admin_cmd(pattern = "why$")) async def hmm(cat): if cat.fwd_from: return whycat = nekos...
513
197
import time import continuous_threading def test_thread(): class Thread(continuous_threading.Thread): def _run(self, *args, **kwargs): print('here') th = Thread() th.start() time.sleep(0.1) def test_continuous(): class CountingThread(continuous_threading.ContinuousThread): ...
2,518
828
import copy import torch.nn as nn from .transformer import (Encoder, EncoderLayer, MultiHeadedAttention, PositionwiseFeedforward, PositionalEncoding) class TransformerEncoder(nn.Module): """Transformer Encod...
2,587
764
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-02-15 13:41 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('members', '0026_auto_20180919_1434'), ('members', '0027_auto_20190208_1119'), ] ope...
338
150
import os import sys import globus_sdk from globus_sdk.tokenstorage import SQLiteAdapter from ._old_config import invalidate_old_config # internal constants _CLIENT_DATA_CONFIG_KEY = "auth_client_data" # env vars used throughout this module GLOBUS_ENV = os.environ.get("GLOBUS_SDK_ENVIRONMENT") GLOBUS_PROFILE = os.e...
5,221
1,694
#!/usr/bin/env python #coding:utf-8 __author__ = 'CoderZh and Tymur' import sys from time import sleep # Important for multithreading sys.coinit_flags = 0 # pythoncom.COINIT_MULTITHREADED import win32com import win32com.client import win32gui import win32con import pythoncom #import keyboard from p...
5,325
2,218
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'efrenfuentes' import unittest from plugin_MontoEscrito import numero_a_letras, numero_a_moneda class TestNumeroLetras(unittest.TestCase): def test_numero_demasiado_alto(self): numero = 1000000000000 self.assertRaises(OverflowError, numero_a...
4,158
1,525
#!/usr/bin/python # -*- coding: utf-8 -*- import os import setuptools setuptools.setup( name = "pconvert-python", version = "0.4.1", author = "Hive Solutions Lda.", author_email = "development@hive.pt", description = "PNG Convert", license = "Apache License, Version 2.0", keyw...
2,238
683
# SPDX-License-Identifier: Apache-2.0 """Graph Optimizer Base""" import copy from .. import logging, utils class GraphOptimizerBase(object): """optimizer graph to improve performance """ def __init__(self): self._logger = logging.getLogger('.'.join(__name__.split('.')[:-1] + [self.__class__._...
2,281
700
import numpy as np from pydub import AudioSegment import random import sys import io import os import glob import IPython from td_utils import * from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.models import Model, load_model, Sequential from tensorflow.keras.layers import Dense, Activation...
3,299
1,167
# ===================================================== # Copyright (c) 2017-present, AUROMIND Ltd. # ===================================================== import os from network import NeuralNetwork from experiments import Experiment from utils import save_object, load_object # ------------------------------------...
1,753
463
#!/usr/bin/env python # # ___INFO__MARK_BEGIN__ ####################################################################################### # Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.) # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file e...
4,353
1,388
#!/usr/bin/env python3 import os import sys import runpy from intelhex import IntelHex #import lz4.frame import subprocess import shutil def get_section_from_elf(elf,section_name): objdump = shutil.which('objdump') cmd = [ objdump,elf,'-h','--section='+section_name] out="" res=subprocess.run(cmd, stdou...
6,789
2,383
# -*- coding: utf-8 -*- from flask import make_response, Blueprint from app import derive_import_root, add_url_rules_for_blueprint from application import exception from application.model.service import Service from application.model.service_template import ServiceTemplate from application.util.database import session...
3,819
1,111
import json import requests class Searchs(object): __module__ = 'trello' def __init__(self, apikey, token=None): self._apikey = apikey self._token = token def get(self, query, idOrganizations, idBoards=None, idCards=None, modelTypes=None, board_fields=None, boards_limit=None, ca...
1,293
408
"""Exogenous parameters are anything "uncontrollable" that affect the design; these are what we consider robustness against and are typically drawn from some distribution """ from typing import Optional, Sequence, Tuple, Union import jax import jax.numpy as jnp from jax._src.prng import PRNGKeyArray import numpy as np...
3,736
1,025
class Base: """Class docstring.""" class Sub(Base): def __in<the_ref>it__(self): pass
103
37
import re from courspider.faculty_calendar_resources.department import Department from courspider.faculty_calendar_resources.url import URL from courspider.course import Course class DepartmentCalendar: def __init__(self, session, url): """ Initialize a new Department Calendar for the given url ...
4,955
1,500
#!/usr/bin/env python # Copyright (c) 2013 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. """Runs all the buildbot steps for ChromeDriver except for update/compile.""" import optparse import os import platform import shu...
6,366
2,368
# ---------------------------------------------------------------------- # | # | CastExpressionParserInfo_UnitTest.py # | # | David Brownell <db@DavidBrownell.com> # | 2021-10-04 09:14:16 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2021 ...
2,924
783
from django.db import models class File(models.Model): id = models.AutoField(primary_key= True) b64 = models.TextField(blank=False, null=False) lastedit = models.DateTimeField(auto_now= True) image_class = models.TextField(blank = True, default = "") labels = models.TextField(blank = True, default= "") def __str...
363
120
''' # ReadQuickly 后端 ``` |-- Server |-- __init__.py |-- server.py (请求服务器) |-- content.py (整合响应数据) |-- spider (爬虫包) |-- weather (天气包) |-- notice (通知包) ``` '''
189
108
import collections import dataclasses import itertools @dataclasses.dataclass(frozen=True) class Point: x: int y: int @dataclasses.dataclass(frozen=True) class Segment: start: Point stop: Point @property def slope(self): dy = self.stop.y - self.start.y dx = self.stop.x - sel...
1,746
662
"""Functions related to converting content into dict/JSON structures.""" import codecs import json import logging from pyquery import PyQuery log = logging.getLogger(__name__) def generate_sections_from_pyquery(body): """Given a pyquery object, generate section dicts for each section.""" # Capture text in...
3,140
959
import contextlib from redbot.core import commands, Config from redbot.core.utils.menus import menu, DEFAULT_CONTROLS import discord import aiohttp import random slytherin = "https://cdn.shopify.com/s/files/1/1325/3287/products/HP8040B_930f8033-607f-41ee-a8e4-fa90871ce7a7.png?v=1546231154" gryffindor = "https://cdn1...
8,427
3,025
from django.shortcuts import render def contact(request): return render(request, 'contacts/contact.html')
117
38
idadevelho=0 s=0 f=0 for p in range(1,3): print('---{}º pessoa---'.format(p)) nome=str(input('digite o {}º nome: '.format(p))).strip() idade=int(input('digite a idade da {}º pessoa: '.format(p))) peso=float(input('digite o peso da {}º pessoa: '.format(p))) sexo=str(input('sexo[M/F]: ')).upper()...
781
300
# -*- coding: utf-8 -*- """ Created on Thu May 3 18:33:28 2018 @author: malopez """ import pandas as pd import matplotlib.pyplot as plt import cv2 images_folder = "C:/Users/malopez/Desktop/disksMD/images" data_folder = "C:/Users/malopez/Desktop/disksMD/data" output_video = './video4.mp4' particle_radius = 1.0 n_part...
1,957
782
# # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # THIS SOFTWARE IS PR...
1,003
323
from django import template from django.utils.safestring import mark_safe import bleach from bleach.sanitizer import BleachSanitizer from bleach.encoding import force_unicode from bootstrap3.renderers import FieldRenderer from bootstrap3.text import text_value import html5lib import re register = template.Library() ...
4,141
1,397
import pytest # from pytest_factoryboy import register def pytest_addoption(parser): parser.addoption( "--slow", action="store_true", default=False, help="run slow tests", ) parser.addoption( "--all", action="store_true", default=False, help="run all tests", ) def _is_connection_psql...
1,158
348
import subprocess from mimetypes import MimeTypes from os import devnull, getcwd, listdir, makedirs, walk from os.path import basename, dirname, exists, isfile, join, splitext from pprint import pprint from urllib.request import pathname2url ALLOWED_AUDIO_MIMETYPES = ['audio/mpeg'] ALLOWED_IMAGE_MIMETYPES = ['image/jp...
2,210
879
print("\033[6;3HHello")
24
14
import sys import difflib import errno import json import logging import functools import os import pytest from shell import shell from diag_paranoia import diag_paranoia, filtered_overview, sanitize_errors VALIDATOR_IMAGE = "datawire/ambassador-envoy-alpine:v1.5.0-116-g7ccb25882" DIR = os.path.dirname(__file__) E...
6,169
1,997
#!/usr/bin/env python3 import json import googlemaps import sys import os gmaps = googlemaps.Client(key=os.environ["GOOGLE_API_KEY"]) print(gmaps) filename = sys.argv[1] with open(filename) as f: data = json.load(f) for d in data: if d.get("address") and not d.get("latitude"): result = gmaps.geocode(...
538
190
import logging import numpy as np import pandas as pd from numba import prange, njit from tardis import constants as const from tardis.plasma.exceptions import PlasmaException from tardis.plasma.properties.base import ( ProcessingPlasmaProperty, Input, TransitionProbabilitiesProperty, ) from tardis.plasm...
48,109
15,730
#!/usr/bin/env python from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser import json import os import codecs from bs4 import BeautifulSoup import argparse import requests import sys import googleapiclient def get_video_info(vid, youtube): respons...
1,805
592