text
string
size
int64
token_count
int64
import socket import threading helpMessage = '-q -- close connection\n-l -- list of connected devices\n-t -- server time \n-s "arduino/client ""reciever name" "message" -- send message (messages can be max 100 character) \nif reciever is an arduino board it can be controlled by this messsage:\n -s arduino "arduino ...
1,794
565
from torchvision import datasets, transforms from base import BaseDataLoader from torch.utils.data import Dataset, DataLoader import pandas as pd import torch from skimage import io#, transform import numpy as np class MnistDataLoader(BaseDataLoader): """ MNIST data loading demo using BaseDataLoader """ ...
3,885
1,252
import evaluation_script import argparse parser = argparse.ArgumentParser(description='Evaluation script used in the eBay SIGIR 2019 eCommerce Search Challenge.') parser.add_argument('-g', '--ground-truth-file', required=True, help="Ground truth file") parser.add_argument('-p', '--prediction-file', required=True, help...
591
186
from .core.starfish import starfish starfish()
48
16
# Generated by Django 2.2 on 2020-04-26 08:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coreapp', '0057_projectpricing_custom_supprt'), ] operations = [ migrations.RenameField( model_name='endpointalgorithm', ...
968
279
import logging from server.singleton_meta import SingletonMeta log = logging.getLogger(__name__) class PriceCache(metaclass=SingletonMeta): def __init__(self): log.debug("[PriceCache] Init new price cache") self.price_cache = {} def init_cache_for_ticker(self, watched_ticker_id): log.info(f"[PriceCa...
1,431
508
# (10,2,20,4,30,6,40,8,50) n=int(input("enter no--")) i=1 c=10 while i<=n: if i%2==0: c+=10 print(i,end=",") i+=1 i+=1 print(c,end=",") # (1+10=11, 11+20=31, 31+30=61, 61+40=101) n=int(input("enter no,-")) i=0 d=1 s=10 while i<n: print(d,end=",") d...
499
336
import os import time from os import mkdir from os.path import isdir from threading import Lock import cv2 import imutils from modules.Camera import Detect from modules.Camera.CameraHandler import CameraHandler from modules.Config import Config from modules.Fusion import Fusion from modules.Logger.Logger import Logge...
9,092
2,420
import torch from torch.autograd import Variable import time import os import sys import numpy as np from utils import AverageMeter, calculate_accuracy, save_gif, accuracy from models.binarized_modules import binarizef def train_epoch(epoch, data_loader, model, criterion, optimizer, opt, epoch_logger...
5,809
1,958
from django.contrib.contenttypes import fields from django.shortcuts import render from .forms import MessageForm, ContactForm from django.views.generic import DetailView, ListView, FormView class MessageAddView(FormView): # form_class = MessageForm form_class = ContactForm template_name = 'contact/messa...
477
136
# Modules import discord from datetime import date from discord import Embed from json import loads, dumps from assets.prism import Tools from discord.ext import commands # Main Command Class class Settings(commands.Cog): def __init__(self, bot): self.bot = bot self.desc = "Changes server settin...
6,506
1,950
import torch from .mcts import MCTS, Node from .utils import select_action def test(config, model, episodes, device, render): model.to(device) model.eval() test_reward = 0 env = config.new_game() with torch.no_grad(): for ep_i in range(episodes): done = False ep_r...
970
286
# coding=utf-8 import torch class RotateRectangleDCNFeatureCalibration(torch.nn.Module): def __init__(self): torch.nn.Module.__init__(self) pass
167
58
import math class MySuperBall: x=0 y=0 radius=0 speed=0 counter=0 previousBall=None vector = 1 def render (self): noStroke () fill (200 , 100) ellipse (self.x,self.y,self.radius , self.radius ) stroke (10) strokeWeight (2) ...
1,824
693
import asyncio import logging import discord from carim_discord_bot import managed_service, config from carim_discord_bot.discord_client import discord_service log = logging.getLogger(__name__) class MemberCountService(managed_service.ManagedService): async def handle_message(self, message: managed_service.Mes...
1,340
372
class EarlyStop: def __init__(self, patience=5): self._patience = patience self._min_loss = None self._counter = -1 def __call__(self, loss): if self._min_loss is None: self._counter = 0 self._min_loss = loss return False if self._min...
491
141
#!/usr/bin/env python3 from GAReport import GAReport VIEW_ID = 'PutViewIDHere' DIMENSIONS = ["Page", ] METRICS = ["Pageviews", "Unique Pageviews", "Avg. Time on Page", "Entrances", "Bounce Rate", "% Exit", "Page Value"] # Use these instructions for creating single and multiple filters: https://developers.google.com...
567
204
from resnet import resnet18_,resnet34_,resnet50_,resnet101_, resnet152_ from keras.layers import Input, Dense, Lambda,Dropout,Conv2D,Activation,Bidirectional,GlobalAveragePooling1D,\ BatchNormalization,Reshape from keras_layer_normalization import LayerNormalization from keras.layers.cudnn_recurrent import CuDN...
14,525
4,980
from .literals import booleans from .models import (readable_web_streams, web_streams, writeable_web_streams) from .paths import web_url_strings
187
53
# -*- coding: utf-8 -*- import os cudaid = 0 os.environ["CUDA_VISIBLE_DEVICES"] = str(cudaid) import sys import time import numpy as np import cPickle as pickle import copy import random from random import shuffle import math import torch import torch.nn as nn from torch.autograd import Variable import data as datar...
27,309
9,577
# Generated by Django 2.1.5 on 2019-02-14 14:25 from django.db import migrations import imagekit.models.fields class Migration(migrations.Migration): dependencies = [ ('openbook_posts', '0015_post_community'), ] operations = [ migrations.AlterField( model_name='postimage', ...
471
155
from collections import MutableMapping, MutableSet, namedtuple from operator import itemgetter class Node(namedtuple("Node", "value, left, right, red")): __slots__ = () def size(self): """ Recursively find size of a tree. Slow. """ if self is NULL: return 0 ...
15,517
4,550
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class LinkOAM(Base): __slots__ = () _SDM_NAME = 'linkOAM' _SDM_ATT_MAP = { 'PacketSubtype': 'linkOAM.header.packet.subtype-1', 'PacketFlags': 'linkOAM.header.packet.flags-2', 'InformationOAMPDUCode': 'l...
45,052
13,813
from flask import current_app from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed from wtforms import StringField, PasswordField, SubmitField, BooleanField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from flask_login import current_user from memos.m...
3,967
1,048
import rsa class RSA: @classmethod def generate_keys(cls, size: int = 512) -> tuple: return rsa.newkeys(size) @classmethod def export_key_pkcs1(cls, public_key: rsa.PublicKey, format: str = "PEM") -> bytes: return rsa.PublicKey.save_pkcs1(public_key, format=format) @classmethod ...
626
226
import paramiko,time,sys,json,os,pandas ######################################################################################################################## ################################################### parms ############################################################# proxy = None Port = 22 Username = open...
3,566
1,080
import importlib import logging from volttron.platform.agent import utils _log = logging.getLogger(__name__) utils.setup_logging() __version__ = "0.1" __all__ = ['Model'] class Model(object): def __init__(self, config, **kwargs): base_module = "volttron.pnnl.models." try: model_type ...
825
256
import draft import os def run(): picks = [[],[]] pairs = draft.pairs() for player in range(1, 3): os.system("clear") pre = "[Player %d]: " % player input(pre + "(Enter when ready) ") pair = 0 while pair < 4: pick = input(pre + "%s (1), %s (2) " % (draft.get_name(pairs[playe...
826
328
# https://open.kattis.com/problems/honey print(*(lambda x: [x[int(input())] for _ in range(int(input()))])([1, 0, 6, 12, 90, 360, 2040, 10080, 54810, 290640, 1588356, 8676360, 47977776, 266378112, 1488801600]), sep="\n")
222
150
# -*- coding: utf-8 -*- """File containing a Windows Registry plugin to parse the USBStor key.""" import logging from plaso.events import windows_events from plaso.lib import eventdata from plaso.parsers import winreg from plaso.parsers.winreg_plugins import interface __author__ = 'David Nides (david.nides@gmail.co...
4,712
1,451
from collections import defaultdict from discord.ext.commands import Cog, command from discord.utils import get from ...utils import check_restricted from ... import exceptions from ... import messagemanager class Help(Cog): async def get_cmd(self, name, bot, user, list_all_cmds=False): cmd = bot.get_comm...
4,877
1,446
"Update a Flatpak repository for new versions of components" import argparse import asyncio import datetime from functools import total_ordering import hashlib from itertools import zip_longest import json from pathlib import Path import re import httpx import jinja2 import yaml GITHUB_DATE_FORMAT = "%Y-%m-%dT%H:%M:...
8,710
2,715
from unittest import TestCase import base.env.pre_process as pre_process import pandas as pd from sklearn.preprocessing import MinMaxScaler from helper.util import get_attribute from base.env.pre_process_conf import active_stragery, get_strategy_analyze import base.env.pre_process class TestProcessStrategy(TestCase)...
1,746
551
#!/usr/bin/env python2.5 #encoding:utf-8 #author:dbr/Ben #project:themoviedb #forked by ccjensen/Chris #http://github.com/ccjensen/themoviedb """An interface to the themoviedb.org API """ __author__ = "dbr/Ben" __version__ = "0.2b" config = {} config['apikey'] = "a8b9f96dde091408a03cb4c78477bd14" config['urls'] = {...
12,194
3,775
import numpy import numpy.linalg def distance_sum(inputs, references): """Sum of all distances between inputs and references Each element should be in a row! """ norms = numpy.zeros(inputs.shape[0]) for i in xrange(references.shape[0]): norms += numpy.apply_along_axis(numpy.linalg.norm, 1...
3,033
1,152
# # PySNMP MIB module CABH-QOS2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CABH-QOS2-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:26:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
17,984
8,532
from django.shortcuts import redirect, render from .models import * from datetime import date from brain import ipfunc def home(request): dados = Apod.getObjectOrRequest() buscaData = request.POST.get('data') if request.method == 'POST': dados = Apod.getObjectOrRequest(str(buscaData)) ret...
2,440
851
from django.db import models from django.utils import timezone from sizefield.models import FileSizeField # Create your models here. class Video(models.Model): sha224 = models.CharField(max_length=56, unique=True) filename = models.CharField(max_length=200) dropbox_directory = models.CharField(max_length=...
805
261
import os.path import json from astral import Astral appdata_folder = os.path.join(os.environ["LOCALAPPDATA"], "Nightshift") def set_location(latitude, longitude): print "Setting location to {0}, {1}".format(latitude, longitude) try: if not os.path.exists(appdata_folder): os.mkdir(appdat...
1,681
498
# BSD 3-Clause License; see https://github.com/jpivarski/awkward-1.0/blob/master/LICENSE from __future__ import absolute_import import numpy import awkward1._util import awkward1._connect._numpy import awkward1.layout import awkward1.operations.convert def count(array, axis=None, keepdims=False, maskidentity=False)...
12,140
4,064
import os import re import sys import warnings __version__ = '1.4.3' line_re = re.compile(r""" ^ (?:export\s+)? # optional export ([\w\.]+) # key (?:\s*=\s*|:\s+?) # separator ( # optional value begin '(?:\'|[^'])*' # single quoted value | ...
4,758
1,328
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This experiment was created using PsychoPy3 Experiment Builder (v2020.2.4post1), on October 27, 2020, at 14:06 If you publish work using this script the most relevant publication is: Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, ...
16,755
5,209
grammar = r""" start: (item ";")+ item: import | coords | playlist | step import : "import" string coords : "coords" coords_body coords_body : "{" coord_def ("," coord_def)* "}" coord_def: string ":" "{" coord_body ("," coord_body)* "}" coord_body: string ":" "[" int "," int "]" playlist : "playlist" string playli...
1,945
760
import configparser import os import shutil import traceback class Conf: def __init__(self, conf): self.options = conf config = configparser.ConfigParser(interpolation=None) if not config.read(conf, encoding='utf-8'): print("I had to remake the config file from default....
1,765
493
#!/usr/bin/env python # __BEGIN_LICENSE__ #Copyright (c) 2015, United States Government, as represented by the #Administrator of the National Aeronautics and Space Administration. #All rights reserved. # __END_LICENSE__ """ Takes as input a CSV file in the format: 37 46 29.2080,-122 25 08.1336,San Francisco 37 27 1...
2,805
1,013
from torchvision.datasets import CIFAR10 from torchvision.datasets import CIFAR100 import os root = '/database/cifar10/' from PIL import Image dataset_train = CIFAR10(root) for k, (img, label) in enumerate(dataset_train): print('processsing' + str(k)) if not os.path.exists(root + 'CIFAR10_image/' + ...
478
195
from toapi import Item, XPath class User(Item): url = XPath('//a[@class="hnuser"][1]/@href') name = XPath('//a[@class="hnuser"][1]/text()') class Meta: source = XPath('//tr[@class="athing"]') route = '/news\?p=\d+'
246
94
''' Failure tests ''' import os from typing import Any import pytest from helpers.github import API api = API() pass_token = Any fail_token = os.getenv('FAIL_TOKEN') fail_org = os.getenv('FAIL_ORG') fail_repo = os.getenv('FAIL_REPO') def test_fail_auth(): ''' Fail 'auth' to Github ''' with pytest.r...
722
259
# -*- coding: utf-8 -*- """ .. module:: skimpy :platform: Unix, Windows :synopsis: Simple Kinetic Models in Python .. moduleauthor:: SKiMPy team [---------] Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB), Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland Licensed under the ...
3,042
1,035
from enum import Enum, unique, auto @unique class Fruit(Enum): APPLE = 1 BANANA = 2 ORANGE = 3 # if you don't care what value to put you can use auto => basically it will get last value used + 1 (if auto is for first item it will be 0 + 1 = 1) PEAR = auto() def main(): print(Fruit.APPLE) # F...
825
322
# Import packages import os import cv2 import numpy as np import tensorflow as tf import sys from imutils.object_detection import non_max_suppression # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util class detec...
3,313
972
# Handle client-side action for an IBM Watson Assistant chatbot # # The code requires my Watson Conversation Tool. For details see # https://github.com/data-henrik/watson-conversation-tool # # # Setup: Configure your credentials # - for Watson Assistant see instructions for the tool # - for Discovery change username / ...
1,770
486
import numpy as np import matplotlib.pyplot as plt from cycler import cycler from source.solving_strategies.strategies.residual_based_newton_raphson_solver import ResidualBasedNewtonRaphsonSolver from source.solving_strategies.strategies.residual_based_picard_solver import ResidualBasedPicardSolver from source.model.s...
2,977
1,144
from typing import Dict from objects.base import BaseModel class RegexDeleter(BaseModel): name: str regex: str chat_id: int for_all: bool def save(self) -> Dict[str, int]: return { 'name': self.name, 'regex': self.regex, 'chat_id': self....
378
131
from copy import deepcopy from django.contrib import admin from cartridge.shop.admin import OrderAdmin from cartridge.shop.models import Order order_fieldsets = deepcopy(admin.site._registry[Order].fieldsets) order_fieldsets[2][1]["fields"] = list(order_fieldsets[2][1]["fields"]) order_fieldsets[2][1]["fields"].ins...
639
198
#!/usr/bin/env python # -*- coding:utf-8 -*- import copy class AttrDict(dict): def __init__(self, seq=None, **kwargs): dict.__init__(self, seq or {}, **kwargs) def __getattr__(self, name): return self.get(name, self.get("__default", None)) def __setattr__(self, name, value): self...
1,483
574
""" Author: Amanda Ortega de Castro Ayres Created in: September 19, 2019 Python version: 3.6 """ from Least_SRMTL import Least_SRMTL import libmr from matplotlib import pyplot, cm from matplotlib.patches import Circle from mpl_toolkits.mplot3d import Axes3D, art3d import numpy as np import numpy.matlib impo...
16,034
5,565
# -*- coding: utf-8 -*- #!/usr/bin/env python # # Copyright 2013-2016 BigML # # 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 requi...
5,375
1,416
import os,time import torch from larcv import larcv import numpy as np import ROOT as rt from array import array class IntersectUB( torch.autograd.Function ): larcv_version = None dataloaded = False imgdimset = False @classmethod def load_intersection_data(cls,intersectiondatafile=None,larcv_vers...
16,229
6,265
from inspect import isclass def build_permissions_fn(permissions): def fn(**kwargs): for perm in permissions: if not perm().has_permission(**kwargs): raise PermissionError(perm().error_message(**kwargs)) return fn class BasePermission: def __init__(self, **kwargs): ...
3,270
819
# Faça um algoritmo que leia o preço de um produto e mostre o novo preço com um desconto. preco = float(input('Digite o preço atual do produto: R$ ')) desconto = float(input('Digite o valor do desconto (0.X): ')) novopreco = preco * desconto print('O novo preço é R$ {}.'.format(novopreco))
290
113
from draw_control import DrawControl if __name__ == '__main__': zotter = DrawControl() test = input("track, rail, pen, hor, ver, diag: ") while(test): if test == "track": dir_in = input('dir step: ') dir = dir_in.split(" ") zotter.track.spin_fixed_step(int(dir[...
1,188
402
import pathlib import logging from torch import nn import numpy as np import torch import torch.functional as F import torchvision.transforms as T from torch.utils.data import Dataset from torchvision.datasets.cityscapes import Cityscapes import cv2 from torchvision.transforms import ToPILImage from torch.utils.data ...
2,961
992
class EventHandler: def __init__(self, maze, maze_handler, maze_builder, bfs, a_star, indexes, text_table, screen): """ Initialize a new EventHandler instance. :param maze: _maze list :param maze_handler: MazeHandler instance :param maze_builder: MazeBuilder instance ...
6,960
2,003
from flask import Flask, render_template, request, jsonify from flask import request from flask import Response from flask import url_for from flask import jsonify import GetOldTweets3 as got import pandas as pd import datetime import numpy as np import requests import json from pyquery import PyQuery as pq app = Fla...
11,838
4,049
__author__ = 'Rachum'
22
11
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import import unicodedata import re, os import logging from django.utils.translation import ugettext_lazy as _ from django.db import models from django.template.loader import render_to_string from djang...
10,072
3,038
# -*- coding: utf-8 -*- from unittest import TestCase from flask_login import login_user from flask_wtf import FlaskForm from wtforms import StringField from wtforms import ValidationError from app import create_app from app import db from app.configuration import TestConfiguration from app.localization import get_l...
5,372
1,455
# Generated by Django 3.1.1 on 2020-11-10 03:16 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Post', '0001_initial'), ] operations = [ migrations.AddField( model_name='post', ...
769
260
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'About.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectN...
2,714
897
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
948
268
import pymysql conexao = pymysql.connect( host='localhost', user='root', password='admin1234', db='ex_01') cursor = conexao.cursor(pymysql.cursors.DictCursor) def select(fields, tables, where=None): global cursor query = 'SELECT ' + fields + ' FROM ' + tables if where: ...
1,244
452
#!/usr/bin/python """downsample Author: Christoph Hahn (christoph.hahn@uni-graz.at) February 2017 Extract a random subsample of ~ x % reads from fastq data. The choice is based on a random number generator. For each fastq read, a random number between 1-100 will be generated. If the random number is smaller than t...
6,792
2,205
""" Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3. You are given the total volume m of the building. Being given m can you find the number n of cub...
585
186
"""Class to handle iterating through tweets in real time.""" import json import os import pandas as pd # Said this was unused. # from bluebird import BlueBird from bluebird.scraper import BlueBird from sentiment import PoliticalClassification from train import TrainingML col_names32 = "created_at,id,id_str,full_tex...
4,597
1,459
#!/usr/bin/env python3 import aws_cdk.aws_iam as iam import aws_cdk.aws_s3 as s3 from aws_cdk import core class ExportingStack(core.Stack): exported_role_a: iam.Role exported_role_b: iam.Role def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kw...
2,107
719
# -*- coding: utf-8 -*- # vim:fenc=utf-8 import pytest import trustpaylib try: unicode py3 = False except NameError: py3 = True unicode = lambda s: s class TestTrustPayCore: secret_key = "abcd1234" aid = "9876543210" pay_request = trustpaylib.build_pay_request( AID=aid, ...
6,344
2,189
inputfile = open('inputDay01.txt', 'r') values = [int(i) for i in inputfile.readlines()] #PART1 def aoc01(numbers, value): for x in numbers: if value - x in numbers: return x * (value - x) #PART2 def aoc02(numbers, value): num1, num2 = None, None for x in numbers: n = value - x ...
606
216
import logging from flask import request from flask_restplus import Resource, Namespace, fields from ..managers import auth_manager from ..managers.auth_manager import token_required from ..exceptions import HTTP_EXCEPTION api = Namespace('auth', description='Authentication related operations') dto = api.model('au...
1,686
515
from abc import ABC, abstractmethod, abstractproperty from typing import Dict __all__ = ["AbstractAlgorithm"] class AbstractAlgorithm(ABC): @abstractmethod def preprocess(self, text: str) -> Dict: """Применяется к каждому фрагменту текста. :param text: Текст :type text: str ...
4,079
1,290
#!/usr/bin/python3 from cffi import FFI source = open("libsec.h", "r").read() header = """ #include <secp256k1.h> #include <secp256k1_extrakeys.h> #include <secp256k1_schnorrsig.h> """ ffi = FFI() ffi.cdef(source) ffi.set_source("_libsec", header, libraries=["secp256k1"]) ffi.compile(verbose=True)
304
146
from kafka import KafkaConsumer, KafkaProducer import json class Producer: producer = None producer_topic = None def __init__(self, server, topic): self.producer = KafkaProducer ( bootstrap_servers=[server], value_serializer=lambda x: json.dumps(x).encode('utf-8') ...
938
276
import psycopg2 import sys from nltk.tokenize import sent_tokenize import re import csv import os # pmid {16300001 - 16400000} try: # starting_pmid = 16300001 # intermediate_pmid = 16400000 starting_pmid = 100001 intermediate_pmid = 200000 ending_pmid = 32078260 while 1: if interme...
2,038
694
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import utility ################### ## main ################### if __name__=='__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("-m", "--model", help="the path to the model file") args = parser.parse_args() p...
439
140
import json from collections.abc import Callable from typing import Optional import numpy as np from PIL import Image from volcengine_ml_platform.datasets.dataset import _Dataset from volcengine_ml_platform.io.tos_dataset import TorchTOSDataset class ImageDataset(_Dataset): """ ImageDataset创建函数 ``ImageDatas...
3,412
1,023
# Copyright 2020 TrueMLGPro # 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, soft...
5,634
2,065
import os, glob from tasks import task, TaskError, get, sh, SHResult def is_yaml_empty(dir): for name in glob.glob("%s/*.yaml" % dir): with open(name) as f: if f.read().strip(): return False return True class Kubernetes(object): def __init__(self, namespace=None, conte...
1,129
361
from dataclasses import dataclass from typing import List, Dict, Any @dataclass class WebsitePage: title: str body: str tags: List[str] created_at: str url: str slug: str meta: Dict @dataclass class WebsiteTag: name: str slug: str pages: List[WebsitePage] @dataclass class Web...
615
202
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # Inspired from https://github.com/rwightman/pytorch-image-models from contextlib import contextmanager import torch from...
1,952
591
import os import fnmatch import deep_learning tests = [file for file in os.listdir(os.getcwd()) if fnmatch.fnmatch(file, 'test_*.py')] tests.remove('test_all.py') for test in tests: print '---------- '+test+' ----------' execfile(test)
250
96
import warnings import argparse import os import logging import lib.metadata as metadata import lib.model as model import lib.text as text import lib.website as website warnings.filterwarnings('ignore') logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) ####################################...
12,328
2,841
from abc import ABC, abstractmethod from collections.abc import MutableSequence from datetime import datetime from typing import NamedTuple, Any, Optional, Iterator from .encoders import ENCODERS, string_encode, default_encoder, datetime_encode, blob_encode class Element(NamedTuple): value: Any tag: str @...
3,887
1,163
from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from django.template import RequestContext, loader from Organizer.models import Department from Organizer.models import Advisor from Organizer.models import Student from Organizer.models import Course from Organizer.models impor...
2,716
867
import numpy as np matrixA = np.loadtxt('./mat-A-32.txt') matrixB = np.loadtxt('./mat-B-32.txt') checking = np.loadtxt('./out32.txt') result = np.dot(matrixA, matrixB) diff = result - checking print(checking) print(result) print(diff) np.absolute(diff) print(np.max(diff)) [rows, cols] = diff.shape with open ('./out20...
462
186
import re from collections import defaultdict from util import * input1="""sesenwnenenewseeswwswswwnenewsewsw neeenesenwnwwswnenewnwwsewnenwseswesw seswneswswsenwwnwse nwnwneseeswswnenewneswwnewseswneseene swweswneswnenwsewnwneneseenw eesenwseswswnenwswnwnwsewwnwsene sewnenenenesenwsewnenwwwse wenwwweseeeweswwwnwwe ws...
16,749
7,936
#!/usr/bin/env python3 import argparse import sys import re import subprocess import os import glob import copy import aff3ct_help_parser as ahp # read all the lines from the given file and set them in a list of string lines with striped \n \r def readFileInTable(filename): aFile = open(filename, "r") lines = [] ...
4,773
1,971
from todoster.file_operations import load_projects from todoster.output_formatter import format_string def list_projects(arguments): projects = load_projects() if not arguments.show_all_projects: projects = list(filter(lambda x: x["active"], projects)) print() project_counter = 1 for proj...
677
191
#!/usr/bin/env python __author__ = 'Tomas Novacik' import unittest2 from game import Game from board import Board, PlayerType, Move class GameTest(unittest2.TestCase): def test_winning_move(self): game = Game() game.start() # set winning status to board board = Board() ...
621
207
""" Functions to mask sentences of undesirable words (stopwords, punctuation etc). Used in get_sentence_embeddings.py to process sentences before finding embeddings. """ import re from skills_taxonomy_v2.pipeline.skills_extraction.cleaning_sentences import ( separate_camel_case, ) def is_token_word(token, token_...
1,911
557
"""destinations Revision ID: 033809bcaf32 Revises: 4a77b8fb792a Create Date: 2017-08-24 05:56:45.166590 """ from alembic import op import sqlalchemy as sa import geoalchemy2 # revision identifiers, used by Alembic. revision = '033809bcaf32' down_revision = '4a77b8fb792a' branch_labels = None depends_on = None def...
1,000
388