function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def cleanup_the_mock(self):
self.patch.stop() | benjamin-hodgson/poll | [
10,
2,
10,
2,
1438953343
] |
def function_to_break(self):
self.x += 1
raise self.expected_exception | benjamin-hodgson/poll | [
10,
2,
10,
2,
1438953343
] |
def given_the_circuit_was_half_broken_and_the_function_failed_again(self):
self.x = 0
self.patch = mock.patch('time.perf_counter', return_value=0)
self.mock = self.patch.start()
contexts.catch(self.function_to_break)
contexts.catch(self.function_to_break)
contexts.catch(self.function_to_break)
self.mock.return_value = 1.1
contexts.catch(self.function_to_break) | benjamin-hodgson/poll | [
10,
2,
10,
2,
1438953343
] |
def it_should_not_call_the_function(self):
assert self.x == 4 | benjamin-hodgson/poll | [
10,
2,
10,
2,
1438953343
] |
def cleanup_the_mock(self):
self.patch.stop() | benjamin-hodgson/poll | [
10,
2,
10,
2,
1438953343
] |
def __init__(self, situation, name, suffix=None):
'''Actions subclass nothing, but require situations to hold them'''
# a situation is like "outdoors", "indoors", or "fighting"
self._situation = situation
self._game = None if situation is None else situation.game()
# "name" is a string for the action & "suffix" is extra information. e.g. Move, North
self._name = name
self._suffix = suffix | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def name(self):
'''getting the name of this action'''
return self._name | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def suffix(self):
'''getting the suffix of this action name
(e.g. "Move" might be the name, and "West" might be the suffix.)
'''
return self._suffix | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def game(self):
'''getting the current subclass of game'''
return self._game | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def situation(self):
'''getting the situation this action is related to'''
return self._situation | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def info(self):
'''placeholder: generic return a string describing this action'''
return '' | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def always_known(self):
'''Is this action Always Known in this game?'''
return False | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def can_do(self):
'''Each action will have to define a method that determines
if the action is currently valid or not.
'''
raise Exception("Not Implemented") | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def do(self):
'''Each Action will have to define a method that will
actually perform some changes to the Game or UI
'''
raise Exception("Not Implemented") | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def execute(self):
'''Convience method, checks if the action can be performed,
if so it does it.
'''
if not self.can_do():
return | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def __str__(self):
if self.suffix() is None:
return self.name() | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def __init__(self, situtation):
Action.__init__(self, situtation, 'Quit') | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def can_do(self):
'''You can always exit the program.
Break this functionality, and your users will hate you.
'''
return True | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def do(self):
'''In this simple implementation, no window pops up
to ask you if you're sure or if you want to save the game first.
'''
sys.exit() | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def __init__(self, situtation):
Action.__init__(self, situtation, 'Do Nothing') | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def can_do(self):
'''Doing nothing is always an option.'''
return True | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def do(self):
'''Sometimes the best thing you can do is nothing.'''
pass | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def __setitem__(self, key, value):
'''Simple type-checking for the Action Key Dict'''
if not isinstance(key, str):
raise TypeError('The action keys key must be a string.')
if not isinstance(value, int):
raise TypeError('The action keys value must be an integer.') | theJollySin/pytextgame | [
1,
1,
1,
2,
1441841366
] |
def print_phase_header(message):
global COUNTER;
print ("\n[" + str("%02d" % int(COUNTER)) + "] >>> " + message)
COUNTER += 1; | gbowerman/azurerm | [
43,
30,
43,
4,
1453075796
] |
def print_phase_message(message):
time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print (str(time_stamp) + ": " + message) | gbowerman/azurerm | [
43,
30,
43,
4,
1453075796
] |
def uploadCallback(current, total):
if (current != None):
print_phase_message('{0:2,f}/{1:2,.0f} MB'.format(current,total/1024/1024)) | gbowerman/azurerm | [
43,
30,
43,
4,
1453075796
] |
def create_widget(self):
"""Create the underlying widget."""
d = self.declaration
self.widget = GridLayout(self.get_context(), None, d.style) | codelv/enaml-native | [
250,
22,
250,
4,
1495306152
] |
def set_orientation(self, orientation):
self.widget.setOrientation(0 if orientation == "horizontal" else 1) | codelv/enaml-native | [
250,
22,
250,
4,
1495306152
] |
def set_columns(self, columns):
self.widget.setColumnCount(columns) | codelv/enaml-native | [
250,
22,
250,
4,
1495306152
] |
def set_rows(self, rows):
self.widget.setRowCount(rows) | codelv/enaml-native | [
250,
22,
250,
4,
1495306152
] |
def main():
args = parse_args()
phenotypes = _create_genetest_phenotypes(
args.grs_filename, args.phenotypes_filename,
args.phenotypes_sample_column, args.phenotypes_separator
)
if args.outcome_type == "continuous":
y_g_test = "linear"
elif args.outcome_type == "discrete":
y_g_test = "logistic"
else:
raise ValueError(
"Expected outcome type to be 'discrete' or 'continuous'."
)
if args.exposure_type == "continuous":
x_g_test = "linear"
elif args.exposure_type == "discrete":
x_g_test = "logistic"
else:
raise ValueError(
"Expected exposure type to be 'discrete' or 'continuous'."
)
n_iter = 1000
logger.info(
"Computing MR estimates using the ratio method. Bootstrapping "
"standard errors can take some time."
)
beta, low, high = mr_effect_estimate(
phenotypes, args.outcome, args.exposure, n_iter, y_g_test, x_g_test
)
print("The estimated beta of the exposure on the outcome and its 95% CI "
"(computed using the empirical " "bootstrap) are:\n")
print("{:.4g} ({:.4g}, {:.4g})".format(beta, low, high)) | legaultmarc/grstools | [
4,
2,
4,
6,
1485209970
] |
def __init__(
self,
signal_hound: SignalHound_USB_SA124B,
frequency=None,
Navg=1,
delay=0.1,
prepare_for_each_point=False,
prepare_function=None,
prepare_function_kwargs: dict = {} | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def acquire_data_point(self, **kw):
if self.prepare_for_each_point:
self.prepare()
time.sleep(self.delay)
if version.parse(qc.__version__) < version.parse('0.1.11'):
return self.SH.get_power_at_freq(Navg=self.Navg)
else:
self.SH.avg(self.Navg)
return self.SH.power() | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def finish(self, **kw):
self.SH.abort() | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def __init__(
self,
signal_hound: SignalHound_USB_SA124B,
Navg=1,
delay=0.1,
**kw | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def acquire_data_point(self, **kw):
frequency = self.swp.pop()
self.SH.set('frequency', frequency)
self.SH.prepare_for_measurement()
time.sleep(self.delay)
return self.SH.get_power_at_freq(Navg=self.Navg) | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def prepare(self, sweep_points):
self.swp = list(sweep_points)
# self.SH.prepare_for_measurement() | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def __init__(
self,
frequency,
QI_amp_ratio,
IQ_phase,
SH: SignalHound_USB_SA124B,
I_ch, Q_ch,
station,
Navg=1,
delay=0.1,
f_mod=10e6,
verbose=False,
**kw):
super(SH_mixer_skewness_det, self).__init__()
self.SH = SH
self.frequency = frequency
self.name = 'SignalHound_mixer_skewness_det'
self.value_names = ['Power']
self.value_units = ['dBm']
self.delay = delay
self.SH.frequency.set(frequency) # Accepts input in Hz
self.Navg = Navg
self.QI_amp_ratio = QI_amp_ratio
self.IQ_phase = IQ_phase
self.pulsar = station.pulsar
self.f_mod = f_mod
self.I_ch = I_ch
self.Q_ch = Q_ch
self.verbose = verbose | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def generate_awg_seq(self, QI_ratio, skewness, f_mod):
SSB_modulation_el = element.Element('SSB_modulation_el',
pulsar=self.pulsar)
cos_pulse = pulse.CosPulse(channel=self.I_ch, name='cos_pulse')
sin_pulse = pulse.CosPulse(channel=self.Q_ch, name='sin_pulse')
SSB_modulation_el.add(pulse.cp(cos_pulse, name='cos_pulse',
frequency=f_mod, amplitude=0.15,
length=1e-6, phase=0))
SSB_modulation_el.add(pulse.cp(sin_pulse, name='sin_pulse',
frequency=f_mod, amplitude=0.15 *
QI_ratio,
length=1e-6, phase=90 + skewness))
seq = sequence.Sequence('Sideband_modulation_seq')
seq.append(name='SSB_modulation_el', wfname='SSB_modulation_el',
trigger_wait=False)
self.pulsar.program_awgs(seq, SSB_modulation_el) | DiCarloLab-Delft/PycQED_py3 | [
51,
39,
51,
31,
1451987534
] |
def __init__(self, Map, CostPrior, RewardPrior, CostParams, RewardParams, Capacity=-1, Minimum=0, SoftmaxChoice=True, SoftmaxAction=True, choiceTau=1, actionTau=0.01, CNull=0, RNull=0, Restrict=False):
"""
Agent class.
Create an agent with a set of costs and rewards.
If sampling parameters are numbers rather than lists the constructor fixes this automatically.
Args:
Map (Map): A map object.
CostPrior (str): String indicating prior's name. Run Agent.Priors() to see list
RewardPrior (str): String indicating Reward prior's name. Run Agent.Priors() to see list
CostParams (list): List of parameters for sampling costs.
RewardParams (list): List of parameters for sampling rewards.
Capacity (int): Number of objects agent can carry. If set to -1 Planner adjusts
it to the total number of objects in the map.
Minimum (int): Minimum number of objects must take before leaving.
SoftmaxChoice (bool): Does the agent select goals optimally?
SoftmaxAction (bool): Does the agent act upong goals optimally?
choiceTau (float): Softmax parameter for goal selection.
actionTau (float): Softmax parameter for action planning.
CNull (float): Probability that a terrain has no cost.
RNull (float): Probability that an object has no reward
Restrict (bool): When set to true the cost samples make the first terrain
always less costly than the rest.
"""
# Check that priors exist.
Priors = self.Priors(False)
if CostPrior in Priors:
self.CostPrior = CostPrior
else:
print("WARNING: Cost prior not found! Setting to uniform")
self.CostPrior = "ScaledUniform"
if RewardPrior in Priors:
self.RewardPrior = RewardPrior
else:
print("WARNING; Reward prior not found! Setting to uniform")
self.RewardPrior = "ScaledUniform"
self.Restrict = Restrict
self.CostDimensions = len(np.unique(Map.StateTypes))
# Get dimensions over which you'll build your simplex
self.RewardDimensions = len(set(Map.ObjectTypes))
self.Capacity = Capacity
self.Minimum = Minimum
self.SoftmaxChoice = SoftmaxChoice
self.SoftmaxAction = SoftmaxAction
if SoftmaxAction:
self.actionTau = actionTau
else:
self.actionTau = None
if SoftmaxChoice:
self.choiceTau = choiceTau
else:
self.choiceTau = None
if self.RewardDimensions == 0:
print("WARNING: No rewards on map. AGENT-001")
if isinstance(CostParams, list):
self.CostParams = CostParams
else:
self.CostParams = [CostParams]
if isinstance(RewardParams, list):
self.RewardParams = RewardParams
else:
self.RewardParams = [RewardParams]
self.CNull = CNull
self.RNull = RNull
self.ResampleCosts() # Generate random cost of map
self.ResampleRewards() # Generate random rewards for objects | julianje/Bishop | [
12,
5,
12,
3,
1424995890
] |
def ResampleCosts(self):
"""
Reset agent's costs.
"""
# Resample the agent's competence
self.costs = self.Sample(
self.CostDimensions, self.CostParams, Kind=self.CostPrior)
self.costs = [
0 if random.random() <= self.CNull else i for i in self.costs] | julianje/Bishop | [
12,
5,
12,
3,
1424995890
] |
def Sample(self, dimensions, SamplingParam, Kind):
"""
Generate a sample from some distribution
Args:
dimensions (int): Number of dimensions
SamplingParam (list): Parameter to use on distribution
Kind (str): Name of distribution
Returns:
None
"""
if (Kind == "Simplex"):
# Output: Simplex sample of length 'dimensions' (Adds to 1)
sample = -np.log(np.random.rand(dimensions))
return sample / sum(sample)
if (Kind == "IntegerUniform"):
return np.round(np.random.rand(dimensions) * SamplingParam[0])
if (Kind == "ScaledUniform"):
return np.random.rand(dimensions) * SamplingParam[0]
if (Kind == "Gaussian"):
return np.random.normal(SamplingParam[0], SamplingParam[1], dimensions)
if (Kind == "Exponential"):
return [np.random.exponential(SamplingParam[0]) for j in range(dimensions)]
if (Kind == "Constant"):
return [0.5 * SamplingParam[0]] * dimensions
if (Kind == "Beta"):
return [np.random.beta(SamplingParam[0], SamplingParam[1]) for i in range(dimensions)]
if (Kind == "Empirical"):
return [random.choice(SamplingParam) for i in range(dimensions)]
if (Kind == "PartialUniform"):
# Generate random samples and scale them by the first parameter.
samples = np.random.rand(dimensions) * SamplingParam[0]
# Now iterate over the sampling parameters and push in static
# values.
for i in range(1, len(SamplingParam)):
if SamplingParam[i] != -1:
samples[i - 1] = SamplingParam[i]
return samples
if (Kind == "PartialGaussian"):
# Generate random gaussian samples.
samples = np.random.normal(
SamplingParam[0], SamplingParam[1], dimensions)
# Now iterate over the sampling parameters and push in static
# values.
for i in range(2, len(SamplingParam)):
if SamplingParam[i] != -1:
samples[i - 2] = SamplingParam[i]
samples = [0 if i < 0 else i for i in samples]
return samples | julianje/Bishop | [
12,
5,
12,
3,
1424995890
] |
def GetSamplingParameters(self):
"""
Return cost and reward sampling parameters, respectively
"""
return [self.CostParams, self.RewardParams] | julianje/Bishop | [
12,
5,
12,
3,
1424995890
] |
def SetRewardSamplingParams(self, samplingparams):
"""
Set sampling parameters for costs
"""
if len(samplingparams) != len(self.RewardParams):
print("Vector of parameters is not the right size")
else:
self.RewardParams = samplingparams | julianje/Bishop | [
12,
5,
12,
3,
1424995890
] |
def plateau(array, threshold):
"""Find plateaus in an array, i.e continuous regions that exceed threshold
Given an array of numbers, return a 2d array such that
out[:,0] marks the indices where the array crosses threshold from
below, and out[:,1] marks the next time the array crosses that
same threshold from below.
Inputs:
array (1d numpy array)
threshold (float or array) If threshold is a single number, any point
above that value is above threshold. If it's an array,
it must have the same length as the first argument, and
an array[i] > threshold[i] to be included as a plateau
Returns:
Numpy 2d array with 2 columns.
Notes:
To find the length of the plateaus, use
out[:,1] - out[:,0]
To find the length of the largest plateau, use
np.max(out[:,1] - out[:,0])
The algorithm fails if a value is exactly equal to the threshold.
To guard against this, we add a very small amount to threshold
to ensure floating point arithmetic prevents two numbers being
exactly equal."""
arr = array.astype(np.float32)
arr = arr - threshold + 1e-12
arrPlus = np.roll(arr, 1)
#Location of changes from -ve to +ve (or vice versa)
#Last point is bogus , so we calculate it by hand
sgnChange = arr*arrPlus
#Roll around can't compute sign change for zeroth elt.
sgnChange[0] = +1
if arr[0] > 0:
sgnChange[0] = -1
loc = np.where(sgnChange < 0)[0]
if np.fmod( len(loc), 2) != 0:
loc.resize( (len(loc)+1))
loc[-1] = len(arr)
return loc | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def outlierRemoval(time, flux):
fluxDetrended = medianDetrend(flux, 3)
out1 = plateau(fluxDetrended, 5 * np.std(fluxDetrended))
out2 = plateau(-fluxDetrended, 5 * np.std(fluxDetrended))
if out1 == [] and out2 == []:
singleOutlierIndices = []
else:
outliers = np.append(out1, out2).reshape(-1,2)
# Only want groups of one outlier, since > 1 may be transit points
singleOutlierIndices = np.sort(outliers[(outliers[:,1] - outliers[:,0] == 1)][:,0])
# Check periodicity of outliers, with PRECISION of 0.0205 days
# 0.0205 days = 29.52 minutes = ~length of long cadence
precision = 0.0205
outlierTimes = time[singleOutlierIndices]
diffs = [outlierTimes[i+1] - outlierTimes[i] for i in range(0, len(outlierTimes)-1)]
diffs = [round(d, 5) for d in diffs]
if len(singleOutlierIndices) >= 4:
if len(set(diffs)) == len(diffs):
possibleTimes = np.array([])
else:
period = max(set(diffs), key = diffs.count) # period = most common difference
epoch = outlierTimes[diffs.index(period)]
possibleTimes = np.arange(epoch, outlierTimes[-1] + 0.5*period, period)
notOutliers = []
for i in range(len(outlierTimes)):
if np.any((abs(possibleTimes - outlierTimes[i]) < precision)):
notOutliers.append(i)
singleOutlierIndices = np.delete(singleOutlierIndices, notOutliers)
elif len(singleOutlierIndices) == 3:
if abs(diffs[0] - diffs[1]) < precision:
singleOutlierIndices = []
# Uncomment to see how the plotting algorithm worked for a lightcurve
# ----------------------------- PLOTTING ----------------------------- #
# plt.subplot(311)
# plt.scatter(time, flux, marker = '.', s = 1, color = 'k', alpha = 1)
# plt.scatter(time[singleOutlierIndices], flux[singleOutlierIndices],
# s = 30, marker = 'o', facecolors = 'none', edgecolors = 'r')
# plt.title('Original')
# plt.subplot(312)
# plt.scatter(time, fluxDetrended, marker = '.', s = 1, color = 'k', alpha = 1)
# plt.scatter(time[singleOutlierIndices], fluxDetrended[singleOutlierIndices],
# s = 30, marker = 'o', facecolors = 'none', edgecolors = 'r')
# x1, x2, y1, y2 = plt.axis()
# plt.hlines([-5*np.std(fluxDetrended), 5*np.std(fluxDetrended)], x1, x2,
# color = 'b', linestyles = 'dashed')
# plt.axis([x1, x2, y1, y2])
# plt.title('Detrended')
# plt.subplot(313)
# plt.scatter(np.delete(time, singleOutlierIndices), np.delete(flux, singleOutlierIndices),
# marker = '.', s = 1, color = 'k', alpha = 1)
# plt.title('Outliers removed: ' + str(len(singleOutlierIndices)))
# plt.show()
# -------------------------------------------------------------------- #
return np.delete(time, singleOutlierIndices), np.delete(flux, singleOutlierIndices) | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def medianDetrend(flux, binWidth):
halfNumPoints = binWidth // 2
medians = []
for i in range(len(flux)):
if i < halfNumPoints:
medians.append(np.median(flux[:i+halfNumPoints+1]))
elif i > len(flux) - halfNumPoints - 1:
medians.append(np.median(flux[i-halfNumPoints:]))
else:
medians.append(np.median(flux[i-halfNumPoints : i+halfNumPoints+1]))
return flux - medians | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def getPhase(time, flux, period, epoch, centerPhase = 0):
"""Get the phase of a lightcurve.
How it works using an example where epoch = 2, period = 3:
1. Subtract the epoch from all times [1, 2, 3, 4, 5, 6, 7] to get
[-1, 0, 1, 2, 3, 4, 5] then divide by the period [3] to get all time
values in phase values which gets you [-0.3, 0, 0.3, 0.6, 1, 1.3, 1.6]
2. Subtract the PHASE NUMBER (floor function) from each PHASE (date1)
which gets you [0.7, 0, 0.3, 0.6, 0, 0.3, 0.6]
3. Sort all the adjusted phases to get [0, 0, 0.3, 0.3, 0.6, 0.6, 0.7]
THERE WILL BE negative values in the beginning here, just not in this example
since no ex. time value divided by the period left a decimal less than 0.25
4. Sort the flux values in the same way the phases were sorted
Inputs:
time Time values of data. (IN DAYS)
flux Flux values of data.
period Period of transit.
epoch Epoch of transit.
centerPhase Which phase should be at the center.
Returns:
q1 Phase values. (IN HOURS)
f1 Flux values for each phase.
"""
epoch += centerPhase * period
date1 = (time - epoch) / period + 0.5
phi1 = ((date1) - np.floor(date1)) - 0.5
q1 = np.sort(phi1) * period * 24.
f1 = flux[np.argsort(phi1)]
return q1, f1 | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def fitModel(time, flux, guessDict, freeParPlanet, ferr = 0):
if not np.all(ferr): ferr = np.ones_like(flux)*1.E-5
freeParStar = ['rho']
# Make the fitting object according to guess dictionary
fitT = FitTransit()
fitT.add_guess_star(ld1 = 0, ld2 = 0)
fitT.add_guess_planet(period = guessDict['period'],
T0 = guessDict['T0'])
fitT.add_data(time = time, flux = flux, ferr = ferr)
fitT.free_parameters(freeParStar, freeParPlanet)
fitT.do_fit()
return fitT | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def do_bls_and_fit(time, flux, min_period, max_period):
S = clean_and_search.Search(time, flux + 1, np.ones_like(flux)*1.E-5)
S.do_bls2(min_period = min_period,
max_period = max_period,
min_duration_hours = 1.5,
max_duration_hours = 6.,
freq_step = 1.E-4,
doplot = False,
norm = False)
guessDict = {'period': S.periods[0],
'T0': S.epoch}
freeParPlanet = ['period', 'T0', 'rprs']
fitT = fitModel(time, flux, guessDict, freeParPlanet)
# Readability of output data
period = fitT.fitresultplanets['pnum0']['period']
epoch = fitT.fitresultplanets['pnum0']['T0']
k = fitT.fitresultplanets['pnum0']['rprs']
rho = fitT.fitresultstellar['rho']
duration = computeTransitDuration(period, rho, k)
if not duration:
duration = S.duration * 24
# Calculating transit depth significance
## fitT.transitmodel sometimes has a NaN value
sigma = computePointSigma(time, flux, fitT.transitmodel, period, epoch, duration)
depth = k ** 2
significance = depth / sigma
phase = getPhase(time, flux, period, epoch)[0]
nTransitPoints = np.sum((-duration * 0.5 < phase) & (phase < duration * 0.5))
SNR = significance * nTransitPoints**0.5
return SNR, period, epoch, duration, depth, fitT.transitmodel, S.f_1, S.convolved_bls | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def computePointSigma(time, flux, transitModel, period, epoch, duration):
t2, f2 = removeTransits(time, flux, period, epoch, duration)
mt2, mf2 = removeTransits(time, transitModel, period, epoch, duration)
return np.nanstd(f2 - mf2) | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def removeTransits(time, flux, period, epoch, duration):
halfDur = 0.5 * duration / 24.
bad = np.where(time < epoch - period + halfDur)[0]
for p in np.arange(epoch, time[-1] + period, period):
bad = np.append(bad, np.where((p - halfDur < time) & (time < p + halfDur))[0])
good = np.setxor1d(range(len(time)), bad)
return time[good], flux[good] | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def computeTransitDuration(period, rho, k):
b = 0.1 # Impact parameter (default value in ktransit)
G = 6.67384e-11 # Gravitational constant
P = period * 86400 # Period in seconds
stellarDensity = rho * 1000
rStarOverA = ((4 * np.pi**2) / (G * stellarDensity * P**2))**(1./3.)
cosI = b * rStarOverA
sinI = np.sqrt(1 - cosI**2)
coeff = rStarOverA * np.sqrt((1+k)**2 - b**2) / sinI
if coeff > 1:
return 0
else:
duration = (P / np.pi) * np.arcsin(coeff)
return duration / 3600 # Duration in hours | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def findSecondary(time, flux, period, epoch, duration):
t2, f2 = removeTransits(time, flux, period, epoch, duration)
minp, maxp = period - 0.1, period + 0.1
if t2[-1] - t2[0] == 0 or 1./maxp < 1./(t2[-1] - t2[0]):
return (np.nan,)*5
if minp < 0.5:
minp = 0.5
planetInfo = do_bls_and_fit(t2, f2, minp, maxp)
return (t2,) + planetInfo[0:4] + (planetInfo[5],) | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def computeOddEvenModels(time, flux, per, epo):
gdOdd = {'period': per * 2,
'T0': epo}
gdEven = {'period': per * 2,
'T0': epo + per}
freeParPlanet = ['rprs']
fitT_odd = fitModel(time, flux, gdOdd, freeParPlanet)
fitT_even = fitModel(time, flux, gdEven, freeParPlanet)
return fitT_odd, fitT_even | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def main(filename):
"""Fit a transit model to a lightcurve.
1. Remove outliers.
2. Detrend the data with a binwidth of 26 cadences. Since MAX_DURATION_HOURS = 6,
and 6 hours = ~13 cadences (ceiling of 12.245), detrending with a binwidth of double
this value will preserve all events with a duration of 13 cadences or less.
3. Create an "S" object. (???) [1 is added to the flux to avoid a division by zero error]
4. Run the BLS algorithm and Tom's transit fitting algorithm. Since the BLS can lock
on to an incorrect, shorter period event, I run it on four different minimum periods,
chosen somewhat arbitrarily. These results go into a dictionary sorted by the
calculated SNR of each fit, and the parameters which give the maximum SNR are used.
5. Plot the original lightcurve, the BLS statistics from its minimum to maximum period,
and a phased lightcurve.
6. Save the plot, and return a string containing the parameters of the fit.
"""
name = filename[-13:-4]
time, flux = np.genfromtxt(filename, unpack = True)
if np.all(np.isnan(flux)):
return '%s\t\t%-8.6g\t%-8.6g\t%-8.6g\t%-4.3f\t%-8.6g\t%-8.6g' %((name,)+(np.nan,)*6)
time, flux = outlierRemoval(time, flux)
flux = medianDetrend(flux, 26)
# Main transit search
minPeriod = 0.5 # Limitations of BLS Fortran code
maxPeriod = (time[-1] - time[0]) / 2.
SNR, period, epoch, duration, depth, transitModel, period_guesses, \
convolved_bls = do_bls_and_fit(time, flux, minPeriod, maxPeriod)
# For the phase curves
phase, phasedFlux = getPhase(time, flux, period, epoch)
phaseModel, phasedFluxModel = getPhase(time, transitModel, period, epoch)
# Secondary search
secTime, secSNR, secPer, secEpoch, secDur, secModel = findSecondary(time, flux, period, epoch, duration)
if secSNR > 5 and abs(period - secPer) < 0.05:
secPhase, secPhaseModel = getPhase(secTime, secModel, secPer, epoch)
idx = len(secPhase[secPhase < 0])
else:
secPhase, secPhaseModel, idx = [], [], 1
# Odd/Even plot
fitT_odd, fitT_even = computeOddEvenModels(time, flux, period, epoch)
phaseModel_odd, phasedFluxModel_odd = getPhase(time, fitT_odd.transitmodel, period * 2, epoch)
phaseModel_even, phasedFluxModel_even = getPhase(time, fitT_even.transitmodel, period * 2, epoch + period)
depthOdd = fitT_odd.fitresultplanets['pnum0']['rprs'] ** 2
depthEven = fitT_even.fitresultplanets['pnum0']['rprs'] ** 2
phaseOdd, fluxOdd = getPhase(time, flux, period * 2, epoch)
phaseEven, fluxEven = getPhase(time, flux, period * 2, epoch + period)
x1, x2 = -duration, duration
y1, y2 = -3*np.std(fluxOdd), 3*np.std(fluxOdd)
if min(fluxOdd) < y1:
y1 = min(fluxOdd) - np.std(fluxOdd)
# sigma = abs(depth1 - depth2) / sqrt(u1^2 + u2^2)
durOdd = computeTransitDuration(period, fitT_odd.fitresultstellar['rho'], fitT_odd.fitresultplanets['pnum0']['rprs'])
durEven = computeTransitDuration(period, fitT_odd.fitresultstellar['rho'], fitT_even.fitresultplanets['pnum0']['rprs'])
sigma = computePointSigma(time, flux, transitModel, period, epoch, duration)
nOddPoints = np.sum((-durOdd*0.5 < phaseOdd) & (phaseOdd < durOdd * 0.5))
nEvenPoints = np.sum((-durEven*0.5 < phaseEven) & (phaseEven < durEven * 0.5))
uOdd, uEven = sigma / np.sqrt(nOddPoints), sigma / np.sqrt(nEvenPoints)
depthDiffSigma = abs(depthOdd - depthEven) / np.sqrt(uOdd**2 + uEven**2)
if doPlot:
gs = gridspec.GridSpec(3,2)
ax1 = plt.subplot(gs[0,:])
axOdd = plt.subplot(gs[1,0])
axEven = plt.subplot(gs[1,1])
ax3 = plt.subplot(gs[2,:])
gs.update(wspace = 0, hspace = 0.5)
ax1.plot(time, flux, 'k')
y1, y2 = ax1.get_ylim()
ax1.vlines(np.arange(epoch, time[-1], period), y1, y2,
color = 'r', linestyles = 'dashed', linewidth = 0.5)
ax1.axis([time[0], time[-1], y1, y2])
ax1.set_title('kplr%s; best period = %8.6g days; SNR = %8.6g' %(name, period, SNR))
ax1.set_xlabel('days')
axOdd.set_ylabel('flux')
axOdd.scatter(phaseOdd, fluxOdd, marker = '.', s = 1, color = 'k', alpha = 1)
axOdd.plot(phaseModel_odd, phasedFluxModel_odd, 'r')
axOdd.axhline(-depthOdd, x1, x2)
axOdd.axis([x1,x2,y1,y2])
axOdd.set_title('odd')
axEven.scatter(phaseEven, fluxEven, marker = '.', s = 1, color = 'k', alpha = 1)
axEven.plot(phaseModel_even, phasedFluxModel_even, 'r')
axEven.axhline(-depthEven, x1, x2)
axEven.yaxis.tick_right()
axEven.axis([x1,x2,y1,y2])
axEven.set_title('even')
if secondary:
plt.plot(secPhase[:idx], secPhaseModel[:idx], 'c')
plt.plot(secPhase[idx:], secPhaseModel[idx:], 'c')
ax3.scatter(phase, phasedFlux, marker = '.', s = 1, color = 'k')
ax3.plot(phaseModel, phasedFluxModel, 'r')
y1, y2 = -3*np.std(phasedFlux), 3*np.std(phasedFlux)
if min(phasedFlux) < y1:
y1 = min(phasedFlux) - np.std(phasedFlux)
ax3.axis([phase[0], phase[-1], y1, y2])
ax3.set_xlabel('phase [hours]')
ax3.text(0.5, 1.25, 'depth diff sigma = %.3f' %depthDiffSigma, horizontalalignment = 'center',
verticalalignment = 'center', transform = ax3.transAxes)
if plotOption == 'save':
plt.savefig(figureSaveLocation + '%s.png' %name, dpi = 200)
plt.close()
elif plotOption == 'show':
plt.show() | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def getResults():
rfn = '/Users/Yash/Desktop/NASA/Summer2014/k2/changedWhichpix/run1/results.txt'
names, periods = np.genfromtxt(rfn, usecols = (0,2), unpack = True)
return names, periods | barentsen/dave | [
4,
3,
4,
8,
1441063936
] |
def find_preference(name):
try:
return prefs_manager.get_preference(name)
except KeyError:
raise CommandError("No such preference **{}** exists.".format(name)) | sk89q/Plumeria | [
35,
2,
35,
2,
1471646188
] |
def __init__(self, key: bytes = b'\x00' * 8, name: str = None):
self.key = key
self.name = name
self.number = 0 | half2me/libant | [
23,
9,
23,
4,
1471543401
] |
def __init__(self, driver: Driver, initMessages, out: Queue, onSucces, onFailure):
super().__init__()
self._stopper = threading.Event()
self._driver = driver
self._out = out
self._initMessages = initMessages
self._waiters = []
self._onSuccess = onSucces
self._onFailure = onFailure | half2me/libant | [
23,
9,
23,
4,
1471543401
] |
def stopped(self):
return self._stopper.isSet() | half2me/libant | [
23,
9,
23,
4,
1471543401
] |
def __init__(self, driver: Driver, name: str = None):
self._driver = driver
self._name = name
self._out = Queue()
self._init = []
self._pump = None
self._configMessages = Queue() | half2me/libant | [
23,
9,
23,
4,
1471543401
] |
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop() | half2me/libant | [
23,
9,
23,
4,
1471543401
] |
def enableRxScanMode(self, networkKey=ANTPLUS_NETWORK_KEY, channelType=CHANNEL_TYPE_ONEWAY_RECEIVE,
frequency: int = 2457, rxTimestamp: bool = True, rssi: bool = True, channelId: bool = True):
self._init.append(SystemResetMessage())
self._init.append(SetNetworkKeyMessage(0, networkKey))
self._init.append(AssignChannelMessage(0, channelType))
self._init.append(SetChannelIdMessage(0))
self._init.append(SetChannelRfFrequencyMessage(0, frequency))
self._init.append(EnableExtendedMessagesMessage())
self._init.append(LibConfigMessage(rxTimestamp, rssi, channelId))
self._init.append(OpenRxScanModeMessage()) | half2me/libant | [
23,
9,
23,
4,
1471543401
] |
def isRunning(self):
if self._pump is None:
return False
return self._pump.is_alive() | half2me/libant | [
23,
9,
23,
4,
1471543401
] |
def test_first_and_last_slashes_trimmed_for_query_string (self):
created_collection = self.config.create_multi_partition_collection_with_custom_pk_if_not_exist(self.client)
document_definition = {'pk': 'pk', 'id':'myId'}
self.client.CreateItem(created_collection['_self'], document_definition)
query_options = {'partitionKey': 'pk'}
collectionLink = '/dbs/' + self.created_db['id'] + '/colls/' + created_collection['id'] + '/'
query = 'SELECT * from c'
query_iterable = self.client.QueryItems(collectionLink, query, query_options)
iter_list = list(query_iterable)
self.assertEqual(iter_list[0]['id'], 'myId') | Azure/azure-documentdb-python | [
148,
143,
148,
23,
1407452788
] |
def test_populate_query_metrics (self):
created_collection = self.config.create_multi_partition_collection_with_custom_pk_if_not_exist(self.client)
document_definition = {'pk': 'pk', 'id':'myId'}
self.client.CreateItem(created_collection['_self'], document_definition)
query_options = {'partitionKey': 'pk',
'populateQueryMetrics': True}
query = 'SELECT * from c'
query_iterable = self.client.QueryItems(created_collection['_self'], query, query_options)
iter_list = list(query_iterable)
self.assertEqual(iter_list[0]['id'], 'myId')
METRICS_HEADER_NAME = 'x-ms-documentdb-query-metrics'
self.assertTrue(METRICS_HEADER_NAME in self.client.last_response_headers)
metrics_header = self.client.last_response_headers[METRICS_HEADER_NAME]
# Validate header is well-formed: "key1=value1;key2=value2;etc"
metrics = metrics_header.split(';')
self.assertTrue(len(metrics) > 1)
self.assertTrue(all(['=' in x for x in metrics])) | Azure/azure-documentdb-python | [
148,
143,
148,
23,
1407452788
] |
def validate_query_requests_count(self, query_iterable, expected_count):
self.count = 0
self.OriginalExecuteFunction = retry_utility._ExecuteFunction
retry_utility._ExecuteFunction = self._MockExecuteFunction
block = query_iterable.fetch_next_block()
while block:
block = query_iterable.fetch_next_block()
retry_utility._ExecuteFunction = self.OriginalExecuteFunction
self.assertEquals(self.count, expected_count)
self.count = 0 | Azure/azure-documentdb-python | [
148,
143,
148,
23,
1407452788
] |
def lookups(self, request, model_admin):
def first_two(s):
s = unicode(s)
if len(s) < 2:
return s
else:
return s[:2]
prefixes = [first_two(alias.name)
for alias in model_admin.model.objects.only('name')]
prefixes = sorted(set(prefixes))
return [(prefix, prefix) for prefix in prefixes] | joneskoo/sikteeri | [
4,
8,
4,
3,
1276636698
] |
def hashToHex(hash):
return format(hash, '064x') | qtumproject/qtum | [
1170,
396,
1170,
38,
1488529031
] |
def allInvsMatch(invsExpected, testnode):
for x in range(60):
with mininode_lock:
if (sorted(invsExpected) == sorted(testnode.txinvs)):
return True
time.sleep(1)
return False | qtumproject/qtum | [
1170,
396,
1170,
38,
1488529031
] |
def __init__(self):
super().__init__()
self.txinvs = [] | qtumproject/qtum | [
1170,
396,
1170,
38,
1488529031
] |
def clear_invs(self):
with mininode_lock:
self.txinvs = [] | qtumproject/qtum | [
1170,
396,
1170,
38,
1488529031
] |
def set_test_params(self):
self.num_nodes = 2
# We lower the various required feerates for this test
# to catch a corner-case where feefilter used to slightly undercut
# mempool and wallet feerate calculation based on GetFee
# rounding down 3 places, leading to stranded transactions.
# See issue #16499
self.extra_args = [["-minrelaytxfee=0.00000100", "-mintxfee=0.00000100"]]*self.num_nodes | qtumproject/qtum | [
1170,
396,
1170,
38,
1488529031
] |
def run_test(self):
node1 = self.nodes[1]
node0 = self.nodes[0]
# Get out of IBD
node1.generate(1)
self.sync_blocks()
self.nodes[0].add_p2p_connection(TestP2PConn())
# Test that invs are received by test connection for all txs at
# feerate of 20 sat/byte
node1.settxfee(Decimal("0.02000000"))
txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)]
assert allInvsMatch(txids, self.nodes[0].p2p)
self.nodes[0].p2p.clear_invs()
# Set a filter of 15 sat/byte on test connection
self.nodes[0].p2p.send_and_ping(msg_feefilter(1500000))
# Test that txs are still being received by test connection (paying 15 sat/byte)
node1.settxfee(Decimal("0.01500000"))
txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)]
assert allInvsMatch(txids, self.nodes[0].p2p)
self.nodes[0].p2p.clear_invs()
# Change tx fee rate to 10 sat/byte and test they are no longer received
# by the test connection
node1.settxfee(Decimal("0.01000000"))
[node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)]
self.sync_mempools() # must be sure node 0 has received all txs
# Send one transaction from node0 that should be received, so that we
# we can sync the test on receipt (if node1's txs were relayed, they'd
# be received by the time this node0 tx is received). This is
# unfortunately reliant on the current relay behavior where we batch up
# to 35 entries in an inv, which means that when this next transaction
# is eligible for relay, the prior transactions from node1 are eligible
# as well.
node0.settxfee(Decimal("0.02000000"))
txids = [node0.sendtoaddress(node0.getnewaddress(), 1)]
assert allInvsMatch(txids, self.nodes[0].p2p)
self.nodes[0].p2p.clear_invs()
# Remove fee filter and check that txs are received again
self.nodes[0].p2p.send_and_ping(msg_feefilter(0))
txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)]
assert allInvsMatch(txids, self.nodes[0].p2p)
self.nodes[0].p2p.clear_invs() | qtumproject/qtum | [
1170,
396,
1170,
38,
1488529031
] |
def setup(self, parser):
parser.add_argument("-m", "--mark", action='append', default=[],
help="Highlight some registers.")
parser.add_argument("-M", "--mark-used", action='store_true',
help="Highlight currently used registers.") | wapiflapi/gxf | [
49,
7,
49,
3,
1415495222
] |
def test_package_data(self):
sources = self.mkdtemp()
f = open(os.path.join(sources, "__init__.py"), "w")
f.write("# Pretend this is a package.")
f.close()
f = open(os.path.join(sources, "README.txt"), "w")
f.write("Info about this package")
f.close() | babyliynfg/cross | [
75,
39,
75,
4,
1489383147
] |
def test_empty_package_dir (self):
# See SF 1668596/1720897.
cwd = os.getcwd() | babyliynfg/cross | [
75,
39,
75,
4,
1489383147
] |
def test_dont_write_bytecode(self):
# makes sure byte_compile is not used
pkg_dir, dist = self.create_dist()
cmd = build_py(dist)
cmd.compile = 1
cmd.optimize = 1 | babyliynfg/cross | [
75,
39,
75,
4,
1489383147
] |
def test_suite():
return unittest.makeSuite(BuildPyTestCase) | babyliynfg/cross | [
75,
39,
75,
4,
1489383147
] |
def __init__(self, vgg16_npy_path=None):
if vgg16_npy_path is None:
path = inspect.getfile(Vgg16)
path = os.path.abspath(os.path.join(path, os.pardir))
path = os.path.join(path, 'vgg16.npy')
vgg16_npy_path = path
print path
self.data_dict = np.load(vgg16_npy_path, encoding='latin1').item()
print('npy file loaded') | huangshiyu13/RPNplus | [
183,
87,
183,
15,
1488787933
] |
def avg_pool(self, bottom, name):
return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name) | huangshiyu13/RPNplus | [
183,
87,
183,
15,
1488787933
] |
def conv_layer(self, bottom, name):
with tf.variable_scope(name):
filt = self.get_conv_filter(name)
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
conv_biases = self.get_bias(name)
bias = tf.nn.bias_add(conv, conv_biases)
relu = tf.nn.relu(bias)
weight_dacay = tf.nn.l2_loss(filt, name='weight_dacay')
return relu, weight_dacay | huangshiyu13/RPNplus | [
183,
87,
183,
15,
1488787933
] |
def conv_layer_new(self, bottom, name, kernel_size=[3, 3], out_channel=512, stddev=0.01):
with tf.variable_scope(name):
shape = bottom.get_shape().as_list()[-1]
filt = tf.Variable(
tf.random_normal([kernel_size[0], kernel_size[1], shape, out_channel], mean=0.0, stddev=stddev),
name='filter')
conv_biases = tf.Variable(tf.zeros([out_channel]), name='biases')
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
bias = tf.nn.bias_add(conv, conv_biases)
weight_dacay = tf.nn.l2_loss(filt, name='weight_dacay')
return bias, weight_dacay | huangshiyu13/RPNplus | [
183,
87,
183,
15,
1488787933
] |
def get_bias(self, name):
return tf.Variable(self.data_dict[name][1], name='biases') | huangshiyu13/RPNplus | [
183,
87,
183,
15,
1488787933
] |
def get_bias_const(self, name):
return tf.constant(self.data_dict[name][1], name='biases') | huangshiyu13/RPNplus | [
183,
87,
183,
15,
1488787933
] |
def checkFile(fileName):
if os.path.isfile(fileName):
return True
else:
print fileName, 'is not found!'
exit() | huangshiyu13/RPNplus | [
183,
87,
183,
15,
1488787933
] |
def __str__(self):
return self.nome | bczmufrn/frequencia | [
2,
4,
2,
1,
1501159947
] |
def __str__(self):
return (
'%s: [%s]' if self.isArray() else '%s: %s'
) % (
'Interface' if self.isInterface() else
'Primitive' if self.isPrimitive() else
'Class',
self.getName()
) | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def ensureclass(clsname):
if clsname in registers:
return
jniname = clsname.replace('.', '/')
if MetaJavaClass.get_javaclass(jniname):
return
registers.append(clsname)
autoclass(clsname) | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def bean_getter(s):
return (s.startswith('get') and len(s) > 3 and s[3].isupper()) or (s.startswith('is') and len(s) > 2 and s[2].isupper()) | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def identify_hierarchy(cls, level, concrete=True):
supercls = cls.getSuperclass()
if supercls is not None:
for sup, lvl in identify_hierarchy(supercls, level + 1, concrete=concrete):
yield sup, lvl # we could use yield from when we drop python2
interfaces = cls.getInterfaces()
for interface in interfaces or []:
for sup, lvl in identify_hierarchy(interface, level + 1, concrete=concrete):
yield sup, lvl
# all object extends Object, so if this top interface in a hierarchy, yield Object
if not concrete and cls.isInterface() and not interfaces:
yield find_javaclass('java.lang.Object'), level +1
yield cls, level | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def autoclass(clsname, include_protected=True, include_private=True):
jniname = clsname.replace('.', '/')
cls = MetaJavaClass.get_javaclass(jniname, classparams=(include_protected, include_private))
if cls:
return cls
classDict = {}
cls_start_packagename = '.'.join(clsname.split('.')[:-1])
# c = Class.forName(clsname)
c = find_javaclass(clsname)
if c is None:
raise Exception('Java class {0} not found'.format(c))
return None
classDict['_class'] = c
constructors = []
for constructor in c.getConstructors():
sig = '({0})V'.format(
''.join([get_signature(x) for x in constructor.getParameterTypes()]))
constructors.append((sig, constructor.isVarArgs()))
classDict['__javaconstructor__'] = constructors
class_hierachy = list(identify_hierarchy(c, 0, not c.isInterface()))
log.debug("autoclass(%s) intf %r hierarchy is %s" % (clsname,c.isInterface(),str(class_hierachy)))
cls_done=set()
cls_methods = defaultdict(list)
cls_fields = {}
# we now walk the hierarchy, from top of the tree, identifying methods
# hopefully we start at java.lang.Object
for cls, level in class_hierachy:
# dont analyse a given class more than once.
# many interfaces can lead to java.lang.Object
if cls in cls_done:
continue
cls_packagename = '.'.join(cls.getName().split('.')[:-1])
cls_done.add(cls)
# as we are walking the entire hierarchy, we only need getDeclaredMethods()
# to get what is in this class; other parts of the hierarchy will be found
# in those respective classes.
methods = cls.getDeclaredMethods()
methods_name = [x.getName() for x in methods]
# collect all methods declared by this class of the hierarchy for later traversal
for index, method in enumerate(methods):
method_modifier = method.getModifiers()
if Modifier.isProtected(method_modifier) and not include_protected:
continue
if Modifier.isPrivate(method_modifier) and not include_private:
continue
if not (Modifier.isPublic(method_modifier) or
Modifier.isProtected(method_modifier) or
Modifier.isPrivate(method_modifier)):
if cls_start_packagename == cls_packagename and not include_protected:
continue
if cls_start_packagename != cls_packagename and not include_private:
continue
name = methods_name[index]
cls_methods[name].append((cls, method, level)) | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def _getitem(self, index):
''' dunder method for List '''
try:
return self.get(index)
except JavaException as e:
# initialize the subclass before getting the Class.forName
# otherwise isInstance does not know of the subclass
mock_exception_object = autoclass(e.classname)()
if find_javaclass("java.lang.IndexOutOfBoundsException").isInstance(mock_exception_object):
# python for...in iteration checks for end of list by waiting for IndexError
raise IndexError()
else:
raise | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def __init__(self, java_iterator):
self.java_iterator = java_iterator | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def next(self):
log.debug("monkey patched next() called")
if not self.java_iterator.hasNext():
raise StopIteration()
return self.java_iterator.next() | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def _iterator_next(self):
''' dunder method for java.util.Iterator'''
if not self.hasNext():
raise StopIteration()
return self.next() | kivy/pyjnius | [
1284,
251,
1284,
140,
1344908347
] |
def setUp(self):
HTTPretty.reset()
HTTPretty.enable() | futurecolors/gopython3 | [
2,
2,
2,
13,
1379656339
] |
def test_get_most_popular_repo(self):
HTTPretty.register_uri(HTTPretty.GET,
'https://api.github.com/search/repositories',
'{"items":[{"full_name": "coagulant/requests2", "name": "requests2"},'
'{"full_name": "kennethreitz/fake_requests", "name": "fake_requests"}]}',
)
assert Github().get_most_popular_repo('Fake_Requests') == 'kennethreitz/fake_requests' | futurecolors/gopython3 | [
2,
2,
2,
13,
1379656339
] |
def test_crawl_py3_issues(self):
HTTPretty.register_uri(HTTPretty.GET,
'https://api.github.com/repos/embedly/embedly-python/issues',
responses=[HTTPretty.Response('[{"state": "open", "title": "WTF?", "html_url": "https://github.com/embedly/embedly-python/issues/1"},'
'{"state": "closed", "title": "Python 3 support", "html_url": "https://github.com/embedly/embedly-python/pull/13"}]'),
HTTPretty.Response('[{"state": "open", "title": "Broken", "html_url": "https://github.com/embedly/embedly-python/issues/2"}]')]
)
assert Github().get_py3_issues('embedly/embedly-python', search=False) == [{
'state': 'closed',
'title': 'Python 3 support',
'html_url': 'https://github.com/embedly/embedly-python/pull/13'
}]
assert HTTPretty.last_request.querystring['state'][0] == 'closed' | futurecolors/gopython3 | [
2,
2,
2,
13,
1379656339
] |
Subsets and Splits