text
string
size
int64
token_count
int64
""" Assign geographically density value to a points. """ from scipy.spatial import KDTree from scipy.spatial.distance import cdist from scipy.stats import norm from scipy.optimize import minimize import numpy as np def general_density_assignation(locs, parameters, values=None, locs2=None): "Density assignation ...
9,368
3,152
from typing import AsyncIterable from nexus.pylon.sources.base import ( DoiSource, PreparedRequest, ) class BiorxivSource(DoiSource): base_url = 'https://dx.doi.org' async def resolve(self) -> AsyncIterable[PreparedRequest]: async with self.get_resolve_session() as session: url =...
561
174
# -*- coding: utf-8 -*- import argparse from difflib import SequenceMatcher import os from pprint import pprint import sys import lib.eac_utils as eac import lib.io_utils as io # input parser = argparse.ArgumentParser() parser.add_argument('-in', dest="INPUT_FILE", default="data/eac_dates.csv", help="File with EAC d...
3,645
1,202
# Script: MovingPen.py # Description: This program uses python's turtle graphics module to draw shapes,lines, # circles and text. # Programmer: William Kpabitey Kwabla. # Date: 27.05.17 # Importing the turtle module. import turtle # It moves the pen to (0, 50) from (0, 0). turtle.goto(0, 50) # It move...
502
208
# Project Euler Problem 7 # Created on: 2012-06-13 # Created by: William McDonald import math import time # Short list of prime numbers under 20 primeList = [2, 3, 5, 7, 9, 11, 13, 17, 19] # Returns True if n is prime, otherwise False def isPrime(n): prime = True for i in primeList: if ...
912
351
import discord from discord.ext import commands from QuentiumBot import HandleData, get_translations # Basic command configs cmd_name = "ban" tran = get_translations() aliases = [] if not tran[cmd_name]["fr"]["aliases"] else tran[cmd_name]["fr"]["aliases"].split("/") class BanAdminRights(commands.Cog): """Ban com...
1,820
558
class _Callback(object): def __init__(self): self._callbacks = [] def register(self, callback): self._callbacks.append(callback) def __call__(self, *args, **kwargs): for c in self._callbacks: c(*args, **kwargs) class DebugListener(object): ROBOT_LISTENER_API_VERSI...
778
261
from tensorflow.keras import Model, layers, regularizers class SemiSparseInput(Model): def __init__(self, params): super(SemiSparseInput, self).__init__() # Correctly handle SELU dropout = layers.AlphaDropout if params.activation == "selu" else layers.Dropout kernel_init = ( ...
3,057
982
# Testing for neo4j query functions from neo4j import GraphDatabase, basic_auth # setup neo4j database connection driver = GraphDatabase.driver("bolt://13.58.54.49:7687", auth=basic_auth("neo4j", "goSEAKers!")) session = driver.session() # Function that can take the intersection of multiple symptom queries # Fabricat...
4,628
1,606
import datetime import math import os import sys import PyQt5 import dotenv from PyInstaller.archive.pyz_crypto import PyiBlockCipher from PyInstaller.building.api import PYZ, EXE, COLLECT from PyInstaller.building.build_main import Analysis from app import version from app.core.utils import OsUtils, PathUtils APP_N...
5,486
1,958
"""App constants""" import os STUDENT_ROLE = 'student' GRADER_ROLE = 'grader' STAFF_ROLE = 'staff' INSTRUCTOR_ROLE = 'instructor' LAB_ASSISTANT_ROLE = 'lab assistant' ROLE_DISPLAY_NAMES = { STUDENT_ROLE: 'Student', GRADER_ROLE: 'Reader', STAFF_ROLE: 'Teaching Assistant', INSTRUCTOR_ROLE: 'Instructor', ...
1,939
879
# Copyright (c) 2017 - 2020 Kiriti Nagesh Gowda, Inc. All rights reserved. # # 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 ...
31,721
12,659
class FoodNotFound(Exception): def __init__(self, msg=None): self.msg = msg def __str__(self): return "식단을 불러올 수 없습니다.\n {}".format(self.msg) class FoodRateDuplicate(Exception): def __init__(self, msg=None): self.msg = msg def __str__(self): return "이미 평가한 항목입니다.\n ...
342
152
def registrar_estudiantes(n): # registro de datos estudiantes = [] for i in range(n): estudiante = {} print(f'estudiante {i+1}:') estudiante['nombre'] = input('nombre del estudiante: ') in_edad = input('edad del estudiante: ') while not in_edad.isdigit(): ...
939
319
import sys import warnings if not sys.warnoptions: warnings.simplefilter('ignore') import json import os import pickle from ._utils import check_file, load_graph, check_available, generate_session from ..stem import _classification_textcleaning_stemmer from .._models._sklearn_model import ( BINARY_XGB, BI...
6,741
2,064
from oidctest.op import func from oidctest.op import oper from oidctest.op.client import Client from oidctest.session import SessionHandler from otest.aus.handling_ph import WebIh from otest.conf_setup import OP_ORDER from otest.conversation import Conversation from otest.events import Events from otest.flow import Fl...
1,580
462
#Criado para randomizar uma lsita de 20mil Colaboradores retornando apenas 1000 colaboradores vários cargos distintos. import pandas as pd import random base = pd.read_excel("usuarios - energisa.xlsx", encoding="ISO-8859-1",error_bad_lines=False) sort1 = base.sample(15000) sort2 = sort1.sample(10000) sort3 = sort2...
466
198
# -*- coding: utf-8 -*- # https://towardsdatascience.com/build-a-machine-learning-simulation-tool-with-dash-b3f6fd512ad6 # We start with the import of standard ML librairies import pandas as pd import numpy as np from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor # We ad...
7,625
2,220
# try openning a file for reading try: f = open("file.txt", "r") except IOError: print "I/O Error" # undefined variable x = 1.0 try: x + y except NameError: print "undefined variable" # example from tutorial def this_fails(): x = 1/0 try: this_fails() except ZeroDivisionError as detail: print ...
356
126
# coding=utf-8 # Copyright 2022 The Balloon Learning Environment 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 require...
1,787
512
""" MTTR Multimodal Transformer class. Modified from DETR https://github.com/facebookresearch/detr """ import copy import os from typing import Optional import torch import torch.nn.functional as F from torch import nn, Tensor from einops import rearrange, repeat from transformers import RobertaModel, RobertaTokenizerF...
15,181
4,994
import os from typing import Dict def get_downloadable_zip(folder_path: str) -> Dict[str, str]: servable_models: Dict[str, str] = {} for root, dirs, files in os.walk(folder_path): for directory in dirs: for f in os.listdir(os.path.join(root, directory)): if f.endswith(".zip...
403
128
from django.core.mail import EmailMessage from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from accounting.models import Attendance, Result from accounting.templatetags import my_tags from class_book import settings from groups.models import Group, Student from subjects.mo...
6,065
1,903
""" 66. How to replace both the diagonals of dataframe with 0? """ """ Difficulty Level: L2 """ """ Replace both values in both diagonals of df with 0. """ """ Input """ """ df = pd.DataFrame(np.random.randint(1,100, 100).reshape(10, -1)) df # 0 1 2 3 4 5 6 7 8 9 # 0 11 46 26 44 11 62 18 7...
1,415
902
from settings import constants from game import bet_sizing, card_tools, card_to_string from base import Node import torch class PokerTreeBuilder(): def __init__(self): pass def build_tree(self, params): root = Node() root.street = params.root_node.street root.bets = params.roo...
3,861
1,146
# # Copyright (c) 2006-2013, Prometheus Research, LLC # """ :mod:`htsql.core.tr.bind` ========================= This module implements the binding process. """ from ..util import maybe, listof, tupleof, similar from ..adapter import Adapter, Protocol, adapt, adapt_many from ..domain import (Domain, BooleanDomain, ...
50,062
12,735
import os import random from django.db.models import signals from django.utils import timezone import factory from factory.django import DjangoModelFactory from locuszoom_plotting_service.users.tests.factories import UserFactory from .. import constants as lz_constants from .. import models as lz_models def choose_...
2,226
695
import requests from os import getenv from typing import List, Dict _API_URL = getenv('API_URL') def get_groups() -> List[Dict]: response = requests.get(f'{_API_URL}/api/v2/groups/by_faculty') response.raise_for_status() return response.json() def get_season() -> str: response = requests.get(f'{_...
761
276
import torch import torch.nn as nn import math import copy from collections import OrderedDict import torch.utils.model_zoo as model_zoo from core.config import cfg import utils.net as net_utils from deform.torch_deform_conv.layers import ConvOffset2D model_urls = { 'resnet50': 'https://s3.amazonaws.com/pytorch/mo...
22,860
7,995
#!/usr/bin/env python import rospy from master_msgs.msg import traction_Orders, imu_Speed, imu_Magnetism, pots, current, rpm, arm_Orders, goal,connection def node_Interface(): rospy.init_node('node_Interface',anonymous=True) rospy.Subscriber('topic_Traction_Orders',traction_Orders,traction_Orders_Callback) ...
1,530
581
from pantofola_search.models import * from pantofola_search.tools.imdb_fetcher import ImdbFetcher def update_new_movie_info(clean_title, imdb_id, torrent, is_imdb=False): my_imdb = ImdbFetcher() if not Movie.objects.filter(pk=imdb_id).exists(): # #[imdb_id,year,max_ratio,[titles[1]]] movie_inf...
1,700
597
"""Expose structural RTLIR generation pass. PyMTL user should only interact with the passes exposed here. """ from .StructuralRTLIRGenL4Pass import StructuralRTLIRGenL4Pass as StructuralRTLIRGenPass
200
62
import json import re import datetime import os import arcpy regex_flag_dict = { # 'ASCII' re.A, # this is py3 only so wont work in arcgis desktop 'IGNORECASE': re.I, 'LOCALE': re.L, "MULTILINE": re.M, "DOTMATCH": re.S, "UNICODE": re.U, "VERBOSE": re.X, } def main(json_path, feature, outp...
7,663
2,430
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
8,784
3,803
from persona import Persona from logger_base import log from cursor import Cursor class PersonaDAO: _SELECCIONAR = 'SELECT * FROM persona ORDER BY id_persona' _INSERTAR = 'INSERT INTO persona(nombre, apellido, email) VALUES(%s, %s, %s)' _ACTUALIZAR = 'UPDATE persona SET nombre=%s, apellido=%s, ema...
1,710
535
import json import pytest from tornado.httpclient import AsyncHTTPClient, HTTPRequest from hmt.serve.mock.log import Log from hmt.serve.mock.scope import Scope from hmt.serve.mock.specs import load_specs from hmt.serve.utils.routing import HeaderRouting @pytest.fixture def app(mocking_app): return mocking_app( ...
5,394
2,043
# Find the maximum negative element in the array. # Display its value and position in the array. import random arr = [random.randint(-50, 50) for _ in range(10)] print(arr) num = -50 position = 0 for i in arr: if i < 0 and i > num: num = i print ('The maximum negative element {}, its position: {}'.for...
346
118
import collections from numpy.core.defchararray import lower import streamlit as st import numpy as np import pandas as pd from pages import utils def app(): st.title("WhatApp Customer Service") st.subheader("Where automation matters")
253
73
""" Tool to convert 9ML files between different supported formats (e.g. XML_, JSON_, YAML_) and 9ML versions. """ from argparse import ArgumentParser from pype9.utils.arguments import nineml_document from pype9.utils.logging import logger def argparser(): parser = ArgumentParser(prog='pype9 convert', ...
1,000
312
i=0 s=[50] for i in range(0,10): print("w%dwww"%i) s[i]=i print(s[i]
85
53
#PYTHON UN POCO MAS AVANZADO METODO DE ABRIR EN CONSOLA print("PYTHON MAS AVANZADO") texto = "TEXTO DE PRUEBA" nombre = "FREYDER" altura = "2 metros" year = 2021 #print(f"{texto}--{nombre}--{altura}--{str(year)}") print(texto + " " +nombre + " "+ altura +" "+ str(year)) #entradas o peticiones por teclado sitio = i...
871
386
# Copyright (c): Wenyi Tang 2017-2019. # Author: Wenyi Tang # Email: wenyi.tang@intel.com # Update Date: 2019/4/3 下午5:03 import argparse import time from pathlib import Path import h5py import numpy as np import tqdm from PIL import Image __all__ = ["gather_videos_vqp", "gather_videos", "print_dataset"] parser ...
3,615
1,390
""" Process 'com.duckduckgo.mobile.android/app_webview/Cookies' """ import os import sqlite3 from modules.helpers.ddg_path_handler import process_directory_paths query_cookies = """ SELECT host_key, path, name, value, creation_utc, last_access_utc, expires_utc, secure, httponly, persistent, ...
1,480
515
""" A simple and short Redis performance test. """ __author__ = 'Dan Gunter <dkgunter@lbl.gov>' __date__ = '8/8/16' import argparse import logging import os import redis import subprocess import sys import time _log = logging.getLogger(__name__) _h = logging.StreamHandler() _h.setFormatter(logging.Formatter('%(asctim...
3,382
1,229
print("Importing packages... ", end="") ############################################################################## import wandb import numpy as np from keras.datasets import fashion_mnist import matplotlib.pyplot as plt wandb.init(project="trail-1") print("Done!") ##################################################...
1,323
428
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Project : icode_flask_be # @Package : task # @Author : jackeroo # @Time : 2019/11/29 5:25 下午 # @File : task.py # @Contact : # @Software : PyCharm # @Desc : from app.extensions import celery from flask_jwt_extended import jwt_required from app.he...
1,386
457
# Copyright 2021 The LabTools 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 agreed to in ...
1,851
713
### # Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) # Distributed under a Modified BSD License. # See accompanying file LICENSE.txt or # http://www.opengeosys.org/project/license ### # Execute this file to generate TESPy network csv files from tespy import cmp, con, nwk, hlp from tespy impo...
3,855
2,321
import py from pypy.jit.codegen.ppc.rgenop import RPPCGenOp from pypy.rpython.lltypesystem import lltype from pypy.jit.codegen.test.rgenop_tests import AbstractRGenOpTests, FUNC, FUNC2 from ctypes import cast, c_int, c_void_p, CFUNCTYPE from pypy.jit.codegen.ppc import instruction as insn # for the individual tests se...
981
397
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from .models import TestModel import json import redis import time redis_cli = redis.Redis(host='127.0.0.1', port=6379, db=0) @csrf_exempt def save_to_redis(request): data = json.loads(req...
996
320
#%% [markdown] # # Comparing approaches to feedforwardness ordering # For evaluating feedforwardness, we have: # - 4 networks # - Axo-dendritic (AD) # - Axo-axonic (AA) # - Dendro-dendritic (DD) # - Dendro-axonic (DA) # - 4+ algorithms for finding an ordering # - Signal flow (SF) # - Spring rank (SR) ...
1,114
347
import logging import json import os # Initialize logger logger = logging.getLogger(__name__) class BlockManager(): def __init__(self, config, processedblock=0): logger.info('Initialize Block Manager') self.processedblock = int(processedblock) self.config = config if os.path.isfile...
1,401
401
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 23 20:35:49 2017 @author: wrightad """ import numpy as N import matplotlib.pyplot as plt def rmse(v1,v2): ''' rmse(v1,v2) - Calculates the root mean square error between two vectors Version 1.0 Created On: Apr 17, 2017 Last Mo...
5,299
1,891
from django.apps import AppConfig class NavedexConfig(AppConfig): name = 'navedex'
89
30
from .fast_ism import FastISM from .ism_base import NaiveISM
61
22
import numpy as np from numpy.testing import assert_array_equal from ..odf import OdfFit, OdfModel, gfa from dipy.core.triangle_subdivide import (create_half_unit_sphere, disperse_charges) from nose.tools import (assert_almost_equal, assert_equal, assert_raises, assert_true) class SimpleOdf...
3,127
1,251
import socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('127.0.0.1', 50007)) s.listen(1) while True: conn, addr = s.accept() with conn: while True: data = conn.recv(1024) if not data: break ...
423
144
#!/usr/bin/python # encoding: utf-8 #!/usr/bin/python # encoding: utf-8 import torch import torch.nn as nn from torch.autograd import Variable import collections from tqdm import tqdm import numpy as np import cv2 import os import random from sklearn.cluster import KMeans import matplotlib.pyplot as plt class strL...
4,503
1,624
#!/usr/bin/env python from __future__ import division import random import argparse import os parser = argparse.ArgumentParser() parser.add_argument("input", help="input FASTQ Directory") parser.add_argument("-n", "--number", type=int, help="number of reads to sample") args = parser.parse_args() random.seed(12) if ...
2,729
853
from django.shortcuts import render from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet from areas.models import Area from areas.serializers import AreaSerializer, SubAreaSerializer class AreasViewSet(ModelViewSet): """ 行政区划信息 """ pagination_class = None # 区划信息不分页 queryset = A...
777
257
# par ou impar ( condicional simples) x = int(input('Digite um valor inteiro: ')) if (x % 2 == 0): print('O numero é par!') if(x % 2 == 1): print('O numero é impar')
173
70
import math from .exceptions import OutOfBoundsException def ERR_BUFFER_OUT_OF_BOUNDS(): return OutOfBoundsException() def ERR_INVALID_ARG_TYPE(name: str, expected: str, actual): return Exception(f'The "{name}" argument must be of type {expected}. Received {actual}') def ERR_OUT_OF_RANGE(string: str, ran...
900
303
from django.shortcuts import render import sys, json, random, hashlib, calendar,time, datetime, os, random import ast from cryptography.fernet import Fernet from django.shortcuts import redirect from django.http import Http404, HttpResponse import json from cryptography.hazmat.primitives.serialization import Encoding, ...
3,507
1,190
# UCTP Main Methods import objects import ioData import random # Set '1' to allow, during the run, the print on terminal of some steps printSteps = 0 #============================================================================================================== # Create the first generation of solutions def start(s...
51,584
14,846
from pylegos import LogFactory def consoleOnlyTest(): logFactory = LogFactory() logLevel = logFactory.LogLevel.INFO log = logFactory.getConsoleLogger() log.debug('This is a console debug message') log.info('This is an console info message') log.warn('This is a warning message') log.error...
840
251
#!/usr/bin/env python import sys import os import time import test_class import subprocess class StorVSCIOZoneTest(test_class.TestClass): def _set_up_vm(self, vm_name, args): # this piece of code will be executed first thing after the VM is # booted up args['working_dir'] = self._test_pa...
3,171
1,021
""" colors ===== Functions that manipulate colors and arrays of colors There are three basic types of color types: rgb, hex and tuple: rgb - An rgb color is a string of the form 'rgb(a,b,c)' where a, b and c are floats between 0 and 255 inclusive. hex - A hex color is a string of the form '#xxxxxx' where each x is ...
16,809
6,603
# used by Matcher RECEIVE_KEY = "_receive_{id}" LAST_RECEIVE_KEY = "_last_receive" ARG_KEY = "{key}" REJECT_TARGET = "_current_target" REJECT_CACHE_TARGET = "_next_target" # used by Rule PREFIX_KEY = "_prefix" CMD_KEY = "command" RAW_CMD_KEY = "raw_command" CMD_ARG_KEY = "command_arg" SHELL_ARGS = "_args" SHELL_ARGV...
420
192
from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import authenticate, login, logout from .models import TodoModel from django.views.generic import ListView, DetailView, CreateView, DeleteView, UpdateView from django.u...
2,124
629
from ._version import version_info, __version__ from .keplergl import * def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': 'keplergl-jupyter', 'require': 'keplergl-jupyter/extension' }]
269
93
from django.test import tag from django.core.files import File from unittest import mock from iaso import models as m from iaso.test import APITestCase class TokenAPITestCase(APITestCase): @classmethod def setUpTestData(cls): data_source = m.DataSource.objects.create(name="counsil") version ...
9,845
3,248
import world import api.captcha.captcha_phone from api.token.jwt_token import JWTToken """ Django 的 shortcuts.py """ world_instance = world.World.instance() redis_server = world_instance.redis captcha_manager = api.captcha.captcha_phone.CaptchaPhone(redis_server) jwt_cli = JWTToken() import django.db
302
107
#!/usr/bin/env python import os import sys import time import datetime import logging import subprocess logging.basicConfig(level=logging.INFO) log = logging.getLogger('dl') NOW = datetime.datetime.now() SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) DOWNLOAD_ROOT = os.getcwd() VERSION = '5.22-61.0' PANTHER...
6,552
2,275
# Copyright 2019 École Polytechnique Fédérale de Lausanne. 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 r...
2,572
723
import kivy from kivy.app import App from kivy.uix.tabbedpanel import TabbedPanelHeader from kivy.uix.tabbedpanel import TabbedPanel from kivy.uix.floatlayout import FloatLayout from kivy.uix.scrollview import ScrollView from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix....
6,423
2,642
import itertools from io import StringIO from queue import LifoQueue inputs = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2" #data = [int(v) for v in StringIO(inputs).read().split(' ')] data = [int(v) for v in open("day8.input").read().split(' ')] def parse_packet(idata, lifoq_children, tc_metadata): if not lifoq_childre...
1,943
715
import json import os import cv2 import numpy as np from dataset_utils.geometry import computeCameraCalibration def line_to_point(p1, p2, p3): return np.abs(np.cross(p2 - p1, p3 - p1, axis=2) / np.linalg.norm(p2 - p1, axis=2)) def get_pts(vid_dir, json_path): video_path = os.path.join(vid_dir, 'video.avi')...
2,971
1,271
#!/usr/bin/python2 import re import subprocess from ansible.module_utils.basic import AnsibleModule def get_procs(process_regex, cmdline_regex): cmd=["ps","-hax","-o","comm pid args"] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) output, error = process.communicate() lines = output.splitlines() pr...
1,292
441
"""@package modified_cholesky Function to perform the modified Cholesky decomposition. """ import numpy as np import numpy.linalg as la def modified_cholesky(a): """ Returns the matrix A if A is positive definite, or returns a modified A that is positive definite. :param np.array a: (n, n) The symmetric matr...
972
311
# -*- coding: utf-8 -*- """ Python Slack Bot docker parser class for use with the HB Bot """ import os import re DOCKER_SUPPORTED = ["image", "container", "help"] SUBCOMMAND_SUPPORTED = ["ls",] def docker_usage_message(): return ("I'm sorry. I don't understand your docker command." "I understand docker [%...
1,528
501
# Entregar arquivo com o código da função teste_cartela # # Verificador de cartela de bingo # # CRIAR UMA FUNÇÃO DO TIPO: # # def teste_cartela(numeros_bilhete,numeros_sorteados): #numeros_bilhete e numeros_sorteados tipo lista com valores inteiros # # ... # # return([bingo,n_acertos,p_acertos,[numeros_acertados],[nume...
1,713
901
from pymarkovchain_dynamic.MarkovChain import * from pymarkovchain_dynamic.DynamicMarkovChain import *
103
32
from transformers import GPTNeoForCausalLM, GPT2Tokenizer from fastapi import FastAPI import re import json from pydantic import BaseModel from typing import Optional import torch app = FastAPI() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") morph_path = './Model' morph_tokenizer = GPT2Toke...
3,033
1,100
(enrollment)= # Enrollment and Waitlist For Dartmouth students, you can track the enrollment status using the ORC timetable. The course is capped at 20 students to facilitate small group collaboration for the final data science project. Please fill out this Google form (while logged in via your Dartmouth email) if y...
504
164
import sys, getopt from zlib import adler32 from PIL import Image from rnd import Generator, sample Usage = """ python decode.py <password> <input image file> <output file> """ def bits(text): out = [] for c in text: n = ord(c) for _ in range(8): out.append(n&1) n >>= 1...
1,683
643
from django.shortcuts import render from .models import Member def index(request): """List all members """ advisors = Member.objects.filter(advisor=True) members = Member.objects.filter(advisor=False) context = {'mobile_title_page': 'Equipe', 'advisors': advisors, 'members': members...
379
110
#!/usr/bin/env python3 import sys import requests ping = sys.argv[1] pong = sys.argv[2] word = sys.argv[3] if not ping.startswith('http'): ping = 'http://' + ping if not pong.startswith('http'): pong = 'http://' + pong while True: r = requests.post(ping, data={'food': word}) answer = r.text if ...
447
167
from django import forms from .models import Comment, Rating, RatingStar class RatingForm(forms.ModelForm): star = forms.ModelChoiceField( queryset=RatingStar.objects.all(), widget=forms.RadioSelect(), empty_label=None ) class Meta: model = Rating fields = ('star'...
437
127
from textwrap import dedent import numpy as np import subprocess import sys import pytest @pytest.mark.slow def test_disabling_capturing(report_line): repeats = 3 code = dedent("""\ import time tic = time.time() import lumicks.pylake print(time.time() - tic) """) ...
527
187
#!/usr/bin/env python # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2013,2014,2017 Contributor # # 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...
3,433
961
import json import os from extra import MainStart import threading import moment from jinja2 import Environment, PackageLoader from sanic import Sanic, response from sanic.log import logger from termcolor import colored from conf import config from spider import bot env = Environment(loader=PackageLoad...
1,418
488
#! /usr/bin/env python """ Copyright (C) 2014 CompleteDB LLC. This program is free software: you can redistribute it and/or modify it under the terms of the Apache License Version 2.0 http://www.apache.org/licenses. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; with...
1,891
592
from flask import render_template, flash, send_from_directory, send_file from app.giturl_class.url_form import UrlForm from app.giturl_class.download_form import DownloadButton from app.giturl_class import bp import json import os USE_TEST_FILE = False if(os.getenv('SM2KG_TEST_MODE') == 'TRUE'): USE_TEST_FILE = ...
5,189
1,473
import platform from enum import Enum, unique @unique class Type(Enum): """Markdown type """ # Separation SEP = '\n' # Place holder NULL = "" SPACE = " " # Markdown single symbol H1 = "#" H2 = "##" H3 = "###" H4 = "####" H5 = "#####" H6 = "######" QUOTE = ...
681
287
from django.shortcuts import render, get_object_or_404 from django.core.exceptions import PermissionDenied from django.http import Http404 from .models import Course from ..mod.models import Moderator from ..files.models import File from ..decorators import login # Create your views here. @login def index(request)...
3,542
1,104
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-26 14:26 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Anime',...
1,134
343
#!/usr/bin/env python import math def read_input(path): with open(path) as file: reactions = [line.strip().split('=>') for line in file.readlines()] reactions2 = [[r[0].strip().split(","), r[1].strip()] for r in reactions] result = {} for reaction in reactions2: goal = ...
5,332
2,483
import time from actions import Action, action @action("sleep") class SleepAction(Action): def __init__( self, seconds, output="Waiting {{ seconds }} seconds before continuing ..." ): self.seconds = seconds self.output_format = output def _run(self): seconds = float(self....
471
133
from ..utils.kfrozendict import kfrozendict from ..utils.kfrozendict import kassertfrozen class ChoiceFilter: ROW_KEYS = { '1': ['choice_filter'], '2': ['choice_filter'], } EXPORT_KEY = 'choice_filter' @classmethod def in_row(kls, row, schema): return 'choice_filter' in ro...
1,262
404
''' Author: Marcel Miljak Klasse: 5aHEL - HTL Anichstraße Diplomarbeit: Entwicklung eines Hamster Roboters Jahrgang: 2021/22 ''' import time from time import sleep import RPi.GPIO as GPIO DIR_2 = 18 # Direction-Pin vom 2ten Modul DIR_1 = 24 # Direction-pin vom 1sten Modul STEP_1 = 25 # ...
3,878
1,561