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 |
|---|---|---|---|---|
main.js | 70000;
var particles = new THREE.Geometry();
function newpos( x, y, z ) {
return new THREE.Vector3( x, y, z );
}
var Pool = {
__pools: [],
// Get a new Vector
get: function() {
if ( this.__pools.length > 0 ) {
return this.__pools.pop();
}
... |
lightness += 0.0003 * delta;
if ( lightness > 0.05 ) lightness -= 0.05;
// TODO Create a PointOnShape Action/Zone in the particle engine
timeOnShapePath += 0.00035 * delta;
if ( timeOnShapePath > 1 ) timeOnShapePath -= 1;
var pointOnShape = circleShape.getPointAt( tim... |
hue += 0.0003 * delta;
if ( hue > 0.1 ) hue -= 0.1; | random_line_split |
main.js | .getElementById( 'vertexshader' ).textContent,
fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true
});
particleCloud = new THREE.PointCloud( particles, shaderMaterial );
var vertices = par... | delta | identifier_name | |
main.js | 70000;
var particles = new THREE.Geometry();
function newpos( x, y, z ) {
return new THREE.Vector3( x, y, z );
}
var Pool = {
__pools: [],
// Get a new Vector
get: function() {
if ( this.__pools.length > 0 ) {
return this.__pools.pop();
}
... | values_color[ target ].setHSL( hue, 0.6, lightness );
pointLight.color.setHSL( hue, 0.6, lightness );
};
};
var onParticleDead = function( particle ) {
var target = particle.target;
if ( target ) {
// Hide the particle
values_color[ target ].setRGB( 0, 0... | * delta;
if ( lightness > 0.05 ) lightness -= 0.05;
// TODO Create a PointOnShape Action/Zone in the particle engine
timeOnShapePath += 0.00035 * delta;
if ( timeOnShapePath > 1 ) timeOnShapePath -= 1;
var pointOnShape = circleShape.getPointAt( timeOnShapePath );
if (!... | conditional_block |
roles.go | memory"`
VirtualCPUs int `yaml:"virtual-cpus"`
ExposedPorts []*RoleRunExposedPort `yaml:"exposed-ports"`
FlightStage FlightStage `yaml:"flight-stage"`
HealthCheck *HealthCheck `yaml:"healthcheck,omitempty"`
}
// RoleRunScaling describes how a role should ... | {
roleSignature = fmt.Sprintf("%s\n%s", roleSignature, pkg.SHA1)
} | conditional_block | |
roles.go | Manual = FlightStage("manual") // A role that only runs via user intervention
)
// RoleManifest represents a collection of roles
type RoleManifest struct {
Roles Roles `yaml:"roles"`
Configuration *Configuration `yaml:"configuration"`
manifestFilePath string
rolesByName map[string]*... | LookupRole | identifier_name | |
roles.go | main job |
// RoleManifest represents a collection of roles
type RoleManifest struct {
Roles Roles `yaml:"roles"`
Configuration *Configuration `yaml:"configuration"`
manifestFilePath string
rolesByName map[string]*Role
}
// Role represents a collection of jobs that are colocated on a container
type Ro... | FlightStagePostFlight = FlightStage("post-flight") // A role that runs after the main jobs are up
FlightStageManual = FlightStage("manual") // A role that only runs via user intervention
) | random_line_split |
roles.go | job
FlightStagePostFlight = FlightStage("post-flight") // A role that runs after the main jobs are up
FlightStageManual = FlightStage("manual") // A role that only runs via user intervention
)
// RoleManifest represents a collection of roles
type RoleManifest struct {
Roles Roles `yaml:"r... |
// LoadRoleManifest loads a yaml manifest that details how jobs get grouped into roles
func LoadRoleManifest(manifestFilePath string, releases []*Release) (*RoleManifest, error) {
manifestContents, err := ioutil.ReadFile(manifestFilePath)
if err != nil {
return nil, err
}
mappedReleases := map[string]*Release{... | {
roles[i], roles[j] = roles[j], roles[i]
} | identifier_body |
autoComplete.js | //alert(scrol.innerHTML);
popup_ac(1); //자동완성창 보여줌.
//document.all.ac_body.style.display = B ;
setTimeout('set_ahl();', 10);
}
function get_aclist() {
var d = "", ds = "", l = 0, s = "", cnt = 0, pos = 0, qlen = 0, img = "";
if (qs_ac_list[0] != "") {
s += "<table width=100% cellpadding... | , me = 1;
o = get_cc(me);
if (o && o[1][0] != "") { ac_show(o[0], o[1], o[2], me); }
else { reqAC(me | identifier_body | |
autoComplete.js | 13) {
//if (a_now>0) search_keyword(qs_ac_list[a_now]);
}
if (key == 40 || (key == 9)) {
if (!a_on) {
req_ac2(1);
return;
}
if (a_now < qs_ac_len) {
if (a_now == 0) bak = search_box.value;
a_now++;
if (a_now > max_row... | random_line_split | ||
autoComplete.js | _body")[0].style.display == "block")
popup_ac(0);
else
popup_ac(2);
}
else {
if ($j("#schInput").val() == "") {
if ($j("#noquery_ac_body")[0].style.display == "block")
popup_ac(0);
else
popup_ac(3);
}
... | rn;
}
if (arr_on) {
return;
}
if (frm_on) {
return;
}
alw = 0;
ac_hide();
}
function req_ac2(me) {
if (search_box.value == "" || acuse == 0) return;
if (a_on && dnc) {
ac_hide();
return;
}
var o = get_cc(me);
if (o && o[1][0] != "") { ... | tu | identifier_name |
autoComplete.js | tch_image(1);
}
}
//인풋박스의 세모 버튼을 눌렀을때 자동완성창을 보여준다.
function show_ac() {
if (acuse == 0) {
if ($j("#ac_body")[0].style.display == "block")
popup_ac(0);
else
popup_ac(2);
}
else {
if ($j("#schInput").val() == "") {
if ($j("#noquery_ac_body")[0]... | if (type == 3) {
$j("#ac_body").css("display", "none");
$j("#off_ac_body").css("display", "none");
$j("#noquery_ac_body")[0].style.display = "block";
swi | conditional_block | |
Marriah_Lewis_Cinema_Project.py |
url = 'https://en.wikipedia.org/wiki/Film_series'
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
#Create a function to process the string into an integer by using re.sub()
def process_num(num):
return float(re.sub(r'[^\w\s.]','',num))
#test function
... | new_df = pd.DataFrame(df.groupby(groupby_column)[count_column].count())
new_df.columns = ['count']
new_df[groupby_column] = new_df.index.get_level_values(0)
new_df.reset_index(drop = True, inplace = True)
return(new_df) | identifier_body | |
Marriah_Lewis_Cinema_Project.py | (movies_TMDB_kaggle.isnull().sum()) #tagline and homepage has the most NaN, unnecessary columns
#Clean the dataframe, removed any unnecessary columns
clean_TMDB_movies= movies_TMDB_kaggle.drop(columns=['homepage', 'id', 'overview', 'status', 'tagline', 'original_title'])
#print(clean_TMDB_movies) #result 4803 ro... | clean_TMDB_movies = clean_TMDB_movies[clean_TMDB_movies['budget'] != 0]
#Removing any movie with a revenue of 0
clean_TMDB_movies = clean_TMDB_movies[clean_TMDB_movies['revenue'] != 0]
#review the profit for each movie therefore a profit column was created
clean_TMDB_movies['profit'] = clean_TMDB_movies['revenue'... | clean_TMDB_movies.dropna(inplace= True)
#print(clean_TMDB_movies.isnull().sum())
#Removing any movie that has a budget of 0
| random_line_split |
Marriah_Lewis_Cinema_Project.py | (movies_TMDB_kaggle.isnull().sum()) #tagline and homepage has the most NaN, unnecessary columns
#Clean the dataframe, removed any unnecessary columns
clean_TMDB_movies= movies_TMDB_kaggle.drop(columns=['homepage', 'id', 'overview', 'status', 'tagline', 'original_title'])
#print(clean_TMDB_movies) #result 4803 ro... |
movies_discretized["main_production"] = production_company
#print(movies_discretized["main_production"].head())
movies_discretized_count = movies_discretized.groupby(["main_production", "percent_profit"])["main_production"].count()
movies_discretized_count_df= pd.DataFrame(movies_discretized_count)
#print(movie... | production_company.append("None") | conditional_block |
Marriah_Lewis_Cinema_Project.py | (df, groupby_column, count_column):
new_df = pd.DataFrame(df.groupby(groupby_column)[count_column].count())
new_df.columns = ['count']
new_df[groupby_column] = new_df.index.get_level_values(0)
new_df.reset_index(drop = True, inplace = True)
return(new_df)
url = 'https://en.wikipedia.org... | groupby_count | identifier_name | |
trace_processing.py | # Create hierarchical interactions in traces
##############################################################
def convert_traces(traces):
return [convert_to_interactions(trace) for trace in traces]
def convert_to_interactions(trace):
used = set()
return [create_interaction(trace, i, used) for i in range(len... |
for j in range(i-1,-1,-1):
print("interaction: {} {}".format(interaction[j].agent_eid, tgt_eid))
if interaction[j].agent_eid == tgt_eid:
return interaction[j]
return None
def interaction_responses(interaction, i):
"""Return the dns that act on the agent of i during that behav... | return None | conditional_block |
trace_processing.py | # Create hierarchical interactions in traces
##############################################################
def convert_traces(traces):
return [convert_to_interactions(trace) for trace in traces]
def convert_to_interactions(trace):
used = set()
return [create_interaction(trace, i, used) for i in range(len... |
def continued_involvement(doing, eid, clock, step=0.01):
"""True if acting or targeted beyond the next frame."""
if eid in doing:
if doing[eid].end_clock > (clock+step): return True
for dn in active_target_of(doing, eid):
if dn.end_clock > (clock+step): return True
return False
######... | """True if acting or targeted in current doing set."""
if eid in doing: return True
for dn in active_target_of(doing, eid):
return True
return False | identifier_body |
trace_processing.py | # Create hierarchical interactions in traces
##############################################################
def convert_traces(traces):
return [convert_to_interactions(trace) for trace in traces]
def convert_to_interactions(trace):
used = set()
return [create_interaction(trace, i, used) for i in range(len... | return interaction[j]
return None
def interaction_responses(interaction, i):
"""Return the dns that act on the agent of i during that behavior."""
agent_eid = interaction[i].agent_eid
# no agent, no response (REM: that's not right, but is given how we're creating interactions right now)
... | for j in range(i-1,-1,-1):
print("interaction: {} {}".format(interaction[j].agent_eid, tgt_eid))
if interaction[j].agent_eid == tgt_eid: | random_line_split |
trace_processing.py | # Create hierarchical interactions in traces
##############################################################
def convert_traces(traces):
return [convert_to_interactions(trace) for trace in traces]
def convert_to_interactions(trace):
used = set()
return [create_interaction(trace, i, used) for i in range(len... | (doing, eid):
"""True if acting or targeted in current doing set."""
if eid in doing: return True
for dn in active_target_of(doing, eid):
return True
return False
def continued_involvement(doing, eid, clock, step=0.01):
"""True if acting or targeted beyond the next frame."""
if eid in d... | current_involvement | identifier_name |
label.go | /label\s*(.*)$`)
customRemoveLabelRegex = regexp.MustCompile(`(?m)^/remove-label\s*(.*)$`)
nonExistentAdditionalLabels = "The label(s) `%s` cannot be applied. These labels are supported: `%s`."
nonExistentLabelInRepo = "The label(s) `%s` cannot be applied, because the repository doesn't have them."
nonExi... | return nil
}
org := e.Repo.Owner.Login
repo := e.Repo.Name
repoLabels, err := gc.GetRepoLabels(org, repo)
if err != nil {
return err
}
issueLabels, err := gc.GetIssueLabels(org, repo, e.Issue.Number)
if err != nil {
return err
}
repoExistingLabels := map[string]string{}
for _, l := range repoLabels ... | {
// Arrange prefixes in the format "sig|kind|priority|...",
// so that they can be used to create labelRegex and removeLabelRegex.
labelPrefixes := strings.Join(prefixes, "|")
labelRegex, err := regexp.Compile(fmt.Sprintf(labelRegexp, labelPrefixes))
if err != nil {
return err
}
removeLabelRegex, err := rege... | identifier_body |
label.go | /label\s*(.*)$`)
customRemoveLabelRegex = regexp.MustCompile(`(?m)^/remove-label\s*(.*)$`)
nonExistentAdditionalLabels = "The label(s) `%s` cannot be applied. These labels are supported: `%s`."
nonExistentLabelInRepo = "The label(s) `%s` cannot be applied, because the repository doesn't have them."
nonExi... | noSuchLabelsOnIssue []string
labelsToAdd []string
labelsToRemove []string
)
// Get labels to add and labels to remove from the RegExp matches.
// Notice: The returned label is lowercase.
labelsToAdd = append(getLabelsFromREMatches(labelMatches),
getLabelsFromGenericMatches(customLabelMatches, ... |
var (
nonexistent []string
noSuchLabelsInRepo []string | random_line_split |
label.go | /label\s*(.*)$`)
customRemoveLabelRegex = regexp.MustCompile(`(?m)^/remove-label\s*(.*)$`)
nonExistentAdditionalLabels = "The label(s) `%s` cannot be applied. These labels are supported: `%s`."
nonExistentLabelInRepo = "The label(s) `%s` cannot be applied, because the repository doesn't have them."
nonExi... | (gc githubClient, log *logrus.Entry, additionalLabels,
prefixes, excludeLabels []string, e *github.IssueCommentEvent) error {
// Arrange prefixes in the format "sig|kind|priority|...",
// so that they can be used to create labelRegex and removeLabelRegex.
labelPrefixes := strings.Join(prefixes, "|")
labelRegex, e... | handle | identifier_name |
label.go | /label\s*(.*)$`)
customRemoveLabelRegex = regexp.MustCompile(`(?m)^/remove-label\s*(.*)$`)
nonExistentAdditionalLabels = "The label(s) `%s` cannot be applied. These labels are supported: `%s`."
nonExistentLabelInRepo = "The label(s) `%s` cannot be applied, because the repository doesn't have them."
nonExi... |
if opts.ExcludeLabels != nil {
excludeLabelsConfigMsg = fmt.Sprintf("%v labels cannot be added by command.\n",
opts.ExcludeLabels)
}
labelConfig[repo.String()] = prefixConfigMsg + additionalLabelsConfigMsg + excludeLabelsConfigMsg
}
yamlSnippet, err := plugins.CommentMap.GenYaml(&tiexternalplugi... | {
additionalLabelsConfigMsg = fmt.Sprintf("%v labels can be used with the `/[remove-]label` command.\n",
opts.AdditionalLabels)
} | conditional_block |
iphelper.go | != nil {
return location, err
}
location, err = this.parseIpGeo(row)
return location, err
}
// 获取ip的区域编码
func (this *IpStore) GetGeocodeByIp(ipSearch string) (uint64, error) {
ro | .searchIpRow(ipSearch)
if err != nil {
return 0, err
}
areacode := this.getGeocodeByRow(row)
codeUint64, err := strconv.ParseUint(areacode, 10, 64)
if err != nil {
return 0, err
}
return codeUint64, nil
}
func (this *IpStore) GetGeoByGeocode(areacode uint64) map[string]string {
result := map... | w, err := this | identifier_name |
iphelper.go | != nil {
return location, err
}
location, err = this.parseIpGeo(row)
return location, err
}
// 获取ip的区域编码
func (this *IpStore) GetGeocodeByIp(ipSearch string) (uint64, error) {
row, err := this.searchIpRow(ipSearch)
if err != nil {
return 0, err
}
areacode := this.getGeocodeByRow(row)
codeUin... | }
if err = binary.Read(buf, binary.BigEndian, &row.Operator); err != nil {
goto fail
}
fail:
return row, err
}
func IP2Num(requestip string) uint64 {
//获取客户端地址的long
nowip := strings.Split(req
uestip, ".")
if len(nowip) != 4 {
return 0
}
a, _ := strconv.ParseUint(nowip[0], 10, 64)
b, _ := s... | art); err != nil {
goto fail
}
if err = binary.Read(buf, binary.BigEndian, &row.End); err != nil {
goto fail
}
if err = binary.Read(buf, binary.BigEndian, &row.Country); err != nil {
goto fail
}
if err = binary.Read(buf, binary.BigEndian, &row.Province); err != nil {
goto fail
}
if err = bin... | identifier_body |
iphelper.go | err != nil {
panic("error read header" + err.Error())
}
this.metaLength = binary.BigEndian.Uint32(buf[0:4])
fmt.Println("meta length is: ", this.metaLength)
if err := this.paseBody(file); err != nil {
panic("parse body failed:" + err.Error())
}
if err := this.parseMeta(file); err != nil {
panic... | break
}
}
if err := output.writeFile(); err != nil {
| random_line_split | |
iphelper.go | != nil {
return location, err
}
location, err = this.parseIpGeo(row)
return location, err
}
// 获取ip的区域编码
func (this *IpStore) GetGeocodeByIp(ipSearch string) (uint64, error) {
row, err := this.searchIpRow(ipSearch)
if err != nil {
return 0, err
}
areacode := this.getGeocodeByRow(row)
codeUin... | il
}
func (this *IpStore) parseMeta(file *os.File) (err error) {
this.metaBuffer = make([]byte, this.metaLength)
if _, err := file.ReadAt(this.metaBuffer, int64(HEADER_LENGTH+HEADER_LENGTH+this.bodyLength)); err != nil {
panic("read meta error")
}
return json.Unmarshal(this.metaBuffer, &this.metaTable)
... | LENGTH
}
return n | conditional_block |
deeqlearning_atari.py | .offset_width, self.target_height, self.target_width)
output = tf.image.resize(output, [IM_SIZE, IM_SIZE], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
return tf.squeeze(output)
def update_state(current_state, next_frame):
'''Takes in the current state, next frame and returns the next state'''
... | self.optimizer.apply_gradients(zip(grads, self.trainable_weights))
return loss_value
def copy_from(self, other):
weights = other.get_weights()
self.set_weights(weights)
def predict(self, X):
X = np.atleast_2d(X)
return self(X)
def sample_action(self, X, eps... | with tf.GradientTape() as tape:
Y_hat = self(X)
# Loss value for this minibatch
loss_value = cost(G, Y_hat, actions, self.K)
grads = tape.gradient(loss_value, self.trainable_weights) | random_line_split |
deeqlearning_atari.py | _width, self.target_height, self.target_width)
output = tf.image.resize(output, [IM_SIZE, IM_SIZE], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
return tf.squeeze(output)
def update_state(current_state, next_frame):
'''Takes in the current state, next frame and returns the next state'''
retur... | (model, target_model, experience_replay_buffer, gamma, batch_size):
#sample experiences
states, actions, rewards, next_states, dones = experience_replay_buffer.get_minibatch()
#calculate targets
next_Qs = target_model.predict(next_states)
next_Q = np.amax(next_Qs, axis=1)
targets = rew... | learn | identifier_name |
deeqlearning_atari.py | _width, self.target_height, self.target_width)
output = tf.image.resize(output, [IM_SIZE, IM_SIZE], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
return tf.squeeze(output)
def update_state(current_state, next_frame):
'''Takes in the current state, next frame and returns the next state'''
retur... |
def sample_action(self, X, eps):
if np.random.random() < eps:
return np.random.choice(self.K)
else:
return np.argmax(self.predict([X])[0])
def learn(model, target_model, experience_replay_buffer, gamma, batch_size):
#sample experiences
states, actions, re... | X = np.atleast_2d(X)
return self(X) | identifier_body |
deeqlearning_atari.py | .offset_width, self.target_height, self.target_width)
output = tf.image.resize(output, [IM_SIZE, IM_SIZE], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
return tf.squeeze(output)
def update_state(current_state, next_frame):
'''Takes in the current state, next frame and returns the next state'''
... |
if self.terminal_flags[index - self.agent_history_length : index].any():
#checks for done flag
continue
break
self.indices[i] = index
def get_minibatch(self):
'''Returns a minibatch of self.batch_size transitions'''
... | continue | conditional_block |
seasonal_cycle_utils.py |
def get_semiannual_cycle(tas):
"""Helper function: get the magnitude and phase for the mode with period 6 """
return get_cycle(tas,period=6)
def get_cycle_map(tas,period = 12):
ntime,nlat,nlon = tas.shape
AMP = MV.zeros((nlat,nlon))
PHI = MV.zeros((nlat,nlon))
for i in range(nlat):
fo... | """Return the tangent of the phase associated with Fourier mode"""
L = len(tas)
freqs = np.fft.fftfreq(L)
closest = np.abs(freqs-1./period)
# i = np.where(freqs == 1./period)[0]
i = np.argmin(closest)
#print 1/freqs[i]
tas_fft = np.fft.fft(tas)/L
R = tas_fft.real
Im = tas_fft.imag
... | identifier_body | |
seasonal_cycle_utils.py | .shape[1])
PHI = MV.zeros(tas.shape[1])
for j in range(tas.shape[1]):
mag,phase = get_cycle(tas[:,j],period=period)
AMP[j] = mag
PHI[j] = phase
AMP.setAxis(0,tas.getLatitude())
PHI.setAxis(0,tas.getLatitude())
return AMP,PHI
def get_annual_cycle_trends(X):
""... | nt, = X.shape
has_models = False | conditional_block | |
seasonal_cycle_utils.py | )
PHI[i,j] = phase
AMP.setAxis(0,tas.getLatitude())
AMP.setAxis(1,tas.getLongitude())
PHI.setAxis(0,tas.getLatitude())
PHI.setAxis(1,tas.getLongitude())
return AMP,PHI
def get_zonal_cycle(tas,period=12.):
if "longitude" in tas.getAxisIds():
tas = cdutil.averager(tas,axis='x'... | fast_annual_cycle | identifier_name | |
seasonal_cycle_utils.py | .average(obs)
if anom:
themean = 0
###TEST
# mag=2*mag
return mag*np.cos(2*np.pi/period*np.arange(len(obs))+phase)+themean
def var_expl_by_annual_cycle(obs,period = 12,detrend = True):
# mag,phase = get_cycle(obs)
if detrend:
obs = signal.detrend(obs)
recon = phase_angle_form(... | nt,nlat,nlon = P.shape
for i in range(nlat):
for j in range(nlon): | random_line_split | |
web.rs |
use crate::Shared;
use crate::DataLogEntry;
use crate::TSDataLogEntry;
use file_db::{create_intervall_filtermap, TimestampedMethods};
use hyper::StatusCode;
use hyper::server::{Http, NewService, Request, Response, Server, Service};
use hyper::header;
use futures::future::{FutureExt as _, TryFutureExt}; // for conver... | random_line_split | ||
web.rs | 345".parse().unwrap();
let server = Http::new()
.bind(
&addr,
HelloWorldSpawner {
shared: shared.clone(),
template_registry: template_registry.clone(),
assets_folder: Rc::new(assets_folder.clone()),
},
)
.unw... | box_and_convert_error | identifier_name | |
web.rs | "WEBASSETS_FOLDER not found ({})",
assets_folder.to_string_lossy()
);
}
let index_html = assets_folder.join("index.html");
if !index_html.is_file() {
bail!("Missing index.html in WEBASSETS_FOLDER.");
}
let template_registry = Rc::new(RefCell::new(Handlebars... | else {
Err(::failure::err_msg("Unknown asset"))
}
}))
}
None => make404(),
}
}
fn serve_history<'a>(&self, date: Option<&'a str>) -> HandlerResult {
match NaiveDate::parse_from_str(date.unwrap_or("nodate"), ... | {
let mut f = File::open(path).unwrap();
let mut buffer = String::new();
f.read_to_string(&mut buffer).unwrap();
Ok(buffer).map(str_to_response)
} | conditional_block |
web.rs | .0:12345".parse().unwrap();
let server = Http::new()
.bind(
&addr,
HelloWorldSpawner {
shared: shared.clone(),
template_registry: template_registry.clone(),
assets_folder: Rc::new(assets_folder.clone()),
},
)
... | {
Response::new()
.with_header(header::ContentLength(body.len() as u64))
.with_body(body)
} | identifier_body | |
cmds.py | Error: \"%s\" already specified as winner.'
ERROR_DUP_LOSER = 'Error: \"%s\" duplicated in losers list'
ERROR_IN_DB = 'Error: \"%s\" is already in the database'
ERROR_SORT_ERROR = 'Error while sorting list. Make sure all players have at least one win or loss.\n'
ERROR_INVALID_SORT = 'Error: Invalid sorting type. Disp... | winnerVal = int(rows[winnerIndex][1])
rows[winnerIndex][1] = str(winnerVal + 1)
# same as winner for each loser
for loser in losers:
loserIndex = getIndex(loser, rows)
loserVal = int(rows[loserIndex][2])
rows[loserIndex][2] = str(loserVal + 1)
# write the new data to the da... | # get index, get win count, increment and update
winnerIndex = getIndex(winner, rows) | random_line_split |
cmds.py | : \"%s\" already specified as winner.'
ERROR_DUP_LOSER = 'Error: \"%s\" duplicated in losers list'
ERROR_IN_DB = 'Error: \"%s\" is already in the database'
ERROR_SORT_ERROR = 'Error while sorting list. Make sure all players have at least one win or loss.\n'
ERROR_INVALID_SORT = 'Error: Invalid sorting type. Displayin... | (msgChannel, statsFile, sortType='WINRATE', player='ALL'):
# read database
data = readDB(statsFile)
# return an error if database not found
if data == 0:
return ERROR_DB_NOT_FOUND
rows = data.rows
print('[INFO] Sort type is %s' % sortType)
returnMsg = ''
if sortType == 'WINRATE'... | dumpStats | identifier_name |
cmds.py | : \"%s\" already specified as winner.'
ERROR_DUP_LOSER = 'Error: \"%s\" duplicated in losers list'
ERROR_IN_DB = 'Error: \"%s\" is already in the database'
ERROR_SORT_ERROR = 'Error while sorting list. Make sure all players have at least one win or loss.\n'
ERROR_INVALID_SORT = 'Error: Invalid sorting type. Displayin... | print('[INFO] \"%s\" added to database' % player)
return INFO_DB_SUCCESS
else:
print('[INFO] Database not updated')
return ERROR_DB_ERROR
elif editType == 'EDIT':
if playerIndex < 0:
print('[ERROR] \"%s\" not found in da... | data = readDB(statsFile)
# return an error if database not found
if data == 0:
return ERROR_DB_NOT_FOUND
rows = data.rows
playerIndex = getIndex(player, rows)
# check if player is already in database
if editType == 'ADD':
if playerIndex > -1:
print('[ERROR] \"%s\" al... | identifier_body |
cmds.py | : \"%s\" already specified as winner.'
ERROR_DUP_LOSER = 'Error: \"%s\" duplicated in losers list'
ERROR_IN_DB = 'Error: \"%s\" is already in the database'
ERROR_SORT_ERROR = 'Error while sorting list. Make sure all players have at least one win or loss.\n'
ERROR_INVALID_SORT = 'Error: Invalid sorting type. Displayin... |
else:
rows[playerIndex] = [rows[playerIndex][0], wins, losses]
# write the new data to the database file
if writeDB(statsFile, data.headers, rows):
print('[INFO] %s\'s data changed' % player)
return INFO_DB_SUCCESS
else:
... | print('[ERROR] \"%s\" not found in database' % player)
print('[INFO] Database not updated')
return (ERROR_PLAYER_NOT_FOUND % player) | conditional_block |
jherax.js | var _dom = document.activeElement;
var _sel = { text: "", slice: "", start: -1, end: -1 };
if (window.getSelection) {
// Get selected text from input fields
if (input.isText(_dom)) {
_sel.start = _dom.selectionStart;
_sel.end = _dom.selecti... | M(_dom)) _dom = $(_dom);
_dom.on("blur", function () { $(".vld-tooltip").remove(); });
var vld = $('<span class="vld-tooltip">' + _msg + '</span>');
vld.appendTo(js.wrapper).position({
of: _dom,
at: "right center",
my: "left+6 center",
collision: "... | identifier_body | |
jherax.js | { return ("0" + n.toString()).slice(-2); };
var fnDate = function() { return (fillZero(f.getDate()) +"/"+ fillZero(f.getMonth() + 1) +"/"+ f.getFullYear()); };
var fnTime = function() { return (fillZero(f.getHours()) +":"+ fillZero(f.getMinutes()) +":"+ fillZero(f.getSeconds())); };
var fnDateT... | (i, value) {
var html = $("<div/>").text(value).html();
return $.trim(html);
}
//-----------------------------------
// Gets selected text in the document
function fnGetSelectedText() {
var _dom = document.activeElement;
var _sel = { text: "", slice: "", start: -1, end: -... | fnGetHtmlText | identifier_name |
jherax.js | { return ("0" + n.toString()).slice(-2); };
var fnDate = function() { return (fillZero(f.getDate()) +"/"+ fillZero(f.getMonth() + 1) +"/"+ f.getFullYear()); };
var fnTime = function() { return (fillZero(f.getHours()) +":"+ fillZero(f.getMinutes()) +":"+ fillZero(f.getSeconds())); };
var fnDateT... | _text = _text.replace(/^\w/, _text.charAt(0).toUpperCase());
if (_isDOM) obj.value = _text;
return _text;
}
//-----------------------------------
// Sets the numeric format in es-CO culture.
// Places decimal "." and thousand "," separator
function fnNumericFormat(obj) {
var... | if (_type == "upper") _text = _text.toUpperCase();
if (_type == "lower" || _type == "word") _text = _text.toLowerCase();
if (_type == "title" || _type == "word") {
_text = _text.replace(/(?:^|-|:|;|\s|\.|\(|\/)[a-záéíóúüñ]/g, function (m) { return m.toUpperCase(); });
... | conditional_block |
jherax.js | return "{" + arr.join(",") + "}";
};
//-----------------------------------
// Escaping user input to be treated as a literal string within a regular expression
function fnEscapeRegExp(txt){
if (typeof txt !== "string") return null;
return txt.replace(/([.*+?=!:${}()|\^\[\]\/\\])/... | (typeof val === "string" ? "\"" + val + "\"" : val));
arr.push(prop);
}); | random_line_split | |
lib.rs | }
let ctime = SystemTime::now().duration_since(UNIX_EPOCH)?;
let fs = FileSystem::create(
disk,
password_opt,
ctime.as_secs(),
ctime.subsec_nanos()
).map_err(syscall_error)?;
let (tx, rx) = channel();
let join_handle = thread::spawn(move || {
let res = r... | with_redoxfs(
disk_redoxfs,
password_opt,
callback | random_line_split | |
lib.rs | ! Path::new(&dest_pkg).exists() {
fs::create_dir(&dest_pkg).unwrap();
}
for (packagename, package) in &config.packages {
let pkgar_path = format!("{}/{}/repo/{}/{}.pkgar",
env::current_dir().unwrap().to_string_lossy(),
... | }
let output_dir = output_dir.as_ref();
let output_dir = output_dir.to_owned();
install_packages(&config, output_dir.to_str().unwrap(), cookbook);
for file in config.files {
file.create(&output_dir)?;
}
let mut passwd = String::new();
let mut shadow = String::new();
let ... | {
//let mut context = liner::Context::new();
macro_rules! prompt {
($dst:expr, $def:expr, $($arg:tt)*) => (if config.general.prompt {
Err(io::Error::new(
io::ErrorKind::Other,
"prompt not currently supported"
))
// match unwrap_or_prom... | identifier_body |
lib.rs | ! Path::new(&dest_pkg).exists() {
fs::create_dir(&dest_pkg).unwrap();
}
for (packagename, package) in &config.packages {
let pkgar_path = format!("{}/{}/repo/{}/{}.pkgar",
env::current_dir().unwrap().to_string_lossy(),
... | <P, F, T>(disk_path: P, bootloader_bios: &[u8], bootloader_efi: &[u8], password_opt: Option<&[u8]>, callback: F)
-> Result<T> where
P: AsRef<Path>,
F: FnOnce(&Path) -> Result<T>
{
let target = get_target();
let bootloader_efi_name = match target | with_whole_disk | identifier_name |
verify.rs | /// Stack of active subtrees
stack: Vec<(P::Item, StackSlot)>,
/// Buffer for math strings of subtrees and hypotheses; shared to reduce
/// actual copying when a hypothesis or saved step is recalled
stack_buffer: Vec<u8>,
/// Scratch space used only when checking the final step
temp_buffer: Vec... | <P: ProofBuilder>(state: &mut VerifyState<P>, label: TokenPtr) -> Result<()> {
// it's either an assertion or a hypothesis. $f hyps have pseudo-frames
// which this function can use, $e don't and need to be looked up in the
// local hyp list after the frame lookup fails
let frame = match state.scoper.g... | prepare_step | identifier_name |
verify.rs | /// Stack of active subtrees
stack: Vec<(P::Item, StackSlot)>,
/// Buffer for math strings of subtrees and hypotheses; shared to reduce
/// actual copying when a hypothesis or saved step is recalled
stack_buffer: Vec<u8>,
/// Scratch space used only when checking the final step
temp_buffer: Vec... | state.builder.build(hyp.address(),
Default::default(),
&state.stack_buffer,
tos..ntos)));
}
/// Adds a named $e hypothesis to the prepared array. These are not kept in the
/// frame arra... | tos..ntos, | random_line_split |
verify.rs | $e), and that logical file order is reflected in
// the stack order of the hypotheses, we can do this in one pass
for (ix, hyp) in fref.hypotheses.iter().enumerate() {
let (ref data, ref slot) = state.stack[sbase + ix];
state.builder.push(&mut datavec, data.clone());
match hyp {
... | {
state.cur_frame = frame;
if let Err(diag) = verify_proof(&mut state, stmt) {
diagnostics.insert(stmt.address(), diag);
}
} | conditional_block | |
pat_fitting.py | 1)), mode='nearest')
# get maximum value for each row
mm1 = np.argmax(imx2, axis=1)
val = imx2[np.arange(0, imx2.shape[0]), mm1]
idx1 = np.where(np.abs(val) > thr)[0] # only select indices above scaled threshold
xx1 = np.vstack((horz_vals[mm1[idx1]], y_data[idx1])) # position of selected poin... | model = one_ele_pat_model
yfit = model(x_data, pp)
plt.plot(x_data, yfit, '-g', label=label)
yfit_t0 = model(x_data, np.array([pp[0], pp[1], 0]))
plt.plot(x_data, yfit_t0, '--g') | conditional_block | |
pat_fitting.py | charge_change
scalefac = thr
sc = np.sqrt(robustCost(sc / scalefac, thr / scalefac, 'BZ0')) * scalefac
if weights is not None:
sc = sc * weights
sc = np.linalg.norm(sc, ord=4) / sc.size
if pp[1] < 10:
sc *= 10
if pp[2] > 150:
sc *= 10
... |
def fit_pat_to_peaks(pp, xd, yd, | return detected_peaks, {'weights': weights, 'detected_peaks': detected_peaks}
# %%
| random_line_split |
pat_fitting.py |
# %%
class pat_score():
def __init__(self, even_branches=[True, True, True], branch_reduction=None):
""" Class to calculate scores for PAT fitting """
self.even_branches = even_branches
self.branch_reduction = branch_reduction
def pat_one_ele_score(self, xd, yd, pp, weights=None, t... | r""" Model for two electron pat
This is \phi = \pm \frac{leverarm}{2} (x - x0) +
\frac{1}{2} \sqrt{( leverarm (x - x0) )^2 + 8 t^2 }
Args:
x_data (array): detuning (mV)
pp (array): xoffset (mV), leverarm (ueV/mV) and t (ueV)
"""
if len(pp) == 1:
pp = pp[0]
xoffset ... | identifier_body | |
pat_fitting.py | _change
scalefac = thr
sc = np.sqrt(robustCost(sc / scalefac, thr / scalefac, 'BZ0')) * scalefac
if weights is not None:
sc = sc * weights
sc = np.linalg.norm(sc, ord=4) / sc.size
if pp[1] < 10:
sc *= 10
if pp[2] > 150:
sc *= 10
... | (pp, xd, yd | fit_pat_to_peaks | identifier_name |
gpkg.go | _id FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys(srs_id)
);
`
// TableGeometryColumnsSQL is the normative sql for the geometry columns table that is
// required if the contents table has at least one table with a data_type of features
// http://www.geopackage.org/spec/#gpkg_geometry_columns_sql
TableGe... |
srss := make([]SpatialReferenceSystem, 0, len(KnownSRS))
// Now need to add SRS that we know about
for _, srs := range KnownSRS {
srss = append(srss, srs)
}
return h.UpdateSRS(srss...)
}
// AddGeometryTable will add the given features table to the metadata tables
// This should be called after creating the ta... | {
_, err := h.Exec(sql)
if err != nil {
return err
}
} | conditional_block |
gpkg.go | _id FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys(srs_id)
);
`
// TableGeometryColumnsSQL is the normative sql for the geometry columns table that is
// required if the contents table has at least one table with a data_type of features
// http://www.geopackage.org/spec/#gpkg_geometry_columns_sql
TableGe... |
// Validate that the value already exists in the data base.
err := h.QueryRow(validateSRSSQL, table.SRS).Scan(&count)
if err != nil {
return err
}
if count == 0 {
// let's check known srs's to see if we have it and can add it.
srsdef, ok := KnownSRS[table.SRS]
if !ok {
return fmt.Errorf("unknown srs: %... | count int
) | random_line_split |
gpkg.go | _id FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys(srs_id)
);
`
// TableGeometryColumnsSQL is the normative sql for the geometry columns table that is
// required if the contents table has at least one table with a data_type of features
// http://www.geopackage.org/spec/#gpkg_geometry_columns_sql
TableGe... | (h *Handle) error {
// Set the pragma's that we need to set for this file
_, err := h.Exec(initialSQL)
if err != nil {
return err
}
// Make sure the required metadata tables are available
for _, sql := range []string{TableSpatialRefSysSQL, TableContentsSQL, TableGeometryColumnsSQL} {
_, err := h.Exec(sql)
i... | initHandle | identifier_name |
gpkg.go | _id FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys(srs_id)
);
`
// TableGeometryColumnsSQL is the normative sql for the geometry columns table that is
// required if the contents table has at least one table with a data_type of features
// http://www.geopackage.org/spec/#gpkg_geometry_columns_sql
TableGe... | }
// AddGeometryTable will add the given features table to the metadata tables
// This should be called after creating the table.
func (h *Handle) AddGeometryTable(table TableDescription) error {
const (
validateSRSSQL = `
SELECT Count(*)
FROM gpkg_spatial_ref_sys
WHERE
srs_id=?
`
validateTableFie... | {
// Set the pragma's that we need to set for this file
_, err := h.Exec(initialSQL)
if err != nil {
return err
}
// Make sure the required metadata tables are available
for _, sql := range []string{TableSpatialRefSysSQL, TableContentsSQL, TableGeometryColumnsSQL} {
_, err := h.Exec(sql)
if err != nil {
... | identifier_body |
test_wikipedia.py |
elif browser == 'ie':
self.driver = webdriver.Ie()
elif browser == 'chrome':
self.driver = webdriver.Chrome(executable_path='/selenium_browser_drivers/chromedriver')
elif browser == 'safari':
self.driver = webdriver.Safari()
self.driver.set_window_position(20,20)
self.driver.set_window_size(1200,8... | self.driver = webdriver.Firefox(executable_path='/selenium_browser_drivers/geckodriver') | conditional_block | |
test_wikipedia.py | _language_link('English')
self.verify_main_page_text(
title_text="Wikipedia, the free encyclopedia",
body_text="the free encyclopedia that anyone can edit")
#@unittest.skip('')
def test_homepage_french_link(self):
if browser == "safari":
self.skipTest('Safari does not click on home page language link as... | text into search term, but not submit
def type_search(self, search_term):
self.home.enter_search_term(search_term)
def verify_suggestions_start_with(self, search_term):
prefix = search_term.lower()
for suggestion in self.home.get_search_suggestions():
title = suggestion['title'].lower()
self.assertTrue(t... | x = "^{0}.*".format(search_term)
encoded_search_term = search_term.replace(" ", "_")
url_regex = ".*{0}$".format(encoded_search_term)
article = pages.ArticlePage(self.driver)
s = article.get_page_title()
self.assertTrue(re.search(title_regex, s),
"Page title '{}' does not start with search term '{}'".f... | identifier_body |
test_wikipedia.py | _language_link('English')
self.verify_main_page_text(
title_text="Wikipedia, the free encyclopedia",
body_text="the free encyclopedia that anyone can edit")
#@unittest.skip('')
def test_homepage_french_link(self):
if browser == "safari":
self.skipTest('Safari does not click on home page language link as... | rch_term, expected_values):
self.open_article_by_search(search_term)
article = pages.ArticlePage(self.driver)
infobox = article.get_infobox_contents()
# check expected values are in info box
for (label, expected_value) in expected_values:
found_value = article.get_value_from_infobox_contents(infobox, lab... | st(self, sea | identifier_name |
test_wikipedia.py | ia, l'encyclopédie libre",
body_text="L'encyclopédie libre que chacun peut améliorer")
#@unittest.skip('')
def test_homepage_german_link(self):
if browser == "safari":
self.skipTest('Safari does not click on home page language link as expected')
self.open_home_page()
self.click_language_link('Deutsch')
... |
class TestCurrentEventsPage(WikipediaCommon):
#@unittest.skip('') | random_line_split | |
instruction.rs | 4, // missing * in spec?
OP0_185 => version >= 5,
VAR_228 => version >= 5,
VAR_233 => version == 6,
_ => false,
}
}
pub fn does_branch(opcode: Opcode, version: u8) -> bool {
use self::Opcode::*;
match opcode {
// ... | {
use self::Opcode::*;
match self.opcode {
OP2_25 | OP2_26 | OP1_136 | VAR_224 | VAR_236 | VAR_249 | VAR_250 => true,
OP1_143 => version >= 4,
_ => false,
}
} | identifier_body | |
instruction.rs | 2, VAR_233 = 233,
VAR_234 = 234, VAR_235 = 235, VAR_236 = 236, VAR_237 = 237, VAR_238 = 238,
VAR_239 = 239, VAR_240 = 240, VAR_241 = 241, VAR_242 = 242, VAR_243 = 243,
VAR_244 = 244, VAR_245 = 245, VAR_246 = 246, VAR_247 = 247, VAR_248 = 248,
VAR_249 = 249, VAR_250 = 250, VAR_251 = 2... | (bytes: &[u8]) -> Vec<OperandType> {
bytes
.iter()
.fold(Vec::new(), |mut acc, n| {
acc.push((n & 0b1100_0000) >> 6);
acc.push((n & 0b0011_0000) >> 4);
acc.push((n & 0b0000_1100) >> 2);
acc.push(n & 0b0000_0011);
... | from | identifier_name |
instruction.rs | , VAR_233 = 233,
VAR_234 = 234, VAR_235 = 235, VAR_236 = 236, VAR_237 = 237, VAR_238 = 238,
VAR_239 = 239, VAR_240 = 240, VAR_241 = 241, VAR_242 = 242, VAR_243 = 243,
VAR_244 = 244, VAR_245 = 245, VAR_246 = 246, VAR_247 = 247, VAR_248 = 248,
VAR_249 = 249, VAR_250 = 250, VAR_251 = 25... | pub addr: usize,
pub opcode: Opcode,
pub name: String,
pub operands: Vec<Operand>,
pub store: Option<u8>,
pub branch: Option<Branch>,
pub text: Option<String>,
pub next: usize,
}
impl Instruction {
pub fn does_store(opcode: Opcode, version: u8) -> bool {
use self... |
#[derive(Debug)]
pub struct Instruction {
| random_line_split |
call_addr_alter.py | _new
#得到data表,含有addr,id字段————————————————————————————-----------------————
# print(data)
province = data[data['id']%10000==0]
province['addr_new'] = 'NULL'
#第一部分:原数据中含有省名和市名。
print('找出原数据中的省名和市名,请稍候.............................................................................')
index_item = ... | -----------------------------
#目前中国的二级行政区由市和盟,自治州,地区组成,分别用data_2, data_3, data_4表示。另外还要考虑省辖县。
data_2 = data[(data['addr'].str.contains('市')|(data['addr'].str.contains('盟'))|(data['id']%10000//1000==9))]
for data_2_item in data_2.index:
data_2.ix[data_2_item, 'addr'] = data_2.ix[data_2_item, 'addr'][... | ---- | conditional_block |
call_addr_alter.py | _new
#得到data表,含有addr,id字段————————————————————————————-----------------————
# print(data)
province = data[data['id']%10000==0]
province['addr_new'] = 'NULL'
#第一部分:原数据中含有省名和市名。
print('找出原数据中的省名和市名,请稍候.............................................................................')
index_item = ... | if province_word not in ['北京', '天津', '上海', '重庆', '香港', '澳门']:
# print(province_word, '***********************************************************')
#找到含有该省名的地址,比如 海南
data_province_index = data_old[data_old["call_addr"].str.contains(province_word)].index
data_old.i... | #找出既有省名又有市名的数据------------------------------------------------------------------------------------------------------------
#遍历每一个省名
for index_province in province.index:
province_word = province.ix[index_province, 'addr_new'] | random_line_split |
call_addr_alter.py | = pd.ExcelWriter(path + file_name[:-4] + '.xlsx')
data.to_excel(writer, 'sheet1')
writer.save()
print('本地文件已生成,获取的数据一共%d行\n'%len(data))
print('函数已经结束,共花费时间%d'%(time.time()-start_1))
#读取本地的通话记录文件,并增加新列
def read_local_data():
#不含中文的数据,或者含有国外名称的数据
#既有一级行政区又有二级行政区的数据
#只有二级行政区的数据
#只有三级行政区的数... | addr_alter_test.csv'
print('get_local_data()函数正在执行,请稍候...')
select_string = '''
select call_addr from call_history
group by call_addr
'''
columns = ['call_addr']
data = my.mysql_connection(select_string, columns)
print('正在生成本地文件,请稍候...')
data.to_csv(path + file_name, index=False, sep='\t',... | identifier_body | |
call_addr_alter.py | = 'call_addr_alter_test.csv'
print('get_local_data()函数正在执行,请稍候...')
select_string = '''
select call_addr from call_history
group by call_addr
'''
columns = ['call_addr']
data = my.mysql_connection(select_string, columns)
print('正在生成本地文件,请稍候...')
data.to_csv(path + file_name, index=False, s... | ile_name_test | identifier_name | |
find.py | y1)
:var quad: target bounary quad in input frame
"""
def __init__(self, target, image, inliers, outliers, H, quad):
self.target = target
self.image = image
self.inliers = inliers
self.outliers = outliers
self.H = H
self.quad = quad
def inTargetCoordinat... | (self, image, data=None):
"""Add a new target to the serach list.
:param image: The image containing just the target.
:param data: Additional user data. Defaults to None.
:raises ValueError: If the image is insufficient.
"""
keypoints, descriptors = self._detect... | add_target | identifier_name |
find.py | _spec: The specification string which consists of
"[detector]-[matcher]". Valid detector values include
sift, surf (Default), and orb. Valid matcher values include flann and
bf (brute_force) (Default).
"""
if search_spec is None or not search_spec:
sear... | H = np.array([[0., 0., x0], [0., 0., y0], [0., 0., 1.0]])
return TrackedTarget(target, image, [(0, 0)], [(x0, y0)], H, quad) | random_line_split | |
find.py | for (x0, y0), (x1, y1) in self.inliers]
outliers = [(x0, y0, x1 + w1, y1) for (x0, y0), (x1, y1) in self.outliers]
if colors['outlier'] is not None: # draw x on each point
r = 2 # radius
thickness = 2
for x0, y0, x1, y1 in outliers:
cv2.line(vis, (x0 ... | return _find_using_template(image_to_find, image, **kwargs) | conditional_block | |
find.py | y1)
:var quad: target bounary quad in input frame
"""
def __init__(self, target, image, inliers, outliers, H, quad):
self.target = target
self.image = image
self.inliers = inliers
self.outliers = outliers
self.H = H
self.quad = quad
def inTargetCoordinat... |
def find(self, image, k=None, ratio=None):
"""Find the targets in the provided image.
:param image: The image to search for targets.
:param k: The number of knnMatches to use. None (Default) uses 2.
:param ratio: The distance ration to use. None (Default) uses 0.75.
... | if color is None:
color = [0, 255, 0]
keypoints, _ = self._detector.detectAndCompute(image, None)
image = image.copy()
return cv2.drawKeypoints(image, keypoints, color=color) | identifier_body |
analyzeAnimatedFrames.py |
iid = decoded.get( 'instanceId', '<unknown>')
have = byInstance.get( iid, [] )
have.append( decoded )
byInstance[iid] = have
if 'returncode' in decoded:
rc = decoded['returncode']
if rc:
logger.info( 'return... |
recs.append( decoded )
logger.info( 'topLevelKeys: %s', topLevelKeys )
return recs
def scriptDirPath():
'''returns the absolute path to the directory containing this script'''
return os.path.dirname(os.path.realpath(__file__))
def instanceDpr( inst ):
#logger.info( 'NCSC Inst details ... | topLevelKeys[ key ] += 1 | conditional_block |
analyzeAnimatedFrames.py |
iid = decoded.get( 'instanceId', '<unknown>')
have = byInstance.get( iid, [] )
have.append( decoded )
byInstance[iid] = have
if 'returncode' in decoded:
rc = decoded['returncode']
if rc:
logger.info( 'return... | ():
'''returns the absolute path to the directory containing this script'''
return os.path.dirname(os.path.realpath(__file__))
def instanceDpr( inst ):
#logger.info( 'NCSC Inst details %s', inst )
# cpuarch: string like "aarch64" or "armv7l"
# cpunumcores: int
# cpuspeeds: list of floa... | scriptDirPath | identifier_name |
analyzeAnimatedFrames.py |
iid = decoded.get( 'instanceId', '<unknown>')
have = byInstance.get( iid, [] )
have.append( decoded )
byInstance[iid] = have
if 'returncode' in decoded:
rc = decoded['returncode']
if rc:
logger.info( 'return... | if 'exception' in decoded:
logger.info( 'exception %s for %s', decoded['exception'], iid )
badOnes.add( iid )
if 'timeout' in decoded:
#logger.info( 'timeout %s for %s', decoded['timeout'], iid )
badOnes.add( iid )
return byInst... | badOnes.add( iid ) | random_line_split |
analyzeAnimatedFrames.py |
iid = decoded.get( 'instanceId', '<unknown>')
have = byInstance.get( iid, [] )
have.append( decoded )
byInstance[iid] = have
if 'returncode' in decoded:
rc = decoded['returncode']
if rc:
logger.info( 'return... |
def scriptDirPath():
'''returns the absolute path to the directory containing this script'''
return os.path.dirname(os.path.realpath(__file__))
def instanceDpr( inst ):
#logger.info( 'NCSC Inst details %s', inst )
# cpuarch: string like "aarch64" or "armv7l"
# cpunumcores: int
# cpuspee... | '''read JLog file, return list of decoded objects'''
recs = []
topLevelKeys = collections.Counter() # for debugging
# demux by instance
with open( inFilePath, 'rb' ) as inFile:
for line in inFile:
decoded = json.loads( line )
if isinstance( decoded, dict ):
... | identifier_body |
shell.py | i, date.strftime(node.get_attr(i), "%d.%m.%Y")))
if node.has_attr("Assigned"):
attrs.append(node.get_attr("Assigned"))
flag = ''
if node_is_expired(node):
flag += '[EXPIRED] '
parent = ''
grandparent = ''
fullnodepath = full_node_path('', node)
if node.get_parent() is not N... | (path=None, select='', filter=''):
check_path(path)
doc = freemind.freemind_load(path)
result = nodes_select(doc, select)
result = nodes_filter(result, filter)
return result
def todo_command(path=None, select='', filter='', group='', format='flag title {attrs} icon'):
result = query_nodes(path... | query_nodes | identifier_name |
shell.py | i, date.strftime(node.get_attr(i), "%d.%m.%Y")))
if node.has_attr("Assigned"):
attrs.append(node.get_attr("Assigned"))
flag = ''
if node_is_expired(node):
flag += '[EXPIRED] '
parent = ''
grandparent = ''
fullnodepath = full_node_path('', node)
if node.get_parent() is not N... |
def estimate_command(path=None, format=' - {grandparent}/{parent}/{title}, {@estimate}h'):
check_path(path)
def fn_list(n):
if not hasattr(fn_list, 'result'):
fn_list.result = []
fn_list.total = 0
if n.has_attr('estimate'):
if n.has_attr('@ICON') and BT... | check_path(path)
def fn_list(n):
if not hasattr(fn_list, 'counter'):
fn_list.counter = 1
if n.has_attr('@ICON') and 'help' in n.get_attr('@ICON'):
print("%s. %s\n %s\n" % (fn_list.counter, n.get_title(), n.get_content()))
fn_list.counter += 1
... | identifier_body |
shell.py | i, date.strftime(node.get_attr(i), "%d.%m.%Y")))
if node.has_attr("Assigned"):
attrs.append(node.get_attr("Assigned"))
flag = ''
if node_is_expired(node):
flag += '[EXPIRED] '
parent = ''
grandparent = ''
fullnodepath = full_node_path('', node)
if node.get_parent() is not N... |
icon = ", ".join(format_icons(node.get_attr('@ICON')))
if node.has_content():
content = "--\n%s\n--\n" % node.get_content()
else:
content = ''
# return "%s%s / %s {%s} %s" % (flag, parent, node.get_title(), ", ".join(attrs), node.get_attr('@ICON'))
# print(format.replace('icon', ... | grandparent = node.get_parent().get_parent().get_title() | conditional_block |
shell.py | print(level * ' ' + nodes.get_title())
if nodes.has_content():
content = nodes.get_content()
l = level + 1
print(l * ' ' + '---')
delim = l * ' '
print(delim + ('\n' + delim).join(content.split("\n")))
print(l * ' ' ... | def display_nodes(nodes:list, level=0):
if type(nodes) is freemind.FreeMindNode: | random_line_split | |
script2.js | tableJson = {};
var sel = ".note."+nb; // Initialise
var redirect = redirect+".php";
while ($(sel).length > 0) { // Tant que l'on a une note
posL = $(sel).position().left; // Position Left
posT = $(sel).position().top; // Position Top
tableJson[nb]={"posL":posL,"posT":posT};
nb++; // On i... | .click(function(event) { // deconnexion
majPos("traitement/deco");
});
$('.note').mousedown(function(event) { // Lorsqu'on presse l'élément
$(this).css('background-color', '#bfb172');
$(this).css('z-index', 1000);
});
// Gestion du positionnement auto
$('.note').mouseup(function(event) { // Lorsqu'on relâc... | ({
url: 'traitement/saveOne.php',
type: 'POST',
dataType: 'text',
data: {tableJson: tableJson,
indice: indice}
})
.done(function() {
console.log("done");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
$("#deco") | identifier_body |
script2.js | vérifie la présence d'un élément
var ok = true;
for (var i = 0; i < Object.keys(tableJson).length; i++) {
// Si un élément est déjà la
if(tableJson[i].posL == xE && tableJson[i].posT == yE){
ok = false;
break;
}
}
if(ok){ // Si ok on positionne l'élément et on met à jour ces coordonné... | au
$.ea | identifier_name | |
script2.js | L = iniLeft;
tableJson[i].posT = iniTop;
$(this).css({
left: xE,
top: yE
});
savePos($(this));
$('.note.'+i).css({
left: iniLeft,
top: iniTop
});
savePos2(i);
}
$(this).css('z-index', '');
// Enregistrement du positionnement
if(boolSave){
... | var numNote = $(this).parent().parent()[0].className;
numNote = numNote.replace("grbt ", ""); // Le numéro de la note
| random_line_split | |
peer.rs | of time.
struct Task {
// Receives `Set` values that need to be sent to the peer.
rx: Receiver<Set<String>>,
// Route information
route: config::Route,
// Tokio reactor handle. Used to establish tcp connections
reactor_handle: Handle,
// Handle to the timer. The timer is used to set a re... | reactor_handle: handle.clone(),
timer: timer.clone(),
// Initialize in the "waiting to connect" state but with a 0 length
// sleep. This will effectively initiate the connect immediately
state: State::Waiting(timer.sleep(Duration::from_millis(0))),
... | rx: rx,
route: route, | random_line_split |
peer.rs | time.
struct Task {
// Receives `Set` values that need to be sent to the peer.
rx: Receiver<Set<String>>,
// Route information
route: config::Route,
// Tokio reactor handle. Used to establish tcp connections
reactor_handle: Handle,
// Handle to the timer. The timer is used to set a re-co... | (&mut self) -> Poll<(), ()> {
trace!(" --> process peer connection");
let service = match self.state {
State::Connected(ref mut service) => service,
_ => unreachable!(),
};
// The connection is currently in the connected state. If there are any
// pen... | process_connected | identifier_name |
peer.rs | of time.
struct Task {
// Receives `Set` values that need to be sent to the peer.
rx: Receiver<Set<String>>,
// Route information
route: config::Route,
// Tokio reactor handle. Used to establish tcp connections
reactor_handle: Handle,
// Handle to the timer. The timer is used to set a re... | let set = self.pending_message.message_to_send().unwrap();
let msg = Request::Join(set);
trace!(" --> sending Join message");
// Dispatch the replication request and get back a future repesenting
// the response from the peer node.
let resp = service.call(msg);
... | {
trace!(" --> process peer connection");
let service = match self.state {
State::Connected(ref mut service) => service,
_ => unreachable!(),
};
// The connection is currently in the connected state. If there are any
// pending replication requests, th... | identifier_body |
test4.py | joy.rz,
joy.hat_x,
joy.hat_y,
buttons))
def get_joy_position(x, y):
"""Given position of joystick axes, return (x, y, angle_in_degrees).
If movement is not outside of deadzone, return (None, None, None)"""
... |
def on_draw(self):
""" Draw this view """
arcade.start_render()
arcade.draw_text("Instructions Screen", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2,
arcade.color.WHITE, font_size=50, anchor_x="center")
arcade.draw_text("Click to advance", SCREEN_WIDTH / 2, SCREEN_H... | """ This is run once when we switch to this view """
arcade.set_background_color(arcade.csscolor.DARK_SLATE_BLUE)
arcade.set_viewport(0, SCREEN_WIDTH - 1, 0, SCREEN_HEIGHT - 1) | identifier_body |
test4.py | joy.rz,
joy.hat_x,
joy.hat_y,
buttons))
def get_joy_position(x, y):
"""Given position of joystick axes, return (x, y, angle_in_degrees).
If movement is not outside of deadzone, return (None, None, None)"""
... | (self, _joystick, button):
""" Handle button-down event for the joystick """
print("Button {} down".format(button))
if button == JUMPBTN:
iced_ground_contact_list = arcade.check_for_collision_with_list(self.player_list[0], self.lowfric_list)
if iced_ground_contact_list... | on_joybutton_press | identifier_name |
test4.py | joy.rz,
joy.hat_x,
joy.hat_y,
buttons))
def get_joy_position(x, y):
"""Given position of joystick axes, return (x, y, angle_in_degrees).
If movement is not outside of deadzone, return (None, None, None)"""
... |
elif self.player.shoot_right_pressed:
self.spawn_bullet(0)
elif self.player.shoot_up_pressed:
self.spawn_bullet(90)
elif self.player.shoot_left_pressed:
self.spawn_bullet(180)
elif self.player.shoot_down_pressed:
... | self.spawn_bullet(270+45) | conditional_block |
test4.py | print("z {}".format(joy.z))
print("rx {}".format(joy.rx))
print("ry {}".format(joy.ry))
print("rz {}".format(joy.rz))
print("hat_x {}".format(joy.hat_x))
print("hat_y {}".format(joy.hat_y))
print("buttons {}".format(joy.buttons))
print("========== Extra joy")
... | print("y {}".format(joy.y)) | random_line_split | |
ip.py | only want one but we might have multiple v4
# subnets on the external network. However, sometimes the RUG
# can't figure out what that value is, because it thinks we
# don't have any external IP addresses, yet. In that case, it
# doesn't give us a default.
if config.default_v4_g... | _parse_head | identifier_name | |
ip.py | # because we only want one but we might have multiple v4
# subnets on the external network. However, sometimes the RUG
# can't figure out what that value is, because it thinks we
# don't have any external IP addresses, yet. In that case, it
# doesn't give us a default.
if... | """
Parse details for an interface, given its data from `ip addr show <ifname>`
:rtype: akanda.router.models.Interface
"""
retval = dict(addresses=[])
for line in data.split('\n'):
if line.startswith(' '):
line = line.strip()
if line.startswith('inet'):
... | identifier_body | |
ip.py | physical interface name into the generic network interface
name.
:param ifname: the physical name to translate, e.g., `eth0`
:type ifname: str
:rtype: str
"""
self.ensure_mapping()
return self.host_mapping.get(real_name)
def update_interfaces(self, interface... | except:
# assume the route is missing and use defaults
pass
else:
for l in cmd_out.splitlines(): | random_line_split | |
ip.py | : str
"""
self.ensure_mapping()
return self.host_mapping.get(real_name)
def update_interfaces(self, interfaces):
"""
Wrapper function that accepts a list of interfaces and iterates over
them, calling update_interface(<interface>) in order to update
their conf... | l = l.strip()
if l.startswith('default'):
match = re.search('via (?P<gateway>[^ ]+)', l)
if match:
return match.group('gateway') | conditional_block | |
lib.rs | cases where elements must be able to drop themselves while linked
//! into a list.
//!
//! The [`List`] type is **not** a lock-free data structure, and can only be
//! modified through `&mut` references.
//!
//! - **[`MpscQueue`]: a multi-producer, single-consumer (MPSC) lock-free
//! last-in, first-out (LIFO)... | ///
/// Suppose we have an entry type like this:
/// ```rust
/// use cordyceps::list;
///
/// struct Entry {
/// links: list::Links<Self>,
/// data: usize,
/// }
/// ```
///
/// The naive implementation of [`links`](Linked::links) for this `Entry` type
/// might look like this:
///
/// ```
/// use cordyceps::Li... | random_line_split | |
index.js | Updated(config) {
let resetConnection = false
if (this.config.host != config.host) {
resetConnection = true
}
this.config = config
this.updateActions()
this.updateFeedbacks()
this.updatePresets()
this.updateVariables()
if (resetConnection === true || this.socket === undefined) {
this.initTCP... | else if (this.receiveBuffer.match(/[P|p]assword:/)) {
this.receiveBuffer = ''
this.socket.send(this.config.password + '\r\n')
} else if (this.receiveBuffer.match(/>/)) {
this.loggedIn = true
if (this.deviceName == '') {
this.receiveBuffer = ''
this.socket.send('version\r\n')
... | {
this.receiveBuffer = ''
this.socket.send(this.config.username + '\r\n')
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.