text
string
size
int64
token_count
int64
from django.apps import AppConfig class FruitsalesConfig(AppConfig): name = 'fruitsales'
95
30
import os os.system('python function_18351015.py > log.txt')
61
27
import sys, os import upandas as upd # Run a single Python script # For many simple, single file projects, you may find it inconvenient # to write a complete Dockerfile. In such cases, you can run a Python # script by using the Python Docker image directly: # versions to consider: 3 (600+ MB), slim (150 MB) alpine (9...
3,337
1,131
from __future__ import annotations from typing import Literal from prettyqt import constants, core, gui, widgets from prettyqt.qt import QtCore, QtWidgets from prettyqt.utils import InvalidParamError, bidict ECHO_MODE = bidict( normal=QtWidgets.QLineEdit.EchoMode.Normal, no_echo=QtWidgets.QLineEdit.EchoMode...
6,555
2,037
# ------------------------------------ # CODE BOOLA 2015 PYTHON WORKSHOP # Mike Wu, Jonathan Chang, Kevin Tan # Puzzle Challenges Number 8 # ------------------------------------ # INSTRUCTIONS: # Write a function that takes an integer # as its argument and converts it to a # string. Return the first character of ...
555
193
import matplotlib.pyplot as plt """ A chi square (X2) statistic is used to investigate whether distributions of categorical variables differ from one another. Here we consider 3 degrees of freedom for our system. Plotted against 95% line""" lidar_nis = [] with open('NISvals_laser.txt') as f: for line in f: ...
1,086
428
import torch from offlinerl.utils.exp import select_free_cuda task = "Hopper-v3" task_data_type = "low" task_train_num = 99 seed = 42 device = 'cuda'+":"+str(select_free_cuda()) if torch.cuda.is_available() else 'cpu' obs_shape = None act_shape = None max_action = None hidden_features = 256 hidden_layers = 2 atoms ...
695
317
from django.contrib.admin.options import get_content_type_for_model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.urls import reverse from django.u...
8,325
2,442
import unittest import torch from torch.nn.functional import binary_cross_entropy as bce, l1_loss from mlx.od.ssd.utils import ( ObjectDetectionGrid, BoxList, compute_intersection, compute_iou, F1) class TestIOU(unittest.TestCase): def test_compute_intersection(self): a = torch.tensor([[0, 0, 2, 2], ...
7,991
3,233
''' AUTOR: Javier Carracedo Date: 08/10/2020 Auxiliar class to test methods from WilliamHillURLs.py ''' import WilliamHillURLs if __name__ == "__main__": myVariable = WilliamHillURLs.WilliamHillURLs() # Print all matches played actually. for item in myVariable.GetAllMatchsPlayedActually(m...
3,284
1,668
import glob import os import shutil import sys import tarfile from tempfile import TemporaryDirectory from ..utils import ERROR from ..utils import Spinner from ..utils import add_jobs_argument from ..utils import add_no_ccache_argument from ..utils import add_verbose_argument from ..utils import box_print from ..util...
3,185
985
""" A model class for Sale """ # local imports from app.api.common.utils import dt from app.api.v2.db_config import conn from app.api.v2.models.cart import Cart # cursor to perform database operations cur = conn.cursor() class Sale(Cart): """ Sale object which inherites some of its attributes from cart ...
1,011
311
import aiohttp from bs4 import BeautifulSoup import asyncio from dembones.webpage import WebPage import dembones.urltools as ut import logging log = logging.getLogger(__name__) class Collector: url_hash = {} def __init__(self, max_concurrent_fetches=3, max_depth=3, fetch_timeout=5, target_...
3,306
931
from ..factory import Type class inputInlineQueryResultVideo(Type): id = None # type: "string" title = None # type: "string" description = None # type: "string" thumbnail_url = None # type: "string" video_url = None # type: "string" mime_type = None # type: "string" video_width = None # type: "int32" v...
501
185
import argparse import train_args def get_arg_parser() -> argparse.ArgumentParser: ''' A set of parameters for evaluation ''' parser = train_args.get_arg_parser() parser.add_argument('--load_path', type=str, help='the path of the model to test') parser.add_argument('--eval_train', action='store...
710
204
""" Creates a fidelity estimator for any pure state, using randomized Pauli measurement strategy. Author: Akshay Seshadri """ import warnings import numpy as np import scipy as sp from scipy import optimize import project_root # noqa from src.optimization.proximal_gradient import minimize_proximal_gradi...
43,792
13,790
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 28 10:29:52 2018 @author: lin """ import numpy as np import matplotlib.pyplot as plt def accuracy(x,y,model): a = model.predict(x,y) a[a>=0.5]=1 a[a<0.5]=0 return np.sum(a==y)/len(a) data1 = np.load("datasets/breast-cancer.n...
2,054
798
# dumpfreeze # Create MySQL dumps and backup to Amazon Glacier import os import logging import datetime import click import uuid import sqlalchemy as sa from dumpfreeze import backup as bak from dumpfreeze import aws from dumpfreeze import inventorydb from dumpfreeze import __version__ logger = logging.getLogger(__na...
11,996
3,648
import csv FLAGS = None def main(): with open('dataset/test.csv', 'w') as csv_file: writer = csv.writer(csv_file, delimiter=',') #for w in range(-FLAGS.width, FLAGS.width+1i): w = -60 while w <= 60: h = -28 #for h in range(-FLAGS.height, FLAGS.height+1): ...
886
276
""" Script to create dataframe from serpent bumat files including all the nuclides. Zsolt Elter 2019 """ import json import os with open ('nuclides.json') as json_file: nuclidesDict = json.load(json_file) #final name of the file dataFrame='PWR_UOX-MOX_BigDataFrame-SF-GSRC-noReactorType.csv' def readInventory...
3,546
1,346
from mongoengine import disconnect from waitress import serve from todolist_backend.server import app, get_configs from .database import panic_init from .info import MONGOENGINE_ALIAS def run_debug(): panic_init() app.run(**get_configs()) # disconnect(alias=MONGOENGINE_ALIAS) def run_production(): p...
453
161
a = int(input("a = ")) b = int(input("b = ")) print("{} + {} = {}".format(a, b, a+b))
86
42
# File: archer_views.py # # Copyright (c) 2016-2022 Splunk Inc. # # 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 appli...
2,953
816
import re import sys from collections import defaultdict from types import TracebackType from typing import ( Callable, DefaultDict, Dict, Generator, List, Optional, Tuple, Type, Union, ) # This is a mapping of plugin_name -> PluginError instances # all PluginErrors get added to thi...
12,198
3,609
import uvicorn from gql import gql, reference_resolver, query from stargql import GraphQL from helper import get_user_by_id, users type_defs = gql(""" type Query { me: User } type User @key(fields: "id") { id: ID! name: String username: String } """) @query('me') def get_me(_, info): r...
572
217
from __future__ import absolute_import, division, print_function import stripe import pytest pytestmark = pytest.mark.asyncio TEST_RESOURCE_ID = "fee_123" TEST_FEEREFUND_ID = "fr_123" class TestApplicationFee(object): async def test_is_listable(self, request_mock): resources = await stripe.Applicatio...
2,519
825
def busyschedule(): times = input() while (times != 0): timeList = [] for i in range(0, times): timeS = raw_input() time = timeS.split() time[0] = time[0].split(":") if time[1] == "a.m.": if time[0][0] == "12": t...
866
280
#!/usr/bin/env python from unittest import TestCase from fundamentals.backtracking.path_through_grid import PathThroughGrid class TestPathThroughGrid(TestCase): def test_no_path(self): grid = [ [0, 1, 0], [1, 0, 1], [0, 0, 1] ] ptg = PathThroughGrid(g...
607
243
import sqlite3 import Sources.Parser conn = sqlite3.connect("Database/vitg.db") cursor = conn.cursor() cursor.execute("SELECT * FROM Locations") results = cursor.fetchall() print(results) conn.close() parser = Sources.Parser.Parser() words = [u"любить", u"бить"] for word in words: command = parser.getCommand(wo...
343
115
import numpy as np import pandas as pd import sys import string import time import subprocess from collections import Counter import string import random def random_pheno_generator(size=6,chars=string.ascii_lowercase): return ''.join(random.choice(chars) for _ in range(size)) #First argument is the gene score dist...
7,018
2,817
"""Convenience functions for dictionary access and YAML""" from sklearn.utils import Bunch from collections import OrderedDict from collections.abc import Mapping import copy import yaml # ---------------------------------------------------------------------------- def deep_convert_list_dict(d, skip_list_level=0): ...
7,273
2,185
########################################################################## # If not stated otherwise in this file or this component's Licenses.txt # file the following copyright and licenses apply: # # Copyright 2016 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not...
6,612
2,068
import logging import yaml logger = logging.getLogger(__name__) class Config(object): __instance__ = None cfg = {} def __new__(cls, *args, **kwargs): if Config.__instance__ is None: Config.__instance__ = object.__new__(cls) return Config.__instance__ def load(self, loca...
492
148
#!/usr/bin/env python3 # -*- coding: iso-8859-15 -*- # 2017, Samantha Klasfeld, the Wagner Lab # the Perelman School of Medicine, the University of Pennsylvania # Samantha Klasfeld, 12-21-2017 import argparse import sys import pandas as pd import numpy as np parser = argparse.ArgumentParser(description="this scrip...
8,536
3,079
# parse the input with open("6-input.txt") as f: fish = [int(n) for n in f.readline().split(",")] startcounts = dict(zip(range(0, 9), [0 for x in range(9)])) for f in fish: startcounts[f] += 1 def updatedcounts(counts): newcounts = {} newcounts[8] = counts[0] newcounts[7] = counts[8] newcount...
884
365
#!/usr/bin/env python # # standalone = True import os, numpy as np os.environ['MCVINE_MPI_BINDING'] = 'NONE' import unittestX as unittest class TestCase(unittest.TestCase): def test1(self): 'mccomponents.sample.samplecomponent: SQkernel' # The kernel spec is in sampleassemblies/V-sqkernel/V-...
3,287
1,185
from ZeroKnowledge import primality import random def goodPrime(p): return p % 4 == 3 and primality.probablyPrime(p, accuracy=100) def findGoodPrime(numBits=512): candidate = 1 while not goodPrime(candidate): candidate = random.getrandbits(numBits) return candidate def makeModulus(numBits=5...
693
278
#!/usr/bin/env python # ############################################################################### # Author: Greg Zynda # Last Modified: 12/11/2019 ############################################################################### # BSD 3-Clause License # # Copyright (c) 2019, Greg Zynda # All rights reserved. # # ...
5,811
2,315
#!/usr/bin/python3 DOC="""plotCurve plotCurve is used to create vertical profiles of different lateral ylabel statistics of FEOTS output. Usage: plotCurve plot <file> [--out=<out>] [--opts=<opts>] [--scalex=<scalex>] [--xlabel=<xlabel>] [--ylabel=<ylabel>] Commands: plot Create a vertical profile p...
2,113
762
################################################################################ # 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...
6,535
2,349
#import pcap #import dpkt #import dnet from collections import defaultdict from scapy.all import * from scapy.all import send as ssend import netifaces import getopt import datetime conf.sniff_promisc=True pcap_specified = False detection_map = defaultdict(list) def detect_poison(pkt): global pcap_specified if IP i...
2,438
1,069
"""Detail Yeti's Malware object structure.""" from .entity import Entity class Malware(Entity): """Malware Yeti object. Extends the Malware STIX2 definition. """ _collection_name = 'entities' type = 'malware' @property def name(self): return self._stix_object.name @property...
534
169
from dsbox.template.template import DSBoxTemplate from d3m.metadata.problem import TaskKeyword from dsbox.template.template_steps import TemplateSteps from dsbox.schema import SpecializedProblem import typing import numpy as np # type: ignore class SRIClassificationTemplate(DSBoxTemplate): def __init__(self...
6,405
1,671
time = eval(input()) qtdtime = [3600, 60, 1] result = [] for i in qtdtime: qtd = time // i result.append(str(qtd)) time -= qtd * i print(f'{result[0]}:{result[1]}:{result[2]}')
192
91
from collections import Counter def count_mentioned(con,names): con=con.lower() res=[con.count(i.lower()) for i in names] return res if res else None
161
50
import threading import functools import sqlalchemy from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class DatabaseContextError(RuntimeError): pass """ Once an engine is created is is not destroyed until the program itself exits. Engines are used to produce a new session when...
5,458
1,483
class Solution: def maximum69Number(self, num: int) -> int: return int(str(num).replace('6', '9', 1))
114
41
import numpy as np from rover_sates import * from state_machine import * # This is where you can build a decision tree for determining throttle, brake and steer # commands based on the output of the perception_step() function def decision_step(Rover, machine): if Rover.nav_angles is not None: machine.ru...
444
141
import sys from loguru import logger logger.remove() logger.add( sys.stdout, format='{level.icon} {time:YYYY-MM-DD HH:mm:ss} <lvl>{level}\t{message}</lvl>', colorize=True, )
188
76
""" Copyright 2013 Rackspace 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 writing, software dist...
1,770
571
import os from dash import dcc, html URL_PATH_SEP = '/' URL_BASE_PATHNAME = os.getenv('REPORT_URL_BASE', URL_PATH_SEP) if URL_BASE_PATHNAME[-1] != URL_PATH_SEP: URL_BASE_PATHNAME += URL_PATH_SEP def Header(app): return html.Div([get_header(app), html.Br([]), get_menu()]) def get_header(app): header = h...
2,953
762
from social_core.backends.ubuntu import UbuntuOpenId
53
15
# -*- coding: utf-8 -*- ''' :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> ''' # pylint: disable=3rd-party-module-not-gated # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import tempfile import shutil # Import Salt Testing Libs from tests.support.mixins import Lo...
10,715
2,862
__name__ = "{{Name}}" __version__ = "{{Version}}"
50
21
import json # PyQt imports from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QDialog from PyQt5.QtWebChannel import QWebChannel # Local includes from .ui.widget_ui import Ui_Dialog from alfred import data_rc import alfred.alfred_globals as ag from alfred.modules.api.view_components import ...
3,203
1,029
import re from utils import * class JackTokenizer: def __init__(self, file_name): self._file = open(file_name, 'r') self._data = [] self._types = [] self._tokens = [] self._xml = ['<tokens>'] self._tokens_iterator = iter(self._tokens) self._token_types_iter...
5,573
1,572
""" Main module of a program. """ import folium from tools import find_coords, user_input def creating_map(): """ Creates HTML page for a given data. """ year, coords = user_input() locations = find_coords(year, coords) mp = folium.Map(location=coords, zoom_start=10) mp.add_child(folium....
1,115
359
from ptCrypt.Symmetric.Modes.Mode import Mode from ptCrypt.Symmetric.BlockCipher import BlockCipher from ptCrypt.Symmetric.Paddings.Padding import Padding class ECB(Mode): """Electronic codebook mode of encryption. The simplest encryption mode. Encrypts every block independently from other blocks. More: ...
1,366
423
#!/usr/bin/env python3 # Originally python2 # Sample from https://www.collabora.com/news-and-blog/blog/2019/05/14/an-ebpf-overview-part-5-tracing-user-processes/ # Python program with embedded C eBPF program from bcc import BPF, USDT import sys bpf = """ #include <uapi/linux/ptrace.h> BPF_PERF_OUTPUT(events); struc...
1,335
535
import numpy as np import pytest from sudoku import SudokuLine, build_rows, build_columns from sudoku import SudokuSquare, build_squares def test_reference(): dimension = 3 dim_pow = dimension ** 2 board = np.zeros((dim_pow, dim_pow), dtype='int') symbols = np.arange(1, dim_pow + 1) squares = build_squares(board...
1,004
433
import os import json import datetime from pytz import timezone, utc def update_total_score(name_list_dict, score_rules, now_kst_aware, penalty_const=.1): """ Update Total Score when scheduled day written in "ScoreRule.json" :param name_list_dict: This contains contestants score info loaded from "namelist....
1,424
453
import os import gzip import pickle import h5py import numpy as np import theano from utils.misc import get_file_names_in_dir from utils.vocab import UNK class Loader(object): def __init__(self, argv): self.argv = argv def load(self, **kwargs): raise NotImplementedError @staticmethod ...
3,500
1,121
from django.urls import path from .views import ( home, MachineDetailView, MachineListView, DryRunDataDetailView, MachineLastDataView, ) urlpatterns = [ path('', MachineListView.as_view(), name='home-view'), path('', MachineListView.as_view(), name='machine-list-view'), path('machine/<...
591
195
""" Python version 3.6.7 OS Linux Ubuntu 18.04.1 LTS Created: 30/11/2018 17:12 Finished: 30/11/2018 19: Author: Adrian Garrido Garcia """ import sys from wall.builder import build_a_wall if __name__ == '__main__': try: build_a_wall(sys.argv[1], sys.argv[2]) except IndexError: rows = input("Ple...
480
187
import os import csv import cv2 import numpy as np import torch from torch.utils.data import Dataset, DataLoader def transform(snippet): ''' stack & noralization ''' snippet = np.concatenate(snippet, axis=-1) snippet = torch.from_numpy(snippet).permute(2, 0, 1).contiguous().float() snippet = snippet.mu...
2,770
1,026
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-19 08:29 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20161006_0128'), ] operations = [...
1,342
385
# generate_tfrecords.py # Note: substantial portions of this code, expecially the create_tf_example() function, are credit to Dat Tran # see his website here: https://towardsdatascience.com/how-to-train-your-own-object-detector-with-tensorflows-object-detector-api-bec72ecfe1d9 # and his GitHub here: https://github.com...
8,505
2,468
import gevent.monkey gevent.monkey.patch_all() import os from logging import getLogger #from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor from apscheduler.schedulers.gevent import GeventScheduler as Scheduler from couchdb import Server, Session from couchdb.http import Unauthorized, extract...
6,398
2,062
#code which sends many setBlock commands all in one go, to see if there was # a performance improvement.. It sent them a lot quicker, but you still had to wait # for minecraft to catch up import mcpi.minecraft as minecraft import mcpi.block as block import mcpi.util as util from time import time, sleep def setManyBloc...
1,078
394
from django import template from django.conf import settings from django.utils.translation import ugettext as _ from django.forms.forms import pretty_name #from yats.diff import generate_patch_html import re try: import json except ImportError: from django.utils import simplejson as json register = template.L...
2,059
622
"""Test the binding of names when a circular zaimportuj shares the same name jako an attribute.""" z .rebinding2 zaimportuj util
129
34
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 8 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import os from scapy.all import * pkts = [] count = 0 pcapnum = 0 def write_cap(x): global pkts...
1,132
403
import pyramid_crud import pytest from pyramid.exceptions import ConfigurationError from pyramid.interfaces import ISessionFactory @pytest.fixture def static_prefix(config): "Add a static URL prefix with the name '/testprefix'" config.add_settings({'crud.static_url_prefix': '/testprefix'}) @pytest.fixture d...
2,862
949
""" You are given a sorted array in ascending order that is rotated at some unknown pivot (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]) and a target value. Write a function that returns the target value's index. If the target value is not present in the array, return -1. You may assume no duplicate exists in...
1,621
606
import discord from discord.ext import commands class utility(commands.Cog): def __init__(self, client): self.client = client @commands.guild_only() @commands.command(name = "avatar", aliases = ["av", "pic"]) async def avatar(self, ctx, user: discord.User=None): if user is No...
987
357
import torch from torch.fx.graph import Node from .pattern_utils import ( register_fusion_pattern, ) from .utils import _parent_name from .quantization_types import QuantizerCls, NodePattern, Pattern from ..fuser_method_mappings import get_fuser_method from ..fuser_method_mappings import get_fuser_method_new from a...
8,215
2,712
import numpy as np import torch import torch.nn as nn import torchvision EPS = 1e-7 class Encoder(nn.Module): def __init__(self, cin, cout, in_size=64, nf=64, activation=nn.Tanh): super(Encoder, self).__init__() network = [ nn.Conv2d(cin, nf, kernel_size=4, stride=2, padding=1, bias=...
9,786
3,994
#!/usr/bin python #coding:utf-8 # # 生成10^7个乱序整数 import random RANGE = 10000000 f = open('../test/input/bitSort.input','w') for i in random.sample(range(RANGE),RANGE): f.write(str(i) + '\n') f.close() print 'generator input file success!'
244
116
# 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) AutoRest Code Generator. # Changes may ...
46,478
13,607
import nibabel as nib import numpy as np from glob import glob def to_slice(image_path,seg_path): image = nib.load(image_path).get_fdata() seg = nib.load(seg_path).get_fdata() image_list = [] seg_list = [] for i in range(image.shape[2]): if(np.nonzero(image[i])!= 0): image_list....
407
152
import os import unittest from doublebook.ebook import Ebook THIS_DIR = os.path.dirname(os.path.abspath(__file__)) class EbookTest(unittest.TestCase): def setUp(self): path_to_text = os.path.join(THIS_DIR, "test_data", "zen_en.txt") self.ebook = Ebook(path_to_text) def test_read(self): ...
576
208
class LogGroup(object): def __init__(self, name, streams=None): self.name = name self.streams = streams @classmethod def from_dict(cls, group_dict): return LogGroup(group_dict['logGroupName']) def __eq__(self, other): return self.name == other.name
299
91
#!/usr/bin/env python """ run this every time you upgrade the godot-base version to generate new matching github workflows You must be in this directory, and in the modules subfolder of godot (just as if you would install this project into godot) usage: python build_github_actions.py --godot-version "3.4.4-stable" --g...
13,924
4,523
from collections import defaultdict from typing import Dict, Iterable, List, Optional, Set, Tuple, cast from sqlalchemy import column from panoramic.cli.husky.common.enum import EnumHelper from panoramic.cli.husky.core.taxonomy.aggregations import AggregationDefinition from panoramic.cli.husky.core.taxonomy.enums imp...
10,061
2,873
import os import re import six import h5py import json import logging import tensorflow.keras as keras from tensorflow.python.keras import optimizers from tensorflow.python.keras.saving import hdf5_format from tensorflow.python.keras.utils import tf_utils from tensorflow.python.keras.saving import saving_utils from t...
13,836
3,879
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-26 06:57 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion from wapps.utils import get_image_model def drop_empty_gallery_images(apps, schema_editor): AlbumImage = apps.get_model('galle...
875
296
#!/usr/bin/env python import climt from pylab import * # Replicates the behavior of the online radiation calculator # see maths.ucd.ie/~rca scheme = 'ccm3' Insolation = 337. #* .75 Imbalance = 30. Albedo = 30. /100. CO2 = 350. CH4 = 1.7 + 1.e-9 N2O = 0. + 1.e-...
6,888
3,247
{ "ev_get_bg_color" : { "repl_text" : ("(self, color, ea) -> int", "(self, ea) -> int or None"), } }
117
53
#pca model n componentes from sklearn.decomposition import PCA import numpy as np from pylab import rcParams import matplotlib.pyplot as plt import pandas as pd def pca_model_n_components(df,n_components): ''' Definition: Initialize pca with n_components args: dataframe and number of components returns: ...
4,576
1,712
import datetime import numpy as np import json from sklearn.decomposition import NMF, LatentDirichletAllocation, TruncatedSVD from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import stopwords import spacy from media_analyzer import database NUM_TOPICS = 20 def load_data(begin, end, langu...
4,446
1,377
import urllib2 def get_public_ip(request_target): grabber = urllib2.build_opener() grabber.addheaders = [('Useragent','Mozilla/5.0')] try: public_ip_address = grabber.open(target_url).read() except urllib2.HTTPError, error: print("There was an error trying to get your Public IP: %s") % (error) except urllib2....
669
248
# import necessary modules import os import re import requests import newspaper from bs4 import BeautifulSoup from newspaper import Article from newspaper import Config from article_summarizer import summarizer from time import sleep # clean data class Cleanser: """Scrape the news site and get the relevant updates...
2,586
705
from aria.models import Genus, Species, Subspecies from django import forms from django.forms import inlineformset_factory from .templates.templates import createTextInput, createSelectInput class CreateSpeciesForm(forms.ModelForm): class Meta: model = Species fields = ["name", "common_name"] ...
1,351
391
import math def angle(m): return 5.5 * m/60; print(angle(20)) i = 0 for m in range(0,1440*60): a = angle(m) / 360 d = a - math.floor(a) if (d < 0.00001): print(a, math.floor(a), d, d == 0.0) i += 1 print(i) for m in range(25): print(360*m/5.5)
285
152
#!/usr/bin/env python # # Public Domain 2014-present MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a com...
4,038
1,278
from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path, include, reverse_lazy from django.views.generic.base import RedirectView from rest_framework import permissions from rest_framework.authtoken import views from rest_framew...
1,779
568
# pylint: disable=line-too-long, no-member from __future__ import print_function import arrow import requests from django.conf import settings from django.contrib.gis.geos import GEOSGeometry from django.utils import timezone from django.utils.text import slugify from passive_data_kit_external_sensors.models import...
4,260
1,238
import numpy as np import os import sys import yaml from .fgcmUtilities import FocalPlaneProjectorFromOffsets from .fgcmLogger import FgcmLogger class ConfigField(object): """ A validatable field with a default """ def __init__(self, datatype, value=None, default=None, required=False, length=None): ...
37,496
11,347
#Bibeta in action. import numpy as np import matplotlib.pyplot as plt from scipy.stats import beta from scipy.stats import randint def plot_1D_function(x, y, y_name='y'): ax = plt.subplot(111) ax.plot(x, y, label=y_name) plt.legend(loc='best') plt.title(y_name) plt.show() def fixed_ob...
1,474
723
from setuptools import setup, find_packages from scatteringmatrix import __version__ with open("README.md", "r") as fh: long_description = fh.read() setup(name='scatteringmatrix', version=__version__, description='Optical scattering matrix library', long_description=long_description, long_...
1,350
387