text stringlengths 38 1.54M |
|---|
import sys
import time
print sys.path.append("/usr/local/lib")
from libopenrave_interface import Environment, v_string, v_double, v2_double
def test_collision(env):
robot = env.getRobot()
collision_manager = env.getCollisionManager()
joint_angles_v = v_double()
joint_angles_v_2 = v_double()
joint_a... |
#! /usr/bin/python3
import time
import json
import iota.harness.api as api
import iota.test.apulu.utils.pdsctl as pdsctl
import iota.test.apulu.utils.misc as misc_utils
def GetBgpNbrEntries(json_out, entry_type):
retList = []
try:
data = json.loads(json_out)
except Exception as e:
api.Logg... |
#Import necessary libraries
import tensorflow as tf
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import sklearn.utils
#Load Iris dataset
df= pd.read_csv("C:\\Users\\rohit.a\\Downloads\\Iris.csv")
cols=['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWid... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('poll', '0003_auto_20190127_2335'),
]
operations = [
migrations.CreateModel(
name='UserCount',
fields=[
('id', models.AutoField(auto_created=True, pri... |
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... |
import sys
from string import ascii_lowercase as al
myDict = {}
anagramDict = {}
def enumdict(alpha):
for i, x in enumerate(alpha):
myDict[x] = i
return myDict
def sort_insertion(my_list):
for i in range(1,len(my_list)):
val_current = my_list[i]
pos = i
# check backwards thr... |
import copy
import time
import climate
import numpy as np
import theanets
import utils
from RawData import RawData
from TrainingTimeSeries import TrainingTimeSeries
climate.enable_default_logging()
def test_RawData_read_csv_multiple_features(algo, layers, train, valid, test):
net = theanets.Regressor(layers=la... |
#Filereading
import os as operatingsys
filename = "foo.txt"
targetone = "foo"
targettwo = "Foo"
myarray = []
yescount=0
with open(filename) as file:
content = file.readlines()
for l in content:
myarray.append(l)
for ll in myarray:
if targetone in ll:
yescount+=1
elif targettwo in ll:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
LOCAL_DEBUG = True
import logging
import re
import sys
import os
import socket
import threading
import time
from lib.common import *
#FLAG = "#d9Fa0j#"
from lib.fast_request import fast_request
from lib.ex_httplib2 import *
import Queue
sys_path = lambda relativePath: "%s/%s... |
#
# This file is subject to the terms and conditions defined in the
# file 'LICENSE', which is part of this source code package.
#
from collections import OrderedDict
from datetime import date, datetime
import importlib
import re
from flask import abort
from flask_restplus import Resource
from sqlalchemy.inspection im... |
# f = c*1.8 + 32
import tensorflow as tf
import numpy as np
import logging
logger = tf.get_logger().setLevel(logging.ERROR)
celsius_q = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
fahrenheit_a = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)
for i, c in enumerate(celsius_q):
print("Celsius ... |
# TODO:
# A. PLACEHOLDER
# Library Imports
import random
# Local Imports
import tkinter_gui_app
import pygame_gui_app
import pyopengl_app
import graphics_engine
import shape_generator
import point_cloud
import nsvt_config as config
class PhysicsEngine():
def __init__(self, wrapper_):
self.wrapper = ... |
# -*- coding: utf-8 -*-
from django import forms
from products.models import Product
class CartUpdateForm(forms.Form):
quantity = forms.IntegerField(initial=1, widget=forms.TextInput(attrs={'class': 'input-small'}))
product = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.HiddenInput)
... |
# Simple Trie Implementation to get a feel for things
# uses reference counters to track where strings end and if there are multiple copies of the same string
class Node:
def __init__(self):
self.children = dict()
self.count = 0
def incrementReferenceCount(self):
self.count = self... |
import pandas as pd
def load_plataforma(perfiles, num_of_students):
# No especificado, quiza el numero de horas que ha estado en la plataforma por materia
# Alberto: Redondear, vector.
lista_plataforma = []
for i in range(1, num_of_students+1):
path_plataforma = "data/apartadolibros/separacion_... |
# encoding: utf-8
# module gi.repository.LibvirtGConfig
# from /usr/lib64/girepository-1.0/LibvirtGConfig-1.0.typelib
# by generator 1.147
"""
An object which wraps an introspection typelib.
This wrapping creates a python module like representation of the typelib
using gi repository as a foundation. Accessing ... |
from datadog import initialize, api
from datadog.api.constants import CheckStatus
options = {
'api_key': '9775a026f1ca7d1c6c5af9d94d9595a4',
'app_key': '87ce4a24b5553d2e482ea8a8500e71b8ad4554ff'
}
initialize(**options)
check = 'app.ok'
host = 'app1'
status = CheckStatus.OK # equals 0
api.ServiceCheck.check(... |
from pytube import YouTube # pip install pytube or pytube3
from pytube import Playlist
import os, re
def Download(yt):
print("Downloading....")
# Filter Streams (Optional)
vids = yt.streams.filter()
# Get only .mp4 format
vids[0].download(r"Tracks/")
def main(c, playlist):
# Filter Playlist Ur... |
# Iterate while input not valid, then return input
def choose(text, output, options):
char = None
while True:
output(text)
try:
char = str(input())
except KeyboardInterrupt:
exit()
except:
continue
if char not in options:
co... |
import random
import tensorflow as tf
import tensorflow.layers
import numpy as np
import tflib as lib
import tflib.nn.conv2d
import tflib.nn.linear
from tflib.nn.rmspropgraves import RmsPropGraves
class Agent():
def __init__(self, sess, config, num_actions=18, action_interval=4):
self.sess = sess
... |
# Login Form
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
chrome_driver_path = "C:\Development\chromedriver.exe"
driver= webdriver.Chrome(chrome_driver_path)
driver.get("https://the-internet.herokuapp.com")
form_auth = driver.find_element_by_xpath("//a[contains(text(),'... |
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num = 0
digits.reverse()
for i in range(len(digits)):
num += digits[i]*(10**i)
num+=1
s=str(num)
result=[]
for i in range(l... |
# import libraries
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.externals import joblib
import model_functions as mf
from model_functions import KeywordExtractor
import arg... |
import numpy
import matplotlib.pyplot as plot
import sys
import math
import scipy.io.wavfile
class Oscillator:
def __init__(self, waveform, frequency, phase_shift, sampling_rate, duration, harmonics=1):
self.waveform = waveform
self.harmonics = harmonics
self.frequency = frequency
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 30 15:26:47 2021
@author: M Shoaib
"""
def countMin(string):
l=len(string)
#performing a dynamic approach
app = [[0]*l for i in range(l)]
#will check for the toatl rift
for dif in range(1,l):
i=0
for j in range(dif,l):
... |
from dao.seat_table import Seat
from dao.flight_table import Flight
def check_is_seated(seat_code, flight_id):
flight = Flight.query.filter_by(id=flight_id).first()
plane_id = flight.plane_id
seat = Seat.query.filter_by(seat_code=seat_code,
plane_id=plane_id).first()
if... |
import sounddevice
import pydub
import time
import numpy
import queue
class audio():
def __init__(self):
self.samples = None
self.now = {}
self.now.update(place=0)
self.now.update(path="")
def openfile(self, filepath):
if ".mp3" in filepath:
self.segment = py... |
import sys
import os
from base64 import b64encode
from json import load, dump
from Crypto.PublicKey import RSA
import requests
from client import Client
SERVER_URI = 'http://0.0.0.0:9000'
if len(sys.argv) < 2:
print('Usage: python download.py <fileid>')
exit(0)
client = Client()
client.get_uuid()
client.get_n... |
def soup(matrix,word):
for fila in range(len(matrix)):
for letra in range(len(matrix[fila])):
if matrix[fila-1][letra-1] == word[0]:
if checksoup(matrix,fila-1,letra-1,word[1:]):
return "{0}{1}".format(chr(ord("A")+fila-1),letra)
def checksoup(matrix,fila,le... |
import ants
import importlib_resources
import pandas as pd
from ants.core.ants_image import ANTsImage
SUPPORTED_CONTRASTS = ["t1", "t2"]
def get_mni(contrast: str, bet: bool) -> ANTsImage:
"""Get the correct MNI ICBM152 09c Asym template,
given contrast and BET status.
Args:
contrast (str): MRI'... |
"""
serializer.py is designed to be used iff you did not properly serialize
all of the information abour your experiment when you ran it in the
first place. You should edit this file to properly describe the
experiment you ran, and then run
>> python serializer.py LOG_FILE_NAME
where LOG_FILE_NAME is the name of the... |
#!/usr/bin/env python
# coding: utf-8
# ## Machine Learning
# ### Logistic Regression - Titanic
# Layout of this notebook
# -------------------------------------------------------------------------------------
# Step 1 - Frame the problem and look at the big picture<br><br>
# Step 2 - Setup<br>
# 2.1 - Common... |
#!/usr/bin/env python3
import bs4, requests
# res = requests.get('https://www.amazon.co.uk/PS4-PRO-Red-Dead-Redemption/dp/B07HKV4TR4/ref=sr_1_1?s=videogames&ie=UTF8&qid=1541109558&sr=1-1&keywords=ps4+pro')
# print(res.raise_for_status)
# soup = bs4.BeautifulSoup(res.text, 'html.parser') # Returns a soup object.
# ele... |
#instance methods
#If we are using atleast one instance variable ---->instance methods.
class Student:
def __init__(self,name,marks):
self.name=name
self.marks=marks
def display(self): # instance method ,bcz we are accessing instance variable.The first arguments of the instance m... |
__author__ = 'liushuo'
from scrapy.cmdline import execute
#from scrapy import cmdline
#命令行运行scrapy库相当于运行此命令;run configuration中配置script params为crawl spidername
cmd = 'scrapy crawl ZhihuSpider'
execute() |
import json
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
def splitData(data):
xs=[]
ys=[]
zs=[]
for y in range(len(data)):
for x in range(len(data[y])):
z=data[y][x]
xs.append(x)
ys.append(y)
zs.append(z)
return (xs, ys, zs)
f=open('seqs/protocols/HTT... |
import threading
from time import sleep
e = threading.Event()
#冲破阻塞wait挡不住它
e.set()
event = e.wait()
print event
e.clear()
event = e.wait(2)
print('timeout:',event)
|
from turtle import Screen
from paddle import Paddle
from ball import Ball
import time
from scoreboard import ScoreBoard
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong")
screen.tracer(n=0)
right_pad = Paddle((350, 0))
left_pad = Paddle((-350, 0))
ball = B... |
def lcSubstring(S1, S2, n, m):
dp=[[0 for i in range(m+1)]for i in range(n+1)]
result=0
for i in range(1,n+1):
for j in range(1,m+1):
if S1[i-1]==S2[j-1]:
dp[i][j]=1+dp[i-1][j-1]
result=max(result,dp[i][j])
else:
dp[i][j]=0
... |
# File Open
# File Handling
# open(filename, mode)
"""
"r" - Read - Default value. Opens a file for reading,
error if the file does not exist
"a" - Append - Opens a file for appending,
creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not ... |
import pytest
from pizza_orders.models import FoodItem, FoodImage
@pytest.fixture(scope="function")
def add_food_item():
def _add_food_item(name: str, item_type: str, price: float, img_file=None):
food_item = FoodItem.objects.create(
name=name, item_type=item_type, price=price
)
... |
# Generated by Django 2.1.4 on 2018-12-29 20:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('carts', '0002_cart_subtotal'),
]
operations = [
migrations.AddField(
model_name='cart',
name='updated',
... |
from poutyne.framework.callbacks import Callback
import torch
from torch.nn.functional import mse_loss
class MseMetaTest(Callback):
"""
Callback object that estimates the MSE loss on the meta test set after each batch or epoch.
"""
def __init__(self, meta_test, filename, periodicity='epoch'):
... |
'''
today's tasks
task1: 筛选出运算符
task2: 根据task1中的运算符分割输入字串
task3: 打印运算结果
'''
import re
def subtract(c,d):
return c-d
def multiply(c,d):
return c*d
def divide(c,d):
return c/d
def add(c,d):
return c+d
def calculator1():
args=["+","-","*","/"]
while 1:... |
from django.core.urlresolvers import reverse
from django.test import TestCase
class CustomTestCase(TestCase):
# TODO: Is there a way to have a single argument turn into a list of one
# when passed to a method?
def assertResponseStatus(self, success_codes, view, args=[], kwargs={}):
self.as... |
'''
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog",... |
# Generated by Django 2.2 on 2019-09-06 19:57
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
nam... |
from django.urls import path
from . import views
from accounts.views import registration_view
# ApiListView
from rest_framework.authtoken.views import obtain_auth_token
app_name = 'accounts'
urlpatterns = [
path('login/',views.login,name='login'),
path('register/',views.register,name='register'),
path('l... |
import datetime
import urlfetch
import copy
from mint.tags import *
from mint.utils import *
class TransactionSet(object):
def __init__(self, mint, query_string='', pyfilters=[]):
self.mint = mint
self.query_string = query_string
self.pyfilters = pyfilters
def filter(self, query=None, ... |
from __future__ import unicode_literals, print_function
import contextlib
import timeit
import traceback
from ..compat import collections_abc, PY2
from .strings import *
from .algorithms import *
from .paths import *
def is_collection(x):
if not isinstance(x, collections_abc.Iterable):
return False
... |
class Assembler(object):
def __init__(self, asmpath='', mripath='', rripath='', ioipath='') -> None:
"""
Assembler class constructor.
Initializes 7 important properties of the Assembler class:
- self.__address_symbol_table (dict): stores labels (scanned in the first pass)
... |
from typing import AnyStr
import hashlib
from functools import wraps
import os
def str_to_byte(func):
"""
decorator adapted from https://forum.kodi.tv/showthread.php?tid=330975
:param func: func taking string as arg
:return: wrapped func
"""
@wraps(func)
def wrapped(*args, **kwargs):
... |
# -*- coding: utf-8 -*-
from imagekit.models.fields import ProcessedImageField
from imagekit.processors import ResizeToFit, ResizeToFill, Adjust
from django.db import models
from productsapp.models import TechnicalSolutions
# Create your models here.
class News(models.Model):
""" Модель новости"""
name = m... |
from subprocess import Popen, PIPE
def get_param_list(params):
""" transform params from dict to list.
"""
if isinstance(params, dict):
for k, v in params.items():
yield str(k)
yield str(v)
else:
raise ValueError("job params can only be dict")
def get_tfjob_cm... |
# -*- coding:utf-8 -*-
__author__ = 'yyp'
__date__ = '2018-5-27 18:09'
class Solution:
"""
Time: O(n)
Space:O(1)
"""
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
res = []
left, right = 0, len(p) - 1
... |
# function similar to describe() with missing value
def func_df_describe_all(df): ## input a dataframe
"""function similar to describe() with missing value
Keyword arguments: df (dataframe); Return: df_summary
"""
df_summary = df.describe(include='all').T
df_summary['miss_perc'] = (df.isnull().sum()... |
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
from time import sleep
from random import randint
import os.path
import pandas as pd
def simple_get(url):
"""
Attempts to get the content at `url` by making an HTTP GET reques... |
import sys
try:
import os
import sqlite3
from platform import system
from termcolor import colored
from pyfiglet import figlet_format
from prettytable import PrettyTable
except ModuleNotFoundError as error:
print(colored(error, color="red"))
input(colored("[!!]Press Any Key To Exit...",... |
import torch
from torch import nn, optim
import torch.nn.functional as F
import matplotlib.pyplot as plt
import torch
from torchvision import datasets, transforms
import src.notebook.assets.h.helper
class Network(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Linear(784, 51... |
# coding:utf-8
from bs4 import BeautifulSoup
import requests
import os
r = requests.get("http://699pic.com/sousuo-218808-13-1.html")
fengjing = r.content
soup = BeautifulSoup(fengjing, "html.parser")
# 找出所有的标签
images = soup.find_all(class_="lazy")
print images # 返回list对象
# for i in images:
# jpg_rl = i["data-origi... |
import numpy as np
#import os
#import math
#from collections import defaultdict
class bModel:
"Create matrices"
def __init__(self,regN):
self.state_vector_curr = np.empty([(2*regN+1),1])
#self.P = []
self.Ep = np.random.normal(0.1, 0.1, 4212)
#self.X_all = []
self... |
import time
import numpy as np
def standard(all_elements, subset_elements):
"""
Standard way to find the intersection of two sets
:param all_elements:
:param subset_elements:
:return:
"""
start = time.time()
verified_elements = []
for element in subset_elements:
if element ... |
def get_input():
with open('day4input.txt') as f:
r = f.read().split('-')
return int(r[0]), int(r[1])
def part1_condition(n):
s = str(n)
prev = 0
repeated = False
nRepeats = 1
for c in s:
digit = int(c)
if digit < prev:
return False
if digit == prev:
nRepeats += 1
else:
if nRepeats >= 2:
... |
# coding: utf-8
# entradas:
NC = int(input())
i, n, k, remover = 0, 0, 0, 0
l = []
while (i < NC):
remover = 0
i += 1
n, k = [int(a) for a in input().split(" ")]
# computações
l = list(range(1, (n+1)))
while (len(l) > 1):
remover += (k - 1)
while (remover >= n):
remo... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2019, Nigel Small
#
# 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
#
# Unle... |
"""
OBJECTIVE: Given a list, sort it from low to high using the SELECTION SORT algorithm
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order)
from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1... |
from flask.ext.restful import Resource
from flask import send_file
class Documentation(Resource):
def get(self):
return send_file('documentation.html')
|
def reverse(string, low, way, array):
if low == len(string):
if len(way) ==3:
array.append(way)
return
for end in range(low + 1, len(string) + 1):
sub = string[low: end]
if sub == sub[::-1]:
reverse(string, end, way + [sub], array)
def palindrome_string(string):
array = []
reverse(string, low=0, way... |
1. Which of the following are constant in regards to time complexity?
a. variable assignments
b. accessing an element in an array by index
c. searching for an element in a linked list
d. in a loop where there are only arithmetic operations inside the loop
e. arithmetic operations
f. searching fo... |
from typing import List, Dict, Any
from mapnlp.alg.chunking import Chunker
from mapnlp.data.chunk import Chunk
from mapnlp.data.morpheme import Morpheme
@Chunker.registry
class IndependentRuleChunker(Chunker):
"""
Simple Rule-based Chunker
where each chunk has only one independent word and some adjunct/... |
#Colt Bradley
#2.25.16
#Homework 12
#import modules
import numpy as n
#define variables
m = 14
l = 1.2
g = 9.8
theta = 35
#Define the matricies
big = n.matrix([[1, 0 ,-n.cos(theta)],[0,1,n.sin(theta)],\
[0, -l/2., n.sin(theta)*l/2]])
col = n.matrix([[0],[m*g],[0]])
#use linear algebra package, pri... |
# transformer.py
#
# Copyright(c) Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
# Licensed under MIT
# Version 2.0.0
import os
import re
from PIL import Image
from app.cards.card import Card, SHAPES, FACE_VALUES
from app.cards.error import TransformerError
from app.blackjack.game.error import GameError
MOVE_X = ... |
#Tic-Tac-Toe
#top-L, top-M, top-R
#mid-L, mid-M, mid-R
#low-L, low-M, low-R
import pprint
import time
theBoard = {'top-L':' ','top-M':' ','top-R':' ',
'mid-L':' ','mid-M':' ','mid-R':' ',
'low-L':' ','low-M':' ','low-R':' ',}
reset = {'top-L':' ','top-M':' ','top-R':' ',
'mid-L':'... |
from django.shortcuts import render
# Create your views here.
import time
from pool import SQLPoll
from django.shortcuts import render, redirect
from django.core.paginator import Paginator
# Create your views here.
def index(request):
request.encoding = 'utf-8'
pag = request.GET.get('pag')
if pag:
... |
from django.shortcuts import render, redirect
from .models import Course
# Create your views here.
def index(request):
context = {
"courses": Course.objects.all()
}
print "hello i am the index page return statement"
return render(request, 'coursesapp/index.html', context)
def addcourse(request... |
from django.urls import path, re_path
from django.views.generic import TemplateView
from workouts import views
from workouts import api_views
app_name='workouts'
urlpatterns = [
############################
# normal django view urls
############################
# workouts index view
path('', Temp... |
"""
Generates sample directories for FID scoring
"""
import argparse
import logging
import pickle
from pathlib import Path
import imageio
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from model.vae import VAE
from model.hm import HM
from dataset.celeba import build_da... |
import socket
import threading
import queue
import sys
from my_AES import AESCipher
from my_RSA import RSAClass
class ClientCom:
def __init__(self,server_ip, port, msg_q):
self.running = False
self.my_socket = socket.socket()
self.server = server_ip
self.port = port
... |
"""
This module should be used to test the parameter and return types of your
functions. Before submitting your assignment, run this type-checker. This
typechecker expects to find files twitterverse_functions.py, small_data.txt,
and typecheck_query.txt in the same folder.
If errors occur when you run this typechecker... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Tests that recipes are on their best behavior.
Checks that recipes only import modules from a whitelist. Imports are
generally not safe in re... |
from datetime import datetime, timedelta
from typing import List
from entities.GpsFix import GpsFix
class LiveStayPoint(object):
"""
Represents a stay point as a spatial object. In conjunction with Visit, it would represent the full spatial time
relevance in user mobility
Attributes:
latitud... |
import json
import csv
import os
import sys
import pandas
from pandas.io.json import json_normalize
import pandas.io.json
arg1="/home/urvi/Downloads/samplenestedjson/"
file_list=[]
if os.path.exists(arg1):
l=os.listdir(arg1)
for each_file in l:
if each_file.endswith(".json"):
print("Iteration")
file_list... |
import json
import graphene
import uuid
from pprint import pprint
class User(graphene.ObjectType):
id = graphene.ID()
username = graphene.String()
n_posts = graphene.Int(required=False)
users = [
User(id=uuid.uuid4(), username="Jack", n_posts=0),
User(id=uuid.uuid4(), username="Bob", n_posts=10),... |
""" Binary Search """
def binary_search(arr, item):
arr.sort()
first = 0
last = len(arr)
found = False
while first<=last and not found:
middle = (first+last)//2
if arr[middle] == item:
found = True
else:
if item < arr[middle]:
last = middle-1
else:
first = middle+1
if found:
return foun... |
#!/usr/bin/env python
#Author: Dale Housler
#Date: 10-10-2013
#OS: UNIX
#Program Description: This file should run the os commands
#Last updated: 13-04-2014
#Open each PDB directory of interest (manually)
#Make sure ('export LD_LIBRARY_PATH=/usr/local/lib') is typed at the command
#prompt if running python3.3 and ... |
#
# calculator for cross-sectional properties
#
# x is the axial direction and y,z and the cross-sectional axes
#
import numpy as np
# ===================================================================
# solid circle
# ===================================================================
density = 2700 # SI [... |
#! /usr/local/bin/python
# runs extract.py and compiles and runs nn-nlp.c
# Anthony Pasqualoni
# Independent Study: Neural Networks and Pattern Recognition
# Adviser: Dr. Hrvoje Podnar, SCSU
# June 27, 2006
import os
import random
import sys
# amount of runs:
if (len(sys.argv) > 1):
runs = sys... |
import feedparser
from sys import argv
abc=feedparser.parse('https://www.abc.es/rss/feeds/abc_EspanaEspana.xml')
veintem=feedparser.parse('https://www.20minutos.es/rss/')
rtve=feedparser.parse('http://api2.rtve.es/rss/temas_espana.xml')
w=int(argv[1])
noticias_abc = abc['entries'][:w]
noticias_veintem = veintem['entr... |
from analysis.blasting import blast_record_set
__author__ = 'GG'
class GenomeSet(object):
"""Store data relative to a whole genome or set of contigs."""
def main(self):
print "This is a GenomeSet object."
def __init__(self, in_file, name):
self.in_file = in_file
self.name = name
... |
from oldowan.mtconvert.seq2sites import seq2sites
from oldowan.polymorphism import Polymorphism
def test_normal_polyC():
"""Normal Poly C stretch at end of HVR3
Seq: CAAAGACACCCCCCACA
Seq: CAAAGACACCCCCCACA
rCRS: CAAAGACACCCCCCACA
Sites: <None>
"""
seq = 'CAAAGACACCCCCCACA'
result ... |
import os
import json
from hotbox_designer.reader import HotboxWidget
from hotbox_designer.data import load_templates, load_json
from hotbox_designer.manager import (
launch_manager, initialize, show, hide, switch, load_hotboxes) |
"""
UTILITIES FOR SALES TREND ANALYSIS
CLASSES:
-- ImportSalesData(product_id)
-- SalesTrendsDF(ts, period_wks, end_date=None, MA_params=None,
exp_smooth_params=None, normed=True)
-- RankProductsPlacesPlaces(product_stats_df, N_results=None)
MAJOR FUNCTIONS:
-- SalesStatsDF(product_IDs, period_... |
from django.conf.urls import include, url
from django.contrib import admin
from datasets import views
urlpatterns = [
url(r"^dssh/", views.AddNewDSS.as_view(), name="addssh"),
url(r"^uploadbranchcodes/$", views.UploadBranchCode.as_view(), name="uploadbranchcode"),
url(r"^submission/new/dssh/", views.AddNe... |
import torch.nn as nn
import torch
from relogic.logickit.base.utils import log
from typing import Tuple
from relogic.logickit.modules.input_variational_dropout import InputVariationalDropout
from relogic.logickit.modules.bilinear_matrix_attention import BilinearMatrixAttention
import copy
import numpy
from relogic.logi... |
def swap(first, second): # Такое название аргументов написано в задании
if len(first) == len(second):
for i in range(len(first)):
first[i], second[i] = second[i], first[i]
elif len(first) > len(second):
min_len = len(second) # Длинна 2 сп... |
"""
calculator.py
Using our arithmetic.py file from Exercise02, create the
calculator program yourself in this file.
"""
from arithmetic import *
def calculator():
while True:
input = raw_input(">") #get input from user here
tokens = input.split(" ")
print tokens
if tokens[0] == ... |
try:
from ptop.settings.local import *
except ImportError:
from ptop.settings.base import *
|
import numpy as np
nulist = [0,0.1,0.2,0.5,1,2,3,4,5]
surffield = []
for nu in nulist:
field = np.loadtxt("nu"+str(nu)+".dat", usecols=(5,))
if nu == 0:
zerofield = min(field)
maxfield = min(field)
surffield.append([nu, maxfield, maxfield/zerofield])
np.savetxt("enhancement-factors.dat",surffield)
|
from rest_framework import permissions
class IsMemberOfChat(permissions.BasePermission):
def has_object_permission(self, request, view, chat):
if request.user:
print(chat.members.all())
return request.user in chat.members.all()
return False
class IsAuthorOfChatMessage(perm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.