max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
mapping/sandbox/graphslam/graphslam_pipeline.py | sameeptandon/sail-car-log | 1 | 11900 | <reponame>sameeptandon/sail-car-log
import os
from os.path import join as pjoin
from subprocess import check_call
from ruffus import files, follows, pipeline_run, pipeline_printout, pipeline_printout_graph, jobs_limit
from graphslam_config import GRAPHSLAM_PATH,\
GRAPHSLAM_MATCH_DIR, GRAPHSLAM_OPT_POS_DIR, GRAP... | import os
from os.path import join as pjoin
from subprocess import check_call
from ruffus import files, follows, pipeline_run, pipeline_printout, pipeline_printout_graph, jobs_limit
from graphslam_config import GRAPHSLAM_PATH,\
GRAPHSLAM_MATCH_DIR, GRAPHSLAM_OPT_POS_DIR, GRAPHSLAM_ALIGN_DIR,\
MATCHES_FI... | en | 0.949083 | # NOTE Have to rerun this after match_traces is run | 2.135067 | 2 |
sandbox/wavelets.py | EtalumaSupport/LumaViewPro | 0 | 11901 | import numpy as np
import matplotlib.pyplot as plt
from astropy.convolution import RickerWavelet2DKernel
ricker_2d_kernel = RickerWavelet2DKernel(5)
plt.imshow(ricker_2d_kernel, interpolation='none', origin='lower')
plt.xlabel('x [pixels]')
plt.ylabel('y [pixels]')
plt.colorbar()
plt.show()
print(ricker_2d_kernel)
| import numpy as np
import matplotlib.pyplot as plt
from astropy.convolution import RickerWavelet2DKernel
ricker_2d_kernel = RickerWavelet2DKernel(5)
plt.imshow(ricker_2d_kernel, interpolation='none', origin='lower')
plt.xlabel('x [pixels]')
plt.ylabel('y [pixels]')
plt.colorbar()
plt.show()
print(ricker_2d_kernel)
| none | 1 | 2.957274 | 3 | |
tests/test_errors.py | raymundl/firepit | 0 | 11902 | <filename>tests/test_errors.py
import os
import pytest
from firepit.exceptions import IncompatibleType
from firepit.exceptions import InvalidAttr
from firepit.exceptions import InvalidStixPath
from firepit.exceptions import InvalidViewname
from firepit.exceptions import StixPatternError
from .helpers import tmp_stora... | <filename>tests/test_errors.py
import os
import pytest
from firepit.exceptions import IncompatibleType
from firepit.exceptions import InvalidAttr
from firepit.exceptions import InvalidStixPath
from firepit.exceptions import InvalidViewname
from firepit.exceptions import StixPatternError
from .helpers import tmp_stora... | en | 0.979698 | Look for finding objects that aren't there | 2.12235 | 2 |
script/run_scribus.py | csneofreak/public-domain-season-songs | 14 | 11903 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import json
import os
import math
import scribus
import simplebin
import inspect
from collections import defaultdict
PWD = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
def pwd(path):
return os.path.join(PWD, path);
DATA_FILE = pwd... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import json
import os
import math
import scribus
import simplebin
import inspect
from collections import defaultdict
PWD = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
def pwd(path):
return os.path.join(PWD, path);
DATA_FILE = pwd... | en | 0.784916 | #!/usr/bin/python # -*- coding: utf-8 -*- # use this to debug # load pages from other document # filename # range of pages to import # insert (1) or replace(0) # where to insert # come to a state that the text box does not overflow: # reduce height # is this really the right way? is there no shortcut provided by scribu... | 2.491812 | 2 |
12-transformar_metro.py | tainagirotto/exercicios-py | 0 | 11904 | # Ler um número em metros e mostrar seu valor em cm e mm:
m = float(input('Digite o valor em metros: '))
dm = m * 10
cm = m * 100
mm = m * 1000
km = m/1000
hm = m/100
dam = m/10
print('O valor em cm é {}' .format(cm))
print('O valor em milímetros é {}' .format(mm))
print('O valor em dm é {}' .format(dm))
print('O val... | # Ler um número em metros e mostrar seu valor em cm e mm:
m = float(input('Digite o valor em metros: '))
dm = m * 10
cm = m * 100
mm = m * 1000
km = m/1000
hm = m/100
dam = m/10
print('O valor em cm é {}' .format(cm))
print('O valor em milímetros é {}' .format(mm))
print('O valor em dm é {}' .format(dm))
print('O val... | pt | 0.992407 | # Ler um número em metros e mostrar seu valor em cm e mm: | 4.183459 | 4 |
src/urls.py | chunky2808/Hire-Me | 0 | 11905 | <filename>src/urls.py<gh_stars>0
"""src URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$... | <filename>src/urls.py<gh_stars>0
"""src URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$... | en | 0.5982 | src URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... | 2.552908 | 3 |
re_compare/re_compare.py | gchase/re-compare | 0 | 11906 | #!/usr/bin/env python3
import logging
import argparse
import traceback
import os
import sys
from analysis import Analysis
from collector import Collector
from config import DEBUG, DEFAULT_LOG_FILE_DIR
def is_dir(dirname):
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
... | #!/usr/bin/env python3
import logging
import argparse
import traceback
import os
import sys
from analysis import Analysis
from collector import Collector
from config import DEBUG, DEFAULT_LOG_FILE_DIR
def is_dir(dirname):
if not os.path.isdir(dirname):
msg = "{0} is not a directory".format(dirname)
... | fr | 0.221828 | #!/usr/bin/env python3 | 2.433018 | 2 |
venv/Lib/site-packages/nipype/conftest.py | richung99/digitizePlots | 585 | 11907 | <gh_stars>100-1000
import os
import shutil
from tempfile import mkdtemp
import pytest
import numpy
import py.path as pp
NIPYPE_DATADIR = os.path.realpath(
os.path.join(os.path.dirname(__file__), "testing/data")
)
temp_folder = mkdtemp()
data_dir = os.path.join(temp_folder, "data")
shutil.copytree(NIPYPE_DATADIR, d... | import os
import shutil
from tempfile import mkdtemp
import pytest
import numpy
import py.path as pp
NIPYPE_DATADIR = os.path.realpath(
os.path.join(os.path.dirname(__file__), "testing/data")
)
temp_folder = mkdtemp()
data_dir = os.path.join(temp_folder, "data")
shutil.copytree(NIPYPE_DATADIR, data_dir)
@pytest.... | en | 0.952237 | Grabbed from https://stackoverflow.com/a/46991331 # Trigger ONLY for the doctests. # Get the fixture dynamically by its name. # Chdir only for the duration of the test. # For normal tests, we have to yield, since this is a yield-fixture. # Delete temp folder after session is finished | 2.062049 | 2 |
tests/test_modules/test_ADPandABlocks/test_adpandablocks_blocks.py | aaron-parsons/pymalcolm | 0 | 11908 | <reponame>aaron-parsons/pymalcolm
from mock import Mock
from malcolm.testutil import ChildTestCase
from malcolm.modules.ADPandABlocks.blocks import pandablocks_runnable_block
class TestADPandABlocksBlocks(ChildTestCase):
def test_pandablocks_runnable_block(self):
self.create_child_block(
pand... | from mock import Mock
from malcolm.testutil import ChildTestCase
from malcolm.modules.ADPandABlocks.blocks import pandablocks_runnable_block
class TestADPandABlocksBlocks(ChildTestCase):
def test_pandablocks_runnable_block(self):
self.create_child_block(
pandablocks_runnable_block, Mock(),
... | none | 1 | 2.286875 | 2 | |
pymbolic/mapper/coefficient.py | sv2518/pymbolic | 0 | 11909 | <filename>pymbolic/mapper/coefficient.py
__copyright__ = "Copyright (C) 2013 <NAME>"
__license__ = """
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 limita... | <filename>pymbolic/mapper/coefficient.py
__copyright__ = "Copyright (C) 2013 <NAME>"
__license__ = """
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 limita... | en | 0.773649 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the ... | 1.964674 | 2 |
day_06/balancer.py | anglerud/advent_of_code_2017 | 3 | 11910 | #!/usr/bin/env python
# coding: utf-8
""" """
import typing as t
import attr
import click
@attr.s(frozen=True)
class Memory(object):
banks: t.Tuple[int, ...] = attr.ib()
def balance(self) -> 'Memory':
mem = list(self.banks)
num_banks = len(self.banks)
# Find the amount of blocks to ... | #!/usr/bin/env python
# coding: utf-8
""" """
import typing as t
import attr
import click
@attr.s(frozen=True)
class Memory(object):
banks: t.Tuple[int, ...] = attr.ib()
def balance(self) -> 'Memory':
mem = list(self.banks)
num_banks = len(self.banks)
# Find the amount of blocks to ... | en | 0.910485 | #!/usr/bin/env python # coding: utf-8 # Find the amount of blocks to balance - remove them from that bank. # Rebalance # Advance the pointer. Find how many steps until we detect a loop. Balancing memory like they were spinning tops. Entrypoint. | 3.616105 | 4 |
python-while/exercise4.py | crobert7/Py-Basics | 0 | 11911 | word = input('Type a word: ')
while word != 'chupacabra':
word = input('Type a word: ')
if word == 'chupacabra':
print('You are out of the loop')
break | word = input('Type a word: ')
while word != 'chupacabra':
word = input('Type a word: ')
if word == 'chupacabra':
print('You are out of the loop')
break | none | 1 | 4.16357 | 4 | |
pw_build/selects.bzl | mspang/pigweed | 0 | 11912 | # Copyright 2021 The Pigweed Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | # Copyright 2021 The Pigweed Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | en | 0.774691 | # Copyright 2021 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ... | 1.472605 | 1 |
subscriptions/models.py | emil-magnusson/py-on-api | 0 | 11913 | <gh_stars>0
# subscriptions/models.py
import uuid
from django.db import models
from accesses.models import Accesses, Services
class OperationalState(models.Model):
operationalState = models.CharField(primary_key=True, max_length=50)
def __str__(self):
return self.operationalState
class Subscription... | # subscriptions/models.py
import uuid
from django.db import models
from accesses.models import Accesses, Services
class OperationalState(models.Model):
operationalState = models.CharField(primary_key=True, max_length=50)
def __str__(self):
return self.operationalState
class Subscriptions(models.Mod... | en | 0.389853 | # subscriptions/models.py #option82 = models.OneToOneField(Option82, on_delete=models.PROTECT) ##dhcpIdentifier ##characteristics | 2.070807 | 2 |
leboncrevard/job.py | mclbn/leboncrevard | 5 | 11914 | <reponame>mclbn/leboncrevard
import smtplib
import time
from email.mime.text import MIMEText
from leboncrevard import scrapper, config
class LbcJob:
def __init__(self, name, url, interval, recipients):
self.name = name
self.url = url
self.scrapper = scrapper.LbcScrapper(url)
self.... | import smtplib
import time
from email.mime.text import MIMEText
from leboncrevard import scrapper, config
class LbcJob:
def __init__(self, name, url, interval, recipients):
self.name = name
self.url = url
self.scrapper = scrapper.LbcScrapper(url)
self.interval = interval
s... | en | 0.526614 | # Ignoring interval and recipients for now # if self.interval != other.interval: # return False # if self.recipients != other.recipients: # return False | 2.503278 | 3 |
tsl/data/datamodule/splitters.py | TorchSpatiotemporal/tsl | 4 | 11915 | <reponame>TorchSpatiotemporal/tsl<gh_stars>1-10
import functools
from copy import deepcopy
from datetime import datetime
from typing import Mapping, Callable, Union, Tuple, Optional
import numpy as np
from tsl.utils.python_utils import ensure_list
from ..spatiotemporal_dataset import SpatioTemporalDataset
from ..util... | import functools
from copy import deepcopy
from datetime import datetime
from typing import Mapping, Callable, Union, Tuple, Optional
import numpy as np
from tsl.utils.python_utils import ensure_list
from ..spatiotemporal_dataset import SpatioTemporalDataset
from ..utils import SynchMode
__all__ = [
'Splitter',
... | en | 0.872573 | Base class for splitter module. # track `fit` calls A decorator to track fit calls. When ``splitter.fit(...)`` is called, :obj:`splitter.fitted` is set to :obj:`True`. Args: obj: Object whose function will be tracked. fn: Function that will be wrapped. Returns:... | 2.17524 | 2 |
demo.py | bringBackm/SSD | 0 | 11916 | import glob
import os
import torch
from PIL import Image
from tqdm import tqdm
from ssd.config import cfg
from ssd.data.datasets import COCODataset, VOCDataset
from ssd.modeling.predictor import Predictor
from ssd.modeling.vgg_ssd import build_ssd_model
import argparse
import numpy as np
from ssd.utils.viz import dra... | import glob
import os
import torch
from PIL import Image
from tqdm import tqdm
from ssd.config import cfg
from ssd.data.datasets import COCODataset, VOCDataset
from ssd.modeling.predictor import Predictor
from ssd.modeling.vgg_ssd import build_ssd_model
import argparse
import numpy as np
from ssd.utils.viz import dra... | en | 0.33825 | #with open(args.config_file, "r") as cf: # config_str = "\n" + cf.read() # print(config_str) #print("Running with config:\n{}".format(cfg)) | 2.334082 | 2 |
quiz/bot/storage/shelter.py | shubham-king/guess-the-melody | 4 | 11917 | <filename>quiz/bot/storage/shelter.py
from shelve import DbfilenameShelf, open
from typing import Type
from quiz.config import Config
from quiz.types import ContextManager, DictAccess
class Shelter(ContextManager, DictAccess):
"""Interface for bot shelter."""
def __init__(self, config: Type[Config]) -> None:... | <filename>quiz/bot/storage/shelter.py
from shelve import DbfilenameShelf, open
from typing import Type
from quiz.config import Config
from quiz.types import ContextManager, DictAccess
class Shelter(ContextManager, DictAccess):
"""Interface for bot shelter."""
def __init__(self, config: Type[Config]) -> None:... | en | 0.516118 | Interface for bot shelter. | 2.733153 | 3 |
src/applications/task310/apps.py | SergeyNazarovSam/SergeyPythonfirst | 2 | 11918 | <gh_stars>1-10
from django.apps import AppConfig
class Task310Config(AppConfig):
label = "task310"
name = f"applications.{label}"
| from django.apps import AppConfig
class Task310Config(AppConfig):
label = "task310"
name = f"applications.{label}" | none | 1 | 1.253314 | 1 | |
scripts/data_creation_v3.py | deepchecks/url_classification_dl | 3 | 11919 | <filename>scripts/data_creation_v3.py
import whois
from datetime import datetime, timezone
import math
import pandas as pd
import numpy as np
from pyquery import PyQuery
from requests import get
class UrlFeaturizer(object):
def __init__(self, url):
self.url = url
self.domain = url.split('//')[-1].s... | <filename>scripts/data_creation_v3.py
import whois
from datetime import datetime, timezone
import math
import pandas as pd
import numpy as np
from pyquery import PyQuery
from requests import get
class UrlFeaturizer(object):
def __init__(self, url):
self.url = url
self.domain = url.split('//')[-1].s... | ja | 0.152182 | ## URL string Features ## URL domain features ## URL Page Features | 2.768415 | 3 |
rgnn_at_scale/models/gat.py | sigeisler/robustness_of_gnns_at_scale | 11 | 11920 | from typing import Any, Dict, Tuple
import torch
from torch_geometric.nn import GATConv
from torch_sparse import SparseTensor, set_diag
from rgnn_at_scale.aggregation import ROBUST_MEANS
from rgnn_at_scale.models.gcn import GCN
class RGATConv(GATConv):
"""Extension of Pytorch Geometric's `GCNConv` to execute a... | from typing import Any, Dict, Tuple
import torch
from torch_geometric.nn import GATConv
from torch_sparse import SparseTensor, set_diag
from rgnn_at_scale.aggregation import ROBUST_MEANS
from rgnn_at_scale.models.gcn import GCN
class RGATConv(GATConv):
"""Extension of Pytorch Geometric's `GCNConv` to execute a... | en | 0.630943 | Extension of Pytorch Geometric's `GCNConv` to execute a robust aggregation function: - soft_k_medoid - soft_medoid (not scalable) - k_medoid - medoid (not scalable) - dimmedian Parameters ---------- mean : str, optional The desired mean (see above for the options), by default 's... | 2.014926 | 2 |
code/renderer/randomize/material.py | jonathangranskog/shading-scene-representations | 21 | 11921 | <gh_stars>10-100
import numpy as np
import pyrr
import os
class Material():
def __init__(self, color=np.ones(3, dtype=np.float32), emission=np.zeros(3, dtype=np.float32), roughness=1.0, ior=15.0, id=0, texture=None, texture_frequency=np.array([1.0, 1.0])):
self.color = color
self.emission = emissio... | import numpy as np
import pyrr
import os
class Material():
def __init__(self, color=np.ones(3, dtype=np.float32), emission=np.zeros(3, dtype=np.float32), roughness=1.0, ior=15.0, id=0, texture=None, texture_frequency=np.array([1.0, 1.0])):
self.color = color
self.emission = emission
self.ro... | none | 1 | 2.746431 | 3 | |
frappe/core/doctype/sms_settings/sms_settings.py | ektai/erp2Dodock | 0 | 11922 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, throw, msgprint
from frappe.utils import nowdate
from frappe.model.document import Documen... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, throw, msgprint
from frappe.utils import nowdate
from frappe.model.document import Documen... | en | 0.601323 | # -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # remove invalid character select mobile_no, phone from tabContact where name=%s and exists( select name from `tabDynamic Link` where link_doctype=%s and link... | 2.293251 | 2 |
blog/migrations/0041_auto_20190504_0855.py | akindele214/181hub_2 | 1 | 11923 | # Generated by Django 2.1.5 on 2019-05-04 07:55
import blog.formatChecker
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0040_auto_20190504_0840'),
]
operations = [
migrations.AlterField(
model_name='videos',
... | # Generated by Django 2.1.5 on 2019-05-04 07:55
import blog.formatChecker
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0040_auto_20190504_0840'),
]
operations = [
migrations.AlterField(
model_name='videos',
... | en | 0.675631 | # Generated by Django 2.1.5 on 2019-05-04 07:55 | 1.678535 | 2 |
tardis/model/tests/test_csvy_model.py | Youssef15015/tardis | 0 | 11924 | <filename>tardis/model/tests/test_csvy_model.py
import numpy as np
import numpy.testing as npt
import tardis
import os
from astropy import units as u
from tardis.io.config_reader import Configuration
from tardis.model import Radial1DModel
import pytest
DATA_PATH = os.path.join(tardis.__path__[0],'model','tests','data'... | <filename>tardis/model/tests/test_csvy_model.py
import numpy as np
import numpy.testing as npt
import tardis
import os
from astropy import units as u
from tardis.io.config_reader import Configuration
from tardis.model import Radial1DModel
import pytest
DATA_PATH = os.path.join(tardis.__path__[0],'model','tests','data'... | none | 1 | 2.129861 | 2 | |
wepppy/taudem/topaz_emulator.py | hwbeeson/wepppy | 0 | 11925 | <gh_stars>0
from typing import List
import os
import json
from os.path import join as _join
from os.path import exists as _exists
import math
from osgeo import gdal, osr
import numpy as np
from scipy.ndimage import label
from subprocess import Popen, PIPE
from pprint import pprint
from wepppy.all_your_base.geo imp... | from typing import List
import os
import json
from os.path import join as _join
from os.path import exists as _exists
import math
from osgeo import gdal, osr
import numpy as np
from scipy.ndimage import label
from subprocess import Popen, PIPE
from pprint import pprint
from wepppy.all_your_base.geo import read_tif... | en | 0.817913 | # subwta # subwta # subcatchments # bound # bound # net # listed bottom to top # need to identify unique pixels # the pixels are listed bottom to top we want them top to bottom as if we walked downt the flowpath # todo: don't think head and tail are being used any where, but these # are inconsistent with case whe... | 2.056532 | 2 |
PyRSM/utils.py | chdahlqvist/RSMmap | 3 | 11926 | <reponame>chdahlqvist/RSMmap
"""
Set of functions used by the PyRSM class to compute detection maps and optimize the parameters
of the RSM algorithm and PSF-subtraction techniques via the auto-RSM and auto-S/N frameworks
"""
__author__ = '<NAME>'
from scipy.interpolate import Rbf
import pandas as pd
import numpy.linal... | """
Set of functions used by the PyRSM class to compute detection maps and optimize the parameters
of the RSM algorithm and PSF-subtraction techniques via the auto-RSM and auto-S/N frameworks
"""
__author__ = '<NAME>'
from scipy.interpolate import Rbf
import pandas as pd
import numpy.linalg as la
from vip_hci.var impo... | en | 0.773522 | Set of functions used by the PyRSM class to compute detection maps and optimize the parameters of the RSM algorithm and PSF-subtraction techniques via the auto-RSM and auto-S/N frameworks Function used to rescale the frames when relying on ADI+SDI before the computation the reference PSF (step='ini') and rescale an... | 1.979752 | 2 |
src/custom_dataset.py | devJWSong/transformer-multiturn-dialogue-pytorch | 11 | 11927 | <reponame>devJWSong/transformer-multiturn-dialogue-pytorch
from torch.utils.data import Dataset
from tqdm import tqdm
import torch
import pickle
import json
class CustomDataset(Dataset):
def __init__(self, args, tokenizer, data_type):
assert data_type in ["train", "valid", "test"]
print(... | from torch.utils.data import Dataset
from tqdm import tqdm
import torch
import pickle
import json
class CustomDataset(Dataset):
def __init__(self, args, tokenizer, data_type):
assert data_type in ["train", "valid", "test"]
print(f"Loading {data_type} data...")
with open(f"{args.t... | en | 0.803391 | # (N, T, S_L) # (N) # (N, T_L) # The system's persona will be handled as extra histories without a speacker token. (or maybe empty...) # Speaker 1: User # Speacker 2: System # Padding # (B, T_L) | 2.47872 | 2 |
research/codec/codec_example.py | FXTD-ODYSSEY/QBinder | 13 | 11928 | # -*- coding: future_fstrings -*-
import codecs
import pdb
import string
# NOTE https://stackoverflow.com/questions/38777818/how-do-i-properly-create-custom-text-codecs
# prepare map from numbers to letters
_encode_table = {str(number): bytes(letter) for number, letter in enumerate(string.ascii_lowercase)}
# prepar... | # -*- coding: future_fstrings -*-
import codecs
import pdb
import string
# NOTE https://stackoverflow.com/questions/38777818/how-do-i-properly-create-custom-text-codecs
# prepare map from numbers to letters
_encode_table = {str(number): bytes(letter) for number, letter in enumerate(string.ascii_lowercase)}
# prepar... | en | 0.553812 | # -*- coding: future_fstrings -*- # NOTE https://stackoverflow.com/questions/38777818/how-do-i-properly-create-custom-text-codecs # prepare map from numbers to letters # prepare inverse map # example encoder that converts ints to letters # see https://docs.python.org/3/library/codecs.html#codecs.Codec.encode # example ... | 3.414511 | 3 |
benchmark_python_lkml.py | Ladvien/rust_lookml_parser | 0 | 11929 | import lkml
from time import time_ns
from rich import print
FILE_PATH = "/Users/ladvien/rusty_looker/src/resources/test.lkml"
with open(FILE_PATH, "r") as f:
lookml = f.read()
startTime = time_ns() // 1_000_000
result = lkml.load(lookml)
print(result)
executionTime = (time_ns() // 1_000_000) - startTime
print('... | import lkml
from time import time_ns
from rich import print
FILE_PATH = "/Users/ladvien/rusty_looker/src/resources/test.lkml"
with open(FILE_PATH, "r") as f:
lookml = f.read()
startTime = time_ns() // 1_000_000
result = lkml.load(lookml)
print(result)
executionTime = (time_ns() // 1_000_000) - startTime
print('... | none | 1 | 2.455943 | 2 | |
Linear_Regression.py | svdeepak99/TSA-Twitter_Sentiment_Analysis | 0 | 11930 | <filename>Linear_Regression.py
from keras.models import Sequential, load_model
from keras.layers import Dense
import csv
import numpy as np
import os
LOAD_MODEL = False
with open("Linear_Regression/Normalized_Attributes.csv", "r", newline='') as fp:
reader = csv.reader(fp)
headings = next(reader)
... | <filename>Linear_Regression.py
from keras.models import Sequential, load_model
from keras.layers import Dense
import csv
import numpy as np
import os
LOAD_MODEL = False
with open("Linear_Regression/Normalized_Attributes.csv", "r", newline='') as fp:
reader = csv.reader(fp)
headings = next(reader)
... | none | 1 | 2.891523 | 3 | |
UserCode/bressler/multibubblescintillationcheck.py | cericdahl/SBCcode | 4 | 11931 | <filename>UserCode/bressler/multibubblescintillationcheck.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 19:33:02 2021
@author: bressler
"""
import SBCcode as sbc
import numpy as np
import pulse_integrator as pi
import gc
def check_multibub_scintillation(run, event, at0, PMTgain, PMTwind... | <filename>UserCode/bressler/multibubblescintillationcheck.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 19:33:02 2021
@author: bressler
"""
import SBCcode as sbc
import numpy as np
import pulse_integrator as pi
import gc
def check_multibub_scintillation(run, event, at0, PMTgain, PMTwind... | en | 0.695019 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Tue Mar 2 19:33:02 2021 @author: bressler #print(str(len(LED_on)/len(fdt))) # to match the indexing of the pre-made code I had 1??? # loop through every PMT trace for the event # if the trace time is within 500 microsec before acoustic t0 lastCamOff = 0 ... | 2.213482 | 2 |
app/core/models.py | echosisdev/openmrs-disa-sync | 0 | 11932 | from django.db import models
from django.db.models.signals import pre_save, post_save
from core.utils.constants import Constants
from core.utils.data_convertion import DataConversion
class ExcelFile(models.Model):
file_name = models.FileField(upload_to='uploads')
date_created = models.DateTimeField(auto_now_... | from django.db import models
from django.db.models.signals import pre_save, post_save
from core.utils.constants import Constants
from core.utils.data_convertion import DataConversion
class ExcelFile(models.Model):
file_name = models.FileField(upload_to='uploads')
date_created = models.DateTimeField(auto_now_... | en | 0.234062 | #person_id = models.IntegerField() # def insert_formatted_nid(sender, instance, created, *args, **kwargs): # if created: # instance.formatted_nid = DataConversion.format_nid(instance.nid) # print(instance.formatted_nid) # post_save.connect(insert_formatted_nid, sender=ViralLoad) | 2.044812 | 2 |
ceibacli/job_schedulers/slurm.py | cffbots/ceiba-cli | 2 | 11933 | <gh_stars>1-10
"""Interface to the `SLURM job scheduler <https://slurm.schedmd.com/documentation.html>`_
.. autofunction:: create_slurm_script
"""
from pathlib import Path
from typing import Any, Dict, List
from ..utils import Options
def create_slurm_script(opts: Options, jobs: List[Dict[str, Any]], jobs_metadata... | """Interface to the `SLURM job scheduler <https://slurm.schedmd.com/documentation.html>`_
.. autofunction:: create_slurm_script
"""
from pathlib import Path
from typing import Any, Dict, List
from ..utils import Options
def create_slurm_script(opts: Options, jobs: List[Dict[str, Any]], jobs_metadata: List[Options]... | en | 0.423716 | Interface to the `SLURM job scheduler <https://slurm.schedmd.com/documentation.html>`_ .. autofunction:: create_slurm_script Create a script to run the workflow using the SLURM job schedule. # Get SLURM configuration # Use the configuration provided by the user # Append command to run the workflow Create a SLURM scrip... | 2.717438 | 3 |
thumbor/url.py | wking/thumbor | 0 | 11934 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
import re
from urllib import quote
class Url(object):
unsafe_or_hash = r'(?:(?... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
import re
from urllib import quote
class Url(object):
unsafe_or_hash = r'(?:(?... | en | 0.62514 | #!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com <EMAIL> # NOQA | 2.2319 | 2 |
Projects/herdimmunity/Person.py | Tech-at-DU/ACS-1111.1-Object-Oriented-Programming | 0 | 11935 | import random
from Virus import Virus
class Person:
''' The simulation will contain people who will make up a population.'''
def __init__(self, is_vaccinated, infection=None):
''' We start out with is_alive = True
All other values will be set by the simulation through the parameters when
... | import random
from Virus import Virus
class Person:
''' The simulation will contain people who will make up a population.'''
def __init__(self, is_vaccinated, infection=None):
''' We start out with is_alive = True
All other values will be set by the simulation through the parameters when
... | en | 0.882093 | The simulation will contain people who will make up a population. We start out with is_alive = True All other values will be set by the simulation through the parameters when it instantiates each Person object. #boolean #boolean #virus object Generate a random number between 0.0 and 1.0 and compare to ... | 3.839336 | 4 |
Cursos/Alura/Python3_Avancando_na_orientacao_a_objetos/models_playlist3.py | ramonvaleriano/python- | 0 | 11936 | <reponame>ramonvaleriano/python-<filename>Cursos/Alura/Python3_Avancando_na_orientacao_a_objetos/models_playlist3.py
class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def... | class Programa:
def __init__(self, nome, ano):
self._nome = nome.title()
self.ano = ano
self._likes = 0
@property
def likes(self):
return self._likes
def dar_like(self):
self._likes += 1
@property
def nome(self):
return self._nome
@nome.set... | none | 1 | 3.708262 | 4 | |
blackjack/game.py | cuiqui/blackjack | 0 | 11937 | import constants as c
from deck import Deck
from player import Human, RandomAI
class Game:
def __init__(self):
self.deck = None
self.players = None
self.scores = None
self.rounds_left = None
self.game_over = False
def new(self):
self.game_over = F... | import constants as c
from deck import Deck
from player import Human, RandomAI
class Game:
def __init__(self):
self.deck = None
self.players = None
self.scores = None
self.rounds_left = None
self.game_over = False
def new(self):
self.game_over = F... | en | 0.97079 | # while there are still rounds left # set round scores to empty # for each player, do a whole turn, which can involve # multiple actions, i.e., two or more "hits" # turn is not over until we receive a score, # whether it's 0, which means it overstepped # or 0 < x <= 21 # do a turn until we get a score, if we don't # ha... | 3.31572 | 3 |
numba/tests/__init__.py | mawanda-jun/numba | 1 | 11938 | <reponame>mawanda-jun/numba
from numba import unittest_support as unittest
import gc
from os.path import dirname, join
import multiprocessing
import sys
import time
import warnings
from unittest.suite import TestSuite
from numba.testing import load_testsuite
from numba.testing import ddt # for backward compatibility
... | from numba import unittest_support as unittest
import gc
from os.path import dirname, join
import multiprocessing
import sys
import time
import warnings
from unittest.suite import TestSuite
from numba.testing import load_testsuite
from numba.testing import ddt # for backward compatibility
try:
import faulthandl... | en | 0.95249 | # for backward compatibility # May fail in IPython Notebook with UnsupportedOperation # Numba CUDA tests are located in a separate directory: # Numba ROC tests are located in a separate directory | 2.180245 | 2 |
src/clustar/fit.py | clustar/Clustar | 4 | 11939 | """
Clustar module for fitting-related methods.
This module is designed for the 'ClustarData' object. All listed methods take
an input parameter of a 'ClustarData' object and return a 'ClustarData' object
after processing the method. As a result, all changes are localized within the
'ClustarData' object.
Visit <https... | """
Clustar module for fitting-related methods.
This module is designed for the 'ClustarData' object. All listed methods take
an input parameter of a 'ClustarData' object and return a 'ClustarData' object
after processing the method. As a result, all changes are localized within the
'ClustarData' object.
Visit <https... | en | 0.550448 | Clustar module for fitting-related methods. This module is designed for the 'ClustarData' object. All listed methods take an input parameter of a 'ClustarData' object and return a 'ClustarData' object after processing the method. As a result, all changes are localized within the 'ClustarData' object. Visit <https://c... | 2.648988 | 3 |
tests/wizard/namedwizardtests/urls.py | felixxm/django-formtools | 0 | 11940 | <filename>tests/wizard/namedwizardtests/urls.py
from django.conf.urls import url
from .forms import (
CookieContactWizard, Page1, Page2, Page3, Page4, SessionContactWizard,
)
def get_named_session_wizard():
return SessionContactWizard.as_view(
[('form1', Page1), ('form2', Page2), ('form3', Page3), ('... | <filename>tests/wizard/namedwizardtests/urls.py
from django.conf.urls import url
from .forms import (
CookieContactWizard, Page1, Page2, Page3, Page4, SessionContactWizard,
)
def get_named_session_wizard():
return SessionContactWizard.as_view(
[('form1', Page1), ('form2', Page2), ('form3', Page3), ('... | none | 1 | 2.093147 | 2 | |
setup.py | ajayp10/derive_event_pm4py | 0 | 11941 | <gh_stars>0
import pathlib
from setuptools import setup
CURRENT_PATH = pathlib.Path(__file__).parent
README = (CURRENT_PATH/"README.md").read_text()
setup(
name="derive_event_pm4py",
version="1.0.1",
description="It derives new events based on rules provided as inputs.",
long_description=README,
... | import pathlib
from setuptools import setup
CURRENT_PATH = pathlib.Path(__file__).parent
README = (CURRENT_PATH/"README.md").read_text()
setup(
name="derive_event_pm4py",
version="1.0.1",
description="It derives new events based on rules provided as inputs.",
long_description=README,
long_descrip... | none | 1 | 1.53169 | 2 | |
tests/service/ai/test_not_killing_itself_ai.py | jonashellmann/informaticup21-team-chillow | 3 | 11942 | import unittest
from datetime import datetime, timezone
from typing import List
from chillow.service.ai.not_killing_itself_ai import NotKillingItselfAI
from chillow.model.action import Action
from chillow.model.cell import Cell
from chillow.model.direction import Direction
from chillow.model.game import Game
from chil... | import unittest
from datetime import datetime, timezone
from typing import List
from chillow.service.ai.not_killing_itself_ai import NotKillingItselfAI
from chillow.model.action import Action
from chillow.model.cell import Cell
from chillow.model.direction import Direction
from chillow.model.game import Game
from chil... | none | 1 | 2.999101 | 3 | |
setup.py | meisanggou/ldapuser | 0 | 11943 | <reponame>meisanggou/ldapuser
#! /usr/bin/env python
# coding: utf-8
# __author__ = 'meisanggou'
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
if sys.version_info <= (2, 7):
sys.stderr.write("ERROR: ldap-user requires Python Version 2.7 or above.\n")
... | #! /usr/bin/env python
# coding: utf-8
# __author__ = 'meisanggou'
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
if sys.version_info <= (2, 7):
sys.stderr.write("ERROR: ldap-user requires Python Version 2.7 or above.\n")
sys.stderr.write("Your Pyt... | en | 0.328095 | #! /usr/bin/env python # coding: utf-8 # __author__ = 'meisanggou' use ldap verify user | 1.80881 | 2 |
tests/test_infection.py | chinapnr/covid-19-data | 3 | 11944 | import json
import pytest
@pytest.mark.usefixtures('client', 'headers')
class TestInfection:
def test_infection_region_tc01(self, client, headers):
# db has data BETWEEN 2020-03-22 2020-03-24
region = 'China'
payload = {
'region': region,
'start_date': '2020-03-22... | import json
import pytest
@pytest.mark.usefixtures('client', 'headers')
class TestInfection:
def test_infection_region_tc01(self, client, headers):
# db has data BETWEEN 2020-03-22 2020-03-24
region = 'China'
payload = {
'region': region,
'start_date': '2020-03-22... | en | 0.439793 | # db has data BETWEEN 2020-03-22 2020-03-24 # db has no data BETWEEN 2020-03-25 2020-03-26 # db has data BETWEEN 2020-03-22 2020-03-24 # look up detail # db has data BETWEEN 2020-03-22 2020-03-24 # look up detail # 'end_date': '2020-03-24', # db has data BETWEEN 2020-03-22 2020-03-24 # look up detail # 'end_date': '202... | 2.310598 | 2 |
tests/test_util_owsutil.py | TimFranken/pydov | 0 | 11945 | """Module grouping tests for the pydov.util.owsutil module."""
import copy
import re
import pytest
from numpy.compat import unicode
from owslib.etree import etree
from owslib.fes import (
PropertyIsEqualTo,
FilterRequest,
)
from owslib.iso import MD_Metadata
from owslib.util import nspath_eval
from pydov.util... | """Module grouping tests for the pydov.util.owsutil module."""
import copy
import re
import pytest
from numpy.compat import unicode
from owslib.etree import etree
from owslib.fes import (
PropertyIsEqualTo,
FilterRequest,
)
from owslib.iso import MD_Metadata
from owslib.util import nspath_eval
from pydov.util... | en | 0.519051 | Module grouping tests for the pydov.util.owsutil module. Clean the given XML string of namespace definition, namespace prefixes and syntactical but otherwise meaningless differences. Parameters ---------- xml : str String representation of XML document. Returns ------- str ... | 2.420217 | 2 |
manage.py | jessekl/twiliochallenge | 0 | 11946 | # -*- coding: utf-8 -*-
"""
manage
~~~~~~
Flask-Script Manager
"""
import os
from flask.ext.script import Manager
from flask.ext.migrate import MigrateCommand
from fbone import create_app
from fbone.extensions import db
from fbone.utils import PROJECT_PATH, MALE
from fbone.modules.user import User, ADMI... | # -*- coding: utf-8 -*-
"""
manage
~~~~~~
Flask-Script Manager
"""
import os
from flask.ext.script import Manager
from flask.ext.migrate import MigrateCommand
from fbone import create_app
from fbone.extensions import db
from fbone.utils import PROJECT_PATH, MALE
from fbone.modules.user import User, ADMI... | en | 0.676292 | # -*- coding: utf-8 -*- manage ~~~~~~ Flask-Script Manager Init/reset database. Run the tests. | 2.185419 | 2 |
llvmsqlite_util/benchmarking/micro/aggregate.py | KowalskiThomas/LLVMSQLite | 0 | 11947 | <reponame>KowalskiThomas/LLVMSQLite
import os
sql_files = [x for x in os.listdir(".") if x.endswith("sql")]
sql_files = list(sorted(sql_files, key = lambda x : int(x.split('.')[0])))
result = ""
for i, f in enumerate(sql_files):
i = i + 1
i = f.replace(".sql", "")
with open(f) as sql:
result += f"... | import os
sql_files = [x for x in os.listdir(".") if x.endswith("sql")]
sql_files = list(sorted(sql_files, key = lambda x : int(x.split('.')[0])))
result = ""
for i, f in enumerate(sql_files):
i = i + 1
i = f.replace(".sql", "")
with open(f) as sql:
result += f"--- Query {i}\n"
result += s... | none | 1 | 2.730538 | 3 | |
demos/crane/main.py | Starli8ht/KivyMD | 0 | 11948 | """
MDCrane demo
=============
.. seealso::
`Material Design spec,
Crane <https://material.io/design/material-studies/crane.html#>`
Crane is a travel app that helps users find and book travel, lodging, and
restaurant options that match their input preferences.
"""
import os
import sys
from pathlib i... | """
MDCrane demo
=============
.. seealso::
`Material Design spec,
Crane <https://material.io/design/material-studies/crane.html#>`
Crane is a travel app that helps users find and book travel, lodging, and
restaurant options that match their input preferences.
"""
import os
import sys
from pathlib i... | en | 0.646282 | MDCrane demo ============= .. seealso:: `Material Design spec, Crane <https://material.io/design/material-studies/crane.html#>` Crane is a travel app that helps users find and book travel, lodging, and restaurant options that match their input preferences. # bundle mode with PyInstaller #:import Fade... | 2.277551 | 2 |
tasks/lgutil/graph_net.py | HimmelStein/lg-flask | 0 | 11949 | <gh_stars>0
# -*- coding: utf-8 -*-
from nltk.parse import DependencyGraph
from collections import defaultdict
import random
import sys
import copy
from json import dumps
from pprint import pprint
try:
from .lg_graph import LgGraph
except:
sys.path.append("/Users/tdong/git/lg-flask/tasks/lgutil")
from .lg_... | # -*- coding: utf-8 -*-
from nltk.parse import DependencyGraph
from collections import defaultdict
import random
import sys
import copy
from json import dumps
from pprint import pprint
try:
from .lg_graph import LgGraph
except:
sys.path.append("/Users/tdong/git/lg-flask/tasks/lgutil")
from .lg_graph import... | en | 0.436548 | # -*- coding: utf-8 -*- {'address': 1, 'ctag': 'PRO', 'deps': defaultdict(list, {'remove-link-verb':[..]}), 'feats': '3|Sg|Masc|Nom', 'head': 2, 'lemma': 'er', --> 'lemma' : <sentence of the ldg> 'tag': 'PPER', 'word': 'Er' --> 'ldg': <graph> } ta... | 2.106483 | 2 |
utils/transformations/char_level/char_dces_substitute.py | Yzx835/AISafety | 0 | 11950 | # !/usr/bin/env python
# coding=UTF-8
"""
@Author: <NAME>
@LastEditors: <NAME>
@Description:
@Date: 2021-09-24
@LastEditTime: 2022-04-17
源自OpenAttack的DCESSubstitute
"""
import random
from typing import NoReturn, List, Any, Optional
import numpy as np
from utils.transformations.base import CharSubstitute
from utils... | # !/usr/bin/env python
# coding=UTF-8
"""
@Author: <NAME>
@LastEditors: <NAME>
@Description:
@Date: 2021-09-24
@LastEditTime: 2022-04-17
源自OpenAttack的DCESSubstitute
"""
import random
from typing import NoReturn, List, Any, Optional
import numpy as np
from utils.transformations.base import CharSubstitute
from utils... | en | 0.353148 | # !/usr/bin/env python # coding=UTF-8 @Author: <NAME> @LastEditors: <NAME> @Description: @Date: 2021-09-24 @LastEditTime: 2022-04-17 源自OpenAttack的DCESSubstitute | 2.598478 | 3 |
piptools/repositories/base.py | LaudateCorpus1/pip-tools | 2 | 11951 | <filename>piptools/repositories/base.py
import optparse
from abc import ABCMeta, abstractmethod
from contextlib import contextmanager
from typing import Iterator, Optional, Set
from pip._internal.index.package_finder import PackageFinder
from pip._internal.models.index import PyPI
from pip._internal.network.session im... | <filename>piptools/repositories/base.py
import optparse
from abc import ABCMeta, abstractmethod
from contextlib import contextmanager
from typing import Iterator, Optional, Set
from pip._internal.index.package_finder import PackageFinder
from pip._internal.models.index import PyPI
from pip._internal.network.session im... | en | 0.795992 | Should clear any caches used by the implementation. Returns a pinned InstallRequirement object that indicates the best match for the given InstallRequirement according to the external repository. Given a pinned, URL, or editable InstallRequirement, returns a set of dependencies (also InstallRequirements... | 2.105254 | 2 |
tfx/orchestration/portable/execution_publish_utils.py | johnPertoft/tfx | 0 | 11952 | # Copyright 2020 Google LLC. All Rights Reserved.
#
# 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 a... | # Copyright 2020 Google LLC. All Rights Reserved.
#
# 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 a... | en | 0.880361 | # Copyright 2020 Google LLC. All Rights Reserved. # # 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 a... | 1.695115 | 2 |
src/dctm/datasets.py | spotify-research/dctm | 11 | 11953 | <reponame>spotify-research/dctm<filename>src/dctm/datasets.py<gh_stars>10-100
#
# Copyright 2020 Spotify AB
# 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/license... | #
# Copyright 2020 Spotify AB
# 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, s... | en | 0.700681 | # # Copyright 2020 Spotify AB # 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, s... | 2.670359 | 3 |
torchreid/optim/sam.py | opencv/deep-person-reid | 1 | 11954 | # Copyright 2020 Google Research
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
'''
Imported from: https://github.com/google-research/sam
'''
import torch
class SAM(torch.optim.Optimizer):
def __init__(self, params, base_optimizer, rho... | # Copyright 2020 Google Research
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
'''
Imported from: https://github.com/google-research/sam
'''
import torch
class SAM(torch.optim.Optimizer):
def __init__(self, params, base_optimizer, rho... | en | 0.754462 | # Copyright 2020 Google Research # SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2020-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # Imported from: https://github.com/google-research/sam # climb to the local maximum "w + e(w)" # get back to "w" from "w + e(w)" # do the actual "sharpness-aware" u... | 1.970757 | 2 |
src/konfiger_stream.py | konfiger/konfiger-python | 4 | 11955 | <reponame>konfiger/konfiger-python
"""
The MIT License
Copyright 2020 <NAME> <<EMAIL>>.
"""
import os.path
from .konfiger_util import type_of, is_string, is_char, is_bool, escape_string, un_escape_string
def file_stream(file_path, delimiter = '=', separator = '\n', err_tolerance = False):
return Konfiger... | """
The MIT License
Copyright 2020 <NAME> <<EMAIL>>.
"""
import os.path
from .konfiger_util import type_of, is_string, is_char, is_bool, escape_string, un_escape_string
def file_stream(file_path, delimiter = '=', separator = '\n', err_tolerance = False):
return KonfigerStream(file_path, delimiter, separat... | en | 0.214728 | The MIT License Copyright 2020 <NAME> <<EMAIL>>. | 2.788142 | 3 |
matematik.py | Drummersbrother/math_for_school | 0 | 11956 | <filename>matematik.py
import math
import numpy as np
import collections
import scipy.stats as sst
import matplotlib.pyplot as plt
def plot(*args, **kwargs):
plt.plot(*args, **kwargs)
plt.show()
def linregshow(x, y, col: str="r"):
linregresult = sst.linregress(list(zip(x, y)))
plot(x, y, col, x, [(val... | <filename>matematik.py
import math
import numpy as np
import collections
import scipy.stats as sst
import matplotlib.pyplot as plt
def plot(*args, **kwargs):
plt.plot(*args, **kwargs)
plt.show()
def linregshow(x, y, col: str="r"):
linregresult = sst.linregress(list(zip(x, y)))
plot(x, y, col, x, [(val... | en | 0.783544 | This is a decorator to specify that a function either takes iterable input in the form of an iterable or a list of passed arguments. If other arguments are needed, the function will need to use kwargs. This passes the list as the first argument. # We make generators into lists Returns the size of the range of v... | 3.713391 | 4 |
docly/ioutils/__init__.py | autosoft-dev/docly | 29 | 11957 | import os
from pathlib import Path
import requests
import shutil
import sys
from distutils.version import LooseVersion
import time
from tqdm import tqdm
from docly.parser import parser as py_parser
from docly.tokenizers import tokenize_code_string
from docly import __version__
# from c2nl.objects import Code
UPDATE_... | import os
from pathlib import Path
import requests
import shutil
import sys
from distutils.version import LooseVersion
import time
from tqdm import tqdm
from docly.parser import parser as py_parser
from docly.tokenizers import tokenize_code_string
from docly import __version__
# from c2nl.objects import Code
UPDATE_... | en | 0.687688 | # from c2nl.objects import Code # UPDATE_CHECK_URL = "http://127.0.0.1:5000/vercheck/check-version/" @param: url to download file @param: dst place to put the file " This function recursively yields all contents of a pathlib.Path object # print(py_toeknizer.tokenize_code_string(func_body)) # code.tokens = token... | 2.367734 | 2 |
java/version.bzl | symonk/selenium | 0 | 11958 | SE_VERSION = "4.2.1"
| SE_VERSION = "4.2.1"
| none | 1 | 0.968973 | 1 | |
scripts/preprocess_for_prediction.py | jmueller95/deepgrind | 0 | 11959 | <filename>scripts/preprocess_for_prediction.py
import pandas as pd
import utils
def check_msms_model_name(converter):
def wrapper(*args, **kwargs):
if kwargs['style'] not in ["pdeep", "prosit"]:
raise Exception("MSMS model must be 'pdeep' or 'prosit'")
converter(*args, **kwargs)
... | <filename>scripts/preprocess_for_prediction.py
import pandas as pd
import utils
def check_msms_model_name(converter):
def wrapper(*args, **kwargs):
if kwargs['style'] not in ["pdeep", "prosit"]:
raise Exception("MSMS model must be 'pdeep' or 'prosit'")
converter(*args, **kwargs)
... | en | 0.911812 | # The charge is one-hot encoded in the comet df, so we can resolve this into 1,2 or 3 by multiplying 1,2 and 3 # with the entries of Charge1, Charge2 and Charge3 # Parse the input file: # Determine if MSMS and RT prediction will be performed jointly or separately # If only one model was supplied, the prediction will be... | 2.575973 | 3 |
GettingStarted/gettingstarted.py | rohitp934/roadtoadatascientist | 0 | 11960 | #importing necessary modules
from sklearn.linear_model import Perceptron
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import numpy as np
# Data and labels
Xtrain = [[182, 80, 34], [176, 70, 33], [161, 60, 28], [154, 55, 27], [166, 63, 30], [189, 90, 36], [175, 63, 28], ... | #importing necessary modules
from sklearn.linear_model import Perceptron
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import numpy as np
# Data and labels
Xtrain = [[182, 80, 34], [176, 70, 33], [161, 60, 28], [154, 55, 27], [166, 63, 30], [189, 90, 36], [175, 63, 28], ... | en | 0.578686 | #importing necessary modules # Data and labels # initializing the ML models # Fitting the models # Testing using our input data # The best classifier out of the two models #argmax function assigns the index of the maximum value to the variable | 3.19627 | 3 |
libs/optimizers.py | bxtkezhan/AILabs | 0 | 11961 | <gh_stars>0
import numpy as np
class SGD:
def __init__(self, lr=0.01, momentum=0.0, decay=0.0, nesterov=False,
maximum=None, minimum=None):
self.lr = lr
self.momentum = momentum
self.decay = decay
self.nesterov = nesterov
self.idx = None
self.maximu... | import numpy as np
class SGD:
def __init__(self, lr=0.01, momentum=0.0, decay=0.0, nesterov=False,
maximum=None, minimum=None):
self.lr = lr
self.momentum = momentum
self.decay = decay
self.nesterov = nesterov
self.idx = None
self.maximum = maximum ... | none | 1 | 2.430618 | 2 | |
pennylane/transforms/qcut.py | therooler/pennylane | 0 | 11962 | # Copyright 2022 Xanadu Quantum Technologies 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 applicable law or a... | # Copyright 2022 Xanadu Quantum Technologies 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 applicable law or a... | en | 0.709884 | # Copyright 2022 Xanadu Quantum Technologies 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 applicable law or a... | 1.913765 | 2 |
tools/SDKTool/src/ui/dialog/progress_bar_dialog.py | Passer-D/GameAISDK | 1,210 | 11963 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright... | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright... | en | 0.93625 | # -*- coding: utf-8 -*- Tencent is pleased to support the open source community by making GameAISDK available. This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright (C)... | 2.016745 | 2 |
9/main.py | misterwilliam/advent-of-code | 0 | 11964 | <gh_stars>0
import itertools
import unittest
data = """Faerun to Norrath = 129
Faerun to Tristram = 58
Faerun to AlphaCentauri = 13
Faerun to Arbre = 24
Faerun to Snowdin = 60
Faerun to Tambi = 71
Faerun to Straylight = 67
Norrath to Tristram = 142
Norrath to AlphaCentauri = 15
Norrath to Arbre = 135
Norrath to Snowdi... | import itertools
import unittest
data = """Faerun to Norrath = 129
Faerun to Tristram = 58
Faerun to AlphaCentauri = 13
Faerun to Arbre = 24
Faerun to Snowdin = 60
Faerun to Tambi = 71
Faerun to Straylight = 67
Norrath to Tristram = 142
Norrath to AlphaCentauri = 15
Norrath to Arbre = 135
Norrath to Snowdin = 75
Norra... | en | 0.71259 | Faerun to Norrath = 129 Faerun to Tristram = 58 Faerun to AlphaCentauri = 13 Faerun to Arbre = 24 Faerun to Snowdin = 60 Faerun to Tambi = 71 Faerun to Straylight = 67 Norrath to Tristram = 142 Norrath to AlphaCentauri = 15 Norrath to Arbre = 135 Norrath to Snowdin = 75 Norrath to Tambi = 82 Norrath to Straylight = 54 ... | 2.95626 | 3 |
100-Exercicios/ex039.py | thedennerdev/ExerciciosPython-Iniciante | 0 | 11965 | #Exercício Python 39: Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
imp... | #Exercício Python 39: Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
imp... | pt | 0.991892 | #Exercício Python 39: Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar, se é a hora exata de se alistar ou se já passou do tempo do alistamento. Seu programa também deverá mostrar o tempo que falta ou que passou do prazo. | 4.074814 | 4 |
fish_dashboard/scrapyd/scrapyd_service.py | SylvanasSun/FishFishJump | 60 | 11966 | <reponame>SylvanasSun/FishFishJump<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fish_core.utils.common_utils import format_dict_to_str, get_current_date, list_to_str, str_to_list
from fish_dashboard.scrapyd.model import ScrapydStatusVO, JobListDO, JobStatus, JobPriority, ProjectListVO, SpiderListV... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from fish_core.utils.common_utils import format_dict_to_str, get_current_date, list_to_str, str_to_list
from fish_dashboard.scrapyd.model import ScrapydStatusVO, JobListDO, JobStatus, JobPriority, ProjectListVO, SpiderListVO
from fish_dashboard.scrapyd.scrapyd_db import Sql... | en | 0.797365 | #!/usr/bin/env python # -*- coding: utf-8 -*- CREATE TABLE %s (job_id VARCHAR(32) PRIMARY KEY, args VARCHAR(20), priority INT(1), creation_time DATE, logs_name VARCHAR(128), logs_url VARCHAR(255), project_name VARCHAR(32), project_version VARCHAR(20)) # Sav... | 2.125099 | 2 |
apps/shared/storage.py | bensternthal/affiliates | 0 | 11967 | <filename>apps/shared/storage.py
import os
from tempfile import mkstemp
from django.conf import settings
from django.core.files import locks
from django.core.files.move import file_move_safe
from django.core.files.storage import FileSystemStorage
from django.utils.text import get_valid_filename
class OverwritingStora... | <filename>apps/shared/storage.py
import os
from tempfile import mkstemp
from django.conf import settings
from django.core.files import locks
from django.core.files.move import file_move_safe
from django.core.files.storage import FileSystemStorage
from django.utils.text import get_valid_filename
class OverwritingStora... | en | 0.880678 | File storage that allows overwriting of stored files. Modified from http://djangosnippets.org/snippets/2173/ Lifted partially from django/core/files/storage.py # Ensure that content is open # Content has a file that we can move. # Write the content stream to a temporary file and move it. | 2.369022 | 2 |
bin/dupeFinder.py | kebman/dupe-finder-py | 1 | 11968 | <filename>bin/dupeFinder.py
#!/usr/bin/env python2
import os
import hashlib
import datetime
import sqlite3
from sqlite3 import Error
def sha256(fname):
"""Return sha256 hash from input file (fname).
:param fname:
:return: Sha256 hash digest in hexadecimal"""
hash_sha256 = hashlib.sha256()
with open(fname, "rb") a... | <filename>bin/dupeFinder.py
#!/usr/bin/env python2
import os
import hashlib
import datetime
import sqlite3
from sqlite3 import Error
def sha256(fname):
"""Return sha256 hash from input file (fname).
:param fname:
:return: Sha256 hash digest in hexadecimal"""
hash_sha256 = hashlib.sha256()
with open(fname, "rb") a... | en | 0.636919 | #!/usr/bin/env python2 Return sha256 hash from input file (fname). :param fname: :return: Sha256 hash digest in hexadecimal Get human readable time from a Python timestamp. :param timestamp: :return: Human readable timestamp (HRT) Make timestamp for SQLite from Python timestamp, meaning a UNIX epoch INTEGER. :para... | 3.320782 | 3 |
Python/factorialIterative.py | Ricardoengithub/Factorial | 0 | 11969 | def factorial(n):
fact = 1
for i in range(2,n+1):
fact*= i
return fact
def main():
n = int(input("Enter a number: "))
if n >= 0:
print(f"Factorial: {factorial(n)}")
else:
print(f"Choose another number")
if __name__ == "__main__":
main()
| def factorial(n):
fact = 1
for i in range(2,n+1):
fact*= i
return fact
def main():
n = int(input("Enter a number: "))
if n >= 0:
print(f"Factorial: {factorial(n)}")
else:
print(f"Choose another number")
if __name__ == "__main__":
main()
| none | 1 | 4.169164 | 4 | |
code_old/sort.py | benwoo1110/A-List-of-Sorts-v2 | 6 | 11970 | ######################################
# Import and initialize the librarys #
#####################################
from code.pygame_objects import *
from code.algorithm.bubblesort import bubblesort
from code.algorithm.insertionsort import insertionsort
from code.algorithm.bogosort import bogosort
from code.algorithm.m... | ######################################
# Import and initialize the librarys #
#####################################
from code.pygame_objects import *
from code.algorithm.bubblesort import bubblesort
from code.algorithm.insertionsort import insertionsort
from code.algorithm.bogosort import bogosort
from code.algorithm.m... | en | 0.310716 | ###################################### # Import and initialize the librarys # ##################################### ################# # Setup logging # ################# # Set data from parent # Display sort screen # Buffer time before sort starts # Get check for interaction with screen # No action # When program is se... | 2.660658 | 3 |
catkin_ws/src/tutorials/scripts/number_sub.py | vipulkumbhar/AuE893Spring19_VipulKumbhar | 3 | 11971 | <gh_stars>1-10
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int64
counter = 0
pub = None
def callback_number(msg):
global counter
counter += msg.data
new_msg = Int64()
new_msg.data = counter
pub.publish(new_msg)
rospy.loginfo(counter)
if __name__ == '__main__':
ro... | #!/usr/bin/env python
import rospy
from std_msgs.msg import Int64
counter = 0
pub = None
def callback_number(msg):
global counter
counter += msg.data
new_msg = Int64()
new_msg.data = counter
pub.publish(new_msg)
rospy.loginfo(counter)
if __name__ == '__main__':
rospy.init_node('... | ru | 0.26433 | #!/usr/bin/env python | 2.253689 | 2 |
setup.py | eddo888/perdy | 0 | 11972 | #!/usr/bin/env python
import codecs
from os import path
from setuptools import setup
pwd = path.abspath(path.dirname(__file__))
with codecs.open(path.join(pwd, 'README.md'), 'r', encoding='utf8') as input:
long_description = input.read()
version='1.7'
setup(
name='Perdy',
version=version,
license='MIT',
... | #!/usr/bin/env python
import codecs
from os import path
from setuptools import setup
pwd = path.abspath(path.dirname(__file__))
with codecs.open(path.join(pwd, 'README.md'), 'r', encoding='utf8') as input:
long_description = input.read()
version='1.7'
setup(
name='Perdy',
version=version,
license='MIT',
... | ru | 0.26433 | #!/usr/bin/env python | 1.544978 | 2 |
utils/slack_send.py | IntelliGrape/pennypincher | 0 | 11973 | from tabulate import tabulate
from slack.errors import SlackApiError
import sys
import logging
import slack
class Slackalert:
"""To send cost report on slack."""
def __init__(self, channel=None, slack_token=None):
self.channel = channel
self.slack_token = slack_token
logging.basicConfi... | from tabulate import tabulate
from slack.errors import SlackApiError
import sys
import logging
import slack
class Slackalert:
"""To send cost report on slack."""
def __init__(self, channel=None, slack_token=None):
self.channel = channel
self.slack_token = slack_token
logging.basicConfi... | en | 0.708562 | To send cost report on slack. Returns all the idle resource information in a dictionary format. Creates a txt file which contains the cost report and sends to the slack channel. #Converts resource info dictionary to tabular format. You will get a SlackApiError if "ok" is False. str like 'invalid_auth', 'channel_not_fo... | 3.248801 | 3 |
src/importer/importer.py | tiefenauer/ip7-python | 0 | 11974 | import logging
from abc import ABC, abstractmethod
from pony.orm import db_session, commit
log = logging.getLogger(__name__)
class Importer(ABC):
def __init__(self, TargetEntity):
self.TargetEntity = TargetEntity
@db_session
def truncate(self):
log.info('Truncating target tables...')
... | import logging
from abc import ABC, abstractmethod
from pony.orm import db_session, commit
log = logging.getLogger(__name__)
class Importer(ABC):
def __init__(self, TargetEntity):
self.TargetEntity = TargetEntity
@db_session
def truncate(self):
log.info('Truncating target tables...')
... | en | 0.576316 | iterate over items to be imported | 2.566188 | 3 |
news/pybo/migrations/0006_auto_20211010_0322.py | Smashh712/nrib | 0 | 11975 | # Generated by Django 3.2.7 on 2021-10-09 18:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pybo', '0005_auto_20211010_0320'),
]
operations = [
migrations.AddField(
model_name='issue',
name='agree_representor... | # Generated by Django 3.2.7 on 2021-10-09 18:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pybo', '0005_auto_20211010_0320'),
]
operations = [
migrations.AddField(
model_name='issue',
name='agree_representor... | en | 0.88296 | # Generated by Django 3.2.7 on 2021-10-09 18:22 | 1.633965 | 2 |
anno_gen/modify_filesprocessed.py | KevinQian97/diva_toolbox | 0 | 11976 | import json
import os
def get_file_index(filesProcessed):
new_dict = {}
for f in filesProcessed:
new_dict[f]={"framerate": 30.0, "selected": {"0": 1, "9000": 0}}
return new_dict
ref = json.load(open("/home/lijun/downloads/kf1_meta/references/kf1_all.json","r"))
files = ref["filesProcessed"]
print... | import json
import os
def get_file_index(filesProcessed):
new_dict = {}
for f in filesProcessed:
new_dict[f]={"framerate": 30.0, "selected": {"0": 1, "9000": 0}}
return new_dict
ref = json.load(open("/home/lijun/downloads/kf1_meta/references/kf1_all.json","r"))
files = ref["filesProcessed"]
print... | none | 1 | 2.610048 | 3 | |
monotone_bipartition/search.py | mvcisback/monotone-bipartition | 1 | 11977 | from enum import Enum, auto
import funcy as fn
import numpy as np
from monotone_bipartition import rectangles as mdtr
from monotone_bipartition import refine
EPS = 1e-4
class SearchResultType(Enum):
TRIVIALLY_FALSE = auto()
TRIVIALLY_TRUE = auto()
NON_TRIVIAL = auto()
def diagonal_convex_comb(r):
... | from enum import Enum, auto
import funcy as fn
import numpy as np
from monotone_bipartition import rectangles as mdtr
from monotone_bipartition import refine
EPS = 1e-4
class SearchResultType(Enum):
TRIVIALLY_FALSE = auto()
TRIVIALLY_TRUE = auto()
NON_TRIVIAL = auto()
def diagonal_convex_comb(r):
... | en | 0.725685 | Binary search over the diagonal of the rectangle. Returns the lower and upper approximation on the diagonal. # Early termination via bounds checks # Compute bounding rec. # Need to compensate for multiple binsearches. # If polarity is True, set initial value at bounding.top. # O.w. use bounding.bot. | 2.664209 | 3 |
api/web/apps/auth/views.py | procool/itstructure | 0 | 11978 | from flask import url_for
from flaskcbv.view import View
from flaskcbv.conf import settings
from misc.mixins import HelperMixin
from misc.views import JSONView
class authView(JSONView):
def helper(self):
return """Authorizaion handler
Use "login" and "passwd" arguments by GET or POST to get ses... | from flask import url_for
from flaskcbv.view import View
from flaskcbv.conf import settings
from misc.mixins import HelperMixin
from misc.views import JSONView
class authView(JSONView):
def helper(self):
return """Authorizaion handler
Use "login" and "passwd" arguments by GET or POST to get ses... | en | 0.532971 | Authorizaion handler Use "login" and "passwd" arguments by GET or POST to get session Session check handler Use "session" argument by GET or POST to check your session | 2.550932 | 3 |
tests/test_heart_forest.py | RainingComputers/pykitml | 34 | 11979 | <reponame>RainingComputers/pykitml
from pykitml.testing import pktest_graph, pktest_nograph
@pktest_graph
def test_heart_forest():
import os.path
import numpy as np
import pykitml as pk
from pykitml.datasets import heartdisease
# Download the dataset
if(not os.path.exists('heartdisease.p... | from pykitml.testing import pktest_graph, pktest_nograph
@pktest_graph
def test_heart_forest():
import os.path
import numpy as np
import pykitml as pk
from pykitml.datasets import heartdisease
# Download the dataset
if(not os.path.exists('heartdisease.pkl')): heartdisease.get()
# Lo... | en | 0.651814 | # Download the dataset # Load heart data set # Create model # Train # Save it # Print accuracy # Plot confusion matrix # Assert accuracy # Predict heartdisease for a person with # age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal # 67, 1, 4, 160, 286, 0, 2, 108, 1, 1.5, 2, 3, 3 # Load the model #... | 2.971682 | 3 |
pdf_audit.py | marctjones/perception | 0 | 11980 | <filename>pdf_audit.py
from globals import Globals
import os
import subprocess
import datetime as dt
from urllib import \
request as request
# urlopen
from io import \
StringIO, BytesIO
import string
import requests
import re
import csv
import threading
import utils as utils
import time
import datetime as date... | <filename>pdf_audit.py
from globals import Globals
import os
import subprocess
import datetime as dt
from urllib import \
request as request
# urlopen
from io import \
StringIO, BytesIO
import string
import requests
import re
import csv
import threading
import utils as utils
import time
import datetime as date... | en | 0.403488 | # urlopen # , LTTextBox, LTTextLine # try: # except Exception as e: # print('PDFDocument(self.parser) FAILED ::::: ' + e.__str__()) # print(self.parser.fp.name + ' FAILED (SEC): ' + i.__str__()) # self.line_count += 1 # 90 SECOND TIMEOUT or FAILED TO PARSER # self.line_count += 1 # 120 SECOND TIMEOUT # Define CSV # roo... | 2.515848 | 3 |
morepath/tests/test_method_directive.py | DuncanBetts/morepath | 0 | 11981 | import morepath
from webtest import TestApp as Client
def test_implicit_function():
class app(morepath.App):
@morepath.dispatch_method()
def one(self):
return "Default one"
@morepath.dispatch_method()
def two(self):
return "Default two"
@app.path(path=... | import morepath
from webtest import TestApp as Client
def test_implicit_function():
class app(morepath.App):
@morepath.dispatch_method()
def one(self):
return "Default one"
@morepath.dispatch_method()
def two(self):
return "Default two"
@app.path(path=... | none | 1 | 2.466808 | 2 | |
edb/edgeql/tracer.py | hyperdrivetech/edgedb | 0 | 11982 | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2015-present MagicStack Inc. and the EdgeDB authors.
#
# 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... | #
# This source file is part of the EdgeDB open source project.
#
# Copyright 2015-present MagicStack Inc. and the EdgeDB authors.
#
# 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... | en | 0.858138 | # # This source file is part of the EdgeDB open source project. # # Copyright 2015-present MagicStack Inc. and the EdgeDB authors. # # 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... | 1.86093 | 2 |
libraries/website/docs/snippets/envs/tree_to_list.py | justindujardin/mathy | 95 | 11983 | <reponame>justindujardin/mathy<gh_stars>10-100
from typing import List
from mathy_core import ExpressionParser, MathExpression
parser = ExpressionParser()
expression: MathExpression = parser.parse("4 + 2x")
nodes: List[MathExpression] = expression.to_list()
# len([4,+,2,*,x])
assert len(nodes) == 5
| from typing import List
from mathy_core import ExpressionParser, MathExpression
parser = ExpressionParser()
expression: MathExpression = parser.parse("4 + 2x")
nodes: List[MathExpression] = expression.to_list()
# len([4,+,2,*,x])
assert len(nodes) == 5 | zh | 0.482692 | # len([4,+,2,*,x]) | 2.965861 | 3 |
math/0x04-convolutions_and_pooling/test/2-main.py | cbarros7/holbertonschool-machine_learning | 1 | 11984 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
convolve_grayscale_padding = __import__(
'2-convolve_grayscale_padding').convolve_grayscale_padding
if __name__ == '__main__':
dataset = np.load('../../supervised_learning/data/MNIST.npz')
images = dataset['X_train']
print(ima... | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
convolve_grayscale_padding = __import__(
'2-convolve_grayscale_padding').convolve_grayscale_padding
if __name__ == '__main__':
dataset = np.load('../../supervised_learning/data/MNIST.npz')
images = dataset['X_train']
print(ima... | fr | 0.221828 | #!/usr/bin/env python3 | 3.355659 | 3 |
code.py | surojitnath/olympic-hero | 0 | 11985 | # --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file
data=pd.read_csv(path)
data.rename(columns={'Total':'Total_Medals'},inplace =True)
data.head(10)
#Code starts here
# --------------
try:
data['Better_Event'] = np.where(... | # --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file
data=pd.read_csv(path)
data.rename(columns={'Total':'Total_Medals'},inplace =True)
data.head(10)
#Code starts here
# --------------
try:
data['Better_Event'] = np.where(... | en | 0.459234 | # -------------- #Importing header files #Path of the file #Code starts here # -------------- #print(data['Better_Event']) # -------------- #Code starts here #print(top_countries) # -------------- #Code starts here # -------------- #Code starts here # -------------- #Code starts here # -------------- #Code starts here ... | 3.45912 | 3 |
planes/kissSlope/kissSlopeWing2.py | alexpGH/blenderCadCamTools | 3 | 11986 | <gh_stars>1-10
import bpy
import math
import numpy as np
#=== add scripts dir to path
import sys
import os
#=== define path of scripts dir
libDir=bpy.path.abspath("//../../scripts/") # version1: relative to current file
#libDir="/where/you/placed/blenderCadCam/scripts/" #version 2: usa an absolute path
if not libDir... | import bpy
import math
import numpy as np
#=== add scripts dir to path
import sys
import os
#=== define path of scripts dir
libDir=bpy.path.abspath("//../../scripts/") # version1: relative to current file
#libDir="/where/you/placed/blenderCadCam/scripts/" #version 2: usa an absolute path
if not libDir in sys.path:
... | en | 0.438371 | #=== add scripts dir to path #=== define path of scripts dir # version1: relative to current file #libDir="/where/you/placed/blenderCadCam/scripts/" #version 2: usa an absolute path #=== add local dir to path #print(sys.path) #=== blender imports only once even if the file change. if we edit outsde, we need to force a ... | 2.048349 | 2 |
saleor/order/migrations/0072_django_price_2.py | elwoodxblues/saleor | 19 | 11987 | # Generated by Django 2.2.4 on 2019-08-14 09:13
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("order", "0071_order_gift_cards")]
operations = [
migrations.RenameField(
model_name="order",
old... | # Generated by Django 2.2.4 on 2019-08-14 09:13
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("order", "0071_order_gift_cards")]
operations = [
migrations.RenameField(
model_name="order",
old... | en | 0.741683 | # Generated by Django 2.2.4 on 2019-08-14 09:13 | 1.759547 | 2 |
miping/training/features.py | mclgoerg/MiningPersonalityInGerman | 1 | 11988 | <filename>miping/training/features.py
import numpy as np
from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import Pipeline
from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import StandardScaler
from ..models.profile import Profile
from ..interfaces.helper import Helper
fr... | <filename>miping/training/features.py
import numpy as np
from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import Pipeline
from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import StandardScaler
from ..models.profile import Profile
from ..interfaces.helper import Helper
fr... | en | 0.778497 | Contains all pipeline functions for both LIWC and glove. Extract LIWC features (namely LIWC categories) from each profile in list as feature. Parameters ---------- profileCol : list, default=None, required List with profiles to generate features for. Returns ... | 2.842155 | 3 |
tests/unit/test_serializers.py | launchpadrecruits/placebo | 1 | 11989 | <reponame>launchpadrecruits/placebo
# Copyright (c) 2015 <NAME>
#
# 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... | # Copyright (c) 2015 <NAME>
#
# 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, s... | en | 0.777202 | # Copyright (c) 2015 <NAME> # # 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, s... | 2.314218 | 2 |
Chapter11/web_03.py | vabyte/Modern-Python-Standard-Library-Cookbook | 84 | 11990 | <filename>Chapter11/web_03.py
import urllib.request
import urllib.parse
import json
def http_request(url, query=None, method=None, headers={}, data=None):
"""Perform an HTTP request and return the associated response."""
parts = vars(urllib.parse.urlparse(url))
if query:
parts['query'] = urllib.pa... | <filename>Chapter11/web_03.py
import urllib.request
import urllib.parse
import json
def http_request(url, query=None, method=None, headers={}, data=None):
"""Perform an HTTP request and return the associated response."""
parts = vars(urllib.parse.urlparse(url))
if query:
parts['query'] = urllib.pa... | en | 0.823413 | Perform an HTTP request and return the associated response. | 3.605414 | 4 |
src/oci/dns/models/external_master.py | Manny27nyc/oci-python-sdk | 249 | 11991 | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | en | 0.730084 | # coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 2.224455 | 2 |
cinder/tests/unit/backup/fake_service_with_verify.py | puremudassir/cinder | 0 | 11992 | <filename>cinder/tests/unit/backup/fake_service_with_verify.py<gh_stars>0
# Copyright (C) 2014 Deutsche Telekom AG
# All Rights Reserved.
#
# 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... | <filename>cinder/tests/unit/backup/fake_service_with_verify.py<gh_stars>0
# Copyright (C) 2014 Deutsche Telekom AG
# All Rights Reserved.
#
# 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... | en | 0.842926 | # Copyright (C) 2014 Deutsche Telekom AG # All Rights Reserved. # # 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 r... | 2.113293 | 2 |
src/fasttick.py | JevinJ/Bittrex-Notify | 12 | 11993 | <filename>src/fasttick.py
import config
import misc
def heartbeat():
"""
Processes data from Bittrex into a simpler dictionary,
calls the save function on it, deletes the oldest
saved dictionary(if it's out of lookback range), and finally
creates a list of the best coins to be used in tkinter list... | <filename>src/fasttick.py
import config
import misc
def heartbeat():
"""
Processes data from Bittrex into a simpler dictionary,
calls the save function on it, deletes the oldest
saved dictionary(if it's out of lookback range), and finally
creates a list of the best coins to be used in tkinter list... | en | 0.788658 | Processes data from Bittrex into a simpler dictionary, calls the save function on it, deletes the oldest saved dictionary(if it's out of lookback range), and finally creates a list of the best coins to be used in tkinter listboxes. :return: A list containing triples of (coin name, increase rate, volume)... | 3.161925 | 3 |
src/mlb_statsapi/model/api/game.py | power-edge/mlb_statsapi_etl | 0 | 11994 | <gh_stars>0
"""
created by nikos at 4/26/21
"""
import datetime
from ..base import MLBStatsAPIEndpointModel
from mlb_statsapi.utils.stats_api_object import configure_api
YMDTHMS = '%Y-%m-%dT%H:%M:%SZ'
YYYYMMDD_HHMMSS = '%Y%m%d_%H%M%S'
MMDDYYYY_HHMMSS = '%m%d%Y_%H%M%S'
class GameModel(MLBStatsAPIEndpointModel):
... | """
created by nikos at 4/26/21
"""
import datetime
from ..base import MLBStatsAPIEndpointModel
from mlb_statsapi.utils.stats_api_object import configure_api
YMDTHMS = '%Y-%m-%dT%H:%M:%SZ'
YYYYMMDD_HHMMSS = '%Y%m%d_%H%M%S'
MMDDYYYY_HHMMSS = '%m%d%Y_%H%M%S'
class GameModel(MLBStatsAPIEndpointModel):
date_forma... | en | 0.996347 | created by nikos at 4/26/21 | 2.101937 | 2 |
scripts/build_folding_map.py | tsieprawski/md4c | 475 | 11995 | #!/usr/bin/env python3
import os
import sys
import textwrap
self_path = os.path.dirname(os.path.realpath(__file__));
f = open(self_path + "/unicode/CaseFolding.txt", "r")
status_list = [ "C", "F" ]
folding_list = [ dict(), dict(), dict() ]
# Filter the foldings for "full" folding.
for line in f:
comment_off =... | #!/usr/bin/env python3
import os
import sys
import textwrap
self_path = os.path.dirname(os.path.realpath(__file__));
f = open(self_path + "/unicode/CaseFolding.txt", "r")
status_list = [ "C", "F" ]
folding_list = [ dict(), dict(), dict() ]
# Filter the foldings for "full" folding.
for line in f:
comment_off =... | en | 0.905756 | #!/usr/bin/env python3 # Filter the foldings for "full" folding. # If we assume that (index0 ... index-1) makes a range (as defined below), # check that the newly provided index is compatible with the range too; i.e. # verify that the range can be extended without breaking its properties. # # Currently, we can handle r... | 2.745547 | 3 |
app/api/v1/models/user_model.py | munniomer/Send-IT-Api-v1 | 0 | 11996 | <gh_stars>0
users = []
class UserModel(object):
"""Class user models."""
def __init__(self):
self.db = users
def add_user(self, fname, lname, email, phone, password, confirm_password, city):
""" Method for saving user to the dictionary """
payload = {
"userId": len(se... | users = []
class UserModel(object):
"""Class user models."""
def __init__(self):
self.db = users
def add_user(self, fname, lname, email, phone, password, confirm_password, city):
""" Method for saving user to the dictionary """
payload = {
"userId": len(self.db)+1,
... | en | 0.755546 | Class user models. Method for saving user to the dictionary Method for checking if user email exist Method for checking if user exist | 3.87355 | 4 |
Codigo/pruebas/Jose_Gonzalez/Solucion_PruebaTipoPiso.py | JoaquinRodriguez2006/RoboCup_Junior_Material | 0 | 11997 | from controller import Robot
from controller import Motor
from controller import PositionSensor
from controller import Robot, DistanceSensor, GPS, Camera, Receiver, Emitter
import cv2
import numpy as np
import math
import time
robot = Robot()
timeStep = 32
tile_size = 0.12
speed = 6.28
media_baldoza = 0.06
estado = 1
... | from controller import Robot
from controller import Motor
from controller import PositionSensor
from controller import Robot, DistanceSensor, GPS, Camera, Receiver, Emitter
import cv2
import numpy as np
import math
import time
robot = Robot()
timeStep = 32
tile_size = 0.12
speed = 6.28
media_baldoza = 0.06
estado = 1
... | es | 0.271607 | # start = robot.getTime() # Camera initialization # Colour sensor initialization # Distance sensor initialization # Motor initialization # Functions # Color sensor # azul: r=65 g=65 b=252 # rojo: r=252 g=65 b=65 # print("r: " + str(r) + " g: " + str(g) + " b: " + str(b)) # Camara image = camera.getImage() image... | 3.000921 | 3 |
drip/migrations/0002_querysetrule_rule_type.py | RentFreeMedia/django-drip-campaigns | 46 | 11998 | # Generated by Django 3.0.7 on 2020-11-25 13:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('drip', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='querysetrule',
name='rule_type',
... | # Generated by Django 3.0.7 on 2020-11-25 13:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('drip', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='querysetrule',
name='rule_type',
... | en | 0.834592 | # Generated by Django 3.0.7 on 2020-11-25 13:13 | 1.715028 | 2 |
venv/lib/python3.6/site-packages/cligj/__init__.py | booklover98/A-_pathfinding | 0 | 11999 | <filename>venv/lib/python3.6/site-packages/cligj/__init__.py
# cligj
# Shared arguments and options.
import click
from .features import normalize_feature_inputs
# Arguments.
# Multiple input files.
files_in_arg = click.argument(
'files',
nargs=-1,
type=click.Path(resolve_path=True),
required=True,
... | <filename>venv/lib/python3.6/site-packages/cligj/__init__.py
# cligj
# Shared arguments and options.
import click
from .features import normalize_feature_inputs
# Arguments.
# Multiple input files.
files_in_arg = click.argument(
'files',
nargs=-1,
type=click.Path(resolve_path=True),
required=True,
... | en | 0.633723 | # cligj # Shared arguments and options. # Arguments. # Multiple input files. # Multiple files, last of which is an output file. # Features from files, command line args, or stdin. # Returns the input data as an iterable of GeoJSON Feature-like # dictionaries. # Options. # Format driver option. # JSON formatting options... | 2.632821 | 3 |