text
string
size
int64
token_count
int64
######################################################################## # This script contains all the data analysis functions # ######################################################################## from __future__ import division from pylab import * import scipy, scipy.stats import tables import ...
4,923
1,558
import eventlet eventlet.monkey_patch() import time from datetime import datetime, timedelta, timezone import pytz from email.utils import parsedate_tz import json from flask import Flask, request, render_template from threading import Thread from tweepy import OAuthHandler, API, Stream, Cursor from flask_socketio i...
3,404
1,032
from django import forms from django.contrib import admin from .models import Attendance, Diet, Participant, Troop from payment.admin import DiscountInline, PaymentInline class AttendanceInline(admin.TabularInline): model = Participant.attendance.through readonly_fields = ("participant",) can_delete = F...
2,255
724
from conf import celery_settings from .app import app @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): pass
142
46
from flask import Flask from flask import render_template import plotly.express as px from plotly.offline import plot app = Flask("Datenvisualisierung") def data(): data = px.data.gapminder() data_ch = data[data.country == 'Switzerland'] return data_ch def viz(): data_ch = data() fig = px.ba...
829
295
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
24,336
6,998
# -*- coding: utf-8 -*- """Script which can be used to compare the features obtained of two different influenza models Usage: get_model_statistics.py <model> [--country=<country_name>] [--no-future] [--basedir=<directory>] [--start-year=<start_year>] [--end-year=<end_year>] [--save] [--no-graph] <baseline> ...
2,940
1,039
from scipy.sparse import vstack from sklearn.metrics.pairwise import cosine_similarity import numpy as np from sisu.preprocessing.tokenizer import is_relevant_sentence, make_sentences, sanitize_text from gismo.gismo import Gismo, covering_order from gismo.common import auto_k from gismo.parameters import Parameters fr...
21,887
6,667
import numpy as np import os from automr import dump_mat from functools import partial, reduce print = partial(print, flush=True) einsum = partial(np.einsum, optimize=True) def print_mol(mol): print(mol._basis) print(mol.atom) print(mol._atom) print(mol.aoslice_by_atom()) print(mol.ao_labels()) #if...
4,482
1,872
from justgood import imjustgood media = imjustgood("YOUR_APIKEY_HERE") query = "gojek" # example query data = media.playstore(query) # Get attributes number = 0 result = "Playstore :" for a in data["result"]: number += 1 result += "\n\n{}. {}".format(number, a["title"]) result += "\nDeveloper : {}".format...
487
167
import numpy as np # disjoint-set forests using union-by-rank and path compression (sort of). class universe: def __init__(self, n_elements): self.num = n_elements self.elts = np.empty(shape=(n_elements, 3), dtype=int) for i in range(n_elements): self.elts[i, 0] = 0 #...
1,089
459
num1 = 1 num2 = 20 num3 = 168 # dev first commit num1 = 1 # resolve conflict num2 = 88888888 # Test next commit num3 = 99
131
71
from __future__ import unicode_literals import frappe from datetime import datetime from frappe.model.document import Document @frappe.whitelist(allow_guest=True) def sendMail(doc,method): if doc.send_email_on_event_creation: for d in doc.event_participants: if d.reference_doctype == "Employee": email = frap...
1,441
573
#!/usr/bin/env python import os import sys import hashlib import httplib import base64 import socket from xml.dom.minidom import * RAC_CODE = { 'x' : 'Unknown error', '0x0' : 'Success', '0x4' : 'Number of arguments does not match', '0xc' : 'Syntax...
8,022
3,786
#!/usr/bin/env python from __future__ import print_function # Copyright 2019 Juliane Mai - juliane.mai(at)uwaterloo.ca # # License # This file is part of the EEE code library for "Computationally inexpensive identification # of noninformative model parameters by sequential screening: Efficient Elementary Effects (EEE)...
10,272
3,365
""" Leetcode #113 """ from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if not root: re...
1,377
466
from .alertsparser import AlertsParser from .subwaytripsparser import SubwayTripsParser from .stationscsvparser import StationsCsvParser
137
38
import os import pygame from input import Input from stages.stage import Stage from stages.stage_example import StageExample from stages.stage1 import Stage1 from stages.stage2 import Stage2 from stages.stage3 import Stage3 from stages.stage4 import Stage4 from stages.stage5 import Stage5 from stages.stage6 import St...
4,254
1,300
# Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the S...
9,439
2,465
import os _ROOT = os.path.abspath(os.path.dirname(__file__)) def get_data(path): return os.path.join(_ROOT, 'wordlist', path)
127
50
""" Usage: briltag insertdata [options] Options: -h --help Show this screen. -c CONNECT Service name [default: onlinew] -p AUTHPATH Authentication file --name TAGNAME Name of the data tag --comments COMMENTS Comments on the t...
745
238
from rendering.manager import * from rendering.scenes import * from rendering.training import * import random import glm import os import numpy as np import math __VOLUME_RECONSTRUCTION_SHADERS__ = os.path.dirname(__file__)+"/shaders/VR" compile_shader_sources(__VOLUME_RECONSTRUCTION_SHADERS__) class RayGenerator(R...
17,152
5,523
def _merge_sort(arr:'list'): if len(arr) <= 1: return arr begin = 0 end = len(arr)-1 middle = (begin+end)//2 first = _merge_sort(arr[begin:middle+1]) second = _merge_sort(arr[middle+1:end+1]) # merge ptr1 = begin ptr2 = middle+1 ptr = 0 while(ptr1<middle...
868
358
# - *- coding: utf- 8 - *- import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options options = Options() options.headless = True path = 'path/to/chromedriver.exe' # You need to change this def parser(): tex...
2,605
980
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def cinematica(t,s0,v0,a): s = s0 + v0*t +(a*t*t/2.0) return s t = np.linspace(0, 5, 500) s0 = 0.5 v0 = 2.0 a = 1.5 s_noise = 0.5 * np.random.normal(size=t.size) s = cinematica(t,s0,v0,a) sdata = s + s_noise coefs, pcov = ...
679
339
import pandas as pd import numpy as np import optuna import xgboost train = pd.read_csv("~/kaggledatasets/riiid-test-answer-prediction/train.csv", nrows=3e6, dtype={'row_id': 'int64', 'timestamp': 'int64', 'user_id': 'int32', ...
1,059
326
from typing import Optional, Dict from pathlib import Path from copy import deepcopy from tqdm import tqdm import torch as pt from torch import Tensor, nn from torch.optim import Adam def train( train_data: Dict[str, Tensor], valid_data: Dict[str, Tensor], model: nn.Module, optimizer: Adam, model...
1,828
595
from django.db import models from django.conf import settings from django.db.models.signals import post_save class Profile(models.Model): username = models.CharField(max_length=255, primary_key=True) bio = models.TextField(null=True, blank=True) image = models.URLField( null=True, blank=T...
898
281
import numpy as np # Compute normalized mutual information between two parcellations z1 and z2 def NMI(z1, z2): N = len(z1) assert N == len(z2) p1 = np.bincount(z1)/N p1[p1 == 0] = 1 H1 = (-p1*np.log(p1)).sum() p2 = np.bincount(z2)/N p2[p2 == 0] = 1 H2 = (-p2*np.log(p2)).sum() joint = np.histogram2d(z1,z2,...
975
490
import pytest from xigt import XigtCorpus, Igt, Tier, Item, Metadata, Meta, MetaChild from xigt.errors import XigtError, XigtStructureError class TestMetadata(): md1 = Metadata() m1 = Meta(id='meta1', text='meta') md2 = Metadata( id='md2', type='basic', attributes={'attr':'val'},...
31,939
11,428
from django.http import JsonResponse def names(request): return JsonResponse({'names': ['William', 'Rod', 'Grant']})
121
38
from sensor import Sensor from stepper import Stepper sensor = Sensor() stepper = Stepper(100) #stepper.start() while True: print(sensor.measure())
156
56
# Generated by Django 2.2.4 on 2019-08-18 16:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [("peering", "0050_auto_20190806_2159")] operations = [ migrations.RenameField( model_name="autonomoussystem", old_name="comment", new_name="comments" ...
1,351
405
# # PySNMP MIB module HP-ICF-IPV6-RA-GUARD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-IPV6-RA-GUARD-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:34:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
7,784
3,395
from transformers import RobertaTokenizer tokenizer = RobertaTokenizer.from_pretrained("roberta-base")
102
29
import numpy as np from .fasthist import hist2d stdquant = np.ndarray(13) stdquant[0] = (0.0000316712418331200) #-4 sdev stdquant[1] = (0.0013498980316301000) #-3 sdev stdquant[2] = (0.0227501319481792000) #-2 sdev stdquant[3] = (0.05) stdquant[4] = (0.1586552539314570000) #-1 sdev or lsdev stdquant[5] = (0.25) ...
2,531
1,040
# coding: utf-8 """ Copyright 2016 SmartBear Software 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 applica...
10,584
2,793
from sys import stdin for line in stdin: n = int(line) if n == 42: break print(n)
89
43
# -*- coding: utf-8 -*- def remainder(number,divisor): return number % divisor def flow_rate(weight,time,period=1): return weight/time*period if __name__=="__main__": print(remainder(20,7)) print(remainder(20,divisor=7)) print(remainder(number=20,divisor=7)) print(remainder(divisor=7,number=20)) print...
367
165
############################## ## cread purified h5ad file ## ############################## # input: annotation table and the whole expression profile # output: purified h5ad file import os import pandas as pd import anndata import argparse import gc import numpy as np parser = argparse.ArgumentParser(description='...
1,981
646
# -*- coding: utf-8 -*- """ Created on Thu Nov 29 13:56:44 2018 @author: RomanGutin """ import pandas as pd import numpy as np #Frequency Tuning Loop amino_letter = ['A','R','D','N','C','E','Q','G','H','I','L','K','M','F','P','S','T','W','Y','V'] length_scores =[4,8,6,6,5,7,7,4,7,5,6,8,7,8,5,5,5,9,8,5] FM_df = pd.Dat...
1,424
581
from kafka import KafkaConsumer class Consumer: def __init__(self, config): bootstrap_server = config.get( "bootstrap_server") + ":" + config.get("port") self.consumer = KafkaConsumer(config.get( "subscription_id_2"), bootstrap_servers=bootstrap_server, api_version=(0, 10), ...
692
202
# utilities import os from re import sub import uuid import subprocess # Image To Pdf import img2pdf # PDF To Images from pdf2image import convert_from_path # PDF To Word from pdf2docx import parse _BASE_DIR = os.getcwd() _BASE_DIR_FILE = os.path.join(_BASE_DIR, "files") def process_image_to_pdf(files, pdf_name...
2,159
744
from kivy.uix.screenmanager import Screen from kivy.properties import StringProperty, ObjectProperty, NumericProperty, ListProperty, BooleanProperty from kivy.app import App from kivy.logger import Logger from library_widgets import TrackingScreenMixin from utils import import_kv import_kv(__file__) class TasksScr...
2,026
596
"""Train logistic regression model on hdf5 features for classification Modified from: https://gurus.pyimagesearch.com/topic/transfer-learning-example-dogs-and-cats/ """ import pickle from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report def train_model(h5py_db, mod...
1,240
403
import pandas as pd v_4 = pd.read_csv('50/predictions_dev_queries_50k_normalized_exp.csv') temp = list(v_4['query_id']) v_4['query_id'] = list(v_4['reference_id']) v_4['reference_id'] = temp v_5 = pd.read_csv('ibn/predictions_dev_queries_50k_normalized_exp.csv') temp = list(v_5['query_id']) v_5['query_id'] = list(v_5...
1,760
831
from src.utils.cache import cache def cheats_key(chat_id: int, user_id: int) -> str: return f'i_stat:cheats:{chat_id}:{user_id}' def cheats_found(chat_id: int, user_id: int, sum_count: int) -> bool: key = cheats_key(chat_id, user_id) sums = cache.get(key, 0) sums += sum_count if sums > 50: ...
399
165
from threading import Thread from flask_mail import Mail, Message from resources.errors import InternalServerError mail = Mail(app=None) app = None def initialize_mail_service(appiclation): global mail global app mail = Mail(app=appiclation) app = appiclation def send_async_email(app, msg, mail): ...
744
225
import base64 import json from OpenSSL.SSL import ( VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, VERIFY_NONE, SSLv3_METHOD, SSLv23_METHOD, TLSv1_METHOD) from twisted.web.http_headers import Headers from twisted.internet.defer import inlineCallbacks, fail, succeed from vxsandbox.resources.http import ( HttpC...
18,541
5,388
from lightutils import get_free_tcp_port port = get_free_tcp_port() print(port) print(type(port))
99
37
from .accessor import Accessor from . import parsers import inspect def populateAccessors(): """ Find all filetype-specific Accessor subclasses in the parsers file (i.e. NVSPL, SRCID, etc.) and instantiate them. This way, one instance of each Accessor is added to the soundDB namespace under the name of th...
722
202
from datetime import datetime from sqlalchemy import ( Column, Integer, Text, DateTime, SmallInteger, BigInteger, String, Date, ForeignKey, UniqueConstraint ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.exc import NoResultFound from sqlalchemy....
3,953
1,375
import nose import os from ogcserver.WMS import BaseWMSFactory def test_wms_capabilities(): base_path, tail = os.path.split(__file__) file_path = os.path.join(base_path, 'mapfile_encoding.xml') wms = BaseWMSFactory() with open(file_path) as f: settings = f.read() wms.loadXML(xmlstring=setti...
556
188
from django.db import models from .base import Base class Transaction(Base): date = models.DateField() description = models.CharField(max_length=400) ammount = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey('Category', on_delete=models.CASCADE) from_account = mo...
977
299
import setuptools try: with open('README.md', 'r') as fh: long_description = fh.read() except: long_description = '' setuptools.setup( name='blackout', version='1.0.4', author='Mike Malinowski', author_email='mike@twisted.space', description='A python package making it...
864
272
class Element: def __init__(self, name, single): self.name = name self.single = single self.attrs = {} self.content = "" def set_attr(self, k, v): self.attrs[k] = v def get_attr(self, v): return self.attrs[k] def tohtml(self): attrs = (" " + " ".join([ "%s=\"%s\...
710
246
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import os import argparse from subprocess import call from .vk_music import VkMusic from .exceptions import AlreadyRunningError from .defaults import SafeFsStorage def main(): parser = argparse.ArgumentParser() parser.add_argumen...
2,590
782
__author__ = "Jens Honer" __copyright__ = "Copyright 2018, Jens Honer Tracking Toolbox" __email__ = "-" __license__ = "mit" __version__ = "1.0" __status__ = "Prototype" import numpy as np _bbox_sign_factors = np.asarray( [ [1.0, 1.0], [0.0, 1.0], [-1.0, 1.0], [...
950
405
from .base import * # noqa DEBUG = True SECURE_SSL_REDIRECT = False # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "CHANGEME!!!" # Enable FE component library PATTERN_LIBRARY_ENABLED = True INTERNAL_IPS = ("127.0.0.1", "10.0.2.2") BASE_URL = "http://localhost:8000" # URL to dire...
866
340
import swig_example swig_example.swig_example_hello() swig_example.link_liba_hello()
84
32
from torch.utils.data import Dataset from torchvision.transforms import transforms from sklearn.model_selection import train_test_split import os import glob import torch import numpy as np from PIL import Image import pdb class LocalDataset(Dataset): def __init__( self, root: str, datase...
3,356
1,087
# Generated by Django 3.1.7 on 2021-04-15 22:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('envdaq', '0008_interface'), ] operations = [ migrations.AlterField( model_name='interface', name='config', ...
408
133
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0001_initial'), ] operations = [ migrations.CreateModel( name='Client', fields=[ ...
2,020
553
from tutils import pdb from tutils import subprocess from tutils import Counter from tutils import partial from tutils import reduce from tutils import wraps from tutils import count from tutils import groupby from tutils import product from tutils import prod from tutils import itemgetter from tutils import Path from ...
3,181
983
from setuptools import setup setup( name='weather', version='0.1', description='CLI frontend for querying weather', packages=['weather'], entry_points={ 'console_scripts': ['weather = weather.__main__:main'] }, author='Aleksi Kauppila', author_email='aleksi.kauppila@gmail.com' )...
323
109
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import * admin.site.register(CharacterEvent) admin.site.register(Event) admin.site.register(CharacterOwner) admin.site.register(Character) admin.site.register(User, UserAdmin)
271
77
#coding=utf-8 import tkinter as tk from tkinter import ttk from tkinter import scrolledtext from tkinter import messagebox as mBox from tkinter import filedialog import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt import datetime i...
9,142
4,060
"""Example of assigning a variable.""" user_name = input("What is your name? ")
80
23
from .common import layers, grid, plotter, DEFAULT_COLORS, set_axes_equal from .atoms import plot_atoms, plot_points from .SiteNetworkPlotter import SiteNetworkPlotter from .SiteTrajectoryPlotter import SiteTrajectoryPlotter
228
69
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2017-2022 Anderson Bravalheri, Univertity of Bristol # High Performance Networks Group # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Yo...
1,525
420
""" Python 2/3 Compatibility ======================== Not sure we need to support anything but Python 2.7 at this point , but copied this module over from flask-peewee for the time being. """ import sys PY2 = sys.version_info[0] == 2 if PY2: text_type = unicode string_types = (str, unicode) unichr = u...
449
151
class Comic: def __init__(self, comic_num): self.id = comic_num self.title = "" self.title_text = "" self.transcript = "" self.explanation = "" self.img_url = "" self.og_title = "" self.og_ttext = ""
216
97
# from discord.ext.commands import Cog # from discord_slash import SlashContext, cog_ext # from discord_slash.utils.manage_commands import create_option # # # class TicTacToeAI(Cog): # def __init__(self, client): # self.client = client # # @cog_ext.cog_subcommand( # base="tictactoe", # b...
888
283
"""This module defines the karma_test rule.""" load("@infra-sk_npm//@bazel/typescript:index.bzl", "ts_library") load("@infra-sk_npm//@bazel/rollup:index.bzl", "rollup_bundle") load("@infra-sk_npm//karma:index.bzl", _generated_karma_test = "karma_test") def karma_test(name, srcs, deps, entry_point = None): """Runs...
3,254
1,028
from fileutils.fileutils import save_output_to_file, select_option_from_menu class ClassicAnalyzerStats: def __init__(self, data, current_event, output_file_name): self.__data = data self.__current_event = current_event self.__output_file_name = output_file_name self.__output = []...
5,894
1,760
import xallennlp.training.mlflow_callback import xallennlp.training.mlflow_checkpointer
88
28
# -*- coding: utf-8 -*- """colabUtil.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1KX9x-rqyj0XfUkLtfOVh8t8T_kW0hs0u #Colab Util This is a collection of utility functions that simplifies data science researchin using colab. I wrote this while ...
11,599
4,169
""" Base common features for product readers """ __classification__ = "UNCLASSIFIED" __author__ = "Thomas McCullough" from typing import Sequence, List, Tuple, Union from sarpy.io.general.base import AbstractReader from sarpy.io.product.sidd1_elements.SIDD import SIDDType as SIDDType1 from sarpy.io.product.sidd2_el...
2,893
945
class GladierBaseTool(object): """Gladier Defaults defines a common method of tying together flows, funcx-functions, and default inputs for starting a flow.""" flow_definition = None flow_input = dict() required_input = [] alias_exempt = ['funcx_endpoint_compute', 'funcx_endpoint_non_compute'...
2,144
608
from django.conf import settings from redis import StrictRedis from rest_framework.response import Response from rest_framework.views import APIView from PersonManage.role.models import Role from PersonManage.role.serializer import OneRole, ManyRole from PersonManage.jurisdiction.models import Jurisdiction class Role...
2,717
778
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See LICENSE file distributed along with the datalad_osf package for the # copyright and license terms. # # ## ##...
5,288
1,522
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains Qt observer pattern related functions and classes """ from __future__ import print_function, division, absolute_import from uuid import uuid4 from functools import partial from Qt.QtCore import Signal, QObject class ObservableProxy(QObject): ...
1,487
357
"""Advent of Code 2019 Day 12.""" from functools import lru_cache import re def main(file_input='input.txt'): lines = [line.strip() for line in get_file_contents(file_input)] moons = parse_moons(lines) after_steps = simulate_steps(moons, 1000) total_energy = find_total_energy(after_steps) print(f'...
3,645
1,151
from django.utils.encoding import force_text from django.utils.text import slugify try: from rest_framework.serializers import ManyRelatedField except ImportError: ManyRelatedField = type(None) try: from rest_framework.serializers import ListSerializer except ImportError: ListSerializer = type(None) ...
1,909
581
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Ui_ZhkuMainWindow.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import Qt...
2,246
744
from django.apps import AppConfig class CalheatmapConfig(AppConfig): name = 'calheatmap'
95
32
import numpy as np from pyNTCIREVAL import Labeler from pyNTCIREVAL.metrics import MSnDCG from collections import defaultdict from ntcir15_tools.data import en_query_ids, ja_query_ids, en_labels, ja_labels def get_rel_level(text): if text == "L0": return 0 if text == "L1": return 1 if text...
767
276
from .contrastive import SupConLoss, NoiseConLoss
50
18
C = int(input("Insira um valor: ")) Fire = (9 * C / 5) + 32 print(Fire)
71
35
""" filename: test.py author: Supriya Sudarshan version: 19.04.2021 description: Takes in the images and predicts (Covid or Non-Covid/Normal) using the *.h5 models """ import numpy as np import matplotlib.pyplot as plt import os from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing impor...
2,145
769
"""Problem 41 of https://projecteuler.net""" from itertools import permutations from projecteuler.inspectors import is_prime def problem_41(): """Solution to problem 41.""" # All 8 and 9 digit pandigitals are divisible by 3. perms = [int(''.join(x)) for x in permutations('1234567')] return max(x for...
348
128
import re import numpy as np from tqdm import tqdm from ..decorators import print_step from multiprocessing import Pool # Compiling for optimization re_sub_1 = re.compile(r"(:(?=\s))|((?<=\s):)") re_sub_2 = re.compile(r"(\d+\.)+\d+") re_sub_3 = re.compile(r"\d{2}:\d{2}:\d{2}") re_sub_4 = re.compile(r"Mar|Apr|Dec|Jan|...
3,064
1,172
import os from dataset.data_config import DataConfig images_data_base_dir = os.path.abspath('../../../data/datasets_coco/') data_conf = { DataConfig.IMAGE_BASEDIR: images_data_base_dir, DataConfig.TRAIN: [ { DataConfig.NICKNAME: 'decay_train', DataConfig.AN...
4,494
1,444
from django.urls import reverse from projectroles.tests.test_permissions import TestProjectPermissionBase from beaconsite.tests.factories import ConsortiumFactory, SiteFactory class UsersMixin: def setUp(self): super().setUp() self.consortium = ConsortiumFactory() self.site = SiteFactory(...
2,905
983
from django.forms import ModelForm from backend.models import Image, Image2 from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): email = forms.EmailField( widget=forms.TextInput(attrs={'class': '...
965
286
""" Created on Mar 7 2018 @author: MCC """ from ctypes import (CDLL, CFUNCTYPE, Structure, c_uint, c_int, c_longlong, POINTER, c_double, c_char, py_object, c_ulonglong, cast, c_char_p, c_byte) from enum import IntEnum from .ul_structs import DaqDeviceDescriptor, AiQueueElement, ...
22,851
8,589
""" Given a Singly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Linked List. """ from typing import Optional from binary_tree_node import Node # type: ignore from tree_traversal import inorder # type: ignore class LLN...
1,478
493
import numpy as np import matplotlib.pyplot as plt from modules.conversions import enu2uvw data = np.load("uv-array.npy") e = data[0,:].transpose() n = data[1,:].transpose() uvarray = [] for i in range(120): u,v = enu2uvw( wavelength=1.690, hour_angle=i/30, declination=...
556
215
# Author: Bishal Sarang import json import os import pickle import time import bs4 import colorama import requests from colorama import Back, Fore from ebooklib import epub from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By fro...
6,540
2,223
# Adapted from Magenta console commands import os from magenta.models.arbitrary_image_stylization import arbitrary_image_stylization_build_model as build_model from magenta.models.image_stylization import image_utils import numpy as np import tensorflow.compat.v1 as tf import tf_slim as slim class Magenta_Model(): ...
4,985
1,606