text
string
size
int64
token_count
int64
# Dependencies from bs4 import BeautifulSoup import requests import re import pandas as pd def scrape(): mars_data = {} # Url of website to be scraped url = 'https://mars.nasa.gov/news/' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # get the lates...
3,685
1,330
#!/usr/bin/env python import os import re import csv def fil(): filetext = os.path.join(os.path.dirname(__file__),'meditech_data','RAW') #filetext = "C:/Users/gcampuzanozuluaga/Dropbox/Programming/Python/APPS/meditech_data/MT/RAW" outtext_temp = os.path.join(os.path.dirname(__file__),'meditec...
10,165
4,305
import numpy as np from plots import plots_for_predictions as pp from utilss import distinct_colours as dc import matplotlib.pyplot as plt c = dc.get_distinct(4) path = '/Users/luisals/Documents/deep_halos_files/mass_range_13.4/random_20sims_200k/lr5e-5/' p1 = np.load(path + "seed_20/predicted_sim_6_epoch_09.npy") t1...
3,144
1,342
# -*- coding: utf-8 -*- REGIONS = {'USRI': 'Rhode Island', 'UY02': 'Canelones', 'KR21': 'Ulsan-gwangyoksi', 'KR20': 'Kyongsang-namdo', 'KM02': 'Grande Comore', 'KM03': 'Moheli', 'CO22': 'Putumayo', 'BN18': 'Zou', 'BN17': 'Plateau', 'BN16': 'Oueme', 'BN15': 'Tutong', 'BN14': 'Littoral', 'BN13': 'Donga', 'BN12': 'Kouffo...
85,945
45,215
_base_config_ = ["base.py"] generator = dict( input_cse=True, use_cse=True ) discriminator=dict( pred_only_cse=False, pred_only_semantic=True ) loss = dict( gan_criterion=dict(type="segmentation", seg_weight=.1) )
236
98
# -*- coding:utf-8 -*- # @author xupingmao <578749341@qq.com> # @since 2020/10/20 00:19:47 # @modified 2020/10/20 00:42:52 import sys sys.path.append("src/python") from mp_encode import * def test_compile(fname): input_fname = "test/compiler/case/%s-input.py" % fname output_fname = "test/compiler/case/%s-o...
676
287
from copy import deepcopy from inspect import getfullargspec import importlib import json import os import logging logger = logging.getLogger(__name__) from torch.optim.optimizer import Optimizer from paragen.optim.optimizer import Optimizer from paragen.utils.rate_schedulers import create_rate_scheduler from paragen...
3,719
1,143
from __future__ import unicode_literals from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .models import Events, Gallery, News, Careers, Partners from django.core.mail import send_mail,BadHeaderError from django.conf import settings from.forms import ContactFo...
2,860
819
from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import Event, Speaker class EventAdmin(SummernoteModelAdmin): summernote_fields = ("content",) admin.site.register(Event, EventAdmin) admin.site.register(Speaker)
274
84
from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import sys python_version = sys.version_info[0] setup( name='batch_jaro_winkler', ext_modules=cythonize([Extension('batch_jaro_winkler', ['cbatch_jaro_winkler.pyx'])], language_level=python_version) )
318
111
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/type/postal_address.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import r...
6,647
2,491
from ...data_connector import Connector from os import environ def test_data_connector() -> None: token = environ["DATAPREP_DATA_CONNECTOR_YELP_TOKEN"] dc = Connector("yelp", _auth={"access_token": token}) df = dc.query("businesses", term="ramen", location="vancouver") assert len(df) > 0 dc.info...
612
243
import os import torch import numpy as np import math import matplotlib.pyplot as plt from matplotlib import cm from qutip import * import imageio plt.rcParams['axes.labelsize'] = 16 from matplotlib import rc rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True) def animate_recon(xt,...
6,294
2,457
# State tracking for WireGuard protocol operations. # Author: Peter Wu <peter@lekensteyn.nl> # Licensed under the MIT license <http://opensource.org/licenses/MIT>. import base64 import hashlib import inspect import socket import traceback from noise_wg import NoiseWG, crypto_scalarmult_base, aead_encrypt, aead_decryp...
17,348
5,961
from common import Modules, data_strings, load_yara_rules, AndroidParseModule, ModuleMetadata from base64 import b64decode from string import printable class dendroid(AndroidParseModule): def __init__(self): md = ModuleMetadata( module_name="dendroid", bot_name="Dendroid", ...
2,007
542
import datetime import uuid from django.test import TestCase from mock import patch from requests import ConnectionError from couchforms.analytics import ( app_has_been_submitted_to_in_last_30_days, domain_has_submission_in_last_30_days, get_all_xmlns_app_id_pairs_submitted_to_in_domain, get_exports_b...
8,942
3,116
from pydantic.dataclasses import dataclass from ...models import VAEConfig @dataclass class SVAEConfig(VAEConfig): r""" :math:`\mathcal{S}`-VAE model config config class Parameters: input_dim (int): The input_data dimension latent_dim (int): The latent space dimension in which lives the ...
462
139
# Parts of code taken from https://www.kaggle.com/aloisiodn/python-3-download-multi-proc-prog-bar-resume by Dourado. # Improvements on the original script: # * you can choose which dataset to download; # * uses threads instead of processes; # * unpacks data into .../label/id.jpg directory structure, which can be ...
7,486
2,303
""" Function def function_name(arg1, arg2, ...) : <op 1> <op 2> ... Function with undefined amount of input def fn_name(*args) --> args' elements make tuple. kwargs = Keyword Parameter >>> def print_kwargs(**kwargs): ... print(kwargs) ... >>> print_kwargs(a=1) {...
790
257
all import tweepy, config, users, re, groupy from tweepy import OAuthHandler from tweepy import API print(tweepy.__version__) auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token,config.access_token_secret) api = tweepy.API(auth) from groupy.client import Client cli...
2,437
847
""" ---OK--- """ from collections import OrderedDict import copy import numpy as np from crystalpy.examples.Values import Interval class PlotData1D(object): """ Represents a 1D plot. The graph data together with related information. """ def __init__(self, title, title_x_axis, title_y_axis): ...
8,486
2,465
from .usersim_rule import * from .realUser import *
51
16
import os import logging import shutil import zipfile import xmltodict from lxml import etree from osgeo import ogr, osr from django.core.exceptions import ValidationError from django.db import models, transaction from django.utils.html import strip_tags from django.template import Template, Context from dominate.ta...
38,534
10,717
import unittest from iptree import IPNode class TestIPNode(unittest.TestCase): def test_node_ipv4(self): node = IPNode('0.0.0.0/0') node.add(IPNode('127.0.0.1/32')) assert '127.0.0.1/32' in node assert '192.0.2.1/32' not in node def test_node_ipv6(self): node = IPNode...
1,313
504
# Python - 3.4.3 Test.it('Basic Tests') Test.assert_equals(invert([1, 2, 3, 4, 5]), [-1, -2, -3, -4, -5]) Test.assert_equals(invert([1, -2, 3, -4, 5]), [-1, 2, -3, 4, -5]) Test.assert_equals(invert([]), [])
208
113
import csv import random import warnings import os from locust import HttpUser, task, between body = { "campaignid":"5kXk20gGDISJdM5el5IT", "walletamount":"0" } header = { "Host": "fkhapi.sastasundar.com", "Apptype": "N", "Appversion": "4.0.4", "Appversioncode": "109", "Deviceid": "81653d...
1,239
524
"""Contains the grid class to create multiple figures.""" from typing import Optional, Tuple from .figure import Figure import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt class Grid: def __init__( self, rows: int, cols: int, size: Optional[Tuple[float, float]] = None ): ""...
1,358
386
# Copyright 2021 The ParallelAccel Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
30,005
8,449
try: from configparser import RawConfigParser except ImportError: from ConfigParser import RawConfigParser class GodotConfigFile(RawConfigParser): def write(self, fp): """Write an .ini-format representation of the configuration state.""" if self._defaults: fp.write("[%s]\n" % D...
1,040
311
import collections def cal(num): i=1 f=factor[num] while i*i<=num: if num%i==0 and i<=max(n,m) and num//i<=max(n,m): f.append(i) i+=1 return num def dfs(i,j): if i==m-1 and j==n-1: return True if i>=m and j>=n or grid[i][j] in factor: ...
683
295
import os import pydicom import numpy as np import dicom_numpy from utils import hidden_errors from tf_utils import * from pathlib import Path def read_dicom_folder(dicom_folder, rescale=None): ''' Reads all .dcm files in `dicom_folder` and merges them to one volume Returns: The volume and the affine...
2,556
833
import sys from PyQt5.QtCore import Qt, QSize, QPoint from PyQt5.QtWidgets import QApplication, QDialog, QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout from PyQt5.QtGui import QPainter, QColor, QPen, QFont from .sudoku import Sudoku class SudokuWidget(QWidget): def __init__(self, parent=None): supe...
5,056
1,762
# ------------------------------------------------------------------------------------------------------ # Copyright (c) Leo Hanisch. All rights reserved. # Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information. # ---------------------------------------------------------...
1,042
297
# -*- coding: UTF-8 -*- from collections import deque class NetworkEntity(object): """Client or Server simulation network entity""" def __init__(self, name): # "client" or "server" self.name = name # simulatation packet list(queue) # _packet_list contains send/recv PacketBuff...
1,695
596
#!/usr/bin/env python """interp_spline_interest.py: Demonstrate spline interpolation. """ from scipy.interpolate import splrep, splev import numpy as np import matplotlib.pyplot as plt # pylint: disable=invalid-name # Interest rates of Jan, Feb, Mar, Jun, Dec. x = np.array([1, 2, 3, 6, 12]) y = np.array([0.080, 0.100...
898
396
import unittest import numpy as np from optimizer import SGD from modules import ConvNet from .utils import * class TestSGD(unittest.TestCase): """ The class containing all test cases for this assignment""" def setUp(self): """Define the functions to be tested here.""" pass def test_sgd(s...
1,351
484
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\tunable_utils\create_object.py # Compiled at: 2020-05-07 00:26:47 # Size of source mod 2**32: 4106 b...
3,373
1,003
# # @lc app=leetcode.cn id=47 lang=python3 # # [47] 全排列 II # # https://leetcode-cn.com/problems/permutations-ii/description/ # # algorithms # Medium (59.58%) # Likes: 371 # Dislikes: 0 # Total Accepted: 78.7K # Total Submissions: 132.1K # Testcase Example: '[1,1,2]' # # 给定一个可包含重复数字的序列,返回所有不重复的全排列。 # # 示例: # # ...
1,583
627
import subprocess as sp import sys sp.run(["pip", "install", "-e", "."], check=True) sp.run(["pytest", "blobfile"] + sys.argv[1:], check=True)
149
60
import Sofa import random from cmath import * ############################################################################################ # this is a PythonScriptController example script ############################################################################################ ###################################...
6,467
2,671
import tensorboardX with tensorboardX.SummaryWriter("foo") as w: w.add_scalar("a", 1.0, 1) w.add_scalar("a", 2.0, 2) with tensorboardX.SummaryWriter("foo/bar") as w: w.add_scalar("a", 3.0, 3) w.add_scalar("a", 4.0, 4) with tensorboardX.SummaryWriter("foo/bar/baz") as w: w.add_scalar("a", 5.0, 5) ...
350
171
############################################################################### # Copyright 2020 UChicago Argonne, LLC. # (c.f. AUTHORS, LICENSE) # For more info, see https://xgitlab.cels.anl.gov/argo/cobalt-python-wrapper # SPDX-License-Identifier: BSD-3-Clause #########################################################...
444
137
#!/usr/bin/env python3 import os orderNumbers = open("orders.txt", "r") #Order numbers to match #Network path to a directory of files that has full details of the order directoryEntries = os.scandir("") outputFile = open("matchedData.dat", "w") for entry in directoryEntries: print("Currently parsing file ", en...
859
245
import pytest import rasterio as rio from rasterio.io import DatasetWriter from cog_worker import Manager from rasterio import MemoryFile, crs TEST_COG = "tests/roads_cog.tif" @pytest.fixture def molleweide_manager(): return Manager( proj="+proj=moll", scale=50000, ) @pytest.fixture def sam...
2,968
1,117
from train import train_model from utils import * import os import sys pwd = os.environ.get('CLIP_DIR') DATA_DIR = "%s/data/processed/" % pwd exp_name = "non_multilabel" run_name = "sentence_structurel_with_crf" train_file_name = "MIMIC_train_binary.csv" dev_file_name = "MIMIC_val_binary.csv" test_file_name = "test_b...
1,031
394
from django.urls import path from . import views app_name = 'persons' urlpatterns = [ path('', views.PersonsTableView.as_view(),name='persons_list'), path('persons_details/<int:pk>',views.PersonsUpdateView.as_view(),name='persons_details_edit'), path('persons_details/create',views.PersonsCreateView.as_vie...
528
178
__title__ = 'logxs' __description__ = 'Replacing with build-in `print` with nice formatting.' __url__ = 'https://github.com/minlaxz/logxs' __version__ = '0.3.2' __author__ = 'Min Latt' __author_email__ = 'minminlaxz@gmail.com' __license__ = 'MIT'
246
96
import time class System(object): manditory = [] optional = [] handles = [] def __init__(self, node_factory): self.node_factory = node_factory def process(self): for node in self.get_nodes(): # print(f"{self.__class__.__name__} system got message from # {n...
977
295
from hytra.pluginsystem import transition_feature_vector_construction_plugin import numpy as np from compiler.ast import flatten class TransitionFeaturesSubtraction( transition_feature_vector_construction_plugin.TransitionFeatureVectorConstructionPlugin ): """ Computes the subtraction of features in the f...
2,918
679
from matplotlib.style import available import pygame as pg from sprites.character import Character from pygame.math import Vector2 from settings import * from math import cos, pi from control import Controler from sprites.gun import MachineGun, Pistol, Rifle from managers.resourcemanager import ResourceManager as GR fr...
5,438
1,743
# # Gtk+ UI pieces for BitBake # # Copyright (C) 2006-2007 Richard Purdie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be ...
716
225
# -*- coding: utf-8 -*- from django.db import migrations from tardis.tardis_portal.models import ( Schema, ParameterName, DatafileParameter, DatafileParameterSet ) from mytardisbf.apps import ( OMESCHEMA, BFSCHEMA ) def forward_func(apps, schema_editor): """Create mytardisbf schemas and pa...
10,198
2,954
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime # Create your models here. class IP_Address(models.Model): ip = models.GenericIPAddressField(verbose_name=u"IP地址") gateway = models.GenericIPAddressField(verbose_name=u"网关") network = models.GenericIPAddressField(verbose_name...
1,473
574
#!/usr/bin/env python3 # # Copyright (c) 2021, The OpenThread Authors. # 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 # ...
9,616
3,395
import time import logging try: from pypylon import pylon except: pylon = None from . input import Input log = logging.getLogger(__name__) # writes the framenumber to the 8-11 bytes of the image as a big-endian set of octets def encode_framenumber(np_image, n): for i in range(4): np_image[0][i+7]...
3,457
1,039
# -*- coding: utf-8 -*- # Copyright (c) 2021. Distributed under the terms of the MIT License. from phonopy.interface.calculator import read_crystal_structure from phonopy.structure.atoms import PhonopyAtoms from vise.util.phonopy.phonopy_input import structure_to_phonopy_atoms import numpy as np def assert_same_phon...
3,100
1,023
""" 2020 Day 15 https://adventofcode.com/2020/day/15 """ from collections import deque from typing import Dict, Iterable, Optional import aocd # type: ignore class ElfMemoryGame: def __init__(self, starting_numbers: Iterable[int]): self.appearances: Dict[int, deque[int]] = {} self.length = 0 ...
1,419
490
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
1,121
269
from typing import Any, TypeVar, Union from types import MethodType, FunctionType from .base_types import BooleanType, Constant, StringType, Collection, Referenceable from .type_checking import TypeChecker AnyArgs = TypeVar("AnyArgs") NoArgs = TypeVar("NoArgs") VarArgs = TypeVar("VarArgs") T = TypeVar("T") class W...
8,796
2,663
"""This script is for training and evaluating a model.""" import sys import os import traceback import numpy as np from functools import partial from utils import * from punctuator import Punctuator from bidirectional_gru_with_gru import BidirectionalGruWithGru from keras.callbacks import ModelCheckpoint from keras.m...
5,741
1,811
""" Contains a canned predictor for a GQN. """ import os import json import numpy as np import tensorflow as tf from .gqn_graph import gqn_draw from .gqn_params import create_gqn_config def _normalize_pose(pose): """ Converts a camera pose into the GQN format. Args: pose: [x, y, z, yaw, pitch]; x, y, z i...
5,719
2,152
# -*- coding: utf-8 -*- # Copyright (C) 2019, QuantStack # SPDX-License-Identifier: BSD-3-Clause from conda.base.constants import DepsModifier, UpdateModifier from conda._vendor.boltons.setutils import IndexedSet from conda.core.prefix_data import PrefixData from conda.models.prefix_graph import PrefixGraph from conda...
6,054
1,907
num = input() lucky = 0 for i in num: if i == '4' or i == '7': lucky += 1 counter = 0 for c in str(lucky): if c == '4' or c == '7': counter += 1 if counter == len(str(lucky)): print("YES") else: print("NO")
264
113
from snakebids.utils.output import ( Mode, get_time_hash, prepare_output, retrofit_output, write_config_file, write_output_mode, ) from snakebids.utils.snakemake_io import ( glob_wildcards, regex, update_wildcard_constraints, ) __all__ = [ "Mode", "get_time_hash", "glob_...
477
181
import pydantic from vizno.renderers import ContentConfiguration, render from vizno.report import Report class CustomObject(pydantic.BaseModel): parameter: int class CustomRenderConfiguration(ContentConfiguration): parameter: int @render.register def _(obj: CustomObject): return CustomRenderConfigura...
659
191
import abc import collections.abc import socket __all__ = ['get_socket_type', 'get_server_socket', 'get_client_socket', 'SocketReader', 'SocketWriter', 'JSONReader', 'JSONWriter'] def get_socket_type(host=None, ip_type=None): if ip_type is not None: return ip_type if host and ':' in host...
945
316
from django.urls import path, include from django.contrib import admin import hackdayproject.main.urls as main_urls import hackdayproject.repo.urls as repo_urls urlpatterns = [ path('admin/', admin.site.urls), path('oauth/', include('social_django.urls', namespace='social')), path('', include(main_urls)), ...
360
109
#!/usr/bin/env python import unittest import logging import importlib import copy import os from mock import patch from nose.tools import raises logging.disable(logging.CRITICAL) ciftify_recon_all = importlib.import_module('ciftify.bin.ciftify_recon_all') class ConvertFreesurferSurface(unittest.TestCase): meshe...
19,134
6,245
# -*- coding: utf-8 -*- ''' Created on Tue Jan 17 16:19:36 2017 @author: Boykai ''' #!/usr/bin/env python # -*- coding: utf-8 -*- import xml.etree.cElementTree as ET # Use cElementTree or lxml if too slow from collections import defaultdict import re import pprint import string import codecs import json import os f...
35,831
9,498
r""" Currently, this package is experimental and may change in the future. """ from __future__ import absolute_import #------------------------------------------------------------------------------ # this little trick is for static builds of VTK. In such builds, if # the user imports this Python package in a non-stat...
640
148
from django.db import models from django.contrib.auth.models import User # Create your models here. class Client(models.Model): user = models.OneToOneField(User,null=True,blank= True,on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) # def __str__(self): # return self.name...
1,176
399
from django.db import models """ ShipmentModels have a one to many relationship with boxes and aliquot Aliquot and Box foreign keys to a ShipmentModel determine manifest contents for shipping purposes (resolved in schema return for manifest view) """ class ShipmentModel(models.Model): carrier = model...
1,299
352
""" Consuming Iterator manually """ from collections import namedtuple def cast(data_type, value): """Cast the value into a correct data type""" if data_type == 'DOUBLE': return float(value) elif data_type == 'STRING': return str(value) elif data_type == 'INT': return int(value...
1,857
603
#! Copyright (C) 2017 Christian Stransky #! #! This software may be modified and distributed under the terms #! of the MIT license. See the LICENSE file for details. from flask import Flask, redirect, request, make_response from shutil import copyfile import json import requests import os.path import uuid ...
1,675
561
import numpy as np import math import logging from termcolor import colored # Check a matrix for: negative eigenvalues, asymmetry and negative diagonal values def positive_definite(M,epsilon = 0.000001,verbose=False): # Symmetrization Mt = np.transpose(M) M = (M + Mt)/2 eigenvalues = np.linalg.eigvals(...
672
209
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ I=lambda:map(int,input().split()) f=abs n,_,a,b,k=I() while k: p,q,u,v=I() P=[a,b] if a<=q<=b:P+=[q] if a<=v<=b:P+=[v] print([min(f(q-x)+f(v-x)for x in P)+f(p-u),f(q-v)][p==u]) k-=1
282
166
import json import sys import pandas args = sys.argv if len(args) == 1 : import main as settings else : import sub as settings from requests_oauthlib import OAuth1Session CK = settings.CONSUMER_KEY CS = settings.CONSUMER_SECRET AT = settings.ACCESS_TOKEN ATS = settings.ACCESS_TOKEN_SECRET t...
850
329
"""This module contains a function for validating a scratch config entry.""" import re from idact.detail.config.validation.validation_error_message import \ validation_error_message VALID_SCRATCH_DESCRIPTION = 'Non-empty absolute path, or environment' \ ' variable name.' VALID_SCRATC...
1,284
392
import warnings from typing import Callable, List, Optional, Union import mpmath import numpy as np import paramak import sympy as sp from paramak import RotateMixedShape, diff_between_angles from paramak.parametric_components.tokamak_plasma_plasmaboundaries import \ PlasmaBoundaries from scipy.interpolate import...
10,135
2,781
s=str(input()) a=[] for i in range(len(s)): si=s[i] a.append(si) b=[] n=str(input()) for j in range(len(n)): sj=n[j] b.append(sj) p={} for pi in range(len(s)): key=s[pi] p[key]=0 j1=0 for i in range(0,len(a)): key=a[i] while j1<len(b): bj=b[0] if key in p: p[k...
907
430
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import datetime import json from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Union import plaid from airbyte_cdk.logger import AirbyteLogger from airbyte_cdk.models import SyncMode from airbyte_cdk.sources import AbstractSou...
4,352
1,319
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import os import shutil from PIL import Image import torch import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils...
17,939
6,688
from __future__ import division import sqlite3 from bisect import bisect_left import plotly.plotly as py from plotly.graph_objs import Scatter, Figure, Layout, Data, YAxis, XAxis from feemodel.util import DataSample from feemodel.app.predict import PVALS_DBFILE from feemodeldata.plotting.plotrrd import BASEDIR de...
2,749
969
import torch import torch.nn.functional as F from torch.autograd import Variable import numpy as np import os import math from utils import logger use_cuda = torch.cuda.is_available() # utility def to_var(x, dtype=None): if type(x) is np.ndarray: x = torch.from_numpy(x) elif type(x) is list: ...
5,181
1,883
from dataclasses import field from marshmallow import Schema, ValidationError, post_load, schema from marshmallow.validate import OneOf, Length from marshmallow.fields import Bool, Str, List, Nested, Email from flask_rebar import ResponseSchema, RequestSchema, errors from ecosante.inscription.models import Inscription ...
3,630
1,110
import math # Exercise 017: Right Triangle """Write a program that reads the length of the opposite side and the adjacent side of a right triangle. Calculate and display the length of the hypotenuse.""" # To do this we will use the Pythagorean theorem: a^2 = b^2 + c^2 # Method 01, without the module Math: # First we...
933
351
"""Package groups the different commands modules.""" from annuaire.commands import download, import_lawyers __all__ = [download, import_lawyers]
146
41
import logging from thespian.actors import * from eventsourcing.application.process import ProcessApplication, Prompt from eventsourcing.application.system import System, SystemRunner from eventsourcing.domain.model.events import subscribe, unsubscribe from eventsourcing.interface.notificationlog import RecordManager...
15,883
4,404
"""This module implements backtracking algorithm to solve sudoku.""" class Board: """ Class for sudoku board representation. """ NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9] def __init__(self, board): """ Create a new board. """ self.board = board def __str__(self) ...
4,517
1,329
# Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Aggregator module.""" import base64 import json import os import platform import shutil import signal import subprocess import time import urllib.request from logging import getLogger from pathlib import Path from subprocess import c...
9,603
3,300
from pearce.emulator import OriginalRecipe, ExtraCrispy import numpy as np training_file = '/home/users/swmclau2/scratch/PearceRedMagicWpCosmo.hdf5' em_method = 'gp' split_method = 'random' a = 1.0 z = 1.0/a - 1.0 fixed_params = {'z':z, 'cosmo': 1}#, 'r':0.18477483} n_leaves, n_overlap = 5, 2 emu = ExtraCrispy(tra...
574
242
# -*- coding: utf-8 -*- # pylint: disable=missing-docstring,unused-import,reimported import json import pytest # type: ignore import xmllint_map_html.xmllint_map_html as xmh def test_parse_ok_minimal(): job = ['[]'] parser = xmh.parse(job) assert next(parser) == NotImplemented
294
115
from rest_framework import mixins, viewsets, status from rest_framework.permissions import ( AllowAny, IsAuthenticated ) from apps.transmissions.models import Transmission from apps.transmissions.serializers import TransmissionModelSerializer, CommentModelserializer from django_filters import rest_framework a...
1,318
353
from amstramdam import app, socketio, timers, manager from flask import session from flask_socketio import emit from .types import GameEndNotification, GameEndPayload from .utils import safe_cancel, wait_and_run from ..game.types import GameName, Coordinates def terminate_game(game_name: GameName) -> None: game ...
4,751
1,498
__copyright__ = 'Copyright(c) Gordon Elliott 2017' """ """ from datetime import date from decimal import Decimal from io import StringIO from unittest import TestCase from glod.model.statement_item import StatementItem from glod.model.account import Account from glod.in_out.statement_item import statement_item_csv...
1,515
508
# Tested with Python 3.6 # Install Pillow: pip install pillow """ This script extracts exif data from JPEG images """ from PIL import Image from PIL.ExifTags import TAGS import sys def getExif(img): res = {} exif = img._getexif() if exif == None: print("No exif data found!!") ...
1,072
382
SCHEMA_VERSION = 2 from .common import ValidationError, SchemaMismatchError from .v2 import MetadataValidatorV2 as MetadataValidator from .v2 import read_v2 as read, write_v2 as write from .v2 import reads_v2 as reads, writes_v2 as writes
240
79
import h5py from ont_fast5_api.conversion_tools import multi_to_single_fast5 from ont_fast5_api import fast5_interface import SequenceGenerator.align as align import SignalExtractor.Nanopolish as events from testFiles.test_commands import * import os, sys import subprocess #todo get basecall data def bas...
9,537
3,126
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # streamondemand-pureita.- XBMC Plugin # Canale italiaserie # http://www.mimediacenter.info/foro/viewtopic.php?f=36&t=7808 # ------------------------------------------------------------ import re from core import httptools from cor...
7,702
2,249
from setuptools import setup setup( name='potnanny-api', version='0.2.6', packages=['potnanny_api'], include_package_data=True, description='Part of the Potnanny greenhouse controller application. Contains Flask REST API and basic web interface.', author='Jeff Leary', author_email='potnanny...
629
217