text
string
size
int64
token_count
int64
import numpy as np import math extraNumber = 4 * math.pi * pow(10,-7) def avgEMF(): turns = input("Input how many turns: ") radius = input("Input the radius (cm):") resistance = input("Input resistance (Ω): ") magField0 = input("Input the first magnetic Field value (T): ") magField1 = in...
754
255
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Computes the spectrogram of a test signal using cupy and cuFFT. Author: Jan Schlüter """ import sys import os import timeit import numpy as np import cupy as cp INPUT_ON_GPU = True OUTPUT_ON_GPU = True from testfile import make_test_signal def spectrogram(signal...
1,908
697
test = { 'name': 'q2b3', 'points': 5, 'suites': [ { 'cases': [ { 'code': '>>> ' 'histories_2b[2].model.count_params()\n' '119260', 'hidden': False, ...
1,597
358
from django.apps import AppConfig from django.contrib.admin.apps import AdminConfig from django.contrib.auth.apps import AuthConfig from django.contrib.contenttypes.apps import ContentTypesConfig from django.contrib.sessions.apps import SessionsConfig from django.db.models.signals import post_migrate from django_celery...
1,427
426
""" To avoid any issues of memory hanging around between inputs, we run each input as a separate process. A little ugly but effective """ import gc import glob import json import os import random import time import numpy as np import torch from common import invoke_main, read_json, write_json, prepare_out_file, chec...
11,604
3,774
import sys, os from subprocess import call try: from downloadPdb import downloadPDB except ImportError: from .downloadPdb import downloadPDB pdbListFile="/home/rsanchez/Tesis/rriPredMethod/data/joanDimers/117_dimers_list.tsv" outPath="/home/rsanchez/Tesis/rriPredMethod/data/joanDimers/pdbFiles/rawPDBs" USE_BIO_...
1,482
648
#!/usr/bin/env python import json import sys import xapian import support def search(dbpath, querystring, offset=0, pagesize=10): # offset - defines starting point within result set # pagesize - defines number of records to retrieve # Open the database we're going to search. db = xapian.Database(dbpa...
1,935
653
import re from rest_framework import serializers from .models import Collection, CollectionIcon class CollectionSerializer(serializers.ModelSerializer): """Collections's serializer""" class Meta: model = Collection read_only = ('token', ) class CollectionIconSerializer(serializers.ModelSe...
1,272
364
# Time: O(n*2^n) # Space: O(2^n) class Solution(object): def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ def dfs(nums, target, used, todo, lookup): if lookup[used] is None: targ = (todo-1)%...
1,738
580
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * # See also: AspellDictPackage class Aspell(AutotoolsPackage, GNUMirrorPackage): """GNU A...
737
307
# # Copyright (C) 2001 greg Landrum # """ unit testing code for compound descriptors """ from __future__ import print_function import unittest import Parser from rdkit.six.moves import xrange class TestCase(unittest.TestCase): def setUp(self): print('\n%s: '%self.shortDescription(),end='') self.piec...
1,888
735
from setuptools import setup, find_packages import pathlib here = pathlib.Path(__file__).parent.resolve() long_description = (here / "readme.md").read_text(encoding="utf-8") setup( name="data_dashboard", version="0.1.1", description="Dashboard to explore the data and to create baseline Machine Learning m...
1,575
543
# 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...
5,577
1,745
from flask_wtf import FlaskForm from wtforms import Form, StringField, PasswordField, BooleanField, SubmitField, IntegerField, validators, FileField, \ MultipleFileField, SelectField, RadioField, HiddenField, DecimalField, TextAreaField from wtforms.fields.html5 import DateField from wtforms.validators import DataR...
9,461
2,830
#coding: utf-8 import sys import os import asyncio import websockets import json import socket import xlrd #global vars phd_data = None pro_data = None def get_host_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('1.255.255.255', 65535)) ip = s.getsockname()[0] ...
2,774
1,020
# # Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. #/ # A DFA walker that knows how to dump them to serialized strings.#/ from io import StringIO from antlr4 import DFA from antl...
2,518
774
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Calibration Controller Performs calibration for hue, center of camera position, and servo offsets """ import os import cv2 import time import json import argparse import datetime import numpy as np import logging as log from env import Moa...
13,242
4,555
from datetime import datetime, timedelta from django.test import TestCase from django.test.utils import override_settings from marketing.tasks import ( delete_multiple_contacts_tasks, list_all_bounces_unsubscribes, run_all_campaigns, run_campaign, send_campaign_email_to_admin_contact, send_sch...
3,739
1,087
from py2html.main import * page = web() page.create() # Header Parameters # text = header text # n = title level page.header(text='My Site', n=1) # Label Parameters # text = label text # color = label color page.label(text='', color='') page.compile()
263
91
import unittest from JorGpi.pickup.pickup import SmartPickUp,Reference,CommandLineOptions class TestPickupIron(unittest.TestCase): @staticmethod def options(*args): return CommandLineOptions(*args) def test_iron_001(self): _input = "test -R _VASP/Fe/noFlip -D _VASP/Fe/flip00000 -E Fe -J1 ...
1,022
371
from django.contrib import admin from django.contrib.auth import get_user_model User = get_user_model() admin.site.register(User)
131
40
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.test import TestCase from django.conf import settings from django.test.client import Client from spotseeker_server.models import Spot import simplejson as json from decimal import * from django.test.utils import override...
21,795
6,532
# this python script makes a rest call to Juniper Northstar to get active LSPs # usage: python get_active_LSPs.py import json import requests from requests.auth import HTTPBasicAuth from pprint import pprint import yaml from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3...
1,807
608
# Copyright 2018 Adrien Guinet <adrien@guinet.me> # # 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 o...
859
310
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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 applicab...
6,031
2,240
# Generated by Django 3.2.5 on 2021-07-11 23:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('trips', '0003_alter_trip_state'), ] operations = [ migrations.CreateModel( name='Invoice', ...
855
271
import logging import os from decimal import Decimal from time import sleep import requests from hexbytes import HexBytes from web3 import Web3 from web3 import contract from web3.contract import Contract from config.constants import BASE_CURRENCIES from config.constants import GAS_LIMITS from config.constants import...
25,875
7,595
#!/usr/bin/env python # License: Apache-2.0 # Copyright (C) 2020 Mikhail f. Shiryaev class Column(object): """ Represents ClickHouse column """ def __init__( self, database: str, table: str, name: str, type: str, default_kind: str, default_expr...
1,170
379
#!/usr/bin/env python3 import os import sys MAX = 8 fpath = sys.argv[1] name = sys.argv[2] with open(fpath, "rb") as fh: sys.stdout.write("char %s[] = {" % (name,) ) i = 0 while True: if i > 0: sys.stdout.write(", ") if i % MAX == 0: sys.stdout.write("\n\t") ...
577
232
import unittest from reactivex import operators as ops from reactivex.testing import ReactiveTest, TestScheduler on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disp...
10,293
4,143
def solve(n, red , blue): rcount = bcount = 0 for i in range(n): if int(red[i]) > int(blue[i]): rcount = rcount +1 elif int(red[i]) < int(blue[i]): bcount = bcount + 1 print( 'RED' if rcount>bcount else ('BLUE' if bcount>rcount else 'EQUAL')) if __name__ == "__ma...
468
176
# Copyright 2014 Scopely, 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 in writing...
2,505
735
import autograd.numpy as np from pyCHAMP.wavefunction.wf_base import WF from pyCHAMP.optimizer.minimize import Minimize from pyCHAMP.sampler.metropolis import Metropolis from pyCHAMP.sampler.hamiltonian import Hamiltonian from pyCHAMP.solver.vmc import VMC class Hydrogen(WF): def __init__(self, nelec, ndim): ...
1,688
647
from braintree.configuration import Configuration from braintree.resource import Resource class AccountUpdaterDailyReport(Resource): def __init__(self, gateway, attributes): Resource.__init__(self, gateway, attributes) if "report_url" in attributes: self.report_url = attributes.pop("re...
585
160
import pygame import pygame.gfxdraw from constants import Constants class Balls(object): def __init__(self, all_sprites, all_balls): self.all_sprites = all_sprites self.all_balls = all_balls def spawn_ball(self, pos, vel, team): # Todo: Figure out how to spawn multiple balls with some...
1,696
590
from pyqtgraph.Qt import QtCore, QtGui import numpy as np from scipy.spatial import distance as dist import glob import re import os from PyQt5 import QtGui from PyQt5.QtCore import * from PyQt5.QtGui import * import sys import cv2 import pandas as pd from PyQt5.Qt import * import pyqtgraph as pg #from PyQt4.Qt import ...
36,597
11,832
frase = input('Digite uma frase: ').upper().strip().replace(' ', '') tamanho = int(len(frase)) inverso = '' #Opção mais simples: # inverso = frase[::-1] for contador in range(tamanho-1, -1, -1): inverso += frase[contador] print('O inverso de {} é {}'.format(frase, inverso)) if frase == inverso: print('Temos...
394
156
from unittest import TestCase from options.pricing.binomial_trees import BinomialTreePricer from options.option import OptionType, Option class BinomialTreeTestCase(TestCase): def test_basic(self): """European option, spot price 50, strike price 52, risk free interest rate 5% expiry 2 years, vo...
540
188
import atexit import os import sys import platform import json import glob import datetime import time import threading import tkinter as tk from pynput import mouse from pathlib import Path from playsound import playsound from enum import Enum import copy #"THE BEER-WARE LICENSE" (Revision 42): #bleach86 wrote this ...
16,589
5,617
""" Other useful structs """ from __future__ import absolute_import from collections import namedtuple """A topic and partition tuple Keyword Arguments: topic (str): A topic name partition (int): A partition id """ TopicPartition = namedtuple("TopicPartition", ["topic", "partition"]) """A Kafka broker...
2,927
825
import cv2 from trackers.tracker import create_blob, add_new_blobs, remove_duplicates import numpy as np from collections import OrderedDict from detectors.detector import get_bounding_boxes import uuid import os import contextlib from datetime import datetime import argparse from utils.detection_roi import get_roi_fra...
7,357
2,421
from flask import request from resources.api_view import ApiView from exceptions.invalid_usage_exception import InvalidUsageException from models.user.user import User from models.user.authenticated_user import AuthenticatedUser class MagicCastleAPI(ApiView): def get(self, user: User, hostname): if hostna...
2,542
662
# Copyright 2018 Contributors to Hyperledger Sawtooth # # 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 ...
2,615
813
import cv2 import os import numpy as np from PIL import Image def frame2video(im_dir, video_dir, fps): im_list = os.listdir(im_dir) im_list.sort(key=lambda x: int(x.replace("_RBPNF7", "").split('.')[0])) img = Image.open(os.path.join(im_dir, im_list[0])) img_size = img.size # 获得图片分辨率,im_dir文件夹下的图片分辨率...
881
399
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 14 17:38:48 2020 @author: luke """ import sys from functools import partial import torch import torch.nn as nn import prettytable as pt from .basic_hook import MODULES_MAPPING def get_model_compute_info(model, input_res, ...
11,103
3,432
# SPDX-License-Identifier: MIT # Copyright (C) 2019-2020 Tobias Gruetzmacher # Copyright (C) 2019-2020 Daniel Ring from ..scraper import _ParserScraper from ..helpers import indirectStarter class Derideal(_ParserScraper): baseUrl = 'https://www.derideal.com/' imageSearch = '//img[contains(@class, "comic-page"...
2,301
784
""" Function are subprograms which are used to compute a value or perform a task. Type of Functions:- Built in Functions: print(), upper() User define functions Advantage of Functions 1. Write once and use it as many time as you need. This provides code reusability 2. Function facilitates ease of code maint...
3,340
1,139
# coding: utf-8 import click @click.command() @click.option('--carrier', prompt='Carrier ID', help='Example: "ect" for Correios') @click.option('--object-id', prompt='Object ID', help='Example: PN871429404BR') def main(carrier, object_id): from trackr import Trackr from trackr.exceptions import ...
945
304
from enum import Enum, auto from subprocess import CalledProcessError, run from pitop.common.command_runner import run_command from pitop.common.logger import PTLogger class NotificationAction: def __init__(self, call_to_action_text, command_str) -> None: self.call_to_action_text = call_to_action_text ...
3,043
921
# xy to location # # Gismo is a plugin for GIS environmental analysis (GPL) started by Djordje Spasic. # # This file is part of Gismo. # # Copyright (c) 2019, Djordje Spasic <djordjedspasic@gmail.com> # Gismo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Lic...
5,778
1,825
# pylint: disable-msg=C0103 """ SentinelAnomalyLookup: This package is developed for Azure Sentinel Anomaly lookup """ # __init__.py from .anomaly_lookup_view_helper import AnomalyLookupViewHelper from .anomaly_finder import AnomalyQueries, AnomalyFinder
256
93
import pygame from pygame.sprite import Sprite class Coins(Sprite): """Coins""" def __init__(self, hub, x, y, name='coin', state='floating'): super().__init__() # Values self.name = name self.hub = hub self.original_pos = [x, y] self.rest_height = y se...
3,989
1,313
from geo.calc import Calc from geo.calc import Distance from geo.geosp import Wt from geo.geosp import Gh from geo.files.csv_file import check
142
49
from pathlib import Path from nb_helpers.clean import clean_all, clean_one from tests import TEST_PATH TEST_PATH TEST_NB = Path("test_nb.py") def test_clean_one(): "clean just one nb" clean_one(TEST_NB) def test_clean_all(): "clean all test nbs" clean_all(path=TEST_PATH)
293
110
import streamlit as st def app(): import yfinance as yf import streamlit as st import datetime import matplotlib.pyplot as plt import talib import ta import numpy as np import matplotlib.ticker as mticker import pandas as pd import requests yf.pdr_override() st.wr...
5,746
2,191
from __future__ import absolute_import from mock import patch from django.db import IntegrityError from sentry.mediators.sentry_apps import Creator from sentry.models import ( AuditLogEntry, AuditLogEntryEvent, ApiApplication, IntegrationFeature, SentryApp, SentryAppComponent, User, ) from...
4,642
1,443
# This file was automatically created by FeynRules 2.3.32 # Mathematica version: 11.3.0 for Mac OS X x86 (64-bit) (March 7, 2018) # Date: Sat 21 Apr 2018 20:48:39 from object_library import all_parameters, Parameter from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot # This is a defau...
17,869
5,802
import time musicLrc = """ [00:03.50]传奇 [00:19.10]作词:刘兵 作曲:李健 [00:20.60]演唱:王菲 [00:26.60] [04:40.75][02:39.90][00:36.25]只是因为在人群中多看了你一眼 [04:49.00] [02:47.44][00:43.69]再也没能忘掉你容颜 [02:54.83][00:51.24]梦想着偶然能有一天再相见 [03:02.32][00:58.75]从此我开始孤单思念 [03:08.15][01:04.30] [03:09.35][01:05.50]想你时你在天边 [03:16.90][01:13.13]想你时你在眼前 [03:...
1,828
1,154
# coding=utf-8 from __future__ import absolute_import import datetime import logging import sys import flask import octoprint.plugin from octoprint.events import eventManager, Events from octoprint.server import user_permission from octoprint.util import RepeatedTimer from .bed_notifications import BedNotifications ...
16,826
6,085
from cspatterns.datastructures import buffer def test_circular_buffer(): b = buffer.CircularBuffer(2, ['n']) assert len(b.next) == 2 assert b.n is None b = buffer.CircularBuffer.create(2, attrs=['n', 'fib']) curr = b out = [0, 1, ] curr.prev[-2].n = 0 curr.prev[-2].fib = 1 curr...
660
297
# Generated by Django 2.1.7 on 2019-02-17 14:50 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='RedactedClientConfig', fields=[ ('id', mode...
1,214
323
from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import matplotlib.colors as colors from numpy import array from numpy import max map = Basemap(llcrnrlon=-0.5,llcrnrlat=39.8,urcrnrlon=4.,urcrnrlat=43., resolution='i', projection='tmerc', lat_0 = 39.5, lon_0 = 1) map.readshapefil...
1,741
720
from nonebot import on_keyword, on_command from nonebot.typing import T_State from nonebot.adapters.cqhttp import Message, Bot, Event # 这两个没用的别删 from nonebot.adapters.cqhttp.message import MessageSegment import requests from nonebot.permission import * from nonebot.rule import to_me from aiocqhttp.exceptions im...
895
353
import html from collections import namedtuple from pathlib import Path from typing import List, Dict import requests from bs4 import BeautifulSoup from lxml import etree from lxml.etree import XPath Emoji = namedtuple('Emoji', 'char name') class EmojiExtractor(object): def __init__(self): self.all_emo...
4,031
1,259
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Tests that the seccomp filters don't let blacklisted syscalls through.""" import os from subprocess import run import pytest import host_tools.cargo_build as host # pylint:disable=import-error @pyte...
5,084
1,726
class a: def __init__(self,da): self.da = da return def go(self): dd() return None def dd(): print('ok') return None aa = a(1) aa.go()
185
68
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.12 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. """ IDA Plugin SDK API wrapper: hexrays """ from sys import version_info if version_info >= (2,6,0): def sw...
566,013
221,219
#!/usr/bin/env python3 """ @author: Sam Cook MySql Parser for graphical presentation """ import mysql.connector import datetime from mysql.connector import Error from datetime import datetime, timedelta import json class sql_graph_info(): def __init__(self, node, interface, time, sql_creds, db): """ ...
3,714
1,121
# test_fluxqubit.py # meant to be run with 'pytest' # # This file is part of scqubits. # # Copyright (c) 2019 and later, Jens Koch and Peter Groszkowski # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. ...
830
289
import FWCore.ParameterSet.Config as cms patPFParticles = cms.EDProducer("PATPFParticleProducer", # General configurables pfCandidateSource = cms.InputTag("noJet"), # MC matching configurables addGenMatch = cms.bool(False), genParticleMatch = cms.InputTag(""), ## particles source to be used for ...
1,379
433
# coding: utf8 from __future__ import unicode_literals import pytest import spacy import json from api.server import parse, doc2json, load_model @pytest.fixture(scope="session") def model(): return "en_core_web_sm" @pytest.fixture(scope="session") def text(): return "This is a sentence about Facebook. Thi...
2,252
839
########################################################################## # # Copyright (c) 2018, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
28,365
10,348
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2022 Valory AG # Copyright 2018-2021 Fetch.AI Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
20,598
6,230
# -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END import os import asyncio import json from unittest.mock import MagicMock, patch from collections import Counter from aiohttp import web import pytest from foglamp.services.core import routes from foglamp.services.core import ...
12,177
3,699
""" Why need dimensional reduction The following is the use of dimensionality reduction in the data set: • As data dimensions continue to decrease, the space required for data storage will also decrease. • Low-dimensional data helps reduce calculation/training time. • Some algorithms tend to perform poorly on high-dim...
3,690
1,033
""" These methods can be called inside WebCAT to determine which tests are loaded for a given section/exam pair. This allows a common WebCAT submission site to support different project tests """ def section(): # Instructor section (instructor to change before distribution) #return 8527 #return 8528 r...
456
132
from datetime import datetime import scrapy import lxml from lxml.html.clean import Cleaner import re SOURCE = 'Página 12' LANGUAGE = 'es' cleaner = Cleaner(allow_tags=['p', 'br', 'b', 'a', 'strong', 'i', 'em']) class Pagina12Spider(scrapy.Spider): name = 'pagina12' allowed_domains = ['www.pagina12.com.ar'] ...
2,727
883
from calendar import c from typing import Dict, List, Union from zlib import DEF_BUF_SIZE import json_lines import numpy as np import re from sklearn.preprocessing import MultiLabelBinarizer from sklearn.manifold import TSNE from sklearn.preprocessing import StandardScaler import pandas as pd import json from scipy.spa...
6,978
2,357
#!/usr/bin/env python # # Copyright (c) 2018, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information # see the Pycom Licence v1.0 document supplied with this file, or # available at https://www.pycom.io/opensource/licensing ...
22,448
6,152
import datetime from django.utils import timezone from django.contrib.auth.models import User from hknweb.events.models import Event, EventType, Rsvp class ModelFactory: @staticmethod def create_user(**kwargs): default_kwargs = { "username": "default username", } kwargs =...
2,315
684
from django.shortcuts import redirect from .forms import PrescriptionForm from core.views import is_doctor, is_nurse, is_admin, is_patient from core.models import * from .models import Prescription from django.contrib.auth.decorators import login_required, user_passes_test from django.utils import timezone from dja...
4,979
1,476
""" 1. Clarification 2. Possible solutions - dfs + memoization - Topological sort 3. Coding 4. Tests """ # T=O(m*n), S=O(m*n) from functools import lru_cache class Solution: DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)] def longestIncreasingPath(self, matrix: List[List[int]]) -> int: if not mat...
2,232
745
#!/usr/bin/env python #coding=utf-8 ''' Remove tailing whitespaces and ensures one and only one empty ending line. ''' import os, re def scan(*dirs, **kwargs): files = [] extensions = kwargs['extensions'] if kwargs.has_key('extensions') else None excludes = kwargs['excludes'] if kwargs.has_key('excludes') else...
1,511
557
from core import * from cameras import * from geometry import * from material import * from lights import * class TestPostprocessing2(Base): def initialize(self): self.setWindowTitle('Pixellation and Reduced Color Palette') self.setWindowSize(1024,768) self.renderer = Rendere...
4,096
1,310
#!/usr/bin/env python def igs_test(target_dir, exp_name, th, group='', dry_run=0): from scripts.conf.conf import machine_conf, machine_info from scripts.utils import run_test import itertools cs = 8192 th = th # Test using rasonable time # T = scale * size / perf # scale = T*perf/size desired_time...
3,027
1,551
import os import shutil import codecs import json from cuddlefish.runner import run_app from cuddlefish.rdf import RDFManifest def run(): original_harness_options = os.path.join('development', 'firefox', 'harness-options.json') backup_harness_options = os.path.join('development', 'firefox', 'harness-options-bak.jso...
654
242
# PyRipple # # Copyright 2015 Gilles Pirio # # 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...
8,408
3,255
# -*- coding: utf-8 -*- """ Unit tests for Senna """ from __future__ import unicode_literals from os import environ, path, sep import logging import unittest from nltk.classify import Senna from nltk.tag import SennaTagger, SennaChunkTagger, SennaNERTagger # Set Senna executable path for tests if it is not specifie...
3,205
1,160
#------------------------------------------------------------------------------- # # Project: EOxServer <http://eoxserver.org> # Authors: Fabian Schindler <fabian.schindler@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2015 EOX IT Services GmbH # # Permission...
8,191
2,183
text = ''' Victor Hugo's ({}) tale of injustice, heroism and love follows the fortunes of Jean Valjean, an escaped convict determined to put his criminal past behind him. But his attempts to become a respected member of the community are constantly put under threat: by his own conscience, when, owing to a case of mista...
4,113
1,570
from typing import Any, Dict import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F FC1_DIM = 1024 FC2_DIM = 128 class MLP(nn.Module): """Simple MLP suitable for recognizing single characters.""" def __init__( self, data_config: Dict[str, Any],...
2,085
751
from pygame import Surface, font from .basewidget import BaseWidget from frontend import Renderer, WidgetHandler class Button(BaseWidget): action = None def __init__(self, x, y, texto, action=None): self.f = font.SysFont('Verdana', 16) imagen = self.crear(texto) rect = imagen.get_rect...
979
366
import numpy as np import tensorflow as tf """ Do an MNIST classification line by line by LSTM """ (x_train, y_train), \ (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train, x_test = x_train/255.0, x_test/255.0 model = tf.keras.Sequential() model.add(tf.keras.layers.LSTM(128, input_shape=(None, 28))) ...
709
286
# coding: utf-8 # In[1]: import numpy as np import pandas as pd import os from random import shuffle from tqdm import tqdm DATA_DIR = '../input/amazon/' TRAIN_TIF_DIR = DATA_DIR + 'train-tif/' TRAIN_CSV = DATA_DIR + 'train.csv' TEST_TIF_DIR = DATA_DIR + 'test-tif/' IMG_SIZE = 100 LR = 1e-3 MODEL_NAME = 'amazon=-{...
984
437
"""Base support for POSIX-like platforms.""" import py, os, sys from rpython.translator.platform import Platform, log, _run_subprocess import rpython rpydir = str(py.path.local(rpython.__file__).join('..')) class BasePosix(Platform): exe_ext = '' make_cmd = 'make' relevant_environ = ('CPATH', 'LIBRARY_...
11,271
3,722
import glob import bs4 import gzip import pickle import re import os from concurrent.futures import ProcessPoolExecutor as PPE import json from pathlib import Path from hashlib import sha256 import shutil Path('json').mkdir(exist_ok=True) def sanitize(text): text = re.sub(r'(\t|\n|\r)', '', text) text = re.s...
3,247
1,146
#!/usr/bin/python # # Copyright 2020 Google LLC # # 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 ag...
5,047
1,477
import functools import json from os.path import abspath, dirname, exists, join from typing import Dict, Sequence import numpy as np import pandas as pd import torch from pymatgen.core import Composition from torch.utils.data import Dataset class CompositionData(Dataset): def __init__( self, df: ...
7,490
2,435
import unittest from dq import util class TestUtil(unittest.TestCase): def test_safe_cast(self): assert util.safe_cast('1', int) == 1 assert util.safe_cast('meow', int, 2) == 2
201
73
""" PermCheck Check whether array A is a permutation. https://codility.com/demo/results/demoANZ7M2-GFU/ Task description A non-empty zero-indexed array A consisting of N integers is given. A permutation is a sequence containing each element from 1 to N once, and only once. For example, array A such that: A[0] = 4...
1,483
554