file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
version.py | #!/usr/bin/python3
"""Script to determine the Pywikibot version (tag, revision and date).
.. versionchanged:: 7.0
version script was moved to the framework scripts folder
"""
#
# (C) Pywikibot team, 2007-2021
#
# Distributed under the terms of the MIT license.
#
import codecs
import os
import sys
import pywikibot
... | (*args: str) -> None:
"""Print pywikibot version and important settings."""
pywikibot.output('Pywikibot: ' + getversion())
pywikibot.output('Release version: ' + pywikibot.__version__)
pywikibot.output('setuptools version: ' + setuptools.__version__)
pywikibot.output('mwparserfromhell version: '
... | main | identifier_name |
version.py | #!/usr/bin/python3
"""Script to determine the Pywikibot version (tag, revision and date).
.. versionchanged:: 7.0
version script was moved to the framework scripts folder
"""
#
# (C) Pywikibot team, 2007-2021
#
# Distributed under the terms of the MIT license.
#
import codecs
import os
import sys
import pywikibot
... |
if __name__ == '__main__':
main()
| """Print pywikibot version and important settings."""
pywikibot.output('Pywikibot: ' + getversion())
pywikibot.output('Release version: ' + pywikibot.__version__)
pywikibot.output('setuptools version: ' + setuptools.__version__)
pywikibot.output('mwparserfromhell version: '
+ mwpars... | identifier_body |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | """
sql_query = Challenge.query
if serial is not None:
# filter for serial
sql_query = sql_query.filter(Challenge.serial == serial)
if transaction_id is not None:
# filter for transaction id
sql_query = sql_query.filter(Challenge.transaction_id ==
... | :return: list of objects | random_line_split |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | erial=None, transaction_id=None,
sortby=Challenge.timestamp,
sortdir="asc", psize=15, page=1):
"""
This function is used to retrieve a challenge list, that can be displayed in
the Web UI. It supports pagination.
Each retrieved page will also contai... | t_challenges_paginate(s | identifier_name |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... | else:
# exact match
sql_query = sql_query.filter(Challenge.serial == serial)
if transaction_id is not None and transaction_id.strip("*"):
# filter for serial
if "*" in transaction_id:
# match with "like"
sql_query = sql_query.filter(Challenge.t... | l_query = sql_query.filter(Challenge.serial.like(serial.replace(
"*", "%")))
| conditional_block |
challenge.py | # -*- coding: utf-8 -*-
# privacyIDEA is a fork of LinOTP
#
# 2014-12-07 Cornelius Kölbel <cornelius@privacyidea.org>
#
# Copyright (C) 2014 Cornelius Kölbel
# License: AGPLv3
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# Licen... |
def _create_challenge_query(serial=None, transaction_id=None):
"""
This function create the sql query for fetching transaction_ids. It is
used by get_challenge_paginate.
:return: An SQLAlchemy sql query
"""
sql_query = Challenge.query
if serial is not None and serial.strip("*"):
# f... | "
This function is used to retrieve a challenge list, that can be displayed in
the Web UI. It supports pagination.
Each retrieved page will also contain a "next" and a "prev", indicating
the next or previous page. If either does not exist, it is None.
:param serial: The serial of the token
:par... | identifier_body |
http.py | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
# MIMICS THE requests API (http://docs.python-re... |
else:
self.shared = _shared
self.shared.ref_count += 1
def __iter__(self):
return Generator_usingStream(None, self.shared.length, self.shared)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def next(self... | self.shared = Data(
length=length,
locker=Lock(),
stream=stream,
done_read=0,
file=file_,
buffer=mmap(file_.fileno(), length)
) | conditional_block |
http.py | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
# MIMICS THE requests API (http://docs.python-re... |
def get_json(url, **kwargs):
"""
ASSUME RESPONSE IN IN JSON
"""
response = get(url, **kwargs)
c = response.all_content
return mo_json.json2value(convert.utf82unicode(c))
def options(url, **kwargs):
kwargs.setdefault(b'allow_redirects', True)
kwargs[b"stream"] = True
return HttpRe... | kwargs.setdefault(b'allow_redirects', True)
kwargs[b"stream"] = True
return HttpResponse(request(b'get', url, **kwargs)) | identifier_body |
http.py | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
# MIMICS THE requests API (http://docs.python-re... | c = response.content
try:
details = mo_json.json2value(convert.utf82unicode(c))
except Exception as e:
Log.error("Unexpected return value {{content}}", content=c, cause=e)
if response.status_code not in [200, 201]:
Log.error("Bad response", cause=Except.wrap(details))
retur... | Log.error("Expecting `json` parameter")
response = post(url, **kwargs) | random_line_split |
http.py | # encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
# MIMICS THE requests API (http://docs.python-re... | (self):
return Generator_usingStream(None, self.shared.length, self.shared)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def next(self):
if self.position >= self.shared.length:
raise StopIteration
end = min(... | __iter__ | identifier_name |
layers.py | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
return compat_utils.batch_to_space(
input=tf.tile(images, [scale**2, 1, 1, 1]),
crops=[[0, 0], [0, 0]],
block_shape=scale)
def minibatch_mean_stddev(x):
"""Computes the standard deviation average.
This is used by the discriminator as a form of batch discrimination.
Args:
x: A `Tensor`... | return images | conditional_block |
layers.py | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
def custom_dense(x,
units,
activation=None,
he_initializer_slope=1.0,
use_weight_scaling=True,
scope='custom_dense',
reuse=None):
"""Custom dense layer.
In comparison with tf.layers.dense This implementation us... | """Custom conv2d layer.
In comparison with tf.layers.conv2d this implementation use the He initializer
to initialize convolutional kernel and the weight scaling trick (if
`use_weight_scaling` is True) to equalize learning rates. See
https://arxiv.org/abs/1710.10196 for more details.
Args:
x: A `Tensor` ... | identifier_body |
layers.py | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | Returns:
A float of he initializer scale.
"""
fan_in = np.prod(shape[:-1])
return np.sqrt(2. / ((1. + slope**2) * fan_in))
def _custom_layer_impl(apply_kernel, kernel_shape, bias_shape, activation,
he_initializer_slope, use_weight_scaling):
"""Helper function to implement custom_x... |
Args:
shape: A list of ints representing the dimensions of a tensor.
slope: A float representing the slope of the ReLu following the layer.
| random_line_split |
layers.py | # coding=utf-8
# Copyright 2022 The TensorFlow GAN 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | (kernel_shape, kernel_initializer):
return tf.layers.conv2d(
x,
filters=filters,
kernel_size=kernel_shape[0:2],
strides=strides,
padding=padding,
use_bias=False,
kernel_initializer=kernel_initializer)
with tf.variable_scope(scope, reuse=reuse):
return _... | _apply_kernel | identifier_name |
vs-11.0-scc-files.py | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 us... | \t\t<SccProjectName>Perforce Project</SccProjectName>
\t\t<SccLocalPath>.</SccLocalPath>
\t\t<SccProvider>MSSCCI:Perforce SCM</SccProvider>
"""
test.write('SConstruct', SConscript_contents)
test.run(arguments="Test.vcxproj")
test.must_exist(test.workpath('Test.vcxproj'))
vcproj = test.read('Test.vcxproj', 'r')
expe... | \t\tSccProjectFilePathRelativizedFromConnection1 = .\\\\
\tEndGlobalSection
"""
expected_vcproj_sccinfo = """\ | random_line_split |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def | ():
parser = argparse.ArgumentParser(description='Generates SQLAlchemy model code from an existing database.')
parser.add_argument('url', nargs='?', help='SQLAlchemy url to the database')
parser.add_argument('--version', action='store_true', help="print the version number and exit")
parser.add_argument(... | main | identifier_name |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def main():
parser = argparse.Ar... |
engine = create_engine(args.url)
metadata = MetaData(engine)
tables = args.tables.split(',') if args.tables else None
metadata.reflect(engine, args.schema, not args.noviews, tables)
outfile = codecs.open(args.outfile, 'w', encoding='utf-8') if args.outfile else sys.stdout
generator = CodeGener... | print('You must supply a url\n', file=sys.stderr)
parser.print_help()
return | conditional_block |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def main():
parser = argparse.Ar... | parser.add_argument('--noindexes', action='store_true', help='ignore indexes')
parser.add_argument('--noconstraints', action='store_true', help='ignore constraints')
parser.add_argument('--nojoined', action='store_true', help="don't autodetect joined table inheritance")
parser.add_argument('--noinflect'... | parser.add_argument('--schema', help='load tables from an alternate schema')
parser.add_argument('--tables', help='tables to process (comma-separated, default: all)')
parser.add_argument('--noviews', action='store_true', help="ignore views") | random_line_split |
main.py | """ """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def main():
| parser = argparse.ArgumentParser(description='Generates SQLAlchemy model code from an existing database.')
parser.add_argument('url', nargs='?', help='SQLAlchemy url to the database')
parser.add_argument('--version', action='store_true', help="print the version number and exit")
parser.add_argument('--schem... | identifier_body | |
xhr_backend.ts | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} fro... | (private _browserXHR: BrowserXhr, private _baseResponseOptions: ResponseOptions) {}
createConnection(request: Request): XHRConnection {
return new XHRConnection(request, this._browserXHR, this._baseResponseOptions);
}
}
| constructor | identifier_name |
xhr_backend.ts | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} fro... |
ObservableWrapper.callNext(this.response, new Response(responseOptions));
// TODO(gdi2290): defer complete if array buffer until done
ObservableWrapper.callReturn(this.response);
});
this._xhr.addEventListener('error', (err) => {
var responseOptions = new ResponseOptions({body: err, t... | {
responseOptions = baseResponseOptions.merge(responseOptions);
} | conditional_block |
xhr_backend.ts | import {ConnectionBackend, Connection} from '../interfaces';
import {ReadyStates, RequestMethods, ResponseTypes} from '../enums';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {ResponseOptions, BaseResponseOptions} from '../base_response_options';
import {Injectable} fro... | }
ObservableWrapper.callNext(this.response, new Response(responseOptions));
// TODO(gdi2290): defer complete if array buffer until done
ObservableWrapper.callReturn(this.response);
});
this._xhr.addEventListener('error', (err) => {
var responseOptions = new ResponseOptions({body:... | responseOptions = baseResponseOptions.merge(responseOptions); | random_line_split |
channel_list.rs | use ui::ncurses::*;
use ui::{RIGHT_PANEL_WIDTH, CMD_ENTRY_HEIGHT, STATS_PANEL_HEIGHT, Position, Size};
use ui::window::BorderWindow;
pub struct ChannelList {
window: BorderWindow,
channels: Vec<String>,
}
impl ChannelList {
pub fn new(size: Size) -> ChannelList {
let window = BorderWindow::new(
... | },
None => false,
}
}
} | random_line_split | |
channel_list.rs | use ui::ncurses::*;
use ui::{RIGHT_PANEL_WIDTH, CMD_ENTRY_HEIGHT, STATS_PANEL_HEIGHT, Position, Size};
use ui::window::BorderWindow;
pub struct ChannelList {
window: BorderWindow,
channels: Vec<String>,
}
impl ChannelList {
pub fn new(size: Size) -> ChannelList {
let window = BorderWindow::new(
... |
pub fn add_channel(&mut self, name: &str) {
self.channels.push(name.to_string());
self.display_channel(self.channels.len() as i32 - 1, name);
}
pub fn remove_channel(&mut self, name: &str) -> bool {
let index = self.channels.iter().position(|ref s| s.as_str() == name);
ma... | {
mvwaddstr(self.window.inner.id,
index,
1,
&format!("{} - {}", index + 1, name));
wrefresh(self.window.inner.id);
} | identifier_body |
channel_list.rs | use ui::ncurses::*;
use ui::{RIGHT_PANEL_WIDTH, CMD_ENTRY_HEIGHT, STATS_PANEL_HEIGHT, Position, Size};
use ui::window::BorderWindow;
pub struct ChannelList {
window: BorderWindow,
channels: Vec<String>,
}
impl ChannelList {
pub fn new(size: Size) -> ChannelList {
let window = BorderWindow::new(
... | (&mut self, name: &str) -> bool {
let index = self.channels.iter().position(|ref s| s.as_str() == name);
match index {
Some(index) => {
self.channels.remove(index);
// TODO: Separate this redraw code into its own function once this method is actually used
... | remove_channel | identifier_name |
FZH04.py | import numpy as n, matplotlib.pyplot as p, scipy.special
import cosmolopy.perturbation as pb
import cosmolopy.density as cd
from scipy.integrate import quad,tplquad
import itertools
from scipy.interpolate import interp1d
from scipy.interpolate import RectBivariateSpline as RBS
import optparse, sys
from sigmas import si... | (S0,deltac,smin,K,d=0.001):
Bp,Bo,Bm = BFZH(S0+d,deltac,smin,K), BFZH(S0,deltac,smin,K), BFZH(S0-d,deltac,smin,K)
return S0/Bo*(Bp-Bm)/2/d
def dlnBFlindlnS0(S0,deltac,smin,K,d=0.001):
Bp,Bo,Bm = BFZHlin(S0+d,deltac,smin,K), BFZHlin(S0,deltac,smin,K), BFZHlin(S0-d,deltac,smin,K)
return S0/Bo*(Bp-Bm)/2/d
##### m_mi... | dlnBFdlnS0 | identifier_name |
FZH04.py | import numpy as n, matplotlib.pyplot as p, scipy.special
import cosmolopy.perturbation as pb
import cosmolopy.density as cd
from scipy.integrate import quad,tplquad
import itertools
from scipy.interpolate import interp1d
from scipy.interpolate import RectBivariateSpline as RBS
import optparse, sys
from sigmas import si... |
S0 = n.arange(0,S0max,0.2)
bFZH = deltac-n.sqrt(2*(smin-S0))*K
bFZHlin = bFZH0+bFZH1*S0
p.show()
################
# Z = float(opts.red)
# M0 = zeta*mmin(Z)*float(opts.mul)
# del0 = float(opts.del0)
###########################
# dlist = n.linspace(8,10,10)
# for del0 in dlist:
# res = fcoll_trapz_log(del... | S0max = sig0(m2R(M0min)) | conditional_block |
FZH04.py | import numpy as n, matplotlib.pyplot as p, scipy.special
import cosmolopy.perturbation as pb
import cosmolopy.density as cd
from scipy.integrate import quad,tplquad
import itertools
from scipy.interpolate import interp1d
from scipy.interpolate import RectBivariateSpline as RBS
import optparse, sys
from sigmas import si... |
def dlinSdlnR(lnR,d=0.001):
res = (n.log(sig0(n.exp(lnR+d)))-n.log(sig0(n.exp(lnR-d))))/d/2
return n.abs(res)
################################## MAIN ######################################
for z in [12., 16.]:
PLOT = True
zeta = 40.
K = scipy.special.erfinv(1-1./zeta)
Tvir = 1.E4
#z = 12.
deltac = Delt... | return RphysoR0(del0,z)*(1+z) | identifier_body |
FZH04.py | import numpy as n, matplotlib.pyplot as p, scipy.special
import cosmolopy.perturbation as pb
import cosmolopy.density as cd
from scipy.integrate import quad,tplquad
import itertools
from scipy.interpolate import interp1d
from scipy.interpolate import RectBivariateSpline as RBS
import optparse, sys
from sigmas import si... | def VdndlnR(lnR0):
S0 = sig0(n.exp(lnR0))
del0 = BFZH(S0,deltac,smin,K)
VoV0 = (RcovEul(del0,z))**3
return VoV0/dlnRdlnR0(lnR0,S0,del0)*S0*fFZH(S0,zeta,bFZH0,bFZH1)*dlinSdlnR(lnR0)
if True:
print 'computing z=',z
#Q = quad(lambda lnR: VdndlnR(lnR),n.log(Rmin),3.5) #integrated over eulerian coordinates
... | return VoV0*S0*fFZH(S0,zeta,bFZH0,bFZH1)*dlinSdlnR(lnR0) | random_line_split |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
out_Co... | (fname):
params = {}
with open(fname,'r') as f:
lines = f.readlines()
for line in lines:
if line[0] == '#':
continue
data = line.split()
idx = int(data[0])
name = data[1]
ie1 = float(data[2])
ie2 = float(data... | read_data_file | identifier_name |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
out_Co... |
else:
l = 5
if not l <= n:
raise ValueError('not l<=n')
print('anum,n,l,nval=',atomic_number,n,l,nval)
nseat = sum_array(nstates,n) -sum_array(nstates,n-1)
nseatopen = nseat - nval
for il in range(l+1,n+1):
nseatopen -= freedom[il]
print('nseat,nseatopen=',... | l = 4 | conditional_block |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
out_Co... |
if __name__ == "__main__":
args = docopt(__doc__)
fname = args['DATA_FILE']
specorder = [ name for name in args['NAME'] ]
params = read_data_file(fname)
write_Coulomb_params(out_Coulomb,params,specorder)
| with open(fname,'w') as f:
#...declare it is 'variable_charge' Coulomb
f.write(' variable_charge \n')
n = 0
e0 = 0.0
for k in specorder:
n += 1
p = params[k]
anum = p[0]
name = p[1]
ie = p[2]
ea = -p[4]
... | identifier_body |
extract_QEq_params.py | #!/usr/bin/env python
"""
Extract atomic parameters for QEq potential.
Usage:
extract_bvs_params.py [options] DATA_FILE NAME [NAME...]
Options:
-h, --help Show this message and exit.
"""
from __future__ import print_function
from docopt import docopt
__author__ = "RYO KOBAYASHI"
__version__ = "180112"
| params = {}
with open(fname,'r') as f:
lines = f.readlines()
for line in lines:
if line[0] == '#':
continue
data = line.split()
idx = int(data[0])
name = data[1]
ie1 = float(data[2])
ie2 = float(data[3])
... | out_Coulomb= 'in.params.Coulomb'
def read_data_file(fname): | random_line_split |
plural.py | # PLURAL - last updated for NodeBox 1rc7
# Author: Tom De Smedt <tomdesmedt@organisms.be>
# See LICENSE.txt for details.
# Based on "An Algorithmic Approach to English Pluralization" by Damian Conway:
# http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html
# Prepositions are used to solve things like
# "moth... | (word, classical=True, custom={}):
return plural(word, NOUN, classical, custom)
def adjective_plural(word, classical=True, custom={}):
return plural(word, ADJECTIVE, classical, custom) | noun_plural | identifier_name |
plural.py | # PLURAL - last updated for NodeBox 1rc7
# Author: Tom De Smedt <tomdesmedt@organisms.be>
# See LICENSE.txt for details.
# Based on "An Algorithmic Approach to English Pluralization" by Damian Conway:
# http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html
# Prepositions are used to solve things like
# "moth... | "-i-classical" : ["afreet", "afrit", "efreet"],
"-im-classical" : ["cherub", "goy", "seraph"],
"o-os" : ["albino", "archipelago", "armadillo", "commando", "ditto", "dynamo", "embryo", "fiasco", "generalissimo", "ghetto", "guano", "inferno", "jumbo", "lingo", "lumbago", "magneto", "manifes... | "a-ata-classical" : ["anathema", "bema", "carcinoma", "charisma", "diploma", "dogma", "drama", "edema", "enema", "enigma", "gumma", "lemma", "lymphoma", "magma", "melisma", "miasma", "oedema", "sarcoma", "schema", "soma", "stigma", "stoma", "trauma"],
"is-ides-classical" : ["clitoris", "iris"],
"us-i-c... | random_line_split |
plural.py | # PLURAL - last updated for NodeBox 1rc7
# Author: Tom De Smedt <tomdesmedt@organisms.be>
# See LICENSE.txt for details.
# Based on "An Algorithmic Approach to English Pluralization" by Damian Conway:
# http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html
# Prepositions are used to solve things like
# "moth... |
return word
#print plural("part-of-speech")
#print plural("child")
#print plural("dog's")
#print plural("wolf")
#print plural("bear")
#print plural("kitchen knife")
#print plural("octopus", classical=True)
#print plural("matrix", classical=True)
#print plural("matrix", classical=False)
#print plural("my", p... | if word in plural_categories[category] and (not classic or (classic and classical)):
if re.search(suffix, word) is not None:
return re.sub(suffix, inflection, word) | conditional_block |
plural.py | # PLURAL - last updated for NodeBox 1rc7
# Author: Tom De Smedt <tomdesmedt@organisms.be>
# See LICENSE.txt for details.
# Based on "An Algorithmic Approach to English Pluralization" by Damian Conway:
# http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html
# Prepositions are used to solve things like
# "moth... | return plural(word, ADJECTIVE, classical, custom) | identifier_body | |
hat.ts | import type { ColorGroup } from '../static-types';
export const hat: ColorGroup = {
black: 'rgba(38, 46, 51, 1)',
blue01: 'rgba(101, 201, 255, 1)',
blue02: 'rgba(81, 153, 228, 1)',
blue03: 'rgba(37, 85, 124, 1)',
gray01: 'rgba(229, 229, 229, 1)',
gray02: 'rgba(146, 149, 152, 1)',
heather: 'rgba(60, 79, 9... | }; | random_line_split | |
runtests.py | #!/usr/bin/env python
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from argparse import ArgumentParser
import django
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, TransactionTestCas... |
def bisect_tests(bisection_label, options, test_labels):
state = setup(options.verbosity, test_labels)
test_labels = test_labels or get_installed()
print('***** Bisecting test suite: %s' % ' '.join(test_labels))
# Make sure the bisection point isn't in the test list
# Also remove tests that ne... | state = setup(verbosity, test_labels)
extra_tests = []
# Run the test suite, including the extra validation tests.
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.runner.DiscoverRunner'
TestRunner = get_runner(settings)
test_runner = TestRunner(
verbosi... | identifier_body |
runtests.py | #!/usr/bin/env python
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from argparse import ArgumentParser
import django
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, TransactionTestCas... | teardown(state)
if __name__ == "__main__":
parser = ArgumentParser(description="Run the Django test suite.")
parser.add_argument('modules', nargs='*', metavar='module',
help='Optional path(s) to test modules; e.g. "i18n" or '
'"i18n.tests.TranslationTests.test_lazy_objects".')
par... | if failures:
print('***** Found problem pair with %s' % label)
return
print('***** No problem pair found') | random_line_split |
runtests.py | #!/usr/bin/env python
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from argparse import ArgumentParser
import django
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, TransactionTestCas... | sys.exit(bool(failures)) | conditional_block | |
runtests.py | #!/usr/bin/env python
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from argparse import ArgumentParser
import django
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, TransactionTestCas... | (paired_test, options, test_labels):
state = setup(options.verbosity, test_labels)
test_labels = test_labels or get_installed()
print('***** Trying paired execution')
# Make sure the constant member of the pair isn't in the test list
# Also remove tests that need to be run in specific combination... | paired_tests | identifier_name |
validitystate.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ValidityStateBinding;
use dom::bindings::codegen::Bindings::ValidityStateBin... | state: ValidityStatus::Valid
}
}
pub fn new(window: &Window, element: &Element) -> Root<ValidityState> {
reflect_dom_object(box ValidityState::new_inherited(element),
window,
ValidityStateBinding::Wrap)
}
}
impl ValidityStat... | impl ValidityState {
fn new_inherited(element: &Element) -> ValidityState {
ValidityState {
reflector_: Reflector::new(),
element: JS::from_ref(element), | random_line_split |
validitystate.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ValidityStateBinding;
use dom::bindings::codegen::Bindings::ValidityStateBin... |
// https://html.spec.whatwg.org/multipage/#dom-validitystate-valid
fn Valid(&self) -> bool {
false
}
}
| {
false
} | identifier_body |
validitystate.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ValidityStateBinding;
use dom::bindings::codegen::Bindings::ValidityStateBin... | (&self) -> bool {
false
}
// https://html.spec.whatwg.org/multipage/#dom-validitystate-typemismatch
fn TypeMismatch(&self) -> bool {
false
}
// https://html.spec.whatwg.org/multipage/#dom-validitystate-patternmismatch
fn PatternMismatch(&self) -> bool {
false
}
... | ValueMissing | identifier_name |
udt.rs | extern crate cassandra;
use cassandra::*;
fn main() {
let mut cluster = Cluster::new();
cluster.set_contact_points("127.0.0.1").unwrap();
match cluster.connect() {
Ok(ref mut session) => {
let schema = session.get_schema();
session.execute(
"CREATE KEYSPACE examples WITH replic... | match field.1.get_type() {
ValueType::VARCHAR => println!("{}", try!(field.1.get_string())),
ValueType::INT => println!("{}", try!(field.1.get_int32())),
ValueType::SET =>
for phone_numbers in try!(fi... | for field in fields_iter {
println!("{}", field.0); | random_line_split |
udt.rs | extern crate cassandra;
use cassandra::*;
fn main() |
fn select_from_udt(session: &Session) -> Result<(), CassandraError> {
let query = "SELECT * FROM examples.udt";
let statement = Statement::new(query, 0);
let mut future = session.execute_statement(&statement);
match future.wait() {
Err(err) => panic!("Error: {:?}", err),
Ok(result) => ... | {
let mut cluster = Cluster::new();
cluster.set_contact_points("127.0.0.1").unwrap();
match cluster.connect() {
Ok(ref mut session) => {
let schema = session.get_schema();
session.execute(
"CREATE KEYSPACE examples WITH replication = \
{ 'class': 'SimpleStrategy', 'replic... | identifier_body |
udt.rs | extern crate cassandra;
use cassandra::*;
fn main() {
let mut cluster = Cluster::new();
cluster.set_contact_points("127.0.0.1").unwrap();
match cluster.connect() {
Ok(ref mut session) => {
let schema = session.get_schema();
session.execute(
"CREATE KEYSPACE examples WITH replic... | (session: &Session) -> Result<(), CassandraError> {
let query = "INSERT INTO examples.udt (id, address) VALUES (?, ?)";
let mut statement = Statement::new(query, 2);
let uuid_gen = UuidGen::new();
let udt_address = schema.get_udt("examples", "address");
let udt_phone = cass_keyspace_meta_user_type_b... | insert_into_udt | identifier_name |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... | ,
startAutoplay () {
if (this.autoplay) {
this.autoplayInterval = setInterval(() => {
this.dir === 'ltr' ? this.goPrev() : this.goNext()
}, this.autoplayTimeout)
}
}
},
mounted () {
if (!process.server && this.au... | {
if (this.autoplayInterval) {
this.autoplayInterval = clearInterval(this.autoplayInterval)
}
} | identifier_body |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... | }
},
mounted () {
if (!process.server && this.autoplayHoverPause) {
this.$el.addEventListener('mouseenter', this.pauseAutoplay)
this.$el.addEventListener('mouseleave', this.startAutoplay)
this.startAutoplay()
}
}
}
export default autoplay | } | random_line_split |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... |
},
startAutoplay () {
if (this.autoplay) {
this.autoplayInterval = setInterval(() => {
this.dir === 'ltr' ? this.goPrev() : this.goNext()
}, this.autoplayTimeout)
}
}
},
mounted () {
if (!process.server ... | {
this.autoplayInterval = clearInterval(this.autoplayInterval)
} | conditional_block |
autoplay.js | const autoplay = {
props: {
/**
* Flag to enable autoplay
*/
autoplay: {
type: Boolean,
default: false
},
/**
* Time elapsed before next slide
*/
autoplayTimeout: {
type: Number,
default: 2000... | () {
if (!process.server) {
this.pauseAutoplay()
this.$el.removeEventListener('mouseenter', this.pauseAutoplay)
this.$el.removeEventListener('mouseleave', this.startAutoplay)
}
},
methods: {
pauseAutoplay () {
if (this.autoplayInterval) {... | destroyed | identifier_name |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... | return
try:
session.messagesReceived(messages)
except Exception:
log.msg('jsonp_send: messagesReceived() failed')
session.close()
self.write('Message handler failed.')
self.set_status(500)
return
self.write('... | self.write("Broken JSON encoding.")
self.set_status(500) | random_line_split |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... |
class JSONPSendHandler(pollingbase.PollingTransportBase):
def post(self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None:
self.set_status(404)
return
... | msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))
self.set_header('Content-Type',
'application/javascript; charset=UTF-8')
self.set_header('Content-Length', len(msg))
# FIXME
self.set_header('Etag', 'dummy')
self.write(msg)
self... | identifier_body |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... |
#data = self.request.body.decode('utf-8')
data = self.request.body
ctype = self.request.headers.get('Content-Type', '').lower()
if ctype == 'application/x-www-form-urlencoded':
if not data.startswith('d='):
log.msg('jsonp_send: Invalid payload.')
... | self.set_status(404)
return | conditional_block |
jsonp.py | import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id): ... | (self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None:
self.set_status(404)
return
#data = self.request.body.decode('utf-8')
data = self.request.... | post | identifier_name |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class | {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public costsHealth: boolean;
public elite: boolean;
public health: number;
public hideStats: boolean;
public id: string;
public name: string;
public mult... | CardDef | identifier_name |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class CardDef {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public c... |
}
| {
this.attack = props.attack || 0;
this.armor = props.armor || 0;
this.cardClass = cleanEnum(props.cardClass, CardClass) as CardClass;
this.cardSet = cleanEnum(props.set, CardSet) as CardSet;
this.cost = props.cost || 0;
this.costsHealth = props.costsHealth || false;
this.elite = props.elite || false;
t... | identifier_body |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class CardDef {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public c... | public name: string;
public multiClassGroup: MultiClassGroup;
public rarity: Rarity;
public race: Race;
public silenced: boolean;
public text: string;
public type: CardType;
constructor(props: any) {
this.attack = props.attack || 0;
this.armor = props.armor || 0;
this.cardClass = cleanEnum(props.cardClas... | random_line_split | |
CardDef.ts | import {CardClass, CardSet, CardType, MultiClassGroup, Race, Rarity} from "./Enums";
import {cleanEnum} from "./helpers";
export default class CardDef {
public attack: number;
public armor: number;
public cardClass: CardClass;
public cardSet: CardSet;
public collectionText: string;
public cost: number;
public c... |
this.collectionText = props.collectionText || "";
this.text = props.text || "";
}
}
| {
// Hero health gem is Armor
this.health = props.armor;
} | conditional_block |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... | (x, weights, biases):
# Prepare data shape to match `rnn` function requirements
# Current data input shape: (batch_size, timesteps, n_input)
# Required shape: 'timesteps' tensors list of shape (batch_size, n_input)
# Unstack to get a list of 'timesteps' tensors of shape (batch_size,
# n_input)
... | RNN | identifier_name |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... |
logits = RNN(X, weights, biases)
prediction = tf.nn.softmax(logits)
# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate... | x = tf.unstack(x, timesteps, 1)
# Define a lstm cell with tensorflow
lstm_cell = rnn.BasicLSTMCell(num_hidden, forget_bias=1.0)
# Get lstm cell output
outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32)
# Linear activation, using rnn inner loop last output
return tf.matmul(output... | identifier_body |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... |
print("Optimization Finished!")
print(loss_group)
print(epoch_group)
plt.plot(epoch_group, loss_group)
plt.show()
end_time = time.time()
time_dif = end_time - start_time
print("Time usage: " + str(timedelta(seconds=int(round(time_dif)))))
# Calculate accuracy for 128 mnist test im... | loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
Y: batch_y})
loss_group.append(loss)
epoch_group.append(step)
print("Step " + str(step) + ", Minibatch Loss= " +
"{:.4f}".format(loss) +... | conditional_block |
LSTM2.py | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... | accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()
loss_group = []
epoch_group = []
# Start training
with tf.Session() as sess:
# Run the initializer
sess.run(init)
start_time = time.time()
... | optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Evaluate model (with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1)) | random_line_split |
test_connection.ts | /**
* super-orm tests
*
* @author Zongmin Lei <leizongmin@gmail.com>
*/
import orm = require("../");
import utils = require("./utils");
describe("Connection", function () {
it("getConnection() support promise", async function () {
const conn = orm.createConnection({
connections: [ utils.getConnectio... | const sql = conn.format("SELECT * FROM ::table WHERE id=:id", {
table: "blog_contents",
id: 2,
});
console.log(sql);
const ret = await conn.query(sql);
console.log(ret);
}
{
const sql = conn.format("SELECT * FROM ?? WHERE id=?", [ "blog_contents", 2 ]);
... | }
{ | random_line_split |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... |
file_path = file_path.split(os.sep)
file_path[-1] = 'transliterated_' + file_path[-1]
file_path = os.sep.join(file_path)
with io.open(file_path, 'w', encoding='utf8') as file:
file.write('\n'.join(new_lines))
print(file_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='C... | else:
new_line += ch
new_lines.append(new_line) | random_line_split |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... | , v in zip(domain, range) }
with io.open(file_path, 'r', encoding='utf8') as file:
lines = file.readlines()
new_lines = list()
for line in lines:
new_line = ''
for ch in line.strip():
if ch in d.keys():
new_line += d[ch]
else:
new_line += ch
new_lines.append(new_line)... | d = { u:v for u | identifier_name |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... | = file_path.split(os.sep)
file_path[-1] = 'transliterated_' + file_path[-1]
file_path = os.sep.join(file_path)
with io.open(file_path, 'w', encoding='utf8') as file:
file.write('\n'.join(new_lines))
print(file_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Convert from/t... |
file_path | conditional_block |
transliteration.py | # -*- coding: utf-8 -*-
import os
import io
import sys
import argparse
ARABIC_LETTERS = [
u'ء', u'آ', u'أ', u'ؤ', u'إ',
u'ئ', u'ا', u'ب', u'ة', u'ت',
u'ث', u'ج', u'ح', u'خ', u'د',
u'ذ', u'ر', u'ز', u'س', u'ش',
u'ص', u'ض', u'ط', u'ظ', u'ع',
u'غ', u'ـ', u'ف', u'ق', u'ك',
u'ل', u'م', u'ن', u'ه', u'و',
u'... | rse.ArgumentParser(description='Convert from/to Buckwalter transliteration')
parser.add_argument('-fp', '--file-path', help='File path to be transliterated', required=True)
parser.add_argument('-tbw', '--to-buckwalter', help='To Buckwalter transliteration from Arabic', required=False, default='False', choices=['Tru... | with io.open(file_path, 'r', encoding='utf8') as file:
lines = file.readlines()
new_lines = list()
for line in lines:
new_line = ''
for ch in line.strip():
if ch in d.keys():
new_line += d[ch]
else:
new_line += ch
new_lines.append(new_line)
file_path = file_path.spli... | identifier_body |
urls.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
urlpatterns = patterns('openstack_dashboard.dashboards.admin.images.views',
url(r'^images/$', views.IndexView.as_view(), name='index'),
url(r'^create/$', views.CreateView.as_view(), name='create'),
url(r'^(?P<image_id>[^/]+)/update/$',
views.UpdateView.as_view(), name='update'),
url(r'^(?P<ima... |
from django.conf.urls import patterns # noqa
from django.conf.urls import url # noqa
from openstack_dashboard.dashboards.admin.images import views | random_line_split |
codeFixAddVoidToPromise_all.ts | /// <reference path='fourslash.ts' />
// @target: esnext
| ////const p1 = new Promise(resolve => resolve());
////const p2 = new Promise<number>(resolve => resolve());
////const p3 = new Promise<number | string>(resolve => resolve());
////const p4 = new Promise<{ x: number } & { y: string }>(resolve => resolve());
verify.codeFixAll({
fixId: "addVoidToPromise",
f... | // @lib: es2015
// @strict: true
| random_line_split |
consts.ts | export const Signatures = {
FileMagic: 0x9aa2d903,
Sig2Kdbx: 0xb54bfb67,
Sig2Kdb: 0xb54bfb65
} as const;
export const ErrorCodes = {
NotImplemented: 'NotImplemented',
InvalidArg: 'InvalidArg',
BadSignature: 'BadSignature',
InvalidVersion: 'InvalidVersion',
Unsupported: 'Unsupported',
... | Tux: 62,
Feather: 63,
Apple: 64,
Wiki: 65,
Money: 66,
Certificate: 67,
BlackBerry: 68
} as const; | Star: 61, | random_line_split |
index.d.ts | // Type definitions for Numeral.js
// Project: https://github.com/adamwdraper/Numeral-js
// Definitions by: Vincent Bortone <https://github.com/vbortone>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// http://numeraljs.com/#locales
interface NumeralJSLocale {
delimiters: {
thousands: string;
... | },
format: (value: any, format: string, roundingFunction: RoundingFunction) => string,
unformat: (value: string) => number
}
type RegisterType = 'format' | 'locale';
// http://numeraljs.com/#use-it
interface Numeral {
(value?: any): Numeral;
version: string;
isNumeral: boolean;
/**
* This function sets the ... | unformat: RegExp, | random_line_split |
editor.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is dis... | .then(response => {
customjs = response.javascript;
return Templates.render('core_reportbuilder/custom_report', response);
})
.then((html, js) => {
return Templates.replaceNodeContents(reportElement, html, js + c... | const toggledEditMode = toggleEditViewMode.dataset.editMode !== "1";
let customjs = '';
getReport(reportElement.dataset.reportId, toggledEditMode) | random_line_split |
editor.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is dis... |
});
initialized = true;
};
| {
event.preventDefault();
const pendingPromise = new Pending('core_reportbuilder/reports:get');
const toggledEditMode = toggleEditViewMode.dataset.editMode !== "1";
let customjs = '';
getReport(reportElement.dataset.reportId, toggledEditMode)
... | conditional_block |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... | except Exception as e:
raise e
if current_uptime == before_uptime:
raise Exception("uptime has not changed")
self.do_until_success_or_timeout(check_uptime, reboot_timeout, what_desc="reboot uptime check success")
# reset ... | random_line_split | |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... | (self, tmp=None, task_vars=None):
self._supports_check_mode = True
self._supports_async = True
if self._play_context.check_mode:
return dict(changed=True, elapsed=0, rebooted=True)
if task_vars is None:
task_vars = dict()
result = super(ActionModule, s... | run | identifier_name |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... |
time.sleep(fail_sleep)
raise TimedOutException("timed out waiting for %s: %s" % (what_desc, exc))
def run(self, tmp=None, task_vars=None):
self._supports_check_mode = True
self._supports_async = True
if self._play_context.check_mode:
return dict(chang... | display.debug("win_reboot: %s fail (expected), retrying in %d seconds..." % (what_desc, fail_sleep)) | conditional_block |
win_reboot.py | # (c) 2016, Matt Davis <mdavis@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... | self._supports_check_mode = True
self._supports_async = True
if self._play_context.check_mode:
return dict(changed=True, elapsed=0, rebooted=True)
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
if result... | identifier_body | |
angular-animate-stylers.js | angular.module('ngAnimateStylers', ['ngAnimateSequence'])
.config(['$$animateStylerProvider', function($$animateStylerProvider)
{
//JQUERY
$$animateStylerProvider.register('jQuery', function() {
return function(element, pre, duration, delay) {
delay = delay || 0;
element.css(pre);
... |
return function(post, done) {
styler.fromTo(
element,
(duration || 0)/1000,
pre || { },
angular.extend( post, {onComplete:done, delay: (delay || 0)/1000} )
);
}
};
});
}]);
| {
throw new Error("GSAP TweenMax or TweenLite is not defined for use within $$animationStylerProvider.");
} | conditional_block |
angular-animate-stylers.js | angular.module('ngAnimateStylers', ['ngAnimateSequence'])
.config(['$$animateStylerProvider', function($$animateStylerProvider)
{
//JQUERY
$$animateStylerProvider.register('jQuery', function() {
return function(element, pre, duration, delay) {
delay = delay || 0;
element.css(pre);
... | return function(element, pre, duration, delay) {
delay = delay || 0;
duration = duration || 1000;
element.css(pre);
return function(post, done) {
var animation = element[0].animate({ 'border-width' : '100px'}, 5000);
//player.onfinish = done;
}
};
... |
//NOT WORKING
$$animateStylerProvider.register('webAnimations', function() { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.