file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
tracer.go | ampling = nil
cfg.EncoderConfig.CallerKey = zapcore.OmitKey
cfg.EncoderConfig.MessageKey = zapcore.OmitKey
cfg.EncoderConfig.LevelKey = zapcore.OmitKey
cfg.DisableCaller = true
for _, opt := range opts {
opt(&cfg)
}
logger, err := cfg.Build()
if err != nil {
panic(err.Error())
}
return &tracer{
logger: ... |
}
if err == nil {
if diff := cmp.Diff(rst, r.Results, cmpopts.EquateEmpty()); len(diff) > 0 && rt.assertOutputs {
return errors.New(diff)
}
}
return nil
}
type UpdatesTrace struct {
ResultsTrace `json:",inline"`
| {
return err
} | conditional_block |
tracer.go | ampling = nil
cfg.EncoderConfig.CallerKey = zapcore.OmitKey
cfg.EncoderConfig.MessageKey = zapcore.OmitKey
cfg.EncoderConfig.LevelKey = zapcore.OmitKey
cfg.DisableCaller = true
for _, opt := range opts {
opt(&cfg)
}
logger, err := cfg.Build()
if err != nil {
panic(err.Error())
}
return &tracer{
logger: ... |
func (s *StoreBallotTrace) New() traceEvent {
return &StoreBallotTrace{}
}
func (s *StoreBallotTrace) Run(r *traceRunner) error {
pending, exist := r.pending[s.ID]
if !exist {
return fmt.Errorf("id %v should be pending", s.ID)
}
if s.Malicious {
pending.SetMalicious()
}
delete(r.pending, s.ID)
err := r.t... | {
return traceStore
} | identifier_body |
tracer.go | cfg.Sampling = nil
cfg.EncoderConfig.CallerKey = zapcore.OmitKey
cfg.EncoderConfig.MessageKey = zapcore.OmitKey
cfg.EncoderConfig.LevelKey = zapcore.OmitKey
cfg.DisableCaller = true
for _, opt := range opts {
opt(&cfg)
}
logger, err := cfg.Build()
if err != nil {
panic(err.Error())
}
return &tracer{
lo... | traceActiveset
traceResults
traceUpdates
traceMalfeasence
)
type traceEvent interface {
Type() eventType
New() traceEvent
Run(*traceRunner) error
}
type ConfigTrace struct {
Hdist uint32 `json:"hdist"`
Zdist uint32 `json:"zdist"`
WindowSize uint32 `json:"w... | traceStore
traceEncode
traceTally
traceBlock
traceHare | random_line_split |
tracer.go | .Sampling = nil
cfg.EncoderConfig.CallerKey = zapcore.OmitKey
cfg.EncoderConfig.MessageKey = zapcore.OmitKey
cfg.EncoderConfig.LevelKey = zapcore.OmitKey
cfg.DisableCaller = true
for _, opt := range opts {
opt(&cfg)
}
logger, err := cfg.Build()
if err != nil {
panic(err.Error())
}
return &tracer{
logger... | () traceEvent {
return &StoreBallotTrace{}
}
func (s *StoreBallotTrace) Run(r *traceRunner) error {
pending, exist := r.pending[s.ID]
if !exist {
return fmt.Errorf("id %v should be pending", s.ID)
}
if s.Malicious {
pending.SetMalicious()
}
delete(r.pending, s.ID)
err := r.trt.StoreBallot(pending)
if r.as... | New | identifier_name |
SemaIndexerStage2.py | _er,onto_basis,relactionate):
#try:
id=usr
if True:
#===
#try:
if True:
#print 'LayersC:',layersc
try:
ir=Identify.resume_process_datac(layersc,onto_basis,purpose,id,relactionate)
except Exception,errc:
print 'Error resume_process_datac:',errc
log... | _process2(sel | identifier_name | |
SemaIndexerStage2.py | lay.set_topico('identificador')
tpc2.uuid=cenar
nrc2= lay.set_nr(lay.name)
nrc2.uuid=cenar
tpc2.connect_to(lay,nrc2,'Composicao')
#print lay.topicos,'....................'
print 'Read object(g1):',obj,' uid:',uid
#-----------
def cached_dt(objectkey,cnts_all_tp):
'''
cached=[]
keyc=objectke... | nrc.uuid=cenar
nr.connect_to(lay,nrc,'Composicao')
ky,results = resultSet1.next()
results = read_dt_level( nrc,3,uid,ic2,lay,results,resultSet1,cenar ) #####
#lay.dump_layer_file()
#print 'collected.la... | =range(0,50)
resultSet1=iterat.get_level(levs)
#sess=conn3.prepare(sql1)
#resultSet = sess.execute ()
ky,results = resultSet1.next()
while results :
DT=results[u"datach"]
TOP=results[u... | conditional_block |
SemaIndexerStage2.py | 5 -inserir no clipping return
'''
def get_aliases_ob( ):
str_ret=[]
for ir in layer_processes.lrs:
print 'get_aliases_ob()->ir(1):',ir
#if ir != None: print 'lr:',ir.name
for topico in ir.topicos:
if len(topico.dt) > 0 :
topicodt=topico.dt
if 'identi... | random_line_split | ||
SemaIndexerStage2.py | lay.set_topico('identificador')
tpc2.uuid=cenar
nrc2= lay.set_nr(lay.name)
nrc2.uuid=cenar
tpc2.connect_to(lay,nrc2,'Composicao')
#print lay.topicos,'....................'
print 'Read object(g1):',obj,' uid:',uid
#-----------
def cached_dt(objectkey,cnts_all_tp):
'''
cached=[]
keyc=objectke... | def get_all(self):
rt=[]
while True:
s=self.next()
if s[0] == None: break
rt.append(s)
return rt
def next(self):
if self.start == -1:
self.start=0
else:
self.start+=1
if self.start < len(... | ]
arr=self.arr
for ky,cols in arr:
for level in level2:
if int(cols[u'LEV']) == level:
rt.append([ky,cols])
rt2=iter_cd(rt)
return rt2
| identifier_body |
HaaLimitsHMass.py | shiftName : the name the uncertainty will be given in the datacard
process : the name of the process
signal must be of the form 'HToAAH{h}A{a}'
data = 'data'
background = 'datadriven'
'... | '''
Create the Haa Limits workspace
'''
SPLINENAME = 'sig{a}'
XRANGE = [50,1000]
XLABEL = 'm_{#mu#mu#tau_{#mu}#tau_{h}}'
def __init__(self,histMap):
'''
Required arguments:
histMap = histogram map. the structure should be:
histMap[region][shift][pro... | identifier_body | |
HaaLimitsHMass.py | shiftNameUp', or 'shiftNameDown'
'' : central value
'shiftName' : a symmetric shift (ie, jet resolution)
'shiftName[Up,Down]' : an asymmetric shift (ie, fake rate, lepton efficiencies, etc)
shiftNa... | addSignalModels | identifier_name | |
HaaLimitsHMass.py | : 'PP' or 'FP' for regions A and B, respectively
shift : '', 'shiftName', 'shiftNameUp', or 'shiftNameDown'
'' : central value
'shiftName' : a symmetric shift (ie, jet resolution)
'shiftName[Up,Down... |
# create model
for h in self.HMASSES:
print h, a, results[a][h]
model = Models.VoigtianSpline(self.SPLINENAME.format(a=a),
**{
'masses' : self.HMASSES,
'means' : [results[a][h]['mean_h{0}_a{1}_{2}'.format(h,a,tag)] for h in self.HMAS... | ws = ROOT.RooWorkspace(param)
ws.factory('x[{},{}]'.format(*self.XRANGE))
ws.var('x').setUnit('GeV')
ws.var('x').setPlotLabel(self.XLABEL)
ws.var('x').SetTitle(self.XLABEL)
model = models[param]
model.build(ws, param)
name = '{}_{}{}'.f... | conditional_block |
HaaLimitsHMass.py | '
'' : central value
'shiftName' : a symmetric shift (ie, jet resolution)
'shiftName[Up,Down]' : an asymmetric shift (ie, fake rate, lepton efficiencies, etc)
shiftName : the name the un... | def addSignalModels(self):
for region in self.REGIONS: | random_line_split | |
sphere.rs | Sphere {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut state = s.serialize_struct("Sphere", 4)?;
state.serialize_field("radius", &self.radius)?;
state.serialize_field("zmin", &self.zmin)?;
state.serialize_field("zmax", &self.zmax)?;
state.seri... | thetamax: thetamax,
phimax: phimax,
}
}
/// Constructs a full sphere
#[inline]
pub fn full(radius: Float) -> Sphere {
Sphere::new(radius, -radius, radius, float::pi() * (2.0 as Float))
}
/// returns the local space bounding box
#[inline]
pub fn ... | {
assert!(radius>(0.0 as Float), "Sphere radius should be positive");
assert!(zmin<zmax, "zmin should be lower than zmax");
if zmin < -radius { zmin = -radius; }
if zmax > radius { zmax = radius; }
if phimax < (0.0 as Float) { phimax = 0.0 as Float; }
let twopi = float:... | identifier_body |
sphere.rs | Sphere {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut state = s.serialize_struct("Sphere", 4)?;
state.serialize_field("radius", &self.radius)?;
state.serialize_field("zmin", &self.zmin)?;
state.serialize_field("zmax", &self.zmax)?;
state.seri... | // #[inline]
// pub fn intersect_ray(&self, ray: &RawRay) -> Option<Float>
// {
// if let Some(t) = Sphere::intersect_ray_full(self.radius, ray) {
// let p = ray.evaluate(t);
// // TODO: refine sphere intersection
// let mut phi = p.y.atan2(p.x);
// if... | Point3f::new(self.radius, self.radius, self.zmax)
)
}
// /// test intersection in local frame, returns `t` when first hit | random_line_split |
sphere.rs | Sphere {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut state = s.serialize_struct("Sphere", 4)?;
state.serialize_field("radius", &self.radius)?;
state.serialize_field("zmin", &self.zmin)?;
state.serialize_field("zmax", &self.zmax)?;
state.seri... | (radius: Float, ray: &RawRay) -> Option<Float>
{
let origin = ray.origin().to_vec();
let direction = ray.direction();
let a = direction.magnitude2();
let b = (direction.mul_element_wise(origin) * (2.0 as Float)).sum();
let c = origin.magnitude2() - radius * radius;
l... | intersect_ray_full | identifier_name |
Dom.ts | if (!Blend.isNullOrUndef(item)) {
item = (((item as any) === true ? defaultEventTarget : item) ||
new Function(item as any)) as any;
el.addEventListener(key, item, false);
}
});
}
if (config.css) {
el.setAttribute(
"class",
Blend.wrapInArray(config.css)
.join(... | {
const me = this,
ref = me.getReference();
if (ref) {
if (ref === ".." && me.el.parentElement) {
return DOMElement.getElement(me.el.parentElement).getReferencedParent();
} else {
return DOMElement.getElement(me.el);
}
} else {
return null;
}
} | identifier_body | |
Dom.ts | }
/**
* Utility function for creating en `HTMLElement`.
* The reference callback function `refCallback` can be used
* to assign child elements which have a `reference` to class
* properties.
*
* The windows parameters `win` can be used to create the element from
* a specific `Wi... | ): NodeListOf<T> {
return (fromRoot || document).querySelectorAll(selector) as NodeListOf<T>; | random_line_split | |
Dom.ts | (config.listeners) {
Blend.forEach(config.listeners, (item: EventListenerOrEventListenerObject, key: string) => {
if (!Blend.isNullOrUndef(item)) {
item = (((item as any) === true ? defaultEventTarget : item) ||
new Function(item as any)) as any;
el.addEventListener(key, item, false);
... | {
return DOMElement.getElement(me.el.parentElement).getReferencedParent();
} | conditional_block | |
Dom.ts | } [refCallback]
* @param {Window} [win]
* @returns {T}
*/
export function createElement<T extends HTMLElement>(
conf?: HTMLElement | ICreateElementConfig,
refCallback?: (reference: string, element: HTMLElement) => any,
defaultEventTarget?: EventListenerObject
): T {
if (conf instanceof HTMLElem... | (el?: HTMLElement | string | ICreateElementConfig) {
const me = this;
me.el = me.renderElement(el);
}
/**
* Internal method that is used to parse and render the HTMLElement.
*
* @protected
* @param {(HTMLElement | string | ICreateElementConfig)} [el]
* @returns {HTMLElement}
* @m... | constructor | identifier_name |
Career and Job Agent.py | try:
filename = 'Dictionary.csv'
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()
if(rows[1]==key):
print("Keyword present in lookup file")
for rows in reader:
clusterData... |
return co
if source == 'indeed':
for everyline in soup2.find_all('span',{'class':'summary','itemprop':'description'}):
if hasattr(everyline, "text"):
co.append(everyline.text)
return co
##The scrapper is a web scrapping function which uses Beaut... | co.append(everyline.text) | conditional_block |
Career and Job Agent.py | try:
filename = 'Dictionary.csv'
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()
if(rows[1]==key):
print("Keyword present in lookup file")
for rows in reader:
clusterData... | if len(d1)==knn_k:
break
else:
links = link[nn]
print ("\n",links)
count=count+1
#Here, we calculate Jaccard's distance and send it back to the Analysis
##function of the agent
## http://journocode.com/2016/03/10/similarity-and-distance-part-1/
def J... | d=[]
d1=[]
knn_k = int(k)
orderedJacc = sorted(k1)
takingK = []
## for x in range(0,k):
takingK = (orderedJacc[:k])
for x in range(0,len(link)):
for k in takingK:
d.append(list_duplicates_of(k1,k))
count=0
for everyd in range(0,len(d)):
if count==knn_k:
... | identifier_body |
Career and Job Agent.py | try:
filename = 'Dictionary.csv'
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()
if(rows[1]==key):
print("Keyword present in lookup file")
for rows in reader:
clusterData... | (key,k):
filename = 'Dictionary.csv'
title = []
content = []
link = []
freq = []
index = 0
ind = []
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()
for rows in reader:
title.append(rows[1])
... | agent | identifier_name |
Career and Job Agent.py | try:
filename = 'Dictionary.csv'
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()
if(rows[1]==key):
print("Keyword present in lookup file")
for rows in reader:
clusterData... | ##frequency of the keyword's occurence in our retreieved links
def agent(key,k):
filename = 'Dictionary.csv'
title = []
content = []
link = []
freq = []
index = 0
ind = []
with open(filename,'rb') as infile:
reader = csv.reader(infile,dialect='excel')
rows = reader.next()... | k1.append(jacc)
actuator(k1, link,k)
##Agent computes all the details. Agent reads details from our table and computes | random_line_split |
implicit.go | skipCache bool) (imp implicitTeam, hitCache bool, err error) {
cacheKey := impTeamCacheKey(displayName, public)
cacher := g.GetImplicitTeamCacher()
if !skipCache && cacher != nil {
if cv, ok := cacher.Get(cacheKey); ok {
if imp, ok := cv.(implicitTeam); ok {
g.Log.CDebugf(ctx, "using cached iteam")
ret... | (ctx context.Context, g *libkb.GlobalContext, impTeamName keybase1.ImplicitTeamDisplayName,
nameWithoutConflict string, preResolveDisplayName string, skipCache bool) (conflicts []keybase1.ImplicitTeamConflictInfo, teamID keybase1.TeamID, hitCache bool, err error) {
defer g.CTrace(ctx,
fmt.Sprintf("attemptLoadImpte... | attemptLoadImpteamAndConflict | identifier_name |
implicit.go | Cache bool) (imp implicitTeam, hitCache bool, err error) {
cacheKey := impTeamCacheKey(displayName, public)
cacher := g.GetImplicitTeamCacher()
if !skipCache && cacher != nil {
if cv, ok := cacher.Get(cacheKey); ok {
if imp, ok := cv.(implicitTeam); ok {
g.Log.CDebugf(ctx, "using cached iteam")
return i... |
return imp, err
}
return imp, nil
}
// attemptLoadImpteamAndConflits attempts to lead the implicit team with
// conflict, but it might find the team but not the specific conflict if the
// conflict was not in cache. This can be detected with `hitCache` return
// value, and mitigated by passing skipCache=false arg... | {
code := keybase1.StatusCode(aerr.Code)
switch code {
case keybase1.StatusCode_SCTeamReadError:
return imp, NewTeamDoesNotExistError(public, displayName)
case keybase1.StatusCode_SCTeamProvisionalCanKey, keybase1.StatusCode_SCTeamProvisionalCannotKey:
return imp, libkb.NewTeamProvisionalError(
... | conditional_block |
implicit.go | skipCache bool) (imp implicitTeam, hitCache bool, err error) {
cacheKey := impTeamCacheKey(displayName, public)
cacher := g.GetImplicitTeamCacher()
if !skipCache && cacher != nil {
if cv, ok := cacher.Get(cacheKey); ok {
if imp, ok := cv.(implicitTeam); ok {
g.Log.CDebugf(ctx, "using cached iteam")
ret... | }
return imp, nil
}
// attemptLoadImpteamAndConflits attempts to lead the implicit team with
// conflict, but it might find the team but not the specific conflict if the
// conflict was not in cache. This can be detected with `hitCache` return
// value, and mitigated by passing skipCache=false argument.
func attemp... | {
mctx := libkb.NewMetaContext(ctx, g)
arg := libkb.NewAPIArg("team/implicit")
arg.SessionType = libkb.APISessionTypeOPTIONAL
arg.Args = libkb.HTTPArgs{
"display_name": libkb.S{Val: displayName},
"public": libkb.B{Val: public},
}
if err = mctx.G().API.GetDecode(mctx, arg, &imp); err != nil {
if aerr, ... | identifier_body |
implicit.go | if match {
teamID = conflict.TeamID
foundSelectedConflict = true
g.Log.CDebugf(ctx, "| found conflict suffix match: %v", teamID)
} else {
g.Log.CDebugf(ctx, "| conflict suffix didn't match (teamID %v)", conflict.TeamID)
}
}
}
if impTeamName.ConflictInfo != nil && !foundSelectedConflict {
... |
func formatImplicitTeamDisplayNameCommon(ctx context.Context, g *libkb.GlobalContext, impTeamName keybase1.ImplicitTeamDisplayName, optionalFrontName *libkb.NormalizedUsername) (string, error) {
writerNames := make([]string, 0, len(impTeamName.Writers.KeybaseUsers)+len(impTeamName.Writers.UnresolvedUsers))
writerNam... | random_line_split | |
keyframe.go |
func fromUTF8(s string) string {
_, b, err := wintrans.Translate([]byte(s), true)
if err != nil {
return s
}
return string(b)
}
//showtext displays text
func showtext(x, y openvg.VGfloat, s, align, font string, fs openvg.VGfloat) {
t := fromUTF8(s)
fontsize := int(fs)
switch align {
case "center", "middle"... | {
pw := deck.Pwidth(p, float64(p1), float64(p2))
return openvg.VGfloat(pw)
} | identifier_body | |
keyframe.go | , base height on overall height
h = pct(ellipse.Hp, ch)
} else {
h = pct(ellipse.Hr, w)
}
if ellipse.Color == "" {
ellipse.Color = defaultColor
}
if ellipse.Opacity == 0 {
ellipse.Opacity = 1
} else {
ellipse.Opacity /= 100
}
openvg.FillColor(ellipse.Color, openvg.VGfloat(ellipse.Opacity)... | } | random_line_split | |
keyframe.go | t, font, fontsize)
case "right", "end", "e":
openvg.TextEnd(x, y, t, font, fontsize)
default:
openvg.Text(x, y, t, font, fontsize)
}
}
// dimen returns device dimemsion from percentages
func dimen(d deck.Deck, x, y, s float64) (xo, yo, so openvg.VGfloat) {
xf, yf, sf := deck.Dimen(d.Canvas, x, y, s)
xo, yo, ... | else {
px[i] = pct(x, cw)
}
y, err := strconv.ParseFloat(ys[i], 32)
if err != nil {
py[i] = 0
} else {
py[i] = pct(y, ch)
}
}
openvg.FillColor(poly.Color, openvg.VGfloat(poly.Opacity))
openvg.Polygon(px, py)
}
openvg.FillColor(slide.Fg)
// every list in the slide
var offset, text... | {
px[i] = 0
} | conditional_block |
keyframe.go | , y1, x2, y2)
openvg.StrokeWidth(0)
}
// ellipse
for _, ellipse := range slide.Ellipse {
x, y, _ = dimen(d, ellipse.Xp, ellipse.Yp, 0)
var w, h openvg.VGfloat
w = pct(ellipse.Wp, cw)
if ellipse.Hr == 0 { // if relative height not specified, base height on overall height
h = pct(ellipse.Hp, ch)
} else ... | whitespace | identifier_name | |
Mash.py |
def main():
c = converter.parse('./ChopinNocturneOp9No2.xml')
melody = c.parts[0] #Melody part
chord = c.parts[1] #Chord part
measureLength = len(melody) #Number of measures
print "length: " + str(measureLength)
for x in range(1,measureLength): #For all measures
print "index" + str(x)
... | print "melody" + str(measure.notes[x].offset) | conditional_block | |
Mash.py | (measureLength)
for x in range(1,measureLength): #For all measures
print "index" + str(x)
if (len(chord.measure(x).notes) == 0 and len(melody.measure(x).notes) == 0):
break
determineChord(chord.measure(x))
determineMelody(melody.measure(x))
def streamCreate():
... | (measure):
totalList = []
totalList2 = []
for x in measure.flat.recurse():
print x
if type(x) == chord.Chord:
totalList.append([x,x.duration,x.offset])
#print x,x.duration,x.offset
elif type(x) == note.Note:
totalList2.append([x,x.duration,x.offset... | findAllNotesWithinMeasureChord | identifier_name |
Mash.py | (measureLength)
for x in range(1,measureLength): #For all measures
print "index" + str(x)
if (len(chord.measure(x).notes) == 0 and len(melody.measure(x).notes) == 0):
break
determineChord(chord.measure(x))
determineMelody(melody.measure(x))
def streamCreate():
... |
def findAllMeasuresWithinParts(melody,chords,newChord,newMelody):
chordMeasures = chords.measure(0)
if chordMeasures is None:
chordMeasures = chords.measure(1)
c1 = chordMeasures
melodyMeasures = melody.measure(0)
if melodyMeasures is None:
melodyMeasures = melody.measure... | n = note.Note(pitch)
n.duration = duration
n.offset = offset
return n | identifier_body |
Mash.py | number = len(c2.parts[1]) #number of measures
number2 = len(c2.parts[1].measure(4))
c = c.parts[0].flat
print c2.parts[1].measure(4).notes[1].duration.type
print number2
#s = stream.Score()
#s.insert(0,c)
#s.insert(1,c2)
#s.show()
def determineChord(measure):
#measure.notes[... | c = converter.parse('./KL_Rains_of_Castamere.xml')
c2 = converter.parse('./FurElise.xml') | random_line_split | |
chain.go | InvalidChain{
Message: fmt.Sprintf("chain has %d first job(s), should "+
"have one (first job(s) = %v)", len(jobIds), jobIds),
}
}
return c.JobChain.Jobs[jobIds[0]], nil
}
// LastJob finds the job in the chain with outdegree 0. If there is not
// exactly one of these jobs, it returns an error.
func (c *cha... | {
indegreeCounts := c.indegreeCounts()
queue := make(map[string]struct{})
// Add all of the first jobs to the queue (in reality there should
// only be 1).
for job, indegreeCount := range indegreeCounts {
if indegreeCount == 0 {
queue[job] = struct{}{}
}
}
jobsVisited := 0
for {
// Break when there a... | identifier_body | |
chain.go | Running: map[string]RunningJob{},
N: 0,
RWMutex: &sync.RWMutex{},
}
}
// ErrInvalidChain is the error returned when a chain is not valid.
type ErrInvalidChain struct {
Message string
}
func (e ErrInvalidChain) Error() string {
return e.Error()
}
// FirstJob finds the job in the chain with indegree ... |
if len(jobIds) != 1 {
return proto.Job{}, ErrInvalidChain{
Message: fmt.Sprintf("chain has %d last job(s), should "+
"have one (last job(s) = %v)", len(jobIds), jobIds),
}
}
return c.JobChain.Jobs[jobIds[0]], nil
}
// NextJobs finds all of the jobs adjacent to the given job.
func (c *chain) NextJobs(j... | {
if count == 0 {
jobIds = append(jobIds, jobId)
}
} | conditional_block |
chain.go | ,
Running: map[string]RunningJob{},
N: 0,
RWMutex: &sync.RWMutex{},
}
}
// ErrInvalidChain is the error returned when a chain is not valid.
type ErrInvalidChain struct {
Message string
}
func (e ErrInvalidChain) Error() string {
return e.Error()
}
// FirstJob finds the job in the chain with indegre... | _, err := c.FirstJob()
if err != nil {
return err
}
// Make sure there is one last job.
_, err = c.LastJob()
if err != nil {
return err
}
// Make sure there are no cycles.
if !c.isAcyclic() {
return ErrInvalidChain{Message: "chain is cyclic"}
}
return nil
}
// RequestId returns the request id of th... | // Make sure there is one first job. | random_line_split |
chain.go | Running: map[string]RunningJob{},
N: 0,
RWMutex: &sync.RWMutex{},
}
}
// ErrInvalidChain is the error returned when a chain is not valid.
type ErrInvalidChain struct {
Message string
}
func (e ErrInvalidChain) Error() string {
return e.Error()
}
// FirstJob finds the job in the chain with indegree ... | (jobId string) proto.Jobs {
var prevJobs proto.Jobs
for curJob, nextJobs := range c.JobChain.AdjacencyList {
if contains(nextJobs, jobId) {
if val, ok := c.JobChain.Jobs[curJob]; ok {
prevJobs = append(prevJobs, val)
}
}
}
return prevJobs
}
// JobIsReady returns whether or not a job is ready to run. ... | PreviousJobs | identifier_name |
node.rs | DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio::time::*;
use tonic::Request;
use crate::cluster::{self, InternalRaftMessage, RaftRequest};
use crate::network::{create_client, RpcClient};
use c... | (
&mut self,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
let mut ready = self.node.ready();
let is_leader = self.node.raft.leader_id == self.node.raft.id;
slog::info!(
self.logger,
"Leader ID: {}, Node ID: {}",
self.node.... | ready | identifier_name |
node.rs | DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio::time::*;
use tonic::Request;
use crate::cluster::{self, InternalRaftMessage, RaftRequest};
use crate::network::{create_client, RpcClient};
use c... |
match timeout(Duration::from_millis(100), self.conf_recv.recv()).await {
Ok(Some(cc)) => {
let ccc = cc.clone();
let state = self.node.apply_conf_change(&cc)?;
self.node.mut_store().set_conf_state(state);
let ... | {
slog::info!(self.logger, "Inbound raft message: {:?}", msg);
self.node.step(msg.into())?;
} | conditional_block |
node.rs | DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio::time::*;
use tonic::Request;
use crate::cluster::{self, InternalRaftMessage, RaftRequest};
use crate::network::{create_client, RpcClient};
use c... |
fn set_hard_state(
&mut self,
commit: u64,
term: u64,
) -> Result<(), crate::error::Error> {
self.node.raft.mut_store().set_hard_state(commit, term);
Ok(())
}
#[allow(irrefutable_let_patterns)]
pub async fn run(
mut self,
) -> Result<(), Box<dyn... | {
self.node.raft.raft_log.committed = 0;
self.node.raft.become_candidate();
self.node.raft.become_leader();
} | identifier_body |
node.rs | ::DashMap;
use http::Uri;
use prost::Message;
use raft::prelude::*;
use raft::{Config, RawNode};
use slog::Logger;
use tokio::sync::mpsc::*;
use tokio::sync::RwLock;
use tokio::time::*;
use tonic::Request;
use crate::cluster::{self, InternalRaftMessage, RaftRequest};
use crate::network::{create_client, RpcClient};
use... | internal_raft_message
.merge(Bytes::from(entry.data.clone()))
.unwrap();
if let Err(error) = self.apply(internal_raft_message) {
slog::error!(self.logger, "Unable to apply entry. {:?}", error);
// TODO: retu... | let mut internal_raft_message = InternalRaftMessage::default(); | random_line_split |
script.py | tle):
assert len(vim) > 0
if len(vim) == 1:
finalImg = vim
else:
finalImg = vim[0]
vim.pop(0)
for img in vim:
finalImg = cv2.hconcat((finalImg, img))
_showImage(finalImg, title)
return finalImg
# Muestra en una imagen 10 parches de 24x24 pixeles:
def dibuja10par... | vim, ti | identifier_name | |
script.py | aciendo uso de una máscara
# binaria o de las funciones extractRegion() y clickAndDraw(), seleccionar
# una región en la primera imagen que esté presente en la segunda imagen.
# Para ello solo hay que fijar los vértices de un polígono que contenga
# a la región.
# * Extraiga los puntos SIFT contenidos en la región ... | img = cv2.imread(img_name, 1)
# Obtener los descriptores:
des = sift.detectAndCompute(img, None)[1]
# Normalizar los descriptores:
des_normalized = []
for d in des:
norm = np.linalg.norm(d)
# Ignoramos los descriptores nulos:
if norm ... | )[2]
sift = cv2.xfeatures2d.SIFT_create()
bf = cv2.BFMatcher(crossCheck=False)
# Inicializar el índice invertido:
indice_invert = dict()
for i in range(dicc.shape[0]):
indice_invert[i] = set()
# Inicializar la bolsa de palabras:
bolsa_palabras = dict()
for i in range(441):
... | identifier_body |
script.py | máscara con
# el parámetro mask).
# * Pinte las correspondencias encontrados sobre las imágenes.
# * Jugar con distintas parejas de imágenes, valorar las correspondencias
# correctas obtenidas y extraer conclusiones respecto a la utilidad de
# esta aproximación de recuperación de regiones/objetos de interés a
# part... | # Mostrar los ejemplos:
# en los dos primeros matches los parches son muy parecidos (casi idénticos)
# en el tercero, hay ligeras variaciones
# en el último son distintos: | random_line_split | |
script.py | aciendo uso de una máscara
# binaria o de las funciones extractRegion() y clickAndDraw(), seleccionar
# una región en la primera imagen que esté presente en la segunda imagen.
# Para ello solo hay que fijar los vértices de un polígono que contenga
# a la región.
# * Extraiga los puntos SIFT contenidos en la región ... | #####################################
# EJERCICIO 3:
#######################################################################################
# Visualización del vocabulario [3 puntos]
# • Usando las imágenes dadas en imagenesIR.rar se han extraido 600
# regiones de cada imagen de forma directa y se han re-escalado e... | .png', 1)
PintaMI([img, ima], "{}ª imagen más cercana: Similaridad = {:.4f}".format(i, similaridades[i][1]))
################################################## | conditional_block |
index_file_deleter.rs | (&self, files: &HashSet<String>) {
if let Err(e) = self.dec_ref_files(files) {
warn!("dec_ref_files_no_error failed with '{:?}'", e);
}
}
/// Returns true if the file should now be deleted.
fn dec_ref(&self, filename: &str) -> bool {
self.ensure_ref_count(filename);
... | }
pub fn has_dv_updates(&self) -> bool {
self.has_dv_updates
} | random_line_split | |
index_file_deleter.rs | _N file
// corresponding to the segmentInfos that was passed
// in. Yet, it must exist, because our caller holds
// the write lock. This can happen when the directory
// listing was stale (eg when index accessed via NFS
// client with sta... | {
let mut to_delete = HashSet::new();
for f in files {
if self.dec_ref(f) {
to_delete.insert(f.clone());
}
}
self.delete_files(&to_delete, true)
} | identifier_body | |
index_file_deleter.rs | files {
if self.dec_ref(f) {
to_delete.insert(f.clone());
}
}
self.delete_files(&to_delete, true)
}
pub fn dec_ref_files_no_error(&self, files: &HashSet<String>) {
if let Err(e) = self.dec_ref_files(files) {
warn!("dec_ref_files_no_er... | delete | identifier_name | |
index_file_deleter.rs | _file) = segment_infos.segment_file_name() {
let pattern = Regex::new(CODEC_FILE_PATTERN).unwrap();
for filename in files {
if pattern.is_match(filename)
|| filename.starts_with(INDEX_FILE_SEGMENTS)
|| filename.starts_with(INDEX_FILE_PENDIN... |
}
self.delete_commits()?;
self.inited = true;
Ok(starting_commit_deleted)
}
/// Set all gens beyond what we currently see in the directory, to avoid double-write
/// in cases where the previous IndexWriter did not gracefully close/rollback (e.g.
/// os/machine crashed... | {
starting_commit_deleted = true;
} | conditional_block |
goclass.go | to be as exact as the host can be ... but also concise
//if float64(int64(f)) != f { // not a simple integer
/*
frac, exp := math.Frexp(f)
intPart := int64(frac * float64(uint64(1)<<sigBits))
expPart := exp - int(sigBits)
if float64(intPart) == frac*float64(uint64(1)<<sigBits) &&
expPart >= -1022 &... | medConst(p | identifier_name | |
goclass.go | hx();` + "\n"
main += "}\n"
pos := "public static function CPos(pos:Int):String {\nvar prefix:String=\"\";\n"
pos += fmt.Sprintf(`if (pos==%d) return "(pogo.NoPosHash)";`, pogo.NoPosHash) + "\n"
pos += "if (pos<0) { pos = -pos; prefix= \"near \";}\n"
for p := len(pogo.PosHashFileList) - 1; p >= 0; p-- {
if p !=... | pos += fmt.Sprintf(`if(pos>%d) return prefix+"%s:"+Std.string(pos-%d);`,
pogo.PosHashFileList[p].BasePosHash,
strings.Replace(pogo.PosHashFileList[p].FileName, "\\", "\\\\", -1),
pogo.PosHashFileList[p].BasePosHash) + "\n"
}
pos += "else return \"(invalid pogo.PosHash:\"+Std.string(pos)+\")\";\n}\n"
if po... | pos += "else "
}
| conditional_block |
goclass.go | && nh != -1 {
n = fmt.Sprintf("GOint64.toFloat(Force.toInt64(GOint64.make(0x%x,0x%x)))", uint32(nh), uint32(nl))
}
if float64(d64i) == math.Pow(2, float64(exp)) {
haxeVal = n // divisor and multiplier the same
} else {
d := fmt.Sprintf("%d", dl)
if dh != 0 && dh != -1 {
d ... | pub := "public " // all globals have to be public in Haxe terms
//gTyp := glob.Type().Underlying().(*types.Pointer).Elem().Underlying() // globals are always pointers to an underlying element
/*
ptrTyp := "Pointer"
//ltDesc := "Dynamic" // these values suitable for *types.Struct
ltInit := "null"
switch gTyp.... | identifier_body | |
goclass.go | hx();` + "\n"
main += "}\n"
pos := "public static function CPos(pos:Int):String {\nvar prefix:String=\"\";\n"
pos += fmt.Sprintf(`if (pos==%d) return "(pogo.NoPosHash)";`, pogo.NoPosHash) + "\n"
pos += "if (pos<0) { pos = -pos; prefix= \"near \";}\n"
for p := len(pogo.PosHashFileList) - 1; p >= 0; p-- {
if p !=... | */
/*
val := exact.MakeFloat64(frac)
num := exact.Num(val)
den := exact.Denom(val)
n64i, nok := exact.Int64Val(num)
d64i, dok := exact.Int64Val(den)
res := float64(n64i) * math.Pow(2, float64(exp)) / float64(d64i)
if !math.IsNaN(res) && !math.IsInf(res, +1) && !math.IsInf(res, -1) { //drop thro... | if float64(intPart) == frac*float64(uint64(1)<<sigBits) &&
expPart >= -1022 && expPart <= 1023 {
//it is an integer in the correct range
haxeVal = fmt.Sprintf("(%d*Math.pow(2,%d))", intPart, expPart) // NOTE: need the Math.pow to avoid haxe constant folding
} | random_line_split |
ssh.rs | (
self,
kdf: &OpenSshKdf,
p: SecretString,
ct: &[u8],
) -> Result<Vec<u8>, DecryptError> {
match self {
OpenSshCipher::Aes256Cbc => decrypt::aes_cbc::<Aes256CbcDec>(kdf, p, ct),
OpenSshCipher::Aes128Ctr => Ok(decrypt::aes_ctr::<Aes128Ctr>(kdf, p, ct)),... | decrypt | identifier_name | |
ssh.rs | self {
OpenSshKdf::Bcrypt { salt, rounds } => {
let mut output = vec![0; out_len];
bcrypt_pbkdf(passphrase.expose_secret(), salt, *rounds, &mut output)
.expect("parameters are valid");
output
}
}
}
}
/// An encrypt... | }
}
mod decrypt {
use aes::cipher::{block_padding::NoPadding, BlockDecryptMut, KeyIvInit, StreamCipher};
use aes_gcm::aead::{AeadMut, KeyInit};
use age_core::secrecy::SecretString;
use cipher::generic_array::{ArrayLength, GenericArray};
use super::OpenSshKdf;
use crate::error::DecryptError... | Identity::Encrypted(_) => unreachable!(),
} | random_line_split |
ssh.rs | use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
use nom::{
branch::alt,
bytes::complete::{tag, take},
combinator::{flat_map, map, map_opt, map_parser, map_res, recognize, rest, verify},
multi::{length_data, length_value},
number::complete::be_u32,
... | {
Some(c1)
} | conditional_block | |
Rmag_aperture_annulus_per_target.py | 201907.txt'
file_info='gasp_target_fitsheader_info_slt2019.txt'
#file_info='gasp_target_fitsheader_info_slt'+date+'.txt'
#file_info='gasp_target_fitsheader_info_slt'+year+month+'.txt'
print('... will read '+file_info+' ...')
df_info=pd.read_csv(file_info,delimiter='|')
#print(df_info)
obj_name='3C345'
dir_obj='Rmag_I... | r_circle_as=r_circle*u.arcsec
r_inner=20.
r_outer=25.
r_inner_as=r_inner*u.arcsec
r_outer_as=r_outer*u.arcsec
aperture=SkyCircularAperture(positions, r_circle_as)
#print(aperture)
r_as=aperture.r
print('r_as =',r_as)
print('number of reference stars : ',n_refstar)
k=0
for i in idx_fitsheader:
print('--------------... | #sys.exit(0)
r_circle=15. | random_line_split |
Rmag_aperture_annulus_per_target.py | file_info='gasp_target_fitsheader_info_slt2019.txt'
#file_info='gasp_target_fitsheader_info_slt'+date+'.txt'
#file_info='gasp_target_fitsheader_info_slt'+year+month+'.txt'
print('... will read '+file_info+' ...')
df_info=pd.read_csv(file_info,delimiter='|')
#print(df_info)
obj_name='3C345'
dir_obj='Rmag_InstMag/'+obj... | mag_instrument[j]=-2.5*np.log10(final_sum[j])
print(j, final_sum[j],mag_instrument[j],rmag[j]) | conditional_block | |
save_secret_in_image_better.py | *2**np.arange(length-1, -1, -1).astype(object))
secret_test = "test123%$&/?!-_,:.;"
assert secret_test==convert_int_to_base_100(convert_base_100_to_int(secret_test))
assert 12345678901234567890==convert_base_100_to_int(convert_int_to_base_100(12345678901234567890))
assert 1234567==convert_lst_bin_to_int(convert_int... |
l_arr_secret_bin_content = [np.array(create_secret_bin_content(secret_str), dtype=np.uint8) for secret_str in l_secret_str]
# TODO: make this into a multiprocessing function too!
def find_best_possible_parameters(n : int=100):
def inner_function():
arr_line_param_offset : np.ndarray =... | secret_int : List[int] = convert_base_100_to_int(secret_str)
secret_bin : List[int] = convert_int_to_lst_bin(secret_int)
l_len_secret_bin = convert_int_to_lst_bin(len(secret_bin))
len_l_len_secret_bin = len(l_len_secret_bin)
assert len_l_len_secret_bin <= MIN_BITS_LENGTH
if len_l... | identifier_body |
save_secret_in_image_better.py | (num_int):
l = []
while num_int > 0:
l.append(num_int % base_100_len)
num_int //= base_100_len
n = list(map(lambda x: lst_int_base_100[x], reversed(l)))
return "".join(n)
def convert_int_to_lst_bin(num_int):
return list(map(int, bin(num_int)[2:]))
def convert_lst_bin_to_int(l_bin... | convert_int_to_base_100 | identifier_name | |
save_secret_in_image_better.py | fjksjfsjfsfjsdlfjafwefawoi'*6,
]
# amount_secrets = 2
# secret_len = 400
# l_secret_str = [''.join(np.random.choice(lst_int_base_100, (secret_len, ))) for _ in range(0, amount_secrets)]
MIN_BITS_LENGTH = 16
JUMP_MIN = 10
JUMP_MAX = 16
def create_secret_bin_content(secret_str : str) ->... | t_params = (jump, offset_prefix, offset_jump + len_arr_suffix)
print("t_params: {}".format(t_params))
l_possible_params.append(t_params) | conditional_block | |
save_secret_in_image_better.py | ([1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1]))
prefix_int : int = 0xabcd2533
suffix_int : int = 0x34bf4634
arr_prefix : np.ndarray = np.array(convert_int_to_lst_bin(prefix_int), dtype=np.uint8)
arr_suffix : np.ndarray = np.array(convert_int_to_lst_bin(suffix_int), dtype=np.uint8)
len_arr_prefix = arr_prefix.shape[0]
le... | Image.fromarray(pix_1_bit).save('images/img_path_src_1bit_encoded_in.png')
img_secret : Image = Image.fromarray(pix_secret)
img_secret.save(img_dst_path) | random_line_split | |
start.py | >")
# def set_token(token, allow_ip):
#
# if request.remote_addr != "127.0.0.1":
# #abort(403)
# return error("not allowed")
#
# cfg["token"]["value"] = token
# cfg["token"]["created"] = time.time()
# cfg["token"]["ip"] = allow_ip
# save_config(cfg, CONFIG_PATH)
#
# return succes... | log.info("backup/restore process finished successfully")
else:
backup_proc.parsed["state"] = "failed: " + backup_proc.parsed.get("unable", "")
if "target" in backup_proc.parsed:
if os.path.exists(backup_proc.parsed["target"]):
shutil.rmtree... | global backup_proc
out = dict(cfg["config"])
if backup_proc is None:
out["running"] = False
return out
assert isinstance(backup_proc, CommandRunner)
backup_proc.get_new_output()
if backup_proc.finished:
if backup_proc.returncode == 0:
backup_proc.parsed["state... | identifier_body |
start.py | # def set_token(token, allow_ip):
#
# if request.remote_addr != "127.0.0.1":
# #abort(403)
# return error("not allowed")
#
# cfg["token"]["value"] = token
# cfg["token"]["created"] = time.time()
# cfg["token"]["ip"] = allow_ip
# save_config(cfg, CONFIG_PATH)
#
# return success()
... | ():
global backup_proc
out = dict(cfg["config"])
if backup_proc is None:
out["running"] = False
return out
assert isinstance(backup_proc, CommandRunner)
backup_proc.get_new_output()
if backup_proc.finished:
if backup_proc.returncode == 0:
backup_proc.parse... | check_for_backup_process | identifier_name |
start.py | # def set_token(token, allow_ip):
#
# if request.remote_addr != "127.0.0.1":
# #abort(403)
# return error("not allowed")
#
# cfg["token"]["value"] = token
# cfg["token"]["created"] = time.time()
# cfg["token"]["ip"] = allow_ip
# save_config(cfg, CONFIG_PATH)
#
# return success()
... |
# save dyndns related values to configuration
elif request.method == "POST":
for key in request.form:
val = request.form.get(key)
if key == "conf":
old_conf = Path(DDCLIENT_CONFIG_PATH).read_text("utf-8")
if old_conf != val:
l... | data = dict(cfg["config"])
data["conf"] = Path(DDCLIENT_CONFIG_PATH).read_text("utf-8").split("\n")
return success(data=data) | conditional_block |
start.py | arsed:
if os.path.exists(backup_proc.parsed["target"]):
shutil.rmtree(backup_proc.parsed["target"])
log.error("backup/restore process failed, logging output: ")
for line in backup_proc.output[-30:]:
log.error(line.replace("\n", ""))... | @app.route("/dyndns/test/http")
@app.route("/dyndns/test/https") | random_line_split | |
Исследование_1705.py | зла
def word_dfs(node, ending=''):
result = [ending] if '#' in node else []
for ch in node:
if ch in ['#', 'n']: continue
result += word_dfs(node[ch], ch + ending)
return result
def num_prefix(prf):
return prefix_node(prf)['n']
# все основы, растущие из данного узла
def bases_with_af... | print("* Прямой ход * ")
next_affixes = direct_alg(bases[-1], specter[-1], false_affixes)
if not next_affixes:
break
else: | random_line_split | |
Исследование_1705.py | trie, prob
def build_cond_prob(voc, prob, len_search):
letters = list(prob.keys())
cond_prob = defaultdict(lambda: 0) # словарь для условных вероятностей
total = defaultdict(lambda: 0)
for word, n in voc.items(): # для слова в словаре
positions = range(-min(len_search, len(word) - 2), 0) ... | ontrol_bases) == 1:
lower = [(b, freq) for b, freq in freq_cur_bases | if len(c | identifier_name |
Исследование_1705.py | return trie, prob
def build_cond_prob(voc, prob, len_search):
letters = list(prob.keys())
cond_prob = defaultdict(lambda: 0) # словарь для условных вероятностей
total = defaultdict(lambda: 0)
for word, n in voc.items(): # для слова в словаре
positions = range(-min(len_search, len(word) - ... | current_dict[ch]
else:
break
aff_len += 1
return affix
# узел trie, соответствующий окончанию aff
def affix_node(aff):
global trie
current_node = trie
for char in aff[::-1]:
current_node = current_node[char]
return current_node
# узел trie, соответст... | длины аффикса
while aff_len < len_search:
# составляем список всех букв предшествующих аффиксу с количествами
L = [(l, current_dict[l]["n"]) for l in current_dict.keys() if l not in '#n']
# сортируем по количествам
L.sort(key=itemgetter(1), reverse=True)
# if affix=='нан':
... | identifier_body |
Исследование_1705.py | , prob, len_search):
letters = list(prob.keys())
cond_prob = defaultdict(lambda: 0) # словарь для условных вероятностей
total = defaultdict(lambda: 0)
for word, n in voc.items(): # для слова в словаре
positions = range(-min(len_search, len(word) - 2), 0) # from -7 to 0
for i in posi... | cont | conditional_block | |
Player.js | const [ draggingLeft, setDraggingLeft ] = useState(0);
const [ jokerSelect, setJokerSelect ] = useState(undefined);
const [ jokerValue, setJokerValue ] = useState({rank: 'two', suit: 'spades'});
const [ cardWidth, setCardWidth ] = useState(0);
const playerWidth = useRef(0);
const draggingRef = useRef([])... |
const [ selected, setSelected ] = useState([]);
const [ order, setOrder ] = useState(cards.map(card => card.id)); | random_line_split | |
Player.js | const [ jokerValue, setJokerValue ] = useState({rank: 'two', suit: 'spades'});
const [ cardWidth, setCardWidth ] = useState(0);
const playerWidth = useRef(0);
const draggingRef = useRef([]);
const selectedRef = useRef([]);
// Need the ref to be able to get and set current value in effect
// Need state ... |
}
if (point1 >= 0 && point2 >= 0) {
const touchOneChange = touches[0].pageX - lastTouches[point1].pageX;
const touchTwoChange = touches[1].pageX - lastTouches[point2].pageX;
// check if swipe
if (touchOneChange * touchTwoChange > 0) {
return { type:... | { point2 = i; } | conditional_block |
Player.js | const [ jokerValue, setJokerValue ] = useState({rank: 'two', suit: 'spades'});
const [ cardWidth, setCardWidth ] = useState(0);
const playerWidth = useRef(0);
const draggingRef = useRef([]);
const selectedRef = useRef([]);
// Need the ref to be able to get and set current value in effect
// Need state ... |
function selectCard(card) {
// make all jokers two of spades (until select feature done)
// const joker = { rank: 'two', suit: 'spades' };
// const playedCard = {
// ...joker,
// ...card,
// is_joker: card.type === 'joker'
// };
const filteredSelect = selected.filter(selectedC... | {
const minScroll = playerRef.current
? playerRef.current.parentElement.offsetWidth - (cards.length * cardOverlapRef.current + (cardWidth - cardOverlapRef.current))
: -Infinity;
return Math.min(0, Math.max(minScroll, scroll));
} | identifier_body |
Player.js | const [ jokerValue, setJokerValue ] = useState({rank: 'two', suit: 'spades'});
const [ cardWidth, setCardWidth ] = useState(0);
const playerWidth = useRef(0);
const draggingRef = useRef([]);
const selectedRef = useRef([]);
// Need the ref to be able to get and set current value in effect
// Need state... | (card) {
// make all jokers two of spades (until select feature done)
// const joker = { rank: 'two', suit: 'spades' };
// const playedCard = {
// ...joker,
// ...card,
// is_joker: card.type === 'joker'
// };
const filteredSelect = selected.filter(selectedCard => selectedCard.id ... | selectCard | identifier_name |
wd.rs | >,
) -> Result<url::Url, url::ParseError>;
/// The HTTP request method to use, and the request body for the request.
///
/// The `url` will be the one returned from the `endpoint()` method above.
fn method_and_body(&self, request_url: &url::Url) -> (http::Method, Option<String>);
/// Return tr... | }
/// Return true if this session should only support the legacy webdriver protocol.
///
/// This only applies to the obsolete JSON Wire Protocol and should return `false`
/// for all implementations that follow the W3C specification.
///
/// See <https://www.selenium.dev/documentation/lega... | random_line_split | |
wd.rs | ) -> Result<url::Url, url::ParseError>;
/// The HTTP request method to use, and the request body for the request.
///
/// The `url` will be the one returned from the `endpoint()` method above.
fn method_and_body(&self, request_url: &url::Url) -> (http::Method, Option<String>);
/// Return true ... | (&self, request_url: &Url) -> (Method, Option<String>) {
T::method_and_body(self, request_url)
}
fn is_new_session(&self) -> bool {
T::is_new_session(self)
}
fn is_legacy(&self) -> bool {
T::is_legacy(self)
}
}
/// A [handle][1] to a browser window.
///
/// Should be obtai... | method_and_body | identifier_name |
plotting_utils.py | If not provided, something sensible is chosen.
bins:
Number of bins to put the chains into.
levs:
Contour levels, in sigma. Default is 1,2,3sigma regions.
Returns:
axobj:
The same axis object passed here, now with the regions plotted.
... | (um_rest,Sfit,um_data,mjy_data,mjy_errors,axobj,*args,**kwargs):
"""
Plot an SED
"""
sedcolor = kwargs.pop('sedcolor','b')
axobj.set_axis_on()
axobj.plot(um_rest,Sfit,color=sedcolor,ls='-')
axobj.set_xscale('log'); axobj.set_yscale('log')
axobj.set_xlabel('$\\lambd... | plot_sed | identifier_name |
plotting_utils.py | If not provided, something sensible is chosen.
bins:
Number of bins to put the chains into.
levs:
Contour levels, in sigma. Default is 1,2,3sigma regions.
Returns:
axobj:
The same axis object passed here, now with the regions plotted.
... | # Shield ourselves against nans or infinities.
x = x[np.isfinite(x) & np.isfinite(y)]
y = y[np.isfinite(x) & np.isfinite(y)]
# do some unit conversions for the sake of our collective sanity
if 'lambda' in labels... | """
Assemble the MCMC samples into the usual triangle plot format.
Parameters:
samples: 2-D array
Array of MCMC samples, of shape (Nsamples,Nparameters)
labels: list of strings
What to label the axes. Latex math-mode is okay.
Returns:
f,axarr: ma... | identifier_body |
plotting_utils.py | If not provided, something sensible is chosen.
bins:
Number of bins to put the chains into.
levs:
Contour levels, in sigma. Default is 1,2,3sigma regions.
Returns:
axobj:
The same axis object passed here, now with the regions plotted.
... |
if mjy_data[i] > 0:
axobj.errorbar(point,mjy_data[i],yerr=mjy_errors[i],color=color,\
marker='o')
else: # Draw upper limits, but make errobar sizes consistent on log-log
ylims,xlims = axobj.get_ylim(), axobj.get_xlim()
... | color = 'r' | conditional_block |
plotting_utils.py | .
If not provided, something sensible is chosen.
bins:
Number of bins to put the chains into.
levs:
Contour levels, in sigma. Default is 1,2,3sigma regions.
Returns:
axobj:
The same axis object passed here, now with the regions plotted.
... | altax.set_xlim(axobj.get_xlim()[0],axobj.get_xlim()[1])
altax.set_ylim(axobj.get_ylim()[0],axobj.get_ylim()[1])
altax.set_xscale('log'); altax.set_xlabel('$\\lambda_{rest}$, $\\mu m$')
# Plot the data points, and plot upper limits if they exist
for i,point in enumerate(um_data):
... | axobj.set_ylim(0.5*mjy_data[mjy_data>0.].min(),2*np.max(Sfit))
altax = axobj.twiny() | random_line_split |
decoder.rs | UnrepresentableLengthError),
#[error(display = "UnknwonSizeNotAllowedInChildElement: pos {:?}", _0)]
UnknwonSizeNotAllowedInChildElement(ebml::ElementPosition),
#[error(display = "ReadContent")]
ReadContent(#[error(cause)] ReadContentError),
#[error(display = "UnknownEbmlId: {:?}", _0)]
Unknown... | if parent_pos.r#type != 'm' {
// throw new Error("parent element is not master element");
unreachable!();
}
self.queue.push(
(
ebml::MasterEndElement {
ebml_id: parent_pos.ebml_id,
... | }
// 閉じタグを挿入すべきタイミングが来た | random_line_split |
decoder.rs | representableLengthError),
#[error(display = "UnknwonSizeNotAllowedInChildElement: pos {:?}", _0)]
UnknwonSizeNotAllowedInChildElement(ebml::ElementPosition),
#[error(display = "ReadContent")]
ReadContent(#[error(cause)] ReadContentError),
#[error(display = "UnknownEbmlId: {:?}", _0)]
UnknownEbm... | eadContentError {
#[error(display = "Date")]
Date(#[error(cause)] std::io::Error),
#[error(display = "Utf8")]
Utf8(#[error(cause)] std::io::Error),
#[error(display = "UnsignedInteger")]
UnsignedInteger(#[error(cause)] std::io::Error),
#[error(display = "Integer")]
Integer(#[error(cause)]... | // スタックからこのタグを捨てる
self.stack.pop();
}
Ok(true)
}
}
#[derive(Debug, Error)]
pub enum R | conditional_block |
decoder.rs | representableLengthError),
#[error(display = "UnknwonSizeNotAllowedInChildElement: pos {:?}", _0)]
UnknwonSizeNotAllowedInChildElement(ebml::ElementPosition),
#[error(display = "ReadContent")]
ReadContent(#[error(cause)] ReadContentError),
#[error(display = "UnknownEbmlId: {:?}", _0)]
UnknownEbm... |
}
impl From<ReadContentError> for DecodeError {
fn from(o: ReadContentError) -> Self {
DecodeError::ReadContent(o)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum State {
Tag,
Size,
Content,
}
pub struct Decoder<'a, D: SchemaDict<'a>> {
schema: &'a D,
... | {
DecodeError::ReadVint(o)
} | identifier_body |
decoder.rs | UnrepresentableLengthError),
#[error(display = "UnknwonSizeNotAllowedInChildElement: pos {:?}", _0)]
UnknwonSizeNotAllowedInChildElement(ebml::ElementPosition),
#[error(display = "ReadContent")]
ReadContent(#[error(cause)] ReadContentError),
#[error(display = "UnknownEbmlId: {:?}", _0)]
Unknown... | (o: ReadContentError) -> Self {
DecodeError::ReadContent(o)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum State {
Tag,
Size,
Content,
}
pub struct Decoder<'a, D: SchemaDict<'a>> {
schema: &'a D,
state: State,
buffer: Vec<u8>,
cursor: usize,
to... | from | identifier_name |
message.py | value = self.kwpop(kw, new_name)
return value
def send(self):
return interface.send(self)
# --------------------------------------------------------------------------
# Deprecated properties
def _warn_about_deprecated_property(self, deprecated_name, new_name):
msg = '... | random_line_split | ||
message.py | kw.pop(name)
else:
if configkey == None:
configkey = 'mail.message.%s' % name
value = interface.config.get(configkey, NoDefault)
if value == NoDefault and old_configkey != None:
value = interface.config.get(old_configkey, NoDefaul... | self.subject = subject
self.date = kwpop("date")
self.encoding = kwpop("encoding", default='us-ascii',
old_configkey='mail.encoding')
self.organization = kwpop("organization")
self.priority = kwpop("priority")
self... | """Instantiate a new Message object.
No arguments are required, as everything can be set using class
properties. Alternatively, I{everything} can be set using the
constructor, using named arguments. The first three positional
arguments can be used to quickly prepare a simple m... | identifier_body |
message.py | .pop(name)
else:
if configkey == None:
configkey = 'mail.message.%s' % name
value = interface.config.get(configkey, NoDefault)
if value == NoDefault and old_configkey != None:
value = interface.config.get(old_configkey, NoDefault)
... | (self, kw, new_name, deprecated_name, value=None):
deprecated_value = self.kwpop(kw, deprecated_name)
if deprecated_value != None:
self._warn_about_deprecated_property(deprecated_name, new_name)
value = deprecated_value
elif value == None:
value = self.kwpop(k... | pop_deprecated | identifier_name |
message.py | kw.pop(name)
else:
if configkey == None:
configkey = 'mail.message.%s' % name
value = interface.config.get(configkey, NoDefault)
if value == NoDefault and old_configkey != None:
value = interface.config.get(old_configkey, NoDefaul... |
def mime(self):
"""Produce the final MIME message."""
author = self.author
sender = self.sender
if not author and sender:
msg = 'Please specify the author using the "author" property. ' + \
'Using "sender" for the From header is deprecated!'
... | message.add_header(**header) | conditional_block |
kubeseal.go | )
return enc, nil
}
func isFilename(name string) (bool, error) {
u, err := url.Parse(name)
if err != nil {
return false, err
}
// windows drive letters
if s := strings.ToLower(u.Scheme); len(s) == 1 && s[0] >= 'a' && s[0] <= 'z' {
return true, nil
}
return u.Scheme == "", nil
}
// getServicePortName obtai... |
conf.AcceptContentTypes = "application/x-pem-file, */*"
restClient, err := corev1.NewForConfig(conf)
if err != nil {
return nil, err
}
return openCertCluster(ctx, restClient, controllerNs, controllerName)
}
// Seal reads a k8s Secret resource parsed from an input reader by a given codec, encrypts all its secre... | {
return nil, err
} | conditional_block |
kubeseal.go | .ReadCloser, error) {
if certURL != "" {
return openCertLocal(certURL)
}
conf, err := clientConfig.ClientConfig()
if err != nil {
return nil, err
}
conf.AcceptContentTypes = "application/x-pem-file, */*"
restClient, err := corev1.NewForConfig(conf)
if err != nil {
return nil, err
}
return openCertClust... | EncryptSecretItem | identifier_name | |
kubeseal.go | )
return enc, nil
}
func isFilename(name string) (bool, error) {
u, err := url.Parse(name)
if err != nil {
return false, err
}
// windows drive letters
if s := strings.ToLower(u.Scheme); len(s) == 1 && s[0] >= 'a' && s[0] <= 'z' {
return true, nil
}
return u.Scheme == "", nil
}
// getServicePortName obtai... |
if len(secret.Data) == 0 && len(secret.StringData) == 0 && !allowEmptyData {
return fmt.Errorf("secret.data is empty in input Secret, assuming this is an error and aborting. To work with empty data, --allow-empty-data can be used")
}
if overrideName != "" {
secret.Name = overrideName
}
if secret.GetName() =... | if err != nil {
return err
} | random_line_split |
kubeseal.go | (uri string) (io.ReadCloser, error) {
// support file:// scheme. Note: we're opening the file using os.Open rather
// than using the file:// scheme below because there is no point in complicating our lives
// and escape the filename properly.
t := &http.Transport{}
// #nosec: G111 -- we want to allow all files to... | {
// #nosec G304 -- should open user provided file
f, err := os.OpenFile(filename, os.O_RDWR, 0)
if err != nil {
return err
}
// #nosec G307 -- we are explicitly managing a potential error from f.Close() at the end of the function
defer f.Close()
b, err := io.ReadAll(f)
if err != nil {
return err
}
orig... | identifier_body | |
TableLaporan.ts | ) {
$sql = /** @lang SQL */ "
-- FILE: ".__FILE__."
-- LINE: ".__LINE__."
SELECT nama_smf
FROM rsupf.master_smf
WHERE kode = '{$resep->idPegawai}'
... | <?php
$this->output = ob_get_contents(); | random_line_split | |
TableLaporan.ts | ,
string $smfSelect
) {
$toUserDate = Yii::$app->dateTime->transformFunc("toUserDate");
$toUserFloat = Yii::$app->number->toUserFloat();
$h = fn(string $str): string => Yii::$app->hash($str);
ob_clean();
ob_start();
$daftarResep = [];
$connection = Yii... | else {
$racik++;
}
if ($resep->noResep != $resepnow) {
if ($resepnow) {
$tdSmf = $smfIsAll ? '<td></td>' : "";
$tdDokter = $dokterIsAll ? '<td></td>' : "";
$html .= "
... | {
$r++;
} | conditional_block |
TableLaporan.ts | Select,
string $smfSelect
) {
$toUserDate = Yii::$app->dateTime->transformFunc("toUserDate");
$toUserFloat = Yii::$app->number->toUserFloat();
$h = fn(string $str): string => Yii::$app->hash($str);
ob_clean();
ob_start();
$daftarResep = [];
$connection... | () {
minTanggalMulai = this._value;
},
...tlm.dateWidgetSetting
});
const tanggalSelesaiWgt = new spl.DateTimeWidget({
| onBeforeCloseDatetimePicker | identifier_name |
TableLaporan.ts | ,
string $smfSelect
) {
$toUserDate = Yii::$app->dateTime->transformFunc("toUserDate");
$toUserFloat = Yii::$app->number->toUserFloat();
$h = fn(string $str): string => Yii::$app->hash($str);
ob_clean();
ob_start();
$daftarResep = [];
$connection = Yii... | ,
onBeforeCloseDatetimePicker() {
minTanggalMulai = this._value;
},
...tlm.dateWidgetSetting
});
const tanggalSelesaiWgt = new spl.DateTimeWidget | {
this._maxDate = maksTanggalSelesai;
} | identifier_body |
ItemView.js | ItemOrderNumbers = $('#ArrowsAndItemOrderNumbers');
$backArrow = $('#ArrowBack');
$forwardArrow = $('#ArrowForward');
$itemOrderNumbers = $('#ItemOrderNumbers');
$avatar = $('#Avatar');
};
/**
* FIXME
* Now I don't fetch item details from the backend because the index... | // The angle of the direction we take to get to the item. Used to rotate the carpet accordingly
const angle = Math.atan2(delta_y, delta_x) * (180 / Math.PI);
if (performAnimations) {
// Rotating the carpet
$carpet.velocity({ trans... | // Differences in x and y we need to travel to get to the item from the current position
const delta_x = (currentLeft - positionItemToVisitNext.left);
const delta_y = (currentTop - positionItemToVisitNext.top);
| random_line_split |
ItemView.js | ItemOrderNumbers = $('#ArrowsAndItemOrderNumbers');
$backArrow = $('#ArrowBack');
$forwardArrow = $('#ArrowForward');
$itemOrderNumbers = $('#ItemOrderNumbers');
$avatar = $('#Avatar');
};
/**
* FIXME
* Now I don't fetch item details from the backend because the index... |
// The angle of the direction we take to get to the item. Used to rotate the carpet accordingly
const angle = Math.atan2(delta_y, delta_x) * (180 / Math.PI);
if (performAnimations) {
// Rotating the carpet
$carpet.velocity({ tran... | {
const viewport = viewModel.getViewPort();
// When performing the animation the View Model needs to know so that it
// can tell other views
viewModel.setAnimationToNextItemRunning(true);
// left and top attributes to give to the map to ... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.