text stringlengths 38 1.54M |
|---|
# -*- coding: utf-8 -*-
import scrapy
import redis
from codeforawler.items import SubmitItem
#xpaths for extracting the submission info
entry_xpath = '//table[@class="status-frame-datatable"]//tr[@data-submission-id]'
url_base = "http://www.codeforces.com/problemset/status/page/%d?order=BY_ARRIVED_DESC"
class Submit... |
SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
def calculate_price(number_of_tickets):
return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining >= 1:
print("There are {} tickets reamining".format(tickets_remaining))
name = input("What is your name? ")
num_ti... |
#!/usr/bin/env python
# coding=utf8
#
# lastfm.py
#
# ...
#
# martind 2008-12-09, 21:44:01
#
from optparse import OptionParser
import sys
from xml.etree import ElementTree as ET
import storm.locals
from feedcache.search import Searcher
# ========
# = conf =
# ========
#http://ws.audioscrobbler.com/2.0/?method=user... |
"""
a, b, c, d = map(int, input().split())
i = 1
while True:
if a <= 0:
print('No')
break
elif c <= 0:
print('Yes')
break
if i % 2 == 0:
a -= d
else:
c -= b
i+=1
"""
n=int(input())
st=set()
for i in range(n):
s=input()
st.add(s)
print(len(st)) |
# Define a procedure, sum3, that takes three
# inputs, and returns the sum of the three
# input numbers.
def sum3(num1, num2, num3):
return num1 + num2 + num3
print sum3(1, 2, 3)
#>>> 6
print sum3(93, 53, 70)
#>>> 216 |
# 차이를 최대로
from itertools import permutations
n = int(input())
data = list(map(int, input().split()))
permuList = list(permutations(data, n))
result = 0
for permu in permuList:
permuSum = 0
for i in range(n-1):
permuSum += abs(permu[i] - permu[i-1])
result = max(result, permuSum)
print(result)
... |
def agnostic_binary_search(arr, target):
# O(n)
# loop throiugh the entire array, checking each array element
# to see if it matches the target
# O(n)
# comparing the value of each element to see if its less than or equal to the target element
# How do i achieve an O(log n) runtime?
# We're... |
'''
Moldoveanu Davide
Hamming Distance
'''
def hammingDistance(string1, string2):
distanza = 0
for n in range(len(string1)):
if string1[n] != string2[n]:
distanza += 1
return distanza
def main():
dna1 = input("Insersci il primo DNA: ")
dna2 = input("Inserisci il secondo DNA: ")
... |
from builtins import staticmethod
class QueryHelper():
@staticmethod
def processQuery(query, info):
q = query.split(";")
begin = int(q[1])
end = int(q[2])
isInverted = q[3]=="1"
isRotated = q[4]=="1"
str = info[begin:end]
result = str.... |
n=int(input())
space=0
val=n
for i in range(0,(n*2)+1):
if(i<n):
print(str(("* ")*val)+str((" ")*space)+str(("* ")*val))
space=space+(2+2)
val=val-1
else:
print(str(("* ")*val)+str((" ")*space)+str(("* ")*val))
space=space-(2+2)
val=val+1
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Finally a model that works
Usage:
$ spark-submit model_v5.py <any arguments you wish to add>
'''
# Import command line arguments and helper functions(if necessary)
import sys
# And pyspark.sql to get the spark session
from pyspark.sql import SparkSession
from py... |
# match al-turayya places
import reverse_geocoder as rg
coordinates = (39.46975, -0.37739)
results = rg.search(coordinates)
print(results) |
import math
import statistics
import pandas as pd
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
from bokeh.io import curdoc
from bokeh.models import HoverTool
from bokeh.models.formatters import DatetimeTickFormatter
from bokeh.models.widgets import Slider
from d... |
from pandas import *
from numpy import *
a=DataFrame({"Name":["a","b","c","d"],"Roll No":[23,24,67,89],"Mark":[56,74,78,79]})
b=DataFrame({"chr":["e","f","g","h"],"No":[29,39,49,59],"id":[49,74,68,99]})
print(a)
print(a.info())
print("-------------------------------2nd Sheet---------------------------")
print(b)
pr... |
import datetime
from django.db import models
from django.urls import reverse
from djmoney.models.fields import MoneyField
from shared.models import Contact, Sponsor
STATUS_CHOICES = (
('Open', 'Open'),
('Closed', 'Closed'),
('In Progress', 'In Progress'),
('Active', 'Active'),
('Cancelled', 'Can... |
import networkx as nx
from sortedcontainers import SortedDict, SortedList
import operator
class Node:
def __init__(self, low, high):
self.low = low
self.high = high
self.max = high
self.edges = []
self.left = None
self.right = None
self.height = 0
def ... |
# coding=utf-8
"""
Selenium相关工具类
"""
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import environment as env
def open_chrome(use_user_dir: bool = True):
""" 启动Chrome浏览器
:param use_user_dir: <bool> 是否使用本地Chrome浏览器中已登录的Google账号(默认使用)
:return <selenium.webdriver.chr... |
import asyncio
import socketio
from server.gameServerMenager import GameServerMenager
from server.auslastung import Workload, get_system_status
URL = 'http://127.0.0.1:5000/'
sio = socketio.AsyncClient()
server_menager = GameServerMenager()
def collect_all_data():
data = {}
data['game_server'] = server_mena... |
import RPi.GPIO as GPIO
import time
channel = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(21, GPIO.OUT)
def callback(channel):
if GPIO.input(channel):
print ("Sound Detected!")
GPIO.output(21, True)
else:
print ("Sound ... |
from django import forms
from apps.income.models import Income
from django.conf import settings
class IncomeForm(forms.ModelForm):
class Meta:
date_payment = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS)
model = Income
fields = '__all__'
def __init__(self, *args, **kwarg... |
from django.contrib import admin
from .models import AirPlane, AirPort, Flight_captain, From_to, Time_line
# Register your models here.
admin.site.register(AirPlane)
admin.site.register(AirPort)
admin.site.register(Flight_captain)
admin.site.register(From_to)
admin.site.register(Time_line)
|
from utilities import NeuralNetwork
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn import datasets
# Load MNIST datasets and apply min/max scaling
# Pixel intensity [0, 1]
# 8 * 8 (64 dimensions)
prin... |
"""=============================
Subclassing ndarray in python
=============================
Introduction
------------
Subclassing ndarray is relatively simple, but it has some complications
compared to other Python objects. On this page we explain the machinery
that allows you to subclass ndarray, and the implicati... |
"""
Molecular kernels.
To be used as part of CartesianProductKernel
Kernels to be implemented:
* Graph-based
* Fingerprints as vectors
* Fingerprints for molecular similarity
* String-based
@author: kkorovin@cs.cmu.edu
TODO:
* Implement the remaining graph-based kernels
* Graphlets do not work
* For fingerprints, d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""genome admin view"""
__author__ = "Kingshuk Dasgupta (rextrebat/kdasgupta)"
__version__ = "0.0pre0"
from flask.ext.admin.contrib.sqla import ModelView
from webapp.models import GenomeRule, GenomeCategory
class GenomeRuleView(ModelView):
column_list = (
... |
#!/usr/bin/env python3
import pycx4.pycda as cda
from cservice import CXService
from settings.cx import v2k_cas
class V2KWatcher:
def __init__(self):
self.c_v2k_regime = cda.StrChan(v2k_cas + '.Regime', on_update=True)
self.c_bep_state = cda.StrChan(v2k_cas + '.BEP.State', on_update=True)
... |
# -*- encoding: utf-8 -*-
'''
@File : eval.py
@Time : 2019/07/08 09:41:16
@Author : Painter
@Contact : painter9509@126.com
'''
import os
import shutil
from glob import glob
from multiprocessing import Process
import subprocess
import numpy as np
import torch
import init_path
from bev_detection.data.d... |
import operator
import random
from collections import deque
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import OneHotEncoder
class LearningAgent:
def __init__(self, replay_size=100000, batch_size=128, gamma=0.995,
epsilon=1, min_epsilon=0.05, eps... |
#! /usr/bin/env python
import docopt
import collections
from pylib import SeqFeatureIO
__doc__ = '''
Usage: gff3_to_bed.py [options] GFF3
This converts a gff3 file to a UCSC-style bed file, grouping
fetures by gene.
Options:
--gene-name-attr ATTR gene name attribute [default: Name]
--gene-feature GENE ... |
from flask import Flask, render_template, redirect, session, request
import random
app = Flask(__name__)
app.secret_key='ThisIsSecure'
@app.route('/')
def index():
if not 'random' in session:
session['random']=random.randint(1,100)
session['format']='hide'
print(session['random'])
return... |
# Generated by Django 2.1.8 on 2019-05-27 05:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='address_info',
fields=[
('id', models.AutoF... |
from __future__ import print_function
import torch
from PIL import Image
import inspect, re
import numpy as np
import os
import collections
import json
import csv
from skimage.exposure import rescale_intensity
import matplotlib.pyplot as plt
from openpyxl import load_workbook
import pandas as pd
from shutil import rmtr... |
# Generated by Django 2.2.4 on 2020-06-30 07:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0032_auto_20200611_1722'),
]
operations = [
migrations.AlterField(
model_name='citizenship',
name='code',
... |
nth = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth',
'seventh',
'eighth',
'ninth',
'tenth',
'eleventh',
'twelfth'
]
phrases = [
"a Partridge in a Pear Tree",
"two Turtle Doves",
"three French Hens",
"four Calling Birds",
"five Gold Rings",
... |
#!/usr/bin/python
import ROOT
from ROOT import std, gROOT, gStyle, gPad, TCanvas, TH1, TH1D, TH2D, TLegend, TLine, TFile, TTree, TLorentzVector, TMath, TVirtualPad, TEventList, TFitResultPtr
import os
import rootstyle
histos = {}
def addHists(name,rebin=1):
prefixes = ["HardProcess:NoSelection:",
"H... |
from django.contrib import admin
from django.urls import include, path
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
app_name = "issues"
urlpatterns = [
path('', include('issues.urls')),
path('admin/', admin.site.urls, name='admi... |
import myPLA as pla
import numpy as np
import time
def main():
TRAIN15_FILE = "ntumlone%2Fhw1%2Fhw1_15_train.dat"
TRAIN18_FILE = "ntumlone%2Fhw1%2Fhw1_18_train.dat"
TEST18_FILE = "ntumlone%2Fhw1%2Fhw1_18_test.dat"
TRAIN15_DATA = np.loadtxt(TRAIN15_FILE, dtype=np.float)
x15 = np.column_stack((np.on... |
'''
------------------------------------------------------------------------------
Copyright (c) 2015 Microsoft Corporation
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 restriction,... |
import types
import urllib
from typing import Callable, AnyStr
from pyramid.renderers import get_renderer
from zope.interface.registry import Components
import logging
logger = logging.getLogger(__name__)
def get_exception_entry_point_key(exception):
x = getattr(exception, "__name__", None) or exception.__clas... |
# If you could invite anyone, living or deceased, to dinner, who
# would you invite? Make a list that includes at least three people you’d like to
# invite to dinner. Then use your list to print a message to each person, inviting
# them to dinner.
dinner_guests = ['Joeji', 'Elon Musk', 'OpenAI']
print(
f"Hey {din... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 19:59:36 2020
@author: nasil
"""
def fibonaci(N):
F = [1,2]
while True:
new_element = F[-1] + F[-2]
if new_element < N:
F.append(new_element)
elif new_element == N:
F.append(new_element)
break
... |
"""
Final Exam Review HW 3
Create a small program which asks for 3 numbers, The program adds the first 2 numbers and multiplies the 3rd number with the sum of the 2 numbers
Example:
Please enter your first number:
22
Please enter your second number:
3
Please enter your third number:
5
Answer:
Sum: ( 22 +3) = 25
Pro... |
import sys
import os
def split_chain(inputfile, outdir):
result_list = []
# exclude ".pdb"
base_file_name = os.path.basename(inputfile)[:-4]
with open(inputfile, "r") as f:
outfile = None
current_chain = ""
for line in f:
if line[0:4] != "ATOM":
conti... |
ans = []
ranking = []
def find(d,table,word,wich,st,name):
global ans
if d[wich] == 0 and word in name:
ans.append(st)
ranking.append((name,wich))
else:
for i in table[wich]:
ne, name = i
find(d,table,word,ne,st+"/"+name,name)
def solution(data, word):
a... |
"""
Configuration Class
"""
import os
import json
import yaml
import numpy as np
class JsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, CfgObject):
return obj.serialize()
return json.JSONE... |
from django.shortcuts import render, render_to_response,get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required,permission_required
from venta.apps.principal.models import *
from venta.apps.usuario... |
#!/usr/bin/env python
"""
*****************************************************************
Licensed Materials - Property of IBM
(C) Copyright IBM Corp. 2020. All Rights Reserved.
US Government Users Restricted Rights - Use, duplication or
disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*************... |
"""Export a subtree as an OGGBundle.
Usage:
export_subtree_bundle.py
(--with-local-roles | --without-local-roles)
(--dossiers-with-parent-reference | --dossiers-with-parent-guid)
<path>
"""
from Acquisition import aq_inner
from Acquisition import aq_parent
from collections import defaultdict
from collections i... |
import numpy as np
from scipy import sparse
from .validation import is_symetric_or_tri
def get_intra_mask(lengths, counts=None):
"""
Returns a mask for intrachromosomal interactions
Parameters
----------
lengths : ndarray, (n, )
lengths of the chromosomes
counts : ndarray or sparse m... |
def counting_sheep(n):
if n==0:
return "INSOMNIA"
s = set(str(n))
val = n
while len(s)<10:
val += n
s |= set(str(val))
return val
n = int(raw_input())
for i in range(n):
start = eval(raw_input())
sheep = counting_sheep(start)
... |
import socket
import time
class P2P_Station:
def __init__(self,
AppID = 2020,
IPv4_server_TCP = "server.singularity-blog.top",
IPv4_server_UDP = "flow.singularity-blog.top",
port_server_TCP = 8000,
port_server_UDP = 8001,
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from split import split_flac, merge_flac, call_process
from split import wav_to_flac, flac_to_wav, wav_to_ape, ape_to_wav, wav_to_wv, wv_to_wav
from subprocess import Popen, PIPE, STDOUT
import traceback
import subprocess
import argparse
import os
import... |
""" dnpHydration module
This module calculates hydration related quantities using processed ODNP data.
"""
import numpy as np
from scipy import interpolate
from scipy import optimize
class FitError(Exception):
"""Exception of Failed Fitting"""
pass
class AttrDict(object):
"""Class with Dictionary-li... |
#import datasets
import os
from numpy.random import randint
import random
import numpy as np
import cv2
from cv2 import imread
import torch.utils.data
from torch.utils.data import Dataset
act2id = {
"BG": 0, # background
"Diving": 1,
"Golf": 2,
"Kicking": 3,
"Lifting": 4,
"Riding": 5,
"... |
import csv
from trie import Trie
''' arquivo que guardara a tabela hash utilizada no projeto '''
class ElemHash():
def __init__(self):
self.movieid = 0
self.generos = None
self.raiting = 0.0
self.num_aval = 0
self.filme = None
# calcula a hash de acordo com o movieid do usuario
def hashing_function(siz... |
import numpy as np
from itertools import combinations
import lossGM as loss
import featureMap as fm
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
import flatten
import os
import copy
from functools import partial
import time
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
def parfor(information... |
from entropy import *
import logging as LOG
from Queue import Queue
from socket import AF_INET, socket, SOCK_STREAM
import sys
from serialization import *
from threading import Thread, Lock
root_port21k = 21000
root_port20k = 20000
address = 'localhost'
mHandler = None
def master_logic(line, client_vv, index):
LO... |
#!/usr/bin/env python
# https://simpy.readthedocs.io/en/latest/topical_guides/events.html
import simpy
class School:
def __init__(self, env):
self.env = env
self.class_ends = env.event()
self.class_begins = env.event()
self.pupil_procs = [env.process(self.pupil(i)) for i in range(3... |
import os
from pathlib import Path
import pytest
from cleo import Application
from cleo import CommandTester
from poetrify.cli import GenerateCommand
@pytest.fixture(scope="function", autouse=True)
def setup_repos(request):
"""Reset current working directory and remove pyproject.toml"""
starting_directory = ... |
from julia import CubicMap
multibrot = CubicMap(a=complex(1, 1))
multibrot.draw_multibrot(res_x=2048, res_y=2048, iterations=300, x_range=(-2, 2), y_range=(-2, 2)) |
import random
# Есть список input_list (python list) целых чисел длинной N. Необходимо выбрать k случайных элементов без повторений по
# индексу . Алгоритм решения должен быть оптимальным по сложности и по ресурсам, определить сложность в нотации O(N,k)
#
# Переводить список в другие структуры данных нельзя. Для получ... |
a = [10, 20, 30, 40, 50, 60]
#def cycle(coll):
# i = 0
# while True:
# yield coll[i]
# i += 1
# if i >= len(coll): i = 0
from itertools import cycle
for i in cycle(a): print(i)
|
# Generated by Django 2.1.4 on 2019-02-11 21:49
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0016_auto_20190108_1729'),
]
operations =... |
def multiple3: 3 % 0 =
def multiple5: 5 % 0 =
def multiple15: 15 % 0 =
def rangeFrom1: 1 switch interval
def fizzbuzz n:
(
(n multiple15 ['FizzBuzz']) # if
(n multiple5 ['Buzz']) # elif
(n multiple3 ['Fizz']) # elif
[n] # else
) case
# MA... |
import MeCab
import sys
tagger = MeCab.Tagger()
for line in tagger.parse(sys.argv[1]).splitlines():
if line != "EOS":
surface, feature = line.split("\t", 1)
print(surface, ", <", feature, ">")
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-02 13:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('oaiso', '0042_genre_relationship'),
]
operations = [
migrations.RemoveField(
... |
import flask_bcrypt
from datetime import datetime
from starter import db
from model.base_model import BaseModel
roles = db.Table('ETL_USER_ROLE',
db.Column('USER_ID', db.Integer, db.ForeignKey('ETL_USER.id'), primary_key=True),
db.Column('ROLE_ID', db.Integer,... |
# Generated by Django 3.0.5 on 2020-04-25 23:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('map', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='store',
old_name='placeID',
... |
from django.urls import path
from rest_framework import routers
from .api import FoodViewSet,RestaurantViewSet,CustomerViewSet,OrderViewSet,customer_list
from rest_framework.urlpatterns import format_suffix_patterns
router = routers.DefaultRouter()
router.register('api/foods',FoodViewSet,'foods')
router.register('api... |
import logging
from gym.envs.registration import register
logger = logging.getLogger(__name__)
register(
id='nbodies-simple-v0',
entry_point='nbodies.envs:SimpleNbodiesEnv',
)
register(
id='nbodies-v0',
entry_point='nbodies.envs:NbodiesEnv',
)
register(
id='nbodies-specialReward-v0'
entry_po... |
import argparse
import pickle
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import torch
import torch.nn as nn
from torchvision import transforms
from model import ImageEnc, CaptionGen
from vocab import Vocabulary
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def g... |
from django import forms
from django.apps import apps
from .constants import (
QUESTION_IDEA_GROUPS, QUESTION_IDEA_TYPES, QUESTION_STARTUP_GROUPS,
QUESTION_STARTUP_TYPES, QUESTION_REGISTRATION_GROUPS, QUESTION_REGISTRATION_TYPES,
)
class QuestionIdeaAdminForm(forms.ModelForm):
"""
Form for QuestionIde... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {integer[]} preorder
# @param {integer[]} inorder
# @return {TreeNode}
def buildTree(self, preorder, inorder):
if len(preorder) == 0 or len(inorder) == 0 or len(preorder) != len(inorder):
ret... |
#Algorithm : count number of 0's in a given binary array
def count(lst, start, end):
totalZero = 0
#base case if empty list
if start == end:
return 0
#base case single element
if start == end-1:
if lst[start] == 0:
... |
# This file is executed on every boot (including wake-boot from deepsleep)
import webrepl
import machine
machine.freq(240000000)
import os
webrepl.start(password = 'x')
# For allowing a connection with ampy, esp osdebug needs to be turned off.
import esp
esp.osdebug(None)
|
import numpy as np
from NeuralNet_2 import costs
from NeuralNet_1 import X_train, y_train_oh
import matplotlib.pyplot as plt
# Set range of values for meshgrid
m1s = np.linspace(-15, 17, 40)
m2s = np.linspace(-15, 18, 40)
M1, M2= np.meshgrid(m1s, m2s) # create meshgrid
# Determine costs for each coordinate... |
import numpy as np
def sixteen2eight(img: np.ndarray, Clim: tuple) -> np.ndarray:
"""
scipy.misc.bytescale had bugs
inputs:
------
I: 2-D Numpy array of grayscale image data
Clim: length 2 of tuple or numpy 1-D array specifying lowest and highest expected values in grayscale image
Michael... |
import sys
sys.path.append("../util")
from mongodb_connector import DBConnector
from optparse import OptionParser
from news_parser import NewsParser
from linis_parser import LinisParser
from text_parser import TextParser
def parse_options():
parser = OptionParser()
parser.add_option("-d", "--debug", dest="debug",... |
# -*- coding: utf-8 -*-
import tensorflow as tf
v1 = tf.Variable(tf.constant(1.0,shape=[1]),name="v1")
v2 = tf.Variable(tf.constant(2.0,shape=[1]),name="v2")
result = v1 + v2
init_op = tf.initialize_all_variables()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init_op)
save_path = saver.sav... |
import numpy as np
import pandas as pd
from dcase_util.data import DecisionEncoder
class ManyHotEncoder:
""""
Adapted after DecisionEncoder.find_contiguous_regions method in
https://github.com/DCASE-REPO/dcase_util/blob/master/dcase_util/data/decisions.py
Encode labels into numpy arrays w... |
# -*- coding: utf-8 -*-
import urllib2
import re
import datetime
import sys
import time
reload(sys)
sys.setdefaultencoding('utf-8')
def getDate(daysAgo):
date_got = datetime.datetime.now() + datetime.timedelta(days=-int(daysAgo))
return date_got
def corDate(Numb):
if int(Numb) < 10:
correctDate = '0' + str(N... |
#factorial
val=input('Enter a number:')
f=1
try:
n=int(val)
if n<0:
print('negative no!')
raise Exception
except Exception:
print('invalid entry')
else:
if n==0:
print('The factorial is 1')
else:
while n>0:
f=f*n
n-=1
... |
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')
print(tips.head())
# iris = sns.load_dataset('iris')
# print(iris.head())
# g = sns.PairGrid(iris)
# g.map(plt.scatter)
# g.map_diag(plt.hist)
# g.map_lower(sns.kdeplot)
# g.map_upper(plt.scatter)
# plt.tight_layout()
# f = sns.Fa... |
import unittest
import re
def is_clean_string(input_string):
"""Implement a function to determine if string doesn't have any special characters
Args:
input_string: input string
Returns: True if a string does not have any special characters
"""
match = re.match('[a-zA-Z]*', input_string)... |
import configparser
import json
import pickle
import sys
import unittest
sys.path.append('../')
from redisStorage import RedisStorage
class TestRedisStorage(unittest.TestCase):
def test_insert_contest(self):
config = configparser.ConfigParser()
config.read('../config.ini')
redis = RedisSt... |
###the sum tool returns the sum of array elemens over a given axis
##import numpy
##my_array = numpy.array([ [4, 2,4], [3, 4,5] ])
##print("sum \n{}".format(numpy.sum(my_array, axis = 0) ))
##print(numpy.sum(my_array, axis = 1) )
##print(numpy.sum(my_array, axis = None) )
##my_array = numpy.array([ [4, 2,4], [3, 4,5] ]... |
from nameko.rpc import rpc
import sojobs.scraping
class ScrapeStackOverflowJobListingsMicroService:
name = "stack_overflow_job_listings_scraping_microservice"
@rpc
def get_job_listing_info(self, job_listing_id):
listing = sojobs.scraping.get_job_listing_info(job_listing_id)
print(listing)
... |
from PIL import Image
from tqdm import tqdm
import h5py
import numpy as np
from view_content_h5py import view_content_of_h5py
def subdivide(image, w_tiles, h_tiles, swidth, sheight):
out = []
for sh in range(h_tiles):
for sw in range(w_tiles):
subimg = image[sh * sheight:(sh + 1) * sheight, sw * swidth:(sw + 1)... |
import subprocess
import pysam
import argparse
from Bio.Seq import Seq
import time
import os.path
import gzip
import ctypes
import sys
import shutil
from collections import defaultdict
import struct
import numpy as np
from tqdm import tqdm
from functools import reduce
import operator
import array
sys.path.append(... |
#coding=utf-8
'''
Created on 2016-12-1
@author: wuchaojie
'''
import json
import httplib
conn = httplib.HTTPConnection("10.10.10.195:7001")
conn.request("GET", "/CSRManagerWebSite/ccbSceneData?CCBRobotHashCode=baac43d762969b5346529bc26356d682")
#conn.request("POST", "/CSRBroker/queryAction")
response = conn.getrespon... |
from django import forms
class NewThreadForm(forms.Form):
title = forms.CharField(label='Title', max_length=100, widget=forms.TextInput(attrs={'size': '70'}))
comment_text = forms.CharField(widget=forms.Textarea(attrs={'style': 'height:400px', 'cols': "80"}))
class ReplyThreadForm(forms.Form):
comment_t... |
#coding: utf-8
import bs4
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(open("index.html"), "lxml")
# print soup.find_all('b')
# for tag in soup.find_all(re.compile("^b")):
# print(tag.name)
# print soup.find_all(["a","b"])
# for tag in soup.find_all(True):
# print(tag.name)
# def has_class_but_no... |
import os
from setuptools import setup, find_packages
from setuptools.command.develop import develop
namespace = ""
if [True for d in os.listdir(os.path.dirname(os.sys.executable)) if d.lower() == "lib"]:
PYDIR = os.path.dirname(os.sys.executable) ;# global python
else:
PYDIR = os.path.dirname(os.path.dirnam... |
from deepface import DeepFace
def represent(img_path, model_name, detector_backend, enforce_detection, align):
result = {}
embedding_objs = DeepFace.represent(
img_path=img_path,
model_name=model_name,
detector_backend=detector_backend,
enforce_detection=enforce_detection,
... |
"""Handle incoming requests and send back the picture"""
import io
from flask import Flask, Response, send_file, render_template
from time import sleep
from fractions import Fraction
try:
import picamera
from camera_pi import Camera
except:
print('Camera not found')
pass
app = Flask(__name__)
@app.rou... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# ==============================================================================
# Copyright (c) 2010, Matteo Bertozzi
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following cond... |
from ase.constraints import Filter,voigt_6_to_full_3x3_stress
import numpy as np
from ase.calculators.calculator import PropertyNotImplementedError
description = '''
Small
'''
class StrainFilter(Filter):
"""Modify the supercell while keeping the scaled positions fixed.
Presents the strain of the supercell a... |
"""
Client for testing, this is mostly copied from starlette 0.14.2
https://github.com/encode/starlette/blob/0.14.2/starlette/testclient.py
After that the standard test client for starlette started using threads to run the server and therefore
broke support for a database connection shared between the test code and t... |
config = {}
# Submit slurm option defaults
config['submit'] = {}
config['submit']['account'] = 'admin'
config['submit']['qos'] = 'admin'
# Reserve slurm option defaults
config['reserve'] = {}
config['reserve']['account'] = 'admin'
config['reserve']['users'] = ['jobl6604', 'holtat', 'joan5896']
|
121910301018 Gampa Tanmaya Manishree 9.25
121910301002 Gaddam Indu 9.06
121910301004 Vadada Venkata Phani Adarsh 8.69
121910301020 Vysyraju Asritha 8.58
121910301046 Sai Priyanka Asapu 8.58
121910301049 Gajjana Nikitha 8.53
121910301015 Datla Sreya 8.50
121910301001 Ganapabathula Sri Lekha 8.33
121910301051 Amarnath Go... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.