text stringlengths 38 1.54M |
|---|
import pyfiglet #pip
from colorama import init
from termcolor import colored
import sys, threading, os, time, json
from libs import getports as gp
from libs import attack_creds_first as attack
from libs import attack_routes_first as routeattack
init()
ascii_banner = pyfiglet.figlet_format("Pyllywood.")
print("{}\n{}\n... |
import pika
import json
# First thing to do is establish a connection with RabbitMQ server
# and create a new channel
# A connection represents a real TCP connection to the message broker,
# whereas a channel is a virtual connection (AMQP connection) inside it.
# This way you can use as many (virtual) connections as ... |
products = {
'test1': {
'path': 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRWIqNg8W4CdYI0RNvT4zEjmfjE5mLqy06R7w&usqp=CAU',
'name': 'Маргарита',
'composition': 'тесто на закваске\nсоус для пиццы\nсырный соус, сыр мозарелло, \nпомидор',
'price': 'Цена: 65 000 сум',
... |
#This is the data from the car
SOURCEDB = 'mysql+mysqldb://solar:Phenix@localhost/solarcar'
#This is the Database used by Telemetry to display data, there are two basic options
TELEMETRYDB = 'sqlite:///temp.db'
#Use database that only exists in memory. Use this if you want an easy setup
#Pros: Don't require mysql o... |
import math
import numpy as np
def im2c(im, w2c, color):
# input im should be DOUBLE !
# color=0 is color names out
# color=-1 is colored image with color names out
# color=1-11 is prob of colorname=color out;
# color=-1 return probabilities
# order of color names:
# black , blue , b... |
from infogan.models.regularized_gan import RegularizedGAN
import prettytensor as pt
import tensorflow as tf
import numpy as np
from progressbar import ETA, Bar, Percentage, ProgressBar
from infogan.misc.distributions import Bernoulli, Gaussian, Categorical
import sys
import os
import time
from infogan.misc.utils import... |
from __future__ import print_function
import numpy as np
import argparse
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transforms
import torch.nn.functional as F
import cv2 as cv
import random
parser = argpar... |
# noinspection PyUnresolvedReferences
from .sub.subadmins.classbook import *
# noinspection PyUnresolvedReferences
from .sub.subadmins.homework import *
|
import zmq
import time
class ClientV1(object):
"""description of class"""
def run(self):
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:18475")
while True:
print "Client version 1 is active..."
socket.send("alpha... |
t = int(raw_input())
def index(n,c,i):
return i*pow(n,c-1)+1
for i in range(1,t+1):
m = map(int, raw_input().split(" "))
n = m[0]
c = m[1]
s = m[2]
str1 = "Case #"+str(i)+": "
L = []
for i in range(0,n):
L.append(index(n,c,i))
for x in L:
str1+=str(x)
str1+=" "
print str1 |
# Code adapted from Corey Shafer
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Rather than doing a for each loop and appending to the list, this is a comprehension
my_list = [n for n in nums]
print(my_list)
# For the same thing, but multipling each value by itself:
my_list = [n*n for n in nums]
print(my_list)
# Using a ... |
import nltk
from nltk.corpus import wordnet
#import lemma
def calculate(queryv,queryn,queryr,verb,noun,adverb):
tot = 0; count = 1
lqv = len(queryv)
lqn = len(queryn)
lqr = len(queryr)
lv = len(verb)
ln = len(noun)
lr = len(adverb)
f = open('semantic_data.txt','a+')
#compare verbs o... |
class ComponentNotInstalledError(Exception):
""" Raised when a framework component is not installed"""
pass
class DirectoryNotFoundError(Exception):
"""Raised when a directory is excpected but not found"""
pass
class PackageNotInstalledError(Exception):
"""Raised when a package is expected but not... |
ANS = []
T = int(input())
for l in range(T):
S, SG, FG, D, TM = map(int, input().strip(' ').split())
SPD = S + (D*180/TM)
SE = abs(SPD - SG)
FE = abs(SPD - FG)
if SE < FE:
ANS.append('SEBI')
elif SE > FE:
ANS.append('FATHER')
elif SE == FE:
... |
import os
import torch
import torch.nn as nn
from .gnmt import GNMT
from .nmt import NMTModel
from .seq2seq import Seq2Seq
from translators.logger import logger
def count_parameters(model, trainable: bool = True):
return sum(p.numel() for p in model.parameters() if p.requires_grad == trainable)
def save_checkp... |
import platform,os, sys, time,csv,contextlib
cPalabraIni=''
cLetraEntro=''
iLetraLargo=0
iIntenfalla=0
bloop=True
lst_Espacio=[]
lst_Entrada=[]
Lst_ImagenA= ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
... |
import binascii
domain = "2mdn"
tld = ".net"
bin_repr = bin(int.from_bytes(domain.encode(), 'big'))
bin_repr = bin_repr[2:] #chop off '0b'
for index, bit in enumerate(bin_repr):
if bit == '1':
bit = '0'
else:
bit = '1'
new_bin_repr = bin_repr[:index] + bit + bin_repr[index + 1:]
new_... |
#!/usr/bin/env python
import sys
def reverse_words(sentence):
reverse_words = sentence.split(' ')[::-1]
return ' '.join(reverse_words)
def get_sentences(input_file):
with open(input_file, 'r') as f:
data = f.read()
sentences = data.split('\n')
return filter(lambda x: x != '', sent... |
from PRS import PRS_extract_phenotypes
import PRS_sumstats
full_bfile_path="/net/mraid08/export/jafar/Microbiome/Analyses/PNPChip/cleanData/PNP_autosomal_clean2_nodfukim"
#extract phenotypes IID Vs. Measured Phenotypes
df_pheno = PRS_extract_phenotypes.extract('s_stats_pheno') #Used for training set
#extract the predi... |
# -----------------------------------------------------------
# Behave Step Definitions for Aries DIDComm File and MIME Types, RFC 0044:
# https://github.com/hyperledger/aries-rfcs/blob/main/features/0044-didcomm-file-and-mime-types/README.md
#
# -----------------------------------------------------------
from time im... |
import Handler,usersdb ,userfun
logged = {}
class Signup(Handler.Handler):
def get(self):
self.render("signup_form.html")
def post(self):
username = self.request.get("username")
email = self.request.get("email")
password = self.request.get("password")
conf = self.request.get("conf")
#i nedd... |
import os
import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv
import logging
import queue
import glob_vars
STATUS_MESSAGE = " frustrated screams.."
USERNAME = "Rolbert 🎲"
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():... |
import torch
from UnarySim.sw.stream.gen import RNG
from UnarySim.sw.stream.shuffle import SkewedSync, Bi2Uni, Uni2Bi
from UnarySim.sw.kernel.shiftreg import ShiftReg
from UnarySim.sw.kernel.abs import UnaryAbs
import math
class CORDIV_kernel(torch.nn.Module):
"""
the kernel of the correlated divivison
thi... |
import numpy as np
# import pandas as pd
from std_msgs.msg import UInt16
class DataResolver:
def __init__(self):
self.arr = []
def avg_resolver(self, arr):
#pick out all none values
self.arr = arr [np.logical_not(np.isnan(arr))]
# self.r_arr = right_arr [np.logical_n... |
"""
:mod:`DBAdapters` -- database adapters for statistics
=====================================================================
.. warning:: the use the of a DB Adapter can reduce the performance of the
Genetic Algorithm.
Pyevolve have a feature in which you can save the statistics of every
gener... |
# =============================================================================
# Ural Telegram-related heuristic functions
# =============================================================================
#
# Collection of functions related to Telegram urls.
#
import re
from collections import namedtuple
from ural.ensu... |
def get_left(index):
return (2 * index) + 1
def get_right(index):
return (2 * index) + 2
def min_heapify(arr, index):
left = get_left(index)
right = get_right(index)
if left < len(arr) and arr[left] < arr[index]:
smallest = left
else:
smallest = index
if right < len(arr) a... |
# Generated by Django 3.1.6 on 2021-08-19 10:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('firstApp', '0016_rooms_room_id'),
]
operations = [
migrations.AddField(
model_name='rooms',
name='slug',
... |
import numpy as np
randn = np.random.randn
import pandas as pd
from bs4 import BeautifulSoup
from urllib2 import urlopen
from pandas.io.parsers import TextParser
import pandas.io.parsers as pdp
from pandas.io.data import DataReader
f = lambda x: str(x)
remove_w = lambda x: x.strip()
buf = urlopen('http://... |
from typing import Optional
import librosa
from librosa import display
import matplotlib.pyplot as plt
import numpy as np
import scipy
from librosa.display import specshow
from scipy.fftpack import fft, fftfreq
from scipy.io import wavfile
from sympy.stats.drv_types import scipy
class SpectraAnalysis:
iterator =... |
#!/bin/python
import sys
example_one = 15
expected = 4
def find_count(input_int):
byte_count = sys.getsizeof(input_int)
bit_count = byte_count * 8
one_count = 0
for i in range(bit_count):
if (input_int & 1) == 1:
one_count += 1
input_int = input_int >> 1
return one_count
def find_count_wh... |
from django.db import models
class Approach(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
description = models.CharField(max_length=500)
score = models.FloatField()
def __str__(self):
return '[ID: %d, Approach: %s, Score: %f]' % (self.id, sel... |
print("Your function is 8n^2+3n+3")
print ("g(n) = n^2 ")
print("Assuming c as 9")
n=0
for i in range (30):
a1 = 8*(i**2)+3*i+3
a2 = 10*(i**2)
if (a2>=a1):
n=i
break
print("Value of n0: ",n)
print ("Value\t\tF(n)\t\tc*G(n)")
for i in range (10,31):
print (i,"\t\t",8*(i**2)+3*i+3... |
import numpy as np
import time
from scipy.cluster.vq import kmeans
nr_total_centers = 200
feature_dimension = 250
def mapper(key, value):
# key: None
# value: one line of input file
yield "key", value
def reducer(key, values):
# key: key from mapper used to aggregate
# values: list of all value ... |
from rest_framework.serializers import ModelSerializer, raise_errors_on_nested_writes
from django.contrib.auth.models import User
from app.api.employee.serializers import Employee_listSerializer
from app.model import Attendance
from rest_framework import serializers
class AttandanceSerialzier(ModelSerializer):
#... |
import requests
import subprocess
import time, sys
print("Welcome to Distributed Nano Proof of Work System")
address = input("Please enter your payout address: ")
print("All payouts will go to %s" % address)
pow_source = int(input("Select PoW Source, 0 = local, 1 = node: "))
if pow_source > 1:
print("Incorrect Ent... |
#!/usr/bin/env python3
"""Check that all exported symbols are specified in the symbol version scripts.
If this fails, please update the appropriate .map file (adding new version
nodes as needed).
"""
import os
import pathlib
import re
import sys
top_srcdir = pathlib.Path(os.environ['top_srcdir'])
def symbols_from_... |
# Generated by Django 3.1.1 on 2020-11-05 16:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('GoodData', '0052_auto_20201102_1732'),
]
operations = [
migrations.CreateModel(
name='app_version',
fields=[
... |
#!/home/kevinr/src/750book-web-project/750book-web-env/bin/python2.7
# EASY-INSTALL-ENTRY-SCRIPT: 'celery==2.5.1','console_scripts','camqadm'
__requires__ = 'celery==2.5.1'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('celery==2.5.1', 'console_... |
#!/usr/bin/env python
import re
import sys
import DNS
if len(sys.argv) == 1 or sys.argv[1] == "-h":
print 'Get last status of someone on twitter'
print "Usage: %s sizeof" % sys.argv[0]
sys.exit(0)
try:
username = re.search('[a-zA-Z0-9*.]*', sys.argv[1]).group(0)
DNS.DiscoverNameServers();
r =... |
# --utf-8--
import unittest
from comment import context
from comment.request_util import Request
from ddt import ddt, data
from datetime import datetime
from testrun import de
from comment.log import get_logger
from comment.every_path import conf_path
from comment.readini import Readini
time = datetime.now().strftime(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Andrea Masi 2014 eraclitux@gmail.com
import unittest
import mock
import requests
from ipcampy.common import CamException
from ipcampy.foscam import FosCam, map_position
class TestFosCam(unittest.TestCase):
def test_map_position_1(self):
self.assertEqual(m... |
from base_command import base_command
import time
command_info = {
'id' : 'echo' ,
'rules' : [ '?(please) start echoing ?(me)' ] ,
'vars' : None
}
class command(base_command) :
def __init__(self,opts) :
# pass on the opts to the base class
super().__init__(opts) ... |
# Copyright 2017, DELLEMC, Inc.
"""
Module to abstract NPM operation
"""
import json
import sys
import os
try:
import common
except ImportError as import_err:
print import_err
sys.exit(1)
class NPM(object):
"""
A module of NPM
"""
def __init__(self, registry, token):
self._registr... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
query = demisto.args()['query']
rows = demisto.args()['rows']
headers = ""
query = query + ' | head ' + rows
res = demisto.executeCommand('splunk-search', {'using-brand': 'splunkpy', 'query': query})
contents = res[0]['Contents... |
import numpy as np
def aux(x):
pol = np.poly1d([-20, 70, -84, 35, 0, 0, 0, 0])
y = pol(x) * (x>=0) * (x<=1) #+ (x>1);
return y
def mother(x):
x = np.abs(x)
int1 = (x > np.pi/4) & (x <= np.pi/2);
int2 = (x > np.pi/2) & (x <= np.pi);
y = int1 * np.sin(np.pi/2*aux(4*x/np.pi-1)) #* np.exp(1j... |
from ..algo import Algo
from .. import tools
import numpy as np
import pandas as pd
from numpy import matrix
from cvxopt import solvers, matrix
solvers.options['show_progress'] = False
class CORN(Algo):
"""
Correlation-driven nonparametric learning approach. Similar to anticor but instead
of distance of r... |
#!/usr/bin/python
# coding: utf-8
# Copyright 2018 AstroLab Software
# Author: Chris Arnault
#
# 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... |
import unittest
import main
class FlaskTestCase(unittest.TestCase):
def setUp(self):
main.app.testing = True
client = main.app.test_client()
rv = client.post('/', data=dict(memo='テスト'))
self.html = rv.data.decode('utf-8').lower()
def test_result(self):
self.assertTr... |
import requests
import matplotlib.pyplot as plt
import json
import pandas
domain = "104.196.179.170/"
address = f'http://{domain}/api/traces'
operations = {
"Recv./": "recv_home_page",
"Recv./cart": "recv_cart",
"Recv./cart/checkout": "recv_cart_checkout",
"Recv./product/0PUK6V6EV0": "recv_product_0P... |
from __future__ import absolute_import, division, print_function
import os
import atexit
from ansible.plugins.callback import CallbackBase
RUNNING_TEMPLATE = "run-ansible/progress/info/running"
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'shrug'
CALLBACK_NAME = 'debconf'
... |
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.views import APIView
from accounts.api.serial... |
import c3srtconv
def write_single(line):
start_time = c3srtconv.time_to_srt_str(line.start_time)
end_time = c3srtconv.time_to_srt_str(line.end_time)
return "{} --> {}\n{}".format(start_time, end_time, line.text)
def write_multiple(lines):
srt = ''
num = 0
for line in lines:
num += 1... |
def has_tag(tag_id, content_item):
if not 'tags' in content_item:
return False
return tag_id in [tag['id'] for tag in content_item['tags']] |
# coding=utf-8
__author__ = 'leo.he'
import logging
logger = logging.getLogger()
logfile = 'app.log'
fh = logging.FileHandler(logfile)
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(mess... |
# Factory for bTCP segments
from btcp.segment_type import *
from btcp.constants import HEADER_SIZE, PAYLOAD_SIZE, SEGMENT_SIZE
from sys import byteorder
# Some indices
SEQUENCE_NUM = 0
ACK_NUM = 2
FLAGS = 4
WINDOW = 5
DATA_LENGTH = 6
CHECKSUM = 8
# Field sizes
SEQUENCE_SIZE = 2
ACK_SIZE = 2
FLAGS_SIZE = 1
WINDOW_SIZE... |
"""templer.django_project_app"""
import os
from templer.core.vars import StringVar
from templer.core.vars import BooleanVar
from templer.core.base import BaseTemplate
from templer.core.structures import Structure
HELP_TEXT = """
This creates a basic skeleton for a Django application within a project.
"""
POST_RUN_M... |
from PIL import Image
import sys
im = Image.open(sys.argv[1])
print('Picture format: ' + im.format)
print('Picture Matrix size: ' + str(im.size))
print('Picture mode: ' + im.mode)
row = im.size[0]
column = im.size[1]
print('Picture row: ' + str(row))
print('Picture column: ' + str(column))
def print_c... |
from django.shortcuts import render, redirect
from buddy_app.models import*
from django.contrib import messages
import bcrypt
def index(request):
return render(request, 'welcome.html')
def create_user(request):
if request.method == "POST":
errors = User.objects.registration_validator(request... |
import sys
from .. import Container, DataAttribute, Attribute, Attributes
from ..exc import Concern
class BaseTransform(Container):
"""The core implementation of common Transform shared routines.
Most transformer implementations should subclass Transform or SplitTransform.
"""
def foreign(self, value, contex... |
import pickle
from utilities import *
import numpy as np
import math
import pickle
from wordTypeCheckFunction import *
from collections import defaultdict
import pprint
def sigmoid(x):
return 1 / (1 + math.exp(-x))
"""
These models are count based probabilistic model
created using the DCS_Pick corpus
-------------... |
import sys
import csv
def WriteCSV(fileName,data):
csvfile = file(fileName, 'wb')
writer = csv.writer(csvfile)
writer.writerows(data)
csvfile.close()
def ReadCSV(fileName):
csvfile = file(fileName, 'rb')
reader = csv.reader(csvfile)
content = [item for item in reader]
#reader.close()
... |
import requests
from concurrent import futures
class ApiClient:
@staticmethod
def get(endpoint):
return requests.get(endpoint)
def get_concurrently(self, endpoints):
with futures.ThreadPoolExecutor(max_workers=len(endpoints)) as executor:
results = executor.map(self.get, endpo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import network
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
networkInfos = None
button_dhcp = None
button_setting_ip = None
entry_ip = None
entry_mask = None
entry_gateway = None
entry_... |
class Accord:
def __init__(self, notes):
self.notes = []
for note in notes:
self.notes.append(note)
def AddNote(note):
self.notes.append(note)
|
from starfish.pipeline import import_all_submodules
from ._base import Decoder
import_all_submodules(__file__, __package__)
|
# -*- coding: utf-8 -*-
"""
Created by
https://github.com/piszewc/
Scrap Wiki will scrap all Wiki tables from selected Page.
All tables are going to be saved to CSV file in current location.
"""
import requests
import pandas as pd
from bs4 import BeautifulSoup
page_html = "https://en.wikipedia.org/wiki/List_of_best... |
# Runtime 28 ms, Memory Usage 14.1 MB
def toGoatLatin(self, S: str) -> str:
# declare an empty dictionary
reference = {}
# iterate through a string of vowels and
for char in "aeiouAEIOU":
reference[char] = ""
# declare 3 variables
# split the argument string by word into a list
... |
import json
import os
import sqlite3
import traceback
DATABASE = os.getcwd()+'/databases/Data.db'
TABLE = 'PlayerInfo'
class Player:
def __init__(self, bot, ctx, user=None):
self.config = json.load(open(os.getcwd() + '/config/config.json'))
self.added_fields = []
self.removed_fields = []
... |
# coding=utf-8
#
from ft_converter.utility import logger
from ft_converter.match import match_repeat
#
# To be completed. See small_program.match_transfer.py
#
# def refine_price(transaction_list):
# """
# Refine the price for a transaction. When a transaction's price is zero,
# i.e., absent from the FT file,... |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
import socket
import thread
host = "192.168.0.101"
port = 9009
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, por... |
import sys
import os.path
sys.path.append(os.path.join(os.pardir,os.pardir))
import disaggregator as da
import disaggregator.PecanStreetDatasetAdapter as psda
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('appliance')
args = parser.parse_args()
db_url = "p... |
def kmax(arr, k, n):
for c in range(k):
max_so_far = -float("inf")
max_here = 0
start = 0
end = 0
s = 0
for i in range(n):
max_here += arr[i]
if (max_so_far < max_here):
max_so_f... |
'''
see also gauss_fitting.py
here:
do_linear_fit(data)
do_quadratic_fit(data)
do_cubic_fit(data)
do_exp_fit(data)
do_gauss_fit(data)
do_logistic_fit(data)
'''
from __future__ import print_function
from __future__ import division
import numpy as np
import scipy.odr
import scipy.optimize as optimize
import matplotlib.... |
from flask import Flask,render_template
from os import walk
app=Flask(__name__,static_folder="Z:\电影\三体-广播剧",static_url_path="/yjw")
@app.route("/")
def wlx():
s=[]
for root,dirs,files in walk("Z:\电影\三体-广播剧"):
for file in files:
b=root+"\\"+file
b=b.replace("\\","/")
b... |
import os
from os import path
import sys
tld = path.realpath(path.join(path.dirname(__file__), '../..'))
sys.path.append(path.join(tld, 'lib/python3.5/site-packages'))
import glob
import subprocess
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
here = ... |
from typing import Union
import httpx
import parsel
from core.utils import get_converted_currency
from schemas.search import Query
from .abstract import AbstractProvider
class MashinaKGProvider(AbstractProvider):
def get_validated_price(self, value: str) -> Union[str, None]:
if value:
return... |
import torch
from torch import nn
import torch.nn.functional as F
class ArcFace(nn.Module):
def __init__(self, margin = 0.5, scale = 64):
super(ArcFace, self).__init__()
self.margin = margin
self.scale = scale
#implementovano dle popisu z clanku ArcaFace https://arxiv.org/pdf/1801.0769... |
#!/usr/bin/env python3
# Import standard modules ...
import unittest
# Import my modules ...
try:
import pyguymer3
except:
raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None
# Define a ... |
from adxl345 import ADXL345
from time import sleep
adxl345 = ADXL345()
while 1:
axes = adxl345.getAxes(True)
print "x= %.3fG\ty=%.3fG\tz=%.3fG" %(axes['x'], axes['y'], axes['z'])
sleep(1)
|
import sys
import os
import gevent
def watch_modules(callback):
modules = {}
while True:
for name, module in list(sys.modules.items()):
if module is None or not hasattr(module, '__file__'):
continue
module_source_path = os.path.abspath(module.__file__).rstrip('c... |
#Title: Pie Graph
#Author: Hrishikesh H Pillai
#Date: 11-11-2019
import matplotlib.pyplot as plt
val=[12,34,50,43]
plt.pie(val)
plt.show() |
from itertools import chain, combinations, product
# Method to extract a value from nested tuple recursively
def extract_elem_from_tuple(my_var):
for val in my_var:
if type(val) == tuple:
for val in extract_elem_from_tuple(val):
yield val
else:
yield val
#... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import ConvLSTMCell, Sign
class EncoderCell(nn.Module):
def __init__(self):
super(EncoderCell, self).__init__()
self.conv = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1,
bias=False)
... |
"""
Title: recursive-gobuster
Date: 20190110
Author: epi <epibar052@gmail.com>
https://epi052.gitlab.io/notes-to-self/
Tested on:
linux/x86_64 4.15.0-43-generic
Python 3.6.6
pyinotify 0.9.6
"""
import time
import signal
import shutil
import argparse
import tempfile
import subprocess
from pathlib import P... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
training = pd.read_csv('E:/train.csv')
x_training = training['x']
y_training = training['y']
x_training = np.array(x_training)
y_training = np.array(y_training)
# print(x_training, " ", y_training)
def finda(m, alpha, y_training, x_training):... |
import os
import sys
import re
import numpy as np
import openmc
import openmc.mgxs
from make_bn800 import *
# Start global variables
N_LEGEND = 2
N_DELAY = 1
# PATH
PATH = "/home/barakuda/Рабочий стол/hdf5_openmc/XMAS172jeff2p2woZr71"
# PATH
ENERGIES = [19640330,
17332530,
14918250,
13840310,
11618340,
10000000,
818730... |
#!/usr/bin/python3
import argparse
from jinja2 import Environment, FileSystemLoader
import datetime
import db.mongodb as md
import re
from utils.email_obj import EmailObj
from setup import *
db_name = trade_db_name
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Daily Report')
parser.... |
from django.shortcuts import render, redirect, reverse
import pandas as pd
import requests
from .models import Exchange, Company
import time
from project import settings
from django.db import connection
from django.core.management import call_command
API_KEY = settings.FINNHUB_API_KEY
END_POINT = 'https://finnhub.io/a... |
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
def getseries(root):
if not root:
return ... |
# -*- coding: utf-8 -*-
__author__ = 'Vit'
from common.setting import Setting
from data_format.url import URL
from interface.loader_interface import LoaderInterface
from interface.model_interface import ModelFromControllerInterface, ModelFromSiteInterface
from interface.site_interface import SiteInterface
from interf... |
import numpy as np
import matplotlib.pyplot as plt
import trimesh
from mayavi import mlab
from bfieldtools.thermal_noise import (
compute_current_modes,
noise_covar,
noise_var,
visualize_current_modes,
)
from bfieldtools.mesh_magnetics import magnetic_field_coupling
import pkg_resources
font = {"fami... |
from multiprocessing import Process, Queue, Event
import tensorflow as tf
from tensorflow import keras
from tensorflow.contrib import training
import numpy as np
from typing import Callable
class DistributedNetworkConfig:
def __init__(self, learning_rate=0.01,
policy_weight=1.0,
... |
import os
import json
# mappings from schema.json to GSQL
dtype_mappings = {
'long': 'INT',
'date': 'DATETIME',
'int': 'INT'
}
def convert_dtype(dt):
if dt in dtype_mappings:
return dtype_mappings[dt]
else:
raise ValueError('Invalid data type: {}'.format(dt))
if __name__ == '__m... |
# coding: utf-8
# In[1]:
import xml.etree.cElementTree as ET
from collections import defaultdict
import re
import pprint
# In[2]:
osmfile = "san-jose.osm"
street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE)
expected = ["Street", "Avenue", "Boulevard", "Drive", "Court", "Place", "Loop", "Circle", "Square", "... |
'''A Deque double-ended queue. It can be visualized similar to a hollow tube or pipe, which is
open at the both ends. Deques allows addition and removal of elements from either ends. It
will be more clear with examples:
'''
import collections
de = collections.deque('JAreina')
print ('deque:', de
)
print( 'Lenght :'... |
import numpy as np
import matplotlib.pyplot as plt
peak_found = np.array([66.491, 92.886, 119.479, 139.362, 165.966, 192.643])
peak_real = np.array([-5.4823, -3.2473, -1.0132, 0.6624, 2.8967, 5.1338])
err = np.array([0.0008, 0.0008, 0.0010, 0.0007, 0.0007,0.0010])
p, cov = np.polyfit(peak_found,peak_real,deg=1,w=er... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 2 19:24:21 2017
@author: 310223340
"""
import pandas as pd
import numpy as np
from data_profile import execute_sql, write_to_table
import NDC_Mapping_v4
#%% create master diagnosis frame
def master_icd9():
print("\nCreating MASTER_icd9...")
ALZHDMTA_icd9 = pd.Da... |
import itertools
import logging
import numpy
import pylab
# Import simulator
import pynn_spinnaker as sim
import pynn_spinnaker_bcpnn as bcpnn
from copy import deepcopy
logger = logging.getLogger("pynn_spinnaker")
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
#-----------... |
""" Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
Example 1:
Input
["MinStack"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.