text
stringlengths
38
1.54M
from etc.utils import file_to_lines from collections import namedtuple from itertools import chain Recipe = namedtuple("Recipe", "ingredients, allergens") lines = file_to_lines("input/day21.txt") def line_to_recipe(line): spl = line.split(" (") ingrs = spl[0].split(" ") allergs = spl[1] if len(spl) == 2 e...
from Class.File import File from Class.Parser import Parser """ "revisions": { "53ea11205f100d59130f75697cd55f70b1276911": { "kind": "REWORK", "_number": 1, "created": "2019-01-16 13:37:09.000000000", "uploader": { "_account_id": 2276 }, "ref": "refs/chan...
def isinstance_list(l, instanceof): return isinstance(l, list) & reduce((lambda x, y: x & isinstance(y, instanceof)), l, True)
from .Node import Node from .Number import Number from .Identifier import Identifier from .Function import Function from .String import String from .Variable import Variable, VariableType from .Block import Block from .Program import Program from .UnaryExpression import UnaryExpression from .BinaryExpression import Bin...
from rest_framework import serializers from .models import * import datetime class WorkshopAddSerializer(serializers.ModelSerializer): class Meta: model = Workshop fields = ('id', 'name', 'place', 'date', 'time', 'duration', 'price', 'info') class StyleSerializer(serializers.ModelSerializer): ...
from django.conf.urls import patterns, url from .views import MyView urlpatterns = patterns('', url('', MyView.as_view(), name='form'), )
from src.views import bp from flask_login import login_required from flask import render_template # ## GLOBAL ### # ## METHOD ### @bp.route('/') @bp.route('/todo') @login_required def todo(): return render_template("todo.html")
import code import random import imageio import math import tensorflow as tf import tensorflow_addons as tfa import matplotlib.pyplot as plt from cfg import get_config; CFG = get_config() def gaussian_k(height, width, y, x, sigma, normalized=True): """Make a square gaussian kernel centered at (x, y) with sigma as...
class BookReader: # Maintain class def __init__(self, library): self.library = library self.current_book = None self.current_page = None def open_book(self, book_id): self.current_book = self.library.get_book(book_id) self.current_page = self.current_book.current_pag...
# Load libraries import requests import json import base64 from PIL import Image from os.path import join from io import BytesIO # Image path image_path = 'test_image.JPEG' # Endpoint ip='localhost' URL = f"http://{ip}:7011/" ENDPOINT = join(URL, "predict") # Prepare image im = Image.open(image_path) buffered = ...
import binascii def byte_to_binary(n): return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8))) def hex_to_binary(h): return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h)) testbytes = [ 'AA0C04000CFFFFE830C03007C51003010803A2E9', ] #THIS EXAMPLE HAS THE WRONG PACKET CONTROL HE...
import math import tensorflow as tf # Model def model_fn(features, labels, mode): def learn_rate(lr, step): return 0.0001 + tf.train.exponential_decay(lr, step, 800, 1 / math.e) input_layer = tf.reshape(features["image"], [-1, 20, 20, 3]) input_layer = tf.to_float(input_layer) / 255.0 Y_ = ...
# quick PoC import subprocess with open("malicious_ips") as data, open('malicious_ips_in_other_logs', 'w') as out: for line in data: cmd = "grep -i " + line.strip() + " PC*" t = subprocess.run(cmd, shell=True, stdout=out)
# Generated by Django 3.1.5 on 2021-04-08 11:50 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Car', fields=[ ('id', model...
import face_recognition import cv2 from imutils.object_detection import non_max_suppression from imutils import paths import imutils import time # This is a super simple (but slow) example of running face recognition on live video from your webcam. # There's a second example that's a little more complicated but runs f...
import json import cv2 import numpy as np import six.moves.cPickle as cPickle # pylint: disable=no-name-in-module,import-error from aisdk.framework.base_inference import InferenceReq, BaseInferenceServer from aisdk.common.image import load_imagev2 import aisdk.proto as pb import aisdk.common.mxnet_base.net from . imp...
import pytest from cwt import COSEKey, load_pem_hcert_dsc class TestHelperHcert: def test_helpers_hcert_load_pem_hcert_dsc_es256(self): dsc = "-----BEGIN CERTIFICATE-----\nMIIBvTCCAWOgAwIBAgIKAXk8i88OleLsuTAKBggqhkjOPQQDAjA2MRYwFAYDVQQDDA1BVCBER0MgQ1NDQSAxMQswCQYDVQQGEwJBVDEPMA0GA1UECgwGQk1TR1BLMB4XDTIx...
import os import csv import json from collections import Counter import PySimpleGUI as sg def display(): """ Genera y devuelve un layout para el analisis del primer archivo """ layout = [ [sg.Text("Quiere generar un archivo JSON de...",justification='center',text_color='Black',font=("Arial",13))], ...
from ....base.layer.shape import BaseShapeAPI from .pad import MXNetPadAPI from .pool import MXNetPoolAPI from .upsample import MXNetUpsampleAPI class MXNetShapeAPI(BaseShapeAPI, MXNetPadAPI, MXNetPoolAPI, MXNetUpsampleAPI): pass
def sub(): num1=int(input("enter num1")) num2=int(input("enter num2")) sub=num1-num2 print(sub) sub()
import pandas as pd import numpy as np number = [0]*40 for i in range(1, 31): # print(i, end=': ') filename = str(i) + '.csv' df=pd.read_csv(filename,header=None,sep=',') series = df[8] for j in range(0, 40): number[j] += int(series[j + 1]) print(number) for k in range(0, 40): number[k...
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: ans = [0] * n stack = [] pre = None for l in logs: fid, state, t = l.split(':') if not stack: stack.append((int(fid), int(t))) else: diff = int(t) - pre[...
#!/usr/bin/python import socket #nasm > add eax,12 #00000000 83C00C add eax,byte +0xc #nasm > jmp eax #00000000 FFE0 jmp eax host ="127.0.0.1" shellcode = ( "\xda\xcb\xbb\x39\x45\x38\xfc\xd9\x74\x24\xf4\x5a\x29\xc9\xb1" "\x14\x31\x5a\x19\x83\xc2\x04\x03\x5a\x15\xdb\xb0\x09\x27\xec" "\xd8\x...
from django.db import models # Create your models here. # # class UserInfo(models.Model): # """ # 员工表 # """ # # # auth=models.OneToOneField("") # name = models.CharField(verbose_name='员工姓名', max_length=16) # # username = models.CharField(verbose_name='用户名', max_length=32) # # password = mod...
""" square N using recursion """ def square1(power): re = 2 if power == 1: return re for i in range(2, power+1): re = re * 2 print(re) def square2(n, power): if power == 1: return n return n * square2(n, power - 1) if __name__ == '__main__': print(square2(...
from ._anvil_designer import survey_rowTemplate from anvil import * import anvil.facebook.auth import anvil.google.auth, anvil.google.drive from anvil.google.drive import app_files import anvil.microsoft.auth import anvil.users import anvil.server import anvil.tables as tables import anvil.tables.query as q from anvil....
import numpy as np import unittest from ray.rllib.utils.replay_buffers.multi_agent_mixin_replay_buffer import ( MultiAgentMixInReplayBuffer, ) from ray.rllib.policy.sample_batch import ( SampleBatch, DEFAULT_POLICY_ID, MultiAgentBatch, ) class TestMixInMultiAgentReplayBuffer(unittest.TestCase): b...
''' query processing ''' import util import json import time import random import math import sys from util import * from cran import * from cranqry import * # Testing the test case like converting queries to terms, checking tfidf scores and cosine similarities. def test(): ''' test your code thoroughly. put th...
import cv2 import numpy as np def find_sql_area(file_name): img = cv2.imread(file_name) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # cv2.imshow("grey", gray) ret, binary = cv2.threshold(gray, 250, 255, cv2.THRESH_BINARY) cv2.imshow("binary", binary) r_pic, contours, hierarchy = cv2.findConto...
def rowsearch(q,p): prow,qrow=[len(p),len(q)]# no. of rows pcol,qcol=[len(p[0]),len(q[0])]# 0 only for reference, pcol= no. of columns in p #print(prow, qrow, pcol, qcol) for i in range(qrow-prow+1):# for checking every row of q if(p[0] in q[i]):#if present in any row of q, then only bother to proceed fur...
# encode python program import csv reader = csv.reader(open('table.csv', 'r')) char_dict = {} for row in reader: k, v = row char_dict[v.replace('"', '', 2)] = k # imports the csv conversion sheet as a dictionary char_dict # importing files and setting an output infile = open(input('What is the name of the ...
#lista.append()-> ingresa valor al final. #lista.insert(index,nuevoElemento))-> añadir nuevo elemento. No remplaza adicina un nuevo elemento. #lista.extend(nuevaLista)-> adiciona nuevos valores que pertenecen a otra lista. #Lista.remove(Elemento a eliminar)-> eilimina elementos de la lista # del lista[indice] -> eiimi...
from django.conf.urls import url from . import views # This line is new! urlpatterns = [ url(r'^$', views.index, name='index'), # This line has changed! url(r'^display$', views.display, name='display'), url(r'^new$', views.new, name='new'), url(r'^create$', views.create, name='create'), ...
def solution(N, number): dp = [{0}, {N}] for idx in range(1, 9): if number in dp[idx]: return idx new = {N * int("1" * (idx + 1))} for e1 in dp[idx]: for e2 in dp[-idx]: new.add(e1 + e2) new.add(e1 - e2) new.add(e2 ...
numbers = [4, 12, 15, 7] highest = numbers[0] lowest = numbers[0] for num in numbers: if num > highest: highest = num if num < lowest: lowest = num print(highest) print(lowest)
# Generated by Django 4.0.7 on 2022-09-22 12:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("zerver", "0413_set_presence_enabled_false_for_user_status_away"), ] operations = [ migrations.RemoveField( model_name="userstatus", ...
import requests import json from datetime import datetime, timedelta from util import time_tool import logging.config # Add mapping: curl -H "Content-Type:application/json" -XPOST http://127.0.0.1:9200/signin/doc/_mapping -d '{"properties": {"key":{"type":"keyword"}, "pv":{"type":"long"}, "uv_device_id":{"type":"long...
#!E:/python34/python.exe from wsgiref.simple_server import make_server from http.cookies import SimpleCookie import cgi import re import hashlib,time html = """ <html> <body> <form enctype="multipart/form-data" method="post" action=""> <p>File:<input type='file' name='file'></p> <input type="submit" ...
from astropy.io import fits from astropy.table import Table import numpy as np import os import glob import sys import pdb class headerTable(): def __init__(self,fileSearch,headList,extension=0): """ A header table is made for a given set of parameters Parameters -----------------...
from bs4 import BeautifulSoup html_str = "<p><!-- 註解文字 --></p>" soup = BeautifulSoup(html_str, "lxml") comment = soup.p.string print(comment) print(type(comment)) # Comment型態
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization from .encode_to_utf8 import encode_str_utf8 import os from dotenv import load_dotenv load_dotenv('.env') PASSWORD = os.environ.get("PASSWORD") p...
import numpy as np X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) Y = np.array([1, 1, 1, 2, 2, 2]) from sklearn.naive_bayes import GaussianNB clf = GaussianNB() clf.fit(X, Y) GaussianNB(priors=None) pred=clf.predict([[-0.8, -1]]).reshape(1,-1) print(pred) labels_test = np.array([[1]]) #准确度评估 评估正...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'FjwDJ.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^fy/', include(...
#!/usr/bin/python import re import subprocess import sys import os import nltk from nltk.stem import PorterStemmer import Stemmer s= Stemmer.Stemmer('german') file = open('fromDb','r') while True: b = file.readline() if b == '': exit() b = b.split('\n') str = b[0].replace('-',' ') split = str.split('\t'...
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(S, C): res = [] ans = '' name_dict = dict() names = S.split('; ') for name in names: name_split = name.split(' ') first_name = name_split[0] last_name = name_split[-1] ...
import argparse import os import pandas as pd import structlog import yaml from .ExperimentsTest import run_all_experiments from .Logging import init as init_logging from .Swarm import Swarm from .Visualizer import Visualizer RESULT_DIR = f"./results/swarm_training/seed_" logger = structlog.getLogger(__name__) de...
''' Сумма квадратов По данному натуральному n вычислите сумму 1²+2²+3²+...+n². ''' n = int(input()) i = 1 sqr_sum = 0 while i <= n: sqr_sum += i ** 2 i += 1 print(sqr_sum)
__author__ = 'yi-linghwong' ############# # Get the slope of the linear equation for a list of user # y = mx + c, where y is number of follower, x is epoch time ############# import sys import os from matplotlib import * import matplotlib.pyplot as plt import pylab import numpy as np from scipy.stats import linregres...
PARAM_COUGH_SOUND = "audio_data_cough" PARAM_MOUTH_SOUND = "audio_data_breathe_mouth" PARAM_NOSE_SOUND = "audio_data_breathe_nose" PARAM_AUDIO = "audio" PARAM_COUGH_SOUND_URL = "audio_data_cough_url" PARAM_MOUTH_SOUND_URL = "audio_data_mouth_url" PARAM_NOSE_SOUND_URL = "audio_data_nose_url" PARAM_SUBMIT_ID = "submit_id...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import datasets import PIL import datasets.mydb import os import datase...
"""This holds the triangle class.""" import math class Circle(object): """A circle is a closed curve that lies a set distance from its center.""" def __init__(self, x, y, r): """Create a circle at `x`, `y` with the given radius `r`.""" self.x, self.y, self.r = float(x), float(y), float(r) ...
#!/usr/bin/python import multiprocessing import traceback from subprocess import * import shlex import re from datetime import datetime import configparser import os, sys config = configparser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'settings.ini')) wp_sites = config.items('wp_sites_to_scan...
######################################################################### # NSAp - Copyright (C) CEA, 2015 - 2016 # 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 for details. ######...
class Solution: digit_to_letters = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} def letterCombinations(self, digits: str) -> List[str]: if not digits: return [] ...
import argparse from functools import partial from multiprocessing import Pool import cv2 import numpy as np from pathlib import Path from tqdm import tqdm import json from misc_utils import load_image, load_vflow, save_image def downsample_rg_path(rgb_path: Path, outdir: Path, downsample=1): # load agl_path...
from pydantic import BaseModel, Field from uuid import UUID, uuid4 from typing import List class Image(BaseModel): id: UUID = Field(default_factory=uuid4) name: str tags: List[str] = Field(default_factory=list)
import numpy as np import os import psi4 psi4.core.be_quiet() def HF_energy(mol_string, basis): psi4.geometry(mol_string) psi4.set_options({'reference': 'uhf'}) return psi4.energy(f'scf/{basis}') def DFT_energy(mol_string, basis): psi4.geometry(mol_string) psi4.set_options({'reference': 'uks'}) ...
# @author Matheus Alves dos Santos n_intersections = int(input()) shortcuts = list(map(int, input().split())) shortcuts = [(shortcut - 1) for shortcut in shortcuts] costs = [0] + ([-1] * (n_intersections - 1)) i, queue = 0, [0] while (i < len(queue)): intersection = queue[i] shortcut = shortcuts[intersection...
from django.urls import path, include from django.views.generic import RedirectView from django.contrib import admin from hr import views from .router import router urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('', RedirectView.as_view(pattern_name='category_cha...
# """ # NOTE: This example is from ModernGL 4 or earlier. We simply disable and archive them for now. # """ # import struct # import ModernGL # from PIL import Image # ctx = ModernGL.create_standalone_context() # prog = ctx.program( # ctx.vertex_shader(''' # #version 330 # in vec2 vert; # ...
# Copyright (C) 2017 Google 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 writi...
# -- # -- Copyright (c) 2015, Facebook, Inc. # -- 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. An additional grant # -- of patent rights can be found in the PATENTS file in the same directory. # -- ...
# Generated by Django 3.2 on 2020-12-01 11:53 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Places', fields=[ ('id', models.AutoField(aut...
#!/usr/bin/env python from __future__ import print_function from __future__ import unicode_literals import contextlib import distutils.sysconfig import os.path import pipes import shutil import subprocess import sys import tempfile PYPY = '__pypy__' in sys.builtin_module_names @contextlib.contextmanager def tmpdir...
################################################################################ # The Frenetic Project # # frenetic@frenetic-lang.org # #############################################################################...
# Generated by Django 2.1.2 on 2019-01-14 14:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mrp_system', '0038_auto_20190114_1348'), ] operations = [ migrations.AddField( model_name='product', name='part_prod...
#!/usr/bin/python2 # # Mike McCune <mmccune@redhat.com # # Copyright 2010 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that ...
''' Copyright 2014 AFour Technologies 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 writing, soft...
class Solution(object): def helper(self, nums, start, tlist, res): res.append(list(tlist)) # if start >= len(nums):#Mistake append before return # return for i in range(start, len(nums)): tlist.append(nums[i]) #Mistake why set start self.helper(nums...
# Index a scraped site by recreating URL structure from wget tree and inserting into DB from argparse import ArgumentParser from urllib import request from bs4 import BeautifulSoup import os import re parser = ArgumentParser() parser.add_argument("domain", help="The domain to construct URL's against.") parser.add_ar...
import ipdb import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import numpy as np import scipy.signal import theano.tensor as T from cle.cle.data import TemporalSeries from cle.cle.data.prep import SequentialPrepMixin from cle.cle.utils import segment_axis, tolist, totuple from iamondb_utils impo...
def addition(num1, num2): try: x = int(num1) + int(num2) except ValueError: print(' Please use numbers') else: print(x) n1 = input(' What is your first number: ') n2 = input('What is your second number: ') addition(n1, n2)
import sys import psycopg2 if (len(sys.argv) != 2): print("Please enter one word as paramater for this program.") else: # take the word word = sys.argv[1] # check for apostrophe tmpword = word count = 0 while (count < len(tmpword)): if (tmpword[count] == "'" and tmpword[count+1] != "'" and tmpword[count-1] !...
# Generated by Django 3.1.7 on 2021-02-28 13:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Uygulama', '0001_initial'), ] operations = [ migrations.AlterField( model_name='uygulama', name='birt_date', ...
import socket import struct import fixgw.netfix as netfix import math from gdl90 import decodeGDL90 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', 4000)) netfix_client = netfix.Client('127.0.0.1', 3490) netfix_client.connect() while True: msg, adr = s.recvfrom(8192) msg = decodeGDL90(msg) ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ CryingDollApp.py MIT License (c) Faure Systems <dev at faure dot systems> CryingDollApp extends AsyncioProp. """ from constants import * from AsyncioProp import AsyncioProp from PropData import PropData from Sound import Sound import random, os if USE_GPIO and os.p...
import unittest from ds.graph import DirectedGraph, UnDirectedGraph class TestGraph(unittest.TestCase): def test_build_digraph(self): pairs = [(0, 1), (1, 2), (2, 3), (3, 4), (0, 8), (8, 2), (2, 9), (9, 7), (7, 6), (6, 3), (3, 5), (5, 4), (4, 6)] g = DirectedGraph() g.build_graph(pairs) ...
from distutils.core import setup from distutils.extension import Extension from distutils.core import setup setup(name='poisson_generator', version='0.1', description='Poisson generator for time series', author='J. Michael Burgess', author_email='jmichaelburgess@gmail.com', packag...
import json from django.db import migrations def check_sort(apps, schema_editor): """ Previously, endpoints may be ordered arbitrarily, but now we're enforcing an order with querysets. Therefore, this migration loops through existing data pivots and alerts us of any which have no sorts applied, as th...
__author__ = 'trunghieu11' def solve(n): if n % 2: return 0 n /= 2 return (n - 1) / 2 if __name__ == '__main__': n = int(raw_input()) print solve(n)
from ebooklib import epub def book(): book = epub.EpubBook() book.set_identifier('test001') book.set_title('test') book.set_language('en') book.add_author('me') c1 = epub.EpubHtml(title='Intro', file_name='chap_01.xhtml', lang='hr') c1.content=u'lines are fun' book.add_item(c1) book...
# -*- coding: utf-8 -*- """ Created on Sat Feb 18 10:57:13 2017 @author: Aaron """ import scipy from scipy import interpolate import math def torque(RPM): #return -3E-7*math.pow(RPM,2)+0.0018*RPM-1.6718 #N*m, torque as a function of RPM at full throttle return -4e-15*math.pow(RPM,4)+8e-11*math.pow...
"""cogeo-mosaic cache configuration""" import pydantic class CacheSettings(pydantic.BaseSettings): """Application settings""" # TTL of the cache in seconds ttl: int = 300 # Maximum size of the LRU cache in MB maxsize: int = 512 # Whether or not caching is enabled disable: bool = False ...
import numpy as np # 使用邻接矩阵表示图的拓扑排序 def topological_sort(g): n = len(g) # 获取所有入度为0的结点 q = [] for j in range(n): flag = True for i in range(n): if g[i][j] == 1: flag = False break if flag: q.insert(0, j) li = [] # 记录结果 ...
import unittest from utils.test_modes import TestModes from utils.ioc_launcher import get_default_ioc_dir, ProcServLauncher from common_tests.danfysik import DanfysikCommon, DEVICE_PREFIX, EMULATOR_NAME, HAS_TRIPPED from utils.testing import skip_if_recsim MAX_RAW_SETPOINT = 1000000 MIN_RAW_SETPOINT = MAX_RAW_SETPOI...
# Generated by Django 2.2.4 on 2019-09-02 06:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('snippets', '0001_initial'), ] operations = [ migrations.RenameField( model_name='snippet', old_name='owmer', new...
import math as mth import sys import ast def build_blocks(arr): blocks = [0]*block_size i = 0 while (i <= len(arr)-1): blocks[mth.floor(i/block_size)] += arr[i] i += 1 return blocks def summin(left, right, arr): blocks = build_blocks(arr) ...
import ssl def getContext(): ''' create a SSL context and return it ''' context = ssl.create_default_context() return context
"""Write a program assigns an angle in degrees to variable called degrees. This program converts this angle to radians and assigns it to a variable called radians. To convert from degrees to radians, use the formula radians = degrees*3.14/180 (3.14 = pi). Print angle in both degrees and radians""" import random def co...
#!/usr/bin/env python3 import argparse from itertools import tee, chain from pprint import pprint example = '..^^.' def threewise(iterable): "s -> (s0,s1, s2), (s1,s2, s3), (s2, s3, s4), ..." a, b, c = tee(chain('.', iterable, '.'), 3) next(b, None) next(c, None) next(c, None) return zip(a, ...
import random import sys sys.path.append("../../src/") from DEVS import AtomicDEVS, CoupledDEVS from mpi4py import MPI class CircleNodeState(object): def __init__(self): self.event = None self.queue = [] self.nr = 0 self.generated = 0 def copy(self): a = CircleNodeSta...
from collections import namedtuple from django.contrib.auth import logout from django.urls import path from . import views from registration import views as v urlpatterns = [ path('dashboard/', views.dashboard, name='dashboard'), path('add-Book/', views.addBook, name='addBook'), path('view-books', views.vie...
import re from django.db import models def get_unique_slug_value(queryset, proposal, field_name="slug", instance_pk=None, separator="-"): """ Returns unique string by the proposed one. Optionally takes: * field name which can be 'slug', 'username', 'invoice_number', etc. * the primary key of the inst...
from keras.models import Sequential from keras.layers import Dense import numpy #Fix random seed numpy.random.seed(7) #load data from data.csv dataset = numpy.loadtxt("data.csv", delimiter=",") #Split into input and output variables input = dataset[:,0:8] output = dataset[:,8] #Define neural network model model = S...
from django.contrib import admin from .models import Organism,CommonName,Synonym,Links, Distribution,Subspecies_Name,Types,PhotoURLS,Comments,BiblioRefer # Register your models here. admin.site.register(Organism) admin.site.register(CommonName) admin.site.register(Synonym) admin.site.register(Links) admin.site.regist...
import re IDENTIFIER_PREFIX = '$I:' OOV_TOKEN = '$OOV' # SENTENCE_SEPS = ('$P:;', '$P:}', '$P:{') SENTENCE_SEPS = ('$P:;', ) def identifier_split_java(token): token = token.rstrip() if token.startswith('@'): # such as '@Override' # java specific s2 = ['@'] + re.findall(r'[A-Z]+[a-z]*|[a-z]+|[:]', ...
from django.conf.urls import url from . import views app_name = 'reporte' urlpatterns = [ url(r'^plan/imprimir/(?P<id>.*)$', views.imprimir_plan, name='imprimir_plan'), url(r'^cuadro/imprimir/(?P<id>.*)$', views.imprimir_cuadro, name='imprimir_cuadro'), # Excel url(r'^reporte/excel/dependencia$', vie...
import os class FakeRule(object): def __init__(self): self._params = {} @property def job_path(self): return os.path.join( os.path.dirname(__file__), 'data/repo' ) def path(self,path): return os.path.join( self.job_path, path ) class FakeTask(FakeRule): ...
#!/usr/bin/env python import rospy from std_msgs.msg import String from sensor_msgs.msg import Image from move_base_msgs.msg import MoveBaseActionGoal, MoveBaseActionFeedback from actionlib_msgs.msg import GoalStatusArray from tf.transformations import quaternion_from_euler from sys import argv import os import yaml f...
# ====== Legal notices # # Copyright (C) 2015 GEATEC engineering # # This program is free software. # You can use, redistribute and/or modify it, but only under the terms stated in the QQuickLicence. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, without even the...