file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
data_tensorboard.py | import tensorflow as tf
from tensorflow import keras
import numpy as np
import os
import cv2
from tensorflow.keras.preprocessing.image import ImageDataGenerator
"""
crop_top takes as an input img which is an array of shape (x, y, 3) and
percentage of picture to crop
"""
def crop_top(img, percent=0.15):
offset =... | },
shuffle=True,
augmentation=apply_augmentation,
covid_percent=0.3,
class_weights=[1., 1., 6.], # default weight of classes. The less numbered class gets is more worthy than the others
# in this case COVID_19
... | mapping={
'normal': 0,
'pneumonia': 1,
'COVID-19': 2 | random_line_split |
start-webserver.py | import sys
sys.path.append('..')
from aips import *
import threading
import webbrowser
import http.server
import requests
import json
import urllib
from staticmap import StaticMap, CircleMarker
from urllib.parse import urlparse, parse_qs
import os
FILE = 'semantic-search'
#HOST = os.getenv('HOST') or 'localhost'
AIPS... |
if ("category" in categoryAndTermVector):
if (len(queryString) > 0):
queryString += " "
queryString += "+doc_type:\"" + categoryAndTermVector["category"] + "\""
... | queryString = categoryAndTermVector["term_vector"] | conditional_block |
start-webserver.py | import sys
sys.path.append('..')
from aips import *
import threading
import webbrowser
import http.server
import requests
import json
import urllib
from staticmap import StaticMap, CircleMarker
from urllib.parse import urlparse, parse_qs
import os
FILE = 'semantic-search'
#HOST = os.getenv('HOST') or 'localhost'
AIPS... | elf):
content_len = int(self.headers.get("Content-Length"), 0)
post_body = self.rfile.read(content_len)
if (self.path.startswith("/tag_query")):
self.sendResponse(tag_query(post_body))
elif self.path.startswith("/tag_places"):
self.sendResponse(tag_places(post_bo... | _POST(s | identifier_name |
start-webserver.py | import sys
sys.path.append('..')
from aips import *
import threading
import webbrowser
import http.server
import requests
import json
import urllib
from staticmap import StaticMap, CircleMarker
from urllib.parse import urlparse, parse_qs
import os
FILE = 'semantic-search'
#HOST = os.getenv('HOST') or 'localhost'
AIPS... | def start_server():
"""Start the server."""
server_address = ("0.0.0.0", int(AIPS_WEBSERVER_PORT))
server = http.server.HTTPServer(server_address, SemanticSearchHandler)
server.serve_forever()
if __name__ == "__main__":
open_browser()
start_server() | "Start a browser after waiting for half a second."""
def _open_browser():
if AIPS_WEBSERVER_HOST == "localhost":
webbrowser.open(WEBSERVER_URL + '/%s' % FILE)
thread = threading.Timer(0.5, _open_browser)
thread.start()
| identifier_body |
start-webserver.py | import sys
sys.path.append('..')
from aips import *
import threading
import webbrowser
import http.server
import requests
import json
import urllib
from staticmap import StaticMap, CircleMarker
from urllib.parse import urlparse, parse_qs
import os
FILE = 'semantic-search'
#HOST = os.getenv('HOST') or 'localhost'
AIPS... | #q = "%2B{!edismax%20v=%22bbq^0.9191%20ribs^0.6186%20pork^0.5991%22}%20%2B{!geofilt%20d=50%20sfield=location_p%20pt=34.9362399,-80.8379247}"
q = urllib.parse.quote(text)
print(q)
#q=text.replace("+", "%2B") #so it doesn't get interpreted as space
qf="text_t"
defType="lucene"
return re... | random_line_split | |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... | (&self) -> ElementId {
// Create a queue to run the 'assign element ID' future on
let core = Arc::clone(&self.core);
// Perform the request and retrieve the result
core.future_desync(|core| core.assign_element_id(ElementId::Unassigned).boxed())
.sync().unwrap()
}
... | assign_element_id | identifier_name |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... |
if let Some(next) = fetched.pop() {
// Just returning the batch we've already fetched
return Poll::Ready(Some(next));
} else if let Some(mut waiting) = next_response.take() {
// Try to retrieve the next item from the batch
... | {
// Fetch up to per_request items for each request
let num_to_fetch = remaining.len();
let num_to_fetch = if num_to_fetch > per_request { per_request } else { num_to_fetch };
let fetch_range = (remaining.start)..(remaining.start ... | conditional_block |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... |
///
/// Retrieves the IDs of the layers in this object
///
fn get_layer_ids(&self) -> Vec<u64> {
self.wait_for_edits();
let layer_responses = self.request_sync(vec![StorageCommand::ReadLayers]).unwrap_or_else(|| vec![]);
layer_responses
.into_iter()
.fl... | self.file_properties().frame_length
} | random_line_split |
stream_animation.rs | use super::stream_layer::*;
use super::stream_animation_core::*;
use crate::traits::*;
use crate::storage::*;
use crate::storage::file_properties::*;
use crate::storage::layer_properties::*;
use ::desync::*;
use flo_stream::*;
use itertools::*;
use futures::prelude::*;
use futures::task::{Poll};
use futures::stream;
... |
///
/// Performs an asynchronous request on a storage layer for this animation
///
pub (super) fn request_async<Commands: Send+IntoIterator<Item=StorageCommand>>(&self, request: Commands) -> impl Future<Output=Option<Vec<StorageResponse>>> {
request_core_async(&self.core, request.into_iter().c... | {
// Create the storage requests. When the storage layer is running behind, we'll buffer up to 10 of these
let mut requests = Publisher::new(10);
let commands = requests.subscribe().boxed();
let storage_responses = connect_stream(commands);
let mut edit_publis... | identifier_body |
config.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
/// Retrieves the extension of the given type if any
pub fn get_mut<T: ConfigExtension>(&mut self) -> Option<&mut T> {
let e = self.0.get_mut(T::PREFIX)?;
e.0.as_any_mut().downcast_mut()
}
}
#[derive(Debug)]
struct ExtensionBox(Box<dyn ExtensionOptions>);
impl Clone for ExtensionBox {
... | {
self.0.get(T::PREFIX)?.0.as_any().downcast_ref()
} | identifier_body |
config.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | }
fn entries(&self) -> Vec<$crate::config::ConfigEntry> {
vec![
$(
$crate::config::ConfigEntry {
key: stringify!($field_name).to_owned(),
value: (self.$field_name != $default).the... | )*
_ => Err($crate::DataFusionError::Internal(
format!(concat!("Config value \"{}\" not found on ", stringify!($struct_name)), key)
))
} | random_line_split |
config.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (&mut self, key: &str, description: &'static str) {
self.0.push(ConfigEntry {
key: key.to_string(),
value: None,
description,
})
}
}
let mut v = Visitor(vec![]);
self.visit(&mut v, "datafusio... | none | identifier_name |
hdm.py | # HDM: Holographic Declarative Memory
# A module for Python ACT-R
# written by M. A. Kelly
# except for the parts written by Terry C. Stewart
# Based on original research and the memory models
# BEAGLE (Jones & Mewhort, 2007) and DSHM (Rutledge-Taylor, Kelly, West, & Pyke, 2014)
#
# To use HDM:
# from ccm.lib... |
else:
value = attribute
slot = ''
# sometimes we want to specify things not to select
# for example, condiment:?unknown!mustard
# means find a condiment that isn't mustard
if value.startswith('?') and value != '?':
first = True
... | slot,value = attribute.split(':')
slot = slot + ':' | conditional_block |
hdm.py | # HDM: Holographic Declarative Memory
# A module for Python ACT-R
# written by M. A. Kelly
# except for the parts written by Terry C. Stewart
# Based on original research and the memory models
# BEAGLE (Jones & Mewhort, 2007) and DSHM (Rutledge-Taylor, Kelly, West, & Pyke, 2014)
#
# To use HDM:
# from ccm.lib... | (self,chunk):
# convert chunk to a list of values
chunkList = chunk.split()
# define random Gaussian vectors for any undefined values
self.defineVectors(chunkList)
# update the memory vectors with the information from the chunk
for p in range(0,len(chunkList)):
# create a copy of ... | addJustValues | identifier_name |
hdm.py | # HDM: Holographic Declarative Memory
# A module for Python ACT-R
# written by M. A. Kelly
# except for the parts written by Terry C. Stewart
# Based on original research and the memory models
# BEAGLE (Jones & Mewhort, 2007) and DSHM (Rutledge-Taylor, Kelly, West, & Pyke, 2014)
#
# To use HDM:
# from ccm.lib... |
def recall(self,chunk,matches,request_number):
logodds = self.cosine_to_logodds(chunk.activation)
time=self.latency*math.exp(-logodds)
if time>self.maximum_time: time=self.maximum_time
yield time
if request_number!=self._request_count: return
self._buffer.set(chunk)
for... | if self.threshold == None:
time=self.maximum_time
else:
logodds = self.cosine_to_logodds(self.threshold)
time=self.latency*math.exp(-logodds)
if time>self.maximum_time: time=self.maximum_time
yield time
if request_number!=self._request_count: return
... | identifier_body |
hdm.py | # HDM: Holographic Declarative Memory
# A module for Python ACT-R
# written by M. A. Kelly
# except for the parts written by Terry C. Stewart
# Based on original research and the memory models
# BEAGLE (Jones & Mewhort, 2007) and DSHM (Rutledge-Taylor, Kelly, West, & Pyke, 2014)
#
# To use HDM:
# from ccm.lib... | query[p][1] = '?'
print(chunkList[p][1])
print(query)
# compute chunk vector
chunkVector = self.getUOGwithSlots(query)
# update memory
self.updateMemory(chunkList[p][1],chunkVector)
# add a chunk to memory
# when the chunk is just a list of values
... | for p in range(0,len(chunkList)):
# create a copy of chunkList
query = copy.deepcopy(chunkList)
# replace p's value with ? in query, but leave slot as is
| random_line_split |
glium_backend.rs | //! Glium-based backend for the Vitral GUI library.
#![deny(missing_docs)]
use euclid::{Point2D, Size2D};
use glium::glutin::dpi::{LogicalPosition, LogicalSize};
use glium::glutin::{self, Event, WindowEvent};
use glium::index::PrimitiveType;
use glium::{self, Surface};
use std::error::Error;
use std::fmt::Debug;
use ... | (&self) -> Size2D<u32> { self.size }
pub fn screenshot(&self) -> ImageBuffer {
let image: glium::texture::RawImage2d<u8> = self.buffer.read();
ImageBuffer::from_fn(image.width, image.height, |x, y| {
let i = (x * 4 + (image.height - y - 1) * image.width * 4) as usize;
image... | size | identifier_name |
glium_backend.rs | //! Glium-based backend for the Vitral GUI library.
#![deny(missing_docs)]
use euclid::{Point2D, Size2D};
use glium::glutin::dpi::{LogicalPosition, LogicalSize};
use glium::glutin::{self, Event, WindowEvent};
use glium::index::PrimitiveType;
use glium::{self, Surface};
use std::error::Error;
use std::fmt::Debug;
use ... | BlitVertex {
pos: [sx + sw, sy + sh],
tex_coord: [1.0, 1.0],
},
BlitVertex {
pos: [sx, sy + sh],
tex_coord: [0.0, 1.0],
},
],
... | pos: [sx + sw, sy],
tex_coord: [1.0, 0.0],
}, | random_line_split |
glium_backend.rs | //! Glium-based backend for the Vitral GUI library.
#![deny(missing_docs)]
use euclid::{Point2D, Size2D};
use glium::glutin::dpi::{LogicalPosition, LogicalSize};
use glium::glutin::{self, Event, WindowEvent};
use glium::index::PrimitiveType;
use glium::{self, Surface};
use std::error::Error;
use std::fmt::Debug;
use ... |
/// Make a new internal texture using image data.
pub fn make_texture(&mut self, img: ImageBuffer) -> TextureIndex {
let mut raw = glium::texture::RawImage2d::from_raw_rgba(
img.pixels,
(img.size.width, img.size.height),
);
raw.format = glium::texture::ClientFor... | {
assert!(
texture < self.textures.len(),
"Trying to write nonexistent texture"
);
let rect = glium::Rect {
left: 0,
bottom: 0,
width: img.size.width,
height: img.size.height,
};
let mut raw = glium::texture:... | identifier_body |
project_util.go | // Copyright 2018 The Operator-SDK Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... |
func MustGetwd() string {
wd, err := os.Getwd()
if err != nil {
log.Fatalf("Failed to get working directory: (%v)", err)
}
return wd
}
func getHomeDir() (string, error) {
hd, err := homedir.Dir()
if err != nil {
return "", err
}
return homedir.Expand(hd)
}
// TODO(hasbro17): If this function is called i... | {
if IsOperatorGo() {
return nil
}
return fmt.Errorf("'%s' can only be run for Go operators; %s or %s do not exist",
cmd.CommandPath(), managerMainFile, mainFile)
} | identifier_body |
project_util.go | // Copyright 2018 The Operator-SDK Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | newGopath string
cwdInGopath bool
wd = MustGetwd()
)
for _, newGopath = range filepath.SplitList(currentGopath) {
if strings.HasPrefix(filepath.Dir(wd), newGopath) {
cwdInGopath = true
break
}
}
if !cwdInGopath {
log.Fatalf("Project not in $GOPATH")
}
if err := os.Setenv(GoPathEnv, ne... | // If GOPATH cannot be set, MustSetWdGopath exits.
func MustSetWdGopath(currentGopath string) string {
var ( | random_line_split |
project_util.go | // Copyright 2018 The Operator-SDK Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... |
return nil
}
func appendContent(fileContents, instruction, content string) (string, error) {
labelIndex := strings.LastIndex(fileContents, instruction)
if labelIndex == -1 {
return "", fmt.Errorf("instruction not present previously in dockerfile")
}
separationIndex := strings.Index(fileContents[labelIndex:],... | {
return fmt.Errorf("error writing modified contents to file, %v", err)
} | conditional_block |
project_util.go | // Copyright 2018 The Operator-SDK Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ... | () (string, error) {
hd, err := homedir.Dir()
if err != nil {
return "", err
}
return homedir.Expand(hd)
}
// TODO(hasbro17): If this function is called in the subdir of
// a module project it will fail to parse go.mod and return
// the correct import path.
// This needs to be fixed to return the pkg import path... | getHomeDir | identifier_name |
sdk-ui.ts | import { Component, ChangeDetectorRef } from '@angular/core';
import {
normalizeURL,
AlertController,
Platform,
ActionSheetController,
NavController,
LoadingController
} from 'ionic-angular';
import { Camera } from '@ionic-native/camera';
import ScanbotSdk, { Page, MrzScannerConfiguration, BarcodeScannerCo... |
public normalizeImageFileUri(imageFileUri: string) {
// normalizeURL - see https://ionicframework.com/docs/wkwebview/
return normalizeURL(imageFileUri);
}
public onImagePreviewTapped(page: Page) {
this.selectedPage = page;
this.changeDetector.detectChanges();
}
private updatePage(page: Pag... | {
await SBSDK.cleanup();
this.pages = [];
this.selectedPage = null;
this.changeDetector.detectChanges();
} | identifier_body |
sdk-ui.ts | import { Component, ChangeDetectorRef } from '@angular/core';
import {
normalizeURL,
AlertController,
Platform,
ActionSheetController,
NavController,
LoadingController
} from 'ionic-angular';
import { Camera } from '@ionic-native/camera';
import ScanbotSdk, { Page, MrzScannerConfiguration, BarcodeScannerCo... | () {
if (!(await this.checkLicense())) { return; }
if (!this.checkSelectedPage()) { return; }
const actionSheet = this.actionSheetCtrl.create({
title: 'Edit selected Page',
buttons: [
{
text: 'Crop/Rotate (Cropping UI)',
icon: 'ios-crop',
handler: () => {
... | presentPageEditActionsSheet | identifier_name |
sdk-ui.ts | import { Component, ChangeDetectorRef } from '@angular/core';
import {
normalizeURL,
AlertController,
Platform,
ActionSheetController,
NavController,
LoadingController
} from 'ionic-angular';
import { Camera } from '@ionic-native/camera';
import ScanbotSdk, { Page, MrzScannerConfiguration, BarcodeScannerCo... | });
}
public async pickImageFromGallery() {
let options = {
quality: IMAGE_QUALITY,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
};
const originalImageFileUri: string = await this.camera.getPicture(options);
if ... | return this.loadingCtrl.create({
content: message | random_line_split |
sdk-ui.ts | import { Component, ChangeDetectorRef } from '@angular/core';
import {
normalizeURL,
AlertController,
Platform,
ActionSheetController,
NavController,
LoadingController
} from 'ionic-angular';
import { Camera } from '@ionic-native/camera';
import ScanbotSdk, { Page, MrzScannerConfiguration, BarcodeScannerCo... |
await SBSDK.removePage({page: this.selectedPage});
let pageIndexToRemove = null;
this.pages.forEach((p, index) => {
if (this.selectedPage.pageId === p.pageId) {
pageIndexToRemove = index;
}
});
this.pages.splice(pageIndexToRemove, 1);
this.selectedPage = null;
this.cha... | { return; } | conditional_block |
main.go | package main
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/Shopify/sarama"
"github.com/araddon/dateparse"
"github.com/riferrei/srclient"
flag "github.com/spf13/pflag"
)
const V... | (schema *srclient.Schema, datum interface{}) (sarama.ByteEncoder, error) {
buffer := make([]byte, 5, 256)
buffer[0] = 0
binary.BigEndian.PutUint32(buffer[1:5], uint32(schema.ID()))
bytes, err := schema.Codec().BinaryFromNative(buffer, datum)
if err != nil {
return nil, err
}
return sarama.ByteEncoder(bytes),... | encode | identifier_name |
main.go | package main
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/Shopify/sarama"
"github.com/araddon/dateparse"
"github.com/riferrei/srclient"
flag "github.com/spf13/pflag"
)
const V... |
func decode(registry *srclient.SchemaRegistryClient, msg []byte) (interface{}, error) {
if msg == nil || len(msg) < 6 {
return nil, errors.New("invalid message")
}
schemaID := binary.BigEndian.Uint32(msg[1:5])
schema, err := registry.GetSchema(int(schemaID))
if err != nil {
return nil, err
}
datum, _, e... | {
consumer, err := sarama.NewConsumerFromClient(client)
if err != nil {
return nil, err
}
defer consumer.Close()
partitionConsumer, err := consumer.ConsumePartition(topic, partition, offset)
if err != nil {
return nil, err
}
defer partitionConsumer.Close()
select {
case msg := <-partitionConsumer.Messag... | identifier_body |
main.go | package main
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/Shopify/sarama"
"github.com/araddon/dateparse"
"github.com/riferrei/srclient"
flag "github.com/spf13/pflag"
)
const V... |
if flags.list {
listTopic(&flags)
return
}
if flags.topic == "" {
fmt.Fprintln(os.Stderr, "ERROR: `topic` isn't specified!")
usage()
os.Exit(1)
}
if flag.NArg() > 0 {
runProducer(&flags)
} else {
runConsumer(&flags)
}
}
type Flags struct {
brokers string
topic string
partition ... | {
usage()
os.Exit(1)
} | conditional_block |
main.go | package main
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/Shopify/sarama"
"github.com/araddon/dateparse"
"github.com/riferrei/srclient"
flag "github.com/spf13/pflag"
)
const V... |
consumer, err := sarama.NewConsumerFromClient(client)
if err != nil {
log.Fatalln("failed to create consumer:", err)
}
defer consumer.Close()
partitions, err := client.Partitions(flags.topic)
if err != nil {
log.Fatalf("failed to list partitions for topic %s: %s\n", flags.topic, err)
}
wg := sync.WaitGro... | client, err := sarama.NewClient(strings.Split(flags.brokers, ","), config)
if err != nil {
log.Fatalln("failed to create create:", err)
}
defer client.Close() | random_line_split |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... | if rpc.term >= self.currentTerm {
// we lost the election... D:
self.convertToFollower();
}
// pretend we didn't hear them whether or not they won, the resend will occur anyway
}
// Update the server when it is a Follower
// Paper:
// Respond to RPCs from candidates and leaders
// ... | }
}
fn candidateAppendEntries(&mut self, rpc: AppendEntriesRpc) { | random_line_split |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... |
// 3. If an existing entry conflicts with a new one delete the
// existing entry and all that follow it
let startLogIndex = rpc.prevLogIndex+1;
for logOffset in range(0, rpc.entries.len()) {
let logIndex = startLogIndex + logOffset as int;
let entry = rpc.entries[logOffset].clone();
... | {
return fail;
} | conditional_block |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... |
fn followerVote(&mut self, rpc: &RequestVoteRpc) -> RaftRpc {
// if the candidate's log is at least as up-to-date as ours vote for them
let mut voteGranted = false;
let lastLogIndex = (self.log.len() - 1) as int;
if self.log.len() == 0 || (rpc.lastLogIndex >= lastLogIndex &&
... | {
let fail = RequestVoteResponse(RequestVoteResponseRpc {sender: self.serverId, term: self.currentTerm, voteGranted: false});
if rpc.term < self.currentTerm {
return fail;
}
// if we haven't voted for anything or we voted for candidate
match self.votedFor {
None => {
return self.... | identifier_body |
server.rs | #[feature(struct_variant)];
#[feature(macro_rules)];
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::udp::{UdpSocket, UdpStream};
use std::io::timer;
use udptransport::UdpTransport;
use transport::RaftRpcTransport;
use rpc::{ServerId, LogEntry, AppendEntries, AppendEntriesResponse, RequestVote, Request... | {
currentTerm: int,
votedFor: Option<ServerId>,
log: ~[LogEntry],
commitIndex: int,
lastApplied: int,
serverType: ServerType,
electionTimeout: int,
receivedVotes: int,
// Leader state:
// for each server, index of the next log entry to send to that
// server, initialized to last log index + 1
n... | RaftServer | identifier_name |
WXmain.js | var startEvt, moveEvt, endEvt;
if ('ontouchstart' in window) {
startEvt = 'touchstart';
moveEvt = 'touchmove';
endEvt = 'touchend';
} else {
startEvt = 'mousedown';
moveEvt = 'mousemove';
endEvt = 'mouseup';
};
var Datas = document.getElementById("DeviceId").value;
/******************... | }
}
}
}
/***********************************save and share end**************************************/
| conditional_block | |
WXmain.js | var startEvt, moveEvt, endEvt;
if ('ontouchstart' in window) {
startEvt = 'touchstart';
moveEvt = 'touchmove';
endEvt = 'touchend';
} else {
startEvt = 'mousedown';
moveEvt = 'mousemove';
endEvt = 'mouseup';
};
var Datas = document.getElementById("DeviceId").value;
/******************... | pe : "json",
success : function (data) {
clickGetFile.style.display = "none";
fileWrap.style.display = "block";
var saveFileLen = data.length;
for (var i = 0; i < saveFileLen; i++) {
var newList = filelist.cloneNode(true);
newList.style.display = "block";
newList.querySelector(".fileName").inn... |
dataTy | identifier_name |
WXmain.js | var startEvt, moveEvt, endEvt;
if ('ontouchstart' in window) {
startEvt = 'touchstart';
moveEvt = 'touchmove';
endEvt = 'touchend';
} else {
startEvt = 'mousedown';
moveEvt = 'mousemove';
endEvt = 'mouseup';
};
var Datas = document.getElementById("DeviceId").value;
/******************... | ;
var contentWrap = document.querySelector(".contentWrap");
var sidebarContent = document.querySelectorAll(".sidebarContent");
var contentLogo = document.querySelector(".contentLogo");
var navList = document.querySelectorAll(".navList");
var contentIndex = 0;
var touchX
var disX;
contentWrap.addEventListener(st... | {
if (sideBarBtn.state == 'closed') {
$Btn_lines[0].classList.add('Btn_top_clockwise');
$Btn_lines[1].classList.add('Btn_mid_hide');
$Btn_lines[2].classList.add('Btn_bottom_anticlockwise');
sideBarBtn.state = 'opened';
contentMove('up', $sidebarWrap);
} else {
... | identifier_body |
WXmain.js | var startEvt, moveEvt, endEvt;
if ('ontouchstart' in window) {
startEvt = 'touchstart';
moveEvt = 'touchmove';
endEvt = 'touchend';
} else {
startEvt = 'mousedown';
moveEvt = 'mousemove';
endEvt = 'mouseup';
};
var Datas = document.getElementById("DeviceId").value;
/******************... | e.preventDefault();
e.stopPropagation();
delOrshareFile();
var confirmDelete = confirm("确定要删除" + "(" + this.parentNode.parentNode.firstElementChild.firstElementChild.innerHTML + ")");
/*deleteTimestamp*/
if (confirmDelete) {
v... | for (var i = 0; i < deleteFile.length; i++) {
deleteFile[i].index = i;
deleteFile[i].onclick = function (e) {
| random_line_split |
ether.service.ts | import { Inject, Injectable, Provider } from '@angular/core';
import { Signer, utils, providers, Wallet, ethers, Contract } from 'ethers';
import { PROVIDER } from './provider-injection-token';
import WalletConnect from '@walletconnect/client';
import QRCodeModal from '@walletconnect/qrcode-modal';
import {
LOCAL_ST... |
// 16-bit - 1000
get astroTier2() {
return (
(this.astroAmount >= 250 || this.secondTokenAmount >= 0.1) &&
this.astroAmount < 1000
);
}
// 32-bit - 1000
get astroTier3() {
return (
(this.astroAmount >= 1000 && this.astroAmount < 20000) ||
(this.hasLvl2 && !this.hasLvl3)
... | {
return this.astroAmount >= 1 && this.astroAmount < 250;
} | identifier_body |
ether.service.ts | import { Inject, Injectable, Provider } from '@angular/core';
import { Signer, utils, providers, Wallet, ethers, Contract } from 'ethers';
import { PROVIDER } from './provider-injection-token';
import WalletConnect from '@walletconnect/client';
import QRCodeModal from '@walletconnect/qrcode-modal';
import {
LOCAL_ST... |
this.connectedAddress$.subscribe(async (res) => {
if (!res) return;
this.idAccount = res;
// this.hasLvl1 = await this.getHasNFT(astroNFT.Lvl_1_NoobCanon, res.toLowerCase());
this.hasLvl2 = await this.getHasNFT(
astroNFT.Lvl_2_PipeCleaner,
res.toLowerCase()
);
t... | {
if (typeof window.web3 !== 'undefined') {
// this.web3 = window.web3.currentProvider;
} else {
// this.web3 = new Web3.providers.HttpProvider('http://localhost:8545');
}
// console.log('transfer.service :: constructor :: window.ethereum');
// this.web3 = new Web3(window.e... | conditional_block |
ether.service.ts | import { Inject, Injectable, Provider } from '@angular/core';
import { Signer, utils, providers, Wallet, ethers, Contract } from 'ethers';
import { PROVIDER } from './provider-injection-token';
import WalletConnect from '@walletconnect/client';
import QRCodeModal from '@walletconnect/qrcode-modal';
import {
LOCAL_ST... | (): Promise<any> {
// console.log('transfer.service :: getAccount :: start');
if (this.account == null) {
this.account = (await new Promise((resolve, reject) => {
// console.log('transfer.service :: getAccount :: eth');
// console.log(this.web3.eth);
this.web3.eth.getAccounts((err,... | getAccount | identifier_name |
ether.service.ts | import { Inject, Injectable, Provider } from '@angular/core';
import { Signer, utils, providers, Wallet, ethers, Contract } from 'ethers';
import { PROVIDER } from './provider-injection-token';
import WalletConnect from '@walletconnect/client';
import QRCodeModal from '@walletconnect/qrcode-modal';
import {
LOCAL_ST... | astroAddress = '0xcbd55d4ffc43467142761a764763652b48b969ff';
secondTokenAddress = '0x62359ed7505efc61ff1d56fef82158ccaffa23d7';
powerUpAddress = '0xd8cd8cb7f468ef175bc01c48497d3f7fa27b4653';
connectedAddress = '';
astroAmount = 0;
secondTokenAmount = 0;
idAccount: string;
connectedAddress$ = new Behav... | private wallet: Wallet;
// web3;
enable;
account; | random_line_split |
app.py | import numpy as np
import yaml
import pickle
import os
from flask import Flask, request, jsonify, render_template, redirect, url_for, flash
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from wtforms import StringField,... |
class ResetPasswordForm(FlaskForm):
password = PasswordField('Password', validators = [DataRequired()])
confirm_password = PasswordField('Confirm Password', validators = [DataRequired(), EqualTo('password')])
submit = SubmitField('Reset Password')
@app.route('/',methods=['GET', 'POST'])
def home():
... | '''
Raises a validation error if a user tries to register using an existing email
'''
if email.data != current_user.email:
user = User.query.filter_by(email = email.data).first()
if user is None:
raise ValidationError('There is no accouunt with that email.... | identifier_body |
app.py | import numpy as np
import yaml
import pickle
import os
from flask import Flask, request, jsonify, render_template, redirect, url_for, flash
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from wtforms import StringField,... | (FlaskForm):
email = StringField('email', validators = [InputRequired(), Email(message = 'Invalid Email'), Length(max = 50)])
username = StringField('UserName', validators = [InputRequired(), Length(min = 4, max = 15)])
submit = SubmitField('Update')
def validate_username(self, username):
'''
... | UpdateAccountForm | identifier_name |
app.py | import numpy as np
import yaml
import pickle
import os
from flask import Flask, request, jsonify, render_template, redirect, url_for, flash
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from wtforms import StringField,... | db.session.commit()
flash('Your account has been updated', 'success')
return redirect(url_for('account'))
elif request.method == 'GET':
form.username.data = current_user.username
form.email.data = current_user.email
return render_template('account.html', title = 'Accoun... | form = UpdateAccountForm()
if form.validate_on_submit():
current_user.username = form.username.data
current_user.email = form.email.data | random_line_split |
app.py | import numpy as np
import yaml
import pickle
import os
from flask import Flask, request, jsonify, render_template, redirect, url_for, flash
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from wtforms import StringField,... |
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
mail = Mail(app)
Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String... | app.debug = False
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
app.config['MAIL_SERVER'] = os.environ['MAIL_SERVER']
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = False
app.config['MAIL__USE_SSL'] = False
app.config['MAIL_USERNAME'] = os.environ['MAIL_USERNAME']
app.config... | conditional_block |
main.go | package main
import (
"fmt"
"image"
"log"
"math/rand"
"sync/atomic"
"time"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil"
"github.com/BurntSushi/xgbutil/xevent"
"github.com/BurntSushi/xgbutil/xgraphics"
"github.com/BurntSushi/xgbutil/xwindow"
)
var DisplayWindow *xwindow.Window
var Win... | (img *xgraphics.Image) {
img.XDraw()
img.XPaint(DisplayWindow.Id)
}
| DrawImage | identifier_name |
main.go | package main
import (
"fmt"
"image"
"log"
"math/rand"
"sync/atomic"
"time"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil"
"github.com/BurntSushi/xgbutil/xevent"
"github.com/BurntSushi/xgbutil/xgraphics"
"github.com/BurntSushi/xgbutil/xwindow"
)
var DisplayWindow *xwindow.Window
var Win... | func DrawImage(img *xgraphics.Image) {
img.XDraw()
img.XPaint(DisplayWindow.Id)
} | random_line_split | |
main.go | package main
import (
"fmt"
"image"
"log"
"math/rand"
"sync/atomic"
"time"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil"
"github.com/BurntSushi/xgbutil/xevent"
"github.com/BurntSushi/xgbutil/xgraphics"
"github.com/BurntSushi/xgbutil/xwindow"
)
var DisplayWindow *xwindow.Window
var Win... |
// Create a window
DisplayWindow, err = xwindow.Generate(X)
if err != nil {
log.Fatalf("Could not generate a new window X id: %s", err)
}
DisplayWindow.Create(X.RootWin(), 0, 0, 1024, 1024, xproto.CwBackPixel, 0)
DisplayWindow.Map()
WindowImage = xgraphics.New(X, image.Rect(0, 0, 1024, 1024))
err = Window... | {
log.Fatal(err)
} | conditional_block |
main.go | package main
import (
"fmt"
"image"
"log"
"math/rand"
"sync/atomic"
"time"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil"
"github.com/BurntSushi/xgbutil/xevent"
"github.com/BurntSushi/xgbutil/xgraphics"
"github.com/BurntSushi/xgbutil/xwindow"
)
var DisplayWindow *xwindow.Window
var Win... |
// Write an instruction to x,y,r
func WriteInstruction(x, y uint32, r *uint32, instr Instruction, data int32) {
mem, _ := Coords(x, y, *r)
instrData := (uint32(instr&0xF) << 20) | uint32(data&0xFFFFF)
Write24Bit(mem, instrData)
*r++
}
// Read a 24 bit pixel as 2x 12 bit uints
func Read12Bit(in []uint8) (outx, ou... | {
// Limit executions to 100 concurrent programs
count := atomic.AddInt64(&execCount, 1)
atomic.AddInt64(&forkCount, 1)
defer atomic.AddInt64(&execCount, -1)
if count > 100 {
return
}
// De-duplicate programs running at the same location
if int(x) >= WindowImage.Rect.Max.X || int(y) >= WindowImage.Rect.Max.Y... | identifier_body |
product_structs.go | // Copyright 2013 The Changkong Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package product
const VersionNo = "20140725"
/* 卖家设置售后服务对象 */
type AfterSale struct {
AfterSaleId int `json:"after_sale_id"`
AfterSaleName strin... | VerticalMarket int `json:"vertical_market"`
}
/* 产品扩展信息 */
type ProductExtraInfo struct {
FieldKey string `json:"field_key"`
FieldName string `json:"field_name"`
FieldValue string `json:"field_value"`
ProductId int `json:"product_id"`
}
/* 产品图片 */
type ProductImg struct {
Created string `json:"creat... | Tsc string `json:"tsc"` | random_line_split |
server-utils.ts | import type { IncomingMessage } from 'http'
import type { Rewrite } from '../lib/load-custom-routes'
import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig } from './config'
import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring... |
export function getUtils({
page,
i18n,
basePath,
rewrites,
pageIsDynamic,
trailingSlash,
caseSensitive,
}: {
page: string
i18n?: NextConfig['i18n']
basePath: string
rewrites: {
fallback?: ReadonlyArray<Rewrite>
afterFiles?: ReadonlyArray<Rewrite>
beforeFiles?: ReadonlyArray<Rewrite>
... | {
if (!defaultRouteRegex) return pathname
for (const param of Object.keys(defaultRouteRegex.groups)) {
const { optional, repeat } = defaultRouteRegex.groups[param]
let builtParam = `[${repeat ? '...' : ''}${param}]`
if (optional) {
builtParam = `[${builtParam}]`
}
const paramIdx = pathn... | identifier_body |
server-utils.ts | import type { IncomingMessage } from 'http'
import type { Rewrite } from '../lib/load-custom-routes'
import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig } from './config'
import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring... | (
req: BaseNextRequest | IncomingMessage,
renderOpts?: any,
detectedLocale?: string
) {
return getRouteMatcher(
(function () {
const { groups, routeKeys } = defaultRouteRegex!
return {
re: {
// Simulate a RegExp match from the \`req.url\` input
... | getParamsFromRouteMatches | identifier_name |
server-utils.ts | import type { IncomingMessage } from 'http'
import type { Rewrite } from '../lib/load-custom-routes'
import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig } from './config'
import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring... |
Object.assign(rewriteParams, destQuery, params)
Object.assign(parsedUrl.query, parsedDestination.query)
delete (parsedDestination as any).query
Object.assign(parsedUrl, parsedDestination)
fsPathname = parsedUrl.pathname
if (basePath) {
fsPathname =
... | {
return true
} | conditional_block |
server-utils.ts | import type { IncomingMessage } from 'http'
import type { Rewrite } from '../lib/load-custom-routes'
import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'
import type { NextConfig } from './config'
import type { BaseNextRequest } from './base-http'
import type { ParsedUrlQuery } from 'querystring... | rewrite.has,
rewrite.missing
)
if (hasParams) {
Object.assign(params, hasParams)
} else {
params = false
}
}
if (params) {
const { parsedDestination, destQuery } = prepareDestination({
appendParamsToQuery: true,
... |
if ((rewrite.has || rewrite.missing) && params) {
const hasParams = matchHas(
req,
parsedUrl.query, | random_line_split |
main.rs | use git2::{Commit, Oid, Repository};
use mailmap::{Author, Mailmap};
use regex::{Regex, RegexBuilder};
use semver::Version;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::{cmp, fmt, str};
use conf... |
}
new
}
}
fn git(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed t... | {
new.map.insert(author.clone(), set.clone());
} | conditional_block |
main.rs | use git2::{Commit, Oid, Repository};
use mailmap::{Author, Mailmap};
use regex::{Regex, RegexBuilder};
use semver::Version;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::{cmp, fmt, str};
use conf... | (repo: &Repository, at: &Commit) -> Result<String, Box<dyn std::error::Error>> {
if let Some(modules) = at.tree()?.get_name(".gitmodules") {
Ok(String::from_utf8(
modules.to_object(&repo)?.peel_to_blob()?.content().into(),
)?)
} else {
return Ok(String::new());
}
}
| modules_file | identifier_name |
main.rs | use git2::{Commit, Oid, Repository};
use mailmap::{Author, Mailmap};
use regex::{Regex, RegexBuilder};
use semver::Version;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::{cmp, fmt, str};
use conf... | .or_insert_with(HashSet::new)
.insert(commit);
}
fn iter(&self) -> impl Iterator<Item = (&Author, usize)> {
self.map.iter().map(|(k, v)| (k, v.len()))
}
fn extend(&mut self, other: Self) {
for (author, set) in other.map {
self.map
.en... | self.map
.entry(author) | random_line_split |
main.rs | use git2::{Commit, Oid, Repository};
use mailmap::{Author, Mailmap};
use regex::{Regex, RegexBuilder};
use semver::Version;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::{cmp, fmt, str};
use conf... |
lazy_static::lazy_static! {
static ref UPDATED: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}
fn update_repo(url: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
let mut slug = url;
let prefix = "https://github.com/";
if slug.starts_with(prefix) {
slug = &slug[prefix.len()..];... | {
let mut cmd = Command::new("git");
cmd.args(args);
cmd.stdout(Stdio::piped());
let out = cmd.spawn();
let mut out = match out {
Ok(v) => v,
Err(err) => {
panic!("Failed to spawn command `{:?}`: {:?}", cmd, err);
}
};
let status = out.wait().expect("wait... | identifier_body |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... |
}
impl GraphLayers<GraphLinksMmap> {
pub fn prefault_mmap_pages(&self, path: &Path) -> Option<mmap_ops::PrefaultMmapPages> {
self.links.prefault_mmap_pages(path)
}
}
#[cfg(test)]
mod tests {
use std::fs::File;
use std::io::Write;
use itertools::Itertools;
use rand::rngs::StdRng;
... | {
Ok(atomic_save_bin(path, self)?)
} | identifier_body |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... | (&self, point_id: PointOffsetType) -> usize {
self.links.point_level(point_id)
}
pub fn search(
&self,
top: usize,
ef: usize,
mut points_scorer: FilteredScorer,
) -> Vec<ScoredPointOffset> {
let entry_point = match self
.entry_points
.... | point_level | identifier_name |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... |
}
}
pub fn save(&self, path: &Path) -> OperationResult<()> {
Ok(atomic_save_bin(path, self)?)
}
}
impl GraphLayers<GraphLinksMmap> {
pub fn prefault_mmap_pages(&self, path: &Path) -> Option<mmap_ops::PrefaultMmapPages> {
self.links.prefault_mmap_pages(path)
}
}
#[cfg(test... | {
let try_legacy: Result<GraphLayersBackwardCompatibility, _> = read_bin(graph_path);
if let Ok(legacy) = try_legacy {
log::debug!("Converting legacy graph to new format");
let mut converter = GraphLinksConverter::new(legacy.links_layers);
... | conditional_block |
graph_layers.rs | use std::cmp::max;
use std::path::{Path, PathBuf};
use common::fixed_length_priority_queue::FixedLengthPriorityQueue;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use super::graph_links::{GraphLinks, GraphLinksMmap};
use crate::common::file_operations::{atomic_save_bin, read_bin, FileStorageError};
... | vector_storage: &TestRawScorerProducer<CosineMetric>,
graph: &GraphLayers<TGraphLinks>,
) -> Vec<ScoredPointOffset> {
let fake_filter_context = FakeFilterContext {};
let raw_scorer = vector_storage.get_raw_scorer(query.to_owned());
let scorer = FilteredScorer::new(raw_scorer.... | top: usize, | random_line_split |
Modules.py | # written by: S. Ali Ahmadi
# last modified: 7/30/2018 - 11:25 PM
#
#
# These modules are written for the purpose of Pattern Recognition course syllabus.
# Some of the functions can be used for general purposes (i.e. read_image)
#
from osgeo import gdal
import sys
import numpy as np
import matplotlib.pyplot as plt
fro... |
plt.show()
# ######################################################################################################################
def difference(time1, time2, channel=0, datype=float):
"""
:param time1: image of time 1, which is pre-phenomena;
:param time2: image of time 2, which is post-phen... | plt.scatter(range(x.shape[1]), x[b, :], marker='.', color='k',
s=0.3, alpha=0.6)
plt.tick_params(axis='y', length=3.0, pad=1.0, labelsize=7)
plt.tick_params(axis='x', length=0, labelsize=0) | conditional_block |
Modules.py | # written by: S. Ali Ahmadi
# last modified: 7/30/2018 - 11:25 PM
#
#
# These modules are written for the purpose of Pattern Recognition course syllabus.
# Some of the functions can be used for general purposes (i.e. read_image)
#
from osgeo import gdal
import sys
import numpy as np
import matplotlib.pyplot as plt
fro... | (reshaped_array, n):
"""
:param reshaped_array: an array with the shape of (n_samples, n_features).
:param n: number of principle components that should remain after transformation.
:return: a new array obtained from PCA with the shape of (n_samples, n_components)
"""
pca = PCA(n_componen... | pca_transform | identifier_name |
Modules.py | # written by: S. Ali Ahmadi
# last modified: 7/30/2018 - 11:25 PM
#
#
# These modules are written for the purpose of Pattern Recognition course syllabus.
# Some of the functions can be used for general purposes (i.e. read_image)
#
from osgeo import gdal
import sys
import numpy as np
import matplotlib.pyplot as plt
fro... | projection = src_file.GetProjectionRef() # Projection
# Need a driver object. By default, we use GeoTIFF
driver = gdal.GetDriverByName('GTiff')
outfile = driver.Create(dst_filename, xsize=cols, ysize=rows,
bands=num_bands, eType=gdal.GDT_Float32)
... | if src_file:
geo_transform = src_file.GetGeoTransform() | random_line_split |
Modules.py | # written by: S. Ali Ahmadi
# last modified: 7/30/2018 - 11:25 PM
#
#
# These modules are written for the purpose of Pattern Recognition course syllabus.
# Some of the functions can be used for general purposes (i.e. read_image)
#
from osgeo import gdal
import sys
import numpy as np
import matplotlib.pyplot as plt
fro... |
# ######################################################################################################################
def pca_transform(reshaped_array, n):
"""
:param reshaped_array: an array with the shape of (n_samples, n_features).
:param n: number of principle components that should remain af... | """
:param time1: image of time 1, which is pre-phenomena;
:param time2: image of time 2, which is post-phenomena; sizes must
agree each other.
:param channel: the default value is 0, which means all the bands;
but the user can specify to perform the application only on
... | identifier_body |
train_utils.py | import string
import random
import sys
import pickle
import pathlib
import time
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow as tf
import imgaug as ia
from imgaug import augmenters as iaa
# sys.path... | epochs=EPOCHS, ):
callbacks = create_callbacks(dataset, model_filename)
dataset.model = model
answers = [data_unit.answer for data_unit in dataset.data_list]
sample_num = len(answers)
# sample_num = len(answers)
train_num = int(sample_num * TRAIN_RATIO)
validate_num = int(sam... |
def train_model(model: Model, dataset, model_filename: str,
batch_size=BATCH_SIZE, | random_line_split |
train_utils.py | import string
import random
import sys
import pickle
import pathlib
import time
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow as tf
import imgaug as ia
from imgaug import augmenters as iaa
# sys.path... |
x_batch, y_batch = np.array(x_batch), np.array(y_batch)
if datatype != DataType.test:
x_batch = SEQ_CVXTZ.augment_images(x_batch).astype("float32")
x_batch = np.array([normalize(x) for x in x_batch])
# org_shape = x_batch.shape
# org_width = x_batch.shape[1]
... | try:
x, y, data_unit, index = create_xy(dataset, datatype)
# x = normalize(x)
x_batch.append(x)
y_batch.append(y)
except StopIteration:
break | conditional_block |
train_utils.py | import string
import random
import sys
import pickle
import pathlib
import time
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow as tf
import imgaug as ia
from imgaug import augmenters as iaa
# sys.path... | ():
# https://www.kaggle.com/CVxTz/cnn-starter-nasnet-mobile-0-9709-lb
def sometimes(aug):
return iaa.Sometimes(0.5, aug)
seq = iaa.Sequential(
[
# apply the following augmenters to most images
iaa.Fliplr(0.5), # horizontally flip 50% of all images
iaa.Fl... | create_sequential_cvxtz | identifier_name |
train_utils.py | import string
import random
import sys
import pickle
import pathlib
import time
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow as tf
import imgaug as ia
from imgaug import augmenters as iaa
# sys.path... |
def create_callbacks(dataset, name_weights, patience_lr=10, patience_es=150):
mcp_save = ModelCheckpoint('model/validate.weights.best.hdf5', save_best_only=True, monitor='val_loss')
# history = metrics.Histories(dataset)
# mcp_save = AllModelCheckpoint(name_weights)
# reduce_lr_loss = ReduceLROnPlate... | SEQ = iaa.Sequential([
iaa.OneOf([
iaa.Fliplr(0.5), # horizontal flips
iaa.Flipud(0.5), # vertically flips
iaa.Crop(percent=(0, 0.2)), # random crops
# Small gaussian blur with random sigma between 0 and 0.5.
# But we only blur about 50% of all imag... | identifier_body |
kubectl.go | /*
Copyright 2023 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... |
return false
}
func kubeClusterAddrFromProfile(profile *profile.Profile) string {
partialClientConfig := client.Config{
WebProxyAddr: profile.WebProxyAddr,
KubeProxyAddr: profile.KubeProxyAddr,
}
return partialClientConfig.KubeClusterAddr()
}
func overwriteKubeconfigFlagInArgs(args []string, newPath string)... | {
if find.Name() == "config" {
return true
}
} | conditional_block |
kubectl.go | /*
Copyright 2023 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... | if err := cli.RunNoErrOutput(command); err != nil {
closeSpanAndTracer()
// Pretty-print the error and exit with an error.
cmdutil.CheckErr(err)
}
closeSpanAndTracer()
os.Exit(0)
}
func runKubectlAndCollectRun(cf *CLIConf, fullArgs, args []string) error {
var (
alreadyRequestedAccess bool
err ... | command.SetArgs(args[1:])
// run command until it finishes. | random_line_split |
kubectl.go | /*
Copyright 2023 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... | (cf *CLIConf, fullArgs []string, args []string) error {
if os.Getenv(tshKubectlReexecEnvVar) == "" {
err := runKubectlAndCollectRun(cf, fullArgs, args)
return trace.Wrap(err)
}
runKubectlCode(cf, args)
return nil
}
const (
// tshKubectlReexecEnvVar is the name of the environment variable used to control if
/... | onKubectlCommand | identifier_name |
kubectl.go | /*
Copyright 2023 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... |
// makeAndStartKubeLocalProxy is a helper to create a kube local proxy and
// start it in a goroutine. If successful, a closeFn and the generated
// kubeconfig location are returned.
func makeAndStartKubeLocalProxy(cf *CLIConf, config *clientcmdapi.Config, clusters kubeconfig.LocalProxyClusters) (func(), string, erro... | {
opts := newKubeLocalProxyOpts(applyOpts...)
config, clusters, useLocalProxy := shouldUseKubeLocalProxy(cf, opts.kubectlArgs)
if !useLocalProxy {
return func() {}, "", nil
}
closeFn, newKubeConfigLocation, err := opts.makeAndStartKubeLocalProxyFunc(cf, config, clusters)
return closeFn, newKubeConfigLocation,... | identifier_body |
colocalization_snps.py | import os
import re
import sys
import datetime
import itertools
import json
from classes.ensembl_client import EnsemblRestClient
from classes.gene_database import GeneDatabase
from classes.enrichr import EnrichR
import numpy as np
import scipy.stats as stats
from statsmodels.sandbox.stats.multicomp import multipletests... |
def enrichr_db_test(file_name, region, genes_db, wsize, pvalue_thr=0.05, record_filter=None):
"""
Runs, for each record of a 'enrich_db table', a fisher test using 'calc_genes_in_region_table' contingency table
:param file_name: full path to enrich_db table
:param region: dict of {chr: [p1, p2, ...]}... | file_pattern = '(.+)\.txt'
ll_ids_pattern = '"([\w\s;]+)"'
prog = re.compile(file_pattern)
ll_prog = re.compile(ll_ids_pattern)
genes_db = create_gene_db('9606', os.path.join(input_path, 'GRCh38/mart_export.txt.gz'))
snp_files = [f for f in os.listdir(input_path) if os.path.isfile(os.path.join(inp... | identifier_body |
colocalization_snps.py | import os
import re
import sys
import datetime
import itertools
import json
from classes.ensembl_client import EnsemblRestClient
from classes.gene_database import GeneDatabase
from classes.enrichr import EnrichR
import numpy as np
import scipy.stats as stats
from statsmodels.sandbox.stats.multicomp import multipletests... |
return assoc
def calc_regions_by_gene_count(assoc):
"""
calculates data table for graph: num_genes vs num_regions (how many regions have 1, 2, 3, ... genes)
:param assoc:
:return: an array of tuples (x, y) sorted by x
"""
counts = {}
max_count = -1
for pos_list in assoc.values():
... | print 'warning: gene %s [%s] should be in a region' % (gene_data.name, gene_data.id) | conditional_block |
colocalization_snps.py | import os
import re
import sys
import datetime
import itertools
import json
from classes.ensembl_client import EnsemblRestClient
from classes.gene_database import GeneDatabase
from classes.enrichr import EnrichR
import numpy as np
import scipy.stats as stats
from statsmodels.sandbox.stats.multicomp import multipletests... | (gene_ids, input_path, output_path):
file_pattern = '(.+)\.txt'
ll_ids_pattern = '"([\w\s;]+)"'
prog = re.compile(file_pattern)
ll_prog = re.compile(ll_ids_pattern)
genes_db = create_gene_db('9606', os.path.join(input_path, 'GRCh38/mart_export.txt.gz'))
snp_files = [f for f in os.listdir(input... | test_genes_vs_multiple_snps | identifier_name |
colocalization_snps.py | import os
import re
import sys
import datetime
import itertools
import json
from classes.ensembl_client import EnsemblRestClient
from classes.gene_database import GeneDatabase
from classes.enrichr import EnrichR
import numpy as np
import scipy.stats as stats
from statsmodels.sandbox.stats.multicomp import multipletests... | magnitude += 1
num /= 1000.0
# add more suffixes if you need them
return '%i%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
def test1():
base_path = '/home/victor/Escritorio/Genotipado_Alternativo/colocalizacion'
snps_ids = load_lines(os.path.join(base_path, 'MS.txt'))
r... |
def human_format(num):
# returns an amount in a human readable format
magnitude = 0
while abs(num) >= 1000: | random_line_split |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... | )
}
}
pub fn place_repeated_scaled_image(image: &mut Image, repeated_image: &Image, pos: &Vec2i, scale: i32, repeat_x: bool, repeat_y: bool) {
let size = Vec2i::new(repeated_image.get_width() as i32, repeated_image.get_height() as i32) * scale;
let range_x = calc_range_for_repeated_line(repeat_x, pos.x, size.x, ... | random_line_split | |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... | else {
Color::rgba(
blend!(src.r, dst.r),
blend!(src.g, dst.g),
blend!(src.b, dst.b),
(outa / 255) as u8
)
}
}
#[inline]
/// Works on f32 with gamma correction of 2.2 power. Source: https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending + https://en.wikipedia.org/wiki/Alpha_compositing#Compos... | {
Color::rgba(0, 0, 0, 0)
} | conditional_block |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... |
pub fn save_png(&self, path: &Path) -> Result<(), std::io::Error> {
use std::fs::File;
use std::io::BufWriter;
let file = File::create(path)?;
let w = &mut BufWriter::new(file);
let mut encoder = png::Encoder::new(w, self.width as u32, self.height as u32);
encoder.set_color(png::ColorType::RGBA);
enc... | {
0..(self.height as i32)
} | identifier_body |
image.rs | use core::ops::Range;
use crate::ImageTrait;
use crate::vec::*;
use crate::rangetools::*;
use std::path::Path;
use static_assertions::*;
pub enum PixelPos {
R,
G,
B,
A,
}
pub fn convert(slice: &mut [Color]) -> &mut [u32] {
assert_eq_size!(Color, u32);
assert_eq_align!(Color, u32);
unsafe { std::slice::from_ra... | (src: &Color, dst: &Color) -> Color {
let srca = src.a as f32 / 255.0;
let dsta = dst.a as f32 / 255.0;
let outa = 1. - (1. - srca) * (1. - dsta);
macro_rules! blend {
($src:expr, $dst:expr) => {
(((($src as f32 / 255.0).powf(2.2) * srca + ($dst as f32 / 255.0).powf(2.2) * dsta * (1.0 - srca)) / outa).powf(1... | ideal_blend | identifier_name |
fish-eye-chart.ts | import {
Axis,
AxisScale,
ScaleOrdinal,
ScalePower,
Selection,
axisBottom,
axisLeft,
format,
pointer as pointerD3,
scaleLinear,
scaleLog,
scaleOrdinal,
scaleSqrt,
schemePastel2,
select,
} from "d3"
import d3Fisheye, { FishEyeScale } from "@/utils/fishEye"
import * as styles from "./fish-... |
public refresh() {
this.updateDimensions(1000)
}
private setupRootEl() {
const rootEl = document.getElementById(this.config.rootElId) as HTMLElement
rootEl.classList.add(styles.fishEyeChart)
this.width =
rootEl.getBoundingClientRect().width - margin.left - margin.right
}
private is... | {
return (
"ontouchstart" in window ||
navigator.maxTouchPoints > 0 ||
(navigator as any).msMaxTouchPoints > 0 // eslint-disable-line @typescript-eslint/no-explicit-any
)
} | identifier_body |
fish-eye-chart.ts | import {
Axis,
AxisScale,
ScaleOrdinal,
ScalePower,
Selection,
axisBottom,
axisLeft,
format,
pointer as pointerD3,
scaleLinear,
scaleLog,
scaleOrdinal,
scaleSqrt,
schemePastel2,
select,
} from "d3"
import d3Fisheye, { FishEyeScale } from "@/utils/fishEye"
import * as styles from "./fish-... | () {
const rootEl = document.getElementById(this.config.rootElId) as HTMLElement
rootEl.classList.add(styles.fishEyeChart)
this.width =
rootEl.getBoundingClientRect().width - margin.left - margin.right
}
private isSmallDevice() {
return this.width < 500
}
private setDom() {
const s... | setupRootEl | identifier_name |
fish-eye-chart.ts | import {
Axis,
AxisScale,
ScaleOrdinal,
ScalePower,
Selection,
axisBottom,
axisLeft,
format,
pointer as pointerD3,
scaleLinear,
scaleLog,
scaleOrdinal,
scaleSqrt,
schemePastel2,
select,
} from "d3"
import d3Fisheye, { FishEyeScale } from "@/utils/fishEye"
import * as styles from "./fish-... | yScale,
}
}
private setAxis() {
const formatFn = format(",d")
this.dom.xAxis = axisBottom(this.vars.xScale as AxisScale<number>)
.tickFormat((tickNumber) => {
if (tickNumber < 1000) {
return formatFn(tickNumber)
}
const reducedNum = Math.round(tickNumber ... | xScale, | random_line_split |
fish-eye-chart.ts | import {
Axis,
AxisScale,
ScaleOrdinal,
ScalePower,
Selection,
axisBottom,
axisLeft,
format,
pointer as pointerD3,
scaleLinear,
scaleLog,
scaleOrdinal,
scaleSqrt,
schemePastel2,
select,
} from "d3"
import d3Fisheye, { FishEyeScale } from "@/utils/fishEye"
import * as styles from "./fish-... |
if (!this.vars.focused) {
this.zoom({
animationDuration: 0,
interactionEvent,
})
}
})
}
private bindMouseLeave() {
return this.dom.svgG.on("mouseleave", () => {
if (!this.vars.focused) {
this.setZoom({
animationDuration: 1000,
... | {
return
} | conditional_block |
modular.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use authentication::perform_authentication;
use futures::{
future::{self, TryFutureExt},
Future, Stream, StreamExt, TryStreamExt,
};
use std::sync::Arc;
use tokio::sync::broadcast::{channel as event_channel, Sender as Broadcast... |
};
// Tunnel naming - The tunnel registry is notified of the authenticator-provided tunnel name
{
let tunnel_registry = Arc::clone(&serialized_tunnel_registry);
Self::name_tunnel(id, tunnel_name.clone(), tunnel_registry).instrument(tracing::span!(
tracing::Level::DEBUG,
"naming... | {
let _ = serialized_tunnel_registry.deregister_tunnel(id).await;
return Ok(());
} | conditional_block |
modular.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use authentication::perform_authentication;
use futures::{
future::{self, TryFutureExt},
Future, Stream, StreamExt, TryStreamExt,
};
use std::sync::Arc;
use tokio::sync::broadcast::{channel as event_channel, Sender as Broadcast... | }
}
}
async fn handle_incoming_request_bistream<Services>(
tunnel_id: TunnelId,
link: WrappedStream,
negotiator: Arc<NegotiationService<Services>>,
shutdown: CancellationToken, // TODO: Respond to shutdown listener requests
) -> Result<(), RequestProcessingError>
where
Services: S... | {
match link {
tunnel::TunnelIncomingType::BiStream(link) => {
Self::handle_incoming_request_bistream(id, link, negotiator, shutdown).await | random_line_split |
modular.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license OR Apache 2.0
use authentication::perform_authentication;
use futures::{
future::{self, TryFutureExt},
Future, Stream, StreamExt, TryStreamExt,
};
use std::sync::Arc;
use tokio::sync::broadcast::{channel as event_channel, Sender as Broadcast... | {
#[error(transparent)]
RegistrationError(#[from] TunnelRegistrationError),
#[error(transparent)]
RegistryNamingError(#[from] TunnelNamingError),
#[error(transparent)]
RequestProcessingError(RequestProcessingError),
#[error("Authentication refused to remote by either breach of protocol or invalid/inadequ... | TunnelLifecycleError | identifier_name |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... |
}
bitflags! {
pub struct PixelFormatFlags: u32 {
/// Texture contains alpha data.
const ALPHA_PIXELS = 0x1;
/// Alpha channel only uncomressed data (used in older DDS files)
const ALPHA = 0x2;
/// Texture contains compressed RGB data.
const FOURCC = 0x4;
///... | {
let mut pf: PixelFormat = Default::default();
if let Some(bpp) = format.get_bits_per_pixel() {
pf.flags.insert(PixelFormatFlags::RGB); // means uncompressed
pf.rgb_bit_count = Some(bpp as u32)
}
pf.fourcc = Some(FourCC(FourCC::DX10)); // we always use extention ... | identifier_body |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... |
let flags = PixelFormatFlags::from_bits_truncate(r.read_u32::<LittleEndian>()?);
let fourcc = r.read_u32::<LittleEndian>()?;
let rgb_bit_count = r.read_u32::<LittleEndian>()?;
let r_bit_mask = r.read_u32::<LittleEndian>()?;
let g_bit_mask = r.read_u32::<LittleEndian>()?;
... | {
return Err(Error::InvalidField("Pixel format struct size".to_owned()));
} | conditional_block |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... | )?;
Ok(())
}
}
impl Default for PixelFormat {
fn default() -> PixelFormat {
PixelFormat {
size: 32, // must be 32
flags: PixelFormatFlags::empty(),
fourcc: None,
rgb_bit_count: None,
r_bit_mask: None,
g_bit_mask: No... | writeln!(
f,
" RGBA bitmasks: {:?}, {:?}, {:?}, {:?}",
self.r_bit_mask, self.g_bit_mask, self.b_bit_mask, self.a_bit_mask | random_line_split |
pixel_format.rs | // The MIT License (MIT)
//
// Copyright (c) 2018 Michael Dilger
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, ... | <W: Write>(&self, w: &mut W) -> Result<(), Error> {
w.write_u32::<LittleEndian>(self.size)?;
w.write_u32::<LittleEndian>(self.flags.bits())?;
w.write_u32::<LittleEndian>(self.fourcc.as_ref().unwrap_or(&FourCC(0)).0)?;
w.write_u32::<LittleEndian>(self.rgb_bit_count.unwrap_or(0))?;
... | write | identifier_name |
amfinder_config.py | # AMFinder - amfinder_config.py
#
# MIT License
# Copyright (c) 2021 Edouard Evangelisti, Carl Turner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without ... | ():
"""
Builds AMFinder command-line parser.
"""
main = ArgumentParser(description='AMFinder command-line arguments.',
allow_abbrev=False,
formatter_class=RawTextHelpFormatter)
subparsers = main.add_subparsers(dest='run_mode', required=True,
... | build_arg_parser | identifier_name |
amfinder_config.py | # AMFinder - amfinder_config.py
#
# MIT License
# Copyright (c) 2021 Edouard Evangelisti, Carl Turner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without ... | files = sum([glob.glob(x) for x in files], [])
return [os.path.abspath(x) for x in files]
def update_tile_edge(path):
"""
Import image settings (currently tile edge).
:param path: path to the input image.
"""
zfile = os.path.splitext(path)[0] + '.zip'
if zf.is_zipfile(zfile):
... | Returns absolute paths to input files.
:param files: Raw list of input file names (can contain wildcards).
"""
| random_line_split |
amfinder_config.py | # AMFinder - amfinder_config.py
#
# MIT License
# Copyright (c) 2021 Edouard Evangelisti, Carl Turner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without ... |
elif id in PAR['monitors']:
PAR['monitors'][id] = value
elif create:
PAR[id] = value
else:
AmfLog.warning(f'Unknown parameter {id}')
def training_subparser(subparsers):
"""
Defines arguments used in training mode.
:param subparsers: ... | PAR[id] = value
if id == 'level':
PAR['header'] = HEADERS[int(value == 2)] # Ensures 0 or 1. | conditional_block |
amfinder_config.py | # AMFinder - amfinder_config.py
#
# MIT License
# Copyright (c) 2021 Edouard Evangelisti, Carl Turner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without ... |
def tsv_name():
"""
Return the TSV file corresponding to the current annotation level.
"""
if PAR['level'] == 1:
return 'col.tsv'
else:
return 'myc.tsv'
def get(id):
"""
Retrieve application settings.
:param id: Unique identifier.
"""
id ... | """ Returns the application directory. """
return APP_PATH | identifier_body |
main.rs | #![feature(proc_macro)]
#![no_std]
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate stm32f30x_hal as hal;
extern crate ls010b7dh01;
extern crate rn4870;
extern crate embedded_graphics as graphics;
extern crate panic_abort;
extern crate nb;
mod display;
mod ble;
use cortex_m::asm;
use cortex_m:... | rcc.apb2.rstr().modify(|_, w| w.syscfgrst().clear_bit());
// Enable systick
p.core.SYST.set_clock_source(SystClkSource::Core);
p.core.SYST.set_reload(16_000_000);
p.core.SYST.enable_interrupt();
p.core.SYST.enable_counter();
// Set up our clocks & timer & delay
let clocks = rcc.cfgr.fr... |
// Enable the syscfg
rcc.apb2.enr().modify(|_, w| w.syscfgen().enabled());
rcc.apb2.rstr().modify(|_, w| w.syscfgrst().set_bit()); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.