text
string
size
int64
token_count
int64
#Author: Rahil Gandotra #This file consists of the custom Mininet topology used for GPF. from mininet.topo import Topo class MyTopo(Topo): def __init__(self): Topo.__init__(self) h1 = self.addHost('h1') h2 = self.addHost('h2') s1 = self.addSwitch('s1', listenPort=6675, dpid='0000...
916
422
def timeNow(): import time rightNow = time.localtime(time.time()) date = time.strftime("%a %b %d", rightNow) time = time.strftime("%H:%M:%S", rightNow) timeStamp = { "time": time, "date": date } print timeStamp['time'] return timeStamp
250
104
# coding=utf-8 import logging import rarfile import os from subliminal.exceptions import ConfigurationError from subliminal.providers.legendastv import LegendasTVSubtitle as _LegendasTVSubtitle, \ LegendasTVProvider as _LegendasTVProvider, Episode, Movie, guess_matches, guessit, sanitize, region, type_map, \ r...
10,819
2,989
import re class Position(object): def __init__(self): self.total_in = None self.total_out = None self.ticker_symbol = None self.total_number_of_shares = None self.remaining_number_of_shares = None self.open_date = None self.close_date = None def format_d...
1,587
567
#!/usr/bin/python3 # -*- coding:utf-8 -*- # Project: http://plankton-toolbox.org # Copyright (c) 2010-2018 SMHI, Swedish Meteorological and Hydrological Institute # License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit). import time import codecs from PyQt5 import QtWidgets from PyQt5 i...
15,789
4,605
#!/usr/bin/env python # this.py --- Example of This predefined trait from traits.api import HasTraits, This class Employee(HasTraits): manager = This #--------------------------------------- # Extrat class Executive(Employee): pass fred = Employee() mary = Executive() # The following is OK, because fred's...
481
137
import boto3 import json import logging import os bucket = os.environ['UPLOAD_BUCKET'] role_arn = os.environ['ASSUMED_ROLE_ARN'] sts_client = boto3.client('sts') logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def lambda_handler(event, context): body ...
1,443
454
"""2017 - Day 5 Part 2: A Maze of Twisty Trampolines, All Alike tests.""" from src.year2017.day05b import solve def test_solve(): assert solve("0\n3\n0\n1\n-3") == 10
173
82
import unittest from manticore.utils.event import Signal class Sender(object): def __init__(self): self.sig = Signal() self.sig2 = Signal() class ManticoreDriver(unittest.TestCase): def setUp(self): self.state = {} def tearDown(self): pass def setReceived(self, key,...
1,374
457
# Generated by Django 3.1.4 on 2020-12-27 17:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0004_token'), ] operations = [ migrations.CreateModel( name='Passwordresetcodes', fields=[ ('...
745
221
from distutils.core import setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="dbprime", version="0.1dev", author="Dalton Dirkson", author_email="sodakdoubled@gmail.com", packages=["dbprime",], )
253
95
# Largest product in a series ''' The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 1254069874715852386305071...
2,491
2,193
import os import re from contextlib import contextmanager import numpy as np import six __all__ = ['humanize_duration', 'camel_to_underscore', 'NOT_SET', 'cached_property', 'clear_cached_property', 'maybe_close', 'iter_files'] def humanize_duration(seconds): """ Format specified time d...
4,102
1,286
# -*- coding: utf-8 -*- """ Created on 2020/8/6 @project: SPAIC @filename: Backend @author: Hong Chaofei @contact: hongchf@gmail.com @description: 定义网络仿真使用的backend,如 Pytorch, Tensorflow, CUDA, 达尔文芯片等,以及相应的微分方程求解方法比如 Euler, 2阶 Runge-Kutta等 """ from abc import abstractmethod, ABC from collections import OrderedDict from ...
54,598
15,574
import cv2 import numpy as np from PIL import Image import os #Verilerin yolu path = "veriseti" recognizer = cv2.face.LBPHFaceRecognizer_create() detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') #imajların alınması ve etiketlenmesi için fonksiyon def getImageAndLabels(pa...
1,257
519
import kivy from kivy.app import App from kivy.uix.button import Label from kivy.uix.colorpicker import ColorPicker from kivy.graphics import Color, Ellipse, Triangle from kivy.properties import StringProperty, ObjectProperty class Titulo(Label): cadena=StringProperty("Jesus te ama...") triangle=ObjectProperty(Non...
1,846
754
from datetime import date maior = menor = 0 atual = date.today().year for c in range(1, 8): nascimento = int(input(f'Em que ano a {c}ª pessoa nasceu? ')) if atual - nascimento > 20: maior += 1 else: menor += 1 print(f'Ao todo, temos {maior} pessoas maiores de idade!') print(f'Ao todo, temos ...
356
137
# -*- coding: utf-8 -*- # zdfneo.py - Aufruf durch __init__.py/ZDF_get_content # # Die Funktionen dienen zur Auswertung der ZDF-Neo-Seiten # Neo_Base = 'https://www.neo-magazin-royale.de' PREFIX = '/video/ardmediathek2016/zdfneo' ##################################################################################...
6,356
2,570
import numpy as np from openbabel import openbabel as ob import logging logger = logging.getLogger() class AtomData: """Store atomic data (atomic number, coordinates, bond type, and serial number). Parameters ---------- atomic_num : int Atomic number. coord : array_like of float (size 3)...
8,732
2,746
import discord, itertools from discord.ext import commands, tasks # Lava is not allowed to change the first text PRESENCE_TEXT = itertools.cycle(["lava is cute", "*pushes you against wall* wanna play fortnite amongus?", "with ur mum", "owo.exe", "dangit jelly", "gewrhgkhewghkhfuckoiyo5uo", "MiEWcWAFT?? OWOWO"]) class...
1,379
466
# Aim is to apply a multiplier to the natural capital scores to reflect the degree of public access # Challenge is that it is difficult to clip or intersect the complex public access layer with the large and # detailed OSMM-based base map - it takes days to run and then fails. # So here we extract a subset of the base ...
33,808
10,700
""" this script parses the pds-rings press release gallery tree at base_url = "http://pds-rings.seti.org/saturn/cassini/" if an image already exists in the database it is updated to get only the most recent month set latest_month_only to True """ latest_month_only = True # like I was really going to do this monthly ...
3,688
1,224
from flask import Blueprint, jsonify, request from packit_dashboard.utils import return_json from packit_dashboard.config import API_URL api = Blueprint("api", __name__) # The react frontend will request information here instead of fetching directly # from the main API. # This is because it will be easier to implemen...
856
287
""" Authentication Utility Functions """ from flask import session from models import Patient, Doctor, Degree, database import hashlib, binascii from config import SECRET_KEY def get_degrees(): return [ degree.to_dict() for degree in Degree.query.all() ] def register_user(user_data): registration_details = ...
4,959
1,495
from __future__ import absolute_import, division, print_function import boost.python ext = boost.python.import_ext("cctbx_eltbx_covalent_radii_ext") from cctbx_eltbx_covalent_radii_ext import * boost.python.inject(ext.table_iterator, boost.python.py3_make_iterator)
267
97
from nba_py import player from numpy import mean import league from consts import all_time_stats import consts name_to_index = {'season': 1, consts.rebounds: 20, consts.assists: 21, consts.steals: 22, consts.blocks: 23, consts.points: 26} class Player: def __init__(self, first, last): print 'Getting {} ...
4,004
1,193
# -*- coding: utf-8 -*- """ Created on Thu Jan 10 18:34:07 2019 计算WMM2015模型,WMM.cof文件需要放到与py相同目录 @author: chens """ import numpy as np from pathlib import Path import xarray import ctypes as ct import sys import datetime from matplotlib.pyplot import figure #libwmm = ct.cdll.LoadLibrary(str('D:\\MyWorks\\WMM2015-mast...
3,668
1,551
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may # not use this file except in compliance with the License. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanyin...
3,089
1,051
""" Contains all the functions related to the search of enitities in the Database """ from tabulate import tabulate def SearchPlayerByName(cur, con): """ Searches for the provided name's similar occurences in the Player's first and last name """ # Take in the input for the search query search = {} s...
2,862
807
# SPDX-License-Identifier: GPL-2.0 # Copyright (c) 2019, Cristian Ciocaltea <cristian.ciocaltea@gmail.com> # # Work based on: # - test_net.py # Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. # - test_fit.py # Copyright (c) 2013, Google Inc. # # Test launching UEFI binaries from FIT images. """ Note: This...
15,413
4,753
#!/usr/bin/env python import report, sys import psycopg2.extras parser = report.get_parser(sys.argv[0]) parser.add_argument('--title', '-t', required=False, dest='title', default="Data Dictionary", help='Report Title') args = parser.parse_args() conn = report.get_connection(args) curs = conn.cursor(cursor_factory=p...
2,234
696
class LinkedList: def __init__(self, data, next='None'): self.data = data self.next = next def takeinputLL(): inputlist = [int(x) for x in input().split()] head = None temp = None for cur in inputlist: if cur == -1: break Newnode = LinkedList(cur) ...
1,112
341
"""empty message Revision ID: 458a7da0c9da Revises: Create Date: 2018-05-01 21:15:27.029811 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '458a7da0c9da' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
2,581
1,068
def ngrams(sequence, n): return list(zip(*[sequence[i:(len(sequence) - (n - 1) + i)] for i in range(n)]))
110
45
import torch import mimic.modalities.utils from mimic.modalities.Modality import ModalityIMG class MimicLateral(ModalityIMG): def __init__(self, enc, dec, args): self.name = 'Lateral' self.likelihood_name = 'laplace' self.data_size = torch.Size((1, args.img_size, args.img_size)) s...
573
198
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
40,564
12,323
import os, sys, shutil from cx_Freeze import setup, Executable from pathlib import Path def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks,...
1,131
389
import os import time import jwt import ldap from eve.auth import TokenAuth from flask import Blueprint, abort, jsonify, request blueprint = Blueprint("login", __name__) ADMIN_USERS = os.environ.get("ADMIN_USERS", "papanowel@gmail.com") JWT_ALGORITHM = os.environ.get("JWT_ALGORITHM", "HS256") JWT_EXPIRE_OFFSET = os....
5,332
1,720
#!/usr/bin/env python # vim: set fileencoding=utf-8 : from distutils.core import setup setup( name="pinyin-comp", version="0.1", description="complete path containing Chinese by pinyin acronym", author="Jekyll Wu", author_email="adaptee@gmail.com", url="http://www.github.com/a...
411
139
def importFromGeoJson(geoJsonName): #driver = ogr.GetDriverByName('geojson') dataSource = ogr.Open(geoJsonName, 0) layer = dataSource.GetLayer() print(layer.GetFeatureCount()) polys = [] image_id = 1 building_id = 0 for feature in layer: building_id = building_id + 1 ...
472
160
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Implement an LRU (Least Recently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods: set(key, value): sets key to value. If there are already n items in ...
1,518
504
# -*- coding: utf-8 -*- from setuptools import setup # Metadata goes in setup.cfg. These are here for GitHub's dependency graph. setup( name="Teeb", install_requires=["chardet==4.0.0", "send2trash==1.5.0", "wand==0.6.5"], )
233
94
#!/usr/bin/env python3 """Constructs article graph.""" from database import clear_db from database.constants import engine from .database_builder import populate_db if __name__ == "__main__": clear_db(engine) populate_db()
233
72
def post_to_solr(article): import settings from pysolarized import solr, to_solr_date solr_int = solr.Solr(settings.SOLR_ENDPOINT_URLS, settings.SOLR_DEFAULT_ENDPOINT) # Build documents for solr dispatch doc = {"id": article["id"], "title": article["title"], "source": article["source"]...
624
205
from pydantic import BaseSettings class DeezerSettings(BaseSettings): api_host: str = 'https://api.deezer.com' user_info_path: str = 'user/me' playlists_path: str = 'user/me/playlists' playlist_tracks_path: str = 'playlist/{}/tracks' @property def user_info_url(self) -> str: return f...
637
234
# -*- coding: utf-8 -*- from flask import Blueprint, jsonify, request from functools import wraps from sqlalchemy import desc from project.common import app, db, fb_api from project.config import ApiConfig from project.models import Client, Message api = Blueprint('api', __name__) def make_error(message): retu...
2,462
826
import unittest import numpy as np from c4.board import Board, PLAYER1 class TestBoard(unittest.TestCase): def test_end_diag_lr(self): b = Board(np.array([[1, 0, 0, 0, 0, 0, 0], [2, 1, 0, 0, 0, 0, 0], [2, 2, 1, 0, 0, 0, 0], ...
3,830
1,818
import numpy as np from sklearn.metrics import accuracy_score from keras.datasets import cifar10 from keras.utils import to_categorical from keras.models import Sequential, Model from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, LSTM, Input, Activation, Reshape, concatenate from keras import optimizers (...
1,134
448
# Copyright 2021 PyAge2, Oleksii Kachaiev <kachayev@gmail.com>. 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
1,652
536
from libavg import avg from events.event_dispatcher import EventDispatcher from multi_view_ctrl.grid_element import GridElement from multi_view_ctrl.configurations.grid_element_div_configuration import GridElementDivConfigurations class GridElementDiv(avg.DivNode, EventDispatcher): def __init__(self, grid_element...
4,045
1,160
import en_core_web_sm from spacy import displacy class Relations_finder: def __init__(self): self.subject = '' self.nlp = en_core_web_sm.load() def generate_html(self, nlp_doc): html = displacy.render([nlp_doc], style="dep", page=True) with open('spacy.html', 'w') as out_file:...
4,152
1,247
from flask import jsonify, request, Blueprint, current_app, send_file, make_response import tensorflow as tf import numpy as np from app.users import utils import cv2 from app.models import User, Data, Predictions, Coordinates from app import db from werkzeug.security import generate_password_hash, check_password_hash ...
8,597
2,561
""" EXERCÍCIO 006: Dobro, Triplo, Raiz Quadrada Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada. """ n = int(input('Digite um número: ')) print('O dobro de {} vale {}.'.format(n, (n * 2))) print('O triplo de {} vale {}.'.format(n, (n * 3))) print('A raiz quadrada de {} é igual a {:.2f...
352
151
""" Utilities for working with Google Cloud Storage. """ import logging import warnings from .deps.optdep import import_optional_dependency logger = logging.getLogger(__name__) _cached_gcs_fs = None def get_gcs_fs_without_warnings(cache_value=True): # TODO It's not expensive to create the gcs filesystem, but...
2,494
730
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: yizhong # created_at: 17-5-2 下午5:00 PAD_WORD = '<blank>' UNK_WORD = '<unk>' BOS_WORD = '<s>' EOS_WORD = '</s>' NUM_WORD = '<num>' PUNC_TAG = '<punc>'
208
109
#coding: utf-8 a = zeros((10,10), double) for i in range(0,10): a[i,i] = 2.0 for i in range(0,9): a[i,i+1] = -1.0 for i in range(0,9): a[i,i+1] = -1.0 n = 5 for i in range(0, n): x = 1
208
124
from django.shortcuts import render from .forms import LanguageForm from learning_django import settings from django.utils import translation def index(request): language_default = settings.LANGUAGE_CODE if request.method == "POST": form = LanguageForm(request.POST) if form.is_valid(): ...
626
166
#create cinet and functions like COMError that simulate Gamry #dtaq.Cook is defined to return dummy data when called #import config here and check if a simulation is being run and if so load that simulation .py that overrides functions like dtaq.Cook
252
62
def main(): variable1 = input() variable2 = input() a = variable1.split() b = variable2.split() first_line = [] second_line = [] for i in a: first_line.append(int(i)) for i in b: second_line.append(int(i)) code(first_line[0], second_line) def code(target, number): ...
512
182
from dataclasses import dataclass, field from .point import Point @dataclass() class Direction(Point): x: int = 0 y: int = 0 NONE: Direction = Direction(0, 0) NORTH: Direction = Direction(0, -1) SOUTH: Direction = Direction(0, 1) EAST: Direction = Direction(1, 0) WEST: Direction = Direction(-1, 0) NORTH_...
737
312
#coding:utf-8 # # id: bugs.core_4158 # title: Regression: LIKE with escape does not work # decription: # tracker_id: CORE-4158 # min_versions: ['2.0.7'] # versions: 2.0.7 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 2.0.7 # resources: Non...
1,437
523
""" arpd_update focuses on easily editing the assume role policy document of a role. """ import os import json import logging import argparse from datetime import datetime from typing import List, Dict, Optional import boto3 # type: ignore from botocore.exceptions import ClientError # type: ignore LOGGER = logging....
18,430
5,733
import pygame import time import math import sys from kartingpros import track, mainmenu, car, settings, loadimage from kartingpros.loadimage import _load_image, _load_sound, _load_font import numpy as np from numpy import save from kartingpros.car import Car from pygame.locals import * from pygame import mix...
7,471
2,594
# -*- coding: utf-8 -*- # vim: set noai syntax=python ts=4 sw=4: # # Copyright (c) 2018-2021 Linh Pham # wwdtm is released under the terms of the Apache License 2.0 """Testing for object: :py:class:`wwdtm.location.LocationUtility` """ import json from typing import Any, Dict import pytest from wwdtm.location import Lo...
9,079
2,804
# -*- coding: utf-8 -*- """ Create a cert with pyOpenSSL for tests. Heavily based on python-opsi's OPSI.Util.Task.Certificate. Source: https://github.com/opsi-org/python-opsi/blob/stable/OPSI/Util/Task/Certificate.py """ import argparse import os import random import socket from tempfile import NamedTemporaryFile fro...
2,204
876
def log(message, *values): """ * operator instructs python to pass items from the sequence as positional arguments Remember: - using the * operator with a generator may cause your program to run out of memory and crash. - adding new positional parameters to functions that accept ...
680
204
from .unet import UnetComplex from .cross_domain import CrossDomainNet from ..utils.fourier import FFT, IFFT class UPDNet(CrossDomainNet): def __init__( self, n_layers=3, layers_n_channels=[8, 16, 32], res=True, non_linearity='relu', channel_...
2,942
964
# Authors: Zhaoshuo Li, Xingtong Liu, Francis X. Creighton, Russell H. Taylor, and Mathias Unberath # # Copyright (c) 2020. Johns Hopkins University - All rights reserved. import copy import numpy as np import torch import torch.nn as nn class NestedTensor(object): def __init__(self, left, right, disp=None, s...
4,342
1,551
from .base import BaseResource class Asg(BaseResource): """ autoscaling group resource to generate from current region """ def __init__(self, logger=None): super().__init__(logger) def amend_attributes(self, _type, _name, attributes: dict): if "launch_template" in attributes and attr...
2,600
724
import numpy as np import scipy.io from sklearn.metrics import confusion_matrix from random import randint, shuffle from argparse import ArgumentParser from helper import getValidDataset import tensorflow as tf parser = ArgumentParser() parser.add_argument('--data', type=str, default='Indian_pines') parser.add_argumen...
28,278
9,110
#!/usr/bin/env python # -*- coding: UTF-8 -*- import math class Point(object): """ class for 2D points x, y - position of point, default 0,0 p - decimals in coordinate output, default 2 """ def __init__(self, x=0, y=0, p=2): self.x = x self.y = y self.p = p de...
2,300
849
#!/usr/bin/env python # coding: utf-8 # In[1]: import time import matplotlib.pyplot as plt import numpy as np import seaborn as sns import tensorflow as tf from scipy.misc import imresize from sklearn.cross_validation import train_test_split import _pickle as cPickle from train import train class Alexnet: de...
4,588
1,953
import random import string import unittest from typing import List, Union, Dict from config import config from p2_assembly.mac2_data_macro import DataMacro from p3_db.test_data import TestData from p3_db.test_data_elements import Pnr from p4_execution.debug import get_debug_loc, add_debug_loc, get_missed_loc from p4_...
4,184
1,485
from dataclasses import dataclass from datetime import datetime from typing import Optional @dataclass class VatsimGeneral: version: str reload: str update: str # will be used as a pk update_timestamp: str # ISO 8601 date string in UTC connected_clients: int unique_users: int def get_dat...
2,893
1,265
from app import db class Temperature(db.Model): """ Model for temperature storing. """ timestamp = db.Column(db.Integer, primary_key=True, index=True, unique=True) internal = db.Column(db.Float) external = db.Column(db.Float) cpu = db.Column(db.Float) def __repr__(self): re...
360
116
# Define imports import pygame from pygame import * import sys import time class Controller: """Class responsible for interacting with the Model and View.""" def __init__(self, view): """Initialize a controller taking input from the View.""" self.model = view.get_model() ...
3,199
746
# Copyright 2012 Rackspace Hosting, 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 ...
17,101
5,272
import re from exceptions import WordPlacementConflict from constants import ACROSS, DOWN def score_placements(placements, display=False): dimensions = [ min([x for x, y, dir in placements.values()]), min([y for x, y, dir in placements.values()]), max([placement[0] + len(word) for word, p...
3,386
1,027
import numpy as np import shapely import geopandas as gpd import xarray as xr import matplotlib.pyplot as plt import seaborn as sns EPSG_3035_PROJ4 = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs " GREY = "#C0C0C0" BLUE = "#4F6DB8" YELLOW = "#FABC3C" SUPPLY_TECHS = [ "hy...
4,200
1,681
import os import confuse config = confuse.LazyConfig('ytbdl', None) def get_loaded_config_sources(): ''' Get existing configuration files Returns: (list): A list of (string) paths to configuration files that exist on the file system. Returns an empty list if no configuration files ...
885
243
from . import machine as m from . import machine_calculator as mc from . import my_time as mt class Factory: def __init__(self, open_time=0.00, close_time=24.00): self.open_time = open_time self.close_time = close_time self.machine_id_map = {} self.machines = [] def get_opera...
4,875
1,764
from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django_extensions.db.models import TimeStampedModel from stdimage import StdImageField from stdimage.utils import UploadToUUID class Place(TimeStampedModel): ...
1,898
570
import tensorflow as tf def shuffle_and_batch_dataset(dataset, batch_size, shuffle_buffer=None): """ This function is used to shuffle and batch the dataset, using shuffle_buffer and batch_size. """ if shuffle_buffer is not None: dataset = dataset.shuffle(shuffle_buffer) dataset = datas...
2,363
739
# # This file is part of Brazil Data Cube Collection Builder. # Copyright (C) 2019-2020 INPE. # # Brazil Data Cube Collection Builder is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Defines a structure component to run celery work...
1,080
343
import numpy as np import matplotlib.pyplot as plt import os f_cutoff = .25 df_cutoff = .05 data_dir = '/data/smurf_data/20181214/1544843999/outputs' f2, df2 = np.load(os.path.join(data_dir, 'band3_badres.npy')) f2p, df2p = np.load(os.path.join(data_dir, 'band3_badpair.npy')) m = np.ravel(np.where(np.logical_or(f2 >...
1,648
900
# Copyright 2018 Dong-Hyun Lee, Kakao Brain. # # Copyright (c) 2020 Intel Corporation # # 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,794
973
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import torch from torch import nn import torch.nn.functional as F class AlexNet(nn.Module): def __init__(self, num_classes=10): super(AlexNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_si...
1,983
849
# pylint:disable=missing-module-docstring,missing-class-docstring,missing-function-docstring from .base import compare_template, SimpleTestCase class TimePickerTest(SimpleTestCase): maxDiff = None def test_rendered(self): template = """ {% load carbondesign %} {% TimePicker form.started_at %} """ ...
38,783
14,276
import unittest from dongtai_agent_python.policy import tracking class TestTracking(unittest.TestCase): def test_yaml_load_is_safe(self): try: import yaml self.assertFalse(tracking.yaml_load_is_safe(('test', yaml.UnsafeLoader), None)) self.assertFalse(tracking.yaml_loa...
652
213
from setuptools import setup setup( name='validator.py', version='1.3.0', author='Samuel "mansam" Lucidi', author_email="sam@samlucidi.com", packages=['validator'], url='https://github.com/mansam/validator.py', description='A library for appling schemas to data structures.', long_descri...
1,107
331
from telegram.ext import Updater from telegram import bot #!/usr/bin/env python # -*- coding: utf-8 -*- updater = Updater(token='660812730:AAEGP-xXkMKoplHR6YsUECqXB8diNgvlfbs') dispatcher = updater.dispatcher import logging import requests state = 1 logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s -...
3,137
1,246
from torch import nn from onconet.models.factory import RegisterModel, load_pretrained_weights, get_layers from onconet.models.default_resnets import load_pretrained_model from onconet.models.resnet_base import ResNet @RegisterModel("custom_resnet") class CustomResnet(nn.Module): def __init__(self, args): ...
893
284
#!/usr/bin/env python import logging from argparse import ArgumentParser import theano from theano import tensor as tt from blocks.algorithms import GradientDescent, Adam from blocks.bricks import MLP, Tanh, Softmax from blocks.bricks.cost import CategoricalCrossEntropy, MisclassificationRate from blocks.initializati...
3,437
1,070
""" Search integral/derivative algorithm class """ from ..items import Items from ..sequence import integral, derivative, summation, product from ..utils import sequence_matches from .base import RecursiveSearchAlgorithm __all__ = [ "SearchSummation", "SearchProduct", "SearchIntegral", "SearchDeriv...
3,682
1,095
from core import ServerConstants def first_click_object_6578(player): if (player.playerEquipment[ServerConstants.AMULET_SLOT] == 1712) and (player.playerEquipment[ServerConstants.CAPE_SLOT] == 10499) and (player.playerEquipment[ServerConstants.WEAPON_SLOT] == 11802): ItemAssistant.addItemToInventoryOrDrop(...
409
150
# 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...
1,662
592
import sys import re from src.GenGraph import * class ExtractData: def __init__(self, genGraph): #print("Init extractData.") self.datas = list() self.datasDefine = False self.file = "pipe" # Cas de base ou l'on prend des données de stdin self.genGraph = genGraph ...
6,972
2,263
from django.contrib import admin from .models import Book, Author, BookInstance, Genre #creating inline for copy instances in book model by TabularInline. # we have foreignkey from bookinstances to book and from book to authors --> just the way of foreignkey! class BooksInstanceInline(admin.TabularInline): model =...
1,642
499
from api.user.models import User from api.cart.models import Cart, CartProduct from api.order.models import Order, OrderProduct from api.product.models import Product
169
45
from math import * import csv import random import numpy as np from optimize import genetic_algorithm with open('pTZ.csv', newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',', quotechar='"') next(csvreader, None) # skip header observations = [( np.array([float(p),float(T)]), float(Z)) ...
4,456
2,140