text stringlengths 8 6.05M |
|---|
# <<Instagram hashtag crawler>>
# leejihee950430@gmail.com
#
# Copyright (c) 2018, Jihee Lee
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribut... |
import math as math
from sklearn.cluster import Birch
from .generic_clustering import GenericClustering
__author__ = "Konstantin Bogdanoski"
__copyright__ = "Copyright 2020, BlanketClusterer"
__credits__ = ["Konstantin Bogdanoski", "Prof. PhD. Dimitar Trajanov", "MSc. Kostadin Mishev"]
__license__ = "MIT"
__version_... |
class Knight:
def __init__(self, name):
self.__name = " ".join(["Sir", name])
self.__bruises = 0
self.__curr_pos = 0
self.__tactical_card = -1
self.__accept_heavy_blows = True
self.__points = 0
self.__fail_start = False
self.__fail_start_count = 0
... |
#B
I,PA=input().split()
if (int(I)+int(PA))%2==0:
print('even')
else:
print('odd')
|
from django.contrib.gis.db import models
class EventType(models.Model):
name = models.CharField(max_length=120)
description = models.TextField(blank=True)
class Event(models.Model):
name = models.CharField(max_length=120)
location = models.PointField(blank=True, null=True)
eventType = models.Forei... |
import click
import pika
from pika.exceptions import AMQPConnectionError
from rabbitmq_util import RABBITMQ_DEFAULT_HOST
from rabbitmq_util import RABBITMQ_DEFAULT_PORT
@click.command()
@click.option('--mode', type=str,
prompt='"send" or "recv" from server',
help='Specify if send-ing or r... |
import unittest
from katas.kyu_7.the_most_amicable_of_numbers import amicable_numbers
class AmicableNumbersTestCase(unittest.TestCase):
def test_true(self):
self.assertTrue(amicable_numbers(220, 284))
def test_true_2(self):
self.assertTrue(amicable_numbers(1184, 1210))
def test_true_3(s... |
import numpy as np
import subprocess
import argparse
import h5py
import tempfile
import os
def fetch_tomtom_args():
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--modisco_h5py", required=True, type=str, help="path to the output .h5py file generated by the run_modisco.py script")
parser.add... |
# Generated by Django 3.1.6 on 2021-02-11 12:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('spareparts', '0003_auto_20210208_1217'),
]
operations = [
migrations.AlterField(
model_name='lo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: cylisery@outlook.com
# depth first search
# return True if value is found, else False
def dfs(node, val):
stack = [node]
visited = []
while len(stack) != 0:
item = stack.pop()
print "%s -> " % item.val
if item.val == val:
... |
import pickle
import os
from datetime import datetime
import getopt
import sys
def get_pickle_file_content(full_path_pickle_file):
pickle_file = open(full_path_pickle_file,'rb')
pickle_list = pickle.load(pickle_file, encoding='latin1')
pickle_file.close()
return pickle_list
def get_all_pickle_... |
# Generated by Django 3.0.6 on 2020-06-04 13:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('musicRun', '0004_auto_20200604_1401'),
]
operations = [
migrations.AlterField(
model_name='song',
name='artists',
... |
# -*- coding: utf-8 -*-
from sys import hexversion
import random
from .context import sortedcontainers
from sortedcontainers import SortedListWithKey
from nose.tools import raises
if hexversion < 0x03000000:
from itertools import izip as zip
range = xrange
def modulo(val):
return val % 10
def test_init... |
# 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 use ... |
def hot_singles(arr1, arr2):
output = []
for x in arr1:
if x not in output and x not in arr2:
output.append(x)
for x in arr2:
if x not in output and x not in arr1:
output.append(x)
return output
'''
Write a function that takes two arguments, and returns a new ... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: songyunlong
@license: (C) Copyright 2018-2021, Node Supply Chain Manager Corporation Limited.
@contact: 1243049371@qq.com
@software: pycharm
@file: ceshi
@time: 2019/3/3 11:13
@desc:
'''
import tensorflow as tf
import numpy as np
from tensorflow_own.Routine_operation... |
import pickle as pkl
import json
import random
import numpy as np
import torch
from sklearn import preprocessing
from sklearn.cluster import KMeans
def read_pickle(file_path):
with open(file_path, 'rb') as f:
vec = pkl.load(f)
return vec
def dump_pickle(file_path, obj):
with open(file_path, ... |
import Horcner as H
import numpy as np
import matplotlib.pyplot as plt
import math
def diff(y):
n = len(y)
delta = np.zeros((n, n))
delta[:, 0] = y
for i in range(1, n):
for j in range(0, n - i):
delta[j, i] = delta[j+1, i-1] - delta[j, i-1]
return delta
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 15:38:32 2018
@author: ppxee
"""
from astropy.io import fits #for handling fits
sem05B = fits.open('SE_outputs_yearstacks/05B_output.fits')
|
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
class WeatherUi:
def __init__(self, logger):
... |
import re
import nltk
import math
from pickle import load
from random import randint
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense
from keras.layers... |
#!/usr/bin/python
# Import the required modules
import cv2, os
import numpy as np
from PIL import Image
import Train_Common as tc
import sys, getopt
help_message = '''
USAGE: Train_Recognizer_LBP.py [--path <Path>] [--model-name <ModelName>] [--label-name <LabelName>]
'''
if __name__ == "__main__":
print (help_... |
'''
Usage:
test longestSubstrLen_3.py by using pytest
'''
import pytest
import os
import sys
# append parent path
sys.path.append(os.path.pardir)
from longestSubstrLen_3 import Solution
from longestSubstrLen_3 import Solution2
test_data = [
("abcabcbb", 3),
('bbbbbb', 1),
('c', 1),
('aab', 2),
... |
#!/usr/bin/env python3
import numpy as np
import matplotlib
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from mpl_toolkits.mplot3d.art3d import Line3DCollection
def plot(graph, **kwargs):
"""
Plots a 2d or 3d graph given an FEA Latti... |
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def set_global_context(context, key, value):
context.dicts[0][key] = value
return ''
|
__author__ = "Narwhale"
import string
# def func(name):
# return name.title()
#
# assert func("lilei") #title
# assert func("hanmeimei")
# assert func("Hanmeimei")
# def func(name,callback=None):
# if callback == None:
# return name.title()
# else:
# return callback(name)
#
# def ff(nam... |
from panda3d.core import Vec3
from .ObjectProperty import ObjectProperty
class TransformProperty(ObjectProperty):
def __init__(self, mapObject):
ObjectProperty.__init__(self, mapObject)
self.valueType = "vec3"
self.defaultValue = Vec3(0)
self.value = self.defaultValue
self... |
'''
Created on Jan 24, 2016
@author: Andrei Padnevici
@note: This is an exercise: 9.1
'''
file = open("romeo.txt")
wordsDict = dict()
for line in file:
words = line.split()
for word in words:
wordsDict[word] = wordsDict.get(word, 0)
print("window: ","window"in wordsDict)
print("wdsfsindow: ","wdsfs... |
# Submitter: loganw1(Wang, Logan)
# Defined below is a special exception for use with the Graph class methods
# Use it like any exception: e.g., raise GraphError('Graph.method" ...error indication...')
class GraphError(Exception):
pass # Inherit all methods, including __init__
class Graph:
# HELPER METHODS:... |
from .midi_csv import midicsv, csvmidi
|
from django.apps import AppConfig
class GamerConfig(AppConfig):
name = 'Gamer'
|
import graphene
from copy import deepcopy
from graphene import relay
from graphene_django.filter import DjangoFilterConnectionField
from graphene_django.types import DjangoObjectType
from graphql import GraphQLError
from graphql_relay import from_global_id
from django.db import IntegrityError
from api.models import I... |
import random
print("WELCOME TO THE GAME OF ROCK , PAPER AND SCISSORS..............")
print("THE RULES ARE AS FOLLOWS::")
print("ROCK BLUNTS SCISSORS,PAPER COVERS ROCKS,SCISSORS CUTS PAPER")
print("WOULD YOU LIKE TO PLAY rock , paper , scissor?(y/n)")
reply=input()
while(reply=="y"):
player_score = 0
computer_score... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 04:58:22 2019
@author: kanchana
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,confusion_matrix, classification_report
import warnings
warnings.filterwarnings("ignore")
... |
# Dependencies
import json
import requests as req
# Save config information
api_key = "25bc90a1196e6f153eece0bc0b0fc9eb"
url = "http://api.openweathermap.org/data/2.5/weather?"
city = "London"
# Build query URL
query_url = url + "appid=" + api_key + "&q=" + city
# Get weather data
weather_response = req.get(query_ur... |
import os
import urllib2
import cookielib
import re
import htmlentitydefs
import codecs
import time
from BeautifulSoup import BeautifulSoup
print 'a'
URL_REQUEST_DELAY = 1
BASE = 'http://www.nytimes.com'
TXDATA = None
TXHEADERS = {'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
OUTPUT_FIL... |
import unittest
from katas.kyu_8.find_maximum_and_minimum_values_of_a_list import min, max
class MinMaxOfListTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(min([-52, 56, 30, 29, -54, 0, -110]), -110)
def test_equal_2(self):
self.assertEqual(min([42, 54, 65, 87, 0]), 0)... |
from django.shortcuts import render #render:渲染
from django.http import HttpResponse
from . import models
# Create your views here.
def index(request):
articles = models.Article.objects.all()
return render(request,'blog/index.html',{'articles':articles}) #HttpResponse('hello world!')
#{'hello':'hello wonde... |
def calPrize(mydice):
sorted_dice = sorted(mydice)
count = len(set(sorted_dice))
if count == 1:
return 50000 + sorted_dice[0] * 5000
elif count == 2:
if sorted_dice[1] == sorted_dice[2]:
return 10000 + sorted_dice[1] * 1000
return 2000 + sorted_dice[1] * 500 + sorted... |
import pygame as pg
from asset import FLOOR, get_sprite, get_player_sprites, OHNOES1, OHNOES2, get_light_halo
from config import SCREEN_HEIGHT, SCREEN_WIDTH, TILE_WIDTH, TILE_HEIGHT, PLAYER_WIDTH, PLAYER_HEIGHT
from events import schedule_event
from screen import Screen
class DefeatScreen(Screen):
def __init__(s... |
from turtle import *
color('red')
for i in range(4):
if i == 2:
left(120)
else:
left(60)
fd(100)
left(60)
for i in range (4):
if i == 0:
left(30)
elif i == 2:
right(120)
else:
right(60)
fd(100)
left(30)
for i in range (4):
if i == 0:
righ... |
import win32com
import win32com.client
import pythoncom
class XASessionEvents:
logInState = 0
def OnLogin(self, code, msg):
print("OnLogin method is called")
if str(code) == '0000':
XASessionEvents.logInState = 1
def OnLogout(self):
print("OnLogout method is called")
... |
from django.shortcuts import render
# Create your views here.
def upload(request):
return render(request,"upload/upload.html")
|
# -*- coding: utf-8 -*-
import logging
import markdown
import base64
from django.conf import settings
from django.shortcuts import resolve_url
from Crypto.Cipher import AES
from docutils.core import publish_parts
from custom.cryptographer import Wrapper
try:
from django.utils.six.moves import cPickle as pickle
exce... |
# Generated by Django 2.2.24 on 2021-10-31 20:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('estudiantes', '0003_auto_20211031_1446'),
]
operations = [
migrations.RenameModel(
old_name='Clases',
new_name='Clase',
... |
import RPi.GPIO as GPIO
import time
import sys
import socket
GPIO.setmode(GPIO.BCM)
GPIO_PIN = 24
GPIO.setup(GPIO_PIN,GPIO.IN,pull_up_down = GPIO.PUD_UP)
delay_time = 1.0
Host = "127.0.0.5"
Port = 5000
sensor_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sensor_socket.connect((Host,Port))
print("Senso... |
import os
from easydict import EasyDict as edict
cfg2 = edict()
cfg2.PATH = edict()
cfg2.PATH.DATA = ['/home/liuhaiyang/dataset/CUB_200_2011/images.txt',
'/home/liuhaiyang/dataset/CUB_200_2011/train_test_split.txt',
'/home/liuhaiyang/dataset/CUB_200_2011/images/']
cfg2.PATH.LABEL = '/home/liuhaiyang/da... |
invocations = list()
with open('message.txt') as f:
lines = f.readlines()
for line in lines :
if line not in invocations :
invocations.append(line)
outF = open("sortie.txt", "w")
for line in invocations :
outF.write(line)
print("Ligne : {}".format(line)) |
# -*- coding: utf-8 -*-
import inject
import logging
import psycopg2
import asyncio
from asyncio import coroutine
from autobahn.asyncio.wamp import ApplicationSession
from model.config import Config
from model.systems.task.task import Task
from model.profiles import Profiles
class WampTask(ApplicationSession):
... |
import unittest
import os
import numpy as np
from gmc.core.models import cnn
from gmc.dataset import musicset, reduce
from gmc.conf import settings
@unittest.skipIf(os.environ.get("DUMMY") == "TRUE",
"not necessary when real dataset not supplied")
class TestNN(unittest.TestCase):
def test_training(self):
... |
from typing import Tuple
from sympy import Expr, Symbol, I, pi, cos, arg, sqrt, cancel, simplify
__all__ = [
"expend_cos",
"amp_and_shift",
]
def expend_cos(expr: Expr, x: Symbol) -> Tuple[Expr, Expr]:
while True:
term = expr.subs(x, pi / 2)
yield term
expr = cancel((expr - term... |
"""
This File generates the header files defining the trained and quantized network.
The following files are required
- [project_root]/data/config.json containing the QuantLab configuration how the network was trained
- [project_root]/data/net.npz, containing the entire network
"""
__author__ = "Tibor Schneider"
__ema... |
#!/bin/evn python
# encoding:utf-8
'''
#=============================================================================
# FileName: cmdLine.py
# Desc: 解析命令行参数,供zoomeye使用
# Author: Crow
# Email: lrt_no1@163.com
# HomePage: @_@"
# Version: 2.0.1
# LastChange: 2017-01-01 17:25:04
# H... |
import random
import json
# station = ["beijing","shanghai","nanjing","hangzhou","wuxi","ningbo","qingdao","wenzhou","shenzhen","tianjing"]
# stationID = ['10010','10011','10012','10013','10014','10015','10016','10017','10018','10019',"10020"]
# weekdays = ["Mon","Tues","Wed","Thurs","Fri","Sat",'Sun']
# def init():
... |
import os
import re
import datetime
def whoisFunc(name):
# выполняем команду whois с переданным доменом
try:
output = os.popen("whois "+name)
except OSError:
return False
# разбиваем информацию, которую выдал whois на массив через "\n" отступ
output = str(output.rea... |
#! /usr/bin/python
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rc('axes', titlesize=16) # fontsize of the axes title
plt.rc('axes', labelsize=16) # fontsize of the x and y labels
plt.rc('xtick', labelsize=12) # fontsize of the tick labels
plt.rc('ytick', labelsize=12) # fon... |
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.authentication import SessionAuthentication
from tastypie import fields
from .models import Review, Book
from django.contrib.auth.models import User
class UserResource(ModelResource):
class Meta:
queryset = User.objects.al... |
../../Sum-Exp-Data.py |
s,b2=map(str,input().split())
d3=s+b2
print(d3)
|
# intraday_ml_strategy.py
import numpy as np
import pandas as pd
from sklearn.externals import joblib
from qstrader.price_parser import PriceParser
from qstrader.event import (SignalEvent, EventType)
from qstrader.strategy.base import AbstractStrategy
class IntradayMachineLearningPredictionStrategy(AbstractStrategy... |
from loguru import logger
from sc2.data import Race
from sc2.constants import *
from sc2.ids.unit_typeid import *
from sc2.ids.ability_id import *
from sc2.unit import Unit
from sc2.units import Units
class ArmyGroup:
"""
Army groups allow control of an individual group of units
Units in an army group ar... |
import unittest
import doctest
def additional_tests():
import simplejson
import simplejson.encoder
import simplejson.decoder
suite = unittest.TestSuite()
for mod in (simplejson, simplejson.encoder, simplejson.decoder):
suite.addTest(doctest.DocTestSuite(mod))
suite.addTest(doctest.DocFi... |
"""Functionality for specifying and cycling through multiple calculations."""
from __future__ import print_function
from distutils.version import LooseVersion
from multiprocessing import cpu_count
import dask
import dask.bag as db
import distributed
import itertools
import logging
import pprint
import traceback
from... |
#buh usgiig jijgeer
a = input()
print(str.lower(a)) |
import pandas as pd
import numpy as np
import os
import json
import logging
import sys
logging.basicConfig(filename='logs.log',
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
... |
import pynetbox
import napalm
import pprint
import secrets
import role_mapping
class Network_Device:
'''An object of the network device you are connecting to.
Attributes:
facts: network device facts available from NAPALM
interfaces: network device interfaces available from NAPALM
'''
d... |
#!/usr/bin/env python
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 th... |
from django.test import TestCase
class ExchangeTests(TestCase):
pass
|
#!/usr/bin/python
# Orthanc - A Lightweight, RESTful DICOM Store
# Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
# Department, University Hospital of Liege, Belgium
# Copyright (C) 2017-2020 Osimis S.A., Belgium
#
# This program is free software: you can redistribute it and/or
# modify it under the terms ... |
# Generated by Django 2.2.13 on 2020-07-12 06:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0020_auto_20200710_2318'),
]
operations = [
migrations.AlterField(
model_name='category',
name='status',... |
from django.contrib import admin
# Register your models here.
from location.models import Location, Student, Grade
class LocationAdmin(admin.ModelAdmin):
list_display = ('lat', 'long', 'student', 'timestamp')
list_filter = ('student', 'timestamp')
class GradeAdmin(admin.ModelAdmin):
list_display = ('da... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: Cleaner library is property of isMOOD and is not publicly distributed
# The script fails without this library at the moment
from future import print_function
import Cleaner # TO IMPLEMENT
import csv
import re
import settings
import spacy
__author__ = 'Zoe Kotti... |
# Generated by Django 3.2 on 2021-04-24 12:19
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('Tour_app', '0007_auto_20210424_1745'),
]
operations = [
migrations.RenameField(
... |
def negativePower(a,b):
a=float(a)
if(a>0 and b==-1):
return (1/a) #base case
return (1/a)*negativePower(a,b+1)
result1=negativePower(2,-1)
result2=negativePower(5,-3)
result3=negativePower(10,-2)
print ("The results are:",result1,result2,result3)
|
x = a
x.find
def osamäärä(a,b):
"""
:param a: jaettava
:param b: jakaja
:return c: osamäärän arvo
"""
c = a/b
return c
osamäärä |
import numpy as np
from ..constants import COLOR_CHANNEL_INDICES
# Default trimmedness: discard anything more than 4 standard deviations from a central value
DEFAULT_TRIM_STDEV = 4
def _trim_data_to_stdev(sample, trim_stdev):
""" Trim the farther reaches of a data set based on a central value and standard devi... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 18:36:34 2019
@author: MAGESHWARAN
"""
import os
import json
import cv2
import numpy as np
from tqdm import tqdm
base_dir = os.getcwd()
data_folder = os.path.join(base_dir, "Dataset")
images_folder = os.path.join(data_folder, "Images")
crops_folder = os.path.join(dat... |
import re
def show_me(name):
return bool(re.match(r'(-[A-Z][a-z]+)+$', '-' + name))
|
list = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = int(input())
list.append(ele)
print(list)
for ele in list:
if(ele>0):
print(ele, end = " ")
|
# -*- coding: utf-8 -*-
import base64
from django.core.urlresolvers import resolve
from django.contrib.auth.models import AnonymousUser
from rest_framework import exceptions
from rest_framework import authentication
from rest_framework.permissions import BasePermission
from django.contrib.auth.models import User
A... |
import unittest
from katas.kyu_7.sir_show_me_your_id import show_me
class ShowMeTestCase(unittest.TestCase):
def test_true_1(self):
self.assertTrue(show_me('Francis'))
def test_true_2(self):
self.assertTrue(show_me('Jean-Eluard'))
def test_true_3(self):
self.assertTrue(show_me('... |
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIE... |
import unittest
from katas.kyu_5.palindrome_chain_length import palindrome_chain_length
class PalindromeChainLengthTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(palindrome_chain_length(87), 4)
def test_equals_2(self):
self.assertEqual(palindrome_chain_length(1), 0)
... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################
# #
# update_html_page.py: update disk space html page #
# ... |
import numpy as np
class Metric_Accuracy:
def calculate(self, output, y):
predictions = np.argmax(output, axis=1)
accuracy = np.mean(predictions == y)
return accuracy
|
from BasicFunctions import *
player1 = Player("Player 1", 1)
player2 = Player("Player 2", 2)
player3 = Player("Player 3", 3)
player4 = Player("Player 4", 4)
talon = Player("Talon",5)
PLAYERS = [player1,player2,player3,player4]
GAMENUM = 0
ROUNDNUM = 0
MONDASOK = ["Négy király", "Dupla játék", "Tuletroá", "Centrum", "K... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 22 20:04:07 2014
@author: Goren
"""
import csv
import os
import numpy as np
import random
class train_loader:
"""Loads data """
TestcasesRatio=0.1
def __init__(self,csv_name,shuffle=False):
self.readcsv(csv_name,shuffle)
def readcsv ... |
# Generated by Django 3.1 on 2020-08-04 17:34
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CONtacts',
fields=[
('id', models.AutoField(a... |
#!/usr/bin/env python3
"""Script to run the auacm cli app"""
import sys
from auacm import main
main.main(sys.argv[1:])
|
from Token import Token
class AST(object):
def __init__(self, nome):
self.nome = nome;
self.children = []
self.tipo = None #tipo do nó. Compound, Assign, ArithOp, etc
self.value = None
def __str__(self, level=0):
ret = "\t"*level+ repr(self) +"\n"
... |
# import urllib.request
# url = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing='
# data = urllib.request.urlopen(url + '37278').read().decode('utf-8')
# while data.startswith('and'):
# print(data)
# data = urllib.request.urlopen(url + data.split(' ')[-1]).read().decode('utf-8')
# print(data)
# pe... |
#!usr/bin/env python3
# @File:send_email.py
# @Date:2018/05/27
# Author:Cat.1
from email.mime.text import MIMEText
import smtplib
import config
msg_from = config.getConfig("send_email", "msg_from")
passwd = config.getConfig("send_email", "passwd")
msg_to = config.getConfig("send_email", "msg_to"... |
#2. 读入文件‘a.txt’.统计文件中每个单词的数量并且进行输出。
#txt的文本文件为
#a:a. Every single time you access a website,
# you leave tracks. Tracks that others can access.
# If you don't like the idea, find out what software can help you cover them
f=open("D://a.txt","r")
a=f.readlines()
print(a)
|
#! -*- coding:utf8 -*-
import os
import sys
import json
reload(sys)
sys.setdefaultencoding("utf-8")
program_path = os.path.abspath(__file__ + "/../..")
def gen_file_abspath(file_path, root_path=None):
if root_path is None:
return program_path + "/" + file_path
else:
return root_path + "/" +... |
#!/usr/bin/env python3
"""
Revision By Changes
---------------------------------------------------------------
0.0.1 Ramanuj Pandey[ramanuj.p7@gmail.com] Ported whole to code to Python3
from CPP, level one ... |
from django.conf.urls import url, include
from django.contrib import admin
import helpdesk_portal.views as views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('... |
from django.shortcuts import render
from django.shortcuts import render_to_response
from .email import send_welcome_email
from django.views.generic.edit import FormView
from django.utils import timezone
from django.contrib.gis.geos import Point
from django.contrib.gis.db.models.functions import Distance
from .forms imp... |
import copy
from typing import List, Any
from kts_linguistics.string_transforms.abstract_transform import AbstractTransform
class TransformPipeline:
def __init__(self, do_cache=False, cache=None):
self.transforms = list()
self.cache = cache if cache is not None else dict()
self.do_cache ... |
# Definition for a singly-linked list
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
result = str(self.val)
if self.next:
result += str(self.next)
return result
class Solution:
# ex. head = 1,2,3,4
def reverseL... |
from __future__ import print_function
import torch
# somehow contains values
x = torch.empty(5, 3)
print(x)
x = torch.rand(5, 3)
print(x)
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
x = torch.tensor([5.5, 3])
print(x)
x = x.new_ones(5, 3, dtype=torch.double)
print(x)
x = torch.randn_like(x, dtype=torch.float... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.