text
string
size
int64
token_count
int64
import angr import claripy path_to_bin = "../binaries/06_angr_symbolic_dynamic_memory" # Find callback def good_job(state): # Get the output of the state stdout = state.posix.dumps(1) # If the program echo'ed "Good Job." then we've found a good state return "Good Job." in str(stdout) # Avoid callba...
3,402
1,371
""" Runs the server """ from aaxus import app app.run()
57
21
# -*- coding: utf-8 -*- """ Created on Thu Dec 6 20:36:02 2018 @author: Rohit """ # ============================================================================= # import numpy as np # a = np.array([5,4])[np.newaxis] # print(a) # print(a.T) # # function [x] = conjgrad(A, b, x) # r = b - A * x; # p = r; # ...
1,416
600
import argparse import logging import math from pathlib import Path import torch.multiprocessing as mp import os from datetime import datetime import nltk import pandas as pd import transformers from torch import nn import torch.distributed from torch._C._distributed_c10d import HashStore from torch.utils.data import...
5,232
1,598
# open input text scenario import xml.etree.ElementTree as ET import os PATH = "G:\\FYP\\FYP-ER-Relationships-Module\\data" text_file = open(PATH+"\\input_text.txt", "r") if text_file.mode == 'r': # Read the scenario and covert that text file into lowercase input_text_load = text_file.read() input_text =...
1,793
622
import pytest import tensorflow as tf from nncf.tensorflow.tensor import TFNNCFTensor from nncf.tensorflow.pruning.tensor_processor import TFNNCFPruningTensorProcessor @pytest.mark.parametrize('device', ("CPU", 'GPU')) def test_create_tensor(device): if not tf.config.list_physical_devices('GPU'): if devi...
2,428
858
from twitchio.dataclasses import Message from typing import Dict, Callable from datetime import datetime from dataclasses import dataclass from src.bot.gameobservers.Observer import Observer from src.bot.gameobservers.Subject import Subject from src.bot.botstates.BotState import BotState from src.bot.botstates.TeamGam...
4,288
1,270
# -*- coding: utf-8 -*- """ Description: Todo: """ import os import sys import logging from collections import deque from base_state import BaseState class Playing1stState(BaseState): """""" def __init__(self, state_controller): super().__init__(state_controller, self.in_state) @BaseState....
515
171
# -*- coding: utf-8 -*- import time, random def isort(i_list): for i in range(1, len(i_list)): for j in range(i,0, -1): if i_list[j] < i_list[j-1]: i_list[j], i_list[j-1] = i_list[j-1], i_list[j] else: break if __name__ == "__main__": alist = [] ...
518
211
""" test_relu.py: Test suite for the ReLU estimator class :class:ReLUEstim` """ from __future__ import print_function from __future__ import division import unittest import numpy as np # Add the path to the vampyre package and import it import env env.add_vp_path() import vampyre as vp def logistic_test(zshape=(1...
1,903
690
"""Live tests of client authentication against the Stormpath service API.""" from os import environ from stormpath.client import Client from stormpath.error import Error from .base import LiveBase class TestAuth(LiveBase): def test_basic_authentication_succeeds(self): client = Client( id=s...
1,543
439
import logging logger1 = logging.getLogger('package1.module1') logger2 = logging.getLogger('package1.module2') logging.basicConfig(level=logging.WARNING) logger1.warning('This is a warning message') logger2.warning('This is a another warning message')
256
76
from pathlib import Path from foreman import define_parameter, rule, get_relpath import foreman if __name__ != 'pkg1': raise AssertionError(__name__) if not __file__.endswith('foreman/tests/testdata/test_command/pkg1/build.py'): raise AssertionError(__file__) relpath = get_relpath() if relpath != Path('p...
862
299
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
11,036
3,544
""" Transitional module for moving to the w3lib library. For new code, always import from w3lib.html instead of this module """ import warnings from scrapy.exceptions import ScrapyDeprecationWarning from w3lib.html import * warnings.warn("Module `scrapy.utils.markup` is deprecated. " "Please import fr...
400
117
#IMPORT log and sqrt FROM math MODULE from math import log, sqrt, exp #IMPORT date AND timedelta FOR HANDLING EXPIRY TIMES from datetime import date, timedelta #IMPORT SciPy stats MODULE from scipy import stats def asian_vol_factor(valDate,startDate,endDate): #VALIDATE START DATE RELATIVE TO END DATE AND RETURN NO...
2,362
904
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import os import math import networkx as nx import functools import scipy.stats import random import sys import copy import numpy as np import torch import utils try: sys.path.append('/opt/MatterSim/build/') # local docker or Philly im...
27,286
8,663
import tensorflow as tf import numpy as np import unittest from dnc.controller import BaseController class DummyController(BaseController): def network_vars(self): self.W = tf.Variable(tf.truncated_normal([self.nn_input_size, 64])) self.b = tf.Variable(tf.zeros([64])) def network_op(self, X):...
7,124
2,469
# -*- coding: utf-8 -*- from scrapy.linkextractors import LinkExtractor from scrapy.loader import ItemLoader from scrapy.loader.processors import Join, MapCompose from scrapy.spiders import CrawlSpider, Rule from movies.items import MoviesItem class DoubanSpider(CrawlSpider): name = 'douban' allowed_domains ...
1,538
510
import numpy as np from scipy.misc import imread, imsave, imresize from keras.models import model_from_json from os.path import join import matplotlib.pyplot as plt import pandas as pd import time def shuffler(filename): df = pd.read_csv(filename, header=0) # return the pandas dataframe return df.reindex(np.random....
1,546
585
# find parmec path import os, sys def where(program): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, program)): return path return None path = where('parmec4') if path == None: print 'ERROR: parmec4 not found in PATH!' print ' Download and compile parmec;'...
3,304
1,478
# -*- coding: utf-8 -*- # @Author : Eurkon # @Date : 2021/6/9 17:13 from api.weibo.api.top import weibo_top
113
62
import pyb import random leds = [pyb.LED(i) for i in range(1, 5)] blue_led = pyb.LED(4) def fanfare(delay=200): def switch_all(on=True): for led in leds: if on: led.on() else: led.off() for i in range(4): switch_all(on=True) py...
1,293
428
import json import os import shutil import urllib.request import traceback import logging import psutil from collections import defaultdict from typing import List, Dict, Tuple from multiprocessing import Semaphore, Pool from subprocess import Popen, PIPE from datetime import datetime, timedelta from lxml import etree...
8,088
2,528
class FollowupEvent: def __init__(self, name, data=None): self.name = name self.data = data class Response: def __init__(self, text=None, followup_event=None): self.speech = text self.display_text = text self.followup_event = followup_event class UserInput: def _...
597
180
# coding: utf-8 # import re import os from django.conf import settings from django.shortcuts import ( render_to_response, get_object_or_404 as _get_object_or_404, redirect) from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from django.contrib.contenttypes.mode...
9,491
2,795
import numpy as np from typing import List def reshpare_to_square_matrix( seq:List)->None: square_matrix = np.array( seq ) # reshpae to square matrix square_matrix.shape = (3,3) return square_matrix if __name__ == '__main__': int_sequence = list( map( int, input().split() ) ) # Method_#1 ...
536
196
import numpy as np import time import csv import multiprocessing import os from numba import njit @njit() def timestep(dist): t1 = 1e-5 t2 = 1e-2 k = 1 timestep = (t2-t1)*np.tanh(k*dist)+t1 return timestep @njit() def random_walk(m,d,t,R,rt): time = 0 #set up random IC on circle of radius ...
2,440
955
import inspect import pytest import numpy as np from datar.core.backends.pandas import Categorical, DataFrame, Series from datar.core.backends.pandas.testing import assert_frame_equal from datar.core.backends.pandas.core.groupby import SeriesGroupBy from datar.core.factory import func_factory from datar.core.tibble im...
8,153
3,314
import requests from functools import reduce import operator from urllib.parse import quote import time TWITCH_HEADER = {'Client-ID': 'nhnlqt9mgdmkf9ls184tt1nd753472', 'Accept': 'application/json'} class Twitch(object): def get_twitch_data(self, game_name): url = 'https://api.twitch.tv/...
2,234
683
#!/usr/bin/env python # Copyright 2014, Rackspace US, 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 applicabl...
2,407
703
from . import FixtureTest class AddMissingBoundaries(FixtureTest): def test_statistical(self): # NE data - no OSM elements # boundary between NV and CA is _also_ a "statistical" boundary self.load_fixtures([ 'file://integration-test/fixtures/' 'ne_10m_admin_1_states...
946
331
import os from flask import render_template from flask_sqlalchemy import SQLAlchemy from app import app FILE_PATH = "/home/ivche/dev/Dodgerino-Game/highscores.db" print(FILE_PATH) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+FILE_PATH app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False DB = SQLAlchemy(app)...
836
287
""" Work with MDS Provider data in JSON files. """ import csv import datetime import hashlib import json import os import pathlib import urllib import requests import pandas as pd from .encoding import JsonEncoder from .providers import Provider from .schemas import SCHEMA_TYPES, STATUS_CHANGES, TRIPS from .versions...
24,076
6,329
import os import rasterio import argparse from PIL import Image import subprocess import pathlib import shutil from glob import glob from numba import njit, prange from OpenVisus import * ### Configuration ext_name = ".tif" dtype = "uint8[3]" limit = 1000 ###-------------- @njit(parallel=True) def...
7,600
3,286
from .plugin import ProcessTimePlugin
38
9
#!/usr/bin/env python3 """ Created on Tue Sep 1 2020 @author: kstoreyf """ import numpy as np import nbodykit import pandas as pd import pickle from nbodykit import cosmology def main(): save_fn = '../data/cosmology_train.pickle' x = generate_training_parameters(n_train=1000) y, extra_input = generate_...
3,972
1,541
from handlers.simplehandler import SimpleHandler _NO_SURFACE = { 'title': 'Не указано покрытие дороги', 'help_text': """Для highway=track не задано покрытие (surface). Объективные параметры: - surface - тип покрытия Субьективные параметры: - surface:grade - оценка качества относительно типа покрытия (0..3) -...
1,256
456
# -*- coding: utf-8 -*- jobwords = [ 'nan', 'temps plein', 'temps complet', 'mi temps', 'temps partiel', # Part / Full time 'cherche', # look for 'urgent','rapidement', 'futur', 'job', 'offre', # Job offer 'trice', 'ère', 'eur', 'euse', 're', 'se', 'ème', 'trices', # Fe...
9,636
3,332
# Copyright 2020 Alexis Lopez Zubieta # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publi...
6,262
2,065
from setuptools import setup import io setup( name='bw2temporalis', version="0.9.2", packages=[ "bw2temporalis", "bw2temporalis.tests", "bw2temporalis.examples", "bw2temporalis.cofire" ], author="Chris Mutel", author_email="cmutel@gmail.com", license=io.open(...
1,631
520
import KratosMultiphysics import KratosMultiphysics.FemToDemApplication.MainFemDem as MainFemDem import KratosMultiphysics.FemToDemApplication as KratosFemDem import KratosMultiphysics.DEMApplication as DEM import KratosMultiphysics.DemStructuresCouplingApplication as DEM_Structures # Python script created to ...
8,444
2,773
import os import yaml import copy import logging from pathlib import Path import torch from torch.nn import * from torch.optim import * import torch.distributed as dist from torch.optim.lr_scheduler import * from torch.nn.parallel import DistributedDataParallel from utils.metrics import * from models import _get_mode...
5,284
1,628
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ GitHub Homepage ---------------- https://github.com/ADP-Benchmarks Contact information ------------------- ADP.Benchmarks@gmail.com. License ------- The MIT License """ from MDP.spaces.space import Space from MDP.transition import Transitio...
6,139
1,479
from graph_peak_caller.multiplegraphscallpeaks import MultipleGraphsCallpeaks from graph_peak_caller.intervals import Intervals from graph_peak_caller import Configuration from graph_peak_caller.reporter import Reporter from offsetbasedgraph import GraphWithReversals as Graph, \ DirectedInterval, IntervalCollection...
7,186
2,170
# -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2021 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html #...
7,141
2,149
# Problem Name: Suffix Trie Construction # Problem Description: # Write a SuffixTrie class for Suffix-Trie-like data structures. The class should have a root property set to be the root node of the trie and should support: # - Creating the trie from a string; this will be done by calling populateSuffixTrieFrom me...
5,312
1,377
def test_list_devices(client): devices = client.devices() assert len(devices) > 0 assert any(map(lambda device: device.serial == "emulator-5554", devices)) def test_list_devices_by_state(client): devices = client.devices(client.BOOTLOADER) assert len(devices) == 0 devices = client.devices(clie...
961
327
import copy import numpy as np import torch from pytorch_lightning.utilities import rank_zero_warn from pytorch_lightning.callbacks import Callback class BestEpochCallback(Callback): TORCH_INF = torch_inf = torch.tensor(np.Inf) MODE_DICT = { "min": (torch_inf, "min"), "max": (-torch_inf, "max"...
2,026
655
from hashlib import sha1 as _sha1 import sqlite3 import unittest from peewee import * import signals import sqlite_ext as sqe import sweepea db = SqliteDatabase(':memory:') class BaseSignalModel(signals.Model): class Meta: database = db class ModelA(BaseSignalModel): a = CharField(default='') clas...
12,840
4,439
#!/usr/bin/python import os, sys import optparse import json, urllib import httplib2 import urlparse def upload(filenames, url, password): parsed = urlparse.urlparse(url) http = httplib2.Http() for filename in filenames: with open(filename) as f: # Load and validate JSON o = json.load(f) s ...
799
279
import unittest class TestIsGoView(unittest.TestCase): def test_nil(self): self.assertFalse(None)
112
38
"""457. Circular Array Loop https://leetcode.com/problems/circular-array-loop/ """ from typing import List class Solution: def circular_array_loop(self, nums: List[int]) -> bool: def helper(start: int, cur: int, count: int, visited) -> int: if nums[cur] * nums[start] < 0: retur...
855
252
import pandas as pd from pandas import read_csv import os import sys import glob import re import soundfile as sf import pyloudnorm as pyln from .thdncalculator import execute_thdn class Task2: def __init__(self,data,file_name): self.df = pd.DataFrame.from_dict(data, orient='columns') self.file_name = file_nam...
10,937
4,125
import tensorflow as tf import tensorflow_hub as hub from tf_agents.networks import network # Bert needs this (I think) TODO: Check? import tensorflow_text as text embedding = "https://tfhub.dev/google/nnlm-en-dim128-with-normalization/2" tfhub_handle_encoder = ( "https://tfhub.dev/tensorflow/small_bert/bert_en_u...
6,253
2,087
# !/usr/bin/env python # _*_ coding:utf-8 _*_ from django.conf.urls import url from . import views urlpatterns = [ # 1. 结算订单 orders/settlement/ url(r'^orders/settlement/$', views.OrdersSettlementView.as_view(), name='settlement'), # 2. orders/commit/ 提交订单 url(r'^orders/commit/$', views.OrdersCo...
475
195
"""Top-level package for Goldmeister.""" __author__ = """Micah Johnson""" __email__ = 'micah.johnson150@gmail.com' __version__ = '0.2.0'
138
57
from user import User from Env import Env_Vars from fetch_from_sheet import SheetData from pymongo import MongoClient from pprint import pprint env_vars = Env_Vars() MongoURI = env_vars.MongoURI client = MongoClient(MongoURI, 27017) db = client['users'] users = db['users'] def do_update(): sheet = SheetData() d...
1,014
362
# @uvicore.service() # class Routes(RoutesInterface, Generic[R]): # endpoints: str = None # @property # def app(self) -> ApplicationInterface: # return self._app # @property # def package(self) -> PackageInterface: # return self._package # @property # def Router(self) ...
1,956
581
n = int(input('Digite um número: ')) if n % 2 == 0 and n % 3 == 0 and n % 5 == 0: print('{} é um número primo!'.format(n)) else: print('{} não é um número primo!'.format(n))
182
75
import threading import time import RPi.GPIO as GPIO import logging import logging.config # declare logger parameters logger = logging.getLogger(__name__) class PWMController(threading.Thread): """ Thread class with a stop() method. Handy class to implement PWM on digital output pins """ def __init_...
1,684
532
# Copyright (c) 2012-2015 Netforce Co. Ltd. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publ...
2,393
801
import math a = float(input('insira um valor')) print('a porção inteira do valor {} é {}'.format(a,math.trunc(a)))
115
42
#from data_loader import * from scipy import signal import matplotlib.pyplot as plt import copy import os import shutil import numpy as np def data_filter(exp_path, probe_type='point', Xtype='loc',ytype='f',num_point=0): shutil.rmtree(exp_path+probe_type+'_expand', ignore_errors=True) os.mkdir(exp_path+probe_t...
5,144
1,838
from collections import deque def parenthesis_matching(user_input): my_stack = deque() my_dict = {'(': ')', '{': '}', '[': ']'} try: count = 0 for letter in user_input: if letter in my_dict.keys(): my_stack.append(letter) count += 1 e...
616
198
def si(p,r,t): n= (p+r+t)//3 return n
58
34
# Example of use of Afanasy's API to generate a summary of the state of the # render farm. # Copyright (c) 2016 rise|fx (Elie Michel) - Released under MIT License import af cmd = af.Cmd() def isSysJob(job): return job['st'] == 0 ## Jobs ## joblist = cmd.getJobList() job_state_counters = {} job_count = 0 for j...
1,670
634
# Copyright (c) 2012 by Zuse-Institute Berlin and the Technical University of Denmark. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this so...
4,931
1,616
from copy import deepcopy import os import re from PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGui from GUI.Visualization import Ui_Visualization from FAE.FeatureAnalysis.Classifier import * from FAE.FeatureAnalysis.FeaturePipeline import FeatureAnalysisPipelines, OnePipeline from FAE.Description.Description...
35,353
10,362
# Copyright 2017 Mirko Lelansky <mlelansky@mail.de> # # 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 a...
1,779
515
# Copyright (c) 2021, Fruiti Limited # 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. from datetime import datetime def convert_custom_timestamp_range(timestamp_range: str) -> list: result = timestamp_range.s...
735
224
import numpy as np import cv2 import argparse from collections import deque import keyboard as kb import time from pynput.keyboard import Key, Controller, Listener class points(object): def __init__(self, x, y): self.x = x self.y = y sm_threshold = 100 lg_threshold = 200 guiding = True keyboar...
5,313
1,823
from django.db import models def picture_upload_path(instance, filename): # file will be saved at <MEDIA_ROOT>/authorPictures/<filename> return 'authorPictures/{0}'.format(filename) def hero_upload_path(instance, filename): # file will be saved at <MEDIA_ROOT>/heroImages/<filename> return 'heroImage...
1,285
418
import re data = open('regex_sum_46353.txt') numlist = list() for line in data: line = line.rstrip() integers = re.findall('[0-9]+', line) if len(integers) < 1: continue for i in range(len(integers)): num = float(integers[i]) numlist.append(num) num_sum = sum(numlist) print (num_sum)
319
123
#!/usr/bin/env python import daemon class TuinWolkDaemon(daemon.Daemon): def run(self): #TODO: implement me! pass
121
51
import json import time import datetime import string import calendar from helpers import get_cpu_temp, check_login, password_hash import web import gv # Gain access to ospi's settings from urls import urls # Gain access to ospi's URL list from webpages import ProtectedPage, WebPage ############## ## N...
7,205
2,482
""" .. _Iroha: Iroha ===== Functions to post transactions in the iroha implementation of the BSMD """ from iroha import IrohaCrypto, Iroha, IrohaGrpc import binascii import sys if sys.version_info[0] < 3: raise Exception('Python 3 or a more recent version is required.') # Transactions request iroha def trace(fu...
4,427
1,288
# -*- coding: utf-8 -*- # import json from tibanna_ffcommon.exceptions import exception_coordinator from tibanna_cgap.start_run import start_run from tibanna_cgap.vars import AWS_REGION, LAMBDA_TYPE config = { 'function_name': 'start_run_' + LAMBDA_TYPE, 'function_module': 'service', 'function_handler': '...
1,068
359
# Copyright by Amplo """ Observer for checking production readiness of model. This part of code is strongly inspired by [1]. References ---------- [1] E. Breck, C. Shanging, E. Nielsen, M. Salib, D. Sculley (2017). The ML test score: A rubric for ML production readiness and technical debt reduction. 1123-1132. 10.110...
3,474
975
#!/usr/bin/env python3 # This is gonna be up to you. But basically I envisioned a system where you have a students in a classroom. Where the # classroom only has information, like who is the teacher, how many students are there. And it's like an online class, # so students don't know who their peers are, or who their ...
2,849
813
import os cleaners = 'korean_cleaners' audio_data_path = os.path.join("/cb_im/datasets/", dataset) data_path = '/home/prml/hs_oh/dataset/emotion_korea/' duration_path = "/home/prml/jihyun/dataset/duration_all/duration" strength_path = "/home/prml/hs_oh/dataset/emotion_strength" # Text text_cleaners = ['korean_cleaner...
1,650
783
# from https://github.com/django-extensions/django-extensions/blob/master/run_tests.py from django.conf import settings from django.core.management import call_command def main(): # Dynamically configure the Django settings with the minimum necessary to # get Django running tests settings.configure( ...
1,083
319
#!/usr/bin/env python3 """Simulation of Shor's algorithm for integer factorization.""" import cmath import math import numpy as np import random class QuMem: """Representation of the memory of the quantum computer.""" def __init__(self, t, n): """Initialize the memory. For Shor's algorithm we have t...
7,275
2,311
print('-'*60) print('\33[35m[ F ] Feminino\33[m \n\33[32m[ M ] Masculino\33[m \n ') sexo = str(input('Qual o seu sexo? ')).strip().upper()[0] # só pega a primeira letra while sexo not in 'MF': sexo = str(input('\33[31mDados inválidos.\33[m Por favor, informe seu sexo: ')).strip().upper()[0] print('\nSexo {} registr...
365
166
import os import cv2 from WordSegmentation import wordSegmentation, prepareImg import json import editdistance from path import Path from DataLoaderIAM import DataLoaderIAM, Batch from Model import Model, DecoderType from SamplePreprocessor import preprocess import argparse import tensorflow as tf class FilePaths: ...
2,858
919
#!/usr/bin/env python """ Module for holding information about an audio file and doing basic conversions """ import hashlib import logging import os import subprocess from asrtoolkit.file_utils.name_cleaners import ( generate_segmented_file_name, sanitize_hyphens, strip_extension, ) from asrtoolkit.file_u...
4,746
1,480
from flask.ext.wtf import Form from wtforms import ( TextField, IntegerField, HiddenField, SubmitField, validators ) class MonkeyForm(Form): id = HiddenField() name = TextField('Name', validators=[validators.InputRequired()]) age = IntegerField( 'Age', validators=[ validators.Input...
574
168
import os import shutil import tensorflow as tf from tensorflow import keras from logs import logDecorator as lD import jsonref import numpy as np import pickle import warnings from tqdm import tqdm from modules.data import getData config = jsonref.load(open('../config/config.json')) logBase = config['logg...
7,008
2,299
import math class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ bits = [0,1] for n in range (2, num+1): count = 0 closestPower = int(math.floor(math.log(n,2))) if closestPower != 0: ...
492
154
#four queen problem bruteforce solution using permutation from itertools import permutations def board(vec): print ("\n".join('.' * i + 'Q' + '.' * (n-i-1) for i in vec) + "\n===\n") n = 8 cols = range(n) for vec in permutations(cols): if n == len(set(vec[i]+i for i in cols)) \ == len(set(ve...
363
139
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pesquisa_produtos.ui' # # Created by: PyQt5 View code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Frame(object): def setupUi(self, Frame): Fram...
10,362
3,855
# -*- coding: utf-8 -*- # MIT license # # Copyright (C) 2019 by XESS Corp. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # t...
7,826
2,567
import cPickle as pickle import os; import sys; sys.path.append('..') import gp import gp.nets as nets PATCH_PATH = ('iplb') X_train, y_train, X_test, y_test = gp.Patch.load_rgb(PATCH_PATH) X_train = X_train[:,:-1,:,:] X_test = X_test[:,:-1,:,:] cnn = nets.RGNetPlus() cnn = cnn.fit(X_train, y_train) test_accuracy ...
516
250
#!/usr/bin/env python # Check that falcon rebuilds an output if it is deleted. import time import os makefile = ''' { "rules": [ { "inputs": [ "source1", "source2" ], "outputs": [ "output" ], "cmd": "cat source1 > output && cat source2 >> output" } ] } ''' def run(test): test.c...
1,066
380
# -*- coding: utf-8 -*- """Top-level package for awesimsoss.""" __author__ = """Joe Filippazzo""" __email__ = 'jfilippazzo@stsci.edu' __version__ = '0.3.5' from .awesim import TSO, TestTSO, BlackbodyTSO, ModelTSO
216
94
from data import all_emoji from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton from aiogram.utils.callback_data import CallbackData from data import all_emoji from utils.googlesheets import send_to_google from utils.set_minus_and_plus_currences import set_minus_and_plus from utils.get_minuses_sum_F...
6,565
2,097
# https://github.com/ArtemNikolaev/gb-hw/issues/24 def multiple_of_20_21(): return (i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0) print(list(multiple_of_20_21()))
181
91
""" ssh brow5079@compute.cla.umn.edu #qsub -I -q gpu qsub -I -l nodes=1:ppn=10 module load python/conda/3.7 source activate env ipython """ from math import sqrt, pi, exp import time import torch import numpy as np import matplotlib.pyplot as plt from matplotlib import rc import seaborn as sns linewidth = 4 alpha ...
1,153
480
import rospy MOVE_CYCLE_PERIOD = 0.01 def move_towards(target, current, step=1): if abs(target-current) < step: return target, True else: if target > current: return current + step, False else: return current - step, False def move_leg(leg, coxa=None, femur=N...
13,761
4,934
import random as rnd from itertools import combinations from time import perf_counter as pfc def seite_ermitteln(versuch): seite = [0]*anz_kugeln links = set(versuch[:len(versuch)//2]) for nr in versuch: seite[nr] = -1 if nr in links else 1 return seite def wiegen(nr, gewicht, seite): return gewicht *...
2,237
998