text
stringlengths
38
1.54M
import lunzi.nn as nn from lunzi.nn import Tensor import tensorflow as tf import numpy as np from td3.policies.actor import Actor from td3.policies.critic import Critic class TD3(nn.Module): def __init__(self, dim_state, dim_action, actor: Actor, critic: Critic, gamma: float, actor_lr: float, cri...
import logging from .packet import DHCPPacket log = logging.getLogger(__name__) class DHCPProtocol: def connection_made(self, transport): self.transport = transport def datagram_received(self, data, addr): #message = data.decode() packet = DHCPPacket(data) log.debug('RECV fr...
import pickle import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.model_selection import GridSearchCV from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import matplotlib.pyplot as plt imp...
from pyparsing import ( alphas, alphanums, LineEnd, LineStart, nums, Word, ZeroOrMore, ) region_identifier = Word(alphanums + '_') region_start = (LineStart() + '@region $ ' + region_identifier.setResultsName('region_identifier') + '{' + LineEnd()) region_end = LineStart() + '}' + Lin...
""" Módulo Collections - Counter (contador) Collections -> High-performance Container Datatypes - Recebe um iteravel como parâmetro e cria um objeto do tipo Collections Counter que é parecido com um dicionário, contendo como chave o elemento da lista passada como parâmetro e como valor a quantidade de ocorrências des...
from django.contrib.sitemaps import Sitemap from askapp.models import Thread, User from django.template.defaultfilters import slugify class ThreadSitemap(Sitemap): """ This class generates sitemap subset for thread URLs https://docs.djangoproject.com/en/1.8/ref/contrib/sitemaps/#sitemap-classes """ ...
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # Licensed under the Apache License, Version 2.0 (t...
# -*- coding: utf-8 -*- import json import sqlite3 from flask import Flask, request, g app = Flask(__name__, static_folder="./html", static_url_path="") @app.route("/config", methods=["GET", "POST"]) def get_config(): cur = g.db.cursor() if request.method == "POST": config = request.json if n...
#Caso de prueba 1 #Se inicializan las siguientes entidades (tablas) : XXX, XXX, XXX, ... #Se prueban la(s) siguiente(s) funcionalidad(es): utilización de prioridades, fijación de proyectos, algoritmo de asignación en general. from pony.orm import * from database import db import Employees.features as Ef, Employees.usua...
import logging logging.basicConfig(level=logging.INFO) from fuel.datasets import TextFile from fuel.streams import DataStream from fuel.schemes import ConstantScheme from fuel.transformers import Batch, Padding, SortMapping, Unpack, Mapping import cPickle as pickle import numpy as np import random logger = logging.getL...
import os import re from jinja2.environment import Environment from jinja2.loaders import DictLoader def test_filters_deterministic(tmp_path): src = "".join(f"{{{{ {i}|filter{i} }}}}" for i in range(10)) env = Environment(loader=DictLoader({"foo": src})) env.filters.update(dict.fromkeys((f"filter{i}" for...
import unittest class AngleCalc: def boundTo180(self,angle): angle = angle%360 if angle >=0 else angle%-360 if (angle <= -180): angle += 360 elif (angle > 180): angle -= 360 return angle def IsAngleBetween(self,first_angle,middle_angle,second_angle): angle_diff1 = mid...
__author__ = 'fumandito' def is_int(x): return x == int(round(x, 0)) print is_int(7.0) # True print is_int(7.5) # False print is_int(-1) # True
# -*- coding: utf-8 -*- from PyQt5 import QtCore, QtGui,QtWidgets # from PyQt5.QtWidgets import QApplication,QDialog, # from PyQt5.QtWidgets import QDialog try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtWidgets.QApplicatio...
import face_recognition as fr import os import fnmatch import datetime as dt import numpy as np import pickle import cv2 import multiprocessing as ml import faceRecognition as fr import frameLoader as fl import calibrateCamera as calibr import db import variables as var import functions as funcs def ge...
def is_Chinese(word): for ch in word: if '\u4e00' <= ch <= '\u9fff': return True return False """ 处理策略的模块 """ import json from bs4 import BeautifulSoup import requests from akamx.lujing import lujings # from akamx.jisuan import Cl_score from akamx.cljiusan import Cl_score cl_score = Cl_scor...
from unittest import TestCase import address_compare.parsers as parse import address_compare.comparers as comp class TestNaive_parse(TestCase): def test_naive_parse(self): self.assertEqual(parse.naive_parse("a b c"), ["a", "b", "c"]) self.assertEqual(parse.naive_parse("A b c", tolower=True), ["a",...
import MySQLdb as mdb import socket def connectDB(): try: conn = mdb.connect(host='127.0.0.1', user='root', passwd='', db='music', charset='utf8') print "connet success" return conn ...
from ..base_app1_api import BaseApp1API class Page1(BaseApp1API): def page1_test_api(self): print('hello page1')
from django.urls import path from . import views urlpatterns = [ path("", views.index,name ="ShopName"), path("about/", views.about,name ="AboutUs"), path("contect/", views.contect,name ="contect"), path("tracker/", views.tracker,name ="TrackingStatus"), path("search/", views.search,name ="Search"),...
def cent(n): cents = [1, 5, 10, 25] coinway = [0] * (n + 1) coinway[0] = 1 for coin in cents: for i in range(1, n + 1): if i >= coin: coinway[i] += coinway[i - coin] return coinway[n] print cent(10)
# # The Multiverse Platform is made available under the MIT License. # # Copyright (c) 2012 The Multiverse Foundation # # 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 restrict...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 2 16:04:17 2020 @author: yochai_yemini """ import torch import data.utils as utils import networks.model_dss import networks.model import pathlib import pickle import numpy as np import scipy.io import soundfile as sf import argparse import matplo...
from django.urls import path from . import views urlpatterns = [ path("", views.getLandingPage, name="landingPage"), path("categories/", views.getCategoriesPage, name="CategoriesPage"), path("about-us/", views.getAboutUsPage, name="aboutUs"), path("category/<str:category_name>", views.getQuizP...
import os import sys from constantsMeta import * def flagString(flags): returnString = "" for i in flags: returnString += i + " " return returnString def simulationCommand(fileName, inPath, outPath, flags): lastPartOfCommand = " " + inPath if not "-v" in flags: lastPartOfCommand = " -f " + outPath + lastP...
#common divisors of 100 #100-100 50 25 20 10 5 4 2 n=100 i=n while i>=2: if n%i==0: print (i,end=' ') i=i-1 #output-->2 4 5 10 20 25 50 100 n=100 i=2 while i<=100: if n%i==0: print(i) i+=1 #common divisors of two numbers #100=2 4 5 10 20 25 50 100 #50 = 2 5...
import sys import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) while True : GPIO.setup(33, GPIO.OUT) time.sleep(0.1) GPIO.setup(33, GPIO.IN) print(GPIO.input(33)) if GPIO.input(33) == 0: print("Say Hi") else : print("hij doet t niet") time.sleep(0.1)
from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException, InvalidSelectorException, \ TimeoutException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from utilities.readpr...
#!/bin/env python # encoding: utf-8 """ https://leetcode.com/problems/integer-to-roman/description/ """ roman_numbers = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, } class Solution(object): def intToRoman(self, num): """ :type num: int :r...
f = open('/Users/jacquelineabalo/Documents/B-large.in'); lines = f.readlines(); target = open('/Users/jacquelineabalo/Documents/blargeresult.txt', 'w'); for i in range(1, len(lines)): flips = 0; pancakes = lines[i].strip(); if pancakes[0]=='+': sign = 1; else: sign = 0; j = 0; w...
from collections import namedtuple H4 = 'html4' # only in html4 H5 = 'html5' # only in html5 HB = 'both' # allowed in both N = 'normal' # has a closing tag E = 'empty' # doesn't have a closing tag ES = namedtuple('ES', 'tag, standard, type_, info') ER = namedtuple('ES', 'tag, info') HTML_ELEMENTS = [ ES("ht...
## # File: RepoLoadExec.py # Date: 15-Mar-2018 jdw # # Execution wrapper -- repository database loading utilities -- # Updates: # # 21-Mar-2018 - jdw added content filters and separate collection for Bird chemical components # 22-May-2018 - jdw add replacment load type, add options for input file paths # ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dummy = ListNode(next=head) offset = dummy ...
import json from pathlib import Path from typing import List, Literal, Optional import numpy as np import scipy from pynwb import NWBFile, TimeSeries from ....basetemporalalignmentinterface import BaseTemporalAlignmentInterface from ....tools.audio import add_acoustic_waveform_series from ....tools.nwb_helpers import...
from flask import render_template,request, make_response, send_from_directory from app import app from pandas import Series, DataFrame import pandas as pd import numpy as np import os import sys sys.path.append("/Users/cv/DS/Insight/class/Project_crime/program_analyze_data") #import compute_crime_risk as ccr import c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 6 02:56:04 2018 @author: oscar """ import pygmo as po import numpy as np import myUDP import time import datetime generations = 500 sizePop = 25 pathsave = '/Users/p277634/python/kaoModel/optimResult/' #pathsave = '' filenameTXT = 'sad...
from saitama_data.lib.read_config import config from saitama_data.datasetup.models.master.id_master.model import IdMaster from saitama_data.datasetup.models.master.id_master._2018.seed import MasterId, SeitoInfo2018, IdMaster2016 from saitama_data.datasetup.models.info import ClassIdSchoolId IdMaster2020 = IdMaster2016...
from django.shortcuts import render from django.urls import reverse # Create your views here. def index(request): return render(request, "birthdaycountdown/index.html", { })
import hou from PySide2 import QtWidgets, QtGui class ReferenceButtons(QtWidgets.QWidget): def __init__(self, *args, **kwargs): super(ReferenceButtons, self).__init__() self.dpifactor = 2 if kwargs['highdpi'] else 1 self.initUI() def initUI(self): self.layout = QtWidgets.QVBo...
import sys import numpy from random import randint as ri from copy import deepcopy VOCAB = 29 # print out usage info def usage(): print("Usage: need 2 argument as matrix length and message", file=sys.stderr) # find the modular multiplicative inverse of 'a' under modulo 'm' def mod_inverse(a, m): a = a % m ...
#!/usr/bin/env python # coding: utf-8 # In[14]: from binance.client import Client from datetime import datetime import time import math import pandas as pd class Point: def __init__(self, x, y): self.x = x self.y = y client = Client('', '') tickers = client.get_all_tickers() BTC_pairs = [] ...
from tkinter import * import cv2 from PIL import Image, ImageTk def show_frame(): # Vì Tkinter không hỗ trợ hàm imshow giống như opencv nên phải show qua nhiều giai đoạn thông qua label. ret, frame = cap.read() # Đọc frame từ camrera frame = cv2.flip(frame, 1) # flip: hàm xoay ngược, lật ảnh , gồm có : -1, ...
import logging import soundcloud import requests import tempfile import os from sady.store import Track from sady import config import asyncio logging.getLogger("requests").setLevel(logging.WARNING) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) CHUNK_SIZE = 512 * 1024 class Gateway(o...
import sqlite3,os class Connect: def connect(self): if not os.path.exists('kitab.db'): import createDb self.db = sqlite3.connect("kitab.db") def getBuyers(self,buyerId=None): self.connect() data = [] if not buyerId: cursor = self.db.execute("SELECT * FROM buyers") else: cursor = self.db.execute("...
import pandas as pd from sklearn.externals import joblib X_test = pd.read_csv('data/X_test.csv', sep=';').drop([ 'max_ordered_per_material', 'min_ordered_per_material', 'max_ordered_per_material_and_org', 'count_ordered_per_material', 'count_ordered_per_material_and_org', 'min_ordered_per_mate...
import sys arr = map(int, raw_input().strip().split(' ')) arr.sort(cmp=None, key=None, reverse=False) min=0 max=0 min_arr=arr[0:4] max_arr=arr[1:5] for i in min_arr: min=min+i for i in max_arr: max=max+i print(str(min)+" "+str(max))
# - DESCREVENDO O DESAFIO print('84 - Aprimore o desafio 93 para que ele funcione com vários jogadores ',end='') print('incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador') print() #INICIALIZANDO O PROGRAMA # IMPORTA BIBLIOTECAS # 1 - RECEBE DADOS j...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from django.contrib import admin from .models import ( Indicator, IndicatorType, Objective, StrategicObjective, ReportingPeriod, ReportingFrequency, CollectedData, Level, ActivityTable, DisaggregationType, DisaggregationLabel, DisaggregationValue, ExternalService,...
import json import numpy as np from sklearn.base import BaseEstimator from senti.utils.sklearn_ import EmptyFitMixin __all__ = ['ExternalModel'] class ExternalModel(BaseEstimator, EmptyFitMixin): def __init__(self, docs_to_path): self.docs_to_path = docs_to_path def predict(self, docs): w...
from django.db import models class Predictions(models.Model): apartment = models.ForeignKey( to="Apartment", null=True, on_delete=models.SET_NULL ) predicted_price = models.DecimalField(max_digits=40, decimal_places=2, null=False) accurate_price = models.BooleanField(null=True) class Meta...
from flask import Flask, make_response, jsonify, request, Blueprint, json, abort from app.v2.views.mainview import thisapi, response from app.v2.models.usersmodel import Users import os import jwt from app.v2 import validations from app.v2 import modelfunctions from app.v2.modelfunctions import Usermethods, Officemetho...
def decor(num): def inner(): a = num() print("======") return a return inner @decor def num(): return 10 # result_fun = decor(num) # print(result_fun()) print(num())
import normalize_with_prism_invariant as norm import viability_normalization as viability import zscore import os import glob import distil def log_normalize_all(proj_dir, search_pattern = '*', assemble_folder='assemble', out_folder='normalize'): #Invariant Normalize everything in project directory for folder...
# Generated by Django 2.1.7 on 2019-03-15 16:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("invoices", "0019_invoice_recipient_denomination")] operations = [ migrations.AlterField( model_name="sender", name="code", ...
import matplotlib.pyplot as plot import matplotlib.pyplot as plt class contour(): # Class for the shapes lineType = '' start = [] end = [] def __init__(self,listA,listB,name): self.start = listA self.end = listB self.lineType = name class sheet(): # Sheet size x =...
import bpy from cgl.plugins.blender import lumbermill as lm class CleanupScene(bpy.types.Operator): """ This class is required to register a button in blender. """ bl_idname = 'object.cleanup_scene' bl_label = 'Cleanup Scene' assetName = bpy.props.StringProperty() # @classmethod #...
def autoexec_warn_clear(): '''Ignore autoexec warning ''' pass def execute_preset(filepath="", menu_idname=""): '''Execute a preset :param filepath: filepath :type filepath: string, (optional, never None) :param menu_idname: Menu ID Name, ID name of the menu this was called from ...
try: class Season: def __init__(self): self.id = None self.username = None self.user_ID = None except Exception as e: print(e)
''' Wypisz zawartosc katalogu oraz podkatalogow ''' import os def list_content(folder_path): for item in os.listdir(folder_path): item_path = os.path.join(folder_path, item) if os.path.isdir(item_path): list_content(item_path) else: print(item_path) list_content(in...
import requests BASE = "http://127.0.0.1:5000/" data =[ {"likes":3, "name": "Shiva Tandava", "views": 89}, {"likes":100, "name": "How to install Python", "views": 5000} ] for i in range(len(data)): response = requests.get(BASE + "video/"+ int(i)) print(response)
import torch import torch.distributions as dist from torch.distributions import constraints from numbers import Number from pvae.distributions.hyperbolic_radius import HyperbolicRadius from pvae.distributions.hyperspherical_uniform import HypersphericalUniform class RiemannianNormal(dist.Distribution): arg_constr...
import os import sys import urllib.request import requests from gtts import gTTS from tkinter import* from tkinter import filedialog import tkinter as tk import tkinter.scrolledtext as tkst from PIL import Image, ImageTk try: from PIL import Image except ImportError: import Image import pytesseract root =...
# 2015-07-09 Runtime: 440 ms # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {TreeNode} root # @return {integer} def countNodes(self, root): # thanks to https:...
from com.kodtodya.producers.QueueProducer import QueueProducer from com.kodtodya.producers.TopicPublisher import TopicPublisher class StompClient: def __init__(self): QueueProducer() #TopicPublisher()
from utils import execute_parallel class Accumulator: accumulator = 0 @staticmethod def accumulate(value): Accumulator.accumulator += value return Accumulator.accumulator def test_parallel(): results = execute_parallel(Accumulator.accumulate, [1, 3]) assert len(list(results)) ==...
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' @File : Stacked_AE.py @Time : 2021/11/03 20:04:14 @Author : Ray Zeng @Version : 1.0 @Contact : 11927025@zju.edu.cn @License : (C)Copyright ''' # %% # here put the import lib import keras from keras.layers import Input, Dropout from keras.layers.core i...
#!/usr/bin/env python3 import sys sys.path.insert(0, '..') from exam import * class QuestFormTextLoaderRevise(QuestFormTextLoader): def load(self): qf = self.get_cached_qf() if type(qf) != type(None): return qf filelist = [i for i in os.listdir() if re.search('\.md$',i) or re.search('\.tx...
def is_valid_ucll_email_address(str): regex = r"\w+\.\w+@(student\.)?ucll\.be" return re.fullmatch(regex, str)
def find_brute(t, p): """ 字符串匹配--bf 暴力搜索 :param t: 主串 :param p: 模式串 :return: 返回 子串p开始的t的最低索引(没找到则为-1) """ n, m = len(t), len(p) for i in range(n-m+1): k = 0 while k < m and t[i+k] == p[k]: k += 1 if k == m: return i return -1 if __nam...
""" This module is part of the isobarQuant package, written by Toby Mathieson and Gavain Sweetman (c) 2015 Cellzome GmbH, a GSK Company, Meyerhofstrasse 1, 69117, Heidelberg, Germany. The isobarQuant package processes data from .raw files acquired on Thermo Scientific Orbitrap / QExactive instrumentation working in H...
#!/usr/bin/python3 ''' EXERCICE 4 ''' employes = { "lausanne": [ "Julien", "Sophie", "Victor", "Paul", "Camille", "Prunille" ], "geneve": [ "Anthéa", "Prunille", "Julien", "Florence", "Sophie", "Etienne", ...
class MinStack: # @param x, an integer # @return an integer def __init__(self): self.L = [] self.m = [] self.length = 0 # self.mv = None def push(self, x): self.L.append(x) if self.length == 0: l = [x, self.length] sel...
"""orgachat URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
import pymssql as ms import time import os class Database(object): def __init__(self,host,port,user,passwd,database='VM2017'): self.host=host self.port=port self.user=user self.passwd=passwd self.database=database def __conn(self): try: ...
# 0 to 36 wheel roulette import random import time import math import matplotlib.pyplot as plt from matplotlib import colors def average(arr): sum = 0 for element in arr: sum+=element return int(sum/len(arr)) def normal_plot(simulations,starting_cash,top_earnings): plt.plot(top_earnings) p...
import sys import sqlite3 ######### conn = sqlite3.connect('admin.db') c = conn.cursor() c.execute('select * from Tripwires where tw_id in (select tw_id from logs)') table1 = c.execute('select * from Tripwires where tw_id in (select tw_id from logs)') b = conn.cursor() table2 = b.execute('select * from logs whe...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import portrait_pb2 as portrait__pb2 class PortraitBackendStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. ...
from django.conf.urls import url from apps.crowdfunding import views urlpatterns = [ # Campaigns url(r'^campaigns/$', views.campaigns_public, name='campaigns_public'), url(r'^campaigns/(?P<pk>\d+)/$', views.campaign_details, name='campaign_details'), url(r'^campaigns/donate/(?P<pk>\d+)/$', views.campa...
from dataset.preprocess.Datasets import DatasetFilter import os from Setting import dataRoot """ Rooms renderable under current setting Filters out rooms that are too large and rooms that miss floor/wall objs """ def renderable_room_filter(height_cap=4, length_cap=6, width_cap=6): def room_criteria(room, house)...
from MovieDB.lib import Query from MovieDB.models import Movie def search(q='', order_by_1='title_sort', order_by_2='year', user=None, watched=None, saved=None, streamable=None): movies = Movie.objects.prefetch_related('watched_by', 'saved_by').order_by(order_by_1, order_by_2) if q: query = Query(Movi...
#10.1 # with open('learning_python.txt') as file_object: # contents = file_object.read() # print(contents.rstrip()) # filename = 'learning_python.txt' # with open(filename) as file_object: # for line in file_object: # print(line.strip()) # with open(filename) as file_object: # lines = file_object....
from ctypes import * dll = cdll.LoadLibrary('IQmeasure.dll'); ret = dll.LP_Init(1,0); print(ret) ret = dll.LP_InitTester("192.168.100.254",1); print(ret) strMa = "/0"*200 FunPrint = dll.LP_GetVersion FunPrint.argtypes = [c_char_p, c_int] #FunPrint.restypes = c_void_p nRst = FunPrint(strMa, len(strMa)) ...
from pi_watchdog.pi_driver.orange_pi_one import RigDriver as OrangeRigDriver from pi_watchdog.pi_driver.stub import RigDriver as StubRigDriver from pi_watchdog.pi_driver.orange_pi_one import BlinkerDriver as OrangeBlinkerDriver from pi_watchdog.pi_driver.stub import BlinkerDriver as StubBlinkerDriver def get_rig_dirv...
import os, glob, shutil # This program is going to input original DICOM directories # that we will rename so our analysis will follow a consistent naming scheme. # Input Needed: directory path containing subject folders, output directory (if different than original) input_dir = '/projects/niblab/bids_projects/Expe...
from crossmod.helpers.filters import CrossmodFilters from crossmod.helpers.index_helper import current_overall_stats from crossmod.helpers.authenticate_helper import *
import logging import re from pathlib import Path from typing import Dict import pandas as pd from xlavir.util import find_file_for_each_sample logger = logging.getLogger(__name__) nextclade_cols = [ ( 'seqName', 'Sample', 'Sample name.', ), ( 'clade', 'Clade', ...
def autoincremento(vinicial,vfinal, idade_final, idade_inicial): vinicial2 = vinicial while vinicial <= vfinal: if vinicial < 100: print('UPDATE "Pessoa13_RR" set "V0{}" = null where "V0{}" = {} ;'.format(vinicial,vinicial, "'X'")) else: print('UPDATE "Pessoa13_RR" set "V{}" = null where "V{}" = {}...
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question, Category class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initializ...
import os import sys def daemonize(): ''' Daemonize a process ''' try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError as e: print >> sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # ...
# -*- coding: utf-8 -*- import cerebro from cerebro.aclasses import Statuses import datetime import zstatuses.py_cerebro as py_cerebro statuses_from_blocked = ['Request'] statuses_to_blocked = ['Done', 'Ready'] statuses_to_stop = ['Done', 'Ready', 'Closed'] statuses_from_reset = ['Not required'] statuses_to_res...
from rest_framework import serializers from apps.user.models.auth import Auth from apps.user.models.user import User from apps.user.models.bazzi import Bazzi from apps.mission.models.participation import Participation from apps.user.models.blocklist import BlockList from apps.core.utils.response import build_response_...
from __future__ import division import numpy as np from collections import defaultdict from commonset import get_two_hierarchies_of_keys class InputSet(object): """ stores inputs, avoids duplicates, returns them as dictionaries. Also provides lb, ub and dtype """ @staticmethod def setup(lower_bou...
from __future__ import unicode_literals from django.apps import AppConfig class PCARIConfig(AppConfig): name = 'pcari'
from splinter import Browser from bs4 import BeautifulSoup import pandas as pd import datetime as dt def mars_news(browser): browser = Browser("chrome", executable_path="chromedriver", headless=True) url = 'https://mars.nasa.gov/news/' # Retrieve page with the requests module browser.visit(url) h...
from django.db import models from .Periodo import Periodo class Disciplina(models.Model): nome = models.CharField(max_length=240) carga_horaria = models.SmallIntegerField() #tinyint teoria = models.DecimalField(max_digits=3,decimal_places=2) pratica = models.DecimalField(max_digits=3,decimal_places=2...
import csv import time ''' with open('selfmadedata.csv', 'rb') as csvfile: for line in csvfile.readlines(): array = line.split(',') date = array[3] print date ''' date1 = [] f1 = open ("ProcessedData.csv","r") # open input file for reading with open('ProcessedData_out.csv', '...
# -*- coding: utf-8 -*- """ Created on Mar 13, 2012 @author: moloch Copyright 2012 Root the Box 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/licen...
import bisect class KthLargest: k = 0 nums = [] def __init__(self, k, nums): """ :type k: int :type nums: List[int] """ self.k = k self.nums = nums nums.sort() def add(self, val): """ :type val: int :rtype: int "...
from enum import Enum from typing import Any import mugen.video.detect as v_detect from mugen.mixins.Filterable import Filter, ContextFilter from mugen.video.segments import Segment """ FILTER FUNCTIONS """ def is_repeat(segment: Segment, memory: Any) -> bool: return v_detect.video_segment_is_repeat(segment, vi...
#Server peer 1 from socket import * import time import threading #Directory of target file file_dir = "File_1.txt" #Initialize dict of target files and their corresponding ports peer_table = {} #number of peers peerCount = 3 #Socket initialization server_port = 3001 l_addr = '127.0.0.1' s_sock = socket(AF_INET, S...