text
string
size
int64
token_count
int64
#!/usr/bin/env python import cv2 import numpy as np import os import glob import itertools import json from numpy.core.fromnumeric import argmax #SECTION 1: UNDISTORT FISHEYE #Read in OpenCV compatible instrinsics & distortion coeffs COLOR_INTRINSIC = np.load('./savedCoeff/colorIntr.npy') COLOR_DIST = np.load('./sav...
1,130
484
import pytest from hypothesis import given from hypothesis.strategies import data from numpy import array, array_equal from tests.strategies import indices, tensor_data from tinytorch.tensor.data import ( IndexingError, TensorData, broadcast_index, shape_broadcast, ) # Check basic properties of layout...
5,617
2,157
from django.apps import AppConfig from terra_accounts.permissions_mixins import PermissionRegistrationMixin class TerraLayerConfig(PermissionRegistrationMixin, AppConfig): name = "terra_layer" permissions = ( ("DataLayer", "can_manage_layers", "Can manage layers"), ("DataSource", "can_manage_...
359
103
#!/usr/bin/env python # Copyright 2021 Jian Wu # License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) from typing import List, Union from aps.tokenizer.base import TokenizerAbc, ApsTokenizer class WordBasedTokenizer(TokenizerAbc): """ Word based (word, character) tokenizer Args: filt...
2,813
811
import os from unittest import mock import pytest import requests from constants import VALID_KEY from utils import FunctionCalledException, function_called_raiser from astrometry_net_client import Session from astrometry_net_client.exceptions import APIKeyError, LoginFailedException some_key = "somekey" # Start o...
1,736
541
import ast import os.path from typing import Iterable from packaging.requirements import InvalidRequirement from packaging.requirements import Requirement from packaging.utils import canonicalize_name from all_repos_depends.errors import DependsError from all_repos_depends.types import Depends NAME = 'python' def ...
2,184
675
from os import listdir from os.path import isfile, join class Command(object): """ Run a command and capture it's output string, error string and exit status Source: http://stackoverflow.com/a/13848259/354247 """ def __init__(self, command): self.command = command def run(self, shell=Tr...
2,829
948
"""StdoutItem class""" from dataclasses import asdict, dataclass from .hark_serialisable import HarkSerialisable, now_str @dataclass class StdoutItem(HarkSerialisable): thread: int text: str time: str = None def __post_init__(self): if self.time is None: self.time = now_str()
317
106
# coding: utf-8 class LZW(object): """ Implementation of the LZW algorithm. Attributes ---------- translation_dict : dict Association between repeated bytes sequences and integers. Examples -------- An array of bytes like ['\x41', '\x42', '\x43', '\x0A', '\x00'] can be represente...
6,911
1,989
""" Contains database models """ from sqlalchemy import Column, ForeignKey, Integer, String, Float from sqlalchemy.orm import relationship from .database import Base class TouristAttraction(Base): __tablename__ = "tourist_attraction" id = Column(Integer, primary_key=True, index=True) name = Column(String...
1,322
420
def rwh_primes2(n): correction = (n%6>1) n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6] sieve = [True] * (n//3) sieve[0] = False for i in range(int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)//3) ::2*k]=[False]*((n//6-(k*k)//6-1)//k+1) sieve[(...
1,096
575
import numpy as np import matplotlib.pyplot as plt import copy k = 4 ratio=0.95 def competitive_k_means(save_plot=False): plt.figure(figsize=(12, 12)) X, y =generate_dataset() plt.scatter(X[:,0],X[:,1],c=y,marker='+') plt.title("results from the data") if save_plot: plt.savefig("data.png") ...
2,649
982
""" Defines a Redshift class which encapsulates a database connection and utility functions for managing that database. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import os import psycopg2 from shiftmanager.mixins import AdminMixin, ReflectionMix...
3,031
842
#Python 3.4.3 #coding=gbk # copy file wangyuxia 20160920 import sys, shutil, os, string path = "E:\\test for qgis\\" target_path = "E:\\test for qgis\\HourScale\\" for i in range(2,31): for j in range(0,24): filename = 'N'+str(i).zfill(2)+str(j).zfill(2) shutil.copyfile(path+'d_02.hdr',target_pat...
387
167
import sys from scipy.special import softmax import torch.onnx import onnxruntime as ort import numpy as np import tensorflow as tf from tensorflow.keras import backend as K from pytorch2keras.converter import pytorch_to_keras from models.faceboxes import FaceBoxes input_dim = 1024 num_classes = 2 model_path = "weig...
3,581
1,321
from setuptools import setup setup(name='pysteamcmd', version='0.1.2', description='Python package to install and utilize steamcmd', url='http://github.com/f0rkz/pysteamcmd', author='f0rkz', author_email='f0rkz@f0rkznet.net', license='MIT', packages=['pysteamcmd'], insta...
358
131
# Copyright (c) 2017, 2018 Jae-jun Kang # See the file LICENSE for details. from x2py.event_factory import EventFactory from x2py.links.link_events import * from x2py.links.strategy import ChannelStrategy from x2py.util.trace import Trace class BufferTransformStrategy(ChannelStrategy): EventFactory.register_type(...
3,292
891
import os import sys import json import time import tqdm import socket import subprocess import numpy as np import visdom from typing import Tuple from typing import Optional def calc_ytick_range(vis: visdom.Visdom, window_name: str, env: Optional[str] = None) -> Tuple[float, float]: lower_bound, upper_bound = ...
5,632
1,927
import os import time from sqlalchemy import create_engine, BigInteger, UnicodeText, Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.exc import SQLAlchemyError from aiogram import Bot, Dispatcher, executor, types from aiogr...
4,960
1,448
import numpy as np import cvnn.layers as complex_layers import tensorflow as tf from pdb import set_trace def get_dataset(): (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.cifar10.load_data() train_images = train_images.astype(dtype=np.complex64) / 255.0 test_images = test_im...
2,912
1,086
"""Write a subset of keys from one CSV to another. Don't use lots of memory. Usage: %s <filename> <outputfile> [--columns=<columns>] [--htm] [--racol=<racol>] [--deccol=<deccol>] [--filtercol=<filtercol>] %s (-h | --help) %s --version Options: -h --help Show this screen. --version ...
2,580
811
""" A binary tree is univalued if every node in the tree has the same value. Return true if and only if the given tree is univalued.   Example 1: Input: [1,1,1,1,1,null,1] Output: true Example 2: Input: [2,2,2,5,2] Output: false   Note: The number of nodes in the given tree will be in the range [1, 100]...
1,030
342
def guide(): print("If you want to be informed about how to charge the electric vehicle, please enter Y.") answer = input() if answer == "Y": print("1.Stop in front of the charger\n" "2.Check the charging connector for my car\n" "3.Connect to the vehicle\n" "4.Set charge amount\n" ...
495
133
#!/usr/bin/env python """ _GetParentStatus_ MySQL implementation of DBSBufferFile.GetParentStatus """ from WMCore.Database.DBFormatter import DBFormatter class GetParentStatus(DBFormatter): sql = """SELECT status FROM dbsbuffer_file INNER JOIN dbsbuffer_file_parent ON dbsbuffer...
1,006
279
import os from time import sleep import requests querysub0 = 'https://linkeddata1.calcul.u-psud.fr/sparql?default-graph-uri=&query=construct%7B+%3Fs+%3Fp+%3Fo%7D+where+%7B+%0D%0Aselect+distinct+%3Fs+%3Fp+%3Fo+where+%7B%0D%0A%7B%0D%0A%3Fs1+++%3Chttp%3A%2F%2Fyago-knowledge.org%2Fresource%2FactedIn%3E+++%3Fs+.%0D%0A%3Fs2...
1,672
866
''' Created on Apr 12, 2011 @author: svenkratz ''' import TestGestures import Protractor3D.Protractor3D from Protractor3D.Protractor3D import * def triplify(g): out = [] if len(g) % 3 != 0: print "Warning: Data not divisible by 3" for k in xrange(len(g)/3): out = out + [[g[3*k], g[3*k+1], g[3*k+2]]] return...
1,418
562
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: José Sánchez-Gallego (gallegoj@uw.edu) # @Date: 2021-03-24 # @Filename: test_hal.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) import pytest from hal import __version__ pytestmark = [pytest.mark.asyncio] async def test_vers...
481
198
import numpy as np def crab_fuel(n): return (n**2 + n) // 2 if __name__ == '__main__': with open('input.txt') as f: pin = np.array([int(x) for x in f.read().split(',')]) distances = np.abs(pin[None, :] - np.arange(pin.max() + 1)[:, None]) total_fuel = np.sum(distances, axis=1) print(f'S...
490
214
# Generated by Django 2.2.10 on 2020-05-18 10:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('events', '0008_alter_field_classification_on_event'), ('core', '0032_delete_instance'), ] operations = [ migrations.DeleteModel( ...
352
126
#!/usr/bin/env python # -*- coding: utf-8 -*- # Python version: 3.6 import numpy as np from torchvision import datasets, transforms import logging import random import torch # Settings for a multiplicative linear congruential generator (aka Lehmer # generator) suggested in 'Random Number Generators: Good # Ones ...
16,114
6,049
#! /usr/bin/python3 # Author: gaurav512 ''' Script written to scrape basic information about a Codeforces profile given the user id Usage: Enter the userid as command line argument OR as the input after running the following in terminal- python3 codeforces.py [userid] ''' import requests, bs4, sys def getDetails(u...
2,502
939
#!/usr/bin/env python # -*- coding: utf-8 -*- # # test_combinator.py # # Copyright 2020 QuatroPe # # This file is part of ProperImage (https://github.com/quatrope/ProperImage) # License: BSD-3-Clause # Full Text: https://github.com/quatrope/ProperImage/blob/master/LICENSE.txt # """ test_combinator module from Proper...
566
224
def cal_A_B(pdo=20, base_score=500, odds=1 / 50): B = pdo / np.log(2) A = base_score + B * np.log(odds) return A, B ''' parameter --------- df:变量的woe,要求与模型训练logit时的列顺序一样 logit:sklearn中的逻辑回归模型,带截距 return ------ 新增每行数据的评分列:Score example: df= cal_score(df,logit) ''' def cal_score_byadd(df, log...
1,025
509
#! /usr/bin/env python3 """ Runs process_logdata_ekf.py on the .ulg files in the supplied directory. ulog files are skipped from the analysis, if a corresponding .pdf file already exists (unless the overwrite flag was set). """ # -*- coding: utf-8 -*- import argparse import os, glob from process_logdata_ekf import p...
3,790
1,167
import inspect import warnings from pathlib import Path def send_model_code(model, model_config, logdir, NEPTUNE_ON=False, exp=None): model_init = None model_forward = None model_config_s = None try: model_init = inspect.getsource(model.__init__) except Exception as e: warnings.war...
1,468
486
def foo() -> object: @decorator def bar(): pass
63
20
# Python import logging from os import path # Abstract from genie.abstract import Lookup # Parser from genie.libs import parser from genie.metaparser.util.exceptions import SchemaEmptyParserError # unicon from unicon.eal.dialogs import Statement, Dialog log = logging.getLogger(__name__) def save_device_informatio...
3,099
873
import matplotlib.pyplot as plt import numpy as np from labellines import labelLines # # Trying to get interpolation to work but getting error: # # ValueError: The number of derivatives at boundaries does not match: expected 1, got 0+0 # from scipy.interpolate import make_interp_spline, BSpline # n_users = np.array([1...
2,933
1,381
# import the necessary packages import argparse import cv2 import numpy as np from polydomino.colordescriptor import ColorDescriptor from polydomino.searcher import Searcher # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument( "-i", "--index", required=T...
2,000
659
import click from irekua_dev_tools.utils import load_config from irekua_dev_tools.utils import get_working_directory from irekua_dev_tools.utils import load_environment_variables from irekua_dev_tools.utils import load_repository_info from . import git from . import dev from . import config from . import db from .ex...
1,253
403
from optimism.JaxConfig import * from optimism import MinimizeScalar from optimism.test import TestFixture from optimism.material import J2Plastic def f(x): return 0.25*x**4 - 50.0*x**2 + 2.0 df = jacfwd(f) class TestMinimizeScalarFixture(TestFixture.TestFixture): def setUp(self): self.minimize_scalar_j...
2,880
1,067
# -*- coding: utf-8 -*- """ import datetime from anima import defaults defaults.timing_resolution = datetime.timedelta(minutes=10) from anima.ui import SET_PYSIDE2 SET_PYSIDE2() from anima.ui.widgets.review import APPROVE, REQUEST_REVISION from anima.ui import review_dialog review_dialog.UI(review_type=REQUEST_REVIS...
2,709
811
import math import re from itertools import permutations from logging import getLogger from typing import Tuple, Union from rpy2 import robjects from rpy2.rinterface_lib.embedded import RRuntimeError from z3 import BitVecVal from .. import util, results from ..decider import RowNumberInfo from ..program import LineIn...
12,737
4,108
# -*- coding: utf-8 -*- """ ------ What is this file? ------ This script targets the istanbul_airbnb_raw.csv file. It cleans the .csv file in order to prepare it for further analysis """ #%% --- Import Required Packages --- import os import pathlib from pathlib import Path # To wrap around filepaths impor...
7,869
2,696
import time import select import queue import atexit import sys import logging from networkdevice import ShureNetworkDevice from channel import chart_update_list, data_update_list # from mic import WirelessMic # from iem import IEM NetworkDevices = [] DeviceMessageQueue = queue.Queue() def get_network_device_by_ip(...
3,695
1,266
import enum class Status(enum.Enum): QUEUED = 'queued' STARTED = 'started' FINISHED = 'finished' ERROR = 'error' def __str__(self): return self.value QUEUED = Status.QUEUED STARTED = Status.STARTED FINISHED = Status.FINISHED ERROR = Status.ERROR
277
107
"""Simulation 1:1:1 comptition binding""" import numpy as np from high_accuracy_binding_equations import * # We can choose to work in a common unit, typically nM, or uM, as long as all # numbers are in the same unit, the result is valid. We assume uM for all # concentrations bellow. # First, lets simulate a few sin...
977
327
import numpy as np from pathlib import Path import sys if __name__ == '__main__': # absolute path my_path = Path(__file__).parent.resolve().expanduser() main_path = my_path.parent.parent seed = 0 nlat = 10 alpha = 1.0 beta = 6.0 gamma = 1.0 epochs = 100 # cmd...
773
338
########################################################################## # # Unit tests (pytest) for load.py # ########################################################################## # SimFin - Simple financial data for Python. # www.simfin.com - www.github.com/simfin/simfin # See README.md for instructions and LI...
3,331
974
import sys from plum import Dispatcher B = sys.modules[__name__] # Allow both import styles. dispatch = Dispatcher() # This dispatch namespace will be used everywhere. from .generic import * from .shaping import * from .linear_algebra import * from .random import * from .numpy import * from .types import * from ...
447
139
# coding: utf-8 from nbgrader.api import Gradebook from nbgrader.apps import ExportApp as BaseExportApp from traitlets import Instance from traitlets import Type from traitlets import default from ..plugins import CanvasCsvExportPlugin from ..plugins import CustomExportPlugin aliases = { "log-level": "Applicatio...
1,514
466
""" django_ocr_server/conf.py +++++++++++++++++++++++++ The settings manager for **django_ocr_server**. Usage: .. code-block:: python from django_ocr_server.conf import ocr_settings # Next line will print a value of **OCR_TESSERACT_LANG** # using the variable from the Django's *settings.py* file # if the variab...
2,810
1,125
from django.apps import AppConfig class SFMConfig(AppConfig): name = 'sfm' verbose_name = 'SFM'
105
37
import math import numpy as np from openeye import oechem from torsion.inchi_keys import get_torsion_oeatom_list, get_torsion_oebond def GetPairwiseDistanceMatrix(icoords, jcoords): ''' input: two sets of coordinates, icoords, jcoords; each of which are a list of OEDoubleArray(3) containing x, y, a...
15,960
5,628
""" 候选生成(Candidate generation) & 排序(LTR, Learning to Ranking)""" # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import argparse from operator import itemgetter from math import sqrt import pandas as pd import py...
6,785
2,257
from datetime import timedelta from airflow import DAG from airflow.utils.dates import days_ago from airflow.operators.python_operator import PythonOperator from tweetstream.consumers.twitter_streaming import TwitterStreamingConsumer from tweetstream.clients.spark import SparkClient default_args = { "owner": "twee...
1,592
563
from polyphony import testbench def expr09(a, b): return a ^ b @testbench def test(): assert 1 == expr09(0b1000, 0b1001) assert 3 == expr09(0b1000, 0b1011) assert 1 == expr09(0b1010, 0b1011) test()
217
115
#!/usr/bin/python from setuptools import setup, find_packages from codecs import open with open('README.rst', 'r', 'utf-8') as fd: long_description = fd.read() setup(name='ipynb_format', version='0.1.1', description='A code formatter for python code in ipython notebooks', long_description=long_...
1,059
321
# -*- coding: utf-8 -*- feet = eval(input("Enter a value for feet: ")) meter = feet * 0.305 print (feet, "feet is %.4f meters" %(meter))
140
63
from mxnet import gluon from mxnet.gluon import HybridBlock from ceecnet.nn.layers.conv2Dnormed import * from ceecnet.utils.get_norm import * from ceecnet.nn.layers.attention import * class ResizeLayer(HybridBlock): """ Applies bilinear up/down sampling in spatial dims and changes number of filters as well ...
16,072
5,935
from django.db.models import Q from haystack import indexes from reviewboard.reviews.models import ReviewRequest class ReviewRequestIndex(indexes.SearchIndex, indexes.Indexable): """A Haystack search index for Review Requests.""" # By Haystack convention, the full-text template is automatically # referen...
1,928
529
from .statement import Statement, StatementType from .event import Event from ._helpers import debugmsg, simulation_error class TransactionGenerator: def __init__(self, simulation, block_num, operands): self.simulation = simulation self.block = self.simulation.program[block_num] self.start_...
7,365
1,859
REDIS_URL = "redis://redis:6379/0" DEBUG = True TESTING = False JOBS = [ { 'id': 'actoken_refresh', 'func': 'actoken:refresh', 'args': None, 'trigger': 'interval', 'seconds': 7000 } ]
234
94
from shutil import copy, copytree, rmtree import pathlib import os import time def update(): """Update is a script to auto update all the files that the user is using""" print('Warehouse Hub is updating, do not close this window...') time.sleep(3) print('Applying patch...') time.sleep(1) c...
727
241
import functools import tensorflow as tf from core import trainer_video, input_reader from core.model_builder import build_man_model from google.protobuf import text_format from object_detection.builders import input_reader_builder from object_detection.protos import input_reader_pb2 from object_detection.protos import...
3,134
1,039
# -*- coding: utf-8 -*- class Config(object): # [Network] n_embed = 100 n_tag_embed = 100 embed_dropout = 0.33 n_lstm_hidden = 400 n_lstm_layers = 3 lstm_dropout = 0.33 n_mlp_arc = 500 n_mlp_rel = 100 mlp_dropout = 0.33 # [Optimizer] lr = 2e-3 beta_1 = 0.9 bet...
460
243
# -*- coding: utf-8 -*- """ Created on Sat Mar 17 23:01:40 2018 @author: pc """ import scholarly,re,urllib.request,nltk import bs4 as bs # ============================================================================= # #Probléme les derniere conf ne se rajoute pas # =======================================...
3,301
1,214
#!/usr/bin/env python3 """ Main code for Robot """ import wpilib import robotmap from wpilib import Joystick from subsystems.drivetrain import DriveTrain as Drive from subsystems.grabber import cubeGrabber from subsystems.elevator import Elevator from subsystems.climber import Climber from subsystems.autonomous import...
4,540
1,480
#!/usr/bin/env python3 """ ATTOM API https://api.developer.attomdata.com """ import requests from urllib.parse import quote, urlencode from api import api PATH = "attomavm/detail" def get_avm_by_address(number_street, city_state): """ API request to get attomavm/detail """ params = urlencode( { "add...
1,764
711
import django from django.db import models from django.db.models.base import ModelBase from django.utils import six from .manager import IdMapManager from . import tls # thread local storage META_VALUES = { 'use_strong_refs': False, 'multi_db': False } class IdMapModelBase(ModelBase): def __new__(mc...
7,064
1,941
from unittest import TestCase from search_in_rotated_sorted_array import Solution class TestSearchInRotatedSortedArray(TestCase): def test_0_when_first_element_is_target(self): self.assertEqual(Solution().search([1, 2, 3, 4, 5, 6, 7], 1), 0) def test_end_index_last_element_is_target(self): s...
1,345
550
#!/usr/bin/env python # -*- coding: utf-8 -*- # 3rd party imports import numpy as np import xarray as xr __author__ = "Louis Richard" __email__ = "louisr@irfu.se" __copyright__ = "Copyright 2020-2021" __license__ = "MIT" __version__ = "2.3.7" __status__ = "Prototype" def ts_skymap(time, data, energy, phi, theta, **...
2,501
847
''' Author: Alex Wong <alexw@cs.ucla.edu> If you use this code, please cite the following paper: A. Wong, and S. Soatto. Unsupervised Depth Completion with Calibrated Backprojection Layers. https://arxiv.org/pdf/2108.10531.pdf @inproceedings{wong2021unsupervised, title={Unsupervised Depth Completion with Calibrate...
2,037
729
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: a = self.get_num(l1) b = self.get_num(...
788
256
import time import re import tweepy import preprocessor as p import config import string consumer_key = config.consumer_key consumer_secret = config.consumer_secret access_token = config.access_token access_token_secret = config.access_token_secret bearer_token = config.bearer_token username = config.username password...
2,834
1,019
# Generated by Django 2.0.3 on 2018-03-14 09:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0003_delegate_public_key'), ] operations = [ migrations.AddField( model_name='history', name='missed', ...
391
133
import tensorflow as tf import numpy as np from tensorflow.python.ops.gen_batch_ops import batch from model import AudioClass from qrnn import QRNN from numpy.random import seed from numpy.random import randn from random import randint from lstmfcn import LSTM_FCN import librosa import os def getData(): outX = [] ...
2,112
780
from pytanga.components import AbstractComponent class ospfv2InterfaceComponent(AbstractComponent): def __init__( self, if_id, network_type=None, priority=None, multi_area_adjacency_primary=None, authentication_type=None, metric=...
3,135
776
import math from typing import List, Tuple def __cria_matriz_quadrada(tamanho: int = 20) -> List[List[str]]: matriz = [] for _ in range(tamanho): linha = ['0' for _ in range(tamanho)] matriz.append(linha) return matriz def __diagonais(matriz: List[List[str]]) -> Tuple[list, list]: t...
4,127
1,503
from pymongo import MongoClient import pymongo from datetime import datetime,time import time from bson.code import Code mongo_client=MongoClient('mongodb://localhost:27017/') db=mongo_client.mydb db_col=db.things dbc = mongo_client.mydb.things print mongo_client print(db) print("connected") def first_querry(): ...
7,017
2,537
#!/usr/bin/env python # -*- coding: utf-8 -*- """ serialize provide means to persist and recreate the currently known set of W_Tags and all shapes and transformations reachable from there. The rmarshal modules is used for serialization; the format is marshal_proto = ( int, # number of shapes [ # shape list ...
7,399
2,382
from web3 import Web3, HTTPProvider import json import os w3 = Web3(HTTPProvider("http://127.0.0.1:7545", request_kwargs={'timeout': 60})) print(f"Web3 is connected : {w3.isConnected()}") accounts = w3.eth.accounts # ------------------------------- get contract ------------------------------- ...
1,359
506
from preprocessing import preprocess from approach1_rulebased import get_predictions_rulebased from approach2_machine_learning import get_predictions_ml from bertopic_clustering import cluster_precursors def main(): '''Main function to use from commandline, preprocess input to generate embeddings, detect agr...
825
218
from tkinter import * import threading import sql_manager as ss def temp(er,s): er.destroy() s.sperson() def temp2(er,s): er.destroy() s.w.destroy() def close_w(self): self.w.destroy() class GUI: def __init__(self): self.w=Tk() p1 = PhotoImage(fi...
8,985
3,403
import sys OPERATIONS = { 'addr': lambda a, b, c, registers: registers[a] + registers[b], 'addi': lambda a, b, c, registers: registers[a] + b, 'mulr': lambda a, b, c, registers: registers[a] * registers[b], 'muli': lambda a, b, c, registers: registers[a] * b, 'banr': lambda a, b, c, registers: registers[a] ...
1,528
590
from aiohttp import web from agents import Agent class WebServer(Agent): html = """ <!DOCTYPE html> <html> <head> <title>WebSocket Echo</title> </head> <body> <h1>WebSocket Echo</h1> <form action="" onsubmit="sendMessage(event)"> ...
1,878
516
from wazimap.data.tables import FieldTable # Define our tables so the data API can discover them. # Household tables FieldTable(['rural population'], universe='Population', table_per_level=False) FieldTable(['area', 'sex'], universe='Population', table_per_level=False) FieldTable(['census_year', 'measure'], universe...
5,401
1,791
import os import asyncio import logging from pony.orm import * import logger from database import start_orm, get_biggest_virgin, Guild, Virgin logger = logging.getLogger('virginity-bot') async def reset_weekly_virginity(): with db_session: virgins = Virgin.select() for virgin in virgins: virgin.tot...
585
206
import os import shutil from .base import GnuRecipe class RacketRecipe(GnuRecipe): def __init__(self, *args, **kwargs): super(RacketRecipe, self).__init__(*args, **kwargs) self.sha256 = 'bf2bce50b02c626666a8d2093638893e' \ '8beb8b2a19cdd43efa151a686c88edcf' self.depe...
1,165
431
import os import sys import berserk from github import Github, InputFileContent, Gist SEPARATOR = "." PADDING = {"puzzle": 0, "crazyhouse": 0, "chess960": 0, "kingOfTheHill": 0, "threeCheck": 2, "antichess": 0, "atomic": 0, "horde": 0, "racingKings": 0, "ultraBullet": 0, "blitz": 1, "classical"...
3,257
1,343
"""empty message Revision ID: 60c735df8d2f Revises: 88bb7e12da60 Create Date: 2019-09-06 08:27:03.082097 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "60c735df8d2f" down_revision = "88bb7e12da60" branch_labels = None depends_on = None def upgrade(): # ...
951
373
import scipy.io.wavfile as wav import numpy as np import os import pickle import random import operator from python_speech_features import mfcc dataset = [] training_set = [] test_set = [] # Get the distance between feature vectors def distance(instance1, instance2, k): mm1 = instance1[0] cm1 = instance1[1] ...
3,640
1,219
import argparse from libs.data_model import AnchorNorthstarDataframe, SalesForceDataframe, \ AnchorSalesforceAccountsDataframe, AnchorSalesforceContactsDataframe from libs.utils import save_dataframes_to_excel parser = argparse.ArgumentParser(description='Reconcile accounts and contacts between Anchor and Salesfo...
1,653
493
def bill(): print("I am bill, please input your name") name = str(raw_input()) print("Hi %s" % name) print("Now input a command") a = raw_input("Command line:") a = a.lower() if a == "": print("You inputed nothing") bill() if a == "help": print("The commands in m...
1,650
503
test = { 'name': 'q3b1', 'points': 2, 'suites': [ { 'cases': [ { 'code': '>>> 4 <= ' "sum(list(X1.describe().loc['mean'])) " '<= 9\n' 'True', ...
757
189
"""Scanpy's high-level API provides an overview of all features relevant to pratical use:: import scanpy.api as sc .. raw:: html <h3>Preprocessing tools</h3> Filtering of highly-variable genes, batch-effect correction, per-cell (UMI) normalization, preprocessing recipes. .. raw:: html <h4>Basic Preproc...
3,050
1,218
import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from .modeling_albert import AlbertPreTrainedModel, AlbertLayerNorm, AlbertLayerGroup from .modeling_bert import BertEmbeddings from .modeling_highway_bert import BertPooler import numpy as np def entropy(x): # x: torch.Tensor, logi...
34,894
10,133
# Copyright 2020 Kapil Thangavelu # # 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,...
1,809
569
import json import os import sys sys.path.append('/usr/lib/python2.7/dist-packages') import cv2 import numpy as np from tqdm import * import dataset_utils class Rovina(object): def __init__(self, config_filename): self.config_filename = config_filename with open(config_filename) as config_fil...
5,773
1,819
import numpy as np from scipy.constants import mu_0, epsilon_0 import matplotlib.pyplot as plt from PIL import Image import warnings warnings.filterwarnings('ignore') from ipywidgets import interact, interactive, IntSlider, widget, FloatText, FloatSlider, fixed from .Wiggle import wiggle, PrimaryWave, ReflectedWave i...
4,952
2,199