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
timer.rs
`advance_to` is what actually fires timers on the `Timer`, and should be /// called essentially every iteration of the event loop, or when the time /// specified by `next_wake` has elapsed. /// * The `Future` implementation for `Timer` is used to process incoming timer /// updates and requests. This is used to s...
(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Pin::new(&mut self.inner).waker.register(cx.waker()); let mut list = self.inner.list.take(); while let Some(node) = list.pop() { let at = *node.at.lock().unwrap(); match at { Some(at)...
poll
identifier_name
timer.rs
<Inner>, } pub(crate) struct Inner { /// List of updates the `Timer` needs to process pub(crate) list: ArcList<ScheduledTimer>, /// The blocked `Timer` task to receive notifications to the `list` above. pub(crate) waker: AtomicWaker, } /// Shared state between the `Timer` and a `Delay`. pub(crate) st...
random_line_split
openapi_terraform_provider_doc_generator.go
ser("v2", openAPIDocURL) if err != nil { return TerraformProviderDocGenerator{}, err } return TerraformProviderDocGenerator{ ProviderName: providerName, Hostname: hostname, Namespace: namespace, SpecAnalyser: analyser, }, nil } // GenerateDocumentation creates a TerraformProviderDocumentation obje...
{ schema = append(schema, t.resourceSchemaToProperty(*p)) }
conditional_block
openapi_terraform_provider_doc_generator.go
.0" OpenAPI provider version PluginVersionConstraint string // SpecAnalyser analyses the swagger doc and provides helper methods to retrieve all the end points that can // be used as terraform resources. SpecAnalyser openapi.SpecAnalyser } // NewTerraformProviderDocGenerator returns a TerraformProviderDocGenerator...
func getSecurity(s openapi.SpecAnalyser) (openapi.SpecSecuritySchemes, *openapi.SpecSecurityDefinitions, error) { security := s.GetSecurity() if security != nil { globalSecuritySchemes, err := security.GetGlobalSecuritySchemes() if err != nil { return nil, nil, err } securityDefinitions, err := security....
{ backendConfig, err := s.GetAPIBackendConfiguration() if err != nil { return nil, err } if backendConfig != nil { _, _, regions, err := backendConfig.IsMultiRegion() if err != nil { return nil, err } return regions, nil } return nil, nil }
identifier_body
openapi_terraform_provider_doc_generator.go
.0" OpenAPI provider version PluginVersionConstraint string // SpecAnalyser analyses the swagger doc and provides helper methods to retrieve all the end points that can // be used as terraform resources. SpecAnalyser openapi.SpecAnalyser } // NewTerraformProviderDocGenerator returns a TerraformProviderDocGenerator...
(s openapi.SpecAnalyser) ([]string, error) { backendConfig, err := s.GetAPIBackendConfiguration() if err != nil { return nil, err } if backendConfig != nil { _, _, regions, err := backendConfig.IsMultiRegion() if err != nil { return nil, err } return regions, nil } return nil, nil } func getSecurity...
getRegions
identifier_name
openapi_terraform_provider_doc_generator.go
1.0" OpenAPI provider version PluginVersionConstraint string // SpecAnalyser analyses the swagger doc and provides helper methods to retrieve all the end points that can // be used as terraform resources. SpecAnalyser openapi.SpecAnalyser } // NewTerraformProviderDocGenerator returns a TerraformProviderDocGenerato...
return TerraformProviderDocumentation{}, errors.New("namespace not provided, this is required to be able to render the provider installation section containing the required_providers block with the source address configuration in the form of [<HOSTNAME>/]<NAMESPACE>/<TYPE>") } if t.PluginVersionConstraint == "" { ...
if t.Namespace == "" {
random_line_split
Teach.js
index, target, record, e, eOpts ) { var me = this; console.log(record) me.topic = Ext.create('Youngshine.view.teach.Topic') me.topic.setParentRecord(record); //me.topic.down('toolbar').setTitle(record.data.studentName) Ext.Viewport.setMasked({xtype:'loadmask',message:'正在加载'}); // 预先加载的数据 var obj = {...
topicteachphotosBack: function(){ var me = this Ext.Viewport.setActiveItem(me.topicteach) Ext.Viewport.remove(me.topicteachphotos,true)
random_line_split
Teach.js
// 全部下课,才能开始上课 Ext.Array.each(records, function(record) { console.log(record.data) if(record.data.endTime < '1901-01-01'){ me.course.down('button[action=addnew]').setDisabled(true) return false } }); */ }else{ Ext.toast('服务请求失败',3000); // toast 1000 }; } ...
html: record.data.content, itemId: 'topicContent', styleHtmlContent: true }], }) this.overlay.show() } }, topicshowBack: function(oldView){ var me = this; Ext.Viewport.setActiveItem(me.topic) Ext.Viewport.remove(me.topicshow,true) }, top
conditional_block
networkBuilder.go
// WithStatsAggregator sets the stats aggregators to the network func (n *NetworkBuilder) WithStatsAggregator(aggregators []workloads.StatsAggregator) *NetworkBuilder { n.Network.StatsAggregator = aggregators return n } // WithNetworkResources sets the network resources to the network func (n *NetworkBuilder) With...
{ n.Network.Iprange = ipRange return n }
identifier_body
networkBuilder.go
func (n *NetworkBuilder) WithStatsAggregator(aggregators []workloads.StatsAggregator) *NetworkBuilder { n.Network.StatsAggregator = aggregators return n } // WithNetworkResources sets the network resources to the network func (n *NetworkBuilder) WithNetworkResources(netResources []workloads.NetworkNetResource) *Netw...
// WithStatsAggregator sets the stats aggregators to the network
random_line_split
networkBuilder.go
need to add allowedIPs // for the hidden nodes if onr.NodeId == pubNr { for _, subnet := range hiddenSubnets { allowedIPs = append(allowedIPs, subnet) allowedIPs = append(allowedIPs, *wgIP(&schema.IPRange{subnet.IPNet})) } } // Since the node is not hidden, we know that it MUST h...
isCGN
identifier_name
networkBuilder.go
(n schema.IPRange) bool { ones, bits := n.IPNet.Mask.Size() if bits != 32 { return false } return ones <= 30 } func genWGQuick(wgPrivateKey string, localSubnet schema.IPRange, peerWgPubKey string, allowedSubnet schema.IPRange, peerEndpoint string) (string, error) { type data struct { PrivateKey string Ad...
{ for _, ip := range iface.Addrs { if !ip.IP.IsGlobalUnicast() || isPrivateIP(ip.IP) { continue } endpoints = append(endpoints, ip) } }
conditional_block
mf6_data_tutorial06.py
# format_version: "1.5" # jupytext_version: 1.5.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # metadata: # section: mf6 # --- # # MODFLOW 6: Working with MODFLOW List Data. # # This tutorial shows how to view, access, and change the underlying data # varia...
# extension: .py # format_name: light
random_line_split
business-export-import.component.ts
(element => element.ma_nganh_nghe.length > 3 ? this.categories.push(element.ten_kem_ma) : 0); }); this.filteredCareerList = this.control.valueChanges.pipe( startWith(''), map(value => this._filter(value)) ); } public getAllCompanyImport() { console.log("+ Function: getAllCompanyImpor...
rn ''; } else { return value.trim(); } } public getCurrentMonth() { var c
identifier_body
business-export-import.component.ts
[null]; public loading: boolean = false; public types = ['Dạng thẻ', 'Dạng bảng']; public page: number = 1; public pager: any = {}; public selectedPeriod: string = ""; public periods = ["Tháng", "Quý", "6 Tháng", "Năm"]; public months: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; public quarters...
valueOfYear, valueOfPeriodDetail); this._marketService.GetAllCompanyExport(valueOfPeriod, valueOfYear, valueOfPeriodDetail, this.isSCT).subscribe( allrecords => { if (allrecords.data.length > 0) { this.dataSource = new MatTableDataSource<CompanyDetailModel>(allrecords.data[0]); if...
valueOfYear = this.selectedYear; console.log(valueOfPeriod,
conditional_block
business-export-import.component.ts
null]; public loading: boolean = false; public types = ['Dạng thẻ', 'Dạng bảng']; public page: number = 1; public pager: any = {}; public selectedPeriod: string = ""; public periods = ["Tháng", "Quý", "6 Tháng", "Năm"]; public months: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; public quarters: ...
istrict()"); this._marketService.GetAllDistrict().subscribe( allrecords => { this.districtList = allrecords.data as DistrictModel[]; this.districtList.forEach(element => this.addresses.push(element.ten_quan_huyen)); }); } public getAllNganhNghe() { console.log("+ Function: GetAll...
ction: GetAllD
identifier_name
business-export-import.component.ts
= false; //Viewchild @ViewChild('TABLE1', { static: false }) table: ElementRef; @ViewChild('scheduledOrdersPaginator', { static: true }) paginator: MatPaginator; @ViewChild('scheduledOrdersPaginator1', { static: true }) paginator1: MatPaginator; @ViewChild('selected_Career', { static: false }) careerEle: Ele...
random_line_split
merge_queryable.go
} // ensure the name of a retained tenant id label gets handled under the // original label name if name == originalDefaultTenantLabel { name = defaultTenantLabel } return m.mergeDistinctStringSlice(func(ctx context.Context, q storage.Querier) ([]string, storage.Warnings, error) { return q.LabelValues(name, ...
{ upstream := m.upstream.Warnings() warnings := make(storage.Warnings, len(upstream)) for pos := range upstream { warnings[pos] = errors.Wrapf(upstream[pos], "warning querying %s", labelsToString(m.labels)) } return warnings }
identifier_body
merge_queryable.go
Names) && labelNames[labelPos] == defaultTenantLabel { tenantLabelExists = true } labelToAdd := defaultTenantLabel // if defaultTenantLabel already exists, we need to add the // originalDefaultTenantLabel if tenantLabelExists { labelToAdd = originalDefaultTenantLabel labelPos = sort.SearchStrings(labelName...
setLabelsRetainExisting
identifier_name
merge_queryable.go
nil } // ensure the name of a retained tenant id label gets handled under the // original label name if name == originalDefaultTenantLabel { name = defaultTenantLabel } return m.mergeDistinctStringSlice(func(ctx context.Context, q storage.Querier) ([]string, storage.Warnings, error) { return q.LabelValues(...
} return warnings
random_line_split
merge_queryable.go
m *mergeQueryable) Querier(ctx context.Context, mint int64, maxt int64) (storage.Querier, error) { tenantIDs, err := tenant.TenantIDs(ctx) if err != nil { return nil, err } if len(tenantIDs) <= 1 { return m.upstream.Querier(ctx, mint, maxt) } var queriers = make([]storage.Querier, len(tenantIDs)) for pos, ...
return errs.Err() } type selectJob struct { pos int querier storage.Querier tenantID string } // Select returns a set of series that matches the given label matchers. If the // tenantLabelName is matched on it only considers those queriers matching. The // forwarded labelSelector is not containing those th...
{ errs.Add(errors.Wrapf(m.queriers[pos].Close(), "failed to close querier for %s %s", rewriteLabelName(defaultTenantLabel), tenantID)) }
conditional_block
model.py
# Model class constructor def __init__(self, gpu): ''' Initialise model object ''' # Set device if (gpu): self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") else: self.device = "cpu" # Function to build model def
(self, arch, learning_rate, hidden_units): ''' Function to build model ''' print('Building model...') # Select & load pre-trained model try: arch = arch.lower() self.model = models.__dict__[arch](pretrained=True) self.arch = arch excep...
build
identifier_name
model.py
# Model class constructor
self.model = models.__dict__[arch](pretrained=True) self.arch = arch except: print("Model " + arch + " not recognised: please refer to documentation for valid model names in pytorch ie vgg16 https://pytorch.org/docs/stable/torchvision/models.html") sys.exit() ...
def __init__(self, gpu): ''' Initialise model object ''' # Set device if (gpu): self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") else: self.device = "cpu" # Function to build model def build(self, arch, learning_rate,...
identifier_body
model.py
# Model class constructor def __init__(self, gpu): ''' Initialise model object ''' # Set device if (gpu): self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") else: self.device = "cpu" # Function to build model def b...
# Switch to evaluation mode - dropout inactive self.model.eval() # Disable gradients - not needed for model prediction with torch.no_grad(): # Do forward pass through network logps = self.model.forward(image_tensor) # Get actual probabilties output f...
# Convert to float tensor image_tensor = image_tensor.float()
random_line_split
model.py
# Model class constructor def __init__(self, gpu): ''' Initialise model object ''' # Set device if (gpu): self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") else: self.device = "cpu" # Function to build model def b...
# Classifier architecture parameters classifier_output_neurons = 102 classifier_dropout = 0.2 # Build new classifier for recognising flowers to work with model self.model.classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(classifi...
print("Unable to determine classifier input units number - unable to create model") return
conditional_block
longfruit.py
prog = 'clang' opts = [ '-Wno-literal-conversion', '-Wno-implicit-int-float-conversion' ] if arch == 'rv64gc': opts.append('--target=riscv64') elif arch == 'rv32gc': opts.append('--target=riscv32') else: assert F...
passed = False for arch, abi in scenarios: c1, c2, asm1, asm2 = run_test(source_file, arch, abi) print(c1, c2)
random_line_split
longfruit.py
z': cost_branch, 'blt': cost_branch, 'bltu': cost_branch, 'bltz': cost_branch, 'bne': cost_branch, 'bnez': cost_branch, 'call': cost_call, 'div': cost_div, 'divu': cost_div, 'divuw': cost_div, 'divw': cost_div, 'ebreak': cost_ebreak...
else: v = f'i{self.var_counter}' self.var_counter = self.var_counter + 1 self.vars.append(v) return v def gen_vars(self, num): return [self.gen_var() for i in range(randint(1, num))] def rand_var(self): return choice(self.vars) def copy(self): ...
v = f'v{self.var_counter}'
conditional_block
longfruit.py
cost_branch, 'lb': cost_load_store, 'lbu': cost_load_store, 'ld': cost_load_store, 'lh': cost_load_store, 'lhu': cost_load_store, 'lui': cost_alu, 'lw': cost_load_store, 'lwu': cost_load_store, 'mul': cost_mul, 'mulh': cost_mul, 'm...
unit = gen_globals(ctx) unit = f'{unit}{gen_func(ctx)}\n' return unit
identifier_body
longfruit.py
': cost_alu, 'not': cost_alu, 'or': cost_alu, 'ori': cost_alu, 'rem': cost_div, 'remu': cost_div, 'remuw': cost_div, 'remw': cost_div, 'ret': cost_ret, 'sb': cost_load_store, 'sd': cost_load_store, 'seqz': cost_alu, 'sext': ...
write_config
identifier_name
main.rs
in sync.items { tasks.push(item.into()); } Self { tasks, } } } #[derive(Debug)] struct Task { item: Item, } impl From<Item> for Task { fn from(item: Item) -> Self { Self { item } } } #[derive(Debug, Deserialize)] struct Sync { /// A new sy...
(u64); #[derive(Debug, Deserialize)] struct Filter { id: FilterId, name: String, query: String, color: Color, item_order: Order, is_deleted: Flag, is_favorite: Flag, } #[derive(Debug, Deserialize)] struct FilterId(u64); #[derive(Debug, Deserialize)] struct Collaborator { id: Collabora...
LabelId
identifier_name
main.rs
std::{collections::BTreeMap, io::Read, fs::File, process::Command}, }; fn main() -> Result<(), Failure> { let mut file = File::open("token")?; let mut token = String::new(); file.read_to_string(&mut token)?; token.insert_str(0, "token="); let output = &Command::new("curl").args(&["https://api.t...
serde::Deserialize, serde_json, serde_repr::Deserialize_repr,
random_line_split
secrets.go
DeleteReplicatedResource: repl.DeleteReplicatedResource, } return &repl } // ReplicateDataFrom takes a source object and copies over data to target object func (r *Replicator) ReplicateDataFrom(sourceObj interface{}, targetObj interface{}) error { source := sourceObj.(*v1.Secret) target := targetObj.(*v1.Secre...
{ repl := Replicator{ GenericReplicator: common.NewGenericReplicator(common.ReplicatorConfig{ Kind: "Secret", ObjType: &v1.Secret{}, AllowAll: allowAll, ResyncPeriod: resyncPeriod, Client: client, ListFunc: func(lo metav1.ListOptions) (runtime.Object, error) { return clie...
identifier_body
secrets.go
:= Replicator{ GenericReplicator: common.NewGenericReplicator(common.ReplicatorConfig{ Kind: "Secret", ObjType: &v1.Secret{}, AllowAll: allowAll, ResyncPeriod: resyncPeriod, Client: client, ListFunc: func(lo metav1.ListOptions) (runtime.Object, error) { return client.Core...
replicatedKeys = append(replicatedKeys, key) delete(prevKeys, key) } if hasPrevKeys { for k := range prevKeys { logger.Debugf("removing previously present key %s: not present in source secret any more", k) delete(resourceCopy.Data, k) } } return replicatedKeys } func (r *Replicator) PatchDeleteDepen...
resourceCopy.Data[key] = newValue
random_line_split
secrets.go
:= Replicator{ GenericReplicator: common.NewGenericReplicator(common.ReplicatorConfig{ Kind: "Secret", ObjType: &v1.Secret{}, AllowAll: allowAll, ResyncPeriod: resyncPeriod, Client: client, ListFunc: func(lo metav1.ListOptions) (runtime.Object, error) { return client.Core...
} resourceCopy.Name = source.Name resourceCopy.Labels = labelsCopy resourceCopy.Type = targetResourceType resourceCopy.Annotations[common.ReplicatedAtAnnotation] = time.Now().Format(time.RFC3339) resourceCopy.Annotations[common.ReplicatedFromVersionAnnotation] = source.ResourceVersion resourceCopy.Annotations[...
{ for key, value := range source.Labels { labelsCopy[key] = value } }
conditional_block
secrets.go
:= Replicator{ GenericReplicator: common.NewGenericReplicator(common.ReplicatorConfig{ Kind: "Secret", ObjType: &v1.Secret{}, AllowAll: allowAll, ResyncPeriod: resyncPeriod, Client: client, ListFunc: func(lo metav1.ListOptions) (runtime.Object, error) { return client.Core...
(sourceKey string, target interface{}) (interface{}, error) { dependentKey := common.MustGetKey(target) logger := log.WithFields(log.Fields{ "kind": r.Kind, "source": sourceKey, "target": dependentKey, }) targetObject, ok := target.(*v1.Secret) if !ok { err := errors.Errorf("bad type returned from Store...
PatchDeleteDependent
identifier_name
lib.rs
#[setters(into)] #[setters(strip_option)] events: Option<Arc<EventSender>>, } impl Default for Fetcher { fn default() -> Self { Self::new(Client::with_http_client(NativeClient::default())) } } impl Fetcher { /// Wraps the fetcher in an Arc. pub fn into_arc(self) -> Arc<Self> { Arc::new(self) } ...
}
random_line_split
lib.rs
")] TimedOut, #[error("error writing to file")] Write(#[source] io::Error), #[error("failed to rename partial to destination")] Rename(#[source] io::Error), #[error("server responded with an error: {}", _0)] Status(StatusCode), } /// Information about a source being fetched. #[derive(Debug,...
{ /// Signals that this file was already fetched. AlreadyFetched, /// States that we know the length of the file being fetched. ContentLength(u64), /// Notifies that the file has been fetched. Fetched, /// Notifies that a file is being fetched. Fetching, /// Reports the amount of by...
FetchEvent
identifier_name
lib.rs
tries.get() { match self.clone().inner_request(uris.clone(), to.clone()).await { Ok(()) => return Ok(()), Err(cause) => why = cause, } } Err(why) } } } async fn inner_req...
{ let status = response.status(); if status.is_informational() || status.is_success() { Ok(response) } else { Err(Error::Status(status)) } }
identifier_body
statformat.py
stat == "http://purl.obolibrary.org/obo/STATO_0000376": return("Z") elif stat == "http://purl.obolibrary.org/obo/STATO_0000282": return("F") elif stat == "http://purl.obolibrary.org/obo/STATO_0000176": return("T") else: return("P") # This function returns the cluste...
peakPVals = [float(peakQueryResult[i]) for i in list( range(4, len(peakQueryResult), 5))] # This is a temporary bug fix due to the FSL exporter currently not # recording corrected peak P-values. except ValueError: peakPVals = [math.nan for row i...
peakPVals = [float(peakQueryResult[i]) for i in list( range(3, len(peakQueryResult), 5))] else:
random_line_split
statformat.py
stat == "http://purl.obolibrary.org/obo/STATO_0000376":
elif stat == "http://purl.obolibrary.org/obo/STATO_0000282": return("F") elif stat == "http://purl.obolibrary.org/obo/STATO_0000176": return("T") else: return("P") # This function returns the cluster forming threshold type of an image. def height_thresh_type(graph, imageType...
return("Z")
conditional_block
statformat.py
stat == "http://purl.obolibrary.org/obo/STATO_0000376": return("Z") elif stat == "http://purl.obolibrary.org/obo/STATO_0000282": return("F") elif stat == "http://purl.obolibrary.org/obo/STATO_0000176": return("T") else: return("P") # This function returns the cluste...
# Remove axis ax = fig.add_subplot(1, 1, 1) plt.axis('off') # Add contrast vector to figure plt.imshow(data, aspect='auto', cmap='Greys', vmin=v_min, vmax=v_max) # Check for bording box. extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) # Save figure (without...
from matplotlib import pyplot as plt conLength = len(data) # We invert the values so the colours appear correctly (i. # e. 1 -> white, 0 -> black). data = np.ones(len(data))-data # Make the contrast vector larger so we can make an image. data = np.kron(data, np.ones((10, 30))) # Add bord...
identifier_body
statformat.py
== "http://purl.obolibrary.org/obo/STATO_0000376": return("Z") elif stat == "http://purl.obolibrary.org/obo/STATO_0000282": return("F") elif stat == "http://purl.obolibrary.org/obo/STATO_0000176": return("T") else: return("P") # This function returns the cluster for...
(statImage): if statImage == "T": return("T") elif statImage == "F": return("F") elif statImage == "Z": return("Z (Gaussianised T/F)") def format_cluster_stats(g, excName): # ---------------------------------------------------------------------- # First we gather dat...
statistic_type_string
identifier_name
message_partition.go
ir, name: storeName, mutex: &sync.RWMutex{}, } return p, p.initialize() } func (p *MessagePartition) initialize() error { p.mutex.Lock() defer p.mutex.Unlock() fileList, err := p.scanFiles() if err != nil { return err } if len(fileList) == 0 { p.maxMessageId = 0 } else { var err error p.maxM...
func (p *MessagePartition) Close() error { p.mutex.Lock() defer p.mutex.Unlock() return p.closeAppendFiles() } func (p *MessagePartition) DoInTx(fnToExecute func(maxMessageId uint64) error) error { p.mutex.Lock() defer p.mutex.Unlock() return fnToExecute(p.maxMessageId) } func (p *MessagePartition) StoreTx(pa...
return nil }
random_line_split
message_partition.go
message file func (p *MessagePartition) calculateMaxMessageIdFromIndex(fileId uint64) (uint64, error) { stat, err := os.Stat(p.indexFilenameByMessageId(fileId)) if err != nil { return 0, err } entriesInIndex := uint64(stat.Size() / int64(INDEX_ENTRY_SIZE)) return (entriesInIndex - 1 + fileId), nil } // Return...
readIndexEntry
identifier_name
message_partition.go
, name: storeName, mutex: &sync.RWMutex{}, } return p, p.initialize() } func (p *MessagePartition) initialize() error { p.mutex.Lock() defer p.mutex.Unlock() fileList, err := p.scanFiles() if err != nil { return err } if len(fileList) == 0 { p.maxMessageId = 0 } else { var err error p.maxMes...
index, errIndex := os.OpenFile(p.indexFilenameByMessageId(firstMessageIdForFile), os.O_RDWR|os.O_CREATE, 0666) if errIndex != nil { defer file.Close() defer os.Remove(file.Name()) return err } p.appendFile = file p.appendIndexFile = index p.appendFirstId = firstMessageIdForFile p.appendLastId = firstMes...
{ p.appendFileWritePosition = uint64(stat.Size()) _, err = file.Write(MAGIC_NUMBER) if err != nil { return err } _, err = file.Write(FILE_FORMAT_VERSION) if err != nil { return err } }
conditional_block
message_partition.go
, name: storeName, mutex: &sync.RWMutex{}, } return p, p.initialize() } func (p *MessagePartition) initialize() error { p.mutex.Lock() defer p.mutex.Unlock() fileList, err := p.scanFiles() if err != nil { return err } if len(fileList) == 0 { p.maxMessageId = 0 } else { var err error p.maxMes...
func (p *MessagePartition) store(msgId uint64, msg []byte) error { if msgId != 1+p.maxMessageId { return fmt.Errorf("Invalid message id for partition %v. Next id should be %v, but was %q", p.name, 1+p.maxMessageId, msgId) } if msgId > p.appendLastId || p.appendFile == nil || p.appendIndexFile == nil { if...
{ p.mutex.Lock() defer p.mutex.Unlock() return p.store(msgId, msg) }
identifier_body
credential.rs
Data { // id, name, url pub rp: ctap_types::webauthn::PublicKeyCredentialRpEntity, // id, icon, name, display_name pub user: ctap_types::webauthn::PublicKeyCredentialUserEntity, // can be just a counter, need to be able to determine "latest" pub creation_time: u32, // for stateless determin...
<UP: UserPresence, T: client::Client + client::Chacha8Poly1305>( authnr: &mut Authenticator<UP, T>, rp_id_hash: &Bytes<32>, id: &[u8], ) -> Result<Self> { let mut cred: Bytes<MAX_CREDENTIAL_ID_LENGTH> = Bytes::new(); cred.extend_from_slice(id) .map_err(|_| Error::...
try_from_bytes
identifier_name
credential.rs
#[derive(Copy, Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum CtapVersion { U2fV2, Fido20, Fido21Pre, } /// External ID of a credential, commonly known as "keyhandle". #[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct CredentialId(pub Bytes<MAX_CREDENTIAL_ID_L...
/// As signaled in `get_info`. /// /// Eventual goal is full support for the CTAP2.1 specification.
random_line_split
credential.rs
Data { // id, name, url pub rp: ctap_types::webauthn::PublicKeyCredentialRpEntity, // id, icon, name, display_name pub user: ctap_types::webauthn::PublicKeyCredentialUserEntity, // can be just a counter, need to be able to determine "latest" pub creation_time: u32, // for stateless determin...
} } pub fn try_from<UP: UserPresence, T: client::Client + client::Chacha8Poly1305>( authnr: &mut Authenticator<UP, T>, rp_id_hash: &Bytes<32>, descriptor: &PublicKeyCredentialDescriptor, ) -> Result<Self> { Self::try_from_bytes(authnr, rp_id_hash, &descriptor.id) ...
{ info_now!("could not deserialize {:?}", bytes); Err(Error::Other) }
conditional_block
dns.go
uint16 event Event } type dnsAnswer struct { name []byte qType uint16 qClass uint16 ttl uint32 dataLen uint16 addr []byte } // metaClient is a query client var metaClient client.CoreInterface // dnsConn saves DNS protocol var dnsConn *net.UDPConn // Start is for external call func Start() { ...
offset := uint16(unsafe.Sizeof(dnsHeader{})) // DNS NS <ROOT> operation if req[offset] == 0x0 { que.event = eventUpstream return } que.getQuestion(req, offset, head) err = nil return } // isAQuery judges if the dns pkg is a query func (h *dnsHeader) isAQuery() bool { return h.flags&dnsQR != dnsQR } // g...
{ que.event = eventUpstream return }
conditional_block
dns.go
uint16 event Event } type dnsAnswer struct { name []byte qType uint16 qClass uint16 ttl uint32 dataLen uint16 addr []byte } // metaClient is a query client var metaClient client.CoreInterface // dnsConn saves DNS protocol var dnsConn *net.UDPConn // Start is for external call func Start() { ...
(que *dnsQuestion, req []byte) (rsp []byte, err error) { var exist bool var ip string // qType should be 1 for ipv4 if que.name != nil && que.qType == aRecord { domainName := string(que.name) exist, ip = lookupFromMetaManager(domainName) } if !exist || que.event == eventUpstream { // if this service doesn'...
recordHandle
identifier_name
dns.go
"bufio" "encoding/binary" "errors" "fmt" "net" "os" "strings" "time" "unsafe" "k8s.io/klog/v2" "github.com/kubeedge/kubeedge/edge/pkg/metamanager/client" "github.com/kubeedge/kubeedge/edgemesh/pkg/common" "github.com/kubeedge/kubeedge/edgemesh/pkg/config" "github.com/kubeedge/kubeedge/edgemesh/pkg/liste...
import (
random_line_split
dns.go
nil && que.qType == aRecord { domainName := string(que.name) exist, ip = lookupFromMetaManager(domainName) } if !exist || que.event == eventUpstream { // if this service doesn't belongs to this cluster go getFromRealDNS(req, que.from) return rsp, fmt.Errorf("get from real dns") } address := net.ParseIP...
{ h.anCount = num }
identifier_body
getprimers.py
df_primers_dups = pd.read_excel(self.excel_file, header=0, parse_cols='A:M, O:X', skiprows=2, names=['Gene', 'Exon', 'Direction', 'Version', 'Primer_seq', 'Chrom', 'M13_tag', 'Batch', 'project', 'Order_date', 'Frag_size', 'an...
:param sheetname: sheet data to be extracted from :return df_primers_dups: data frame containing extracted data which may include duplicates. :return df_primers: data frame containing only data necessary to get genome coordinates. """
random_line_split
getprimers.py
ps', 'rs', 'hgvs', 'freq', 'ss', 'ss_proj', 'other2', 'action_to_take', 'check_by'], sheetname=sheetname, index_col=None) to_drop = ['Version', 'M13_tag', 'Batch', 'project', 'Order_date', 'Frag_size', 'anneal_temp', 'Other'...
(self, csv): """Runs virtual PCR on a CSV file using the isPcr and pslToBed tools installed from UCSC. :param csv: a csv file is need as an input with format "name, forward, reverse". :return bedfile: with results of virtual PCR if there is a match. """ print "Ru...
run_pcr
identifier_name
getprimers.py
ps', 'rs', 'hgvs', 'freq', 'ss', 'ss_proj', 'other2', 'action_to_take', 'check_by'], sheetname=sheetname, index_col=None) to_drop = ['Version', 'M13_tag', 'Batch', 'project', 'Order_date', 'Frag_size', 'anneal_temp', 'Other'...
forwards = primer_list[::2] reverses = primer_list[1::2] while list_position < len(forwards): ser = pd.Series([names[list_position], forwards[list_position], reverses[list_position]]) primer_seqs = primer_seqs.append(ser, ignore_index=True) list_position +=...
names.append(item)
conditional_block
getprimers.py
Chrom')) df_primers = df_primers.reset_index(drop=True) return df_primers_dups, df_primers def run_pcr(self, csv): """Runs virtual PCR on a CSV file using the isPcr and pslToBed tools installed from UCSC. :param csv: a csv file is need as an input with format "name, forward...
"""Creates tables and adds data into the database. Function modifies the given data frame to generate three tables in the database (Primers, SNPs, Genes) and performs data checks. If data for a particular gene is already in the database, this is overridden and the previous data is saved...
identifier_body
lib.rs
_void, _>(null_mut())) } #[repr(C)] #[derive(Debug)] pub enum RawType { Null, Bool, Uint64, Int64, Double, Date, String, Binary, Fd, Dictionary, Array, Error, } #[repr(C)] #[derive(Debug)] pub enum CallStatus { InProgress, MoreAvailable, Done, Error, ...
{ code: u32, message: String, stack_trace: Box<Value>, extra: Box<Value> } #[link(name = "rpc")] extern { /* rpc/object.h */ pub fn rpc_get_type(value: *mut RawObject) -> RawType; pub fn rpc_hash(value: *mut RawObject) -> u32; pub fn rpc_null_create() -> *mut RawObject; pub fn rpc_...
Error
identifier_name
lib.rs
c_void, _>(null_mut())) } #[repr(C)] #[derive(Debug)] pub enum RawType { Null, Bool,
Uint64, Int64, Double, Date, String, Binary, Fd, Dictionary, Array, Error, } #[repr(C)] #[derive(Debug)] pub enum CallStatus { InProgress, MoreAvailable, Done, Error, Aborted, Ended } pub enum RawObject {} pub enum RawConnection {} pub enum RawClient {} ...
random_line_split
pirep.py
loc2>[A-Z0-9]{3,4})" ) OV_OFFSET = re.compile( ( r"(?P<dist>[0-9]{1,3})\s?" "(?P<dir>NORTH|EAST|SOUTH|WEST|N|NNE|NE|ENE|E|ESE|" r"SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW)\s+(OF )?(?P<loc>[A-Z0-9]{3,4})" ) ) DRCT2DIR = { "N": 0, "NNE": 22.5, "NE": 45, "ENE": 67.5, "E": 90, ...
(BaseModel): """ A Pilot Report. """ base_loc: str = None text: str = None priority: Priority = None latitude: float = None longitude: float = None valid: datetime.datetime = None cwsu: str = None aircraft_type: str = None is_duplicate: bool = False class Pirep(product.TextPro...
PilotReport
identifier_name
pirep.py
, "SSW": 202.5, "SW": 225, "WSW": 247.5, "W": 270, "WNW": 292.5, "NW": 305, "NNW": 327.5, "NORTH": 0, "EAST": 90, "SOUTH": 180, "WEST": 270, } class Priority(str, Enum): """Types of reports.""" def __str__(self): """When we want the str repr.""" ret...
res -= datetime.timedelta(hours=24)
conditional_block
pirep.py
NNE": 22.5, "NE": 45, "ENE": 67.5, "E": 90, "ESE": 112.5, "SE": 135, "SSE": 157.5, "S": 180, "SSW": 202.5, "SW": 225, "WSW": 247.5, "W": 270, "WNW": 292.5, "NW": 305, "NNW": 327.5, "NORTH": 0, "EAST": 90, "SOUTH": 180, "WEST": 270, } class Priori...
""" Figure out the lon/lat for this location """ lat = self.nwsli_provider[loc]["lat"] lon = self.nwsli_provider[loc]["lon"] # shortcut if dist == 0: return lon, lat meters = distance(float(dist), "MI").value("M") northing = meters * math.cos(math.radians(bear...
identifier_body
pirep.py
): """When we want the str repr.""" return str(self.value) UA = "UA" UUA = "UUA" class PilotReport(BaseModel): """ A Pilot Report. """ base_loc: str = None text: str = None priority: Priority = None latitude: float = None longitude: float = None valid: datetime.da...
report.aircraft_type,
random_line_split
requester.go
struct { // Request is the request to be made. Request *http.Request //RequestBody []byte RequestParamSlice *RequestParamSlice DataType string DisableOutput bool // N is the total number of requests to make. N int // C is the concurrency level, the number of concurrent workers to run. C int // H2 is ...
} // sync send func (b *Work) syncSend(throttle <-chan time.Time, client http.Client) { for i := 0; ; i++ { if time.Now().Sub(b.startTime) > b.PerformanceTimeout { break } if b.QPS > 0 { <-throttle } select { case <-b.stopCh: break default: requestParam := b.getRequestParam(i) b.makeRequ...
{ if b.QPS > 0 { <-throttle } select { case <-b.stopCh: break default: requestParam := b.getRequestParam(i*b.C + widx) b.makeRequest(&client, &requestParam) } }
conditional_block
requester.go
Work struct { // Request is the request to be made. Request *http.Request //RequestBody []byte RequestParamSlice *RequestParamSlice DataType string DisableOutput bool // N is the total number of requests to make. N int // C is the concurrency level, the number of concurrent workers to run. C int // H...
return os.Stdout } return b.Writer } // Run makes all the requests, prints the summary. It blocks until // all work is done. func (b *Work) Run() { // append hey's user agent ua := b.Request.UserAgent() if ua == "" { ua = megSenderUA } else { ua += " " + megSenderUA } b.results = make(chan *result) b.s...
func (b *Work) writer() io.Writer { if b.Writer == nil {
random_line_split
requester.go
Work struct { // Request is the request to be made. Request *http.Request //RequestBody []byte RequestParamSlice *RequestParamSlice DataType string DisableOutput bool // N is the total number of requests to make. N int // C is the concurrency level, the number of concurrent workers to run. C int // H...
() io.Writer { if b.Writer == nil { return os.Stdout } return b.Writer } // Run makes all the requests, prints the summary. It blocks until // all work is done. func (b *Work) Run() { // append hey's user agent ua := b.Request.UserAgent() if ua == "" { ua = megSenderUA } else { ua += " " + megSenderUA } ...
writer
identifier_name
requester.go
seconds. SingleRequestTimeout time.Duration // Timeout in seconds PerformanceTimeout time.Duration // Qps is the rate limit. QPS int // DisableCompression is an option to disable compression in response DisableCompression bool // DisableKeepAlives is an option to prevents re-use of TCP connections between d...
{ var wg sync.WaitGroup wg.Add(b.C) for i := 0; i < b.C; i++ { go func(i int) { b.runWorker(b.N/(b.C), i) defer wg.Done() }(i) } wg.Wait() }
identifier_body
type_check.rs
x, t1) :: ctx) e2 --lambdas are complicated (this represents ʎx.e) typeInfer ctx (Lambda x e) = do t1 <- allocExistentialVariable t2 <- typeInfer ((x, t1) :: ctx) e return $ FunctionType t1 t2 -- ie. t1 -> t2 --to solve the problem of map :: (a -> b) -> [a] -> [b] when we use a variable whose type has un...
{ symbol_table: HashMap<PathSpecifier, TypeContextEntry>, evar_table: HashMap<u64, Type>, existential_type_label_count: u64 } impl TypeContext { pub fn new() -> TypeContext { TypeContext { symbol_table: HashMap::new(), evar_table: HashMap::new(), existential_type_label_count: 0, } }...
ypeContext
identifier_name
type_check.rs
= args.get(0).unwrap(); let type_arg = self.from_anno(arg); let spec = PathSpecifier(data_construcor.clone()); let ty = TFunc(Box::new(type_arg), Box::new(TConst(UserT(type_constructor.name.clone())))); (spec, ty) }, ...
}
random_line_split
chinpnr_account_pull.py
1474013', '6000060281607816', '6000060281871398', '6000060281894104', '6000060281940983', '6000060281943249', '6000060281948468', '6000060281951239', '6000060282077968', '6000060282137644', '6000060282182522', '6000060282311535', '6000060282710505', '6000060282717438', '6000060282742464...
'6000060291243806', '6000060291340862', '6000060291431540', '6000060291483681', '6000060291553294', '6000060291706959', '6000060292219430', '6000060292566439', '6000060292741605', '6000060293019252', '6000060293381519', '6000060293320112', '6000060293384730', '6000060293387871', '6000060...
random_line_split
chinpnr_account_pull.py
(data): # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = "INSERT INTO tb_chinapnr_account_detail(create_time, \ serial_number, usr_id, user_name, acct_type,debit_or_credit_mark,tran_amount,free_amount,acct_amount,in_usr_id,buss_type,des_note) \ VALUES ('%s', '%s', '%s', '...
insert
identifier_name
chinpnr_account_pull.py
000060286369920', '6000060286403660', '6000060286413551', '6000060286417968', '6000060286426949', '6000060286533431', '6000060286556059', '6000060286595864', '6000060286670372', '6000060286823653', '6000060286954351', '6000060286957811', '6000060286982865', '6000060287011733', '60000602...
if i != 1: next = browser.find_element_by_xpath('//p[@class="page"]/a[@title="Next"]') next.click() wait.until(EC.presence_of_element_located( (By.XPATH, '//p[@class="page"]/a[@class="current" and @title="' + str(i) + '"]'))) ...
conditional_block
chinpnr_account_pull.py
453923', '6000060269456948', '6000060269455093', '6000060269455994', '6000060269459071', '6000060269455869', '6000060269456118', '6000060269456261', '6000060269457616', '6000060269462708', '6000060269461736', '6000060269463618', '6000060269652085', '6000060269469033', '6000060269480234'...
# SQL 插入语句 sql = "INSERT INTO tb_chinapnr_account_detail(create_time, \ serial_number, usr_id, user_name, acct_type,debit_or_credit_mark,tran_amount,free_amount,acct_amount,in_usr_id,buss_type,des_note) \ VALUES ('%s', '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s')" % \ ...
identifier_body
viewer.js
== "no")) { this.playing = false; } this.updateButtons(); if (this.args.speed) { var speed = parseFloat(this.args.speed); if (!isNaN(speed)) this.speed = speed; } // Load game, if passed by url var game = null; if (this.args.web) { // Request game with ajax gam...
else game = this.args.game; if (!game) { $("File").addEventListener("change", function(ev) { if (ev.target.files.length > 0) { Viewer.loadFromFile(ev.target.files[0]); } }, false); this.showOverlay("Upload"); } else this.loadFromURL(game); }, show...
{ // Arguments passed by Jutge if (location.host) game = location.protocol + "//" + location.host + "/"; else game = "https://battle-royale-eda.jutge.org/"; if (this.args.nbr) { game += "?cmd=lliuraments&sub="+this.args.sub+"&nbr="+this.args.nbr+"&download=partida"; } else game += ...
conditional_block
viewer.js
}, false); this.canvas.addEventListener("mousemove", function(ev) { Viewer.mouseMove(ev); }, false); this.canvas.addEventListener("mouseout", function(ev) { Viewer.mouseOut(ev); }, false); this.canvas.addEventListener("mousewheel", function(ev) { Viewer.mouseWheel(ev); }, false); var root = $("Pla...
loadMusic: function(url) { ++this.loading; this.stopMusic();
random_line_split
keyboard.rs
=> Key::F3, Code::F4 => Key::F4, Code::F5 => Key::F5, Code::F6 => Key::F6, Code::F7 => Key::F7, Code::F8 => Key::F8, Code::F9 => Key::F9, Code::F10 => Key::F10, Code::NumLock => Key::NumLock, Code::ScrollLock => Key::ScrollLock, Code::Nump...
0x0049 => Code::F7, 0x004A => Code::F8, 0x004B => Code::F9, 0x004C => Code::F10,
random_line_split
keyboard.rs
(code: Code, m: Modifiers) -> Key { fn a(s: &str) -> Key { Key::Character(s.into()) } fn s(mods: Modifiers, base: &str, shifted: &str) -> Key { if mods.contains(Modifiers::SHIFT) { Key::Character(shifted.into()) } else { Key::Character(base.into()) } ...
code_to_key
identifier_name
keyboard.rs
fn n(mods: Modifiers, base: Key, num: &str) -> Key { if mods.contains(Modifiers::NUM_LOCK) != mods.contains(Modifiers::SHIFT) { Key::Character(num.into()) } else { base } } match code { Code::KeyA => s(m, "a", "A"), Code::KeyB => s(m, "b", "B"...
{ if mods.contains(Modifiers::SHIFT) { Key::Character(shifted.into()) } else { Key::Character(base.into()) } }
identifier_body
motion-export-dialog.component.ts
'@angular/material/dialog'; import { auditTime, Observable } from 'rxjs'; import { Permission } from 'src/app/domain/definitions/permission'; import { ChangeRecoMode, LineNumberingMode, MOTION_PDF_OPTIONS, PERSONAL_NOTE_ID } from 'src/app/domain/models/motions/motions.constants'; import { StorageServic...
/** * Function to change the state of the property `disabled` of a given button. * * Ensures, that the button exists. * * @param button The button whose state will change. * @param nextState The next state the button will assume. */ private changeStateOfButton(button: MatBut...
{ if (event.value.includes(MOTION_PDF_OPTIONS.ContinuousText)) { this.tocButton.checked = false; this.addBreaksButton.checked = false; } }
identifier_body
motion-export-dialog.component.ts
from '@angular/material/dialog'; import { auditTime, Observable } from 'rxjs'; import { Permission } from 'src/app/domain/definitions/permission'; import { ChangeRecoMode, LineNumberingMode, MOTION_PDF_OPTIONS, PERSONAL_NOTE_ID } from 'src/app/domain/models/motions/motions.constants'; import { StorageS...
else { this.enableControl(`content`); this.changeStateOfButton(this.speakersButton, true); } if (format === ExportFileFormat.CSV || format === ExportFileFormat.XLSX) { this.disableControl(`lnMode`); this.disableControl(`crMode`); this.disable...
{ this.disableControl(`content`); this.changeStateOfButton(this.speakersButton, false); }
conditional_block
motion-export-dialog.component.ts
from '@angular/material/dialog'; import { auditTime, Observable } from 'rxjs'; import { Permission } from 'src/app/domain/definitions/permission'; import { ChangeRecoMode, LineNumberingMode, MOTION_PDF_OPTIONS, PERSONAL_NOTE_ID } from 'src/app/domain/models/motions/motions.constants'; import { StorageS...
@Component({ selector: `os-motion-export-dialog`, templateUrl: `./motion-export-dialog.component.html`, styleUrls: [`./motion-export-dialog.component.scss`], encapsulation: ViewEncapsulation.None }) export class MotionExportDialogComponent extends BaseUiComponent implements OnInit { /** * impor...
random_line_split
motion-export-dialog.component.ts
Time, Observable } from 'rxjs'; import { Permission } from 'src/app/domain/definitions/permission'; import { ChangeRecoMode, LineNumberingMode, MOTION_PDF_OPTIONS, PERSONAL_NOTE_ID } from 'src/app/domain/models/motions/motions.constants'; import { StorageService } from 'src/app/gateways/storage.service'...
onCloseClick
identifier_name
watched_bitfield.rs
: String, /// The length from the beginning of the `BitField8` to the last /// watched video. anchor_length: usize, bitfield: BitField8, } impl Display for WatchedField { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}:{}:{}", se...
} /// Module containing all the impls of the `serde` feature #[cfg(feature = "serde")] mod serde { use std::str::FromStr; use serde::{de, Serialize}; use super::WatchedField; impl<'de> serde::Deserialize<'de> for WatchedField { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> ...
{ watched.bitfield }
identifier_body
watched_bitfield.rs
video_ids: Vec<String>, } impl WatchedBitField { pub fn construct_from_array(arr: Vec<bool>, video_ids: Vec<String>) -> WatchedBitField { let mut bitfield = BitField8::new(video_ids.len()); for (i, val) in arr.iter().enumerate() { bitfield.set(i, *val); } WatchedBit...
deserialize_empty
identifier_name
watched_bitfield.rs
: String, /// The length from the beginning of the `BitField8` to the last /// watched video. anchor_length: usize, bitfield: BitField8, } impl Display for WatchedField { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}:{}:{}", se...
} pub fn set(&mut self, idx: usize, v: bool) { self.bitfield.set(idx, v); } pub fn set_video(&mut self, video_id: &str, v: bool) { if let Some(pos) = self.video_ids.iter().position(|s| *s == video_id) { self.bitfield.set(pos, v); } } } impl fmt::Display for Wa...
{ false }
conditional_block
watched_bitfield.rs
_video: String, /// The length from the beginning of the `BitField8` to the last /// watched video. anchor_length: usize, bitfield: BitField8, } impl Display for WatchedField { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}:{}:{}", ...
for i in 0..video_ids.len() { // TODO: Check what will happen if we change it to `usize` let id_in_prev = i as i32 + offset; if id_in_prev >= 0 && (id_in_prev as usize) < bitfield.length { resized_wbf.set(i, bitfield.get...
bitfield: BitField8::new(video_ids.len()), video_ids: video_ids.clone(), }; // rewrite the old buf into the new one, applying the offset
random_line_split
pisco_redsequence.py
5,0.01) #just for the line plot in the 3rd plot redshift_range=np.arange(0.10,0.8,0.05) #for the actual data number=[] if color=='sloan_g-sloan_r': redshift_range=np.arange(0.10,0.36,0.05) elif color=='sloan_r-sloan_i': redshift_range=np.arange(0.10,0.71,0.05) for redshift in reds...
i_band0=-20.5 color_err=0.15 band_1, band_2 = color.split("-") band_1_idx=filters.index(band_1) band_2_idx=filters.index(band_2) rs_models=dict() rs_models[color]=dict() for z, m in zip(zs,mags): #mag_1=m[band_1_idx] mag_2=m[band_2_idx] mag_1=blue_model(c...
if color=='sloan_r-sloan_z': slope_r_m_i=-0.0192138872893 slope_r_m_z=(1.584 * slope_r_m_i) slope_fit=[slope_r_m_z, 0] i_band0=-20. elif color=='sloan_g-sloan_i': slope_v_m_i=-0.029 slope_g_m_i=(1.481 * slope_v_m_i) slope_fit=[slope_g_m_i, 0] i_band0=-...
identifier_body
pisco_redsequence.py
5,0.01) #just for the line plot in the 3rd plot redshift_range=np.arange(0.10,0.8,0.05) #for the actual data number=[] if color=='sloan_g-sloan_r': redshift_range=np.arange(0.10,0.36,0.05) elif color=='sloan_r-sloan_i': redshift_range=np.arange(0.10,0.71,0.05) for redshift in reds...
(fname): with open(fname) as f: content = f.readlines() content = [x.strip() for x in content] band=[x.split(' ')[0][-1] for x in content[5:-1]] corr=[float(x.split(' ')[1]) for x in content[5:-1]] ecorr=[float(x.split(' ')[3]) for x in content[5:-1]] return zip(band,corr,ecorr), corr d...
find_offset
identifier_name
pisco_redsequence.py
5,0.01) #just for the line plot in the 3rd plot redshift_range=np.arange(0.10,0.8,0.05) #for the actual data number=[] if color=='sloan_g-sloan_r': redshift_range=np.arange(0.10,0.36,0.05) elif color=='sloan_r-sloan_i': redshift_range=np.arange(0.10,0.71,0.05) for redshift in reds...
elif color=='sloan_r-sloan_i': if redshift <= 0.36: blue_mag=(0.348871987852+0.75340856*redshift)+red_mag else: blue_mag=(-0.210727367027+2.2836974*redshift)+red_mag else: print 'This color has not been implemented.' return blue_mag def histogram_plot(xranf,...
blue_mag=(0.787302458781+2.9352*redshift)+red_mag
conditional_block
pisco_redsequence.py
5,0.01) #just for the line plot in the 3rd plot redshift_range=np.arange(0.10,0.8,0.05) #for the actual data number=[] if color=='sloan_g-sloan_r': redshift_range=np.arange(0.10,0.36,0.05) elif color=='sloan_r-sloan_i': redshift_range=np.arange(0.10,0.71,0.05) for redshift in reds...
print 'This color has not been implemented.' return blue_mag def histogram_plot(xranf,numberf,df,ax=None,line=False,cbar=False): l2=6 ax.set_xlim(0,0.8) ic2,ic3=0,0 numbers=numberf[:6] numbers2=numberf[l2:] ax.bar(xranf[:6],numbers,width=0.05,color='red',alpha=0.5,align='center') ...
else: blue_mag=(-0.210727367027+2.2836974*redshift)+red_mag else:
random_line_split
main.rs
fn index(&self, (x, y): (usize, usize)) -> &Self::Output { &self.view[x + self.width * y] } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum Orientation { Up, Down, Left, Right, } impl TryFrom<u8> for Orientation { type Error = Error; fn try_from(value: u8) -> Result<Self, ...
o = n.0; break; } } if !found_turn { break; } } let route = Route(route); Ok(route) } } fn part_01(input: &str) -> Result<usize, Error> { let mut aligment_parameters = 0; l...
found_turn = true; route.append(&mut o.orient(n.0));
random_line_split
main.rs
fn index(&self, (x, y): (usize, usize)) -> &Self::Output { &self.view[x + self.width * y] } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum Orientation { Up, Down, Left, Right, } impl TryFrom<u8> for Orientation { type Error = Error; fn try_from(value: u8) -> Result<Self, Sel...
fn forward(&self, pos: (usize, usize), o: Orientation) -> Option<(usize, usize)> { let width = self.width; let height = self.height; let d = o.delta(); pos.0 .checked_add_signed(d.0) .and_then(|x| pos.1.checked_add_signed(d.1).map(|y| (x, y))) .f...
{ let width = self.width; let height = self.height; [ Orientation::Up, Orientation::Down, Orientation::Left, Orientation::Right, ] .into_iter() .filter_map(move |o| { let d = o.delta(); pos.0 ...
identifier_body
main.rs
fn index(&self, (x, y): (usize, usize)) -> &Self::Output { &self.view[x + self.width * y] } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum Orientation { Up, Down, Left, Right, } impl TryFrom<u8> for Orientation { type Error = Error; fn try_from(value: u8) -> Result<Self, ...
(&self, pos: (usize, usize), o: Orientation) -> Option<(usize, usize)> { let width = self.width; let height = self.height; let d = o.delta(); pos.0 .checked_add_signed(d.0) .and_then(|x| pos.1.checked_add_signed(d.1).map(|y| (x, y))) .filter(move |(x, ...
forward
identifier_name
main.rs
} else { view.push(o); } } let height = view.len() / width; Ok(View { view, width, height, }) } } impl Index<(usize, usize)> for View { type Output = u8; fn index(&self, (x, y): (usize, usize)) -> ...
{ width = view.len(); }
conditional_block
val.rs
` half of `Val` used to send the result of an asynchronous /// computation to the consumer of `Val`. /// /// This is created by the `pair` function. pub struct Complete<T, E> { inner: Arc<Inner<T, E>>, cancellation: Cell<bool>, } /// A future representing the cancellation in interest by the consumer of /// `Va...
(&mut self, task: &mut Task) -> Poll<bool, ()> { self.inner.poll(task) } fn schedule(&mut self, task: &mut Task) { self.inner.schedule(task) } } /* * * ===== Inner ===== * */ impl<T, E> Inner<T, E> { /// Complete the future with the given result fn complete(&self, res: Option<...
poll
identifier_name
val.rs
the cancellation in interest by the consumer of /// `Val`. /// /// If a `Val` is dropped without ever attempting to read the value, then it /// becomes impossible to ever receive the result of the underlying /// computation. This indicates that there is no interest in the computation /// and it may be cancelled. /// /...
val.then(move |res| { tx.send(res.unwrap()).unwrap(); res
random_line_split
val.rs
` half of `Val` used to send the result of an asynchronous /// computation to the consumer of `Val`. /// /// This is created by the `pair` function. pub struct Complete<T, E> { inner: Arc<Inner<T, E>>, cancellation: Cell<bool>, } /// A future representing the cancellation in interest by the consumer of /// `Va...
/// Abort the computation. This will cause the associated `Val` to panic on /// a call to `poll`. pub fn abort(self) { self.inner.complete(None, false); } /// Returns a `Future` representing the consuming end cancelling interest /// in the future. /// /// This function can onl...
{ self.inner.complete(Some(Err(err)), false); }
identifier_body
DissertationScript.py
try: site = urlopen(el).read() text = open("CongressBLAHfolder/"+agen+str(num)+a+str(reg3.groups()[0])+".txt","wb") text.write(site) except Exception as e: print("This didn't work: "+s...
for el in reg2: print(el) #print(el) #li.append(el) reg3 = re.search('hrg(\d*?)\/',el)
random_line_split
DissertationScript.py
("_")[1][:-4] # Load original files, so I can get the names of everyone f2 = open("Congressional Hearings TXT/" + file.split("_")[0] + ".txt", "rb").read().decode() # Code to get name list from beginning of each file on GPO.gov (need to make sure this gets everyone) try...
(): ###Create files with each Senator and their full website, including PersonID #Load GPO Biographies - JSON and extract the key, which is names of all Congresspeople going back to 1997 names = json.load(open('GPO Biographies - JSON')) names = list(names.keys()) #This gets rid of middle names and m...
cspan_selenium_getsite
identifier_name
DissertationScript.py
outer function to find the ID if difflib.get_close_matches(name.title(), file_to_list_upper("C-SPAN PersonID (simplified).txt"),cutoff=.8): print(difflib.get_close_matches(name.title(), file_to_list_upper("C-SPAN PersonID (simplified).txt"),cutoff=.8)) ID = dict_cspan_id(dif...
name = line.split("\t")[0].replace(" ","") date = line.split("\t")[3].split("-")[:-1] date = "-".join(date) starttime = line.split("\t")[7] if len(line.split("\t"))>10: rtmp = line.split("\t")[10].split(" -o ")[0] + " -o " +name + date + "_" + starttime + ...
conditional_block