text stringlengths 38 1.54M |
|---|
"""
Pre-Programming 61 Solution
By Teerapat Kraisrisirikul
"""
def main():
""" Main function """
data = {'FOOT': 5, 'LEG': 10, 'HEAD': 15, 'DOWN': 0, 'END LEAW GUN': 0}
acts = list()
score, down, passed, passed_scr = 0, 0, False, 100
while down < 3:
acts.append(input().upper())
if ... |
# Generated by Django 2.0.7 on 2018-08-01 01:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('films', '0008_auto_20180731_1653'),
]
operations = [
migrations.AddField(
model_name='film',
name='cam',
... |
# Menu Driven Program
def add(x,y):
z = x + y
print(z)
def sub(x,y):
z = x - y
print(z)
def div(x,y):
z = x / y
print(z)
def mul(x,y):
z = x * y
print(z)
print("""
1. Add
2. Sub
3. Div
4. Mul
""")
ch = input("Enter your choice : ")
f_num = int(input("Enter fir... |
# @generated by generate_proto_mypy_stubs.py. Do not edit!
import sys
from google.protobuf.descriptor import (
Descriptor as google___protobuf___descriptor___Descriptor,
)
from google.protobuf.internal.containers import (
RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedC... |
#!/usr/bin/python3
"""Adds a function to attempt to add attributes to objects."""
def add_attribute(obj, name, value):
"""Attempts to add a value to an object.
Args:
obj: object to attempt to add to.
name (str): name of attribute to add.
value: value to add.
Raises:
TypeE... |
from django.shortcuts import get_object_or_404
from rest_framework import viewsets, mixins, status
from rest_framework.decorators import action
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from .models import FileUpload, Submission, Assignment, Unit, Cours... |
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import reverse
from django.core import serializers
from django.core.paginator import Paginator
fr... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 10:59:52 2019
@author: skans
"""
import os
import sys
import pandas as pd
sys.path.append(r'C:\Users\skans\Documents\GitHub\Autonomous-Open-Data-Mining')
from Autonomous-Open-Data-Mining.platforms.distributing_links_on_platforms.distributing_links_on_platforms import ... |
import sys
import setuptools
from Cython.Build import cythonize
import numpy as np
import os
os.environ["C_INCLUDE_PATH"] = np.get_include()
print (np.get_include())
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyapprox-jjakeman",
version="0.0.1",
author="Joh... |
# coding: utf-8
# # 使用RNN进行情绪分析
# 在这里我们将使用RNN(循环神经网络)进行情感分析,至于为什么使用RNN而不是普通的前馈神经网络,是因为RNN能够存储序列单词信息,得到的结果更为准确。这里我们将使用一个带有标签的影评数据集进行训练模型。
# 使用的RNN模型架构如下:
# <img src="assets/network_diagram.png" width=400px>
# 在这里,我们将单词传入到嵌入层而不是使用ONE-HOT编码,是因为词嵌入是一种对单词数据更好的表示。
# 在嵌入层之后,新的表示将会进入LSTM细胞层。最后使用一个全连接层作为输出层。我们使用sigmiod作为激... |
import enchant
from quasimodo.data_structures.submodule_interface import SubmoduleInterface
import logging
dirty_words = ["their", "so", "also"]
forbidden = ["used", "called", "xbox", "youtube", "xo", "quote",
"quotes", "minecraft", "important", "considered", "why",
"using", "as", "for", "a... |
#!/usr/bin/env python
import subprocess
mounts = {}
for line in subprocess.check_output(['mount', '-l']).split('\n'):
parts = line.split(' ')
if len(parts) > 2:
mounts[parts[2]] = parts[0]
for k in mounts:
print mounts[k] + ": " + k
|
__author__ = 'Daniel Maly'
import unittest
from test.dummy_input_source import DummyInputSource
from test.dummy_output_receiver import DummyOutputReceiver
from binterpreter import Binterpreter
from util import *
class TestBinterpreter(unittest.TestCase):
def test_hello_world(self):
print("Starting hello ... |
from serve.utils import convert_and_pad
import numpy as np
def convert_and_pad_data(word_dict, data, pad=500):
result = []
lengths = []
for sentence in data:
converted, leng = convert_and_pad(word_dict, sentence, pad)
result.append(converted)
lengths.append(leng)
return np.ar... |
import numpy as np
import argparse
import pickle
import matplotlib.pyplot as plt
#from Sat import SatManager as Sat
from commons.time_interval import TimeInterval
from commons.Timelist import TimeList
from basins import V2
#from postproc import masks
from commons.utils import addsep
#import os
def argument():
par... |
def countingValleys(steps, path):
count=0
a=0
sum=0
for i in range(steps):
a=sum
if path[i]=='U':
sum+=1
else:
sum-=1
if sum==0 and a==-1:
count+=1
return count |
from data.Service import ServiceSQL
import json
import traceback
from datetime import date, datetime
def cmdinsert(table,objeto):
table = str(table)
TABLE_NAME = table
sqlstatement = ''
keylist = "("
valuelist = "("
firstPair = True
for key, value in objeto.items():
if key !=... |
from flask import Blueprint, jsonify, request
from app.api.v2.views.partyv import parties
from app.api.v2.views.OfficeView import Offices
from app.api.v2.views.userView import Users
from app.api.v2.views.voteView import Votes
prtInstance = parties() #create party object and will initialize all blueprint
office... |
from bs4 import BeautifulSoup
import requests
import os
class CommicTracker:
def __init__(self, saveFile):
self.trackingComic = {}
self.saveFile = saveFile
self.initDict()
'''
DICT FUNCTION:
Create the dict from the save file when called
'''
def initDict(self)... |
# 1. data for triangles
# sets of non-rare all homoz. and heteroz.
def test_depth(depth):
if depth == '.':
return False
else:
return int(depth) > 15
from collections import defaultdict
from interval import interval
from sys import stderr
class reference_block:
def __init__(self, line_tab)... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import os
import sys
import time
import traceback
from datetime import datetime
import urllib3
import re
import requests
from requests.exceptions import HTTPError
# Disable insecure warnings
urllib3.disable_warnings()
FIELD_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 17:54:32 2019
@author: kazuki.onodera
"""
import numpy as np
import pandas as pd
from tqdm import tqdm
from sklearn.externals import joblib
import os, gc
from itertools import combinations
import utils
utils.start(__file__)
PREF = 'f008'
alp... |
from sortedcontainers import SortedList
class Solution:
def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:
maps = SortedList([0])
rslt, cumsum = 0, 0
for num in nums:
cumsum += num
left = maps.bisect_left(cumsum-upper)
right = maps.bi... |
import os, sys # Only library needed
def setup():
# First time, setup autoGit.
print("Initiating setup.")
# Ask if user wants to install cron
if input("Would you like to install cron now? [no]: ")=="y":
os.system("sudo apt install cron")
print("How often would you like to commit?")
commitTimes... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
# GN version: //mojo/apps/js
# //mojo/apps/js/bindings
# //mojo/apps/js/bindings/gl
't... |
import cv2
def main():
windowName='Video PLAYER'
cv2.namedWindow(windowName)
filename = 'C:\\Users\\spars\\Desktop\\programs\\python\\opencv\\output\\lfr.avi'
cap=cv2.VideoCapture(filename)
while (cap.isOpened()):
ret, frame = cap.read()
print(ret)
#f... |
# Generated by Django 2.2.6 on 2020-01-05 16:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('p_library', '0003_auto_20200105_1905'),
]
operations = [
migrations.AlterField(
model_name='book',
name='copy_count'... |
from contextlib import AbstractContextManager
class PreparedStatement(AbstractContextManager):
def __init__(self, ps):
self.ps = ps
def run(self, **params):
return self.ps.run(**params)
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def close(self):
... |
#Program to find nth fibinocci number
number = int(input("Enter a number "))
if number == 1:
print("The first fibinocci number is 1")
elif number == 2:
print("The second fibinocci number is 2")
else:
fib1 = 1
fib2 = 2
for i in range(3,number + 1):
fib3 = fib1 + fib2
fib1 = fib2
... |
from baselayer.app.access import permissions, auth_or_token
from baselayer.log import make_log
from tornado.ioloop import IOLoop
from sqlalchemy.orm import sessionmaker, scoped_session
import astropy.units as u
import healpix_alchemy as ha
from ..base import BaseHandler
from ...models import DBSession, Galaxy
log ... |
# first, run DNest4 with max number of levels set to 1
import sys
import numpy as np
import matplotlib.pyplot as plt
# from astroML.plotting import hist
def do_plot(data, name, column=1, save=None, bins=None, normed=True, logxscale=False):
fig, ax = plt.subplots(1,1)
if bins is None:
bins = 100 #np.l... |
from sklearn import metrics
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_auc_score, auc
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import classification_report
from collections imp... |
#!/usr/bin/python
import os
import sys
import datetime
from time import sleep
import serial
ser = serial.Serial(
port='/dev/ttyACM0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
... |
from card import Card
from random import shuffle
class Deck:
def __init__(self):
self.cards = []
def createDeck(self):
suits = ["H", "D", "C", "S"]
ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "0", "J", "Q", "K"]
for suit in suits:
for value, rank in enum... |
from django.shortcuts import render
from .models import Owner, ReposDetail
from .serializers import ReposDetailSerializer
from rest_framework.views import APIView
from .git_apis import get_repos, get_followers
from rest_framework.response import Response
from rest_framework import status
from IPython import embed
# Cr... |
import openturns as ot
from math import exp
from matplotlib import pyplot as plt
from openturns.viewer import View
f1 = ot.SymbolicFunction(['t'], ['sin(t)'])
f2 = ot.SymbolicFunction(['t'], ['cos(t)*cos(t)'])
myBasis = ot.Basis([f1, f2])
coefDis = ot.Normal([2] * 2, [5] * 2, ot.CorrelationMatrix(2))
myTG = ot.Regular... |
# Copyright [2018] [Wang Yinghao]
#
# 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
#
# Unless required by applicable law or agreed to in writ... |
# -*- coding: utf-8 -*-
import sqlite3
import os
from os import listdir
from os.path import isfile, join
import shutil
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
class SeqData:
def __init__(self):
self.frames = []
self.cplex_durations ... |
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRe... |
import sys
import os
import numpy as np
import re, string, unicodedata
import pickle
import nltk
from nltk.corpus import stopwords
from os import listdir
from os.path import isfile, join
from bs4 import BeautifulSoup
from operator import mul
from functools import reduce
from collections import Counter
#nltk.download('... |
import json
import logging
import requests
from api.ot.token1 import Token1
class Department(object):
logging.basicConfig(level=logging.INFO)
url = 'https://qyapi.weixin.qq.com/cgi-bin/department/create'
def creat_depart(self):
data = {
"name": "开发中心",
"name_en": "Dev",
... |
import networkx as nx
from collections import Counter
import numpy as np
def edge_score(e):
"""
return score of an edge given edge
Args:
e: tuple (u, v, weight)
returns:
float: some heuristic score
"""
# 0: trivial return weight
return e[2]
# 1:
# return
def nai... |
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=50)
description = models.TextField()
def get_absolute_url(self):
return "/book/%s/" % self.id
|
# !/usr/bin/env python
import json
from webapp2_extras import json as JSON
from google.appengine.ext import ndb
class User(ndb.Model):
"""The model for storing information about each individual user
"""
# The required user name and password
username = ndb.StringProperty(required=True, indexed=True)
password = n... |
f = open('book.txt','r')
book = f.read().split()
f.close()
def frequency(word):
return len(filter(lambda w: word.lower() == w.lower(), book))
def total_frequency(word_list):
return sum(map(frequency,word_list))
def frequency_and_word(word):
return [word, frequency(word)]
def most_used():
f = map(frequency_a... |
# Definition for singly-linked list.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
l = []
total = 0
for i in s:
if i in l:
n = l.index(i)
l = l[(n+1): ]
l... |
import networkx as nx
from pymnet import *
import random
import matplotlib
import cascade as cas
matplotlib.use('TkAgg')
nodes = 100
layers = 3
intra_thres = 0.1
inter_thres = 0.1
coords = {}
attack_type = "normal" # choose one of the "normal", "spatial_number", "spatial_range"
def make_interlayer_edges(n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot to reply to Telegram messages.
This is built on the API wrapper.
This program is dedicated to the public domain under the CC0 license.
"""
import logging
import telegram
from telegram.error import NetworkError, Unauthorized
from time import sleep
from telegra... |
#!/usr/bin/python2
# -*- coding: utf-8 -*-
#--------------------------
# check_node_stat.py
#
# GSI
# m.zweig
# 09.12.2015
#
# check node with eb-ls if response
# if response everything is fine
# not -> node is dead
#-------------------------
import re,sys
import commands, getopt, subprocess
from subprocess impo... |
# -*- coding: utf-8 -*-
import tensorflow as tf
from optimizer import distributed_optimizer as optimizer
import distributed_tf_data_utils as tf_data_utils
try:
from .model_fn import model_fn_builder
except:
from model_fn import model_fn_builder
import numpy as np
import tensorflow as tf
from bunch import Bunch
fro... |
import tornado.web
class Results(tornado.web.RequestHandler):
def initialize(self, experiment_reader):
self.experiment_reader = experiment_reader
def get(self):
project_name = self.get_argument("project_name", default=None)
start_time = self.get_argument("experiment", default=None)
... |
import os
import os.path as op
import pickle
import numpy as np
import mne
from scipy.io import loadmat
from joblib import Parallel, delayed
import pickle
from nilearn.image import (load_img, coord_transform, new_img_like, math_img,
smooth_img)
from nilearn import plotting
from matplotli... |
from sklearn.feature_extraction.text import TfidfVectorizer
from konlpy.tag import Twitter
twitter = Twitter()
file = open('./test2.txt','r',encoding='utf-8')
lines = file.readlines()
# 2. 변수 rawdata 저장
rawdata = []
for line in lines:
rawdata.append(line)
file.close()
tfv=TfidfVectorizer(tokenizer=twitter.morphs... |
import flask
import requests
from datetime import datetime
from settings import SERVICES_URI, SESSION_EXPIRES_AFTER
from tools import parse_datetime, render_datetime
class Session(dict, flask.sessions.SessionMixin):
def __init__(self, json, **kwargs):
super().__init__(**kwargs)
self.id = json['id... |
#!/usr/bin/env python3
number = 1
power = 7830457
start = 28433
while power >34:
start *= 17179869184
power -= 34
start = int(str(start)[-11:])
start *= 2**power
start = int(str(start)[-10:])
print(start + 1)
|
# Generated by Django 2.1.2 on 2018-10-16 16:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainAuth', '0004_auto_20181004_0928'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='email',
),
... |
def unique_pairs(n):
"""Produce pairs of indexes in range(n)"""
for i in range(n):
for j in range(i+1, n):
yield i, j
s = "a string to examine"
for i, j in unique_pairs(len(s)):
if s[i] == s[j]:
answer = (i, j)
break
print(unique_pairs(s))
|
from __future__ import unicode_literals
import unittest
from mcinfo import nbt
testData = {
'type': "TAG_Compound",
'includes': ['3', 'other', 'things'],
'desc': "example nbt structure",
'content': {
'a_string': {
'type': "TAG_String",
'desc': "A string! what did you ex... |
from collections import Counter
S = input()
C = Counter(S)
print(C)
Keys = tuple(C.keys())
cnt = 0
for k in Keys:
if k != "x" and C[k]%2:
cnt += 1
if not cnt % 2:
print(-1)
############################
S = input()
l = 0
r = len(S)-1
cnt = 0
while l < r:
if S[l] == S[r]:
l += 1
... |
import urllib.request
import urllib
def get_teach_link(category_link):
url = category_link##'https://www.khanacademy.org/test-prep/mcat/cells#cell-membrane-overview'
res = urllib.request.urlopen(url=url)
page_source = res.read().decode('utf-8')
with open('a.txt','w',encoding = 'utf-8') as f:
... |
from powerline_shell.themes.default import DefaultColor
"""
absolute colors based on
https://github.com/arcticicestudio/nord-vim
"""
dark0 = 235
dark1 = 237
dark2 = 239
dark3 = 241
dark4 = 243
light0 = 229
light1 = 223
light2 = 250
light3 = 248
light4 = 246
dark_gray = 0
light_gray = 8
light_white = 7
dark_white = 1... |
import socket
host=input('Enter ip: ')
port=int(input('Enter port no. : '))
name=input('Enter your name.')
s=socket.socket()
host_name=str(s.recv(5000),'utf-8')
def connecting():
s.connect((host,port))
def Messaging():
msg=input(host_name,':> ')
if __name__=='__main__':
connecting()
... |
def NN(number, digitCount):
# Normalizes a single digit number to have digitCount 0s in front of it
format = "%0" + str(digitCount) + "d"
print format
return format % number
a = [1,2,3,4]
for i in range(4):
print NN(a[i],2) |
import os
#BOLETA DE VENTA
#DECLARAR VARIABLES
cliente,costo_ducha,costo_ceramica,costo_innodoro="",0.0,0.0,0.0
#INPUT
cliente=os.sys.argv[1]
costo_ducha=float(os.sys.argv[2])
costo_innodoro=float(os.sys.argv[3])
costo_ceramica=float(os.sys.argv[4])
#PROCESSING
monto_total=(round(costo_ducha+costo_ceramica+costo_inno... |
n = int(input())
bu = []
values = []
for i in range(n):
value = list(map(str, input().split()))
buy = {'id': 0, 'type': 'xx', 'name': 'aa', 'price': 0, 'quantity': 0}
if value[1] == 'Buy':
buy['id'] = int(value[0])
buy['type'] = str(value[1])
buy['name'] = str(value[2])
... |
'''
Wrappers for the "DictionaryServices" framework on MacOSX 10.5 or later.
Dictionary Services lets you create your own custom dictionaries that users
can access through the Dictionary application. You also use these services to
access dictionaries programatically and to support user access to dictionary
look-u... |
import bin.spl_ast as ast
import bin.spl_types as typ
INT_LEN = 8
class Compiler:
def __init__(self, tree):
self.root: ast.Node = tree
self.res = bytearray()
def compile(self):
self.compile_node(self.root)
def get_bytes(self) -> bytes:
return bytes(self.res)
def com... |
#coding:utf-8
import pysam
from pysam import VariantFile
import os
import math
import numpy as np
import gc
zero_file = open("man_made_0.txt", "a")
for sv in open('/mnt/hde/gao/wj/simulate/testSimuResult1/bp.txt'):
sv=sv.strip('\n')
tmp=sv.split(' ')
bp1=int(tmp[0])+10000
bp2=int(tmp[1])+10000
... |
"""
WSGI config for kasse project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
import sys
import site
prev_sys_path = list(sys.path)
site.addsitedir(
'/home/rav/en... |
# Copyright (c) 2017 akhail
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import peewee
from .base import DATABASE
from .student import Student
DATABASE.connect()
try:
DATABASE.create_tables([
Student
])
except (peewee.ProgrammingError, peewee.OperationalE... |
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.index, name='index'),
path('lista/', views.lista, name='lista'),
path('interno/', views.interno, name='interno'),
path('externo/', views.externo, name='externo'),
path('', views.login, name='login_index'),
pat... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 17:15:48 2020
@author: fijrin.j.roysh
"""
from Query_Preprocessing import int_to_vocab, vocab_to_int,encoded
from Simple_Train_RNN_Model_v4 import build_model, checkpoint_dir, vocab_size,embedding_dim,rnn_units
import tensorflow as tf
import pandas as pd
from flask ... |
#! -*- coding: utf-8 -*-
"""Test Dataflow module provides tests
for the pygoogleanalytics.dataflow DataFlow class
"""
from pygoogleanalytics import dataflow
class TestDataFlow:
"""TestDataFlow class provides methods for testing DataFlow class
"""
def test_dataflow(self):
"""DataFlow object should... |
from __future__ import division
import vigra
import numpy as np
class StructureTensor(object):
def __init__(self):
self.st = None
def compute(self, lf3d, params):
"""
call this method to compute the structure tensor subroutines in the order following:
- pre_filter
- ... |
import logging
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect
from django.urls import reverse
from django.views import View
from django.views.generic import ListView
from django.v... |
import pytest
import json
from ..spm_load_config import DEPENDENCY_REGEX
from ..spm_parser import get_records, get_closest_activity
import re
def test_get_records_copy_attributes():
task_groups = dict(
file_ops_1=[
".files = {'$PATH-TO-NII-FILES/tonecounting_bold.nii.gz'};",
".act... |
import string
MIN_PASSWORD_LENGHT=5
MAX_PASSWORD_LENGHT=15
LOWER=string.ascii_lowercase
UPPER=string.ascii_uppercase
DIGITS=string.digits
PUNCTUATION=string.punctuation
lower=0
upper=0
digit=0
punctuation=0
print("Please enter a valid password")
password=input("Your password must be between 5 and 15 characters, and co... |
import pudb
from maybe import Just, Nothing, lift
from toolz import thread_first, partial
def add (a, b):
return a + b
a = Just(1)
b = Just(2)
c = Nothing
maybe_add = lift(add)
d = maybe_add (a,b)
e = maybe_add (a,c)
pu.db
f = a.bind(partial(add, b))
print ("d = ", d)
print ("e = ", type(e))
print ("f = ", f)
|
users = []
account_file = "../website_rework/text_files/accounts.txt"
def user_create():
# word aan gegeven wat er in de array users komt te staan
class User:
def __init__(self, id, username, password, email, logins):
self.id = id
self.username = username
self.passw... |
#!/usr/bin/env python3
import os
import time
import json
from microsoft_bonsai_api.simulator.client import BonsaiClient, BonsaiClientConfig
from microsoft_bonsai_api.simulator.generated.models import SimulatorInterface, SimulatorState, SimulatorSessionResponse
from sim.simulator_model import SimulatorModel
def main()... |
crwaling='Data crawling is fun'
# print(crwaling.find('i'))
# print(crwaling.rfind('i'))
# print(crwaling.find('i',1,9))
# print('-'*12)
# print(crwaling.index('i'))
# print(crwaling.rindex('i'))
# print(crwaling.rindex('i',1,9))#오류
#split : 지정된 문자로 문자열을 분할함, 리스트 형식으로 분할
token = crwaling.split()
print(token)
names='l... |
from googlesearch import search
query = "python" #the text you want to search
#tld refers to the top level domain like .com or .in
#num refers to the number of results we want
for i in search(query,tld = "com", num=10, stop=10, pause=2):
print(i) |
def logg(info):
import logging
logger = logging.getLogger('info')
logger.setLevel(logging.DEBUG)
log_file = '服务端.log'
file_log = logging.FileHandler(log_file)
logger.addHandler(file_log)
file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fi... |
import re
import datetime
def add_offset_to_date(date:str, offset):
""" return a well formated format for the new offset with the offset applied
Expected format : 00:00:00,000 h:m:s,ms"""
original_date = datetime.datetime.strptime(date, '%H:%M:%S,%f')
hours, minutes, seconds, miliseconds = offset ... |
#!/usr/bin/env python
import torch.nn as nn
def print_tensor_stats(x, name):
flattened_x = x.cpu().detach().numpy().flatten()
avg = sum(flattened_x)/len(flattened_x)
print(f"\t\t\t\t{name}: {round(avg,10)},{round(min(flattened_x),10)},{round(max(flattened_x),10)}")
class ResNet(nn.Module):
de... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = 'home'),
path('password_generator', views.password, name = 'password'),
] |
# dummy import example
# import statement does not require .py extension
# a folder containing modules is called a package
# the files in the folder are called modules
# imported as module
import utility
# imported as package.module
import ex_folder.multiply
# another way to write this is
# import * will import all... |
from django.urls import path
from . import views
app_name = "player"
# hittalaget.se/spelare/ny/
# hittalaget.se/spelare/fotboll/ny/
urlpatterns = [
path('ny/', views.PlayerInitiateCreateView.as_view(), name="initiate_create"),
path('<str:sport>/', views.PlayerListView.as_view(), name="list"),
path('<str... |
# coding=utf-8
"""
Created on Monday 28 March 00:53:34 2020
@author: nkalyan🤠
'''implementing Python scripts on'''
"""
from string import punctuation
from collections import defaultdict
import os
def get_line(path):
"""Method that get each line from the file and reads it"""
try: # Excep... |
# Definition for a binary tree node
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
## dfs recursively
def levelOrderBottom1(self, root):
res = []
self.dfs(root, 0, res)
return res
... |
class Model:
def __init__(self):
self.__StonesOnBoard = dict()
self.marked_stone = None
def put_stone(self, position, stone):
if position not in self.__StonesOnBoard:
self.__StonesOnBoard[position] = stone
print("put_stone: ", self.__StonesOnBoard.keys())
... |
from domain.reporting.reporter import RGCollectorInterface
from domain.rule_group import SecurityGroup
from exceptions.custom_expections import ParseAWSResponseError
import boto3
class AWSSGCollector(RGCollectorInterface):
__source_key = "aws"
__name = "AWS SecurityGroup Collector"
def __init__(self):... |
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from itertools import accumulate
from random import random
from typing import TYPE_CHECKING
from simulation.config import INSTANCE as CONFIG
from simulation.id import generate_id
if TYPE_CHECKING:
from simulation.ev... |
"""This file is loaded when starting a new application instance."""
import vendor
# Add the libraries under ./lib to the classpath.
# This method is recommended by Google, according to http://stackoverflow.com/a/25564125/1567183.
vendor.add('lib')
|
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from theano import shared
from collections import OrderedDict
from logistic_sgd import LogisticRegression
from AutoEncoder import AutoEncoder, BernoulliAutoEncoder, GaussianAutoEncoder, ReluAutoEn... |
import numpy as np
import scipy as sp
class Abel:
@staticmethod
def diff(F):
res = np.zeros(len(F))
diff=np.diff(F)
res[0:len(F)-1]=diff[:]
return res
@staticmethod
def transform(F):
diff=Abel.diff(F)
nx = len(F)
x=np.arange(nx)
integral = ... |
import math
import time
def main(a):
m=a*2
nf=int(math.log(m,2))
values=[x*2 for x in range(a+1)]
factors=[0 for x in range(nf)]
factors[0]=1
cm=1
x=0
while True:
if x==0:
if cm==nf:
break
if factors[0]<factors[1]:
factors[0... |
# Generated by Django 3.1.7 on 2021-06-05 11:44
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0008_remove_profile_number_of_children'),
]
operations = [
migrations.RemoveField(
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 27 15:20:05 2018
@author: myth
"""
import rtlsdr
from pylab import *
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as signal
from scipy.io.wavfile import write
fs = 1e6 # sampling frequency
f_int = 100.4e6
f_off = 240000 ... |
from django.contrib import admin
from .models import *
admin.site.register(Manager)
admin.site.register(Provider)
admin.site.register(Goods)
admin.site.register(Record)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.