text
string
size
int64
token_count
int64
from pydub import AudioSegment import os import math from pathlib import Path ''' Splice wav files into multiple segments. ''' LENGTH = 3 # Set splice length in seconds def splice(audioPath, outputPath): # try: # os.mkdir('Spliced Spectrogram training') # Need to figure out where to put this # excep...
779
269
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: Wu Liang @contact: @date: 2014/06/23 """ import os import sqlite3 import urllib2 import shutil import tarfile import hashlib import codecs from mako.template import Template from pyquery import PyQuery currentPath = os.path.join(os.path.dirname(os.path.real...
3,947
1,395
import os import sys sys.path.insert(0, os.path.abspath("..")) # -------------------------------------------------------------------------------------- project = "nisystemlink" copyright = "2020, National Instruments" author = "National Instruments" # The short X.Y version version = "0.1" # The full version, includ...
1,527
529
from typing import Dict, List from arango.cursor import Cursor from django.http.response import Http404 from django.shortcuts import get_object_or_404 from rest_framework.pagination import LimitOffsetPagination from rest_framework.request import Request from rest_framework_extensions.mixins import NestedViewSetMixin ...
2,702
760
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import logging import os import sys def ParseArgs(): parser = argparse.ArgumentParser( description='Host file generator for CELab E...
2,613
829
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from django.urls import reverse from django_extensions.db.models import TimeStampedModel from mptt.models import MPTTModel, TreeForeignKey ...
8,037
2,334
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------...
59,466
16,533
import unittest from gamesopt.train import train, TrainConfig class TestOptimizer(unittest.TestCase): def test_sgda(self): config = TrainConfig(num_iter=2) train(config)
190
58
import pandas as pd def loadTest(filepath): df = pd.read_csv(filepath) return df
91
33
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,832
591
from setuptools import setup, find_packages install_requires = [ "allennlp>=0.9.0", "wandb==0.8.15", ] setup( name='allennlp_wandb', version='0.0.1', description='Utilities to use allennlp with wandb', packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), p...
425
161
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="django-axes", description="Keep track of failed login attempts in Django-powered sites.", long_description="\n".join( [ open("README.rst", encoding="utf-8").read(), open("CHANGES.rst", encoding="...
2,311
706
from django.contrib import admin from achievements import models admin.site.register(models.Achievement)
106
29
from torch.nn import CrossEntropyLoss class GPT2Loss(CrossEntropyLoss): def __init__(self, pad_token_id): super(GPT2Loss, self).__init__(ignore_index=pad_token_id) def forward(self, output, labels): """ Loss function for gpt2 :param output: :param labels: :retu...
1,925
591
import numpy as np import pandas as pd import matplotlib.pyplot as plt def main(filename): data = pd.read_csv(filename, header=None) means = data.mean(axis = 0) stds = data.std(axis = 0) return means[0], means[1], stds[0], stds[1] if __name__ == '__main__': files_http1 = ['./results/benchmark_siz...
6,481
2,659
import unittest import os from matplotlib import pyplot as plt from shapely import geometry, affinity X_COORDINATE = 0 Y_COORDINATE = 1 def extract_x_y(polygon: list) -> (list, list): """Extract the x and y coordinates as two separate lists""" x_list = [] y_list = [] for vertex in polygon: x...
7,376
2,491
import os from PIL import Image from array import * from random import shuffle import shutil def move_file(src_path, dst_path, file): print("from : ",src_path) print("to : ",dst_path) try: # cmd = 'chmod -R +x ' + src_path # os.popen(cmd) f_src = os.path.join(src_path, file) ...
1,332
459
import sys from pyspark import SparkContext import json print('spark got python path -> ' + str(sys.executable)) logfile = sys.argv[1] sc = SparkContext() logdata = sc.textFile(logfile).cache() a_count = logdata.filter(lambda s: 'a' in s).count() b_count = logdata.filter(lambda s: 'b' in s).count() print(json.dumps({'a...
348
126
import bpy from bpy.props import * from ...nodes.BASE.node_base import RenderNodeBase class RenderNodeGetListIndex(RenderNodeBase): """A simple input node""" bl_idname = 'RenderNodeGetListIndex' bl_label = 'Get List Index' def init(self, context): self.create_output('RenderNodeSocketInt', "i...
738
239
from keras.models import load_model import cv2 import pickle import keras.backend as K import numpy as np from src.model_path import MODEL_PATH '''def predict(self, cell): model = load_model('./model/Model.h5') f = K.function([model.layers[0].input, K.learning_phase()],[model.layers[-1].output]) rescaled_cell = ...
1,188
431
# -*- coding: utf-8 -*- """A module for plotting penguins data for modelling with scikit-learn.""" # Imports --------------------------------------------------------------------- import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd # Constants -----------------------------...
4,544
1,656
from django.db import migrations def rename_sslyze_parser(apps, schema_editor): Test_Type_model = apps.get_model('dojo', 'Test_Type') try: test_type_sslyze = Test_Type_model.objects.get(name='SSLyze 3 Scan (JSON)') test_type_sslyze.name = 'SSLyze Scan (JSON)' test_type_sslyze.save() ...
623
215
import unittest from forestgame.game.world import World class WorldTest(unittest.TestCase): def test_world_inits_to_empty_data(self): world = World(None, "1", "0", 0, 0, [], []) self.assertEqual(0, world.get_size_x()) self.assertEqual(0, world.get_size_y()) self.assertEqual([], world.get_tile_data(...
4,203
1,905
# Copyright 2021 Richard Johnston <techpowerawaits@outlook.com> # SPDX-license-identifier: 0BSD import string from loguru import logger try: import cell_pos from exceptions import InvconvMissingHeaders import ftype import msg_handler except ModuleNotFoundError: import invconv.cell_pos as cell_pos...
9,756
3,095
import os from tkinter import * import tkinter.filedialog as tkfd from PIL import Image import numpy as np import solvers.generation_solver.image_seperation as IS def layer_interface(img_num): layer_names = [] layer_nums = [] for k in range(img_num): master = Toplevel() master.title(f"Imag...
5,501
2,078
from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq import re, json # Getting the page URL = "https://www.astronomytrek.com/star-constellations-brightest-stars/" uClient = uReq(url=URL) page_html = uClient.read() page_soup = soup(page_html, "html.parser") # Opening a file to write in star...
953
363
class Solution: def maxArea(self, height) -> int: left=0 right=len(height)-1 res=min(height[left],height[right])*(right-left) while right>left: res=max(res,(right-left)*min(height[right],height[left])) if height[left]<height[right]: left+=1 ...
493
171
# coding=utf-8 # Copyright 2020 TF.Text 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 applicable law or ag...
13,688
5,124
"""Unit test for the index.py file.""" import unittest from datetime import datetime, timedelta, timezone import json from unittest.mock import patch, mock_open import requests_mock from src import index from src import github_services class ModuleIntegerationTest(unittest.TestCase): """Integeration test for th...
5,324
1,643
# -*- coding: utf-8 -*- # # Copyright 2017 Ricequant, 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 ...
3,133
1,081
import funcvote as vote votes = input("투표내용 >>>") # print(votes) # print(type(votes)) result = vote.str2int(votes) print(vote.countvotes(result)) result = vote.countvotes(result) vote.printvote(result) # 투표 초안
215
100
# Day 2: Operators # Start using arithmetic operators. # # https://www.hackerrank.com/challenges/30-operators/problem # #!/bin/python3 import sys if __name__ == "__main__": meal_cost = float(input().strip()) tip_percent = int(input().strip()) tax_percent = int(input().strip()) cost = meal_cost * (1 ...
427
158
from django.http import HttpResponse from django.template import RequestContext, loader from django.shortcuts import render, get_object_or_404, redirect from django.core.urlresolvers import reverse from django.core.cache import cache from articles.models import CIFArticle from .forms import CIFArticleForm def index(r...
2,503
728
# Copyright (c) 2021, Omid Erfanmanesh, All rights reserved. class RuntimeMode: TRAIN = 0 TUNING = 1 CROSS_VAL = 2 FEATURE_IMPORTANCE = 3
156
72
# noinspection PyPep8 """pydoc_fork A fork of pydoc that is optimized for generating html documentation in a CI context Usage: pydoc_fork <package>... [options] pydoc_fork (-h | --help) pydoc_fork --version Options: -h --help Show this screen. -v --version Show version. ...
2,616
814
""" libs.strings By default, uses `en-gb.json` file inside the `strings` top-level folder. If language changes, set `libs.strings.default_locale` and run `libs.strings.refresh()`. """ import json default_locale = "en-us" cached_strings = {} def refresh(): global cached_strings with open(f"strings/{default_...
444
145
# Copyright 2013-2021 The Salish Sea MEOPAR Contributors # and The University of British Columbia # 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...
5,881
1,726
"""distributions module.""" from UQpy.distributions.collection.Beta import Beta from UQpy.distributions.collection.Binomial import Binomial from UQpy.distributions.collection.Cauchy import Cauchy from UQpy.distributions.collection.ChiSquare import ChiSquare from UQpy.distributions.collection.Exponential import Exponent...
1,469
418
# # Example file for HelloWorld # def main(): print("Hello World") name = input("What is your name? ") print("Nice to meet you,", name) if __name__ == "__main__": main()
190
67
import sys import csv import json import math import pygame import numpy as np from pygame.locals import * import pandas as pd from data import * from agent import agentsList, Agent global screenSize screenSize = [1920, 1080] def load_parameters(path): package = [] file = open(path, 'r') j = json.load(f...
15,309
6,412
""" Package has implementation for the FID score calculation """ from GAN.FID import fid_score from GAN.FID import inception
126
37
import unittest from flask_monitoringdashboard.core.profiler.util.stringHash import StringHash class TestStringHash(unittest.TestCase): def test_stringhash(self): string_hash = StringHash() self.assertEqual(string_hash.hash('abc'), 0) self.assertEqual(string_hash.hash('def'), 1) ...
574
185
from django.shortcuts import render, get_object_or_404 from .models import News # Create your views here. def index(request): latest_news_list = News.objects.order_by('-pub_date')[:10] context = {'latest_news_list': latest_news_list} return render(request, 'news/index.html', context) def detail(request, ...
439
154
#!/usr/bin/python import os.path import cppcodebase import random def CreateLibJamfile(lib_number, classes): os.chdir(cppcodebase.lib_name(lib_number)) handle = file("Jamfile.jam", "w") handle.write ("SubDir TOP lib_" + str(lib_number) + " ;\n\n") handle.write ("SubDirHdrs $(INCLUDES) ;\n\n") han...
1,229
468
""" FOTA update tool which is called from the dispatcher during installation Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ import logging import os import platform from threading import Timer from typing import Any, Optional, Mapping from future.moves.urllib.parse impo...
8,482
2,268
import copy import datetime import sys import os import time import argparse import traceback import pytz import syncthing from influxdb import InfluxDBClient import yaml from yaml2dataclass import Schema, SchemaPath from typing import Optional, Dict, Type, List from dataclasses import dataclass, asdict, field @dat...
8,727
2,571
# -*- coding: utf-8 -*- import os import re import shutil import typing from PIL import Image from PyPDF2 import PdfFileReader import PyPDF2.utils import pytest from preview_generator.exception import UnavailablePreviewType from preview_generator.manager import PreviewManager from tests import test_utils CURRENT_DI...
5,230
1,991
from ipso_phen.ipapi.base.ipt_abstract import IptBase from ipso_phen.ipapi.tools import regions import numpy as np import cv2 import logging logger = logging.getLogger(__name__) from ipso_phen.ipapi.base import ip_common as ipc class IptFilterContourBySize(IptBase): def build_params(self): ...
10,495
3,197
from wrapper_tests.upsert_test import * from wrapper_tests.upsertvaluedict_test import * import os import logging import sys import argparse import signal logging.getLogger().setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s - %(name)s...
718
229
import smtplib gmail_user = 'your email' gmail_password = 'your password' sent_from = gmail_user to = ['reciever email'] #Create a list for all the recievers subject = 'OMG Super Important Message' body = 'Hey, what\'s up?\n- You' email_text = """\ From: %s To: %s Subject: %s %s """ % (sent_from, ", "....
598
231
''' Created on 11 Sep 2015 @author: si ''' import json import random import time from threading import Thread # import urllib import urllib2 from Queue import Queue import logging logger = logging.getLogger(__name__) API_URL = "http://127.0.0.1:5000/" class LoadTest(object): """ Create a single process with...
4,532
1,370
from django.contrib import admin from django.conf.urls import include,url from .import views urlpatterns = [ url(r'^$', views.IndexView.as_view(),name='index'), #homeapp_detail_view_url url(r'^(?P<pk>[0-9]+)/$',views.LocationView.as_view(),name='property'), #homeapp/detailview/moredetailview url(r'...
407
154
from utils import * from model import Model2 if __name__ == '__main__': train_data = DataLoader('../data/trainX.txt', '../data/trainY.txt') test_data = DataLoader('../data/testX.txt', '../data/testY.txt') train_data.set_batch(100) test_data.set_batch(100) char_dic = CharDic([train_data]...
541
211
#!/usr/bin/env python ############################################################################## ## # This file is part of Sardana ## # http://www.sardana-controls.org/ ## # Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain ## # Sardana is free software: you can redistribute it and/or modify # it under th...
3,475
1,010
import numpy as np def accuracy_score(y_true, y_pred): a = np.argmax(y_true, axis=1) b = np.argmax(y_pred, axis=1) return np.count_nonzero(a == b) / y_true.shape[0]
179
79
from asaas.typing import SyncAsync from typing import Any, Optional, Dict class FinancialTransactions: def __init__(self, parent: Any) -> None: self.parent = parent def list( self, query: Optional[Dict[Any, Any]] = None, **kwars: Any ) -> SyncAsync[Any]: return self.parent.request...
462
138
from functools import partial from uuid import UUID from dateutil.parser import parse as dateutil_parse from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from rest_framework import serializers from rest_framework.exceptions import ValidationError from r...
17,672
4,677
import math import random from ark import dear_imgui, ApplicationFacade, Arena, Event, Integer, Collider, RenderObject, Size, Camera, Vec3, Numeric class Application: def __init__(self, application: ApplicationFacade): self._down_x = 0 self._down_y = 0 self._application = application ...
4,763
1,712
# coding: utf-8 """ Jamf Pro API ## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh...
11,693
3,294
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ssokeygendialog.ui' # # Created: Sun Feb 1 12:33:36 2015 # by: PyQt5 UI code generator 5.4 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(s...
1,342
456
import urllib.request import os from typing import List from util.n_util import NUser from util.n_util import get_n_entry import time import threading from util.array_util import slice_array delay: float = 2.5 class ProgressWrapper: """The progress wrapper keeps track of the progress of a operation by wrapping a...
4,138
1,229
import pytest from stable_baselines import A2C, ACER, ACKTR, DeepQ, DDPG, PPO1, PPO2, TRPO from stable_baselines.ddpg import AdaptiveParamNoiseSpec from stable_baselines.common.identity_env import IdentityEnv, IdentityEnvBox from stable_baselines.common.vec_env import DummyVecEnv PARAM_NOISE_DDPG = AdaptiveParamNoise...
2,907
1,050
import tensorflow as tf from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants export_dir = './reference/00000002' graph_pb = './creditcardfraud.pb' builder = tf.saved_model.builder.SavedModelBuilder(export_dir) with tf.gfile.GFile(graph_pb, "rb") as f: ...
1,129
384
from __future__ import division from __future__ import absolute_import from pycuda.tools import context_dependent_memoize import numpy as np def platform_bits(): return tuple.__itemsize__ * 8 def has_stack(): from pycuda.driver import Context return Context.get_device().compute_capability() >= (2, 0) ...
936
320
import torch from scipy.stats import median_absolute_deviation class Transform_Base(object): """ Base class for transformations based on some data. """ def __init__(self, Ytr): self.Ytr = Ytr # Transform the mean def scale_mean(self, mu): return mu # Reve...
1,666
604
# eliminate duplicate service periods from a GTFS database from graphserver.ext.gtfs.gtfsdb import GTFSDatabase import sys from optparse import OptionParser def main(): usage = """usage: python dedupe.py <graphdb_filename>""" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() ...
2,797
922
class MyClass: def __repr__(self): return self.__class__.__name__ + '()' print(MyClass().__repr__())
105
37
import pytest from prefect.core import Edge, Flow, Parameter, Task from prefect.tasks.core import collections from prefect.tasks.core.constants import Constant from prefect.tasks.core.function import FunctionTask class IdentityTask(Task): def run(self, x): return x class TestConstant: def test_cons...
9,562
3,251
"""Node class module for Binary Tree.""" class Node(object): """The Node class.""" def __init__(self, value): """Initialization of node object.""" self.value = value self.left = None self.right = None def __str__(self): """Return a string representation of the nod...
536
155
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: ...
26,713
10,000
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from deepsv import deepsv from unittest.mock import patch """Tests for the deepsv module. """ def test_something(): assert True def test_adding_numbers(): assert deepsv.add_numbers(1, 1) == 2 assert deepsv.add_numbers(1, 2) != 2 def test_wi...
1,627
630
#!/usr/bin/env python """TcEx Dependencies Command""" # standard library import os import platform import shutil import subprocess # nosec import sys from distutils.version import StrictVersion # pylint: disable=no-name-in-module from pathlib import Path from typing import List from urllib.parse import quote # third...
8,959
2,515
from .AST.sentence import * from .AST.expression import * from .AST.error import * import sys sys.path.append("../") from console import * def executeSentence2(self, sentence): if isinstance(sentence, CreateDatabase): h=0 elif isinstance(sentence, ShowDatabases): h=0 e...
2,198
704
# Copyright 2017-present Open Networking Foundation # # 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,592
1,600
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author: x.huang # @date:17-8-4 import logging from pony.orm import db_session from handlers.base.base import BaseRequestHandler class LoginRequireError(Exception): pass class AuthBaseHandler(BaseRequestHandler): """ 登录验证的基类 """ def prepare(self): ...
2,575
695
# -*- coding: utf-8 -*- #| This file is part of cony #| #| @package Pysol python cli application #| @author <lotfio lakehal> #| @license MIT #| @version 0.1.0 #| @copyright 2019 lotfio lakehal import sys # load module function # this function loads a module by string name def load_module(module): ...
475
162
import torch import torch.nn as nn import torch.nn.functional as F import pytest from . import autograd_hacks class StriddenNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 20, 5, stride=2, padding=2) self.conv2 = nn.Conv2d(20, 30, 5, stride=2, padding=2) ...
6,387
2,647
import unittest import mailpile from mock import patch from mailpile.commands import Action as action from tests import MailPileUnittest class TestCommands(MailPileUnittest): def test_index(self): res = self.mp.rescan() self.assertEqual(res.as_dict()["status"], 'success') def test_search(sel...
5,213
1,809
from gym import spaces import numpy as np from scipy import interpolate import yaml from navrep.envs.navreptrainenv import NavRepTrainEnv from navrep.rosnav_models.utils.reward import RewardCalculator from navrep.rosnav_models.utils.reward import RewardCalculator class RosnavTrainEncodedEnv(NavRepTrainEnv): """ ...
7,739
2,566
from __future__ import annotations import sys from functools import wraps from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple from pdm._types import CandidateInfo, Source from pdm.context import context from pdm.exceptions import CandidateInfoNotFound, CorruptedCacheError from pdm.models...
9,789
2,636
import pytest from starsessions import SessionBackend @pytest.mark.asyncio async def test_cookie_read_write(cookie: SessionBackend, session_payload: dict) -> None: new_id = await cookie.write(session_payload, "session_id") assert await cookie.read(new_id) == session_payload @pytest.mark.asyncio async def t...
713
230
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from pyarrow import flight from sqlalchemy_dremio.exceptions import Error, NotSupportedError from sqlalchemy_dremio.flight_auth import HttpDremioClientAu...
4,888
1,391
#!/opt/rasa/anaconda/bin/python # -*-: coding utf-8 -*- """ Snips core and nlu server. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import time import os from socket import error as socket_error fr...
2,081
693
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-08-02 17:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gtd', '0017_auto_20180108_1508'), ] operations = [ migrations.AddField( ...
462
170
from abc import ABCMeta, abstractmethod import random import json import pickle import numpy as np import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import nltk from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from tensorflow....
6,652
2,138
import discord from discord.ext import commands client = commands.Bot(command_prefix='your prefix',owner_ids = {your user id},case_insensitive=True ) class TieThePie(commands.Cog): def __init__(self,client): self.client=client @commands.command() async def tiethepie(self,ctx): embed=discord.Embed(title...
607
237
""" @brief Generate Fe55 images and associated darks and bias images according to section 5.4 of the E/O document (Dec 19, 2012 version). @author J. Chiang <jchiang@slac.stanford.edu> """ import os import numpy as np from sim_inputs import * from sim_tools import * def generate_Fe55_images(exptimes, nxrays, outdir, ...
3,359
1,268
import math import numpy as np import torch import torch.nn as nn from ....ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules from ....ops.pointnet2.pointnet2_stack import pointnet2_utils as pointnet2_stack_utils from ....utils import common_utils from ...backbones_2d.transformer import ...
32,663
11,543
import os def display_on_editor(text): with open('.metabot2txt', 'w') as f: f.write(text) os.system('gedit .metabot2txt') def display_list_on_editor(texts): if os.path.isfile('.metabot2txt'): os.remove('.metabot2txt') for text in texts: with open('.metabot2txt', 'a') as ...
451
162
#PRIMARY IMPORTS import discord, os, datetime, sys, json, traceback, logging #SECONDARY IMPORTS from apscheduler.schedulers.asyncio import AsyncIOScheduler from discord.ext import commands from data import config #LOGGING logger = logging.getLogger("ivry") logger.debug("errors.py Started") class Er...
47,394
13,577
## Problem 5: Extracting Data from JSON # Example: http://py4e-data.dr-chuck.net/comments_42.json # data consists of a number of names and comment counts in JSON # { # comments: [ # { # name: "Matthias" # count: 97 # }, # { # name: "Geomer" # count: 97 # } # ... # ] # } ...
1,315
426
from ariadne import make_executable_schema, load_schema_from_path from ariadne.asgi import GraphQL from resolvers import query, skill, person, eye_color, mutation # import schema from GraphQL file type_defs = load_schema_from_path("./schema.gql") schema = make_executable_schema( type_defs, query, skill, person, ...
376
125
import importlib import time from pathlib import Path import os import sys def import_plugins(): #find actual path realpath = os.path.realpath(__file__) dirname = os.path.dirname(realpath) #add modules & plugins plugin_path = os.path.join(dirname, "plugins") for dir_path in Path(plugin_path)....
1,127
362
""" Functions support other modules. """ import uuid def check_response(response, key=None): """CHeck the api response. Make sure the status call is successful and the response have specific key. Return: class: `Response <Response>` """ code = response.status_code if not 200 <= code ...
1,208
350
import numpy as np def filter_data(data, use_most_common): _, nc = data.shape for c in range(nc): nr, _ = data.shape if nr <= 1: break col_score = sum(data[:,c])/nr if use_most_common: keep_val = col_score >= 0.5 else: keep_va...
1,064
414
import tensorflow as tf import numpy as np with tf.variable_scope("student"): input_label = tf.placeholder(dtype=tf.float32, shape=[10, 10], name="label") input_image = tf.placeholder(dtype=tf.float32, shape=[10, 224, 224, 3], name="input") conv1 = tf.layers.conv2d(inputs=input_image, filters=64, kernel_s...
1,096
443
import scipy.stats import numpy as np def f_test(sample_x, sample_y, larger_varx_alt): """ Computes the F-value and corresponding p-value for a pair of samples and alternative hypothesis. Parameters ---------- sample_x : list A random sample x1,...,xnx. Let its (underlying) variance be ox...
5,365
1,907
import os, subprocess def compile_core(comp, scilib): """ ATTENTION, NOT FINISHED """ subprocess.call(("make pawpy_%s"%comp).split()) def compile_core(comp, scilib): """ ATTENTION, NOT FINISHED """ subprocess.call("make hfc".split())
243
106
""" Example usage of Finnhub socket API. """ from __future__ import print_function # Py2 compat import websocket from finnhub_python.utils import get_finnhub_api_key def write_line(data, fname): with open(fname, 'a+') as f: f.write(data + '\n') def on_message(ws, message): write_line(message, tick_...
1,125
417
""" Pycovjson - Command line interface Author: rileywilliams Version: 0.1.0 """ import argparse from pycovjson.write import Writer from pycovjson.read_netcdf import NetCDFReader as Reader def main(): """ Command line interface for pycovjson - Converts Scientific Data Formats into CovJSON and saves to disk. ...
2,570
766