text stringlengths 38 1.54M |
|---|
import torch.utils.data as data
from glob import glob
import matplotlib.pyplot as plt
from torchvision import transforms
from PIL import Image
import random
import os
import numpy as np
import torch
class cudatatest(data.Dataset):
def __init__(self,scale):
super(cudatatest, self).__init__()
... |
"""
BSD 3-Clause License
Copyright (c) 2016-2019 Russ 'trdwll' Treadwell. All rights reserved.
"""
from django import forms
from django.contrib.auth.models import User
#from . models import UserProfile
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import ugettext_lazy as _
from c... |
from os import path
import serial
from time import sleep
from datetime import datetime
from twisted.internet import endpoints
from twisted.web import xmlrpc, server
from AutoFocus import AutoFocus, Camera
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create a file handler
handler... |
import networkx as nx
from numpy.random import random, choice, shuffle
from epidag.factory import get_workshop
import epidag.factory.arguments as vld
from abc import ABCMeta, abstractmethod
__author__ = 'TimeWizard'
__all__ = ['INetwork', 'NetworkLibrary', 'NetworkSet',
'NetworkGNP', 'NetworkBA', 'NetworkPr... |
import json
from pprint import pprint
import csv
hashmap = {}
result = []
# create hashmap -- mapping of objectID & index of object from restaurants_list.csv
with open('restaurants_list.json') as data_file:
restaurant_data = json.load(data_file)
for idx, obj in enumerate(restaurant_data):
objectID = o... |
from oauth2client import client, crypt
CLIENT_ID = '728044119950-mpcea0183l7c87lflutdide1vfdmvjrb.apps.googleusercontent.com'
def validate_user_id(userId):
# (Receive token by HTTPS POST)
if userId == -1:
print('USER ID ENTERED AS -1')
return -1
try:
idinfo = client.verify_id_token... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-01 01:47
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('oaiso', '0033_auto_20170701_1036'),
]
operations =... |
import re
import pandas as pd
from step4 import *
import imaplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from values import *
def fetchname(x):
your_string = re.sub('\W+', ' ', x)
bad_chars = ['Hi Rekha']
your_string = your_string.strip()
for i in... |
from django.shortcuts import render, HttpResponse, redirect
def index(request):
print "-----in the INDEX ROUTE------------"
try:
request.session['total_spent']
request.session['items_bought']
except:
request.session['total_spent'] = 0
request.session['items_bought'] = 0
print type(request.session['items_... |
#!/usr/bin/env python3.6
import argparse
import git
import random
import re
import sys
import database
check_commit_pool = set()
check_email2comparisons = dict()
def check_comparison_id(commit1, commit2):
assert commit1 != commit2
return commit1 + commit2 if commit1 < commit2 else commit2 + commit1
# A ... |
#python3
'''
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
The input array will only contain 0 and 1.
The lengt... |
import textgenrnn as tgr
ufo_tgr2 = tgr.textgenrnn(name='ufo_model2')
ufo_tgr2.train_from_file('training_data2.txt', new_model=True, batch_size=512, num_epochs=5, rnn_bidirectional=True, rnn_size=64)
ufo_tgr.generate_samples(temperatures=[0.35, 0.45, .55, .65, .75], return_as_list=False)
textgen = textgenrn... |
import subprocess
import time
import os
#-----------------------------------------------------------------------
def mapstate(winid):
"""
what is the mapped state of this window?
returns 'NoWindow','IsUnMapped','IsViewable'
"""
fd=subprocess.Popen('xwininfo -id "%s" 2>/dev/null'%(winid),shell=True... |
from plugins import BotPlugin
import re
class LetMeGoogleThatForYou(BotPlugin):
TRIGGER = "google"
def exec_plugin(self, command):
pattern = re.compile(r'google\s*(.+)$')
match = re.match(pattern, command)
if match:
query = match.group(1).replace(' ', '+')
ret... |
# -*- coding: utf-8 -*-
# @Time : 2021/4/22 3:10 下午
# @Author : AI悦创
# @FileName: Spider.py
# @Software: PyCharm
# @Blog :http://www.aiyc.top
# @公众号 :AI悦创
import requests
import cchardet
import traceback
import re
from bs4 import BeautifulSoup
import csv
def downloader(url, timeout=10, headers=None, debug=Fa... |
from .wauchier import WauchierAllowedPOS, WauchierAllowedLemma, WauchierTokens, Wauchier
from .floovant import FloovantTokens, FloovantAllowedPOS, FloovantAllowedLemma, Floovant
import copy
import time
DB_CORPORA = {
"wauchier": {
"corpus": Wauchier,
"tokens": WauchierTokens,
"lemma": Wauch... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/8/15 10:06
@Author : QDY
@FileName: 546. 移除盒子.py
@Software: PyCharm
"""
"""
给出一些不同颜色的盒子,盒子的颜色由数字表示,即不同的数字表示不同的颜色。
你将经过若干轮操作去去掉盒子,直到所有的盒子都去掉为止。
每一轮你可以移除具有相同颜色的连续 k 个盒子(k>= 1),这样一轮之后你将得到 k*k 个积分。
当你将所有盒子都去掉之后,求你能获得的最大积分和。
示例:
输入:boxes = [1,3,2,2,2,... |
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.reverse import reverse
from rest_framework.test import APIClient, APITransactionTestCase
from tests.factories.user import UserFactory
class CreateTokenForUserTest(APITransactionTestCase):
client = APIClient()
... |
#
#
# SSH brutforce cracker, based on project frome 'Violent Python'
# by TJ O'Connor
#
import pxssh
import time
from threading import *
maxConnections = 5
connection_lock = BoundedSemaphore(value = maxConnections)
Found = False
Fails = 0
def conn(host, user, password, release):
global Found
global Fails
... |
import io
import os
import selenium
import time
import requests
import numpy as np
from google_images_download import google_images_download
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.co... |
import tweepy, credentials
import time
def status(account):
creds = credentials.credentials(1)
consumer_key = creds[0]
consumer_secret = creds[1]
access_token = creds[2]
access_token_secret = creds[3]
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_to... |
from datetime import date, datetime
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render
from persona.models import PersonaModel
class PersonaForm(forms.Form):
nombre = forms.CharField(label='Nombre', max_length=100)
apellido = forms.CharField(label='Apel... |
# One Distribution Inside (ODIn)
import pandas as pd
import numpy as np
import math
from KFold import KFold
from random import shuffle
def CreateHistogram(scores, thresholds):
scores.sort()
hist = [0] * 12
hist[0] = np.searchsorted(scores, thresholds[0], side="right")
for i in range(1, 11):
right = np.se... |
#!C:\Python27\python
# -*- coding: utf-8 -*-
'''
Created on 2016年6月20日
@author: tc
'''
import unittest,time,sys
from common_actions.commonActions import CommonActions
from common_actions.advantageRechargeActions import AdvantageActions
class advantageActions(unittest.TestCase):
def setUp(self):
self.c... |
import pyglet
from pyglet.gl import *
window = pyglet.window.Window()
@window.event
def on_draw():
# window.clear()
glClear(GL_COLOR_BUFFER_BIT)
glLoadIdentity()
glBegin(GL_TRIANGLES)
glVertex2f(0, 0) # 3个坐标点
glVertex2f(window.width, 0)
glVertex2f(window.width, window.height)
glEnd(... |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
pass
class Product(models.Model):
product_name = models.CharField(max_length=256)
description = models.CharField(max_length=64)
img_url = models.CharField(max_length=128... |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, Normalizer
from neupy import algorithms, estimators, environment, layers, architectures
from sklearn import metrics
from sklearn.model_selection import cross_validate
from sklea... |
#!/usr/bin/python
import os
import sys
import asyncore, socket
import threading
import time
import Queue
import random
run = True
def handle_message(message):
outfile = '/tmp/message_handler_file'
with open(outfile, 'a') as f:
f.write('%s\n' % message)
return
class Consumer(threading.Thread):
... |
import pytest
from contextlib import ExitStack as does_not_raise
import math
class Solution:
def get_num_open(self, n):
"""
Given a number of lockers, n, get the number of open lockers after they have been
cycled in multiples of 1-n.
Only perfect squares will be left, so calculate... |
from django.db import models
class kind(models.Model):
name = models.CharField(max_length=200,help_text="enter a furniture kind: ")
def __str__(self):
return self.name
class furniture(models.Model):
title = models.CharField(max_length=200)
kind = models.ManyToManyField(kind,he... |
"""This file contains the helper RPCA function which calculate the rank and
sparsity of the outputs."""
import numpy as np
def get_rank(matrix, sigma):
"""This function returns the rank of the input matrix, D using its
singular values D_sigma."""
if not (matrix.ndim == 2):
raise Exception('Input ... |
import numpy as np
import pandas as pd
from math import floor
import os
from gensim.models import Word2Vec
from tqdm import tqdm
import tensorflow as tf
from class_model_vari import video2seq
import sys
### prepare directory path
test_path = sys.argv[1].rstrip('/')
output_path = sys.argv[2].rstrip('/')
#### load testin... |
import copy
from core.HqlParse import HqlParse
import re
import datetime
def convert2mysql_type(value,index):
result = value
if value.upper() == "STRING" and index < 70:
result = 'varchar(255)'
elif value.upper() == "STRING" and index > 70:
result = 'TEXT'
return result
def my_forma... |
# Generated by Django 3.1.7 on 2021-04-05 20:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('address', '0005_auto_20210405_1717'),
('core', '0004_auto_20210405_1706'),
]
operations = [
migrati... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('ERRO: por favor, digite um número do menu.')
continue
except KeyboardInterrupt:
print('Usuário preferiu não digitar esse número.')
return ... |
import json
import random
class Productionist(object):
"""A production system for in-game natural language generation from an Expressionist grammar.
Objects of this class operate over a probabilistic context-free generative grammar exported by
Expressionist according to requests originating from a game s... |
# 198. House Robber
# https:#leetcode.com/problems/house-robber/
class Solution:
def rob(self, nums) -> int:
prev, ans = 0, 0
for num in nums:
tmp = ans
ans = max(ans, prev + num)
prev = tmp
return ans
|
'''alien_0={}
alien_0['color']='green'
alien_0['points']=5
alien_0['x-position']=0
alien_0['y_position']=25
alien_0['speed']='medium'
print(alien_0)
del alien_0['points']
print(alien_0)
alien_0={'color':'red','point':'15'}
alien_1={'color':'blue','point':'10'}
alien_2={'color':'yellow','point':'5'}
aliens=[alien_0,a... |
from django.db import models
# Create your models here.
class MaterialInfo(models.Model):
MaterialName = models.CharField(max_length=30, null=False)
maker = models.CharField(max_length=30)
category = models.CharField(max_length=20)
ChemName = models.CharField(max_length=200)
TechInfo = models.Text... |
from tensorflow.keras.layers import Input, Conv2D, Conv2DTranspose, BatchNormalization, Activation, Dropout
from tensorflow.keras.applications import DenseNet121
import tensorflow as tf
def unet_model(input_tensor):
# contraction 1§l
conv_1_1 = Conv2D(filters=32, kernel_size=(3, 3), padding="same", name="conv... |
import boto3
from collections import defaultdict
from pprint import pprint
r53 = boto3.client('route53')
ec2 = boto3.client('ec2')
s3 = boto3.client('s3')
dangling_resources = defaultdict()
s3_all_buckets = s3.list_buckets()
r53_zone = r53.list_hosted_zones()
def ec2_info(ipaddress,record_name):
try:
inst... |
class Solution:
# @param {string} s
# @param {string[]} words
# @return {integer[]}
def findSubstring(self, s, words):
if not s or not words or not words[0]:
return []
wordDic, sDic = {}, {}
for item in words:
if item not in wordDic.keys():
... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
import pymongo
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from crawle... |
import isbnlib
import isbnlib._exceptions as exceptions
import isbnlib.dev._exceptions as goob_exceptions
def getBookData(isbn13):
try:
data = isbnlib.meta(str(isbn13), service='goob')
except goob_exceptions.NoDataForSelectorError:
# Google books not working
try:
data_open ... |
## MIT License
##
## Copyright (c) 2021 conveen
##
## 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, including without limitation the rights
## to use, copy, modify, mer... |
#print(f"Hello world {variable}")
def check(story):
rude_words = ["feo", "chiquito", "hola", "que", "hace"]
with open("my_story.txt") as my_story:
contents = my_mystory.read()
rude_count = 0
for rude in rude_words:
if rude in contents:
rude_count += 1
print(f"found rude word:... |
import pandas as pd
import numpy as np
def fetch_time(df, key):
"""
Identity, for time itself only?
t1 x1
t2 x2
t3 x3
->
t1 x1
t2 x3
t3 x3
"""
return df[key].to_numpy()
def fetch_diff(df, key):
"""
For accumulative quantities
t1 x1
t2 x2
t3 x3
->
... |
import ROOT
from ROOT import TLorentzVector
def lepHasOverlap(Chain, index, isGen = False):
#Check the flavor of the lepton and initialize variables
hasOverlap = False
inputVec = TLorentzVector()
inputVec.SetPtEtaPhiE(Chain._lPt[index], Chain._lEta[index], Chain._lPhi[index], Chain._lE[index])
... |
# Generated by Django 3.0.4 on 2020-04-05 09:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shopWeb', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Products',
fields=[
('id',... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution, third party addon
# Copyright (C) 2017- Vertel AB (<http://vertel.se>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of th... |
# this project is licensed under the WTFPLv2, see COPYING.wtfpl for details
from PyQt5.QtWidgets import (
QTabWidget, QAction,
)
from PyQt5.QtCore import pyqtSlot as Slot, pyqtSignal as Signal
from PyQt5.QtGui import QKeySequence
from .threads_widget import ThreadsWidget
from .thread_widget import ThreadWidget
fr... |
from threading import Thread
import threading
import time
def qsort(sets, left, right):
print("thead {0} is sorting {1}".format(threading.current_thread(), sets[left:right]))
i = left
j = right
pivot = int(sets[int((left + right) / 2)])
temp = 0
while i <= j:
while pivot > sets[i]:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayOpenLotteryRegionCreateResponse(AlipayResponse):
def __init__(self):
super(AlipayOpenLotteryRegionCreateResponse, self).__init__()
self._region_id = None
@... |
import pytest
import requests
class TestEventsUserScope(object):
env_id = "5"
event_id = "BeforeInstanceLaunch"
scope = "scalr"
def test_events_create(self,api):
create_resp = api.create("/api/v1beta0/user/envId/events/",
params=dict(envId=self.env_id),
body=dict(
... |
from transformers import BertTokenizer
from transformers import BertForTokenClassification
from transformers import BertConfig
from transformers import AdamW, WarmupLinearSchedule
import torch
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
import json
import os
from tqd... |
"""Unit test suite for the Bytes Streams examples in the AWS-hosted documentation.
.. note::
These tests rely on discoverable AWS credentials existing.
"""
import os
import tempfile
import pytest
from .test_i_aws_encrytion_sdk_client import skip_tests, SKIP_MESSAGE
from .docs_examples_bytes import cycle_file
@... |
# Francis Amani
# Pythion 2.0
""" Dictionaries """
# First Trial
print ''
student_details = { 'id':"16671/1313", 'name': "John Doe"
}
print student_details ['id']
# Second trial
print ''
student_details ['course'] = 'computer science'
print student_details
# Third trial
name = (raw.inpu... |
# Generated by Django 3.1.7 on 2021-03-29 12:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blogger', '0009_auto_20210326_1344'),
]
operations = [
migrations.AddField(
model_name='blog',
name='bio',
... |
"""
SCRIPT 1:
This script calculates the average topic distributions and average syntactic measures.
1. Function "get_genre_averages" is used for genre averages
2. Function "get_decade_averages" is used for decade averages
3. Results are saved as .csv and .png files
"""
import os
import pandas as pd
import matplotlib.... |
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(-np.pi,np.pi,500,endpoint=True)
y=np.sin(x)
plt.plot(x,y)
ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
ax.xaxis.set_ticks... |
'''
dia = 3
mes = "Março"
ano = 2021
print("Eu faço aniversário em {} de {} de {}.".format(dia,mes,ano))
'''
# nome = "clarice"
# nome = nome.capitalize()
# print(nome) #resultado = Clarice
''' palavra = "alura"
palavra.upper()
print(palavra) #qual é o resultado? = alura '''
'''# coding: utf-8... |
import sys
import os
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToText
from apache_beam.options.pipeline_options import PipelineOptions
import apache_beam as beam
from logging import basicConfig, getLogger, INFO
basicConfig(level=INFO, format='%(asctime)-15s %(levelname)s %(filename)-s:%(li... |
from params import *
from intersectionarc import *
from calculrayoncourbure import *
def cibleatteignable(segments,p,v):
[positioninit1,positioninit2,orientationinit1,orientationinit2,vinit1,vinit2,deltat,amaxlat,epsilonmax,amax,amin,tsb,l,larg,vmax,N,rv,m,alpha,lanti]=params()
Rminamaxlat=v**2/amaxlat
... |
def palindrome():
found = False
number = 9
while not found:
for i in range(1, int( number ** 0.5) + 1):
if number % i == 0:
x = str(number)
y = str(bin(number))[2:]
if (x[:len(x)/2] == x[len(x):len(x)/2:-1]) and (y[:len(y)/2] == y[len(y):le... |
import csv
import sys
import numpy as np
import matplotlib.pyplot as plt
def checkArgs():
if (len(sys.argv) != 4):
print "Please enter three arguments. For instance, run: \
\npython lr.py train.csv test.csv 0.005"
exit(0)
train_file = sys.argv[1]
test_file = sys.argv[2]
try:
... |
#coding:utf-8
import json
import random
import request
import time
print('####################创建协议开始##################')
##创建协议入参
data1 = {"transDesc":"test1","businessId":"2","channelType":"LFT"}
#创建协议请求地址
url1 = 'http://172.29.66.21:80/api/protocol/create'
t1 = request.rzequest(url1, data1)
sss1 = json.loads(t1)
... |
import numpy as np, os, multiprocessing, time
import myClass as STUC
ROOT = "new-data/russian/2016/"
TI = STUC.TI
Sess_dict = np.load(ROOT+"Sess_dict.npy").item(0)
''' the data structure of complex topic pattern
ldaStr=tuple(gamma),tau=tau,prob_list=Supp_gamma_tau[tau],supp=average,l=gamma_len,contain=tuple([tuple... |
'''Test utility functions'''
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import numpy as np
import wavenet.utils as utils
def test_sample_from():
distr = np.array([
[0.1, 0.2, 0.7],
[0.4, 0.5... |
import abc
from pygameAssets import pygameAssets, pygame
from object_display import Object_display
from recipe_data import Recipe_data
from points import Point, Rectangle
from price import Price
from pay import Pay
class Button(Object_display):
def __init__(self, w: int, h: int, coordinate: Rectangle):
su... |
from django.shortcuts import render, HttpResponse, redirect
def index(request):
return render(request, 'survey/index.html')
def process(request):
if request.method == "POST":
request.session['data'] = {
"Name": request.POST['name'],
"Location": request.POST['location'],
"Langua... |
#!/usr/local/bin/python3
import sys
import os
#function taken from https://stackoverflow.com/questions/2460177/edit-distance-in-python
def levenshteinDistance(s1, s2):
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2+1]
... |
from transformers import AutoModel
from torch import nn
class MiniModel(nn.Module):
def __init__(self, model_name, n_labels_A, n_labels_B):
super().__init__()
self.model = AutoModel.from_pretrained(model_name)
self.first_classifier = nn.Linear(768, n_labels_A)
self.second_classifie... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 02 18:27:00 2015
@author: Yang
"""
import pandas as pd
import numpy as np
s=pd.Series([1,3,5,np.nan,6,8])
print s
dates = pd.date_range('20130101', periods=6)
print dates
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
print df
df2 = pd.DataF... |
import math
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
count=0
primes=[True]*n
for i in range(2,int(math.sqrt(n))+1):
if primes[i]==False:
continue
for j in range(i*i,n,i):
... |
from typing import List
from ..parser.ast import AST, Node
from ..scanner.tokens import Tokens
from ..semantic import COMPUTATION_NODES, CONSTANT_NODES
class CodeGenerator:
"""
Generates code for the dc language from an AST of the ac language.
"""
def __init__(self, ast: AST):
self.ast = ast
... |
from os import listdir
from numpy import asarray
from numpy import savez_compressed
from PIL import Image
from mtcnn.mtcnn import MTCNN
from matplotlib import pyplot
def load_image(filename):
# load image from file
image = Image.open(filename)
# convert to RGB, if needed
image = image.convert('RGB')
# convert to ... |
import time
def addHeightsToDict(x, dictHeights):
if x in dictHeights:
dictHeights[x] = dictHeights[x] + 1
else:
dictHeights[x]=1
return dictHeights
start_time = time.time()
# f = open("B-small-attempt01.in")
# f = open("B-large01.in")
f = open("B-large1.in")
result = open('B-large1.in.txt', 'w')
# result = o... |
import json
import time
import tornado.websocket
import services.dbHandler as database
database.init_database()
debug = True
clients = []
# Socket Handler
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
if 'Hostname' in self.request.headers:
client_hostname = self... |
# marca centenario RJ
# functions
def draw_lines(points, t):
# set state
autoclosepath(True)
nofill()
stroke(0)
strokewidth(t)
# draw
beginpath()
_moveto = True
for point in points:
x, y = point
if _moveto:
moveto(x, y)
_moveto = False
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# df = pd.read_csv('test.csv')
# df = pd.read_csv ('test.csv', na_values = ['-','not available']) # '-' dan 'not available' diubah jadi NaN
df = pd.read_csv('test.csv', na_values={ #ubah per column (better ubah semuanya jadi Nan)
... |
# -*-coding:utf8-*-
from django.shortcuts import render_to_response
# Create your views here.
def login(request):
pass
|
x=0
def setup ():
size (400 , 400)
def draw ():
for x in range(5):
circle(random (0 , 400 ),random (0 , 400),10)
|
# -*- coding: utf-8 -*-
"""
Start on random article on Wikipedia and follow the first link
on main body of article that is not within parentheses or italicized,
repeating for each subsequent article until finding Philosophy page.
Stores 500 starting pages and their path lengths to Philosophy.
Keeps tracks of all visi... |
import logging
from datetime import datetime
from .exceptions import DoesNotExist, MultipleObjectsReturned
from .data import language_codes
logger = logging.getLogger(__name__)
class Model(object):
def __init__(self, data, collection):
self._collection = collection
self.conn = collection.conn
... |
from django.test import TestCase
from django.urls import reverse
from .models import meeting, meetingminutes, resource, event
from .views import newResource, getresources
from django.contrib.auth.models import User
# Tests the 'meeting' model
class MeetingTitleTest(TestCase):
def test_string(self):
meet=me... |
#! /usr/bin/env python
#__________________________________________________
# pyLorenz/utils/initialisation/
# gaussianindependantinitialiser.py
#__________________________________________________
# author : colonel
# last modified : 2016/10/9
#__________________________________________________
#
# class to hand... |
import os
dirname = os.path.dirname(__file__)
class File_Locations:
local_data_directory = os.path.join(dirname,"data")
"""
Available from https://www.neighborhoodatlas.medicine.wisc.edu/
"""
adi_location = os.path.join(dirname,"data/adi/US_blockgroup_15.txt")
"""
Available from cps.ipums.org
Current var... |
# -*- coding: utf-8 -*-
"""
Copyright (c) Dario Götz and Jörg Christian Reiher.
All rights reserved.
"""
import threading
import datetime
from keys import *
from config import Config
_CONFIG = Config(__name__)
class JudgingManager(object):
'''
Provides the judging management responsible for keepin... |
"""Base classes."""
from jupyter_server.extension.handler import ExtensionHandlerMixin
class TerminalsMixin(ExtensionHandlerMixin):
"""An extension mixin for terminals."""
@property
def terminal_manager(self):
return self.settings["terminal_manager"] # type:ignore[attr-defined]
|
from telegram.ext import Updater, CommandHandler, ConversationHandler,CallbackQueryHandler,MessageHandler, Filters
from telegram import InlineKeyboardMarkup,InlineKeyboardButton
import yaml, logging, os
import extract
import pdf_to_text
import telegram
INPUT_TEXT,INPUT_TEXT_C = range(2)
text = ""
INPUT_PDF, ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'stylesheets.ui'
#
# by: PyQt4 UI code generator 4.5.4
#
# WARNING! All changes made in this file will be lost!
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future... |
from django.urls import path
from vkrb.text.views import TextGetView
app_name = 'text'
urlpatterns = [
path('get/', TextGetView.as_view()),
]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 11:20:38 2018
@author: mtech
"""
"""
This programme (should) takes the raw data, sorts it into baselines, averages for repeated data,
undoes the mod 2pi, calculates an array where data needs predicting and prints to a file
for use in a george library proce... |
#coding: utf-8
from pyquery import PyQuery as pyq
import uctxt_content
url = "http://www.uctxt.com/book/17/17785/"
doc = pyq(url)
# print doc
dl = doc('dl')
titles = dl('a')
count = dl.children().length
urlContents = []
for x in xrange(0,count):
a = titles.eq(x)
href = a.attr('href')
urlContent = url+href
urlConte... |
from discord.ext.commands import Bot
import asyncio
import logging
import colorlog
from importlib import import_module, reload
from collections import namedtuple
from inspect import iscoroutinefunction, isfunction
from functools import partial, wraps
from contextlib import suppress
import pkgutil
import sys
from websoc... |
import json
info = {
'name': 'alex',
'age': 32
}
f = open('test.txt', 'w')
# f.write(str(info))
# print(json.dumps(info))
f.write(json.dumps(info))
f.close()
|
import pandas as pd
import numpy as np
import click
from preprocessing import apply_preprocessing, apply_preprocessing_bert
from data_loading import load_tweets, load_test_tweets, split_data, seed_everything, split_data_bert
from models.bi_lstm import run_bidirectional_lstm
from models.machine_learning_models import r... |
#题目地址:https://leetcode-cn.com/problems/plus-one/
class Solution:
def plusOne(self, digits: 'List[int]') -> 'List[int]':
n = len(digits)#获取原来数组的长度
temp = [0] * n#生成一个与原数组相同长度的全0数组
up = 0#是否进位
last = digits[-1]#最低位的数字[4,3,2,1][-1] => 1
last += 1#将最低位的数字+1
if last == 10... |
# Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
import unittest
import logging
import asyncio
from hbmqtt.plugins.manager import PluginManager
formatter = "[%(asctime)s] %(name)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s"
logging.basicConfig(level=logging.INFO, for... |
from cosmic_pons import (read_pon_list, read_cosmic, read_pon, tabulate_pon,
remove_empty)
from io import StringIO
import pytest
import pandas as pd
from pandas.testing import assert_frame_equal as afe
from numpy.testing import assert_array_equal as aae
def test_read_pon_list():
pon_list ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.