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 |
|---|---|---|---|---|
bot.js | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// bot.js is your main bot dialog entry point for handling activity types
// Import required Bot Builder
const { ActionTypes, ActivityTypes, CardFactory } = require('botbuilder');
const { LuisRecognizer } = require('botbui... | this.helpMessage = `You can type "send <recipient_email>" to send an email, "recent" to view recent unread mail,` +
` "me" to see information about your, or "help" to view the commands` +
` again. For others LUIS displays intent with score.`;
// Create a DialogSet that contains ... | // Instructions for the user with information about commands that this bot may handle. | random_line_split |
bot.js | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// bot.js is your main bot dialog entry point for handling activity types
// Import required Bot Builder
const { ActionTypes, ActivityTypes, CardFactory } = require('botbuilder');
const { LuisRecognizer } = require('botbui... | ;
async promptStep(step) {
const activity = step.context.activity;
if (activity.type === ActivityTypes.Message && !(/\d{6}/).test(activity.text)) {
await this.commandState.set(step.context, activity.text);
await this.conversationState.saveChanges(step.context);
}
... | {
//console.log(dc);
switch (dc.context.activity.text.toLowerCase()) {
case 'signout':
case 'logout':
case 'signoff':
case 'logoff':
// The bot adapter encapsulates the authentication processes and sends
// activities to from the Bot Connector Serv... | identifier_body |
parser_manager.py | from pkg_resources import require
require("numpy>=1.11.1")
require("scipy>=0.19.1")
import argparse
import logging
import re
import cv2
from os.path import split, exists, isdir, isfile, join, abspath, getmtime, dirname, expanduser
from os import listdir, makedirs, chmod, close
import sys
from CrystalMatch.dls_focuss... |
def get_formulatrix_image_path(self):
path = self.get_args().Formulatrix_image.name
self._check_is_file(path)
return path
def get_to_json(self):
return self.get_args().to_json
def get_job_id(self):
return self.get_args().job
# returns an error if the focused ... | return self.images_to_stack | identifier_body |
parser_manager.py | from pkg_resources import require
require("numpy>=1.11.1")
require("scipy>=0.19.1")
import argparse
import logging
import re
import cv2
from os.path import split, exists, isdir, isfile, join, abspath, getmtime, dirname, expanduser
from os import listdir, makedirs, chmod, close
import sys
from CrystalMatch.dls_focuss... | (self):
return self.get_args().to_json
def get_job_id(self):
return self.get_args().job
# returns an error if the focused image is not saved
# may want to change this for saving done later
def get_focused_image_path(self):
focusing_path = abspath(self.get_args().beamline_stack_... | get_to_json | identifier_name |
parser_manager.py | from pkg_resources import require
require("numpy>=1.11.1")
require("scipy>=0.19.1")
import argparse
import logging
import re
import cv2
from os.path import split, exists, isdir, isfile, join, abspath, getmtime, dirname, expanduser
from os import listdir, makedirs, chmod, close
import sys
from CrystalMatch.dls_focuss... | type=file,
help='Image file from the Formulatrix - selected_point should correspond to co-ordinates on '
'this image.')
else:
parser.add_argument('Formulatrix_image',
metavar="For... | metavar="Formulatrix_image_path", | random_line_split |
parser_manager.py | from pkg_resources import require
require("numpy>=1.11.1")
require("scipy>=0.19.1")
import argparse
import logging
import re
import cv2
from os.path import split, exists, isdir, isfile, join, abspath, getmtime, dirname, expanduser
from os import listdir, makedirs, chmod, close
import sys
from CrystalMatch.dls_focuss... |
return selected_points
def get_focused_image(self):
focusing_path = abspath(self.get_args().beamline_stack_path)
if "." not in focusing_path:
files = self._sort_files_according_to_names(focusing_path)
# Run focusstack
stacker = FocusStack(files, self.get... | point_string = point_string.strip('()')
match_results = point_expected_format.match(point_string)
# Check the regex matches the entire string
# DEV NOTE: can use re.full_match in Python v3
if match_results is not None and match_results.span()[1] == len(poi... | conditional_block |
certificate_fetcher.go | package rancher
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/rancher/go-rancher-metadata/metadata"
"github.com/rancher/go-rancher/v2"
"github.com/rancher/lb-controller/config"
)
const (
DefaultCertName = "fullchain.pem"
DefaultK... |
func (fetcher *RCertificateFetcher) setInitPollDone() {
fetcher.initPollMu.Lock()
fetcher.initPollDone = true
fetcher.initPollMu.Unlock()
}
func (fetcher *RCertificateFetcher) FetchCertificates(lbMeta *LBMetadata, isDefaultCert bool) ([]*config.Certificate, error) {
// fetch certificates either from mounted cert... | {
isDone := false
fetcher.initPollMu.RLock()
isDone = fetcher.initPollDone
fetcher.initPollMu.RUnlock()
return isDone
} | identifier_body |
certificate_fetcher.go | package rancher
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/rancher/go-rancher-metadata/metadata"
"github.com/rancher/go-rancher/v2"
"github.com/rancher/lb-controller/config"
)
const (
DefaultCertName = "fullchain.pem"
DefaultK... | } else {
logrus.Infof("LookForCertUpdates: Force Update triggered, updating the cache from cert dir %v", fetcher.CertDir)
}
//there is some change, refresh certs
fetcher.mu.Lock()
fetcher.CertsCache = make(map[string]*config.Certificate)
for path, newCert := range fetcher.temp... | } else {
//compare with existing cache
if forceUpdate || !reflect.DeepEqual(fetcher.CertsCache, fetcher.tempCertsMap) {
if !forceUpdate {
logrus.Infof("LookForCertUpdates: Found an update in cert dir %v, updating the cache", fetcher.CertDir) | random_line_split |
certificate_fetcher.go | package rancher
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/rancher/go-rancher-metadata/metadata"
"github.com/rancher/go-rancher/v2"
"github.com/rancher/lb-controller/config"
)
const (
DefaultCertName = "fullchain.pem"
DefaultK... | (certID string) (*config.Certificate, error) {
if certID == "" {
return nil, nil
}
opts := client.NewListOpts()
opts.Filters["id"] = certID
opts.Filters["removed_null"] = "1"
cert, err := fetcher.Client.Certificate.ById(certID)
if err != nil {
return nil, fmt.Errorf("Coudln't get certificate by id [%s]. Err... | FetchRancherCertificate | identifier_name |
certificate_fetcher.go | package rancher
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/rancher/go-rancher-metadata/metadata"
"github.com/rancher/go-rancher/v2"
"github.com/rancher/lb-controller/config"
)
const (
DefaultCertName = "fullchain.pem"
DefaultK... |
}
//read target file
return fetcher.readFile(targetPath)
}
func (fetcher *RCertificateFetcher) readFile(filePath string) (*[]byte, error) {
contentBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("Error reading file %s, error: %v", filePath, err)
}
return &contentBytes, nil
}
| {
return nil, fmt.Errorf("File %s pointed by symlink %s does not exist, error: %v", targetPath, absFilePath, err)
} | conditional_block |
ProteinRNN.py | # Here we import the modules that we will use for the task
import numpy as np
import math
import statistics
import tensorflow as tf
import string
import random
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
from google.colab import drive
from tensorflow.python.framework... |
### The function for gathering tests
def read_seqV2(sequence):
f = open(sequence, 'r')
test = []
testlabel = []
# Reading file and extracting paths and labels
with open(sequence, 'r') as File:
infoFile = File.readlines() # Reading all the lines from File
count = 0
for ... | testlabel = []
test = []
temp = line.split()
charList = list(temp)
seq = []
for i in range(50): # convert each letter into an int, randomly flip a char or more
# these 3 if conditions randomly flip a character letter to find dependeny, can comment out either or for experimentation
if i == 15:
... | identifier_body |
ProteinRNN.py | # Here we import the modules that we will use for the task
import numpy as np
import math
import statistics
import tensorflow as tf
import string
import random
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
from google.colab import drive
from tensorflow.python.framework... | (line):
testlabel = []
test = []
temp = line.split()
charList = list(temp)
seq = []
for i in range(50): # convert each letter into an int, randomly flip a char or more
# these 3 if conditions randomly flip a character letter to find dependeny, can comment out either or for experimentation
if ... | FlipChars | identifier_name |
ProteinRNN.py | # Here we import the modules that we will use for the task
import numpy as np
import math
import statistics
import tensorflow as tf
import string
import random
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
from google.colab import drive
from tensorflow.python.framework... |
print(str(matches) + " matches")
print("________________________\n")
print("\n")
# end of for loop and going on to the next rial
i += 1
k = 1
trials += 1
print("\n End of trials.")
| continue | conditional_block |
ProteinRNN.py | # Here we import the modules that we will use for the task
import numpy as np
import math
import statistics
import tensorflow as tf
import string
import random
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
from google.colab import drive
from tensorflow.python.framework... | # line is the temp[0] pass as an argument here
def FlipChars(line):
testlabel = []
test = []
temp = line.split()
charList = list(temp)
seq = []
for i in range(50): # convert each letter into an int, randomly flip a char or more
# these 3 if conditions randomly flip a character letter to find depe... |
# convert made up sequence to a tensor | random_line_split |
accounts.go | // Copyright © 2018-2019 Apollo Technologies Pte. Ltd. All Rights Reserved.
package accounts
import (
"context"
"fmt"
"math/big"
"net/http"
"strconv"
"github.com/HiNounou029/nounouchain/api/utils"
"github.com/HiNounou029/nounouchain/polo"
"github.com/HiNounou029/nounouchain/common/xenv"
"github.com/HiNounou... | Beneficiary: header.Beneficiary(),
Signer: signer,
Number: header.Number(),
Time: header.Timestamp(),
GasLimit: header.GasLimit(),
TotalScore: header.TotalScore()})
results = make(BatchCallResults, 0)
vmout := make(chan *runtime.Output, 1)
for i, clause := range clauses {
exe... | &xenv.BlockContext{ | random_line_split |
accounts.go | // Copyright © 2018-2019 Apollo Technologies Pte. Ltd. All Rights Reserved.
package accounts
import (
"context"
"fmt"
"math/big"
"net/http"
"strconv"
"github.com/HiNounou029/nounouchain/api/utils"
"github.com/HiNounou029/nounouchain/polo"
"github.com/HiNounou029/nounouchain/common/xenv"
"github.com/HiNounou... | c (a *Accounts) Mount(root *mux.Router, pathPrefix string) {
sub := root.PathPrefix(pathPrefix).Subrouter()
sub.Path("/*").Methods("POST").HandlerFunc(utils.WrapHandlerFunc(a.handleCallBatchCode))
sub.Path("/{address}").Methods(http.MethodGet).HandlerFunc(utils.WrapHandlerFunc(a.handleGetAccount))
sub.Path("/{addr... | revision == "" || revision == "best" {
return a.chain.BestBlock().Header(), nil
}
if len(revision) == 66 || len(revision) == 64 {
blockID, err := polo.ParseBytes32(revision)
if err != nil {
return nil, utils.BadRequest(errors.WithMessage(err, "revision"))
}
h, err := a.chain.GetBlockHeader(blockID)
if... | identifier_body |
accounts.go | // Copyright © 2018-2019 Apollo Technologies Pte. Ltd. All Rights Reserved.
package accounts
import (
"context"
"fmt"
"math/big"
"net/http"
"strconv"
"github.com/HiNounou029/nounouchain/api/utils"
"github.com/HiNounou029/nounouchain/polo"
"github.com/HiNounou029/nounouchain/common/xenv"
"github.com/HiNounou... | esults = append(results, convertCallResultWithInputGas(out, gas))
if out.VMErr != nil {
return results, nil
}
gas = out.LeftOverGas
}
}
return results, nil
}
func (a *Accounts) handleBatchCallData(batchCallData *BatchCallData) (gas uint64, gasPrice *big.Int, caller *polo.Address, clauses []*tx.Clause,... | return nil, err
}
r | conditional_block |
accounts.go | // Copyright © 2018-2019 Apollo Technologies Pte. Ltd. All Rights Reserved.
package accounts
import (
"context"
"fmt"
"math/big"
"net/http"
"strconv"
"github.com/HiNounou029/nounouchain/api/utils"
"github.com/HiNounou029/nounouchain/polo"
"github.com/HiNounou029/nounouchain/common/xenv"
"github.com/HiNounou... | w http.ResponseWriter, req *http.Request) error {
addr, err := polo.ParseAddress(mux.Vars(req)["address"])
if err != nil {
return utils.BadRequest(errors.WithMessage(err, "address"))
}
h, err := a.handleRevision(req.URL.Query().Get("revision"))
if err != nil {
return err
}
tokenAddress := req.URL.Query().Ge... | andleGetAccount( | identifier_name |
main.rs | use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc};
use structopt::StructOpt;
use url::Url;
use tracing::{Level, info};
use bevy::{
input::{
keyboard::ElementState as PressState,
mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel},
},
prelude::*,
render::mesh::{Mesh, VertexAt... |
#[tokio::main]
async fn run(options: Opt) -> Result<(), Box<dyn std::error::Error>> {
let path = std::env::current_dir().unwrap();
println!("The current directory is {}", path.display());
tracing::subscriber::set_global_default(
tracing_subscriber::FmtSubscriber::builder()
.with_max_l... | {
let opt = Opt::from_args();
run(opt)
} | identifier_body |
main.rs | use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc};
use structopt::StructOpt;
use url::Url;
use tracing::{Level, info};
use bevy::{
input::{
keyboard::ElementState as PressState,
mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel},
},
prelude::*,
render::mesh::{Mesh, VertexAt... | (
mut state: ResMut<RequestTileOnConnectedState>,
mut sender: ResMut<Events<SendEvent>>,
receiver: ResMut<Events<ReceiveEvent>>
) {
for evt in state.event_reader.iter(&receiver) {
if let ReceiveEvent::Connected(connection, _) = evt {
info!("Requesting tile because connected to server... | request_tile_on_connected | identifier_name |
main.rs | use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc};
use structopt::StructOpt;
use url::Url;
use tracing::{Level, info};
use bevy::{
input::{
keyboard::ElementState as PressState,
mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel},
},
prelude::*,
render::mesh::{Mesh, VertexAt... | mcam.right = None;
mcam.forward = None;
}
}
}
/// Pushes camera actions based upon scroll wheel movement.
fn act_on_scroll_wheel(
mouse_wheel: Res<Events<MouseWheel>>,
mut acts: ResMut<Events<CameraBPAction>>,
) {
for mw in mouse_wheel.get_reader().iter(&mouse_wheel) {
... |
if !in_rect && ax.is_finite() && ay.is_finite() {
mcam.right = Some(ax);
mcam.forward = Some(ay);
} else { | random_line_split |
main.rs | use std::{fs, net::ToSocketAddrs, path::PathBuf, sync::Arc};
use structopt::StructOpt;
use url::Url;
use tracing::{Level, info};
use bevy::{
input::{
keyboard::ElementState as PressState,
mouse::{MouseButtonInput, MouseScrollUnit, MouseWheel},
},
prelude::*,
render::mesh::{Mesh, VertexAt... |
if let Some(w) = mcam.forward {
acts.send(CameraBPAction::MoveForward(Some(w)))
}
}
fn play_every_sound_on_mb1(
mev: Res<Events<MouseButtonInput>>,
fxs: Res<Assets<AudioSource>>,
output: Res<AudioOutput>,
) {
for mev in mev.get_reader().iter(&mev) {
if mev.button == MouseButto... | {
acts.send(CameraBPAction::MoveRight(Some(w)))
} | conditional_block |
rzline.py | # -*- coding: utf-8 -*-
import os
import json
import time
import copy
import scrapy
import pymysql
from scrapy.exceptions import CloseSpider
from Bill.util import misc
from scrapy.conf import settings
from Bill.items import RzlineItem
from Bill.util.send_email import EmailSender
Today = time.strftime("%Y%m%d")
Today... | # formdata['page'] += 1
# base_url = 'http://www.rzline.com/web/mobuser/market/quoteShow'
# url = base_url + '&page=' + str(formdata['page'])
# yield scrapy.Request(
# url=url,
# callback=self.parse_id,
... | # formdata = response.meta['data'] | random_line_split |
rzline.py | # -*- coding: utf-8 -*-
import os
import json
import time
import copy
import scrapy
import pymysql
from scrapy.exceptions import CloseSpider
from Bill.util import misc
from scrapy.conf import settings
from Bill.items import RzlineItem
from Bill.util.send_email import EmailSender
Today = time.strftime("%Y%m%d")
Today... | f data_list:
for i in data_list:
user_id = i['orgUserId']
company = i['orgSimpleName']
price_list = i['quotePriceDetailList'] if i['quotePriceDetailList'] else []
if len(price_list):
formdata1 = copy... | i | identifier_name |
rzline.py | # -*- coding: utf-8 -*-
import os
import json
import time
import copy
import scrapy
import pymysql
from scrapy.exceptions import CloseSpider
from Bill.util import misc
from scrapy.conf import settings
from Bill.items import RzlineItem
from Bill.util.send_email import EmailSender
Today = time.strftime("%Y%m%d")
Today... |
flag = 1
city = response.meta['city']
data = response.body.decode()
json_data = json.loads(data)
id_url = 'http://www.rzline.com/web/mobuser/market/quoteDetail'
print('当前页数:{}'.format(response.meta['data']['page']))
print('data=', response.meta['data'])
t... | city},
)
def parse_id(self, response): | conditional_block |
rzline.py | # -*- coding: utf-8 -*-
import os
import json
import time
import copy
import scrapy
import pymysql
from scrapy.exceptions import CloseSpider
from Bill.util import misc
from scrapy.conf import settings
from Bill.items import RzlineItem
from Bill.util.send_email import EmailSender
Today = time.strftime("%Y%m%d")
Today... | ta']
if data_list:
for i in data_list:
user_id = i['orgUserId']
company = i['orgSimpleName']
price_list = i['quotePriceDetailList'] if i['quotePriceDetailList'] else []
if len(price_list):
... | pass
url = base_url + '&page=' + str(formdata['page'])
yield scrapy.Request(
url=url,
dont_filter=True,
callback=self.parse_id,
errback=self.hand_error,
meta={'data': formdata, 'heade... | identifier_body |
mod.rs | mod searcher;
use self::searcher::{SearchEngine, SearchWorker};
use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages};
use crate::stdio_server::handler::CachedPreviewImpl;
use crate::stdio_server::job;
use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context};
use cr... | _typed(&mut self, ctx: &mut Context) -> Result<()> {
let query = ctx.vim.input_get().await?;
let query_info = parse_query_info(&query);
// Try to refilter the cached results.
if self.cached_results.query_info.is_superset(&query_info) {
let refiltered = self
.... | rent_lines = self
.current_usages
.as_ref()
.unwrap_or(&self.cached_results.usages);
if current_lines.is_empty() {
return Ok(());
}
let input = ctx.vim.input_get().await?;
let lnum = ctx.vim.display_getcurlnum().await?;
// lnum i... | identifier_body |
mod.rs | mod searcher;
use self::searcher::{SearchEngine, SearchWorker};
use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages};
use crate::stdio_server::handler::CachedPreviewImpl;
use crate::stdio_server::job;
use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context};
use cr... | // otherwise restore the fuzzy query as the keyword we are going to search.
let (keyword, query_type, usage_matcher) = if fuzzy_terms.is_empty() {
if exact_terms.is_empty() {
(query.into(), QueryType::StartWith, UsageMatcher::default())
} else {
(
exact_te... | random_line_split | |
mod.rs | mod searcher;
use self::searcher::{SearchEngine, SearchWorker};
use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages};
use crate::stdio_server::handler::CachedPreviewImpl;
use crate::stdio_server::job;
use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context};
use cr... | else {
(
exact_terms[0].text.clone(),
QueryType::Exact,
UsageMatcher::new(exact_terms, inverse_terms),
)
}
} else {
(
fuzzy_terms.iter().map(|term| &term.text).join(" "),
QueryType::StartWith,
... | {
(query.into(), QueryType::StartWith, UsageMatcher::default())
} | conditional_block |
mod.rs | mod searcher;
use self::searcher::{SearchEngine, SearchWorker};
use crate::find_usages::{CtagsSearcher, GtagsSearcher, QueryType, Usage, UsageMatcher, Usages};
use crate::stdio_server::handler::CachedPreviewImpl;
use crate::stdio_server::job;
use crate::stdio_server::provider::{BaseArgs, ClapProvider, Context};
use cr... | &mut Context) -> Result<()> {
let current_lines = self
.current_usages
.as_ref()
.unwrap_or(&self.cached_results.usages);
if current_lines.is_empty() {
return Ok(());
}
let input = ctx.vim.input_get().await?;
let lnum = ctx.vim.di... | , ctx: | identifier_name |
service.go | // Copyright 2020 PingCAP, 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 i... |
// @Summary Preview a log search task group
// @Param id path string true "task group id"
// @Security JwtAuth
// @Success 200 {array} PreviewModel
// @Failure 401 {object} utils.APIError "Unauthorized failure"
// @Failure 500 {object} utils.APIError
// @Router /logs/taskgroups/{id}/preview [get]
func (s *Service) Ge... | {
taskGroupID := c.Param("id")
var taskGroup TaskGroupModel
var tasks []*TaskModel
err := s.db.First(&taskGroup, "id = ?", taskGroupID).Error
if err != nil {
_ = c.Error(err)
return
}
err = s.db.Where("task_group_id = ?", taskGroupID).Find(&tasks).Error
if err != nil {
_ = c.Error(err)
return
}
resp :... | identifier_body |
service.go | // Copyright 2020 PingCAP, 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 i... |
if len(req.Targets) == 0 {
utils.MakeInvalidRequestErrorWithMessage(c, "Expect at least 1 target")
return
}
stats := model.NewRequestTargetStatisticsFromArray(&req.Targets)
taskGroup := TaskGroupModel{
SearchRequest: &req.Request,
State: TaskGroupStateRunning,
TargetStats: stats,
}
if err := ... | {
utils.MakeInvalidRequestErrorFromError(c, err)
return
} | conditional_block |
service.go | // Copyright 2020 PingCAP, 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 i... | (c *gin.Context) {
taskGroupID := c.Param("id")
var lines []PreviewModel
err := s.db.
Where("task_group_id = ?", taskGroupID).
Order("time").
Limit(TaskMaxPreviewLines).
Find(&lines).Error
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, lines)
}
// @Summary Retry failed tasks in a log... | GetTaskGroupPreview | identifier_name |
service.go | // Copyright 2020 PingCAP, 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 i... | taskGroup := TaskGroupModel{}
err := s.db.Where("id = ? AND state != ?", taskGroupID, TaskGroupStateRunning).First(&taskGroup).Error
if err != nil {
_ = c.Error(err)
return
}
taskGroup.Delete(s.db)
c.JSON(http.StatusOK, utils.APIEmptyResponse{})
}
// @Summary Generate a download token for downloading logs
//... | taskGroupID := c.Param("id") | random_line_split |
create.go | /*
Copyright 2019 The Kubernetes 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 agreed to in writing, ... | desiredNodes = append(desiredNodes, desiredNode)
}
for n := 0; n < flags.workers; n++ {
role := constants.WorkerNodeRoleValue
desiredNode := nodeSpec{
Name: fmt.Sprintf("%s-%s-%d", clusterName, role, n+1),
Role: role,
}
desiredNodes = append(desiredNodes, desiredNode)
}
// add an external load bala... | Name: fmt.Sprintf("%s-%s-%d", clusterName, role, n+1),
Role: role,
} | random_line_split |
create.go | /*
Copyright 2019 The Kubernetes 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 agreed to in writing, ... | := make(chan error, len(funcs))
for _, f := range funcs {
f := f // capture f
go func() {
errCh <- f()
}()
}
for i := 0; i < len(funcs); i++ {
if err := <-errCh; err != nil {
return err
}
}
return nil
}
| identifier_body | |
create.go | /*
Copyright 2019 The Kubernetes 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 agreed to in writing, ... | (volumes []string) CreateOption {
return func(c *CreateOptions) {
c.volumes = volumes
}
}
// CreateCluster creates a new kinder cluster
func CreateCluster(clusterName string, options ...CreateOption) error {
flags := &CreateOptions{}
for _, o := range options {
o(flags)
}
// Check if the cluster name alread... | Volumes | identifier_name |
create.go | /*
Copyright 2019 The Kubernetes 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 agreed to in writing, ... | mt.Printf("Preparing nodes %s\n", strings.Repeat("📦", numberOfNodes))
// detect CRI runtime installed into images before actually creating nodes
runtime, err := status.InspectCRIinImage(flags.image)
if err != nil {
log.Errorf("Error detecting CRI for images %s! %v", flags.image, err)
return err
}
log.Infof("... | numberOfNodes++
}
f | conditional_block |
command_server.rs | //! Internal server that accepts raw commands, queues them up, and transmits
//! them to the Tick Processor asynchronously. Commands are re-transmitted
//! if a response isn't received in a timout period.
//!
//! Responses from the Tick Processor are sent back over the commands channel
//! and are sent to worker proce... | (
&mut self, command: Command, commands_channel: String
) -> Receiver<Result<Response, String>> {
let temp_lock_res = self.conn_queue.lock().unwrap().is_empty();
// Force the guard locking conn_queue to go out of scope
// this prevents the lock from being held through the entire if/e... | execute | identifier_name |
command_server.rs | //! Internal server that accepts raw commands, queues them up, and transmits
//! them to the Tick Processor asynchronously. Commands are re-transmitted
//! if a response isn't received in a timout period.
//!
//! Responses from the Tick Processor are sent back over the commands channel
//! and are sent to worker proce... | for task in cmd_rx.wait() {
let res = dispatch_worker(
task.unwrap(), al, &mut client, &mut sleeper_tx, command_queue.clone()
);
// exit if we're in the process of collapse
if res.is_none() {
break;
}
}
}
impl CommandServer {
pub fn new(insta... | random_line_split | |
command_server.rs | //! Internal server that accepts raw commands, queues them up, and transmits
//! them to the Tick Processor asynchronously. Commands are re-transmitted
//! if a response isn't received in a timout period.
//!
//! Responses from the Tick Processor are sent back over the commands channel
//! and are sent to worker proce... |
}
Ok(sleeper_tx)
}).wait().ok().unwrap(); // block until a response is received or the command times out
}
/// Manually loop over the converted Stream of commands
fn dispatch_worker(
work: WorkerTask, al: &Mutex<AlertList>, mut client: &mut redis::Client,
mut sleeper_tx: &mut UnboundedSend... | { // timed out
{
al.lock().expect("Couldn't lock al in Err(_)")
.deregister(&wr_cmd.uuid);
}
attempts += 1;
if attempts >= CONF.cs_max_retries {
// Let the main thread know it's safe to use th... | conditional_block |
Workload.js | /**
* Created by songchao on 16/6/25.
*/
/**
* 入口方法,调用显示工作量
* @param employeeID
*/
function showWorkload(packageID) {
if (packageID != undefined) {
Workload.id = packageID;
Workload.whichRequest = 1;
}
$(canvas).attr({width: $(canvas).width() + "px", height: $(canvas).height() + "px"})... | identifier_name | ||
Workload.js | /**
* Created by songchao on 16/6/25.
*/
/**
* 入口方法,调用显示工作量
* @param employeeID
*/
function showWorkload(packageID) {
if (packageID != undefined) {
Workload.id = packageID;
Workload.whichRequest = 1;
}
$(canvas).attr({width: $(canvas).width() + "px", height: $(canvas).height() + "px"})... | }
if (day < 10) {
day = "0" + day;
}
var fromTime = "";
var days = 0;
switch (type) {
case 0:
Workload.year = year;
fromTime = year + "-01-01";
Workload.days = 365;
Workload.rectNum = 12;
break;
case 1:
... | random_line_split | |
Workload.js | /**
* Created by songchao on 16/6/25.
*/
/**
* 入口方法,调用显示工作量
* @param employeeID
*/
function showWorkload(packageID) {
if (packageID != undefined) {
Workload.id = packageID;
Workload.whichRequest = 1;
}
$(canvas).attr({width: $(canvas).width() + "px", height: $(canvas).height() + "px"})... | () {
//清除所有动画
for (var i = 0; i < time.length; i++) {
clearInterval(time[i]);
}
time.length = 0;
}
function drawCloseButton(context) {
var image = new Image();
image.src = "../images/index/close.png";
var imagex = Workload.width() - 37;
var imagey = 5;
if (image.complete) {
... | load[month]++;
}
}
} else if (type == 1) {//月
//统计一年中每个月的工作量
for (i = 0; i < data.length; i++) {
var dd = data[i];
var day = new Date(dd.outTime).getDate();
if (load[day] == undefined) {
load[day] = 1;
} e... | identifier_body |
runningView.js | define([
'../../config/configTopics',
'../tool',
'../../lib/lib',
'../command',
'../dataFetch',
'../../lib/underscore'], function(topics, tool, lib, command, dataFetch, _, tip){
var privateMethods, publicMethods,
STAR_FLAG = 'star-';
privateMethods = {
conditionNodes: {
},
starRender: {
/*c... | var renderData = methods[condition.name](condition.value, condition);
lib.extend(condition, renderData);
});
}
},
scene: {},
tipObj: {},
tipPanel: lib.g('window-tip')
}
publicMethods = {
hasInitEvents: false,
initSet: function(id, ev, events, context){
privateMethods.scene[id] = {
... | methods[condition.name](condition.value, condition);
lib.extend(condition, renderData);
});
}
if(conditions.star){
conditions.star.forEach(function(condition){
| conditional_block |
runningView.js | define([
'../../config/configTopics',
'../tool',
'../../lib/lib',
'../command',
'../dataFetch',
'../../lib/underscore'], function(topics, tool, lib, command, dataFetch, _, tip){
var privateMethods, publicMethods,
STAR_FLAG = 'star-';
privateMethods = {
conditionNodes: {
},
starRender: {
/*c... | changeTo: function(id){
var nodes = privateMethods.nodes,
scene = privateMethods.scene[id],
events = scene.ev,
context = scene.context;
Object.keys(events).forEach(function(ev){
var data = events[ev],
node = nodes[ev];
node.onclick = data.click ? function(){
data.click.call(conte... | };
//lib
}, | random_line_split |
p6.py |
# coding: utf-8
# ## Question 6
# ### Ali Mortazavi
# ### 96131044
#
# In many pattern recognition applications, Sample Generation plays an important role, where it is
# necessary to generate samples which are to be normally distributed according to a given expected
# vector and a covariance matrix.<bn>
# In this... | ():
plt.xlim([-10, 10])
plt.ylim([-10, 10])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
# In[5]:
N =5000 # we changed N, because N=500 was too small for being visua... | setting_function | identifier_name |
p6.py |
# coding: utf-8
# ## Question 6
# ### Ali Mortazavi
# ### 96131044
#
# In many pattern recognition applications, Sample Generation plays an important role, where it is
# necessary to generate samples which are to be normally distributed according to a given expected
# vector and a covariance matrix.<bn>
# In this... |
#
# for i in range(0, len(sigmas)):
# s = np.random.normal(mu, sigmas[i], N)
# print ("mu", mu, "Sigma", sigmas[i])
# plt.scatter (s, np.zeros(len(s)), s=0.1, color=colors[i])
# plt.xlim([485, 515])
# plt.show()
# #### b) Generate samples from a normal distributions specified by the following pa... | s = np.random.normal(mu, sigmas[i], N)
print ("mu", mu, "Sigma", sigmas[i])
sns.distplot(s, color=colors[i], bins=bins)
plt.scatter (s, np.zeros(len(s)), s=0.2, color=colors[i])
plt.xlim([485, 515])
plt.show() | conditional_block |
p6.py |
# coding: utf-8
# ## Question 6
# ### Ali Mortazavi
# ### 96131044
#
# In many pattern recognition applications, Sample Generation plays an important role, where it is
# necessary to generate samples which are to be normally distributed according to a given expected
# vector and a covariance matrix.<bn>
# In this... |
# In[5]:
N =5000 # we changed N, because N=500 was too small for being visualized well
samples = np.random.multivariate_normal(np.array([-5,5]), np.array([[1,0],[0,1]]), N)
setting_function()
plt.scatter (samples[:,0], samples[:,1], s=0.2)
plt.show()
# c.2) A diagonal line (/ shape) in the centre<br>
# We... | plt.xlim([-10, 10])
plt.ylim([-10, 10])
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none') | identifier_body |
p6.py | # coding: utf-8
# ## Question 6
# ### Ali Mortazavi
# ### 96131044
#
# In many pattern recognition applications, Sample Generation plays an important role, where it is
# necessary to generate samples which are to be normally distributed according to a given expected
# vector and a covariance matrix.<bn>
# In this ... | vec = np.array([samples[i]-estimated_mean])
tmp = np.matmul(vec.T, vec)
estimated_var += tmp
estimated_var /= (len(samples)-1)
print ("estimated sigma")
print (estimated_var)
print ("real sigma:")
print (np.array([[2,1],[1,3]]) )
# Comment: The estimated mean and sigma are close to real mean and real sigm... | print ("real mean [2,1]")
estimated_var = 0
for i in range(0, len(samples)): | random_line_split |
twitch.py | #!/usr/bin/env python3
import os
import sys
import json
import dateutil.parser
import datetime
import pytz
import logging
import aiohttp
import discord
logger = logging.getLogger('twitch')
stream_state = {}
async def twitch_request(client_id, endpoint, in_id):
params = { 'id': in_id }
headers = { 'Client-ID'... | (client_id, game_id, user_id):
game = await twitch_request(client_id, 'games', game_id)
if game:
return game['name']
else:
headers = { 'Client-ID': client_id,
'Accept': 'application/vnd.twitchtv.v5+json' }
try:
async with aiohttp.get('https://api.tw... | get_game_title | identifier_name |
twitch.py | #!/usr/bin/env python3
import os
import sys
import json
import dateutil.parser
import datetime
import pytz
import logging
import aiohttp
import discord
logger = logging.getLogger('twitch')
stream_state = {}
async def twitch_request(client_id, endpoint, in_id):
params = { 'id': in_id }
headers = { 'Client-ID'... |
async def lookup_users(config, user_list):
headers = { 'Client-ID': config['twitch']['client-id'],
'Content-Type': 'application/json' }
async with aiohttp.get('https://api.twitch.tv/helix/users', headers=headers, params=user_list) as r:
if r.status == 200:
user_json = await... | game = await twitch_request(client_id, 'games', game_id)
if game:
return game['name']
else:
headers = { 'Client-ID': client_id,
'Accept': 'application/vnd.twitchtv.v5+json' }
try:
async with aiohttp.get('https://api.twitch.tv/kraken/streams/%s' % user_i... | identifier_body |
twitch.py | #!/usr/bin/env python3
import os
import sys
import json
import dateutil.parser
import datetime
import pytz
import logging
import aiohttp
import discord
logger = logging.getLogger('twitch')
stream_state = {}
async def twitch_request(client_id, endpoint, in_id):
params = { 'id': in_id }
headers = { 'Client-ID'... |
return (response, None)
async def get_subs(config):
headers = { 'Authorization': 'Bearer %s' % config['twitch']['app-token'] }
get_more = True
user_ids = []
params = None
while get_more:
get_more = False
async with aiohttp.get('https://api.twitch.tv/helix/webhooks/subscriptions... | streams_json = await r.json()
users = await parse_streams(client, config, server, streams_json)
if len(users) > 0:
response = "Announced %s" % (' '.join(users)) | conditional_block |
twitch.py | #!/usr/bin/env python3
import os
import sys
import json
import dateutil.parser
import datetime
import pytz
import logging
import aiohttp
import discord
logger = logging.getLogger('twitch')
stream_state = {}
async def twitch_request(client_id, endpoint, in_id):
params = { 'id': in_id }
headers = { 'Client-ID'... | sub_data['hub.topic'] = "https://api.twitch.tv/helix/streams?user_id=%s" % user['id']
# Send a (un)subcription request for each username
async with aiohttp.post('https://api.twitch.tv/helix/webhooks/hub', headers=headers, data=json.dumps(sub_data)) as r:
if r.status== 202:
... | user_ids = []
# Send a (un)subcription request for each username
for user in users:
logger.info('%s: %s' % (user['display_name'], user['id']))
sub_data['hub.callback'] = "%s?lb3.server=%s&lb3.user_id=%s" % (config['twitch']['webhook_uri'], config['discord']['server'], user['id']) | random_line_split |
msg.go | /*
Package msg creates a simple messaging package with flexible formatting that
can be used to write to multiple sinks.
Here is an example use.
import (
"jlinoff/utils/msg"
"io"
"os"
)
// My package logger.
var log *msg.Object
// Initialize it at startup.
func init() {
... | else {
ofmtb = append(ofmtb, b)
}
case spec:
s = normal // after parsing the spec go back to the normal state
// specification state, parse specifications of the form:
// %(<fmt>)<id>
// %<id>
beg := i - 1
if b == '(' {
// This is a format specification. Capture it.
// If ')' is... | {
s = spec
} | conditional_block |
msg.go | /*
Package msg creates a simple messaging package with flexible formatting that
can be used to write to multiple sinks.
Here is an example use.
import (
"jlinoff/utils/msg"
"io"
"os"
)
// My package logger.
var log *msg.Object
// Initialize it at startup.
func init() {
... | It allows you to insert arbitrary text.
Unlike the other functions it does not automatically append a new line.
Example:
msg.Printf("this is just random text that goes to all writers\n")
*/
func (o Object) Printf(f string, a ...interface{}) {
// Create the formatted output string.
s := fmt.Sprintf(f, a...)
... |
/*
Printf prints directly to the log without the format string. | random_line_split |
msg.go | /*
Package msg creates a simple messaging package with flexible formatting that
can be used to write to multiple sinks.
Here is an example use.
import (
"jlinoff/utils/msg"
"io"
"os"
)
// My package logger.
var log *msg.Object
// Initialize it at startup.
func init() {
... | (f string, a ...interface{}) {
if o.InfoEnabled {
o.PrintMsg("INFO", 2, f, a...)
}
}
/*
InfoWithLevel prints an info message obtaining the filename, function and
line number from the caller specified by level "l". l=2 is the same
as Debug().
It automatically appends a new line.
Example:
msg.InfoWithLevel(2... | Info | identifier_name |
msg.go | /*
Package msg creates a simple messaging package with flexible formatting that
can be used to write to multiple sinks.
Here is an example use.
import (
"jlinoff/utils/msg"
"io"
"os"
)
// My package logger.
var log *msg.Object
// Initialize it at startup.
func init() {
... |
/*
PrintMsg is the basis of all message printers except Printf. It prints the
formatted messages and normally would not be called directly.
t - is the type, normally one of DEBUG, INFO, WARNING or ERROR
l - is the caller level: 0 is this function, 1 is the caller, 2 is the callers caller and so on
... | {
// Create the formatted output string.
s := fmt.Sprintf(f, a...)
// Output it for each writer.
for _, w := range o.Writers {
fmt.Fprintf(w, s)
}
} | identifier_body |
examples.js | /*****************.REDUCE (callback function) **********************/
//reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce //it to a single value.
var numbers = [2,4,5,7,8,9];
var sum = numbers.reduce(function(runningTotal, num) {
return runningTo... |
function newUser(name, email, password) {
//create a new object with properties matching the arguments passed in.
//return the new object
var newObj = {
name: name,
email: email,
password: password
};
return newObj;
}
var languages = {
english: 'Welcome',
czech: 'Vitejte',
danish: '... | {
//create a new object with a name property with the value set to the name argument
//add an age property to the object with the value set to the age argument
//add a method called meow that returns the string 'Meow!'
//return the object
var newCat = {
name: name,
age: age,
meow:function ... | identifier_body |
examples.js | /*****************.REDUCE (callback function) **********************/
//reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce //it to a single value.
var numbers = [2,4,5,7,8,9];
var sum = numbers.reduce(function(runningTotal, num) {
return runningTo... | function colorOf(r,g,b){
var red = r.toString(16);
if (red.length === 1) red = "0" + red;
var green = g.toString(16);
if (green.length === 1) green = "0" + green;
var blue = b.toString(16);
if (blue.length === 1) blue = "0" + blue;
return "#" + red + green + blue;
}
colorOf(255,0,0); // outputs '#ff0000... | return num;
}
}
| random_line_split |
examples.js | /*****************.REDUCE (callback function) **********************/
//reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce //it to a single value.
var numbers = [2,4,5,7,8,9];
var sum = numbers.reduce(function(runningTotal, num) {
return runningTo... | (n) {
if (n === 0) {
return 1;
}
// This is it! Recursion!!
return n * factorial(n - 1);
}
console.log(factorial(10));
/*****************FOR LOOPS**********************/
// print all odd numbers between 300 and 333
for(var i = 300; i <= 333; i++) {
if(i % 2 !== 0) {
console.log(i);
... | factorial | identifier_name |
examples.js | /*****************.REDUCE (callback function) **********************/
//reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce //it to a single value.
var numbers = [2,4,5,7,8,9];
var sum = numbers.reduce(function(runningTotal, num) {
return runningTo... |
}
return num > 1;
}
function isPrime(num) {
//return true if num is prime.
//otherwise return false
//hint: a prime number is only evenly divisible by itself and 1
//hint2: you can solve this using a for loop
//note: 0 and 1 are NOT considered prime numbers
if(num < 2) return false;
for (v... | {
return false;
} | conditional_block |
header.go | package rpm
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"unsafe"
)
// See the reference material at
// https://rpm-software-management.github.io/rpm/manual/.
// Header is a parsed RPM header.
type Header struct {
tags *io.SectionReader
data *io.SectionReader
Infos []Entry... | (b []byte) error {
if len(b) < 16 {
return io.ErrShortBuffer
}
e.Tag = Tag(int32(binary.BigEndian.Uint32(b[0:4])))
e.Type = Kind(binary.BigEndian.Uint32(b[4:8]))
e.offset = int32(binary.BigEndian.Uint32(b[8:12]))
e.count = binary.BigEndian.Uint32(b[12:16])
return nil
}
| UnmarshalBinary | identifier_name |
header.go | package rpm
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"unsafe"
)
// See the reference material at
// https://rpm-software-management.github.io/rpm/manual/.
// Header is a parsed RPM header.
type Header struct {
tags *io.SectionReader
data *io.SectionReader
Infos []Entry... |
func (h *Header) loadTag(ctx context.Context, i int) (*EntryInfo, error) {
e := &h.Infos[i]
if e.Tag == Tag(0) {
b := make([]byte, entryInfoSize)
if _, err := h.tags.ReadAt(b, int64(i)*entryInfoSize); err != nil {
return nil, fmt.Errorf("header: error reading EntryInfo: %w", err)
}
if err := e.UnmarshalB... | {
if i, ok := tagByValue[key]; ok {
t := tagTable[i].Type
// Check the type. Some versions of string are typed incorrectly in a
// compatible way.
return t == typ || t.class() == typ.class()
}
// Unknown tags get a pass.
return true
} | identifier_body |
header.go | package rpm
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"unsafe"
)
// See the reference material at
// https://rpm-software-management.github.io/rpm/manual/.
// Header is a parsed RPM header.
type Header struct {
tags *io.SectionReader
data *io.SectionReader
Infos []Entry... |
if dataSz > dataMax {
return fmt.Errorf("header botch: data length (%d) out of range", dataSz)
}
tagsSz := int64(tagsCt) * entryInfoSize
// Sanity check, if possible:
var inSz int64
switch v := r.(type) {
case interface{ Size() int64 }:
// Check for Size method. [ioSectionReader]s and [byte.Buffer]s have t... | {
return fmt.Errorf("header botch: number of tags (%d) out of range", tagsCt)
} | conditional_block |
header.go | package rpm
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"unsafe"
)
// See the reference material at
// https://rpm-software-management.github.io/rpm/manual/.
// Header is a parsed RPM header.
type Header struct {
tags *io.SectionReader
data *io.SectionReader
Infos []Entry... | }
switch {
case prev > e.offset:
return fmt.Errorf("botched entry: prev > offset (%d > %d)", prev, e.offset)
case e.Tag < TagHeaderI18nTable && !isBDB:
return fmt.Errorf("botched entry: bad tag %v (%[1]d < %d)", e.Tag, TagHeaderI18nTable)
case e.Type < TypeMin || e.Type > TypeMax:
return fmt.Errorf("... | e, err := h.loadTag(ctx, i)
if err != nil {
return err | random_line_split |
profiles.go | package tc
/*
* 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
* "Lic... |
// ProfileExistsByName returns whether a profile with the given name exists, and any error.
// TODO move to helper package.
func ProfileExistsByName(name string, tx *sql.Tx) (bool, error) {
count := 0
if err := tx.QueryRow(`SELECT count(*) from profile where name = $1`, name).Scan(&count); err != nil {
return fal... | {
count := 0
if err := tx.QueryRow(`SELECT count(*) from profile where id = $1`, id).Scan(&count); err != nil {
return false, errors.New("querying profile existence from id: " + err.Error())
}
return count > 0, nil
} | identifier_body |
profiles.go | package tc
/*
* 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
* "Lic... |
// Validate profile does not already exist
if profile.Name != nil {
if ok, err := ProfileExistsByName(*profile.Name, tx); err != nil {
errString := fmt.Sprintf("checking profile name %v existence", *profile.Name)
log.Errorf("%v: %v", errString, err.Error())
errs = append(errs, errors.New(errString))
} ... | {
if ok, err := CDNExistsByName(*profile.CDNName, tx); err != nil {
errString := fmt.Sprintf("checking cdn name %v existence", *profile.CDNName)
log.Errorf("%v: %v", errString, err.Error())
errs = append(errs, errors.New(errString))
} else if !ok {
errs = append(errs, fmt.Errorf("%v CDN does not exist",... | conditional_block |
profiles.go | package tc
/*
* 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
* "Lic... | }
// ProfileCopyResponse represents the Traffic Ops API's response when a Profile
// is copied.
type ProfileCopyResponse struct {
Response ProfileCopy `json:"response"`
Alerts
}
// ProfileExportImportNullable is an object of the form used by Traffic Ops
// to represent exported and imported profiles.
type ProfileEx... | ID int `json:"id"`
Name string `json:"name"`
ExistingID int `json:"idCopyFrom"`
ExistingName string `json:"profileCopyFrom"`
Description string `json:"description"` | random_line_split |
profiles.go | package tc
/*
* 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
* "Lic... | (ids []int64, tx *sql.Tx) (bool, error) {
count := 0
if err := tx.QueryRow(`SELECT count(*) from profile where id = ANY($1)`, pq.Array(ids)).Scan(&count); err != nil {
return false, errors.New("querying profiles existence from id: " + err.Error())
}
return count == len(ids), nil
}
// ProfileExistsByID returns wh... | ProfilesExistByIDs | identifier_name |
lib.rs | //! Securely zero memory with a simple trait ([Zeroize]) built on stable Rust
//! primitives which guarantee the operation will not be 'optimized away'.
//!
//! ## Usage
//!
//! ```
//! use zeroize::Zeroize;
//!
//! fn main() {
//! // Protip: don't embed secrets in your source code.
//! // This is just an examp... | //! 2. Ensure all subsequent reads to the memory following the zeroing operation
//! will always see zeroes.
//!
//! This crate guarantees #1 is true: LLVM's volatile semantics ensure it.
//!
//! The story around #2 is much more complicated. In brief, it should be true that
//! LLVM's current implementation does not... | //! ## What guarantees does this crate provide?
//!
//! Ideally a secure memory-zeroing function would guarantee the following:
//!
//! 1. Ensure the zeroing operation can't be "optimized away" by the compiler. | random_line_split |
lib.rs | //! Securely zero memory with a simple trait ([Zeroize]) built on stable Rust
//! primitives which guarantee the operation will not be 'optimized away'.
//!
//! ## Usage
//!
//! ```
//! use zeroize::Zeroize;
//!
//! fn main() {
//! // Protip: don't embed secrets in your source code.
//! // This is just an examp... | () {
atomic::fence(atomic::Ordering::SeqCst);
atomic::compiler_fence(atomic::Ordering::SeqCst);
}
/// Set a mutable reference to a value to the given replacement
#[inline]
fn volatile_set<T: Copy + Sized>(dst: &mut T, src: T) {
unsafe { ptr::write_volatile(dst, src) }
}
#[cfg(feature = "nightly")]
#[inlin... | atomic_fence | identifier_name |
lib.rs | //! Securely zero memory with a simple trait ([Zeroize]) built on stable Rust
//! primitives which guarantee the operation will not be 'optimized away'.
//!
//! ## Usage
//!
//! ```
//! use zeroize::Zeroize;
//!
//! fn main() {
//! // Protip: don't embed secrets in your source code.
//! // This is just an examp... |
/// Set a mutable reference to a value to the given replacement
#[inline]
fn volatile_set<T: Copy + Sized>(dst: &mut T, src: T) {
unsafe { ptr::write_volatile(dst, src) }
}
#[cfg(feature = "nightly")]
#[inline]
fn volatile_zero_bytes(dst: &mut [u8]) {
unsafe { core::intrinsics::volatile_set_memory(dst.as_mut... | {
atomic::fence(atomic::Ordering::SeqCst);
atomic::compiler_fence(atomic::Ordering::SeqCst);
} | identifier_body |
fakes.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![cfg(test)]
use {
crate::{
client::{bss_selection::SignalData, scan, types as client_types},
config_management::{
Credent... |
pub fn get_recorded_connect_reslts(&self) -> Vec<ConnectResultRecord> {
self.connect_results_recorded
.try_lock()
.expect("expect locking self.connect_results_recorded to succeed")
.clone()
}
/// Manually change the hidden network probabiltiy of a saved network... | {
self.connections_recorded
.try_lock()
.expect("expect locking self.connections_recorded to succeed")
.clone()
} | identifier_body |
fakes.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![cfg(test)]
use {
crate::{
client::{bss_selection::SignalData, scan, types as client_types},
config_management::{
Credent... | #[derive(Clone)]
pub struct FakeScanRequester {
// A type alias for this complex type would be needless indirection, so allow the complex type
#[allow(clippy::type_complexity)]
pub scan_results:
Arc<Mutex<VecDeque<Result<Vec<client_types::ScanResult>, client_types::ScanError>>>>,
#[allow(clippy:... | rng.gen::<u8>().into(),
)
}
| random_line_split |
fakes.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![cfg(test)]
use {
crate::{
client::{bss_selection::SignalData, scan, types as client_types},
config_management::{
Credent... | () -> (mpsc::Sender<String>, mpsc::Receiver<String>) {
const DEFAULT_BUFFER_SIZE: usize = 100; // arbitrary value
mpsc::channel(DEFAULT_BUFFER_SIZE)
}
/// Create past connection data with all random values. Tests can set the values they care about.
pub fn random_connection_data() -> PastConnectionData {
le... | create_inspect_persistence_channel | identifier_name |
fakes.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![cfg(test)]
use {
crate::{
client::{bss_selection::SignalData, scan, types as client_types},
config_management::{
Credent... | else { None },
)
.flatten()
.collect()
}
}
}
/// Note that the configs-per-NetworkIdentifier limit is set to 1 in
/// this mock struct. If a NetworkIdentifier is already stored, writing
/// a config to it will evict the pr... | { Some(config.clone()) } | conditional_block |
yahoo_plus_save.py | '''
Yahoo Plus Saver
Copyright 2021 LossFuture
Public Version 1.0 9/4/2021
'''
import requests
import json
import re
import time
import sys
import sqlite3
from bs4 import BeautifulSoup
import urllib.request
from itertools import cycle
#https://github.com/lossfuture/yahoo-answer-backup
#add your per... | (self,logfile_name,dbpath):
dbpath='''file:{}?mode=rw'''.format(dbpath)
self.conn = sqlite3.connect(dbpath,uri=True)
self.c = self.conn.cursor()
self.logfile_name="yahoo_plus.log"
self.requests_cnt=0
self.https_proxy=proxies[0]
@staticmethod
def convert_... | __init__ | identifier_name |
yahoo_plus_save.py | '''
Yahoo Plus Saver
Copyright 2021 LossFuture
Public Version 1.0 9/4/2021
'''
import requests
import json
import re
import time
import sys
import sqlite3
from bs4 import BeautifulSoup
import urllib.request
from itertools import cycle
#https://github.com/lossfuture/yahoo-answer-backup
#add your per... |
def parse_file(self,file):
a_file = open(file, "r",encoding="utf8")
list_of_lists = []
for line in a_file:
stripped_line = line.strip()
if stripped_line[0] =="#": #skip with sharp symbol
continue
if len(stripped_line)==0:
... | '''Get data from database, return a list without column name'''
if arg is None:
self.c.execute(sql)
else:
self.c.execute(sql,arg)
b=self.c.fetchall()
return b | identifier_body |
yahoo_plus_save.py | '''
Yahoo Plus Saver
Copyright 2021 LossFuture
Public Version 1.0 9/4/2021
'''
import requests
import json
import re
import time
import sys
import sqlite3
from bs4 import BeautifulSoup
import urllib.request
from itertools import cycle
#https://github.com/lossfuture/yahoo-answer-backup
#add your per... |
else:
self.c.execute('''INSERT OR IGNORE INTO answers (question_id,is_accepted,answer,datecreated,author_type,author_name,author_link,upvotecount) VALUES(?,?,?,?,?,?,?,?)''',(newqid,1,content2,date2,author_t2,author_n2,user_url[user_urlpos],upvote_c2))
user_urlpos+=1;
... | pass | conditional_block |
yahoo_plus_save.py | '''
Yahoo Plus Saver
Copyright 2021 LossFuture
Public Version 1.0 9/4/2021
'''
import requests
import json
import re
import time
import sys
import sqlite3
from bs4 import BeautifulSoup
import urllib.request
from itertools import cycle
#https://github.com/lossfuture/yahoo-answer-backup
#add your per... | except UnicodeEncodeError:
print("{0} : UnicodeEncodeError, String Contains Non-BMP character".format(self._curtime()))
#print("{0} : {1}".format(time.strftime("%d/%m/%Y %H:%M:%S"),string),file= open(self.logfile_name, "a"))
print(str1,file= open(self.logfile_name,... | print(str1)
| random_line_split |
anichart.py | ## Builtin
import copy
import csv
import datetime
import functools
import json
import re
## Custom Module
import AL_Web as web
from AL_Web import requests as alrequests
from aldb2 import SeasonCharts
CHARTNAME = "AniChart"
APIURL = r"http://anichart.net/api/browse/anime?season={season}&year={year}&sort=-score&full_pa... |
@overwrite_season
def cleanapidata_csv(data):
""" Cleans the API data for use in a CSV and returns a list of headers along with the clean data.
Converts startdate to EST startdate.
Adds firstepisode date.
Adds EST_airing time.
Features overwrite_season decorator
Returns ([list of Headers... | """ Replaces the season value of a list of Show objects or data dicts
Mutates the objects in-place.
"""
if not SeasonCharts.matchseason(season):
raise SeasonCharts.SeasonError
## Check data format
if test_rawdata(data):
for cat,shows in data.items():
for show in show... | identifier_body |
anichart.py | ## Builtin
import copy
import csv
import datetime
import functools
import json
import re
## Custom Module
import AL_Web as web
from AL_Web import requests as alrequests
from aldb2 import SeasonCharts
CHARTNAME = "AniChart"
APIURL = r"http://anichart.net/api/browse/anime?season={season}&year={year}&sort=-score&full_pa... | tags = []
for tag in show['tags']:
tags.append((tag['name'],tag['spoiler']))
for genre in show['genres']:
## AniChart... generates "" Genres??? O.o
if genre:
tags.append((genre,False))
airingtime = show.get('airing')
if not airingtime: airingtime = datetime.... | continuing = show['category'].lower() == "leftovers"
summary = f"(From {CHARTNAME})\n{show.get('description')}"
| random_line_split |
anichart.py | ## Builtin
import copy
import csv
import datetime
import functools
import json
import re
## Custom Module
import AL_Web as web
from AL_Web import requests as alrequests
from aldb2 import SeasonCharts
CHARTNAME = "AniChart"
APIURL = r"http://anichart.net/api/browse/anime?season={season}&year={year}&sort=-score&full_pa... | (show, showfactory = SeasonCharts.Show):
""" Converts an AniChart Show to a standard Show Object """
if not isinstance(show,Show):
raise TypeError("converttostandard requires an AniChart Show Object.")
chartsource = [(CHARTNAME,show['id']),]
if show.get("season") is None or not SeasonCharts.mat... | converttostandard | identifier_name |
anichart.py | ## Builtin
import copy
import csv
import datetime
import functools
import json
import re
## Custom Module
import AL_Web as web
from AL_Web import requests as alrequests
from aldb2 import SeasonCharts
CHARTNAME = "AniChart"
APIURL = r"http://anichart.net/api/browse/anime?season={season}&year={year}&sort=-score&full_pa... |
s = str(startdate)
d,m,y = [max(dt,1) for dt in [int(s[6:8]),int(s[4:6]),int(s[:4])]]
return f"{d:0>2}/{m:0>2}/{y:0>4}"
def getseason(data):
""" Tries to determine the season that an anime aired based on its season value and it's ratings """
## Season key is the most reliable
season = data.get... | return "01/01/2017" | conditional_block |
runIPRscan.py | #!/usr/bin/env python
# $Id: iprscan5_urllib2.py 2809 2015-03-13 16:10:25Z uludag $
# ======================================================================
#
# Copyright 2009-2014 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex... |
else: # Argument is a sequence id
params['sequence'] = options.input
elif options.sequence: # Specified via option
if os.access(options.sequence, os.R_OK): # Read file into content
params['sequence'] = readFile(options.sequence)
else: # Argument is a sequence id
... | params['sequence'] = readFile(options.input) | conditional_block |
runIPRscan.py | #!/usr/bin/env python
# $Id: iprscan5_urllib2.py 2809 2015-03-13 16:10:25Z uludag $
# ======================================================================
#
# Copyright 2009-2014 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex... | (paramName):
printDebugMessage('printGetParameterDetails', 'Begin', 1)
doc = serviceGetParameterDetails(paramName)
print(str(doc.name) + "\t" + str(doc.type))
print(doc.description)
for value in doc.values:
print(value.value, end=' ')
if str(value.defaultValue) == 'true':
... | printGetParameterDetails | identifier_name |
runIPRscan.py | #!/usr/bin/env python
# $Id: iprscan5_urllib2.py 2809 2015-03-13 16:10:25Z uludag $
# ======================================================================
#
# Copyright 2009-2014 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex... |
# Read a file
def readFile(filename):
printDebugMessage('readFile', 'Begin', 1)
fh = open(filename, 'r')
data = fh.read()
fh.close()
printDebugMessage('readFile', 'End', 1)
return data
# No options... print help.
if numOpts < 2:
parser.print_help()
# List parameters
elif options.params... | printDebugMessage('getResult', 'Begin', 1)
printDebugMessage('getResult', 'jobId: ' + jobId, 1)
# Check status and wait if necessary
clientPoll(jobId)
# Get available result types
resultTypes = serviceGetResultTypes(jobId)
for resultType in resultTypes:
# Derive the filename for the resu... | identifier_body |
runIPRscan.py | #!/usr/bin/env python
# $Id: iprscan5_urllib2.py 2809 2015-03-13 16:10:25Z uludag $
# ======================================================================
#
# Copyright 2009-2014 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex... | clientPoll(jobId)
# Get available result types
resultTypes = serviceGetResultTypes(jobId)
for resultType in resultTypes:
# Derive the filename for the result
if options.outfile:
filename = options.outfile + '.' + \
str(resultType['identifier']) + '.' + \
... |
def getResult(jobId):
printDebugMessage('getResult', 'Begin', 1)
printDebugMessage('getResult', 'jobId: ' + jobId, 1)
# Check status and wait if necessary | random_line_split |
main.py | #!/usr/bin/python
# __ _ _
# /__\__ ___ __ _ _ __ ___ | |_| |__ ___ /\ /\___ _ _ ___ ___
# /_\/ __|/ __/ _` | '_ \ / _ \ | __| '_ \ / _ \ / /_/ / _ \| | | / __|/ _ \
# //__\__ \ (_| (_| | |_) | __/ | |_| | | | __/ / __ ... | (self, arg):
""""clear" - Clear all text from the screen."""
if platform.system == "Windows":
os.system("cls")
else:
os.system("clear")
# :)
def do_hacf(self, arg):
if 'Troll' in worldRooms['Main Hall'][STORAGE]:
print(bcolors.start ... | do_clear | identifier_name |
main.py | #!/usr/bin/python
# __ _ _
# /__\__ ___ __ _ _ __ ___ | |_| |__ ___ /\ /\___ _ _ ___ ___
# /_\/ __|/ __/ _` | '_ \ / _ \ | __| '_ \ / _ \ / /_/ / _ \| | | / __|/ _ \
# //__\__ \ (_| (_| | |_) | __/ | |_| | | | __/ / __ ... |
def do_look(self, arg):
"""Look at an item, direction, or the area:
"look" - display the current area's description
"look <direction>" - display the description of the area in that direction
"look exits" - display the description of all adjacent areas
"look <item>" - display the description of an it... | possibleItems = []
itemToDrop = text.lower()
# get a list of all "description words" for each item in the inventory
invDescWords = getAllDescWords(inventory)
for descWord in invDescWords:
if line.startswith('drop %s' % (descWord)):
return [] # comman... | identifier_body |
main.py | #!/usr/bin/python
# __ _ _
# /__\__ ___ __ _ _ __ ___ | |_| |__ ___ /\ /\___ _ _ ___ ___
# /_\/ __|/ __/ _` | '_ \ / _ \ | __| '_ \ / _ \ / /_/ / _ \| | | / __|/ _ \
# //__\__ \ (_| (_| | |_) | __/ | |_| | | | __/ / __ ... |
def do_inventory(self, arg):
"""Display a list of the items in your possession."""
if len(inventory) == 0:
print('Inventory:\n (nothing)')
return
# first get a count of each distinct item in the inventory
itemCount = {}
fo... | print('Showing brief exit descriptions.')
| random_line_split |
main.py | #!/usr/bin/python
# __ _ _
# /__\__ ___ __ _ _ __ ___ | |_| |__ ___ /\ /\___ _ _ ___ ___
# /_\/ __|/ __/ _` | '_ \ / _ \ | __| '_ \ / _ \ / /_/ / _ \| | | / __|/ _ \
# //__\__ \ (_| (_| | |_) | __/ | |_| | | | __/ / __ ... |
print('You do not see that nearby.')
def complete_look(self, text, line, begidx, endidx):
possibleItems = []
lookingAt = text.lower()
# get a list of all "description words" for each item in the inventory
invDescWords = g... | print('\n'.join(textwrap.wrap(worldItems[item][LONGDESC], SCREEN_WIDTH)))
return | conditional_block |
render_global.rs | use std::error;
use std::rc::Rc;
use std::cell::RefCell;
use std::ops::Deref;
use std::sync::Mutex;
use gl_bindings::gl;
use cgmath::{Matrix4, SquareMatrix, vec3, Point3, Rad};
use crate::demo;
use crate::utils::lazy_option::Lazy;
use crate::render::{Framebuffer, FramebufferAttachment, AttachmentPoint, ImageFormat, Ren... | // let mut program = RefCell::borrow_mut(&program);
// program.delete();
// }
// if let Some(program) = self.program_post_resolve.take() {
// let mut program = RefCell::borrow_mut(&program);
// program.delete();
// }
// Reload shader from assets
// // Load shaders
// self.program_ehaa_scene = So... | // if let Some(program) = self.program_ehaa_scene.take() { | random_line_split |
render_global.rs | use std::error;
use std::rc::Rc;
use std::cell::RefCell;
use std::ops::Deref;
use std::sync::Mutex;
use gl_bindings::gl;
use cgmath::{Matrix4, SquareMatrix, vec3, Point3, Rad};
use crate::demo;
use crate::utils::lazy_option::Lazy;
use crate::render::{Framebuffer, FramebufferAttachment, AttachmentPoint, ImageFormat, Ren... |
else {
// Create fbo
self.framebuffer_scene_hdr_ehaa = Some(Rc::new(RefCell::new({
let mut fbo = Framebuffer::new(event.resolution.0, event.resolution.1);
fbo.add_attachment(FramebufferAttachment::from_new_texture(AttachmentPoint::Depth, ImageFormat::get(gl::DEPTH_COMPONENT32F)));
fbo.add_atta... | {
let mut fbo = RefCell::borrow_mut(t);
fbo.resize(event.resolution.0, event.resolution.1);
} | conditional_block |
render_global.rs | use std::error;
use std::rc::Rc;
use std::cell::RefCell;
use std::ops::Deref;
use std::sync::Mutex;
use gl_bindings::gl;
use cgmath::{Matrix4, SquareMatrix, vec3, Point3, Rad};
use crate::demo;
use crate::utils::lazy_option::Lazy;
use crate::render::{Framebuffer, FramebufferAttachment, AttachmentPoint, ImageFormat, Ren... | (&mut self) {
// let asset_folder = demo::demo_instance().asset_folder.as_mut().unwrap();
// Log
println!("Reloading shaders!");
// Reload shaders from asset
self.program_ehaa_scene.reload_from_asset().expect("Failed to reload scene shader from asset");
self.program_post_composite.reload_from_asset().e... | reload_shaders | identifier_name |
spinup.py | #!/usr/bin/env python
# Copyright (C) 2017 Andy Aschwanden
import itertools
from collections import OrderedDict
import os
try:
import subprocess32 as sub
except:
import subprocess as sub
from argparse import ArgumentParser
import sys
sys.path.append("../resources/")
from resources import *
grid_choices = [5... |
cmd = [ncgen, "-o", pism_config_nc, pism_config_cdl]
sub.call(cmd)
if not os.path.isdir(odir):
os.mkdir(odir)
state_dir = "state"
scalar_dir = "scalar"
spatial_dir = "spatial"
for tsdir in (scalar_dir, spatial_dir, state_dir):
if not os.path.isdir(os.path.join(odir, tsdir)):
os.mkdir(os.path.join(odir... | ncgen = "ncgen" | conditional_block |
spinup.py | #!/usr/bin/env python
# Copyright (C) 2017 Andy Aschwanden
import itertools
from collections import OrderedDict
import os
try:
import subprocess32 as sub
except:
import subprocess as sub
from argparse import ArgumentParser
import sys
sys.path.append("../resources/")
from resources import *
grid_choices = [5... | ssa_n_values,
ppq_values,
tefo_values,
phi_min_values,
phi_max_values,
topg_min_values,
topg_max_values,
)
)
tsstep = "yearly"
scripts = []
scripts_post = []
simulation_start_year = options.start_year
simulation_end_year = options.end_year
for n, combinat... | itertools.product(
sia_e_values, | random_line_split |
polynom.py | """
Modular arithmetic
"""
from collections import defaultdict
import numpy as np
class ModInt:
"""
Integers of Z/pZ
"""
def __init__(self, a, n):
self.v = a % n
self.n = n
def __eq__(a, b):
if isinstance(b, ModInt):
return not bool(a - b)
else:
... |
def __bool__(self):
return bool(self.v)
def __add__(a, b):
assert isinstance(b, ModInt)
assert a.n == b.n
return ModInt(a.v + b.v, a.n)
def __radd__(a, b):
assert isinstance(b, int)
return ModInt(a.v + b, a.n)
def __neg__(a): return ModInt(-a.v, a.n)
... |
def __hash__(self):
return hash((self.v, self.n)) | random_line_split |
polynom.py | """
Modular arithmetic
"""
from collections import defaultdict
import numpy as np
class ModInt:
"""
Integers of Z/pZ
"""
def __init__(self, a, n):
self.v = a % n
self.n = n
def __eq__(a, b):
if isinstance(b, ModInt):
return not bool(a - b)
else:
... | @staticmethod
def sign_changes(l):
return sum(a * b < 0 for a, b in zip(l, l[1:]))
def isreal(P):
return not any(isinstance(c, ModInt) for c in P)
def isinteger(P):
return all(isinstance(c, int) for c in P)
def sturm(P):
"""
Number of distinct real roots
... | turn Polynomial([ModInt(c, p) for c in P])
| identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.