text
string
size
int64
token_count
int64
import collections from typing import Optional import numpy as np from astromodels import Parameter, Model from astromodels.functions.priors import Cosine_Prior, Uniform_prior from threeML import PluginPrototype from threeML.io.file_utils import sanitize_filename from threeML.plugins.DispersionSpectrumLike import Dis...
9,501
2,663
import matplotlib.pyplot as plt def _determine_vmax(max_data_value): vmax = 1 if max_data_value > 255: vmax = None elif max_data_value > 1: vmax = 255 return vmax def plot_image(heatmap, original_data=None, heatmap_cmap=None, data_cmap=None, show_plot=True, output_filename=None): # ...
1,881
588
import torch import common.torch from .classifier import Classifier from .utils import get_normalization2d, get_activation class LeNet(Classifier): """ LeNet classifier. """ def __init__(self, N_class, resolution=(1, 32, 32), channels=64, activation='relu', normalization='bn', linear=1024, dropout=Fa...
4,680
1,438
""" All Available Module on Server Belong to Here """ AVAILABLE_MODULES = ( "api", ) def init_app(app, **kwargs): from importlib import import_module for module in AVAILABLE_MODULES: import_module( f".{module}", package=__name__ ).init_app(app, **kwargs)
309
99
""" Slixmpp: The Slick XMPP Library Copyright (C) 2016 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr> This file is part of Slixmpp. See the file LICENSE for copying permission. """ import logging import slixmpp from slixmpp.stanza import Message from slixmpp.xmlstream.handler import Callback from slixm...
2,154
736
#!/usr/bin/python #Quam Sodji 2015 #Setup script to install the needed python modules #Installs kn/Slack and python-jss modules #We assume you have Git installed....... import subprocess import os import sys import shutil clone_jss = subprocess.check_output(['git','clone','git://github.com/sheagcraig/python-jss.git'])...
1,050
359
""" Linear State Space Element Class """ class Element(object): """ State space member """ def __init__(self): self.sys_id = str() # A string with the name of the element self.sys = None # The actual object self.ss = None # The state space object self.settings = ...
969
270
# Copyright 2017 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
4,819
1,289
# -*- coding: utf-8 -*- ''' Created on Oct 27, 2015 @author: nlp ''' import numpy as np import math # nmf 聚类主体 def nmf(file_list, k): X = np.array(file_list).transpose() m_x, n_x = X.shape # 随机生成初始矩阵 U = np.random.rand(m_x, k) V = np.random.rand(n_x, k) is_convergence = False count =...
3,988
1,654
#!/usr/bin/env python import numpy as np import scipy.linalg as la import matplotlib.pyplot as plt from scipy.sparse.linalg import cgs from scipy.sparse import csr_matrix fig = plt.figure() t_min = 0.0 t_max = 10.0 x_min = -10.0 x_max = 10.0 y_min = -10.0 y_max = 10.0 a = 1.0 c = 5.0 m = 400 n = 100 def ind(i, j):...
3,834
1,743
# -*- coding: utf-8 -*- """ Created on Sun Jan 19 23:19:43 2020 @author: elif.ayvali """ import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict class deep_Q_net(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed): ...
2,667
915
# -*- coding: utf-8 -*- """ Created on Tue Apr 23 18:53:30 2019 @author: zky """ from sys import argv from math import log from scipy import stats input_bin25_file = argv[1] ip_bin25_file = argv[2] input_total_reads_count = int(argv[3]) ip_total_reads_count = int(argv[4]) peak_windows_number = int(argv[5]) output_ip_f...
3,352
1,240
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools.command.test import test as TestCommand try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: h...
2,541
824
import numpy as np import pandas as pd from typing import Tuple, Dict from .load_csv import load_raw_classes, load_raw_epigenomic_data, load_raw_nucleotides_sequences from .store_csv import store_raw_classes, store_raw_epigenomic_data, store_raw_nucleotides_sequences from auto_tqdm import tqdm def drop_unknown_datapoi...
1,895
614
# -*- coding: utf-8 -*- ''' plexOdus Add-on ''' import json from resources.lib.modules import client from resources.lib.modules import control user = control.setting('fanart.tv.user') if user == '' or user is None: user = 'cf0ebcc2f7b824bd04cf3a318f15c17d' headers = {'api-key': '3eb5ed2c401a206391ea8d1a031...
7,857
2,806
""" nuqql conversation helpers """ import datetime import logging from typing import TYPE_CHECKING import nuqql.win from .conversation import CONVERSATIONS from .logmessage import LogMessage if TYPE_CHECKING: # imports for typing # pylint: disable=cyclic-import from nuqql.backend import Backend # noqa ...
3,599
1,226
import vaex import pytest @pytest.mark.skipif(vaex.utils.devmode, reason='runs too slow when developing') def test_gcs(): df = vaex.open('gs://vaex-data/testing/xys.hdf5?cache=false&token=anon') assert df.x.tolist() == [1, 2] assert df.y.tolist() == [3, 4] assert df.s.tolist() == ['5', '6'] df = ...
801
338
"""Constants.""" # A ``None``-ish constant for use where ``None`` may be a valid value. NOT_SET = type('NOT_SET', (), { '__bool__': (lambda self: False), '__str__': (lambda self: 'NOT_SET'), '__repr__': (lambda self: 'NOT_SET'), '__copy__': (lambda self: self), })() # An alias for NOT_SET that may be...
388
138
import socket print("Waiting for connections...") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('', 9090)) sock.listen() n_sock, addr = sock.accept() print("Client connected! Sending HTTP-message") conn.send( b"HTTP/1.0 200 OK\nContent-Type: text/html\n\n" + open("index.html", "rb").read...
340
138
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals, print_function from datetime import datetime import os from os.path import dirname, join import sys import time import unittest import uuid import logging LOGGING_FORMAT = '\n%(levelname)s %(asctime)s %(message)s' logging.basicConfig(lev...
2,998
982
# This file implements functions model_fn, input_fn, predict_fn and output_fn. # Function model_fn is mandatory. The other functions can be omitted so the standard sagemaker function will be used. # An alternative to the last 3 functions is to use function transform_fn(model, data, input_content_type, output_content_ty...
1,227
375
# -*- coding: utf-8 -*- import kicad import model from stackups import JLCPCB6Layers #from dram import lp4 # IMX8MM # Diff pairs should be matched within 1ps # CK_t/CK_c max 200 ps # CA[5:0] # CS[1:0] min: CK_t - 25ps, max: CK_t + 25ps # CKE[1:0] # DQS0_t/DQS0_c min: CK_t - 85ps, max CK_t + 85ps # DQ[7:0]...
802
445
from django.shortcuts import render # Create your views here. def subscribe(request): return render(request, "subscribe.html", {'data': {}})
165
46
#Sean Billings, 2015 import random import numpy import subprocess import constraints from experiment import Experiment from objectiveFunctions import WeightedSumObjectiveFunction, IdealDifferentialObjectiveFunction from waveGuideMPBOptimizer import differentialEvolution, createPopulation, gradientDescentAlgorithm impor...
4,795
1,552
""" cookie_handler.py Copyright 2006 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope t...
2,781
773
import os import urllib.request from zipfile import ZipFile HOME_DIRECTORY = os.path.join('datasets','raw') ROOT_URL = 'https://os.unil.cloud.switch.ch/fma/fma_metadata.zip' if not os.path.isdir(HOME_DIRECTORY): os.makedirs(HOME_DIRECTORY) zip_path = os.path.join(HOME_DIRECTORY, 'data.zip') urllib.request.urlretr...
435
174
from thesis.parsers.classes import Args def split_args(args: Args): dataset_args = args.datatrain training_args = args.training model_args = args.model embedding_args = args.embedds visual_args = args.visual run_args = args.runs log_args = args.logs return dataset_args, training_args...
2,601
956
# Copyright 2019 The TensorFlow Authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
6,625
1,967
import os import logging import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from src.architectures.readout import READOUTS from src.architectures.embedding import EMBEDDINGS from .attention_pooling import POOLING_LAYERS from ..message_passing import MP_LAYERS from .....
3,479
1,095
from slixmpp.xmlstream import register_stanza_plugin from slixmpp.plugins import BasePlugin from slixmpp.plugins.xep_0004 import stanza from slixmpp.plugins.xep_0004.stanza import FormField from slixmpp.plugins.xep_0122.stanza import FormValidation class XEP_0122(BasePlugin): """ XEP-0122: Data Forms """ ...
533
203
#!/usr/bin/env python3 import lib N=1000000 sieve = lib.get_prime_sieve(N) primes = lib.primes(N, sieve) primes = primes[4:] def is_truncatable(n): num = n c = 0 while num: if not sieve[num]: return False num = int(num / 10) c += 1 while c: num = n % 10**c if not sieve[num]: r...
497
217
import click @click.group() def cli(): pass @cli.command("restore_atmo") @click.argument('currentFile') @click.argument('backupFile') @click.argument('newFilePath') def restore_atmo(current_file, backup_file, new_file_path): from Utils.AtmoFileProcessing.RestoreAtmo import create_restored_world_file cre...
708
231
import sys from pathlib import Path from datetime import datetime import argparse import json import torch from torchvision.utils import save_image import torchvision import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.metrics import pairwise_distances_argmin from sklea...
3,610
1,153
from __future__ import annotations import os from typing import TYPE_CHECKING, Final, List from urllib.parse import urldefrag import disnake from disnake.ext import commands, tasks from monty.log import get_logger from monty.utils.helpers import encode_github_link from monty.utils.messages import DeleteButton if T...
6,350
1,771
#!/usr/bin/env python # -*- encoding: utf-8 -*- """Tests for utility classes.""" import datetime import sys import unittest from absl import app from absl.testing import absltest from grr_response_core.lib import rdfvalue from grr.test_lib import test_lib long_string = ( "迎欢迎\n" "Lorem ipsum dolor sit amet...
18,608
7,447
import pytest from server import rest @pytest.fixture def client(): rest.app.testing = True #rest.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///server.MyStudents' client = rest.app.test_client() yield client def test_get(client): res = client.get('/schueler') assert res.status_code ==...
909
344
#combine.py, combines available dictionaries into one, and generates csv file for latex #f = open('dict_random') mem_ops = 'MOVS','MOV','LDR','LDRH','LDRB','LDRSH','LDRSB','LDM','STR','STRH','STRB','STM' ari_ops = 'ADDS','ADD','ADC','ADCS','ADR','SUBS','SUB','SBCS','RSBS','MULS','MUL','RSB','SBC' com_ops = 'CMP','CM...
3,143
1,507
#from src.piclient import PiClient from src.streamclient import StreamClient import math options = { "boarddetector": { "prepare": { "resize": [512, 512] }, "corners": { "maxcorners": 500, "qualitylevel": 0.01, "mindistance": 20 }, ...
4,102
1,345
#!/usr/bin/env python # encoding: utf-8 """ compute_transformation_error.py Created by Maria Isabel Restrepo on 2012-09-24. Copyright (c) 2012 . All rights reserved. This script computes the distances betweeen an estimated similarity transformation and its ground trutrransformation is used to transform a "source" coor...
2,773
1,107
"""Country added Revision ID: be21086640ad Revises: 153f720f966f Create Date: 2021-11-09 15:34:04.306218 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'be21086640ad' down_revision = '153f720f966f' branch_labels = None depends_on = None naming_convention = { ...
16,301
9,442
#!/usr/bin/python # coding=UTF-8 # ex:ts=4:sw=4:et=on # Copyright (c) 2013, Mathijs Dumon # All rights reserved. # Complete license can be found in the LICENSE file. import os from pyxrd.data import settings from pyxrd.project.models import Project from pyxrd.phases.models import Component, Phase def generate_expan...
26,718
10,679
import sys """ Example : Input: 2 (Test cases) 3 (Size of array) 0 1 1 (input) 3 0 1 2 """ # To store no of test cases here (2). # To store input here (0 1 1) and (0 1 2). t = int(sys.stdin.readline()) # print(t) l = [] while t: #To store the size of array here (3). n = int(sys.stdin.readline()) ...
1,322
547
""" Some persistent maps (gdbm) require special encoding of keys and/or values. This is an abstraction for these kinds of quirks. """ from itertools import imap import collections import gdbm as dbm import json from sqlitedict import SqliteDict import os class EncodedDict(collections.MutableMapping): """ Sub...
3,660
1,247
class Solution: def minCut(self, s: str) -> int: dp=self.isPal(s) return self.bfs(s,dp) def isPal(self,s): dp=[[False for i in s] for i in s] for i in range(len(s)): dp[i][i]=True if i+1<len(s): dp[i][i+1]=True if s[i]==s[i+1] else False ...
1,672
658
from PySide6.QtGui import QColor from PySide6.QtWidgets import QFrame, QHBoxLayout, QWidget from PySide6.QtCore import Qt, QSettings, QEvent from utils import colors import pyqtgraph as pg import numpy as np class ScrollablePlotWidget(pg.PlotWidget): """ Subclass of `pg.PlotWidget` that overrides `wheelEven...
3,708
1,124
### IT WORKS BOIISSS WE DID IT!!!!### #------------------------------------------------------------- #Imports #------------------------------------------------------------- import tensorflow as tf import numpy as np from PIL import Image import cv2 import colorsys import random import time from googleapiclient.http i...
9,124
3,145
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from collections import OrderedDict from torch import nn from maskrcnn_benchmark.modeling import registry from maskrcnn_benchmark.modeling.make_layers import conv_with_kaiming_uniform from . import fpn as fpn_module from . import res2net @regis...
2,790
1,162
"""Memory watchdog: periodically read the memory usage of the main test process and print it out, until terminated.""" import os import sys import time try: page_size = os.sysconf('SC_PAGESIZE') except (ValueError, AttributeError): try: page_size = os.sysconf('SC_PAGE_SIZE') except (ValueError, Attr...
608
212
import pytest pytest_plugins = ["fixtures.accounts", "fixtures.deployments"] def pytest_sessionfinish(session, exitstatus): if exitstatus == pytest.ExitCode.NO_TESTS_COLLECTED: # we treat "no tests collected" as passing session.exitstatus = pytest.ExitCode.OK @pytest.fixture(autouse=True) def i...
371
124
# 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 ...
38,375
12,089
#!/usr/bin/env python # -*- coding: utf-8 -*- from file.file import file class txt2bin( file ): def read( self, file ): datas = [] with open( file, 'r', encoding='utf-8' ) as f: lines = f.readlines() for line in lines: data = line....
1,254
375
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Maziar Raissi """ import sys sys.path.insert(0, '../PGP/') import numpy as np import matplotlib.pyplot as plt import pandas as pd from parametric_GP import PGP if __name__ == "__main__": # Import the data data = pd.read_pickle('airline.pick...
2,105
932
# # Author: Robert Abram <rabram991@gmail.com> # # This file is subject to the terms and conditions defined in the # file 'LICENSE', which is part of this source code package. # import os from proj.settings.base import * # # Logging # LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatter...
2,081
688
#!/usr/bin/env python3 # Copyright 2018 Brocade Communications Systems LLC. 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. # You may also obtain a copy of the License at # http://www.apache.org/licenses/LICENS...
3,426
1,046
import logging import unittest from contextlib import contextmanager class _CaptureLogHandler(logging.Handler): """ A logging handler capturing all (raw and formatted) logging output. """ def __init__(self): super().__init__() self.records = [] def emit(self, record): sel...
2,345
624
from flask import Flask, render_template, session, redirect, url_for, request, flash, abort, current_app, make_response from flask_login import login_user, logout_user, login_required, current_user from . import admin from .. import db from ..models import User, Post from ..form import PostForm from functools import wr...
892
258
# ---------------------------------------------------------------------------- # Copyright (c) 2017-2018 FIRST. All Rights Reserved. # Open Source Software - may be modified and shared by FRC teams. The code # must be accompanied by the FIRST BSD license file in the root directory of # the project. # ------------------...
2,561
766
"""! @brief Neural Network: Self-Organized Feature Map @details Implementation based on paper @cite article::nnet::som::1, @cite article::nnet::som::2. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import math import random import matplotlib.pyplot as pl...
39,324
11,706
import rospy from styx_msgs.msg import TrafficLight import numpy as np from keras.models import Model from keras import applications from keras.models import load_model from keras.preprocessing import image as img_preprocessing import cv2 # load the trained model from keras.utils.generic_utils import CustomObjectScop...
2,265
676
# -*- coding: utf-8 -*- """Cluster plotting tools""" __author__ = ["Christopher Holder", "Tony Bagnall"] __all__ = ["plot_cluster_algorithm"] import pandas as pd from sktime.clustering.base._typing import NumpyOrDF from sktime.clustering.base.base import BaseClusterer from sktime.clustering.partitioning._lloyds_parti...
2,080
682
from sqlalchemy.orm import Session from src import crud from src.core.security import verify_password from src.schemas.user import UserCreate, UserUpdate from src.tests.utils.user import create_random_user_by_api from src.tests.utils.utils import random_lower_string def test_create_user(db: Session): username = ...
2,858
874
from django.test import TestCase from transductor.forms import EnergyForm from transductor.models import TransductorModel class EnergyTransductorForm(TestCase): def setUp(self): t_model = TransductorModel() t_model.name = "TR 4020" t_model.transport_protocol = "UDP" t_model.serial_...
1,062
356
from typing import Any, List, Optional import hydra import torch import torchmetrics from omegaconf import DictConfig from pytorch_lightning import LightningModule from ..optimizer.scheduler import create_scheduler from ..utils import utils from ..utils.misc import mixup_data log = utils.get_logger(__name__) class...
3,729
1,130
#! /usr/bin/env python ############################# BEGIN FRONTMATTER ################################ # # # TEA - calculates Thermochemical Equilibrium Abundances of chemical species # # ...
11,122
2,888
from pylab import * import tables def exactSol(X, Y, t): return exp(-2*t)*sin(X)*cos(Y) fh = tables.openFile("s251-dg-diffuse-2d_q_1.h5") q = fh.root.StructGridField nx, ny, nc = q.shape dx = 2*pi/nx Xf = linspace(0, 2*pi-dx, nx) dy = 2*pi/ny Yf = linspace(0, 2*pi-dy, ny) XX, YY = meshgrid(Xf, Yf) Xhr = linspace...
2,073
1,208
# Importação de bibliotecas from datetime import date # Título do programa print('\033[1;34;40mCLASSIFICAÇÃO DE CATEGORIAS PARA NATAÇÃO\033[m') # Objetos nascimento = int(input('\033[30mDigite o ano do seu nascimento:\033[m ')) idade = date.today().year - nascimento mirim = 9 infantil = 14 junior = 19 senior = 20 # ...
973
479
from everett.component import RequiredConfigMixin, ConfigOptions from everett.manager import ConfigManager, ConfigOSEnv class BotConfig(RequiredConfigMixin): required_config = ConfigOptions() required_config.add_option('flask_loglevel', parser=str, default='info', doc='Set the log level for Flask.') requi...
1,681
408
import sys output=sys.argv[1] input_list=(sys.argv[2:]) EXP={} header=[] for input_file in input_list: fi=open(input_file) header=header+fi.readline().replace('"','').rstrip().split() for line in fi: seq=line.replace('"','').rstrip().split() if seq[0] in EXP: EXP[s...
618
282
def main(j, args, params, tags, tasklet): params.merge(args) doc = params.doc tags = params.tags out = "" cmdstr = params.macrostr.split(":", 1)[1].replace("}}", "").strip() md5 = j.base.byteprocessor.hashMd5(cmdstr) j.system.fs.createDir(j.system.fs.joinPaths(j.core.portal.active.filesro...
1,152
414
from pyramda.function.curry import curry from pyramda.function.always import always from pyramda.iterable.reduce import reduce from .either import either @curry def any_pass(ps, v): return reduce(either, always(False), ps)(v)
232
76
from django.shortcuts import render, get_object_or_404 from django.utils.timezone import now from schedule.models import Calendar from schedule.periods import Day from bio.scheduler import models def actions(request): actions = models.Action.objects.order_by('-created_on') period = Day(actions, now()) # X...
817
257
try: import MyTable except NameError as e: print(e) import importlib importlib.import_module('Constraints') # 現在 locals() にある module に Constraints.py モジュールを加える。 # (MyTableにConstraintsを加える。`from Constraints import PK,UK,FK,NN,D,C`する) # トレースバックで例外発生モジュールを補足 import sys, traceback exc_t...
1,759
759
# -*- coding: utf-8 -*- # # Copyright (C) 2018-2020 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://trac.edgewall.org/wiki/TracLicense. # # This software cons...
22,797
7,336
import click, requests, sys bootstrap_ip = '192.168.0.2' bootstrap_port = '8000' base_url = 'http://' + bootstrap_ip + ':' + bootstrap_port @click.group() def toychord(): """CLI client for toy-chord.""" pass @toychord.command() @click.option('--key', required=True, type=str) @click.option('--value', requir...
2,646
913
from sportstrackeranalyzer.plugins.plugin_simple_distances import Plugin_SimpleDistance
87
22
"""Initial creation of schema Revision ID: a12e86de073c Revises: Create Date: 2018-01-05 13:42:18.768932 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'a12e86de073c' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### comma...
2,598
905
""" TakeDown v0.0.1 =============== author: Zesheng Xing email: zsxing@ucdavis.edu This Python project is to help people search on some client hosting contents that potential violate the their copyright. """ VERSION = "0.1.0" DESCRIPTION = "A python script that allows users to search potential copyright violated info...
5,106
1,254
import os.path CABEXTRACT_TEST_DIR = os.path.join(os.path.dirname(__file__), 'test-data', 'cabextract', 'cabs') CABEXTRACT_BUGS_DIR = os.path.join(os.path.dirname(__file__), 'test-data', 'cabextract', 'bugs') LIBMSPACK_TEST_DIR = os.path.join(os.path.dirname(__file__), 'test-data', 'libmspack') def read_cabextract_...
977
386
""" Exceptions module """ class CuckooHashMapFullException(Exception): """ Exception raised when filter is full. """ pass
141
42
import networkx as nx class _CentralityMetrics: def __init__(self, G, metrics): self.G = G self.metrics = metrics def _compute_metrics(self): metrics = self.metrics if metrics == 'degree_centrality': c = self.degree_centrality() elif...
1,212
374
############################################################################### # Copyright (C) 2016 Juho Kokkala # This is part of Juho Kokkala's PoDoCo project. # # This file is licensed under the MIT License. ############################################################################### """ Particle filters for tra...
3,558
1,265
import torch import torch.nn.functional as F from torch import nn import dgl import networkx as nx class SemanticGCN(nn.Module): def __init__(self, config, in_dim, out_dim, rel_dim): super(SemanticGCN, self).__init__() self.config = config self.gcn1 = SemanticGCNLayer(in_dim, out_dim, rel...
2,610
995
from inspect import cleandoc from textwrap import indent from lark import Lark, Transformer from lark.exceptions import LarkError from .interval import Interval from . import errors def parse(ctx, fname): with open(fname, "r") as f: t = f.read() try: l = Lark(open(ctx.implfile("s...
3,808
1,391
print('Interrogando um suspeito: ') pg1 = str(input("Telefonou para a vítma?(S/N)\n").upper().strip()) pg2 = str(input('Esteve no local do crime?(S/N)\n').upper().strip()) pg3 = str(input('Mora perto da vítma?(S/N)\n').upper().strip()) pg4 = str(input('Devia para a vítma?(S/N)\n').upper().strip()) pg5 = str(input('Já t...
567
239
class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle == "": return 0 for i in range(0, len(haystack) - len(needle) + 1): print(haystack[i : i + len(needle)], needle) if haystack[i : i + len(needle)] == needle: return i ...
334
112
from template import Template from template.test import TestCase, main class Stringy: def __init__(self, text): self.text = text def asString(self): return self.text __str__ = asString class TextTest(TestCase): def testText(self): tt = (("basic", Template()), ("interp", Template({ "I...
2,235
966
# Copyright (c) 2021 John Carrino import math from pprint import pprint import matplotlib.pyplot as plt from frispy import Disc from frispy import Discs model = Discs.destroyer mph_to_mps = 0.44704 v = 70 * mph_to_mps rot = -v / model.diameter * 1.2 x0 = [6, -3, 25] a, nose_up, hyzer = x0 disc = Disc(model, {"vx": ...
761
370
# # This file is part of LiteX. # # Copyright (c) 2018-2020 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause from migen import * from migen.genlib.resetsync import AsyncResetSynchronizer from litex.build.io import DifferentialInput from litex.soc.interconnect.csr import * from li...
6,200
2,060
__all__ = ( 'des_encrypt', 'des_decrypt', ) from typing import List, Any from ._tools import * from ._constant import * from rich import print from rich.text import Text from rich.panel import Panel def keygen(key: bytes) -> List[List[int]]: res = [] key = bytes_to_binlist(key) key = permute_wit...
3,044
1,264
#!/usr/bin/python3 import subprocess import apt import sys cache = apt.cache.Cache() cache.update() cache.open() packages = [ 'git', 'curl', 'wget', 'software-properties-common', 'build-essential', 'automake', 'libtool', 'autoconf', 'pkg-config'...
1,080
389
from time import time import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), 'src')) from singly_linkedlist.singly_linkedlist import SinglyLinkedList start = time() linked_list = SinglyLinkedList() for i in range(100000): linked_list.insert_head(111111111111) end = time() print("Took {0} sec...
377
145
# 1. 两数之和 from typing import List, Optional class Solution: def twoSum(self, nums: List[int], target: int) -> Optional[List[int]]: index_map = {} for index, value in enumerate(nums): index_map[value] = index for index, value in enumerate(nums): remain = target - val...
561
180
#!/usr/bin/env python2 import rosbag import sys filename = sys.argv[1] topics = sys.argv[2:] with rosbag.Bag(filename) as bag: for topic, msg, t in bag.read_messages(topics): print('%s @%.7f ----------------------------' % (topic, t.to_sec())) print(msg) print('Press ENTER to continue') ...
454
136
from alegra.api_requestor import APIRequestor from alegra.resources.abstract import CreateableAPIResource from alegra.resources.abstract import EmailableAPIResource from alegra.resources.abstract import ListableAPIResource from alegra.resources.abstract import UpdateableAPIResource from alegra.resources.abstract impor...
1,011
285
"""Utilities for hyperparameter optimization. These estimators will operate in parallel. Their scalability depends on the underlying estimators being used. """ from dask_searchcv.model_selection import GridSearchCV, RandomizedSearchCV # noqa
244
61
x = 5 y = 6 print(x*y)
23
18
import pytest from ..iocsh import IocshRedirect, IocshSplit, split_words @pytest.mark.parametrize( "line, expected", [ pytest.param( """dbLoadRecords(a, "b", "c")""", ["dbLoadRecords", "a", "b", "c"], id="basic_paren" ), pytest.param( "...
2,521
722
from bs4 import BeautifulSoup from datetime import datetime from lxml import etree import time import codecs import pickle import os def printSeparator(character, times): print(character * times) if __name__ == '__main__': doiPrefix = '10.7202' #erudit's doi prefix myTime = datetime.now().strftime('%Y-%m-%d_...
1,723
764
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Milight 3.0 (LimitlessLED Wifi Bridge v6.0) library: Control wireless lights (Milight 3.0) with Wifi Note that this library was tested with Milight Wifi iBox v1 and RGBW lights. It should work with any other lights and bridge using Milight 3.0 / LimitlessLED v6....
49,071
17,550
import os import numpy as np import pandas as pd from Base import Train, Predict def getTest(boolNormalize, boolDeep, boolBias, strProjectFolder): if boolNormalize: if boolDeep: strOutputPath = "02-Output/" + "Deep" + "Normal" else: if boolBias: strOutputPa...
2,602
832