text
string
size
int64
token_count
int64
#!/usr/bin/env python3 #https://codeforces.com/problemset/problem/1284/B #记录每个序列是否有上升,如果没有min.max是多少.. #n=1e5,还得避免O(N**2).. #上升情况分解 #情况1: sx+sy中sx或sy本身是上升的 #情况2: sx,sy都不上升,判断四个极值的情况(存在几个上升) #DP..增量计数; f(n+1)=f(n)+X; X=?? # 如果s本身上升,X=(2n+1) # 如果s本身不升,拿s的min/max去一个数据结构去检查(min/max各一个?)..(低于线性..binary search??) # .. def ...
1,278
673
"""Test hudjango.auth.decorator functionality."""
50
15
from apprentice.agents import SoarTechAgent from apprentice.working_memory import ExpertaWorkingMemory from apprentice.working_memory.representation import Sai # from apprentice.learners.when_learners import q_learner from ttt_simple import ttt_engine, ttt_oracle def get_user_demo(): print() print("Current Pl...
3,672
1,080
#!/usr/bin/env python """ @author : 'Muhammad Arslan <rslnrkmt2552@gmail.com>' """ import re import zlib import cv2 from scapy.all import * pics = "pictues" faces_dir = "faces" pcap_file = "bhp.pcap" def get_http_headers(http_payload): try: headers_raw = http_payload[:http_payload.index("\r\n\r\n")+2...
2,905
1,019
import unittest, sys, time sys.path.extend(['.','..','py']) import h2o_cmd, h2o, h2o_hosts, h2o_browse as h2b, h2o_import as h2i # Uses your username specific json: pytest_config-<username>.json # copy pytest_config-simple.json and modify to your needs. class Basic(unittest.TestCase): def tearDown(self): h...
1,536
524
# -*- coding: utf-8 -*- ''' @time: 2019/9/8 18:45 @ author: javis ''' import os class Config: # for data_process.py #root = r'D:\ECG' root = r'data' train_dir = os.path.join(root, 'ecg_data/') # test_dir = os.path.join(root, 'ecg_data/testA') # train_label = os.path.join(root, 'hf_round1_labe...
1,229
672
from behave import * import subprocess import os import boto3 @when("the stack config is changed") def step_impl(context): # Get config file path vpc_config_file = os.path.abspath(os.path.join( os.path.dirname(os.path.dirname(__file__)), "config", "test-env", "a", "vpc....
974
336
import cv2 import matplotlib.pyplot as plt import easyocr reader = easyocr.Reader(['en'], gpu=False) image = cv2.imread('results/JK_21_05/page_1.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) dilated = cv2.dilate(image, None, iterations=1) eroded = cv2.erode(image, None, iterations=1) res = reader.readtext(erod...
840
394
# model settings model = dict( type='Recognizer3D', backbone=dict(type='X3D', frozen_stages = -1, gamma_w=1, gamma_b=2.25, gamma_d=2.2), cls_head=dict( type='X3DHead', in_channels=432, num_classes=400, multi_class=False, spatial_type='avg', dropout_ratio=0.7, ...
874
351
from typing import TypeVar, Optional def ceildiv(n: int, d: int) -> int: return -(-n // d) T = TypeVar("T") def coalesce(*args: Optional[T]) -> T: if len(args) == 0: raise TypeError("coalesce expected >=1 argument, got 0") for arg in args: if arg is not None: return arg ...
372
125
from djitellopy import Tello import cv2, math import numpy as np import jetson.inference import jetson.utils from threading import Thread import time net = jetson.inference.detectNet("ssd-mobilenet-v1", threshold=0.5) #facenet is working; ssd-mobilenet-v1 drohne = Tello() drohne.connect() print(drohne.get_battery()) ...
1,589
776
from PyQt5.QtCore import QAbstractTableModel, QAbstractItemModel from PyQt5.QtCore import Qt, QModelIndex, pyqtSlot class LoadTypesProcess(QAbstractTableModel): def __init__(self): super().__init__() self.csv_values = [] self.header_model = HeaderModel() def index(self, row, column, p...
3,638
1,051
#!/usr/bin/env python # mix of: # https://www.programcreek.com/python/example/88577/gi.repository.Gst.Pipeline # https://github.com/GStreamer/gst-python/blob/master/examples/helloworld.py # http://lifestyletransfer.com/how-to-launch-gstreamer-pipeline-in-python/ import sys import collections from pprint import pprint...
3,752
1,371
# -*- coding: utf-8 -*- u"""Test simulationSerial :copyright: Copyright (c) 2016 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest pytest.importorskip('srwl_bl') #: Used for a sanity check o...
3,464
1,206
import unittest from kubragen import KubraGen from kubragen.jsonpatch import FilterJSONPatches_Apply, ObjectFilter, FilterJSONPatch from kubragen.provider import Provider_Generic from kg_nodeexporter import NodeExporterBuilder, NodeExporterOptions class TestBuilder(unittest.TestCase): def setUp(self): s...
1,306
401
import os import json import time import torch # Called when the deployed service starts def init(): global model global device # Get the path where the deployed model can be found. model_filename = 'obj_segmentation.pkl' model_path = os.path.join(os.environ['AZUREML_MODEL_DIR'], model_filename) ...
1,349
408
# Copyright 2014, Doug Wiegley, A10 Networks. # # 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 appli...
5,023
1,644
#coding:utf-8 # 数据库结构体 class DataBase: url = "" port = 3306 username = "" password = "" database = "" charset = "" # 测试用例信息结构体 class CaseInfo: path = "" case_list = [] # 测试用例结构体 class Case: url = "" db_table = "" case_id = "" method = "" data = {} c...
388
163
# Copyright 2012 James McCauley # # 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 writi...
2,000
668
channels1 = { "#test1": ("@user1", "user2", "user3"), "#test2": ("@user4", "user5", "user6"), "#test3": ("@user7", "user8", "user9") } channels2 = { "#test1": ("@user1", "user2", "user3"), "#test2": ("@user4", "user5", "user6"), "#test3": ("@user7", "...
850
297
from __future__ import unicode_literals from __future__ import absolute_import, division, print_function """ This module contains (and isolates) logic used to find entities based on entity type, list selection criteria and search terms. """ __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 20...
20,989
6,052
from mss import mss from PIL import Image def screengrab(monitor=0, output="screenshot.png"): """ Uses MSS to capture a screenshot quickly. """ sct = mss() monitors = sct.enum_display_monitors() scale = 1 game_x = 300*scale game_y = 300*scale mon_x = monitors[monitor]["left"] mon_y = ...
3,029
1,107
#encoding=utf8 from starflyer import Handler, redirect, asjson from camper import BaseForm, db, BaseHandler from camper import logged_in, is_admin from wtforms import * from sfext.babel import T from camper.handlers.forms import * import werkzeug.exceptions from bson import ObjectId from camper.handlers.images import ...
3,829
1,112
import argparse import h5py import sys import os from savu.version import __version__ class NXcitation(object): def __init__(self, description, doi, endnote, bibtex): self.description = description.decode('UTF-8') self.doi = doi.decode('UTF-8') self.endnote = endnote.decode('UTF-8') ...
4,210
1,331
#! /home/drcl_yang/anaconda3/envs/py36/bin/python from pathlib import Path import sys FILE = Path(__file__).absolute() sys.path.append(FILE.parents[0].as_posix()) # add code to path path = str(FILE.parents[0]) import numpy as np from sympy import Symbol, solve import time import roslib import rospy from std_msgs...
25,124
9,714
import time import pymysql # for pulling UCSC data import pandas as pd from pathlib import Path import logging # app from .progress_bar import * # tqdm, context-friendly LOGGER = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) logging.getLogger('numexpr').setLevel(logging.WARNING) # these login st...
14,697
4,714
import sys, json # simple JSON echo script for line in sys.stdin: print json.dumps(json.loads(line))
104
36
# encoding: utf-8 """ @author: BrikerMan @contact: eliyar917@gmail.com @blog: https://eliyar.biz @version: 1.0 @license: Apache Licence @file: test.py.py @time: 2019-01-25 14:43 """ import unittest from tests import * from kashgari.utils.logger import init_logger init_logger() if __name__ == '__main__': unittes...
329
143
import functools @functools.total_ordering class Text: def __init__(self, id: int, text: str): self.id = id self.text = text def __eq__(self, other): return self.id == other.id and self.text == other.text def __lt__(self, other): return (self.id, self.text) < (other.id, ot...
536
183
from models.DecisionTree import DecisionTree class Forest: def __init__(self, hyper_parameters, training_set): """ Inicializa a floresta com suas árvores. :param hyper_parameters: dictionary/hash contendo os hiper parâmetros :param training_set: dataset de treinamento """ ...
1,661
462
class BaseAnsiblerException(Exception): message = "Error" def __init__(self, *args, **kwargs) -> None: super().__init__(*args) self.__class__.message = kwargs.get("message", self.message) def __str__(self) -> str: return self.__class__.message class CommandNotFound(BaseAnsiblerEx...
912
281
# -*- coding: utf-8 -*- from django.test import TestCase, Client from models import Contato import json class TestCase(TestCase): """ Realiza o teste utilizando request a API e avaliando seu retorno """ def setUp(self): self.c = Client() def test_contato_api(self): """ te...
2,358
790
from itertools import count, tee class Bouncy: def __init__(self, porcentage): """ print the number bouncy :type porcentage: int -> this is porcentage of the bouncy """ nums = count(1) rebound = self.sum_number(map(lambda number: float(self.is_rebound(number)), coun...
2,073
578
#!/usr/bin/env python import sys from deiis.rabbit import Message, MessageBus from deiis.model import Serializer, DataSet, Question if __name__ == '__main__': if len(sys.argv) == 1: print 'Usage: python pipeline.py <data.json>' exit(1) # filename = 'data/training.json' filename = sys.argv...
909
286
""" Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. """ __author__ = 'Danyang' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution:...
1,100
360
from menu_item import MenuItem # Move the code above to menu_item.py # Import the MenuItem class from menu_item.py menu_item1 = MenuItem('Sandwich', 5) print(menu_item1.info()) result = menu_item1.get_total_price(4) print('Your total is $' + str(result))
259
93
def make_list(element, keep_none=False): """ Turns element into a list of itself if it is not of type list or tuple. """ if element is None and not keep_none: element = [] # Convert none to empty list if not isinstance(element, (list, tuple, set)): element = [element] elif isinstan...
398
112
import tkinter as tk class View(): def __init__(self): window = tk.Tk() self.frame = tk.Frame(master=window, width=200, height=200) self.frame.pack() def show_grid(self, grid): for i in range(4): for j in range(4): label = tk.Label(master=self.frame,...
392
141
__author__ = 'pavelkosicin' from model.label import Label def test_create_record_label(app): app.label.create_recording_artist(Label(name="rl_#1", asap="WB86-8RH31.50UTS-J", note="Mens autem qui est in festinabat non facere bonum, voluntas in malo reperit."))
310
112
import numpy as np def eval_rerr(X, X_hat, X0=None): """ :param X: tensor, X0 or X0+noise :param X_hat: output for apporoximation :param X0: true signal, tensor :return: the relative error = ||X- X_hat||_F/ ||X_0||_F """ if X0 is not None: error = X0 - X_hat return np.linalg....
583
245
# License: BSD Style. from ...utils import verbose from ..utils import _data_path, _data_path_doc, _get_version, _version_doc @verbose def data_path(path=None, force_update=False, update_path=True, download=True, verbose=None): """ Get path to local copy of visual_92_categories dataset. .....
2,208
666
"""helpers module """ import json import pcap import yaml def get_adapters_names(): """Finds all adapters on the system :return: A list of the network adapters available on the system """ return pcap.findalldevs() def config_loader_yaml(config_name): """Loads a .yml configuration file :p...
1,131
327
#Evaludador de numero primo #Created by @neriphy numero = input("Ingrese el numero a evaluar: ") divisor = numero - 1 residuo = True while divisor > 1 and residuo == True: if numero%divisor != 0: divisor = divisor - 1 print("Evaluando") residuo = True elif numero%divisor == 0: residuo = False if residu...
428
170
#!/usr/bin/env python __author__ = "Mageswaran Dhandapani" __copyright__ = "Copyright 2020, The Spark Structured Playground Project" __credits__ = [] __license__ = "Apache License" __version__ = "2.0" __maintainer__ = "Mageswaran Dhandapani" __email__ = "mageswaran1989@gmail.com" __status__ = "Education Purpose" impo...
2,364
776
import spacy def find_entities(input_phrase, language): models = { 'en': 'en_core_web_sm', 'pl': 'pl_core_news_sm', 'fr': 'fr_core_news_sm', 'de': 'de_core_news_sm', 'it': 'it_core_news_sm', } if language in models: nlp = spacy.load(models[language]) doc = nlp(input_phrase)...
737
264
# Python programming that returns the weight of the maximum weight path in a triangle def triangle_max_weight(arrs, level=0, index=0): if level == len(arrs) - 1: return arrs[level][index] else: return arrs[level][index] + max( triangle_max_weight(arrs, level + 1, index), triangle_ma...
488
172
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
1,114
301
# -*- coding:utf-8 -*- # Usage : python ~~.py import sys import os import pickle import collections import pandas as pd import numpy as np from itertools import chain from itertools import combinations from itertools import compress from itertools import product from sklearn.metrics import accuracy_score from multiproc...
4,687
1,537
#!python3.6 import difflib from pprint import pprint import sys text1 = ''' 1. Beautiful is better than ugly. 2. Explicit is better than implicit. 3. Simple is better than complex. 4. Complex is better than complicated. '''.splitlines(keepends=True) text2 = ''' 1. Beautiful is better than ugly. 3. Simple i...
591
191
from directory_forms_api_client.actions import PardotAction from directory_forms_api_client.helpers import Sender from django.conf import settings from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.urls import reverse, reverse_lazy from django.utils.decorators import method_d...
5,703
1,738
import unicodedata import warnings import logging import re import argparse import sbol3 import openpyxl import tyto from .helper_functions import toplevel_named, strip_sbol2_version, is_plasmid, url_to_identity, strip_filetype_suffix from .workarounds import type_to_standard_extension BASIC_PARTS_COLLECTION = 'Basi...
25,138
7,594
""" Test runner for the JSON Schema official test suite Tests comprehensive correctness of each draft's validator. See https://github.com/json-schema-org/JSON-Schema-Test-Suite for details. """ import sys from jsonschema import ( Draft3Validator, Draft4Validator, Draft6Validator, Draft7Validator, ...
5,921
1,904
import copy import json import os from collections import UserDict from signalworks.tracking import Event, Partition, TimeValue, Value, Wave class MultiTrack(UserDict): """ A dictionary containing time-synchronous tracks of equal duration and fs """ def __init__(self, mapping=None): if mappi...
8,635
2,500
from .contact_helper import ContactHelper
41
9
import cv2 import matplotlib.pyplot as plt import glob import os filepath ="afm_dataset4/20211126/" files = [line.rstrip() for line in open((filepath+"sep_trainlist.txt"))] files = glob.glob("orig_img/20211112/*") def variance_of_laplacian(image): # compute the Laplacian of the image and then return the focus # me...
1,676
731
import os def check_path(path): if not path or not path.strip() or os.path.exists(path): return os.makedirs(path) pass
139
48
#!/usr/bin/env python # *-* coding: UTF-8 *-* """Solutia problemei Cursor""" DIRECTIONS = {" stanga ": [-1, 0], " dreapta ": [1, 0], " jos ": [0, -1], " sus ": [0, 1]} def distanta(string, pozitie): """Determinarea distantei""" directie, valoare = string.split() directie = direct...
1,027
405
from django.db import models import datetime from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.core.validators import MaxValueValidator, MinValueValidator class Hoods(models.Model): name = models.CharField(max_length = 100) location = mode...
1,932
593
# Author: Pan Fan, Chun Chieh Chang, Sakshi Jain # Date: 2020/11/27 """Compare the performance of different classifier and train the best model given cross_validate results . Usage: src/clf_comparison.py <input_file> <input_file1> <output_file> <output_file1> Options: <input_file> Path (including filename and fil...
5,710
1,888
import torch.nn as nn import params as P import hebbmodel.hebb as H class Net(nn.Module): # Layer names FC = 'fc' CLASS_SCORES = FC # Symbolic name of the layer providing the class scores as output def __init__(self, input_shape=P.INPUT_SHAPE): super(Net, self).__init__() # Shape of the tensors that we ...
1,294
497
""" The :mod:`pure_sklearn.feature_extraction` module deals with feature extraction from raw data. It currently includes methods to extract features from text. """ from ._dict_vectorizer import DictVectorizerPure from . import text __all__ = ["DictVectorizerPure", "text"]
275
81
#------------------------------------------------------------------------------- # Uppod decoder #------------------------------------------------------------------------------- import urllib2 import cookielib def decode(param): try: #-- define variables loc_3 = [0,0,0,0] ...
3,887
1,784
import numpy as np from matplotlib import pyplot as plt import pandas as pd from Eir.DTMC.spatialModel.randomMovement.randMoveSIRD import RandMoveSIRD from Eir.utility import Person1 as Person class RandMoveSIRDV(RandMoveSIRD): """ An SIRDV model that follows the Random Movement Model. When the individuals...
11,796
3,549
from localtalk import create_app, create_server app = create_app() server = create_server() # server.start() if __name__ == '__main__': app.run(debug=True, host='localhost')
183
64
import glob import os import numpy as np import nibabel as nb import argparse def get_dir_list(train_path): fnames = glob.glob(train_path) list_train = [] for k, f in enumerate(fnames): list_train.append(os.path.split(f)[0]) return list_train def ParseData(list_data): ''' Creates a...
3,087
1,189
try: from django.urls import include, re_path except ImportError: from django.conf.urls import include, url as re_path urlpatterns = [ re_path(r'^podcast/', include('podcast.urls', namespace='podcast')), ]
220
73
from collections import Iterable class BaseManager(object): # you must initialise self.resource_env in __init__ fields = None class Meta: abstract = True def _is_iterable(self, ids): if isinstance(ids, str) or not isinstance(ids, Iterable): ids = [ids, ] return ...
2,246
706
#moduleForShowingJudges #cmd /K "$(FULL_CURRENT_PATH)" #cd ~/Documents/GitHub/Keyboard-Biometric-Project/Project_Tuples #sudo python -m pip install statistics #python analyzeData.py """ Author: Zachary Nowak and Matthew Nowak Date: 3/09/2018 Program Description: This code can record the Press Time and Flight Time of...
2,070
741
from dcstats import * from _version import __version__
55
16
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: ## By passing the case if empty linked list if not he...
1,081
251
import unittest def get_formatted_name(first, last, middle = ""): """生成整洁的姓名""" if middle: full_name = f"{first} {middle} {last}" else: full_name = f"{first} {last}" return full_name.title() class NamesTestCase(unittest.TestCase): #创建一个测试类,继承于unittest.TestCase 这样才能Python自动测试 """测试...
973
485
import requests as r from collections import defaultdict class session(): req = {"jsonrpc": "2.0", "id": 1} sid = None def __init__(self, server='http://raspisanie.admin.tomsk.ru/api/rpc.php'): self.server = server self.sid = self.request("startSession")['sid'] def reques...
2,350
768
from __future__ import unicode_literals from django.db import models from hospital.models import Hospital # Create your models here. class Donor(models.Model): name = models.CharField(max_length = 200) username = models.CharField(max_length = 200) password = models.CharField(max_length = 200) gender =...
785
259
from unittest import TestCase from lf3py.test.helper import data_provider from tests.helper.example.flowapi import perform_api class TestHandler(TestCase): @data_provider([ ( { 'path': '/models', 'httpMethod': 'GET', 'headers': {}, ...
763
197
'''Trains a simple convnet on the MNIST dataset. Does flat increment from T. Xiao "Error-Driven Incremental Learning in Deep Convolutional Neural Network for Large-Scale Image Classification" Starts with just 3 classes, trains for 12 epochs then incrementally trains the rest of the classes by reusing the trained we...
7,651
2,644
import torch import torch.nn as nn from loss_fn import contrastive_loss import config class HybridLoss(nn.Module): def __init__(self, alpha=0.5, temperature=0.07): super(HybridLoss, self).__init__() self.contrastive_loss = contrastive_loss.SupConLoss(temperature) self.alpha = alpha def cross_entropy_one_...
717
281
# Copyright 2016 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
2,815
879
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('history', '0006_committeemember_member'), ] operations = [ migrations.AlterField( model_name='meetingminutes', ...
606
209
## Author: Victor Dibia ## Web socket client which is used to send socket messages to a connected server. import websocket import time import json from websocket import WebSocketException, WebSocketConnectionClosedException import sys #import _thread as thread import websocket ws = websocket.WebSocket() retry_thresh...
1,521
436
def get_span_and_trace(headers): try: trace, span = headers.get("X-Cloud-Trace-Context").split("/") except (ValueError, AttributeError): return None, None span = span.split(";")[0] return span, trace
233
74
from anndata import AnnData import numpy as np import pandas as pd from scipy.sparse import csr_matrix from joblib import delayed from tqdm import tqdm import sys import igraph from .utils import ProgressParallel from .. import logging as logg from .. import settings def pseudotime(adata: AnnData, n_jobs: int = 1, ...
8,085
2,732
# coding=utf-8 # Copyright 2021 The OneFlow 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 require...
6,786
1,928
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import pytest from ....testing import example_data from ...niftyreg import get_custom_path from ...niftyreg.tests.test_regutils import no_nifty_tool from .. import FillLesions @pytest.mark.skipif(no_nif...
1,198
434
def init_actions_(service, args): """ this needs to returns an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'test': ['install'] } de...
2,358
613
from fastapi.testclient import TestClient import os import sys sys.path.append("..") from libs.config_engine import ConfigEngine from api.config_keys import Config from api.processor_api import ProcessorAPI import pytest config_path='/repo/config-coral.ini' config = ConfigEngine(config_path) app_instance = ProcessorA...
1,297
418
from os import path from setuptools import find_namespace_packages, setup this_directory = path.abspath(path.dirname(__file__)) with open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name='lambda-learner', namespace_packages=['linkedin'], version='0.0.1', long_description...
1,353
446
from django.core.serializers.json import DjangoJSONEncoder class CallableJSONEncoder(DjangoJSONEncoder): def default(self, obj): if callable(obj): return obj() return super().default(obj)
222
63
import abc import enum import json import pickle import time import Famcy import _ctypes import os import datetime from flask import session from werkzeug.utils import secure_filename # GLOBAL HELPER def get_fsubmission_obj(parent, obj_id): """ Inverse of id() function. But only works if the object is not garbage col...
9,563
3,483
from crispy_forms import layout from crispy_forms.helper import FormHelper from django.conf import settings from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django import forms from .models import UserProfile class RegisterForm(UserCreationForm): username = forms.Ch...
1,982
545
import sys import os from multiprocessing import Process, Queue, Manager from threading import Timer from wadi_harness import Harness from wadi_debug_win import Debugger import time import hashlib def test(msg): while True: print 'Process 2:' + msg #print msg def test2(): print 'Process 1' tim...
3,187
1,502
# -*- coding: utf-8 -*- """ Independent model based on Geodesic Regression model R_G """ import torch from torch import nn, optim from torch.autograd import Variable from torch.utils.data import DataLoader import torch.nn.functional as F from dataGenerators import ImagesAll, TestImages, my_collate from axisAngle impo...
7,720
2,948
# from django.shortcuts import render, redirect, get_object_or_404 from .forms import CharacterForm from rick_and_morty_app.models import Character from django.views.generic import ListView, CreateView, UpdateView, DetailView, DeleteView from django.urls import reverse_lazy # new # Create your views here. class HomeP...
1,033
289
import os, sys def mrcnnPath(): filePath = os.path.dirname(os.path.realpath(__file__)) return os.path.abspath(os.path.join(filePath, os.pardir, os.pardir)) def currentFilePath(file=None): file = file if file else __file__ return os.path.dirname(os.path.realpath(file)) def mrcnnToPath(): sys.path....
339
128
from __future__ import print_function import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) from event_extractor.dataprocess import data_loader from event_extractor.train.eval import evaluate import importlib import time class TrainProcess(object): def __i...
6,840
2,292
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
3,298
971
''' data_handler.py ''' import os from sorter.lib.db import DB from sorter.lib.book_utils import get_by_id, get_by_isbn from sorter.lib.parse_xml import parse_isbn13_response, parse_id_response def store_data(books, db_file): ''' Store the book data in the provided database ''' database = DB(db_file) ...
3,114
1,023
#!/usr/bin/python3 '''Prepare Filelists for Semantic3D Segmentation Task.''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import logging import os import math import pathlib import random import argparse from datetime import datetime from logger import ...
3,054
985
""" Computer system. Scripts related to the class CIM_ComputerSystem. """ import sys import socket import lib_util # This must be defined here, because dockit cannot load modules from here, # and this ontology would not be defined. def EntityOntology(): return ( ["Name"], ) import lib_common from lib_properties...
7,382
2,594
cidade = str(input('Qual é o Nome da sua Cidade ?: ')).strip() print('Sua cidade possui o nome Santo?',cidade[:5].upper() == 'SANTO')
133
48
import pathlib import urlpath def loading(store=None): if store is None: raise ValueError('data store not specified') if store == 'gs': base = urlpath.URL('gs://') elif store == 'az': base = urlpath.URL('https://carbonplan.blob.core.windows.net') elif store == 'local': ...
391
123